function main() { const scriptProperties = PropertiesService.getScriptProperties(); const projects = JSON.parse(scriptProperties.getProperty('PROJECTS')); // 複数のprojectを指定可能 const connect_sid = scriptProperties.getProperty('CONNECT_SID'); let lastbackupedList = JSON.parse(scriptProperties.getProperty('LAST_BACKUPED_LIST') || '[]'); const folder = DriveApp.getFolderById('xxx'); // お好みのfolderを選択してください lastbackupedList = projects.map((project, i) => downloadBackup({ project, connect_sid, folder, lastbackuped: lastbackupedList[i] || 0 })); scriptProperties.setProperty('LAST_BACKUPED_LIST', JSON.stringify(lastbackupedList)); } const zero = n => String(n).padStart(2, '0'); function downloadBackup({ project, connect_sid, folder, lastbackuped }) { const backups = getBackupList({ project, connect_sid }); const backupIds = backups .flatMap(({ backuped, id }) => backuped > lastbackuped ? [id] : []) .slice(0, 10); // 直近10ファイルまで取得する if (backupIds.length === 0) { console.log('no backup files found.'); return lastbackuped; } const jsons = getBackupFiles({ project, connect_sid, fileIds: backupIds }); console.log('Save backup files...'); let saveNum = 0; jsons.forEach(json => { const exported = new Date(json.exported * 1000); const fileName = `${project}_${exported.getFullYear()}${zero(exported.getMonth() + 1)}${zero(exported.getDate())}${zero(exported.getHours())}${zero(exported.getMinutes())}${zero(exported.getSeconds())}.json`; folder.createFile(fileName, JSON.stringify(json, null, 2), 'application/json'); saveNum++; console.log(`Saved: ${saveNum}/${jsons.length}`); }); // backupの最終更新日時を返す const newLastBackuped = Math.max(...jsons.map(({ exported }) => parseInt(exported))); console.log(`Finish saving. Last backuped date: ${new Date(newLastBackuped * 1000)}`); return newLastBackuped; } function getBackupList({ project, connect_sid }) { console.log(`Start fetching the backup list of /${project}...`); const response = UrlFetchApp .fetch(`https://scrapbox.io/api/project-backup/${project}/list`, { headers: { Cookie: `connect.sid=${connect_sid}` }, }); const json = JSON.parse(response.getContentText()); console.log(`Finish fetching.`, { backupNum: json.backups.length }); return json.backups; } function getBackupFiles({ project, fileIds, connect_sid }) { console.log(`Start fetching ${fileIds.length} backups from /${project}...`, fileIds); const responses = UrlFetchApp .fetchAll(fileIds.map(fileId => { return { url: `https://scrapbox.io/api/project-backup/${project}/${fileId}.json`, headers: { Cookie: `connect.sid=${connect_sid}` }, }; }) ); const jsons = responses.map(response => JSON.parse(response.getContentText())); console.log('Finish fetching.'); return jsons; }