GDrive API not return all files in my drive - google-api

Im using google api to get files, but only return the files created using the api, the files created by UI GDrive not returned in request. I using the DriveScopes.DRIVE_FILE SCOPE
When I use postman all files returned.
Get Credencials:
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT)
throws IOException {
// Load client secrets.
InputStream in = GoogleHelper.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
if (in == null) {
throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
}
GoogleClientSecrets clientSecrets =
GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
.setAccessType("offline")
.build();
LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
Credential credential = new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
//returns an authorized Credential object.
return credential;
}```
Get files:
``` java
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
Drive service = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
.setApplicationName(APPLICATION_NAME)
.build();
FileList result = service.files().list()
.setFields("nextPageToken, files(id, name, webViewLink)")
.setSupportsAllDrives(true)
.execute();
List<File> files = result.getFiles();
if (files == null || files.isEmpty()) {
System.out.println("No files found.");
} else {
System.out.println("Files:");
for (File file : files) {
System.out.printf("%s (%s) \n", file.getName(), file.getId());
}
} ```
Console:
``` shell
Files:
default.jpeg (1Dp1SKe36q8W2geRHKU_VsjzrZe1Bme3e)
PRODUCTS (1N-t7AQQz2ubR9kIxIgBWgZDTuVrSkvVU)
IMAGES (1gFWkC8dALK2RL9wV4PTrjr47EDsHz2VO) ```
Screenshort's gdrive
[enter image description here][1]
[1]: https://i.stack.imgur.com/yn4gw.png
If I create file by UI GDrive, the file not returned in request, only if create file by API.
The second file not found in api. Can you help me?

Related

Whatsapp Api Cloud Image Upload Issue

I am trying to upload an image for whataspp cloud api , i've transformed curl code to c# using RestSharp but i got this error . I was triying to change the file parameter format but it doesn't work. I don't know if i am missing something in the json maybe.
here is the code i use :
public void whatsapp_image_upload()
{
var client = new RestClient("https://graph.facebook.com/" + num_whatsapp_business + "/media");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer " + token_authorization);
request.AddHeader("Content-Type", "application/json");
request.AddParameter("messaging_product", "whatsapp");
request.AddParameter("file", "C:\\Users\\cnarea\\Pictures\\empaque.jpg");
request.AddParameter("type", "image/jpeg");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
}
and this is the error i recieve :
{"error":{"message":"An unknown error has occurred.","type":"OAuthException","code":1,"fbtrace_id":"AFWXnEVRuvp82ewjaUEtoLa"}}
Well i was able to solve it, i have to use postman app to obtain c# code ,my code is this :
public void whatsapp_image_upload()
{
try
{
string filePath = #"C:\Users\cnarea\Pictures\procesos.jpeg";
var client = new RestClient("https://graph.facebook.com/"+num_whatsapp_business+"/media");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer "+token_authorization);
request.AddFile("file", filePath, "image/jpeg");
request.AddParameter("messaging_product", "whatsapp");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}

How to use postman for testing get request given below?

I want to create an android app to perform file operations in google drive which uses Spring boot as backend. So I had searched so many times in google and finally I got this one. But they didn't mentioned about the working. If anyone knows please help me. And please suggest some good tutorial to perform file operations in google drive using Spring boot rest api.
Get Request to create a directory in Google Drive
#GetMapping("/directory/create")
public ResponseEntity<String> createDirectory(#RequestParam String path) throws Exception {
String parentId = fileManager.getFolderId(path);
return ResponseEntity.ok("parentId: "+parentId);
}
getFolderId Function
public String getFolderId(String path) throws Exception {
String parentId = null;
String[] folderNames = path.split("/");
Drive driveInstance = googleDriveManager.getInstance();
for (String name : folderNames) {
parentId = findOrCreateFolder(parentId, name, driveInstance);
}
return parentId;
}
findOrCreateFolder Function to create if given folder does not exist in google drive
private String findOrCreateFolder(String parentId, String folderName, Drive driveInstance) throws Exception {
String folderId = searchFolderId(parentId, folderName, driveInstance);
// Folder already exists, so return id
if (folderId != null) {
return folderId;
}
//Folder dont exists, create it and return folderId
File fileMetadata = new File();
fileMetadata.setMimeType("application/vnd.google-apps.folder");
fileMetadata.setName(folderName);
if (parentId != null) {
fileMetadata.setParents(Collections.singletonList(parentId));
}
return driveInstance.files().create(fileMetadata)
.setFields("id")
.execute()
.getId();
}
Post request to upload file to google drive
#PostMapping(value = "/upload",
consumes = {MediaType.MULTIPART_FORM_DATA_VALUE},
produces = {MediaType.APPLICATION_JSON_VALUE} )
public ResponseEntity<String> uploadSingleFileExample4(#RequestBody MultipartFile file,#RequestParam(required = false) String path) {
logger.info("Request contains, File: " + file.getOriginalFilename());
String fileId = fileManager.uploadFile(file, path);
if(fileId == null){
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
return ResponseEntity.ok("Success, FileId: "+ fileId);
}
Upload function to upload file to google drive
public String uploadFile(MultipartFile file, String filePath) {
try {
String folderId = getFolderId(filePath);
if (file != null) {
File fileMetadata = new File();
fileMetadata.setParents(Collections.singletonList(folderId));
fileMetadata.setName(file.getOriginalFilename());
File uploadFile = googleDriveManager.getInstance()
.files()
.create(fileMetadata, new InputStreamContent(
file.getContentType(),
new ByteArrayInputStream(file.getBytes()))
)
.setFields("id").execute();
return uploadFile.getId();
}
} catch (Exception e) {
System.out.print("Error: "+e);
}
return null;
}
Reference
https://technicalsand.com/file-operations-in-google-drive-api-with-spring-boot/
To test the above get request in postman.
Assume you are running on localhost:8080 then request will be -
localhost:8080?path="directory_name"
Testing GET request in Postman: Image
If you are running in local,
http://{host}:{port}/{endpoint}
http://localhost:8080/directory/create

Google Drive Api - Error after copying multiple files .NET - Cancel connection by remote host

Console application below return exception after copying many files. I'd like to know the exactly limit of copying and creating folders with Google drive api in .NET. Follow the Inner Exception: "Unable to read data from the transport connection: Was Forced to cancel the exist connection by remote host".
static void Main(string[] args)
{
if (Debugger.IsAttached)
CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.GetCultureInfo("en-US");
string[] Scopes = { DriveService.Scope.DriveReadonly, DriveService.Scope.DriveFile };
ServiceAccountCredential credential;
using (var stream =
new FileStream("key.json", FileMode.Open, FileAccess.Read))
{
credential = GoogleCredential.FromStream(stream)
.CreateScoped(Scopes)
.UnderlyingCredential as ServiceAccountCredential;
}
// Create Drive API service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Test App",
});
Google.Apis.Drive.v3.Data.File copiedFile = new Google.Apis.Drive.v3.Data.File();
for (int i = 0; i < 50; i++)
{
copiedFile.Name = "";
copiedFile.Parents = new List<string> { "1I6eCYECR8lfpWP6wFDWeYkTsUMC6jKie" };
try
{
var lFile = service.Files.Copy(copiedFile, "157cV64pH6Jdpm8SER1MQStPhnl01XHI65AsfPwSeTqw").Execute();
Console.WriteLine("File " + (i+1).ToString() + " copied.");
}
catch (Exception e)
{
Console.WriteLine("Error = " + e.InnerException.Message);
}
}
}
Print_Error
Thanks for helping! I've realized that our SonicWall firewall was blocking some requests. After set (Sonicwall) to not block our request, the issue was resolved.
I have attached the full error here.
Print Error

Can upload image using ASP.NET WEB API but not when deployed

I am using ASP.NET WEB API to upload image to server. But when i upload the source code of my web api to gearhost.com and make a post request. I am unable to post the image. This is my web api controller code:
[Route("upload")]
[HttpPost]
public async Task<string> Upload()
{
var ctx = HttpContext.Current;
var root = ctx.Server.MapPath("/uploads/");
var provider = new MultipartFormDataStreamProvider(root);
try
{
await Request.Content
.ReadAsMultipartAsync(provider);
foreach (var file in provider.FileData)
{
var name = file.Headers
.ContentDisposition
.FileName;
// remove double quotes from string.
name = name.Trim('"');
var localFileName = file.LocalFileName;
var filePath = Path.Combine(root, "files", name);
// File.Move(localFileName, filePath);
// SaveFilePathSQLServerADO(localFileName, filePath);
// SaveFileBinarySQLServerADO(localFileName, name);
// SaveFilePathSQLServerEF(localFileName, filePath);
SaveFileBinarySQLServerEF(localFileName, name, filePath);
if (File.Exists(localFileName))
File.Delete(localFileName);
}
}
catch
{
return "Error";
}
return "File uploaded successfully!";
}
public void SaveFileBinarySQLServerEF(string localFile, string fileName, string filePath)
{
// 1) Get file binary
byte[] fileBytes;
using (var fs = new FileStream(localFile, FileMode.Open, FileAccess.Read))
{
fileBytes = new byte[fs.Length];
fs.Read(fileBytes, 0, Convert.ToInt32(fs.Length));
}
// 2) Create a Files object
var file = new tblimage()
{
Data = fileBytes,
Names = fileName,
ContentType = filePath
};
// 3) Add and save it in database
using (var ctx = new coachEntities())
{
ctx.tblimages.Add(file);
ctx.SaveChanges();
}
}
Here is the successful call from localhost:
Image posted through localhost
However when deployed the same code and make request through postman then I get this error:
Image posted through live server
Maybe, "uploads" doesn't have write permission
Check the permission in your uploads folder.
Go to properties-- security
Give the read write permission.
Though it is not good idea to return the exception details in live code. As you are not maintaining log. For testing, Please return the exception details. Also, how are you getting the response like "unable to upload, try again" because it is not there in your code

How to move (not copy) a file with JCIFS?

I'm wondering how I can move a file from one folder to another on an SMB share, using JCIFS.
First, there is no move() method whatsoever.
Then, this approach:
SmbFile smbFromFile = new SmbFile("smb://...pool/from-here/the-file.pdf", auth);
SmbFile smbToFile = new SmbFile("smb://...pool/to-here/the-file.pdf", auth);
smbFromFile.renameTo(smbToFile);
throws an Exception, "The system cannot find the path specified."
Rename only works in the same path. Altering the parameters doesn't help.
Right now, I'm using
smbFromFile = new SmbFile("smb://...pool/from-here/the-file.pdf", auth);
smbToFile = new SmbFile("smb://...pool/to-here", auth);
smbFromFile.copyTo(smbToFile);
smbFromFile.delete();
This feels somehow wrong.
Unfortunately, in the docu I don't find anything about moving a file.
Does somebody have a bit more information? It should be a part of SMB, right (SMB_COM_MOVE)?
Turned out I was a muppet as I had messed up my configuration parameters.
Both ways are working fine:
Method 1:
SmbFile smbFromFile = new SmbFile("smb://...pool/from-here/the-file.pdf", auth);
SmbFile smbToFile = new SmbFile("smb://...pool/to-here/the-file.pdf", auth);
smbFromFile.renameTo(smbToFile);
Method 2:
smbFromFile = new SmbFile("smb://...pool/from-here/the-file.pdf", auth);
smbToFile = new SmbFile("smb://...pool/to-here/the-file.pdf", auth);
smbFromFile.copyTo(smbToFile);
smbFromFile.delete();
There are two possible Scenarios:
1.) The file needs to be moved on the same server ( That is, the authentication details for Input folder and Output folder are same).
Use renameTo() method.
public boolean moveFile(SmbFile file) {
log.info("{"Started Archiving or Moving the file");
String targetFilePath = this.archiveDir + file.getName(); //Path where we need to move that file.
try {
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("", userId, userPassword);
log.info("targetFilePath: {} , currentFile : {}",targetFilePath, file);
SmbFile targetFile = new SmbFile(targetFilePath, auth);
//authenticate the SmbFile
try {
file.renameTo(targetFile); //Use renameTo method for same server
log.info("Archived File : {} to: {}", file.getName(),
targetFile.getName());
return true;
} catch (SmbException e) {
log.error("Unable to Archive File: {}", file.getName());
return false;
}
} catch (MalformedURLException e) {
log.error("Connection failed to Server Drive: {}", targetFilePath);
}
return false;
}
2.) The file needs to be moved on Different server ( That is, the authentication details for Input folder and Output folder are NOT same).
Use copyTo() method.
Here I will suggest, You can firstly authenticate the first server on which file is present, And check if the File exists, If it is existing then add that in a list :
public List<SmbFile> xmlFiles = new ArrayList<>(); //Here we will add all the files which are existing.
public boolean isFileExists() throws MalformedURLException, SmbException {
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("",
userID, userPassword); //authenticating input folder.
SmbFile smbFile = new SmbFile(inputFolder, auth);
SmbFile[] smbFiles = smbFile.listFiles();
boolean isFilePresent = false;
if (smbFiles.length > 0) {
for (SmbFile file : smbFiles) {
if (file.getName().toLowerCase(Locale.ENGLISH)
.contains(AppConstant.FILE_NAME.toLowerCase(Locale.ENGLISH))) {
xmlFiles.add(file);
isFilePresent = true;
}
}
}
if (isPlanFilePresent) {
log.info("Number of files present on Server: {}",smbFiles.length);
return true;
}
return false;
}
This will give you the files in the list. Go ahead to copy it to another server. Note that you need to authenticate here for the output Folder only.
public boolean moveFile(SmbFile file) {
log.info("Started Moving or Archiving the file");
String toFilePath = this.outputFolder + file.getName(); //path where you need to copy the file from input folder.
try {
NtlmPasswordAuthentication auth1 = new NtlmPasswordAuthentication("", outputFolderUserId, outputFolderPassword); //authenticating output folder
log.info("targetFilePath: {} and currentFile : {}", toFilePath, file);
SmbFile targetFile = new SmbFile(toFilePath, auth1);
try {
file.copyTo(targetFile);
file.delete(); //delete the file which we copied at our desired server
log.info("Archived File : {} to: {}", file.getName(), targetFile.getName());
return true;
} catch (SmbException e) {
log.error("Unable to Archive File: {}", file.getName());
return false;
}
} catch (MalformedURLException e) {
log.error("Connection failed to Server Drive: {}", toFilePath);
}
return false;
}

Resources