DocumentApp.openById () завершается с ошибкой «Служба недоступна» - PullRequest
0 голосов
/ 22 мая 2018

Я пытаюсь прочитать содержимое электронной таблицы, которая содержит некоторые значения folderId, fileName и targetFile, а затем на основе данных, введенных в электронную таблицу.

Я нашел последнюю fileId в накопителе для того же fileName, так как несколько файлов с одним и тем же именем добавляются в папку ежедневно (это делается функцией mostRecentFiIeInFolder), а затемЯ пытаюсь скопировать содержимое последнего файла с идентификатором dociIdSource в другой файл с идентификатором docIdTarget (что выполняется функцией docCopy).

Но когда я попытался реализовать это с помощьюDocumentApp, я получаю странную ошибку, которая говорит

Служба недоступна: документы

для кода var baseDoc = DocumentApp.openById(docID);.

Могу ли я знать, где я иду не так?

// Test function to call applyDocCopytoList.
function test(){
  applyDocCopytoList();
}

// Read the values from the spreadsheet.
function applyDocCopytoList(){
  var originalSpreadsheet = SpreadsheetApp.openById('sheet Id goes here').getSheetByName("sheet name goes here");
  var getRange = originalSpreadsheet.getDataRange();
  var data = originalSpreadsheet.getDataRange().getValues();
  for (var i = 1; i < data.length; i++) {
    var folderId = data[i][1];
    var fileName = data[i][2];
    var targetFile = data[i][3];

    Logger.log('****************Record No: ' + i);
    Logger.log('folderId: ' + data[i][1]);
    Logger.log('fileName: ' + data[i][2]);
    Logger.log('targetFile: ' + data[i][3]);

    var latestFileId = mostRecentFiIeInFolder(folderId, fileName);
    if(latestFileId!= undefined){
      docCopy(latestFileId, targetFile);
    }
  }
}


// Log the id of the latest file with a particular name in the folder.
function mostRecentFiIeInFolder(folderId, fileName) {
  var folder = DriveApp.getFolderById(folderId);
  Logger.log(folder);
  var files = DriveApp.getFilesByName(fileName);
  Logger.log(fileName);
  var result = [];
  // Checks whether the given file is in the folder or not
  if(!files.hasNext()){
    Logger.log('No such file in the folder with the given name');
  }
  else{
    while (files.hasNext()) {
      var file = files.next();
      result.push([file.getDateCreated(), file.getId()]);
    }
    Logger.log('************All the file ids with the same file name and their dates created************');  
    Logger.log(result);
    result.sort(function (x, y){
      var xp = x[0];// get first element in inner array
      var yp = y[0];
      return xp == yp ? 0 : xp > yp ? -1 : 1;// choose the sort order, here its in descending order of created date
    });    
    var id = result[0][1];
    Logger.log(id);
    return id;
  }
}

// Copy the contents of the latest file in the target file.
function docCopy(dociIdSource, docIdTarget){
  Logger.log('The file with id: ' + dociIdSource + ' will be copied to the target id: ' + docIdTarget);

  var docID = docIdTarget;
  var baseDoc = DocumentApp.openById(docID); //Service unavailable: Docs error is thrown for this line of code
  var body = baseDoc.getBody();

  var otherBody = DocumentApp.openById(dociIdSource).getBody();
  var totalElements = otherBody.getNumChildren();
  for( var j = 0; j < totalElements; ++j ) {
    var element = otherBody.getChild(j).copy();
    var type = element.getType();
    if( type == DocumentApp.ElementType.PARAGRAPH )
      body.appendParagraph(element);
    else if( type == DocumentApp.ElementType.TABLE )
      body.appendTable(element);
    else if( type == DocumentApp.ElementType.LIST_ITEM )
      body.appendListItem(element);
    else if( type == DocumentApp.ElementType.INLINE_IMAGE )
      body.appendImage(element);
    else if( type == DocumentApp.ElementType.TEXT ) 
      body.setText(element); 
    else
      throw new Error("According to the doc this type couldn't appear in the body: " + type);
  }
}

1 Ответ

0 голосов
/ 23 мая 2018

Обратите внимание, что ваша функция mostRecentFiIeInFolder на самом деле никогда не использует папку и никогда не проверяет, что файлы имеют правильный тип, то есть фактически являются файлами Google Docs.Таким образом, если искомое имя не должно было ничего найти (т.е. в целевой папке нет недавнего файла с таким именем), но в другом месте вашего накопителя был какой-то альтернативный файл, который не является файлом Google Docs, ваш скрипт найдет его.и относитесь к нему как к чему-то, чего нет.

Решение состоит в том, чтобы ограничить поиск нужной вам папкой, и опять-таки по фактическому миметипу Документов Google:

function testIt() {
  var folderIds = [
    "", // Search all of Drive
    "123428349djf8234", // Search that specific folder
  ];
  // Log (in Stackdriver) the file id of the most recently created Google Docs file with the name "some name" in the various folders:
  folderIds.forEach(function (folderId) {
    console.log(getMostRecentFileIdWithName("some name", folderId, MimeType.GOOGLE_DOCS));
  });
}

function getMostRecentFileIdWithName(fileName, folderId = "", mimeType = "") {
  // If a folder was given, restrict the search to that folder. Otherwise, search with
  // DriveApp. (Throws an error if the folderId is invalid.)
  var parent = folderId ? DriveApp.getFolderById(folderId) : DriveApp;

  // I assume your fileName variable does not contain any unescaped single-quotes.
  var params = "name='" + fileName + "'";
  // If a mimetype was given, search by that type only, otherwise search any type.
  if (mimeType)
    params += " and mimeType='" + mimeType + "'";
  var matches = parent.searchFiles(params),
      results = [];

  // Collect and report results.
  while (matches.hasNext())
    results.push(matches.next());
  if (!results.length)
    throw new Error("Bad search query \"" + params + "\" for folder id = '" + folderId + "'.");

  // Sort descending by the creation date (a native Date object).
  // (a - b sorts ascending by first column).
  results.sort(function (a, b) { return b.getDateCreated() - a.getDateCreated(); });
  return results[0].getId();
}

Подробнее одопустимые параметры поиска в документации Drive REST API , а также дополнительные сведения о собственной реализации скрипта приложений в документации DriveApp .

...