Last active
January 22, 2017 17:20
-
-
Save vensko/1dcb3b495bbc81b4ae42799415469185 to your computer and use it in GitHub Desktop.
Save selected text to Google Drive
This file contains hidden or 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
/* | |
Generate your bookmarklet here: https://d.vensko.net/google-script-save-snippets-to-google-drive | |
Copyright (c) 2017 Dzmitry Vensko | |
Permission is hereby granted, free of charge, to any person obtaining | |
a copy of this software and associated documentation files (the | |
"Software"), to deal in the Software without restriction, including | |
without limitation the rights to use, copy, modify, merge, publish, | |
distribute, sublicense, and/or sell copies of the Software, and to | |
permit persons to whom the Software is furnished to do so, subject to | |
the following conditions: | |
The above copyright notice and this permission notice shall be | |
included in all copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, | |
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | |
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND | |
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE | |
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION | |
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION | |
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | |
*/ | |
function Input(e) { | |
this.html = compileHTML(e.parameter); | |
this.title = e.parameter.title; | |
this.url = e.parameter.url; | |
this.fileName = sanitizeFileName(this.title); | |
this.resources = e.parameters['resources[]'] ? fixRelativePaths(this.url, e.parameters['resources[]']) : []; | |
this.resourceResponses = {}; | |
this.folder = e.parameter.folder ? getFolderByFullPath(e.parameter.folder + '/' + month()) : null; | |
this.folderZip = e.parameter.folder_zip ? getFolderByFullPath(e.parameter.folder_zip + '/' + month()) : null; | |
this.folderPdf = e.parameter.folder_pdf ? getFolderByFullPath(e.parameter.folder_pdf + '/' + month()) : null; | |
}; | |
/** | |
* @returns {String} | |
*/ | |
function getDefaultFolder() | |
{ | |
return 'Scrapbook'; | |
} | |
function doPost(e) { | |
var input = new Input(e); | |
if (!input.folder && !input.folderZip && !input.folderPdf) { | |
return HtmlService.createHtmlOutput('Please, set select at least one method of storage.'); | |
} | |
var doc = null, responseUrl = null; | |
if (input.folderZip) { | |
responseUrl = createZip(input).getDownloadUrl().replace('&gd=true', ''); | |
} | |
if (input.folderPdf) { | |
responseUrl = createPdf(input).getDownloadUrl().replace('&gd=true', ''); | |
} | |
if (input.folder) { | |
// TODO: Find a way to make a new revision from raw HTML | |
deleteIfExists(input.fileName, input.folder); | |
doc = createDocument(input); | |
responseUrl = 'https://docs.google.com/feeds/download/documents/export/Export?id=' + doc.getId() + '&exportFormat=html'; | |
//responseUrl = DriveApp.getFileById(doc.getId()).getUrl(); | |
} | |
return HtmlService.createHtmlOutput( | |
responseUrl ? (doc ? input.html.replace('<body>', '<body><b>Saved: </b>') : 'Saved: <a href="' + responseUrl + '" target="_top">' + input.title + '</a>') : 'Something went wrong :(' | |
); | |
} | |
function doGet(e) { | |
var t = HtmlService.createTemplateFromFile('Bookmarklet'); | |
t.dev = e.parameter.dev; | |
return t.evaluate(); | |
} | |
/** | |
* @param {Input} input | |
* @returns {Document} | |
*/ | |
function createDocument(input) { | |
var doc = Drive.Files.insert({ | |
title: input.fileName, | |
mimeType: MimeType.HTML, | |
parents: [{ id: input.folder.getId() }] | |
}, createHtmlBlob(input.html, input.fileName), { | |
convert: true | |
}); | |
DriveApp.getFileById(doc.getId()).setDescription(input.url); | |
return doc; | |
} | |
/** | |
* @param {Input} input | |
* @returns {File} | |
*/ | |
function createZip(input) { | |
var fileName = input.fileName + '.htmlz'; | |
var blob = Utilities.zip(prepareFiles(input), fileName); | |
return updateOrCreateFile(input.folderZip, fileName, blob).setDescription(input.url); | |
} | |
/** | |
* @param {Input} input | |
* @returns {File} | |
*/ | |
function createPdf(input) { | |
var fileName = input.fileName + '.pdf'; | |
var blob = Utilities.newBlob(dataUrify(input), MimeType.HTML, input.fileName + ".pdf").getAs(MimeType.PDF); | |
return updateOrCreateFile(input.folderPdf, fileName, blob).setDescription(input.url); | |
} | |
/** | |
* @param {Folder} folder | |
* @param {String} fileName | |
* @param {Blob} blob | |
* @returns {File} | |
*/ | |
function updateOrCreateFile(folder, fileName, blob) { | |
var existing = folder.getFilesByName(fileName); | |
if (existing.hasNext()) { | |
return Drive.Files.update({ | |
title: fileName, | |
mimeType: blob.getContentType() | |
}, existing.next().getId(), blob); | |
} else { | |
return folder.createFile( blob ); | |
} | |
} | |
/** | |
* @param {String} fileName | |
* @param {Folder} folder | |
* @returns void | |
*/ | |
function deleteIfExists(fileName, folder) { | |
var existing = folder.getFilesByName(fileName); | |
if (existing.hasNext()) { | |
existing.next().setTrashed(true); | |
} | |
} | |
/** | |
* @param {String} fullPathToFolder | |
* @returns {Folder} | |
*/ | |
function getFolderByFullPath(fullPathToFolder) { | |
var paths = fullPathToFolder.split("/"); | |
var curFolder = DriveApp.getRootFolder(); | |
for(var i = 0; i < paths.length; i++) { | |
var folders = curFolder.getFoldersByName(paths[i]); | |
curFolder = folders.hasNext() ? folders.next() : curFolder.createFolder(paths[i]); | |
} | |
return curFolder; | |
} | |
/** | |
* Converts a string to a valid file name | |
* @param {String} str | |
* @returns {String} | |
*/ | |
function sanitizeFileName(str) { | |
var illegalRe = /[\/\?<>\\:\*\|":]/g; | |
var controlRe = /[\x00-\x1f\x80-\x9f]/g; | |
var reservedRe = /^\.+$/; | |
var windowsReservedRe = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i; | |
var windowsTrailingRe = /[\. ]+$/; | |
return str | |
.replace(illegalRe, '') | |
.replace(controlRe, '') | |
.replace(reservedRe, '') | |
.replace(windowsReservedRe, '') | |
.replace(windowsTrailingRe, '') | |
.replace(/\s+/g, ' ') | |
.trim() | |
.substring(0, 254); | |
} | |
/** | |
* @returns {String} | |
*/ | |
function month() { | |
var today = new Date(); | |
var mm = today.getMonth() + 1; //January is 0! | |
var yyyy = today.getFullYear(); | |
if (mm < 10) { | |
mm = '0' + mm | |
} | |
return yyyy + '-' + mm; | |
} | |
/** | |
* @param {String} filename | |
* @returns {String|null} | |
*/ | |
function contentTypeFromFileName(filename, withAudio) { | |
var ext = getExtension(filename); | |
var extensions = { | |
jpg: MimeType.JPEG, | |
jpeg: MimeType.JPEG, | |
gif: MimeType.GIF, | |
png: MimeType.PNG, | |
svg: MimeType.SVG | |
}; | |
if (withAudio) { | |
extensions.mp3 = 'audio/mp3'; | |
extensions.ogg = 'audio/ogg'; | |
} | |
return extensions[ext] ? extensions[ext] : null; | |
} | |
/** | |
* @param {String} filename | |
* @returns {String} | |
*/ | |
function getExtension(filename) { | |
var ext = filename.split('.'); | |
return ext[ext.length - 1].toLowerCase(); | |
} | |
/** | |
* @param {String} url | |
* @returns {String} | |
*/ | |
function createLocalFilename(url) { | |
var filename = url.split('/'); | |
filename = filename[filename.length - 1]; | |
var ext = contentTypeFromFileName(filename, true) ? getExtension(filename) : null; | |
var randomName = randomString(5) + '.' + ext; | |
return ext ? filename.replace(new RegExp('\\.' + ext + '$'), '') + '_' + randomName : randomName; | |
} | |
/** | |
* Escapes arbitrary strings to use them in regular expressions | |
* @param {String} url | |
* @returns {String} | |
*/ | |
function escapeRegExp(str) { | |
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); | |
} | |
/** | |
* @param {Number} len | |
* @returns {String} | |
*/ | |
function randomString(len) { | |
var text = ""; | |
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; | |
for ( var i=0; i < len; i++ ) { | |
text += possible.charAt(Math.floor(Math.random() * possible.length)); | |
} | |
return text; | |
} | |
/** | |
* @param {String} html | |
* @param {String} fileName | |
* @returns {Blob} | |
*/ | |
function createHtmlBlob(html, fileName) { | |
return Utilities.newBlob('', MimeType.HTML, fileName + '.html').setDataFromString(html, 'utf-8'); | |
} | |
/** | |
* @param {Input} input | |
* @returns {String} | |
*/ | |
function compileHTML(input) { | |
var baseUrl = input.url.split('//')[0] + '//' + input.url.split('//')[1].split('/')[0]; | |
var html = '<html><head><meta charset="utf-8"><title>' + input.title + '</title></head><body><a href="' + input.url + '">' + input.url + '</a><hr>' + input.html + '</body></html>'; | |
html = html.replace(/="\/\//g, '="http://').replace(/="\//g, '="' + baseUrl + '/'); | |
return html; | |
} | |
/** | |
* @param {String} baseUrl | |
* @param {String[]} paths | |
* @returns {String[]} | |
*/ | |
function fixRelativePaths(baseUrl, paths) { | |
for (var i = 0, l = paths.length; i < l; i++) { | |
paths[i] = paths[i].indexOf('://') > -1 ? paths[i] : absolutePath(baseUrl, paths[i]); | |
} | |
return paths; | |
} | |
/** | |
* @param {String} base | |
* @param {String} relative | |
* @returns {String} | |
*/ | |
function absolutePath(base, relative) { | |
var stack = base.split("/"), | |
parts = relative.split("/"); | |
stack.pop(); // remove current file name (or empty string) | |
// (omit if "base" is the current folder without trailing slash) | |
for (var i=0; i < parts.length; i++) { | |
if (parts[i] == ".") | |
continue; | |
if (parts[i] == "..") | |
stack.pop(); | |
else | |
stack.push(parts[i]); | |
} | |
return stack.join("/"); | |
}; | |
/** | |
* @param {Input} input | |
* @returns {Blob[]} | |
*/ | |
function prepareFiles(input) { | |
var res, filename, html = input.html, blobs = []; | |
for (var i = 0, l = input.resources.length; i < l; i++) { | |
res = getRemoteFile(input, input.resources[i]); | |
if (!res) continue; | |
filename = 'files/' + createLocalFilename(input.resources[i]); | |
blobs.push(res.getBlob().setName(filename)); | |
html = html.replace(new RegExp(escapeRegExp(input.resources[i]), 'g'), filename); | |
} | |
blobs.unshift(createHtmlBlob(html, 'index')); | |
return blobs; | |
} | |
/** | |
* @param {Input} input | |
* @returns {String} | |
*/ | |
function dataUrify(input) { | |
var res, ctype, src, pattern, html = input.html; | |
for (var i = 0, l = input.resources.length; i < l; i++) { | |
res = getRemoteFile(input, input.resources[i]); | |
if (!res) continue; | |
ctype = (ctype = contentTypeFromFileName(input.resources[i])) ? ctype : res.getHeaders()['Content-Type']; | |
src = Utilities.base64Encode(res.getContent()); | |
pattern = ' src=["\']{1}' + escapeRegExp(input.resources[i]) + '["\']{1}'; | |
html = html.replace(new RegExp(pattern, 'g'), ' src="data:' + ctype + ';base64,' + src + '"'); | |
} | |
return html; | |
} | |
/** | |
* @param {Input} input | |
* @param {String} url | |
* @returns {HTTPResponse|null} | |
*/ | |
function getRemoteFile(input, url) { | |
var res = input.resourceResponses[input]; | |
if (!res) { | |
try { | |
res = UrlFetchApp.fetch(url, { muteHttpExceptions: true, validateHttpsCertificates: false }); | |
} catch (e) { | |
Logger.log(e.toString()); | |
return null; | |
} | |
} | |
return res; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment