Not receiving "webViewLink" in response? - google-drive-api

After turning on Google Drive API access from the management console and getting my Client ID keys, I followed the sample code (using Python 2.7) and I am able to insert a folder, set the appropriate permissions (type=anyone,role=reader), and insert a text/html type file into the new folder.
However the JSON file resource objects I receive from executing insert on the drive service have no 'webViewLink' field! There are 'webContentLink' and 'selfLink' fields but 'webViewLink', which is necessary for static HTML publishing, seems to be missing.
Most perplexing. If this feature hasn't been turned on yet or if I need to configure my account settings to allow HTML publishing please let me know. Any other help would be most appreciated ;)

The webViewLink property is only returned for public folders, and not the single files inside such folders. You can use that as the base url to construct links to your files.

The WebViewLink file property can be retrieved by doing something like this:
$file = $service->files->get($file_id, array('fields' => 'webViewLink'));
$web_link_view = $file->getWebViewLink();
OR
$sheetsList = $drive_service->files->listFiles([
'fields' => 'files(id, name, webViewLink, webContentLink)',
]);
$web_link_view = $sheetsList->current()->getWebViewLink();
Pay attention that you should load the file specifying which fields you wanna bring with it (In this case, webViewLink). If you don't do that, only id and name will be available.
If you also need to configure file permissions, you can do something like:
$permissions = new \Google_Service_Drive_Permission();
$permissions->setRole('writer');
$permissions->setType('anyone');
$drive_service->permissions->create($file_id, $permissions);
Possible values for setRole() and setType() can be found here: https://developers.google.com/drive/api/v3/reference/permissions/create

Related

CSV file read issue in firebase functions

I am trying to read a csv file in a firebase function so that I can process the file and do the rest operations using the data.
import * as csv from "csvtojson";
const csvFilePath = "<gdrive shared link>"
try{
console.log("First Method...")
csv()
.fromFile(csvFilePath)
.then((jsonObj: any)=>{
console.log("jsonObj....",JSON.stringify(jsonObj));
})
console.log("Second Method...")
const jsonArray=await csv().fromFile(csvFilePath);
console.log("jsonArray...", JSON.stringify(jsonArray))
}
catch(e){
console.log("error",JSON.stringify(e))
}
The above mentioned are the 2 methods I have tried for reading the csv but both shows the firebase error
'Error: File does not exist. Check to make sure the file path to your csv is correct.'
In case of 'csvFilePath' I have tried 2 methods
Just added the csv file in same folder of the function and added the code like
const csvFilePath = "./student.csv"
Added the same file to google drive and changed the access permissions to anyone with the link can read and edit and given the path to same
const csvFilePath = "<gdrive shared link>"
Both shows the same error. In case of google drive I don't want to use any sort of google credential because I was intented to read a simple csv file in firebase function.
I will start by proposing that you convert your csv to json locally or without the function and see if it works. This is because I see you are using ES6 imports which might be causing an issue since all the documentation uses require. You can also try CSV Parse or some solutions provided in this question as an alternative, trying them without the function to check if it actually works and discard it. Actually, you can upload the JSON once you have converted it from the csv, but that depends on what you are trying to do.
I think the best way to achieve this, is following the approach given in this question, that first uploads the file into cloud storage and using onFinalize() to trigger the conversion.
Also, will address these three questions that went through similar issues with the path. They were able to fix it by adding __dirname. Each one has some extra useful information.
Context for "relative paths" seems to change to the calling module if a module is imported
The csvtojson converter ignores my file name and just puts undefined
How to avoid the error which throws a csvtojson

Autodesk Forge - downloaded item has a different name

I'm using the https://developer.api.autodesk.com/oss/v2/buckets/:bucketKey/objects/:objectName endpoint to download an item (a Revit model) from BIM 360. Using this documentation. The file gets downloaded fine and the contents are correct however, after downloading, the file name is the GUID of the file (4aac519c-ab91-42a5-85c5-f023c82d4736.rvt) , not the 'displayName' of the file (my file.rvt) . I'm getting the file name like so:
var headervalue = resp.Headers.FirstOrDefault(x => x.Name == "Content-Disposition")?.Value;
string contentDispositionString = Convert.ToString(headervalue);
ContentDisposition contentDisposition = new ContentDisposition(contentDispositionString);
fileName = contentDisposition.FileName;
I've used the same method on another project and it's working fine. The content and the file name of the file both are correct. However somehow the endpoint is behaving differently on this project.
Any pointers what could be the issue here?
I'm not sure if this is mentioned somewhere in the documentation but I don't think you should rely on the Content-Disposition of the response headers for this. If you want to get a filename for whichever object you're downloading, you should always get it from the actual item record (obtained in the 3rd step of the tutorial you linked to).

Download a file from Google Drive using google-api-ruby-client

I try to download files from a directory on Google Disk.
The code, mostly copied from official quickstart guide, works fine:
# ... code from official quickstart tutorial...
# Initialize the API
service = Google::Apis::DriveV3::DriveService.new
service.client_options.application_name = APPLICATION_NAME
service.authorization = authorize
# now the real deal
response = service.list_files(q: "'0ByJUN4GMe_2jODVJVVpmRE1VTDg' in parents and trashed != true",
page_size: 100,
fields: 'nextPageToken, files(id, name)')
puts 'Files:'
puts 'No files found' if response.files.empty?
response.files.each do |file|
puts "#{file.name} (#{file.id})"
# content = service.get_file(file.id, download_dest: StringIO.new)
end
The output looks fine:
Files:
k.h264 (0B4D93ILRdf51Sk40UzBoYmZKMTQ)
output_file.h264 (0B4D93ILRdf51V1RGUDFIWFQ5cG8)
test.mp4 (0B4D93ILRdf51dWpoZWdBV3l4WjQ)
test2.mp4 (0B4D93ILRdf51ZmN4ZGlwZjBvR2M)
test3.mp4 (0B4D93ILRdf51ZXo0WnVfdVBjTlk)
12.mp4 (0ByJUN4GMe_2jRzEwS1FWTnVkX00)
01.mp4 (0ByJUN4GMe_2jSlRWVEw4a1gxa2s)
01.mp4 (0ByJUN4GMe_2jOFpPMW9YNjJuY2M)
But once I uncomment content = service.get_file(file.id, download_dest: StringIO.new), I get a lot of errors:
Files:
k.h264 (0B4D93ILRdf51Sk40UzBoYmZKMTQ)
/Users/mvasin/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/google-api-client-0.9.15/lib/google/apis/core/http_command.rb:211:in `check_status': Invalid request (Google::Apis::ClientError)
[...lots of other 'from' stuff...]
from /Users/mvasin/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/google-api-client-0.9.15/generated/google/apis/drive_v3/service.rb:772:in `get_file'
from quickstart.rb:56:in `block in <main>'
from quickstart.rb:54:in `each'
from quickstart.rb:54:in `<main>'
But that's the way it should work according to ruby section in "download files" official tutorial.
I also tried content = service.get_file(file.id, download_dest: "/tmp/#{file.name}"), but it failed with the same set of errors.
UPDATE: Here are my findings. If you start with Google Drive API Ruby quick start tutorial, and want make it download something,
1) change scope to not just let your script read meatadata, but read files contents as well:
SCOPE = Google::Apis::DriveV3::AUTH_DRIVE_METADATA_READONLY
to at least
SCOPE = Google::Apis::DriveV3::AUTH_DRIVE_READONLY
2) Filter out google docs files, because you can't download them this way, you have to convert them. To filer them:
2.1) Add mime_type to fileds set:
response = service.list_files(page_size: 10, fields: 'nextPageToken, files(id, name, mime_type)')
2.2) and in the final loop where you print files' ids and names, put something like
service.get_file(file.id, download_dest: "/your/path/#{file.name}") unless file.mime_type.include? "application/vnd.google-apps"
From the error that you got, it says that your request is invalid. So make sure that your request there are correct. Here is the documentation on how to download files using Ruby(just click the Ruby on the example to view the ruby code.)
Take NOTE: Downloading the file requires the user to have at least
read access. Additionally, your app must be authorized with a
scope
that allows reading of file content.
For more information, check these threads:
How to download file from google drive api
A Ruby library to read/write files

Google Drive API get file Edit URL

As of 04/20/2015 the Google Documents API v3.0 is deprecated, and will no longer function function on and after this date. So anyone using this API must switch to use the Google Drive API.
I have integrated the Google Drive API into my PHP application, but I can not find how to get a EDIT url for a file I have created or uploaded. Previously in the Google Documents API after uploading a file, the response would return a edit url that would be a direct url to edit the file.
I am using a service account that uses a generated key by my google developers account at https://console.developers.google.com. This means my application is making calls on behalf of my service account the developer account has created for me. A google drive service account CAN NOT be accesses by the Drive UI, because as a user you can not login to the account as you would a personal google account.
What I have done is shared my documents I have uploaded or created with my personal account, and the url google returns in the call is named "alternateLink" and it is formatted as such:
https://docs.google.com/file/d/0B0nkjw07ekP9LUpuZG4tOHcxdkE/edit?usp=drivesdk
However when logged into the account I shared the above file with, it just goes to a viewer and not the "Google Docs Editor"
How can I get a file's edit link with Google Drive API?
The link you are using is correct, so that's not the issue.
The main problem was you have to set convert true in the time of upload. Without converting the file google will give you the link to view not to edit.
Here you will get file upload detials. Please check the below code i have only added the convert field:-
$file = new Google_Service_Drive_DriveFile();
$file->setTitle($title);
$file->setDescription($description);
$file->setMimeType($mimeType);
// Set the parent folder.
if ($parentId != null) {
$parent = new Google_Service_Drive_ParentReference();
$parent->setId($parentId);
$file->setParents(array($parent));
}
try {
$data = file_get_contents($filename);
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => $mimeType,
'convert' => true // To convert you file
));
return $createdFile;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
The AlternateLink is the edit url, and my issue was the uploadType value and the mime-type for the document type when attempting to upload or create the document with the google drive api.
The file edit URL can be found under the WebViewLink file property. You can retrieve it by doing something like:
$sheetsList = $drive_service->files->listFiles([
'fields' => 'files(id, name, webViewLink, webContentLink)',
]);
// You could be using $seetList->getFiles() to loop through the files.
// Here we're just picking the current one (any file) to get the WebViewLink for.
print $sheetsList->current()->getWebViewLink();
In order to adjust file permissions you can use:
$permissions = new \Google_Service_Drive_Permission();
$permissions->setRole('writer');
$permissions->setType('anyone');
$drive_service->permissions->create($file_id, $permissions);
Possible values for setRole() and setType() can be found here: https://developers.google.com/drive/api/v3/reference/permissions/create

nodejs dont recognize own extension instead of JSON

I am trying to use own .extension for .JSON files. But when I require them node don't recognize them.
For example when I do:
var users = require('users.json');
users is now a object like:
name: 'somebody', age: 27
When I do just the same file but other .extension"
require('users.myextension')
users is now empty;
=> {}
Is there a way to fix this, otherwise I have to use just JSON as extension.
You can look at globals
In short you can instruct how require should load a file in this way:
require.extensions['.extension'] = require.extensions['.json'];
Please mind that this is deprecated but as stated in the note the feature probably will not be removed since the module system is locked.