Skip to content

Instantly share code, notes, and snippets.

@westonkd
Created March 19, 2023 02:41
Embed
What would you like to do?
// 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))
}
@westonkd
Copy link
Author

This script does the following:

  1. Searches all Gmail threads for messages from Amazon indicating a Kindle Scribe notebook has been shared
  2. Iterates through all messages in that thread and extracts the links to those notebooks. These links are valid for seven days.
  3. Downloads the notebooks pointed to by the extracted links
  4. Finds or creates the folder in the user's Google Drive folder named "Kindle Scribe Notes"
  5. Uploads the notebook PDF to this folder in Google Drive

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment