How to get the filesize of document from Doc Picker - google-drive-api

I am using the Picker Class (https://developers.google.com/picker/docs/reference#configuration-classes-and-types) to allow users to upload files from their Google Drive account.
I can get various properties of what they've selected, but I cannot seem to be able to get the file size;
eg;
var doc = data[google.picker.Response.DOCUMENTS][0];
url = doc[google.picker.Document.URL];
var name = doc[google.picker.Document.NAME];
var size = ??? [how-to-get-document-file-size]

Using the property name fileSize, as given in Drive REST API v2 - Files, can be used but is only populated for files with content stored in Drive. It is not populated for Google Docs or shortcut files.
I tried to look for ways on how to get file size too, but it seems that it is currently not available. Google Drive SDK currently do not provide the size of a file created within Google doc and found this SO post - Retrieve a “Google doc” created file size with the google drive api for ios which is somehow related to your concern.

Related

Google Picker API hide native google drive workspace formats

In Google Drive a user can create a new Google Doc/Sheet/Slide/Form etc as a Drive native format. Is there a way to hide these types of files when using the Drive Picker API? I want the user to only see files they have uploaded (or have had shared with them) and not created in Drive.
For example, if I add a view to the picker with ViewId.DOCUMENTS, then everything from Google Doc, txt, and docx show up. Just haven't found away to filter out the Google Doc mime type.
Have you tried using setMimeTypes? Use it to specify what format do you want to be included.
Code:
var view = new google.picker.View(google.picker.ViewId.DOCS);
// include only txt and docx files
view.setMimeTypes("text/plain,application/vnd.openxmlformats-officedocument.wordprocessingml.document");
var picker = new google.picker.PickerBuilder()
.addView(view)
Output:
Note:
Drive picker was made for google drive. So it's natural to only have Views supporting its native file types.
What's good is that Google provided us a way of specifying file types not included in their views via setMimeTypes
Currently, I don't find any methods in excluding a certain mime type or view
Additionally, you can try setQuery. I tested this a bit and it seems view.setQuery("*.docx|*.txt") will result in all docx and txt files (in my case). You can combine this with or choose it over setMimeTypes. Just test it out to see what solution fits you.
Reference:
Picker

move generated google Form to specific google drive folder using google apps script

I am creating a few forms using Google Apps Script which automatically generates in my root (My Drive) of my Google Drive.
I want to move these forms to a specific folder of a Shared Drive.
I googled about moving files (or any object) to another folder, most of them are suggesting that copy the file to a specific location, then delete from the source location.
But in this case, my formIds are changing which I don't want to change.
Is there any better way to move files (in my case Forms) to another location in Google Drive?
As a developer you should always favor canonical sources over 3rd party tutorials that pop-up in google search. The official documentation for the Drive API has guides describing how to move files from one drive folder to the next. I suggest you start there.
the following code should work for moving any file, including forms, to a destination folder in Google Drive:
var fileId = '1234567890abcdefghijklmnopqrstuvwxyz'; //<--replace string with your file ID
var destinationFolderId = 'zyxwvutsrqponmlkjihgfedcba0987654321';//<--replace string with your destination folder ID
function moveFile(fileId,destinationFolderId) {
var destinationFolder = DriveApp.getFolderById(destinationFolderId);
DriveApp.getFileById(fileId).moveTo(destinationFolder);
}

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...

Using Google Picker to access a shared Google Drive within a PHP webapp

I have a Google Drive that contains hundreds of files that are currently referenced and then linked within a PHP webapp. Users authenticate with the webapp and not with Google. I want use the Google Picker and point it at this shared, but private, Google Drive so users can access these documents.
I've seen a load of examples where the Picker is used to access the users Google Drive but not where Picker is pointing to another Google Drive.
I'm migrating from Google Documents List API v2 where this functionality is available, but the PIcker is far better solution.
Is there a way to accomplish this?
If your using the Google Picker from here https://developers.google.com/picker/docs then you can set one view for not shared drives and another one for shared drives, this will appear as two tabs on the picker
const docsView = new google.picker.DocsView(googleViewId)
.setIncludeFolders(true)
.setSelectFolderEnabled(true);
const folderView = new google.picker.DocsView(googleViewId)
.setIncludeFolders(true)
.setEnableDrives(true)
.setSelectFolderEnabled(true);
const picker = new window.google.picker.PickerBuilder()
.enableFeature(google.picker.Feature.SIMPLE_UPLOAD_ENABLED)
.enableFeature(google.picker.Feature.SUPPORT_TEAM_DRIVES)
.enableFeature(google.picker.Feature.MULTISELECT_ENABLED)
.addView(docsView)
.addView(folderView)
.setOAuthToken(oauthToken)
.setDeveloperKey(Config.googlePickerApiKey)
.setCallback((data)=>{
if (data.action === google.picker.Action.PICKED) {
// var fileId = data.docs[0].id;
onSelect(data.docs)
}
});
It's not documented but you can set a Google user ID while building a new picker.
var picker = new google.picker.PickerBuilder().setAuthUser(<userId>)...

how to find files not owned by me in Google apps script

In Google Drive one can search files 'Not owned by me'.
I need access to this from Google Apps Script.
I already tried DocsList.find("Not 'me' in owner"); which appears to be the way to do it in the drive API, but without success (in fact that gets me files with me as owner.) I also replaced me with my email address, with and without quotes, but again without success.
Does anyone know if this is possible (other than by iterating all files and checking getOwner().getEmail() manually, which would take far too long given the enormous amount of files owned by this specific user.)
I think the updated answer as of now is to use DriveApp.searchFiles(params) (https://developers.google.com/apps-script/reference/drive/drive-app#searchFiles(String) ).
Code is something like:
// Log the name of every file in the user's Drive that shared with me
var files = DriveApp.searchFiles('sharedWithMe');
while (files.hasNext()) {
var file = files.next();
Logger.log(file.getName());
}
This function will return an array of all files shared with you. It uses the Advanced Drive Service, which must be enabled before use.
/**
* Get array of files on user's Google Drive that have been shared with them.
* From https://stackoverflow.com/a/15947340/1677912
*
* #returns {Array} Array of file resources
* (see https://developers.google.com/drive/v2/reference/files#resource)
*/
function getSharedWithMe() {
var optionalArgs = {q:"sharedWithMe=true"};
var sharedFiles = Drive.Files.list(optionalArgs);
debugger; // pause in debugger
return sharedFiles.items;
}
You can do the same thing without code, by using the Google Drive SDK "Explorer".
See this previous answer that used this technique to get a list of trashed files.
You'll find the Files List API Explorer at the bottom of the Google Drive SDK documentation page for Files:list. For information about search terms, see Search for files. For our purposes, we'll just use sharedWithMe.
If you leave "fields" blank, you'll get everything that's known about the shared files. You can expand and collapse the results using hard-to-see minus sign tags. But it's helpful to limit the output. I used items(id,selfLink,owners/displayName). Here's how that looks: