Gists
Abstract A script using resumable upload with file streams is proposed to enhance file handling within the Gemini Generative AI API for Node.js. This script allows uploading from web URLs and local storage, efficiently handles large files, and offers potential reusability with other Google APIs.
Description The @google/generative-ai library provides a powerful way to interact with the Gemini Generative AI API using Node.js. This enables developers to programmatically generate creative text formats, translate languages, write different kinds of creative content, and answer your questions in an informative way, all powered by Gemini’s advanced AI models.
Gists
Abstract This report provides a Google Apps Script to retrieve all files, including those within subfolders, for a designated folder. It addresses the challenges of retrieving files within deeply nested folder structures and obtaining complete file paths.
Introduction Google Apps Script empowers developers to interact with Google Drive data programmatically, unlocking a wide range of functionalities. A core component of this interaction is the Drive service (DriveApp) and Drive API.
Gists
Abstract This script automates moving a folder including files and folders between Google Drives (personal or shared) by recreating the folder structure and transferring files, overcoming limitations for shared drives.
Introduction This report addresses a common challenge: efficiently moving folders, including their subfolders and files, between Google Drives, encompassing both personal and shared drives using a script. While Google Drive offers straightforward methods for moving individual files between any drives, directly moving entire folders containing subfolders presents limitations, particularly when shared drives are involved.
Gists
This is a sample script for comparing the file contents of files on Google Drive using Google Apps Script.
Sample script Before you use this script, please enable Drive API at Advanced Google services. And also, please set the file IDs you want to check whether the file contents of the files are the same.
function checkFiles_(f, checks = ["md5Checksum", "sha1Checksum", "sha256Checksum"]) { files = f.map(id => DriveApp.getFileById(id)); const fields = [.
Gists
This is a sample script for achieving the resumable download of a file from Google Drive using Dive API with Python.
There might be a case in that you want to achieve the resumable download of a file from Google Drive using Dive API with Python. For example, when a large file is downloaded, the downloading might be stopped in the middle of downloading. At that time, you might want to resume the download.
Gists
This is a sample script for retrieving the total file sizes in the specific folder of Google Drive using Google Apps Script.
There is a case where you want to retrieve the total file sizes in the specific folder of Google Drive using Google Apps Script. In this post, I would like to introduce a sample script for achieving this.
Sample script Before you use this script, please enable Drive API at Advanced Google services.
Gists
This is a sample script for transferring the ownership of a file to another user using Google Apps Script.
In the current stage, about the consumer account (gmail.com) the specification for transferring the ownership of a file has been changed as follows. Ref
The current owner initiates an ownership transfer by creating or updating the prospective new owner’s file permission. The permission must include these settings: role=writer, type=user, and pendingOwner=true.
Gists
Unfortunately, in the current stage, in order to retrieve the file list using the created date, the search query of createdDate cannot be used with searchFiles method of DriveApp in Google Apps Script. This has already been reported at this issue tracker In this post, I would like to introduce a workaround for searching the files using the created date.
Issue and workaround The parameter of “searchFiles” method of DriveApp uses the search query for Drive API v2.
Gists
This is a sample script for the resumable upload using Axios with Node.js.
Sample script In this sample script, as a sample situation in order to explain the resumable upload, the file data is loaded from the local PC, and the data is uploaded to Google Drive with the resumable upload.
const axios = require("axios"); const fs = require("fs").promises; async function sample() { const filepath = "./###"; // Please set the filename and file path of the upload file.
Gists
This is a sample script for uploading files to Google Drive with asynchronous process using Python.
Sample script import aiohttp import asyncio import json folder_id = "###" # Please set the folder ID you want to put. token = "###" # Please set your access token. url = "https://www.googleapis.com/upload/drive/v3/files" async def workers(file): async with aiohttp.ClientSession() as session: metadata = {"name": file["filename"], "parents": [folder_id]} data = aiohttp.
Gists
In this report, I would like to report about the current specification of the search query for the file list method in Drive API.
Recently, I noticed that the specification of the search query for the file list method in Drive API might have been changed. I thought that to know the change of specification of the search query is important for creating the application using Drive API. In this report, I would like to introduce the current specification of the search query.
Gists
This is a simple sample script for achieving the resumable upload to Google Drive using Axios. In order to achieve the resumable upload, at first, it is required to retrieve the location, which is the endpoint of upload. The location is included in the response headers. After the location was retrieved, the file can be uploaded to the location URL.
In this sample, a text data is uploaded with the resumable upload using a single chunk.
Gists
This is a sample script of Node.js for downloading the data and uploading the data to Google Drive with the resumable upload without saving it as a file. The downloaded data is uploaded to Google Drive with the stream.
Sample script Before you use this, please set the variables of accessToken, url, fileSize, mimeType and filename. In this case, fileSize is required to set because the data is uploaded with the resumable upload.
Overview This is a Google Apps Script library for creating, updating and exporting Google Apps Script project of the standalone type using Drive API. In this case, Apps Script API is not used.
Description I had reported “Drive API cannot create Google Apps Script project no longer” before. Ref About this, I had reported the future request. Ref At July 30, 2020, I could confirm that the Google Apps Script project of the standalone type got to be able to be created by multipart/form-data using Drive API again.
Gists
I have reported “Drive API cannot create Google Apps Script project no longer”. Ref About this, I had reported the future request. Ref Today, I could confirm that the Google Apps Script project of the standalone type got to be able to be created by multipart/form-data using Drive API. This is a good news for me. By this, the following 2 patterns can be used from now.
Pattern 1: Create new standalone GAS project by Apps Script API.
Gists
These are the sample scripts for uploading files of multipart/form-data to Google Drive using Drive API with Node.js. In this case, googleapis for Node.js is not used.
In these sample script, the maximum file size is 5 MB. Please be careful this. When you want to upload the files more than 5 MB, please check this report.
Sample script 1 This sample script uploads a file using the modules of fs and request.
Overview This is a Google Apps Script library for achieving the ownership-transfer of the specific folder including the files and sub-folders using Drive API.
IMPORTANT: PLEASE BE CAREFUL THIS. At first, please read this section I cannot take responsibility for the problems occurred by this library. So when you use this library, please use it by according to your own decision and at your own responsibility. This GAS library transfers the ownership of files and folders.
I noticed that the specification of Files: copy in Drive API was changed. About the method of Files: copy in Drive API v3, this method could be used with the scope of https://www.googleapis.com/auth/drive.readonly until July 5, 2020. But I confirmed that in the current stage, the scope is required to be changed to the following scopes.
https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/drive.appdata https://www.googleapis.com/auth/drive.photos.readonly Please be careful this.
Gists
In this report, I would like to report for processing to create new file to the specific folder using Drive API. When the new file is created to the specific folder using Drive API, the property of parents with the value of folder ID is included in the request body of the method “Files: create”. About this process, I had thought that the file is directly created to the specific folder.
Overview These are the sample scripts of the batch requests for Drive API using Google Apps Script.
Description When we want to manage the files and folders on Google Drive, we have 2 ways. One is the use of Drive service. Another is the use of Drive API. In the case of them, when we want to manage a lot of files and folders, unfortunately, both ways have no batch requests.
Gists
This is a sample script for creating a shortcut on Google Drive using Google Apps Script.
Sample script Before you run the script, please enable Drive API at Advanced Google services.
function createShortcut(targetId, name, folderId) { const resource = { shortcutDetails: { targetId: targetId }, title: name, mimeType: "application/vnd.google-apps.shortcut", }; if (folderId) resource.parents = [{ id: folderId }]; const shortcut = Drive.Files.insert(resource); return shortcut.
Overview This is Google Apps Script library for copying folder on Google Drive.
Description I have sometimes the situation that it is required to back up the folder on Google Drive to Google Drive. But unfortunately, the method of makeCopy() of Class File and the method of Files: copy of Drive API cannot be used for directly copying the folder on Google Drive. So I created this as a library. This library can copy the folder on Google Drive.
Gists
This is a sample flow for updating a file with the resumable upload using Drive API.
Sample situation: In this answer, as a sample situation, it supposes that a text file in Google Drive is updated by the resumable upload with the multiple chunks. And as the method for requesting, I use the curl command.
I prepared 2 files for 2 chunks. As the test situation, the 2 chunks of 262,144 bytes and 37,856 bytes are uploaded.
Gists
This is a sample script for retrieving the files and folders which have no parents in own Google Drive.
When you use this script, please enable Drive API at Advanced Google services.
Sample script const myFunction = () => { const token = ScriptApp.getOAuthToken(); const fields = decodeURIComponent( "nextPageToken,files(name,id,mimeType,parents)" ); const q = decodeURIComponent("'me' in owners and trashed = false"); let files = []; let pageToken = ""; do { const res = UrlFetchApp.
Gists
Today, I noticed that new Google Apps Script project of the standalone script type cannot be created by the method of Files: create in Drive API. From now, in order to manage the Google Apps Script project, only Google Apps Script API is required to be used. By this, the following issues are brought.
When the new standalone GAS project is created in the specific folder by uploading the local script, the following flow is required to be run.
Gists
This is a simple sample script for achieving the resumable upload to Google Drive using Python. In order to achieve the resumable upload, at first, it is required to retrieve the location, which is the endpoint of upload. The location is included in the response headers. After the location was retrieved, the file can be uploaded to the location URL.
In this sample, a PNG file is uploaded with the resumable upload using a single chunk.
Gists
This is a simple sample script for achieving the resumable upload to Google Drive using Node.js. In order to achieve the resumable upload, at first, it is required to retrieve the location, which is the endpoint of upload. The location is included in the response headers. After the location was retrieved, the file can be uploaded to the location URL.
In this sample, a PNG file is uploaded with the resumable upload using a single chunk.
Gists
Overview This is a sample script for the music streaming player for Discord with Google Drive using Node.js.
Description This sample script can achieve to play the music when uses the voice channel on Discord. The music files are put in the specific folder of Google Drive. This script downloads all music files and plays the music files at the voice channel with the stream.
Usage 1. Register BOT to Discord At first, please register your BOT to Discord.
Gists
This is a sample script for modifying the revisions of a file on Google Drive using Google Apps Script. This script can be used for not only Google Docs files, but also the files except for Google Docs.
Issue and workaround: Unfortunately, in the current stage, at Google Docs files, the revision of Google Docs cannot be directly changed by APIs with a script. So as one of several workarounds, I would like to propose to overwrite the Google Docs file using the exported data.
Gists
There are 2 sample scripts.
Create new Spreadsheet using a text value as CSV data. Overwrite the existing Google Document using a text value. When you use these script, please enable Drive API and retrieve your access token.
Create New Spreadsheet using Text Value const request = require('request'); const textData = "a1, b1, c1, d1, e1"; // This is used as CSV data. const orgMimeType = "text/csv"; const orgFileName = "sample.
Gists
News At October 11, 2019, I published a Javascript library to to run the resumable upload for Google Drive. When this is used, the large file can be uploaded. You can also use this js library.
Description This is a sample script for uploading files to Google Drive using Javascript. The files are uploaded by Drive API v3. gapi.client.drive.files.create() can create an empty file on Google Drive. But it cannot directly upload files including contents.
Gists
This is a sample script for retrieving a folder tree using Node.js. In this sample, you can set the top of folder for the folder tree. In generally, the folder tree is created by retrieving folders from the top folder in order. For example, when Google Apps Script is used, the script becomes like this. But when Drive API is used for this situation, if there are a lot of folders in the top folder, a lot of APIs are required to be called.
Gists
This is a sample script for uploading files from local PC to Google Drive using Python. In this sample, Quickstart is not used. So when you use this script, please retrieve access token.
Curl sample : curl -X POST \ -H "Authorization: Bearer ### access token ###" \ -F "metadata={name : 'sample.png', parents: ['### folder ID ###']};type=application/json;charset=UTF-8" \ -F "file=@sample.png;type=image/png" \ "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart" ]
Python sample : When above curl sample is converted to Python, it becomes as follows.
Gists
This sample script is for updating thumbnail of file on Google Drive using Python.
This sample supposes that quickstart is used and default quickstart works fine. In order to use this sample, please carry out as follows.
Replace main() of the default quickstart to this sample. Script : import base64 # This is used for this sample. def main(): credentials = get_credentials() http = credentials.
Gists
This sample script is for downloading files under a specific folder using Node.js. It can download files with Google Docs and others.
This sample supposes as follows. So please confirm it.
quickstart is used and default quickstart works fine. In order to use this sample, please carry out as follows.
Replace listFiles() of the default quickstart to this sample. Set folderid. This script can retrieve files in the folder with folderid.
This sample script converts from Microsoft Docx File on Google Drive to Google Spreadsheet, and converts to HTML file.
Drive APIs v2 and v3 are used for this. Please set as follows.
Drive API v2 Drive API v3 “Drive API v2” can be used at Google Apps Script by enabling Drive API of Advanced Google services and of Google API Console.
How to use it is as follows.
This is a sample script for OCR using Google Drive API. A text file which converted by OCR can be retrieved by inputting an image file.
In this sample, Python Quickstart is used. The detail information is https://developers.google.com/drive/v3/web/quickstart/python. Please read “Step 1: Turn on the Drive API” and “Step 2: Install the Google Client Library”.
from __future__ import print_function import httplib2 import os import io from apiclient import discovery from oauth2client import client from oauth2client import tools from oauth2client.
This is a sample script for converting a PDF file to a TXT file. 2 steps are required for this.
Upload a PDF file as a Google Document Download a Google Document as a TXT file In this sample, Python Quickstart is used. The detail information is https://developers.google.com/drive/v3/web/quickstart/python. Please read “Step 1: Turn on the Drive API” and “Step 2: Install the Google Client Library”.
from __future__ import print_function import httplib2 import os import io from apiclient import discovery from oauth2client import client from oauth2client import tools from oauth2client.
These scripts can be executed on Script Editor. But, in order to use these, you have to enable Drive API of Advanced Google services and of Google API Console. “Drive API v2” can be used at Google Apps Script by enabling Drive API of Advanced Google services and of Google API Console.
How to use it is as follows.
In the script editor, select Resources > Advanced Google services
This is a sample GAS script to create an Excel file, which was downloaded from web, as Spreadsheet. By using Drive API, it can be achieved without access token.
Script :
function downloadFile(fileURL, folder) { var filename = fileURL.match(".+/(.+?)([\?#;].*)?$")[1]; var response = UrlFetchApp.fetch(fileURL); var rc = response.getResponseCode(); var blob = response.getBlob(); var resource = { "mimeType": "application/vnd.google-apps.spreadsheet", "parents": [{id: folder}], "title": filename }; var res = Drive.
There are a lot of APIs on Google. When we use Google Drive APIs, they usually have “fields” as a resource. The parameter “fields” gives various information which is selected to us. This is one of important parameters. And this can be used at Google Apps Script (GAS) although that version is v2. About how to use it, there are some documents. But it is difficult to find how to use it at GAS.
These GASs retrieve an access token for using Google Drive API. There are 3 parts. Before you use this, please retrieve client ID, client secret and redirect uri from Google , and choose scopes.
1. Retrieving code from web This is a script to output URL for retrieving “code” from web. Please retrieve “code” by import this URL to your browser. After you run this script, using “url” got from this script, it retrieves “code”.
It is necessary to retrieve access token on Google. Scope is as follows.
https://www.googleapis.com/auth/drive Other mimetypes can be seen here.
Download and convert from Spreadsheet to Excel curl -X GET -sSL \ -H "Authorization: Bearer [Your access token]" \ -o "Excel file name" \ "https://www.googleapis.com/drive/v3/files/[File ID]/export?mimeType=application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" Upload and convert from Excel to Spreadsheet curl -X POST -sSL \ -H "Authorization: Bearer [Your access token]" \ -F "metadata={ \ name : '[File name on Google Drive]', \ mimeType : 'application/vnd.