Google Docs API see Docs without knowing id - google-chrome

I'm creating a Chrome extension which when highlighting text anywhere will offer the user to save the highlighted text to any Doc in Google Docs. So the idea is to show a list of last 10 Google Docs and the user could save it to any of them or could search for another Doc.
I've been reading documentation on Chrome identity API, Docs API and Drive API, and they all mention that we need to know the Doc's id (which is inside the url of the Doc).
So it's not possible to display a list of Docs without knowing their actual ids? I guess it would be a security violation if an extension or an app could do this? Or I'm mistaken and it's actually possible?
P.S. This link seems to be what I was looking for (so it's possible): https://developers.google.com/drive/api/v3/reference/files/list

Answer:
Yes, you can get a list of the last 10 modified files in Google Drive using the modifiedDate, pageSize and mimeType parameters.
More Information:
You can make a Files: list query to the Drive API with parameters narrowing down your search. As you do not know the file IDs, you can search for files which have the application/vnd.google-apps.document MIME Type, and then narrow the search down by ordering by the modifiedDate and only requesting 10 results.
Code:
As I'm not 100% sure on which language you are using, I've provided a simple Apps Script example below. The relevant references can be seen below though so you can modify this to suit your coding requirements.
function myFunction() {
var searchTerms = {
orderBy: "modifiedDate",
pageSize: 10,
q: "mimeType='application/vnd.google-apps.document'"
};
for (var i = 0; i < 10; i++) {
Logger.log(Drive.Files.list(searchTerms).items[i].title);
}
}
Don't forget to enable the Advanced Drive Service for this! Also remember that the Advanced Drive service uses Drive v2, though this can be done in both Drive API v2 and Drive API v3.
References:
Google Drive API v3 - Files: list
Advanced Drive Service - Listing folders
G Suite and Drive MIME Types

Related

Google App Script Advanced Service: Drive API

https://spreadsheet.dev/automatically-convert-excel-spreadsheets-to-google-sheets-using-apps-script
On the page above, Drive API is introduced to convert excel file to Google Sheet
let blob = excelFile.getBlob();
let config = {
title: "[Google Sheets] " + excelFile.getName(),
parents: [{id: excelFile.getParents().next().getId()}],
mimeType: MimeType.GOOGLE_SHEETS
};
let spreadsheet = Drive.Files.insert(config, blob);
I've been checking Google Drive API's ducumentation and references, but couldn't find anything regarding Drive.Files and Drive.Files.insert. Can someone direct me to the right documentation so I can learn to use these interfaces myself? Thanks!
Unfortunately, it seems that the detailed document of Drive API of Advanced Google services is not been officially published. But, in your situation, I thought that the document at the autocomplete of the script editor of Google Apps Script might be useful.
When the script editor of Google Apps Script is used, you can use the autocomplete of each method. In this case, when Drive API is enabled at Advanced Google services, this autocomplete can be also used for the methods of Drive API. When this is used, the documents of each method can be seen as follows. As a sample, Drive.Files.insert is used.
This completion includes an explanation of the method. In the case of Drive.Files.insert, it is found that it is Insert a new file. and the arguments are
resource: Drive_v2.Drive.V2.Schema.File
This is a request body of "Files: insert" of Drive API v2 Ref
mediaData: Blob
This is a Blob.
optionalArgs: Object
This is the query parameter of "Files: insert" of Drive API v2 Ref
, respectively. From this, it is found that this is Drive API v2. And, Drive_v2.Drive.V2.Schema.File is returned. This can be seen at here.
I thought that this document of the autocomplete with the script editor might be useful for understanding how to use Drive API at Advanced Google services.
Note:
This autocomplete can be also used for all APIs (Sheets API, Docs API, and so on) of Advanced Google services. I think that the document shown with the autocomplete with the script editor might be useful for understanding how to use the APIs at Advanced Google services.
References:
Advanced Google services
Using autocomplete
You may look into the use of Drive.Files and Drive.Files.insert under Advanced Drive Service.
It is somewhat the same use of Drive API, but the provided code on the reference you have provided leans toward using Drive API on App Script (which has a somewhat different syntax as oppose to using Drive API with other languages)
References:
https://developers.google.com/apps-script/advanced/drive
https://developers.google.com/drive/api/v2/reference/files/insert
https://developers.google.com/drive/api/samples

Using ApI is it possible to edit or open Google Sheet?

Using API to get access_token and now I need to open Google Sheet.
Step 1.
Authorization: Bearer ya29.a0AV...." together with link: "https://docs.google.com/spreadsheets/u/0/d/[DocumentFileID]/edit"
Step 2.
Now HTML document back (~200kb). I'm using libcurl for that.
The problem is - missing are some css and js files and I see document just partially. Is there any way to open/edit Google Sheet using API?
I know for the option to just open https://docs.google.com/spreadsheets/u/0/d/[DocumentFileID]/edit in the new browser tab, but in that case I need to manually login to Google and that's what I try to avoid, because I want to use API to login and to open/edit a Sheet.
I also know for the option to share a document but I also try to avoid that. I'm writing application to customers who can access they own documents once they confirmed API usage.
I think you may have misunderstood what the google sheets api can do
The Google Sheets API is a RESTful interface that lets you read and modify a spreadsheet's data.
It gives you access to the data, it does not allow you to open the google sheets web application. Your going to have to code your own google sheets type app if you want users to open sheets directly.

How can I Find All Uses of a Google Script Library?

I have a Google Script library that is used by at least 100 other scripts (some that are bound to spreadsheets/documents, some that are not). How can I find all of these client scripts that reference my library script?
More specifically, I need to be able to add a new feature into the library that requires new permissions that I (the user) must grant. The client scripts won't run if I just add this feature to the library without granting the permissions to each of the client scripts. So ultimately, I need to give this new permission to each of the clients. And if I knew what scripts were actually using this library, I could do that manually for each one. But I need to URL's or ID's or something for each of those scripts.
Answer:
Unfortunately this is not possible to do.
More Information
It is possible to get a list of standalone Scripts from your Drive, though scripts bound to a file can not be searched for using regular searching methods.
It is possible, using the help of this Google Account page to get a list of all the Apps that have access to your account, though only files you have authorised will appear here, and apps which are not just those created by you in Apps Script will appear there (for example, other add-ons or even Android Apps bound to your account appear here).
A Partial Workaround:
Using Google Apps Script, you can list all Apps Script Projects that you own with help of the MimeType enumeration GOOGLE_APPS_SCRIPT
var scripts = DriveApp.getFilesByType(MimeType.GOOGLE_APPS_SCRIPT);
var arr =[ ];
while (scripts.hasNext()) {
var script = scripts.next();
arr.push(script)
}
Logger.log(arr);
Or even just searching for type:script in Drive, however this only returns a list of scripts that are not bound to a file.
You can then use regular Google Drive search terms to find which of these files contain, for example, a unique method name that the library uses. I am aware this isn't a perfect solution and you would still have to look for projects bound to a file using the above webpage.
Feature Request:
It appears that back in 2014 a feature request for this was made on Google's Issue Tracker, though I would suggest creating another feature request for this here as it was marked as a duplicate of another issue. You can make a feature request under the correct Apps Script component here.
References:
Google Apps Script - Enum MimeType
Google Drive Search Query Terms
Apps with access to your account
Google's Issue Tracker
Feature Request: Listing and searching for container bound scripts
Create an Apps Script Feature Request

Script for a Google Doc .makeCopy() the comments aren't copied?

Hello is possible twhen copying a Google Doc document to copy also the comments in the "copy doc."Because I've tried this with the TEMPLATE_DOC_ID which has many comments and I don't find the comments in the "copy".I am missing something?It's another method? Thanks!
//Make a copy of the template file
var documentId = DriveApp.getFileById(TEMPLATE_DOC_ID).makeCopy().getId();
Unfortunately, the Google Docs copied by makeCopy() don't include the comments. So the comments and replies are required to be inserted to the copied file, after the file was copied. In order to implement this, please enable Drive API at Advanced Google Services and API console.
Enable Drive API v2 at Advanced Google Services
On script editor
Resources -> Advanced Google Services
Turn on Drive API v2
Enable Drive API at API console
About Drive API, in your environment, this might have already been enabled.
On script editor
Resources -> Cloud Platform project
View API console
At Getting started, click Enable APIs and get credentials like keys.
At left side, click Library.
At Search for APIs & services, input "Drive". And click Drive API.
Click Enable button.
If API has already been enabled, please don't turn off.
Sample script :
var documentId = DriveApp.getFileById(TEMPLATE_DOC_ID).makeCopy().getId();
// Added script
var commentList = Drive.Comments.list(TEMPLATE_DOC_ID);
commentList.items.forEach(function(item) {
var replies = item.replies;
delete item.replies;
var commentId = Drive.Comments.insert(item, documentId).commentId;
replies.forEach(function(reply) {
Drive.Replies.insert(reply, documentId, commentId).replyId;
});
});
Note :
Unfortunately, the create time and modified time couldn't updated. So the date becomes the created date.
References :
Advanced Google Services
Drive API
Comments: insert
Replies: insert
If this was not what you want, I'm sorry.

Get JSON of container-bound Google Apps-Script through Apps-Script or download

If you create a non-container bound g-apps script (i.e. not as part of a gDoc or a gSheet), you can download it (however not view as a .json directly in the browser from the link) from gDrive as a .json. If you download a gDoc or gSheet, it converts to xlsx or docx and opening these with a zip viewer shows a number of files (many of type xml) however none contain the Google version's attached scripts.
Is there a way to read script files as a .json from within another Google Apps
Script? perhaps using the Drive-API or with g-a-s. DriveApp class?
Is there a way to download or read through DriveApp, the .jsons of
container bound scripts (which are usually invisible from all but within the original gFile)?
Update
Based on Kriggs, added a Logger.log(link) and this works great for stand-alone scripts.
How about for container-bound?
for stand alone script files:
exportLinks={
application/vnd.google-apps.script+json=
script.google.com/feeds/download/export?id=[scriptId]&format=json
}
for container-bound script files, there are links to csv, sheet and pdf, but no script json.
exportLinks= {
text/csv=docs.google.com/spreadsheets/export?id=[sheetId]&exportFormat=csv,
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet=
docs.google.com/spreadsheets/export?id=[sheetId]exportFormat=xlsx,
application/pdf=
docs.google.com/spreadsheets/export?id=[sheetId]&exportFormat=pdf
}
Update
In Google sheet, go to Tools->script Editor->
URL in address bar looks like:
https://script.google.com/macros/d/
[ProjectKey]/edit?uiv=2&mid=[aVeryLongAlphaNum]
this is the download json:
https://script.google.com/feeds/download/export?id=[ProjectKey]
Question is, can we use the Drive API to find [ProjectKey]
Have there been any feature requests for DriveApp/Drive-API methods to seek Project Keys in your account?
Would there be a way to test if a file has a container bound script? Then the question is, is the script included in the file size (this can be easily tested, however it is unknown to the asker at this point).
Something like this may work although it looks computationally costly:
var SizeOfFile = yourFile.getSize();//
var charsInFile = yourFile.getAsString();
var unicodeSizeReference = [];//get bytes per character array
charsInFile.sort()
//find frequency of characters then multiply from unicoseSizeReference.
//there could be other gotchas as well, however this is just testing for feasibility
var SizeOfTextInFile = [/*#of chars in file name and sheetname*/]+[/*#of chars in all sheets*/];
SizeOfTextInFile *= unicodeBytesPerCharacter;//ranges from 1 to 4
var someThreshold = 10;//bytes
var hasScript=0;
if ([SizeOfFile - SizeOfTextInFile] > someThreshold) hasScript=1
Yes you have to get it trough the Drive API with OAuth2, I used the DriveApp to get the fileId, but you can modify to use Drive api aswell. To enable the Drive API go to Resources -> Advanced Google Services, find the Drive API and turn on.
When you send a get with Drive you get back an object of the file which contains the property exportLinks, using it you fetch the URL with OAuth2 authentication (the ScriptApp.getOAuthToken()), the fetched string will be a JSON, which has the Array fileswith the colection of scripts.
function getAppsScriptAsJson( fileName ) {
var fileDrive = Drive.Files.get( DriveApp.getFilesByName( fileName ).next().getId() );
var link = JSON.parse(fileDrive)[ 'exportLinks' ][ 'application/vnd.google-apps.script+json' ];
var fetched = UrlFetchApp.fetch(link, {headers:{'Accept':'application/vnd.google-apps.script+json', "Authorization":'Bearer '+ScriptApp.getOAuthToken()}, method:'get'});
return JSON.parse(fetched.getContentText());
}
As for container bound:
DriveApp can't get it by name
It doesn't display an ID anywhere, just the project key
Drive API can't lookup by the project id, nor DriveApp
Drive API can't find by the name
There's no reference of the script from the returned object from Drive API nor the DriveApp
I guess it is pretty much incognito, doubt there's any way ATM.
You can always make a Standalone app and set it as a library for the Spreadsheet...