0Auth2 проблема, чтобы получить мои библиотеки фотографий Google в моем листе Google - PullRequest
0 голосов
/ 06 января 2019

Я пытаюсь следовать документации, но никогда не получаю 0Auth2 для подключения. Кстати, я запускаю сценарий вручную со страницы сценариев листов Google, где я должен получить запрос на разрешение доступа? (Я не понимаю всю эту схему 0Auth2, и я уже дал разрешение на запуск сценария и получил идентификатор клиента и секрет) ... Смотрите ниже мои процедуры лога и скрипта (первый шаг к фотографии все еще минималистичен, так как я еще не прошел через шаг 0Auth2 ;-). Заранее спасибо за любой намек. Я думал, что это будет тривиально, так как это мой собственный лист и учетная запись Google Photo ...

Вход:

[19-01-06 17:50:05:809 CET] starting
[19-01-06 17:50:05:810 CET] getPhotoService
[19-01-06 17:50:05:849 CET] false
[19-01-06 17:50:05:850 CET] redirectURI=https://script.google.com/macros/d/[REMOVED]/usercallback
[19-01-06 17:50:05:864 CET] Open the following URL and re-run the script: https://accounts.google.com/o/oauth2/auth?client_id=[removed].apps.googleusercontent.com&response_type=code&redirect_uri=https%3A%2F%2Fscript.google.com%2Fmacros%2Fd%2F[removed]%2Fusercallback&state=[removed]&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fphotoslibrary.readonly&login_hint=[removed]&access_type=offline&approval_prompt=force

Сценарий:

function getPhotoService() {
  // Create a new service with the given name. The name will be used when
  // persisting the authorized token, so ensure it is unique within the
  // scope of the property store.
  Logger.log('getPhotoService');
  return OAuth2.createService('gPHOTOfj')

  // enable caching on the service, so as to not exhaust script's PropertiesService quotas
  .setPropertyStore(PropertiesService.getUserProperties())
  .setCache(CacheService.getUserCache())

  // Set the endpoint URLs, which are the same for all Google services.
  .setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
  .setTokenUrl('https://accounts.google.com/o/oauth2/token')

  // Set the client ID and secret, from the Google Developers Console.
  .setClientId(CLIENT_ID)
  .setClientSecret(CLIENT_SECRET)

  // Set the name of the callback function in the script referenced
  // above that should be invoked to complete the OAuth flow.
  .setCallbackFunction('authCallback')
  //.setCallbackFunction('https://script.google.com/macros/d/'+SCRIPT_ID+'/authCallback')

  // Set the property store where authorized tokens should be persisted.
  .setPropertyStore(PropertiesService.getUserProperties())

  // Set the scopes to request (space-separated for Google services).
  .setScope('https://www.googleapis.com/auth/photoslibrary.readonly')

  // Below are Google-specific OAuth2 parameters.

  // Sets the login hint, which will prevent the account chooser screen
  // from being shown to users logged in with multiple accounts.
  .setParam('login_hint', Session.getActiveUser().getEmail())

  // Requests offline access.
  .setParam('access_type', 'offline')

  // Forces the approval prompt every time. This is useful for testing,
  // but not desirable in a production application.
  .setParam('approval_prompt', 'force');
}

function authCallback(request) {
  Logger.log('Called back!');
  var photoService = getPhotoService();
  var isAuthorized = photoService.handleCallback(request);
  if (isAuthorized) {
    Logger.log('Authorisation Success!');
  } else {
    Logger.log('Authorisation Denied...!');
  }
}

// Modified from http://ctrlq.org/code/20068-blogger-api-with-google-apps-script
function photoAPI() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var albums_sh = ss.getSheetByName("albums") || ss.insertSheet("albums", ss.getSheets().length); 
  albums_sh.clear(); var nrow = new Array(); var narray = new Array(); 
  Logger.log("starting");  

  var service = getPhotoService();
  Logger.log(service.hasAccess());
  Logger.log('redirectURI='+service.getRedirectUri());

  if (service.hasAccess()) {

    var api = "https://photoslibrary.googleapis.com/v1/albums";

    var headers = {
      "Authorization": "Bearer " + service.getAccessToken()
    };

    var options = {
      "headers": headers,
      "method" : "GET",
      "muteHttpExceptions": true
    };

    var response = UrlFetchApp.fetch(api, options);

    var json = JSON.parse(response.getContentText());

    for (var i in json.items) {
      nrow = []; nrow.push(json.items[i].id);  nrow.push(json.items[i].name); nrow.push(json.items[i].url); narray.push(nrow);
    }
    albums_sh.getRange(1,1,narray.length,narray[0].length).setValues(narray);


  } else {
    var authorizationUrl = service.getAuthorizationUrl();
    Logger.log("Open the following URL and re-run the script: " + authorizationUrl);
  }
}

1 Ответ

0 голосов
/ 08 января 2019

Так что это работает, если другие хотят его использовать. Но это довольно медленно (у меня 500 альбомов ...):

function photoAPI() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var albums_sh = ss.getSheetByName("albums") || ss.insertSheet("albums", ss.getSheets().length); 
  albums_sh.clear();
  var narray = []; 

  var api = "https://photoslibrary.googleapis.com/v1/albums";
  var headers = { "Authorization": "Bearer " +  ScriptApp.getOAuthToken() };
  var options = { "headers": headers, "method" : "GET", "muteHttpExceptions": true };

  var param= "", nexttoken;
  do {
    if (nexttoken)
      param = "?pageToken=" + nexttoken; 
    var response = UrlFetchApp.fetch(api + param, options);
    var json = JSON.parse(response.getContentText());
    json.albums.forEach(function (album) {
      var data = [
        album.title,
        album.mediaItemsCount,
        album.productUrl
      ];
      narray.push(data);
    });
    nexttoken = json.nextPageToken;
  } while (nexttoken);
  albums_sh.getRange(1, 1, narray.length, narray[0].length).setValues(narray);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...