如何使用Google Photos API方法:电子表格的Google Apps脚本中的mediaItems.search

以撒战士

我真的想独自解决这个问题...

我正在尝试使用Google Photos API和Google Apps脚本将Google图片中的照片元数据加载到工作表中。

在上一个问题上提供了很多帮助之后,我能够取得一些进步

是否可以将Google照片元数据加载到Google表格中?

我现在有两个功能。

函数photoAPI_ListPhotos()-使用方法:mediaItems.list并给我所有未存档的照片函数photoAPI_ListAlbums()-使用方法:Albums.list并给我所有的相册

我要做的是从特定相册中检索所有照片。方法:mediaItems.search应该执行此操作,但是它使用POST协议,而我发现的先前工作示例仅使用GET。查看该页面上的示例,其中有一个javascript部分,但在应用程序脚本中不起作用。

UrlFetchApp的文档告诉我如何格式化POST请求,但不告诉我如何添加用于身份验证的参数。

外部的API也没有给我,我要找的例子。

我感觉好像丢失了一些必不可少的信息,希望我不要浪费每个人在这里询问的时间。只是一个如何在应用程序脚本中将POST与oauth结合使用的可靠示例,应该可以帮助我了解需要去的地方。

这是我列出所有未存档照片的工作功能。

function photoAPI_ListPhotos() {
  /*
  This function retrieves all photos from your personal google photos account and lists each one with the Filename, Caption, Create time (formatted for Sheet), Width, Height, and URL in a new sheet.
  it will not include archived photos which can be confusing if you happen to have a large chunk of archived photos some pages may return only a next page token with no media items.

  Requires Oauth scopes. Add the below line to appsscript.json
  "oauthScopes": ["https://www.googleapis.com/auth/spreadsheets.currentonly", "https://www.googleapis.com/auth/photoslibrary", "https://www.googleapis.com/auth/photoslibrary.readonly", "https://www.googleapis.com/auth/script.external_request"]

  Also requires a standard GCP project with the appropriate Photo APIs enabled.
  https://developers.google.com/apps-script/guides/cloud-platform-projects
  */

  //Get the spreadsheet object
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  //Check for presence of target sheet, if it does not exist, create one.
  var photos_sh = ss.getSheetByName("photos") || ss.insertSheet("photos", ss.getSheets().length); 
  //Make sure the target sheet is empty
  photos_sh.clear();
  var narray = []; 

  //Build the request string. Max page size is 100. set to max for speed.
  var api = "https://photoslibrary.googleapis.com/v1/mediaItems?pageSize=100";
  var headers = { "Authorization": "Bearer " +  ScriptApp.getOAuthToken() };
  var options = { "headers": headers, "method" : "GET", "muteHttpExceptions": true };

  //This variable is used if you want to resume the scrape at some page other than the start. This is needed if you have more than 40,000 photos.
  //Uncomment the line below and add the next page token for where you want to start in the quotes.
  //var nexttoken="";

  var param= "", nexttoken;
  //Start counting how many pages have been processed.
  var pagecount=0;

  //Make the first row a title row
  var data = [
    "Filename",
    "description",
    "Create Time",
    "Width",
    "Height",
    "ID",
    "URL",
    "NextPage"
  ];
  narray.push(data);

  //Loop through JSON results until a nextPageToken is not returned indicating end of data
  do {
    //If there is a nextpagetoken, add it to the end of the request string
    if (nexttoken)
      param = "&pageToken=" + nexttoken; 

    //Get data and load it into a JSON object
    var response = UrlFetchApp.fetch(api + param, options);
    var json = JSON.parse(response.getContentText());

    //Check if there are mediaItems to process.
    if (typeof json.mediaItems === 'undefined') {
      //If there are no mediaItems, Add a blank line in the sheet with the returned nextpagetoken

      //var data = ["","","","","","","",json.nextPageToken];
      //narray.push(data);
    } else {
      //Loop through the JSON object adding desired data to the spreadsheet.
      json.mediaItems.forEach(function (MediaItem) {

        //Check if the mediaitem has a description (caption) and make that cell blank if it is not present.
        if(typeof MediaItem.description === 'undefined') {
            var description = "";
          } else {
            var description = MediaItem.description;
          }

        //Format the create date as appropriate for spreadsheets.
        var d = new Date(MediaItem.mediaMetadata.creationTime);

        var data = [
          MediaItem.filename,
          "'"+description, //The prepended apostrophe makes captions that are dates or numbers save in the sheet as a string. 
          d,
          MediaItem.mediaMetadata.width,
          MediaItem.mediaMetadata.height,
          MediaItem.id,
          MediaItem.productUrl,
          json.nextPageToken
        ];
        narray.push(data);
      });
    }

    //Get the nextPageToken
    nexttoken = json.nextPageToken;    

    pagecount++;
    //Continue if the nextPageToaken is not null
    //Also stop if you reach 400 pages processed, this prevents the script from timing out. You will need to resume manually using the nexttoken variable above.
  } while (pagecount<4 && nexttoken);

    //Continue if the nextPageToaken is not null (This is commented out as an alternative and can be used if you have a small enough collection it will not time out.)
  //} while (nexttoken);

  //Save all the data to the spreadsheet.
  photos_sh.getRange(1, 1, narray.length, narray[0].length).setValues(narray);
}
Tanaike
  • 您想使用Google Photo API检索特定相册的所有照片。
  • 您想知道如何通过Google Apps脚本使用mediaItems.search的方法。
  • 您已经能够使用Google Photo API检索数据。

如果我的理解是正确的,那么该示例脚本如何?请认为这只是几个答案之一。

示例脚本1:

var albumId = "###"; // Please set the album ID.

var headers = {"Authorization": "Bearer " + ScriptApp.getOAuthToken()};
var url = "https://photoslibrary.googleapis.com/v1/mediaItems:search";
var mediaItems = [];
var pageToken = "";
do {
  var params = {
    method: "post",
    headers: headers,
    contentType: "application/json",
    payload: JSON.stringify({albumId: albumId, pageSize: 100, pageToken: pageToken}),
  }
  var res = UrlFetchApp.fetch(url, params);
  var obj = JSON.parse(res.getContentText());
  Array.prototype.push.apply(mediaItems, obj.mediaItems);
  pageToken = obj.nextPageToken || "";
} while (pageToken);
Logger.log(mediaItems)
  • 在mediaItems.search的方法中albumIdpageSizepageToken包含在有效负载中,并且这些值作为的内容类型发送application/json

示例脚本2:

修改脚本后,以下修改的脚本如何?

function photoAPI_ListPhotos() {
  var albumId = "###"; // Please set the album ID.

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var photos_sh = ss.getSheetByName("photos") || ss.insertSheet("photos", ss.getSheets().length); 
  photos_sh.clear();
  var narray = []; 
  var api = "https://photoslibrary.googleapis.com/v1/mediaItems:search";
  var headers = { "Authorization": "Bearer " +  ScriptApp.getOAuthToken() };
  var nexttoken = "";
  var pagecount = 0;
  var data = ["Filename","description","Create Time","Width","Height","ID","URL","NextPage"];
  narray.push(data);
  do {
    var options = {
      method: "post",
      headers: headers,
      contentType: "application/json",
      payload: JSON.stringify({albumId: albumId, pageSize: 100, pageToken: nexttoken}),
    }
    var response = UrlFetchApp.fetch(api, options);
    var json = JSON.parse(response.getContentText());
    if (typeof json.mediaItems === 'undefined') {
      //If there are no mediaItems, Add a blank line in the sheet with the returned nextpagetoken

      //var data = ["","","","","","","",json.nextPageToken];
      //narray.push(data);
    } else {
      json.mediaItems.forEach(function (MediaItem) {
        if(typeof MediaItem.description === 'undefined') {
            var description = "";
          } else {
            var description = MediaItem.description;
          }
        var d = new Date(MediaItem.mediaMetadata.creationTime);
        var data = [
          MediaItem.filename,
          "'"+description,
          d,
          MediaItem.mediaMetadata.width,
          MediaItem.mediaMetadata.height,
          MediaItem.id,
          MediaItem.productUrl,
          json.nextPageToken
        ];
        narray.push(data);
      });
    }
    nexttoken = json.nextPageToken || "";
    pagecount++;
  } while (pagecount<4 && nexttoken);
  photos_sh.getRange(1, 1, narray.length, narray[0].length).setValues(narray);
}

注意:

  • 该脚本假定如下。
    • 启用了Google Photo API。
    • 的范围https://www.googleapis.com/auth/photoslibrary.readonlyhttps://www.googleapis.com/auth/photoslibrary包含在范围内。

参考:

如果我误解了您的问题,而这不是您想要的结果,我深表歉意。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Google电子表格脚本

如何根据活动电子表格 Google Apps 脚本中的数据创建多个电子表格?

Google Apps脚本,从外部电子表格中检索数据的最快方法

从电子表格中修改另一个电子表格:Google Apps脚本

在Google时区(而不是电子表格时区)中使用Google Apps电子表格脚本的日期

如何使用API在新的Google电子表格中创建第一行?

如何使用Google Spreadsheet API在电子表格文件中插入超链接

使用Google电子表格脚本复制并粘贴

使用 PHP API 在 Google Drive 电子表格中对表格进行排序

如何通过Python中的Google Drive API重命名Google电子表格?

如何在 google 电子表格中为 google api 项目打开访问权限?

使用Google云端硬盘中的Google Spreadsheets API创建电子表格

如何从Google电子表格中删除行?

使用 Google 电子表格中的 ContactsApp

如何在Google Apps脚本中获取发布到网络电子表格的ID

如何在Google Apps脚本中的不同电子表格之间复制条件格式

使用 Google Apps 脚本确认电子表格列中的值

从Google表格电子表格调用python脚本的好方法是什么?

如何使用Google App脚本合并Google电子表格中的多个标签?

如何使用Google Apps脚本引用外部电子表格

如何在Google Apps脚本中使用本机电子表格功能?

如何使用Google Apps脚本向电子表格单元格添加链接

如何使用Google Apps脚本应用电子表格过滤器?

使用Google Sheet API在电子表格中添加(创建)新工作表

使用API向Google电子表格中添加多行

自动更新 Google 电子表格脚本

Google App脚本电子表格

Google 电子表格脚本 - 搜索功能

语法错误:Google 电子表格脚本