This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Main function | |
function backupNotebooks() { | |
const urls = notebookUrlsFromInterval(); | |
uploadNotebooks(urls) | |
} | |
/* Gmail Concerns */ | |
const intervalDays = 1 | |
const threadFilter = `from:do-not-reply@amazon.com "kindle" newer_than:${intervalDays}d` | |
function threadsFromLastInterval() { | |
return GmailApp.search(threadFilter) | |
} | |
/* Google Drive Concerns */ | |
const folderName = "Kindle Scribe Notes" | |
function uploadNotebooks(urls) { | |
const folder = notebookFolder() | |
uploadFilesToFolder(urls, folder) | |
} | |
function uploadFilesToFolder(urls, folder) { | |
urls.forEach((url) => { | |
const blob = UrlFetchApp.fetch(url).getBlob() | |
const file = folder.createFile(blob) | |
const name = filenameFor(url) | |
file.setName(name) | |
file.setDescription(`Backup of #{name} from Kindle Scribe`) | |
}) | |
} | |
function filenameFor(url) { | |
var match = /^https?:\/\/([^\/]+)\/([^?]*\/)?([^\/?]+)/.exec(url); | |
if (match) { | |
return decodeURIComponent(match[3]); | |
} | |
return "unkown_name" | |
} | |
function notebookFolder() { | |
let folders = DriveApp.getFoldersByName(folderName) | |
console.log(`folders: ${folders.hasNext()}`) | |
if (!folders || !folders.hasNext()) { | |
return DriveApp.createFolder(folderName) | |
} | |
return folders.next() | |
} | |
/* URL Concerns */ | |
function notebookUrlFrom(message) { | |
const notebookUrlPattern = /U=(https%3A%2F%2Fkindle-content-requests-prod\.s3\.amazonaws\.com.*Signature%3[a-zA-Z0-9]{65})/ | |
const matches = message.match(notebookUrlPattern) | |
if (!matches) return | |
return matches[1] | |
} | |
function notebookUrlsFromInterval() { | |
return threadsFromLastInterval().map((thread) => { | |
return thread.getMessages().map((message) => notebookUrlFrom(message.getPlainBody())) | |
}).flat().filter((url) => !!url).map((url) => decodeURIComponent(url)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This script does the following: