|
// Not in use as much anymore since my kid is no longer in preschool, but figured I'd put it out there for other parents. |
|
// Run this on a daily schedule and it will download any images that are sent to your email and save them to a folder in |
|
// Google drive. Images are organized by [year] and [month] and photos are formated as [day]--[id]--[i] where the id is |
|
// the id of the message, and i is the position of the image in the message. |
|
|
|
function mkdirp(root, path) { |
|
var ptr = root; |
|
path.forEach(function(part) { |
|
var iter = ptr.getFoldersByName(part); |
|
|
|
if (iter.hasNext()) { |
|
ptr = iter.next(); |
|
} else { |
|
ptr = ptr.createFolder(part); |
|
} |
|
}); |
|
return ptr; |
|
} |
|
|
|
function twodigit(num) { |
|
if (num < 10) { |
|
return '0' + num |
|
} else { |
|
return '' + num |
|
} |
|
} |
|
|
|
function imageDownloader() { |
|
var root = DriveApp.getRootFolder(); |
|
var folderName = "Tadpoles Photos"; |
|
|
|
var regexp = /img [^>]*/g; |
|
|
|
var query = 'from:[email protected] newer_than:1d'; |
|
|
|
var threads = GmailApp.search(query); |
|
|
|
var images = {}; |
|
|
|
threads.forEach(function(thread) { |
|
var messages = thread.getMessages(); |
|
|
|
messages.forEach(function(message) { |
|
var date = message.getDate(); |
|
|
|
var year = date.getFullYear(); |
|
var month = date.getMonth() + 1; |
|
|
|
var day = twodigit(date.getDate()); |
|
var id = message.getId(); |
|
|
|
var body = message.getBody(); |
|
var $ = Cheerio.load(body); |
|
|
|
$('img[alt="tap photo to view at tadpoles"]').each(function(i, elem) { |
|
var src = $(this).attr('src'); |
|
|
|
if (images[src]) { |
|
return |
|
} |
|
|
|
images[src] = { |
|
fileName: [day, id, i].join("--") + ".jpg", |
|
folder: mkdirp(root, [ folderName, year, month ]), |
|
}; |
|
}); |
|
}); |
|
}); |
|
|
|
Object.keys(images).forEach(function(src) { |
|
var { fileName, folder } = images[src]; |
|
|
|
var image = UrlFetchApp.fetch(src).getBlob(); |
|
image.setName(fileName); |
|
var file = folder.createFile(image); |
|
}); |
|
} |