google drive file link automatically change format in spreadsheet - google-apps-script

I am implementing some download and upload file functionality in google drive through google app-script storing the drive link in google sheet. upload works fine but after some time the link is turn into some kind of hyperlink as like below
so that's why I am no longer able to get the link simply writting .getDisplayValue()
const ss = SpreadSheetApp.getActive().getActiveSheet() let url = ss.getRange().getDisplayValue()
Any Suggestion ...?
I tried Adding .getRichTextValue().getLinkUrl() But It also does not worked as It is not a HyperLink

Issue and workaround:
From your sample image, in your situation, the link of the file is changed to the smart chip. In the current stage, unfortunately, there are no methods for managing the smart chips on a Spreadsheet. So, in this case, it is required to use a workaround. The workaround is as follows.
Convert Google Spreadsheet to XLSX data.
By this, the file links of the smart chip are converted to simple strings and hyperlinks.
Convert XLSX data to Google Spreadsheet.
Retrieve the hyperlinks from the cells.
This method is from How to get in Apps Script the value of a dropdown in a Google Doc? and https://tanaikech.github.io/2022/10/27/retrieving-values-of-calendar-events-of-smart-chips-on-google-document-using-google-apps-script/ .
When this flow is reflected in a sample script, how about the following sample script?
Sample script:
Please copy and paste the following script to the script editor of Google Spreadsheet and set range that you want to retrieve the hyperlinks as A1Notation. In this sample, Drive API is used. So, please enable Drive API at Advanced Google services.
function myFunction() {
const range = "Sheet1!A1:A10"; // Please set the range you want to retrieve the hyperlinks.
const ss = SpreadsheetApp.getActiveSpreadsheet();
const url = "https://docs.google.com/spreadsheets/export?exportFormat=xlsx&id=" + ss.getId();
const blob = UrlFetchApp.fetch(url, { headers: { authorization: "Bearer " + ScriptApp.getOAuthToken() } }).getBlob();
const tempId = Drive.Files.insert({ mimeType: MimeType.GOOGLE_SHEETS, title: "temp" }, blob).id;
const tempFile = DriveApp.getFileById(tempId);
const tempSS = SpreadsheetApp.open(tempFile);
const res = tempSS.getRange(range).getRichTextValues().map((r, i) => r.map((c, j) => ({ value: c.getText(), url: c.getLinkUrl() || "", range: { row: i + 1, column: j + 1 } })));
tempFile.setTrashed(true);
console.log(res);
}
Testing:
When this script is run, the following result is obtained.
[
[{"value":"sample value","url":"https://drive.google.com/file/d/###/view?usp=share_link","range":{"row":1,"column":1}}],
,
,
,
]
Note:
As another approach, in your showing sample image, if you want to convert the file links of the smart chip to the normal value with the hyperlink, how about the following sample script? In this sample, range is overwritten by the normal values with the hyperlinks obtained by converting from XLSX data.
function myFunction2() {
const range = "Sheet1!A1:A10"; // Please set the range you want to retrieve the hyperlinks.
const ss = SpreadsheetApp.getActiveSpreadsheet();
const url = "https://docs.google.com/spreadsheets/export?exportFormat=xlsx&id=" + ss.getId();
const blob = UrlFetchApp.fetch(url, { headers: { authorization: "Bearer " + ScriptApp.getOAuthToken() } }).getBlob();
const tempId = Drive.Files.insert({ mimeType: MimeType.GOOGLE_SHEETS, title: "temp" }, blob).id;
const tempFile = DriveApp.getFileById(tempId);
const tempSS = SpreadsheetApp.open(tempFile);
const r = tempSS.getRange(range);
const tempSheet = r.getSheet().copyTo(ss);
tempSheet.getRange(r.getA1Notation()).copyTo(ss.getRange(range));
ss.deleteSheet(tempSheet);
tempFile.setTrashed(true);
}
References:
Retrieving Values of Calendar Events of Smart Chips on Google Document using Google Apps Script (Author: me)
Related thread
How to get in Apps Script the value of a dropdown in a Google Doc?

Related

Name Images Exported From GoogleSheets With Specific ID Pulled From Corrisponding Cell

I have a Google Sheet spreadsheet containing personal data I collect from people who subscribe to my association. They have to complete an online form and sign it. The data is then sent to the spreadsheet and the signature is imported as a PNG in-cell-image.
I need to extract all the PNG signatures and assign them the specific ID found in the same row so I can later match the signature with the correct personal data when generating a PDF form with another script.
ID
Signature
1a2b3c4d
image.png
5e6f7g7h
image.png
I am currently using the following code I found online. It saves all the images to a folder as PNG files but it assigns names like "image-1", "image-2" in a random order.
Here is the code:
function myFunction() {
const spreadsheetId = SpreadsheetApp.getActiveSpreadsheet().getId();
const url = "https://docs.google.com/spreadsheets/export?exportFormat=xlsx&id=" + spreadsheetId;
const blob = UrlFetchApp.fetch(url, {headers: {authorization: `Bearer ${ScriptApp.getOAuthToken()}`}}).getBlob().setContentType(MimeType.ZIP);
const xlsx = Utilities.unzip(blob);
xlsx.forEach(b => {
const name = b.getName().match(/xl\/media\/(.+)/);
if (name) DriveApp.getFolderById("1mdJbbG_0aF8wjEIuVPsMr9jV31wPINRk").createFile(b.setName(name[1]));
});
}
How can I edit the code to name each file with the corresponding ID?
Thanks a lot!
EDIT:
I collect data from an online form which is displayed in the image below.
Online Form
When clicking on the signature field, a signature pad opens and allows the user to sign.
Signature Pad
Collected data are then sent to the following spreadsheet stored in Google Drive.
Spreadsheet
The script which sends data from the form to the spreadsheet should be the following
function submit(data) {
data = JSON.parse(data)
const headers = SETTINGS.HEADERS.map(({value}) => value)
const id = Utilities.getUuid()
const signatures = []
const values = SETTINGS.HEADERS.map(({key}, index) => {
if (key === "id") return id
if (key === "timestamp") return new Date()
if (!key in data) return null
if (Array.isArray(data[key])) return data[key].join(",")
if (data[key].startsWith("data:image")) {
signatures.push(index)
return SpreadsheetApp.newCellImage().setSourceUrl(data[key]).build().toBuilder()
}
return data[key]
})
const ws = SpreadsheetApp.getActive().getSheetByName(SETTINGS.SHEET_NAME.RESPONSES) || SpreadsheetApp.getActive().insertSheet(SETTINGS.SHEET_NAME.RESPONSES)
ws.getRange(1,1, 1, headers.length).setValues([headers])
const lastRow = ws.getLastRow()
ws.getRange(lastRow + 1, 1, 1, values.length).setValues([values])
signatures.forEach(index => {
ws.getRange(lastRow + 1, index + 1).setValue(values[index])
})
return JSON.stringify({success: true, message: `Grazie per la tua richiesta di iscrizione! ID: ${id}`})
}
The need is to rename the signature image with the submission ID.
In that way, in theory, when I run Tanaike's script to extract the images from the spreadsheet, they should be named with the ID of the corresponding form submission.
As of now, when I run Tanaike's script I get the following output.
Tanaike's script output
Thanks a lot!
I believe your goal is as follows.
You want to export the images of column "O" in Google Spreadsheet. In this case, you want to use the values of column "B" as the filename.
The image is put into the cells as CellImage.
Modification points:
Using XLSX data converted from Spreadsheet, when the image files are directly retrieved from XLSX data, unfortunately, the images cannot correspond to each cell coordinate. I thought that this is the reason of your issue. In this case, it is required to parse the XLSX data. But, I thought that in this case, the script might be a bit complicated. So, in order to retrieve the image data from the XLSX with the cell coordinate, I have created a Google Apps Script library. Ref
In this answer, I would like to propose a sample script using the library.
Usage:
1. Install Google Apps Script library.
Please install DocsServiceApp Google Apps Script library. You can see how to install it at here.
2. Sample script.
Please copy and paste the following script to the script editor of Spreadsheet. And, please set the variables of folderId and sheetName.
function myFunction() {
const folderId = "###"; // Please set folder ID you want to put the created files.
const sheetName = "Sheet1"; // Please set your sheet name.
// Retrieve image data.
const ss = SpreadsheetApp.getActiveSpreadsheet();
const res = DocsServiceApp.openBySpreadsheetId(ss.getId()).getSheetByName(sheetName).getImages();
// Retrieve IDs from from column "B"
const folder = DriveApp.getFolderById(folderId);
const sheet = ss.getSheetByName(sheetName);
const values = sheet.getRange("B1:B" + sheet.getLastRow()).getValues();
// Create files.
res.forEach(({ range, image }) =>
folder.createFile(image.blob.setName(`${values[range.row - 1][0]}.png` || image.blob.getName()))
);
}
When this script is run, the image data is retrieved and created as the image file using the filename retrieved from column "B".
Note:
In this sample script, from your provided sample image, it supposes that the image data and the filename are put in the columns "O" and "B", respectively. Please be careful about this.
Reference:
DocsServiceApp

Saving a Google Sheet as epub

I have a Google Sheet with content in say Col 1. One sentence in each row. I am looking for a script which can save the Col 1 as 'epub' with each sentence (in row) as a new page.
I believe your current situation and your goal as follows.
In your Spreadsheet, there are the sentences in each row of the column "A".
You want to retrieve a value from a cell of column "A" and convert it as a file of EPUB on your Google Drive.
You want to achieve this using Google Apps Script.
In this case, I would like to propose the following flow.
Retrieve the values from the column "A" of the Spreadsheet.
Create Google Document as the temporal file.
Copy the values to Google Document.
Export Google Document as EPUB of application/epub+zip and save it as a file on Google Drive.
Remove the temporal file.
When above flow is reflected to the script, it becomes as follows.
Sample script:
Please copy and paste the following script to the script editor of Google Spreadsheet you want to use. And, please run myFunction. By this, the values are retrieved from the cells "A1:A" and create EPUB files using the values of each row.
function myFunction() {
const sheetName = "Sheet1"; // Please set the sheet name.
const folderId = "root"; // Please set the folder ID you want to export the EPUB files. In the case of "root", the files are created to the root folder.
// 1. Retrieve the values from the column "A" of the Spreadsheet.
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
const startRow = 1;
const endRow = sheet.getLastRow();
const values = sheet.getRange(`A${startRow}:A${endRow}`).getDisplayValues();
// 2. Create Google Document as the temporal file.
const tempDoc = DocumentApp.create("temp");
const id = tempDoc.getId();
const url = "https://docs.google.com/feeds/download/documents/export/Export?exportFormat=epub&id=" + id;
const params = {headers: {authorization: `Bearer ${ScriptApp.getOAuthToken()}`}};
const folder = DriveApp.getFolderById(folderId || "root");
const ids = values.map(([a], i) => {
// 3. Copy the values to Google Document.
const filename = `rowNumber${i + 1}`;
const doc = DocumentApp.openById(id).setName(filename);
doc.getBody().clear().appendParagraph(a);
doc.saveAndClose();
// 4. Export Google Document as EPUB of `application/epub+zip` and save it as a file on Google Drive.
const blob = UrlFetchApp.fetch(url, params).getBlob().setName(`${filename}.epub`);
return folder.createFile(blob).getId();
});
console.log(ids); // Here, you can see the file IDs of the created EPUB files at the log.
// 5. Remove the temporal file.
DriveApp.getFileById(id).setTrashed(true);
}
In this sample script, the filename is rowNumber${i + 1}. So, the created filename is like rowNumber1.epub, rowNumber2.epub. If you want to change this, please modify above script.
The endpoint of const url = "https://docs.google.com/feeds/download/documents/export/Export?exportFormat=epub&id=" + id; is from exportLinks of the method of "Files: get" of Drive API. Ref
Note:
In this case, when a lot of rows are existing in your Spreadsheet, the process time might be over the maximum execution time of 6 minutes. Please be careful this. If the process time is over the maximum execution time, please modify the values of startRow and endRow.
If an error related to Drive API occurs, please enable Drive API at Advanced Google servicves.
If you want to convert the values of the column "A" as one EPUB file, you can also use the following script.
function myFunction2() {
const sheetName = "Sheet1";
const folderId = "root"; // Please set the folder ID you want to export the EPUB files. In the case of "root", the files are created to the root folder.
const filename = `sampleFile`; // Please set the output filename.
// 1. Retrieve the values from the column "A" of the Spreadsheet.
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
const startRow = 1;
const endRow = sheet.getLastRow();
const values = sheet.getRange(`A${startRow}:A${endRow}`).getDisplayValues();
// 2. Create Google Document as the temporal file.
const tempDoc = DocumentApp.create(filename);
// 3. Copy the values to Google Document.
tempDoc.getBody().clear().appendParagraph(values.flat().join("\n"));
tempDoc.saveAndClose();
const id = tempDoc.getId();
// 4. Export Google Document as EPUB of `application/epub+zip` and save it as a file on Google Drive.
const url = "https://docs.google.com/feeds/download/documents/export/Export?exportFormat=epub&id=" + id;
const params = {headers: {authorization: `Bearer ${ScriptApp.getOAuthToken()}`}};
const folder = DriveApp.getFolderById(folderId || "root");
const blob = UrlFetchApp.fetch(url, params).getBlob().setName(`${filename}.epub`);
const createdFileId = folder.createFile(blob).getId();
console.log(createdFileId); // Here, you can see the file ID of the created EPUB file at the log.
// 5. Remove the temporal file.
DriveApp.getFileById(id).setTrashed(true);
}
References:
Spreadsheet Service
Class UrlFetchApp
Drive Service
You need to enable Advanced Drive API
function makeEPUB() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Sheet1');
const rg = sh.getRange(1,1,sh.getLastRow(),1);
const vs = rg.getDisplayValues().flat();//get rows
const document = DocumentApp.create('mydoc');//creat doc
let body = document.getBody();
vs.forEach(s =>{body.appendParagraph(s);body.appendPageBreak();});//append sentences and page breaks
document.saveAndClose();
let exportLink = Drive.Files.get(document.getId()).exportLinks["application/epub+zip"];
let response = UrlFetchApp.fetch(exportLink, {headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()}});
let file = DriveApp.createFile(response.getBlob());
file.setName(document.getName() + ".epub");
}
Mostly Copied from Amit Agarwal
Don't know if it works. Have no way that I know of to test it.

How to get the excel data from a url into google sheets using google apps script?

Follow up question to this question - How to fix invalid url error using UrlfetchApp?
This is the url to download the excel data from :
https://corvo-reports.s3.amazonaws.com/TRESAH/2020-08-16/45d32ff8-bccd-4c16-8916-6c19c28f2f3c%402020-08-16%2017%3A30%3A00.0/Sponsored%20Products%20Search%20term%20report%20-%20Scotch%20Brite.xlsx?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20200816T174421Z&X-Amz-SignedHeaders=host&X-Amz-Expires=604799&X-Amz-Credential=AKIAY2R3XYZC46Q4PK5E%2F20200816%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Signature=726ca9b98cd766966b756bc708b780377ff62e5bbfec8c09b97294bfb0cd63f7
This is a report that comes in on a schedule and I need to take this data and put it in a google sheet. It's a large report so I need to clear all existing data on the sheet and replace it with the new data. I've been struggling with this and could use some help.
This is the code I have right now:
// Globals
const DataFolderId = 'XXXXX'
const label = 'YYYYY'
/*
* Download the excel file and put it in a google sheet
*
* #return : Hopefully, it adds the data to the google sheet
*/
function excelToSheets() {
// Get the link to the excel file
const url = getDownloadLink(label)
const excelFile = UrlFetchApp.fetch(url).getBlob()
const filename = 'Report: ' + Utilities.formatDate(new Date(), "IST", "yyyy-MM-dd")
// Download the file to google drive
const fileInfo = {
title: filename,
mimeType: "MICROSOFT_EXCEL",
"parents": [{'id': DataFolderId}],
}
// Currently, this adds a zip file to google drive, instead of an excel/google sheet file
const file = Drive.Files.insert(fileInfo, excelFile, {convert: true})
// Assign the id of the downloaded file to a variable
const id = file.id
// Put data in a spreadsheet - this does not work
spreadsheet(id)
}
/*
* Helper function to put data in the google sheet
*/
function spreadsheet (id) {
const source = SpreadsheetApp.openById(id)
const destination = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('data')
destination.clearContents()
source.copyTo(destination)
}
/*
* Get the download link from the gmail label
*
* #return : The link from the most recent email
*/
function getDownloadLink (label) {
const lookupLabel = GmailApp.getUserLabelByName(label)
const thread = lookupLabel.getThreads()[0]
const message = thread.getMessages()[0]
const data = message.getPlainBody()
const regExp = new RegExp('[\n\r].*Download:\\s*([^\n\r]*)')
const link = regExp.exec(data)[1].trim()
return link
}
Currently, the excelToSheets() function takes the excel file from the link and adds a zip file in google drive. I'm not sure what I'm doing wrong here - I've just been trying to follow a bunch of tutorials on the topic online.
Your help would be greatly appreciated!
When you fetch a blob from a download link it might not contain the correct mimeType information
Workaround
Perform the request in two steps
step save the file as Excel on your Drive
Convert the Excel file to Google Sheets
Sample
function excelToSheets() {
const url = getDownloadLink(label);
const excelFile = UrlFetchApp.fetch(url).getBlob();
const filename = 'Report: ' + Utilities.formatDate(new Date(), "IST", "yyyy-MM-dd")
const fileInfo = {
title: filename,
mimeType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
parents: [{id: DataFolderId}],
}
const file = Drive.Files.insert(fileInfo, excelFile)
const id = file.id;
const excelFile2 = DriveApp.getFileById(id).getBlob();
const fileInfo2 = {
title: filename,
mimeType: MimeType.GOOGLE_SHEETS,
parents: [{id: DataFolderId}],
}
const file2 = Drive.Files.insert(fileInfo2, excelFile2);
const id2 = file2.id;
spreadsheet(id2)
}

Import CSV data into Google Sheets

When trying to use the IMPORTDATA function for this file:
https://www.kaggle.com/stefanoleone992/fifa-20-complete-player-dataset#players_20.csv
An unexpected error occurs that says it is impossible to import data into the spreadsheet. Is there any other way that I can bring this data to my spreadsheet?
This data would be very important to the work I'm doing. It would save me from almost 3 months of work to be able to type and copy everything and then filtering according to my need.
It would be very important to be able to import at least the simple info of all players, but do not necessarily have to import all columns of info from each player. The amount of columns can import is already perfect.
I would be grateful if there was any way.
You want to download a CSV file of players_20.csv from https://www.kaggle.com/stefanoleone992/fifa-20-complete-player-dataset and put the CSV data to the Spreadsheet.
You want to achieve this using Google Apps Script.
If my understanding is correct, how about this answer? Please think of this as just one of several answers.
Issue and workaround:
Unfortunately, the CSV data cannot be directly downloaded from the URL of https://www.kaggle.com/stefanoleone992/fifa-20-complete-player-dataset#players_20.csv. In order to download the CSV file, it is required to login to kaggle. As other pattern, you can also download it using API. In this answer, in order to download the CSV file, I used Kaggle's public API.
Usage:
1. Retrieve token file:
Before you use the script, please register an account to https://www.kaggle.com, and retrieve the token file. About how to retrieve the token file, you can see the official document.
In order to use the Kaggle’s public API, you must first authenticate using an API token. From the site header, click on your user profile picture, then on “My Account” from the dropdown menu. This will take you to your account settings at https://www.kaggle.com/account. Scroll down to the section of the page labelled API:
To create a new token, click on the “Create New API Token” button. This will download a fresh authentication token onto your machine.
In this script, the token object in the downloaded token file is used.
2. Run script:
Please copy and paste the following script to the container-bound script of Spreadsheet. And please set the variavles of csvFilename, path and tokenObject. In your case, I have already set csvFilename and path. So please set only your token object.
function myFunction() {
var csvFilename = "players_20.csv"; // Please set the CSV filename.
var path = "stefanoleone992/fifa-20-complete-player-dataset"; // Please set the path.
var tokenObject = {"username":"###","key":"###"}; // <--- Please set the token object.
var baseUrl = "https://www.kaggle.com/api/v1/datasets/download/";
var url = baseUrl + path;
var params = {headers: {Authorization: "Basic " + Utilities.base64Encode(tokenObject.username + ':' + tokenObject.key)}};
var blob = UrlFetchApp.fetch(url, params).getBlob();
var csvBlob = Utilities.unzip(blob).filter(function(b) {return b.getName() == csvFilename});
if (csvBlob.length == 1) {
var csvData = Utilities.parseCsv(csvBlob[0].getDataAsString());
var sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);
} else {
throw new Error("CSV file of " + csvFilename + " was not found.");
}
}
Flow:
The flow of this script is as follows.
When the script is run, the kaggle command of kaggle datasets download -d stefanoleone992/fifa-20-complete-player-dataset is run with Google Apps Script. By this, the ZIP file is downloaded.
Retrieve the CSV file of csvFilename from the downloaded ZIP file.
Parse the CSV data from the CSV file.
Put the CSV data to the active sheet.
In this script, all data is processed with the blob. So the file is not created.
Note:
It seems that the CSV data is large. So please wait until the script is finished.
In my environment, I spent for about 150 seconds until the CSV data is put to the Spreadsheet.
The CSV data of players_20.csv has 18279 rows and 104 columns.
If an error occurs at Utilities.unzip(blob), please test to modify from var blob = UrlFetchApp.fetch(url, params).getBlob() to var blob = UrlFetchApp.fetch(url, params).getBlob().setContentTypeFromExtension().
References:
Authentication of Kaggle's public API
kaggle-api
If I misunderstood your question and this was not the direction you want, I apologize.
Added 1:
If you want to select the columns you want to put, please modify above sample script as follows.
From:
var csvData = Utilities.parseCsv(csvBlob[0].getDataAsString());
var sheet = SpreadsheetApp.getActiveSheet();
To:
var csvData = Utilities.parseCsv(csvBlob[0].getDataAsString());
var needColumns = [1, 2, 3];
csvData = csvData.map(function(row) {return needColumns.map(function(col) {return row[col]})});
var sheet = SpreadsheetApp.getActiveSheet();
In above modification, as the test case, the columns of 1, 2 and 3 are put to the Spreadsheet.
Added 2:
From the result of benchmark for putting CSV data to Spreadsheet, for example, how about using Sheets API for putting CSV data? For this, please modify above sample script as follows. Before you run the script, please enable Sheets API at Advanced Google services.
From:
var csvData = Utilities.parseCsv(csvBlob[0].getDataAsString());
var sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange(1, 1, csvData.length, csvData[0].length).setValues(csvData);
To:
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var resource = {requests: [{pasteData: {data: csvBlob[0].getDataAsString(), coordinate: {sheetId: sheet.getSheetId()}, delimiter: ","}}]};
Sheets.Spreadsheets.batchUpdate(resource, ss.getId());
In this case, I spent for about 50 seconds until the CSV data is put to the Spreadsheet.
Reference:
Benchmark: Importing CSV Data to Spreadsheet using Google Apps Script
Advanced Google services

How to get file (video) duration of google drive file programmatically?

Either using rest API, Google Scripts, Node SDK, whatever works.
I'm seeing this in the docs but that doesn't seem to tell me the duration:
function watchFile(fileId, channelId, channelType, channelAddress) {
var resource = {
'id': channelId,
'type': channelType,
'address': channelAddress
};
var request = gapi.client.drive.files.watch({
'fileId': fileId,
'resource': resource
});
request.execute(function(channel){console.log(channel);});
}
I found this link but it doesn't seem to help https://apis-nodejs.firebaseapp.com/drive/classes/Resource$Files.html#watch
You want to retrieve the duration of the video on your Google Drive.
You want to achieve this using Google Apps Script.
If my understanding is correct, how about this sample script? In this modification, I used files.get and files.list methods of Drive API. From your question, I thought that the script that the endpoint is directly requests might be useful for your situation. So I proposed the following script.
1. Using files.get method
In this sample script, the duration is retrieved from a video file.
Sample script:
function sample1() {
var fileId = "###"; // Please set the file ID of the video file.
var fields = "mimeType,name,videoMediaMetadata"; // duration is included in "videoMediaMetadata"
var url = "https://www.googleapis.com/drive/v3/files/" + fileId + "?fields=" + encodeURIComponent(fields) + "&access_token=" + ScriptApp.getOAuthToken();
var res = UrlFetchApp.fetch(url);
var obj = JSON.parse(res);
Logger.log("filename: %s, duration: %s seconds", obj.name, obj.videoMediaMetadata.durationMillis / 1000);
// DriveApp.getFiles() // This line is put for automatically detecting the scope (https://www.googleapis.com/auth/drive.readonly) for this script.
}
2. Using files.list method
In this sample script, the durations are retrieved from a folder including the video files.
Sample script:
function sample2() {
var folderId = "###"; // Please set the folder ID including the video files.
var q = "'" + folderId + "' in parents and trashed=false";
var fields = "files(mimeType,name,videoMediaMetadata)"; // duration is included in "videoMediaMetadata"
var url = "https://www.googleapis.com/drive/v3/files?q=" + encodeURIComponent(q) + "&fields=" + encodeURIComponent(fields) + "&access_token=" + ScriptApp.getOAuthToken();
var res = UrlFetchApp.fetch(url);
var obj = JSON.parse(res);
for (var i = 0; i < obj.files.length; i++) {
Logger.log("filename: %s, duration: %s seconds", obj.files[i].name, obj.files[i].videoMediaMetadata.durationMillis / 1000);
}
// DriveApp.getFiles() // This line is put for automatically detecting the scope (https://www.googleapis.com/auth/drive.readonly) for this script.
}
Note:
These are simple sample scripts. So please modify them for your situation.
I'm not sure about the format of your video files. So if above script cannot be used for your situation, I apologize.
References:
Files of Drive API
Class UrlFetchApp
If I misunderstood your question and this was not the result you want, I apologize.
Updated: March 19, 2020
From January, 2020, the access token cannot be used with the query parameter like access_token=###. Ref So please use the access token to the request header instead of the query parameter. It's as follows.
var res = UrlFetchApp.fetch(url, {headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()}});