How can I get browser URL via API of a Google Spreadsheet from its id? - google-sheets

I'm importing a csv file to Google spreadsheet via API,
I have a DocumentListEntry object:
DocumentList docs = new DocumentList("test");
docs.login(adminEmail, adminPassword);
DocumentListEntry newDocs=docs.uploadFile(uploadfilepath, filename);
I can retrieve its id doing newDocs.getDocId() but how I can find the URL to be used as a link in browser to open the document?

You can use the Drive SDK API "files/get" to get web url by fileid. The API document is here:
https://developers.google.com/drive/v2/reference/files/get
From the result json file, there is a "alternateLink" which is right what you wanted.

Related

Google sheets last opened time stamp

How do I see the exact time stamp a sheet was opened on Google Sheets? I can see the date it was opened under ‘Last opened by me’ but not the exact time (unless opened today). Thank you
Please take note that this solution will only provide you the datetime you last viewed the file. It will not show you the datetime when another user opened/viewed a Google Sheet file.
Use Drive API v3 (either API explorer or choose your preferred programming language):
Use Files.list() to search for files in your drive. Use the query term to filter your search.
In this example query, I want to get all the files in my drive with Google Sheets mimetype having the file name of 'Copy of Inventory'
Sample Request using API explorer:
q: mimeType = 'application/vnd.google-apps.spreadsheet' and name = 'Copy of Inventory'
fields:files/name, files/id, files/viewedByMeTime
Sample Response using API explorer:
{
"files": [
{
"id": "1-zarWNraQWigfRl6YyjhUpWHEROVaR9BcAxxxxxx",
"name": "Copy of Inventory",
"viewedByMeTime": "2021-05-18T17:12:39.630Z"
}
]
}
You can also do this in Apps Script using Advanced Drive Service which uses Drive API v2.
Note that the file name tag in Drive API v2 is title
Sample Code:
function getSheetViewTime() {
var query = 'mimeType = "application/vnd.google-apps.spreadsheet" and title = "Copy of Inventory"';
Logger.log(query);
var files = Drive.Files.list({q:query});
Logger.log(files.items[0].lastViewedByMeDate)
}
Result:
5:53:14 AM Notice Execution started
5:53:16 AM Info mimeType = "application/vnd.google-apps.spreadsheet" and title = "Copy of Inventory"
5:53:16 AM Info 2021-05-18T17:12:39.630Z
5:53:16 AM Notice Execution completed

How to get the shared file with Microsoft Graph?

I want to share files from MS OneDrive to a user via MS graph API. And user can view my shared file directly through the link. I have read the Document of Creating a sharing Link for a DriveItem and use this API to create a sharing link for my sharing files.
I wonder how to implement with MS graph API? Any suggestion and tips are welcome. Thanks
According to your description, I assume you want to get the share file by using MS Graph API.
Base on my test, We can create a shareLink for this this file.
Then we can use the following steps to get the file information by converting the shareLink.
Encoding the shareLink by using the following logic:
1)First, use base64 encode the URL.
2)Convert the base64 encoded result to unpadded base64url format by removing = characters from the end of the value, replacing / with _ and + with -.)
3)Append u! to be beginning of the string.
If you want access the shared files, you can use the following API:
GET /shares/{shareIdOrUrl}/driveItem
The shareIdOrUrl parameter is the result in step1.
This API will return all the information about the shared file.
As an example, to encode a URL in C#:
string sharingUrl = "https://onedrive.live.com/redir?resid=1231244193912!12&authKey=1201919!12921!1";
string base64Value = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(sharingUrl));
string encodedUrl = "u!" + base64Value.TrimEnd('=').Replace('/','_').Replace('+','-');
For more detail, we can refer to this document.

How to download a file via the Google Drive API?

I'm working to download a file via the Google Drive API using the gem google-api-client.
x = Google::Apis::DriveV2
drive = x::DriveService.new
drive.authorization = auth
files = drive.list_files
files.items.each_with_index do |file, index|
url_to_index = file.export_links.select { |k, v| v if k == 'text/plain' }
file_content = open(url_to_index["text/plain"]).read
end
The problem is file_content is returning the Google login screen not the file in text/plain format. It appears that when my Rails app opens the URL it does not have access to the text file.
What's the right way to enable my Rails app to grab the file in the text format?
Stated in Download Files
Depending on the type of download you'd like to perform — a file, a Google Document, or a content link — you'll use one of the following URLs:
Download a file — files.get with alt=media file resource
Download and export a Google Doc — files.export
Link a user to a file — webContentLink from the file resource
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.
You may go through the documentation for more information and examples.
See the log output: Two factor autentifications need to you permit access from you app to your google drive account.
In log you will see needed info to do this: link and secret_key.
tail -f log/*.log
I just realize that mimetype for download is different from the file meta.
Please check this url for available mimetype : https://developers.google.com/drive/api/v3/integrate-open
for example mimeType : 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
'

google drive sdk/google drive api ----using PHP web application

I am creating website page using Google drive API which do following stuff:--
provide user set of pdf file which is stored in my Google drive without any type of Login / authentication by any means and file are public.
who visit that page and if he/she want to download that file/pdf then he/she can do so just by clicking on it without any signup and login.
i have no idea how to getting started with it...is it necessary to use OAuth 2...
in simple word i want to use google drive as file hosting site to host my file and reach users through website.
please give me your valuable solution...
thanks
For php look here for a full example and video. You have to download the Google Drive API for the programming language you are using. Then use that API to help you auth and access files. Here is an example from Google developers page using PHP
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
$client = new Google_Client();
// Get your credentials from the console
$client->setClientId('YOUR_CLIENT_ID');
$client->setClientSecret('YOUR_CLIENT_SECRET');
$client->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$service = new Google_DriveService($client);
$authUrl = $client->createAuthUrl();
//Request authorization
print "Please visit:\n$authUrl\n\n";
print "Please enter the auth code:\n";
$authCode = trim(fgets(STDIN));
// Exchange authorization code for access token
$accessToken = $client->authenticate($authCode);
$client->setAccessToken($accessToken);
//Insert a file
$file = new Google_DriveFile();
$file->setTitle('My document');
$file->setDescription('A test document');
$file->setMimeType('text/plain');
$data = file_get_contents('document.txt');
$createdFile = $service->files->insert($file, array(
'data' => $data,
'mimeType' => 'text/plain',
));
print_r($createdFile);
?>
You will want to use the PHP client library located here: https://developers.google.com/api-client-library/php/
You will then want to authenticate against google using auth2.
Then you can make calls to the Drive API https://developers.google.com/drive/v2/reference/ using the PHP client library.

Reading File on Google Drive using Dart

I created a configuration file (Simple Text File) on my Google Drive and now I would like to read it from my Chrome Packaged Dart Application. But I'm not able to get more information of the file than it's name, size etc.
For accessing Google Drive I use the google_drive_v2_api.
Any suggestion on how to get the contents of my configuration file would be great! Thanks!
I just did some test in my own chrome app, uploading and downloading a simple file:
chrome.identity.getAuthToken(new chrome.TokenDetails(interactive: true ))
.then((token){
OAuth2 auth = new SimpleOAuth2(token);
var drive = new gdrive.Drive(auth)..makeAuthRequests=true;
drive.files.insert({},content:window.btoa('hello drive!')).then((sentMeta){
print("File sent! Now retrieving...");
drive.files.get(sentMeta.id).then((repliedMeta){
HttpRequest request = new HttpRequest()..open('GET', repliedMeta.downloadUrl)
..onLoad.listen((r)=>print('here is the result:'+r.target.responseText));
auth.authenticate(request).then((oAuthReq)=>oAuthReq.send());
});
});
});
It works, but the HttpRequest to get content back seems heavy...
But i really recommend you to a take look to chrome.storage.sync if your config file size is < to 4ko... If not, you could also use the chrome SyncFileSystem API... They are both easier to use, and SyncFileSystem use Drive as backend.
This page on downloading files talks through the process for getting the contents of a file.

Resources