// Scoutworks → copy the Knowledge Base to Google Drive, nightly.
// https://developers.scoutworks.app/recipes/mirror-knowledge-base
const BASE = 'https://api-demo.scoutworks.app/api/v1';
const ROOT_NAME = 'Scoutworks Knowledge Base';
function copyKnowledgeBase() {
const props = PropertiesService.getScriptProperties();
const since = props.getProperty('NEXT_UPDATED_SINCE');
// A minute before this run began: a file changed while it runs is read again next time.
const startedAt = new Date(Date.now() - 60 * 1000).toISOString();
const root = rootFolder();
// Folders: one Drive folder for each Scoutworks folder, nested the same way.
const folders = readAll('/folders');
const byId = {};
folders.forEach(function (f) { byId[f.id] = f; });
const driveFolders = {};
function driveFolderFor(id) {
if (!id) return root;
if (driveFolders[id]) return driveFolders[id];
const f = byId[id];
const parent = driveFolderFor(f.parentId);
driveFolders[id] = childFolder(parent, f.name, f.id);
return driveFolders[id];
}
// Files that changed since last night (every file, the first time).
const changed = since
? readPages('/files?updatedSince=' + encodeURIComponent(since))
: readPages('/files');
// Files skipped on an earlier night are tried again, changed or not.
const seen = {};
changed.items.forEach(function (f) { seen[f.id] = true; });
props.getKeys().forEach(function (key) {
if (key.indexOf('retry:') !== 0 || seen[key.slice(6)]) return;
const res = fetchOrNull(BASE + '/files/' + key.slice(6));
if (res) changed.items.push(res.data);
else props.deleteProperty(key); // Deleted in Scoutworks since.
});
changed.items.forEach(function (file) {
// A file still waiting for its scan is copied once the scan is done, which changes its updatedAt.
if (file.kind !== 'upload' || file.virusScan === 'infected' || file.virusScan === 'pending') return;
// Already copied as it is now: a run stopped part-way carries on from here.
if (props.getProperty('ver:' + file.id) === file.updatedAt) return;
const link = downloadLink(file.id);
if (!link) {
// Not downloadable just now: kept on a list and tried again next night.
props.setProperty('retry:' + file.id, file.name);
return;
}
props.deleteProperty('retry:' + file.id);
const blob = UrlFetchApp.fetch(link.url).getBlob().setName(file.name);
const target = driveFolderFor(file.folderId);
removeCopy(file.id);
props.setProperty('file:' + file.id, target.createFile(blob).getId());
props.setProperty('ver:' + file.id, file.updatedAt);
Utilities.sleep(600); // Stay well under 120 requests a minute.
});
// Copies of files deleted in Scoutworks go to the bin.
const live = {};
readAll('/files').forEach(function (f) { live[f.id] = true; });
props.getKeys().forEach(function (key) {
if (key.indexOf('file:') === 0 && !live[key.slice(5)]) removeCopy(key.slice(5));
});
// Only once everything is saved: next time, read what changed after this.
props.setProperty('NEXT_UPDATED_SINCE', changed.nextUpdatedSince || startedAt);
}
// One record, or null when it no longer exists.
function fetchOrNull(url) {
const apiKey = PropertiesService.getScriptProperties().getProperty('SCOUTWORKS_API_KEY');
const res = UrlFetchApp.fetch(url, {
headers: { Authorization: 'Bearer ' + apiKey },
muteHttpExceptions: true,
});
if (res.getResponseCode() === 404) return null;
return fetchScoutworks(url);
}
// A file's 15-minute link, or null when it cannot be downloaded now
// (a Drive doc, a flagged file, or one waiting for its scan).
function downloadLink(id) {
const apiKey = PropertiesService.getScriptProperties().getProperty('SCOUTWORKS_API_KEY');
const res = UrlFetchApp.fetch(BASE + '/files/' + id + '/download', {
headers: { Authorization: 'Bearer ' + apiKey },
muteHttpExceptions: true,
});
if (res.getResponseCode() === 409 || res.getResponseCode() === 503) return null;
if (res.getResponseCode() === 429) {
Utilities.sleep(Number(res.getHeaders()['Retry-After'] || 60) * 1000);
return downloadLink(id);
}
const body = JSON.parse(res.getContentText());
if (res.getResponseCode() !== 200) throw new Error(body.error.code + ': ' + body.error.message);
return body.data;
}
function rootFolder() {
const found = DriveApp.getFoldersByName(ROOT_NAME);
return found.hasNext() ? found.next() : DriveApp.createFolder(ROOT_NAME);
}
// The Drive folder for a Scoutworks folder. The script remembers which
// Drive folder each Scoutworks id became, so a renamed folder is renamed
// here too rather than copied twice.
function childFolder(parent, name, id) {
const props = PropertiesService.getScriptProperties();
const known = props.getProperty('folder:' + id);
let folder = null;
if (known) {
try { folder = DriveApp.getFolderById(known); } catch (e) { folder = null; }
}
if (!folder || folder.isTrashed()) {
folder = parent.createFolder(name);
props.setProperty('folder:' + id, folder.getId());
}
if (folder.getName() !== name) folder.setName(name);
// A folder moved in Scoutworks moves here too.
const parents = folder.getParents();
if (!parents.hasNext() || parents.next().getId() !== parent.getId()) folder.moveTo(parent);
return folder;
}
// Bin the copy of a Scoutworks file, if the script made one.
function removeCopy(id) {
const props = PropertiesService.getScriptProperties();
const known = props.getProperty('file:' + id);
if (!known) return;
try { DriveApp.getFileById(known).setTrashed(true); } catch (e) { /* already gone */ }
props.deleteProperty('file:' + id);
props.deleteProperty('ver:' + id);
}
// Every item in a list, following nextCursor to the last page.
function readAll(path) {
return readPages(path).items;
}
function readPages(path) {
const items = [];
let cursor = null;
let nextUpdatedSince = null;
do {
let url = BASE + path + (path.indexOf('?') === -1 ? '?' : '&') + 'limit=200';
if (cursor) url += '&cursor=' + encodeURIComponent(cursor);
const body = fetchScoutworks(url);
items.push.apply(items, body.data);
cursor = body.nextCursor;
nextUpdatedSince = body.nextUpdatedSince || nextUpdatedSince;
} while (cursor);
return { items: items, nextUpdatedSince: nextUpdatedSince };
}
// Calls the API. Waits and tries again if the rate limit is reached.
function fetchScoutworks(url) {
const apiKey = PropertiesService.getScriptProperties().getProperty('SCOUTWORKS_API_KEY');
if (!apiKey) throw new Error('Add SCOUTWORKS_API_KEY in Project Settings → Script Properties.');
for (let attempt = 0; attempt < 3; attempt++) {
const res = UrlFetchApp.fetch(url, {
headers: { Authorization: 'Bearer ' + apiKey },
muteHttpExceptions: true,
});
const body = JSON.parse(res.getContentText());
if (res.getResponseCode() === 200) return body;
if (res.getResponseCode() === 429 || res.getResponseCode() === 503) {
Utilities.sleep(Number(body.retryAfter || res.getHeaders()['Retry-After'] || 60) * 1000);
continue;
}
throw new Error(body.error.code + ': ' + body.error.message);
}
throw new Error('Scoutworks is still busy. The copy will try again tomorrow night.');
}