Created
July 12, 2015 21:18
-
-
Save chriszs/0f49f6953f5c41ffb5e1 to your computer and use it in GitHub Desktop.
Get the contents of a Google Doc and process it with ArchieML. Exports the function retrieve to do this. Requires getting Google Auth credentials separately with a command line tool (e.g. https://www.npmjs.com/package/google-auth) and setting some environment variables for GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, GOOGLE_REFRESH_TOKEN and DOC_ID (…
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
var archieml = require('archieml'), | |
google = require('googleapis'); | |
var drive = google.drive('v2'); | |
var OAuth2 = google.auth.OAuth2; | |
var oauth2Client = new OAuth2(process.env.GOOGLE_CLIENT_ID, process.env.GOOGLE_CLIENT_SECRET, 'http://localhost'); | |
var docId = process.env.DOC_ID; | |
var exportLinkCache = null, | |
exportLinkLastRefresh = null; | |
oauth2Client.setCredentials({ | |
refresh_token: process.env.GOOGLE_REFRESH_TOKEN | |
}); | |
google.options({ | |
auth: oauth2Client | |
}); | |
function getExportLink(docId,cb) { | |
if (exportLinkCache && exportLinkLastRefresh && exportLinkLastRefresh > (new Date().setHours(-24))) { | |
cb(null,exportLinkCache); | |
return; | |
} | |
drive.files.get({ | |
fileId: docId | |
}, function(err, doc) { | |
if (err) { | |
cb(err); | |
return; | |
} | |
exportLink = doc.exportLinks['text/plain']; | |
exportLinkCache = exportLink; | |
exportLinkLastRefresh = new Date(); | |
cb(null,exportLink); | |
}); | |
} | |
function getData(exportLink,cb) { | |
oauth2Client.request({ | |
method: 'GET', | |
uri: exportLink | |
}, function(err, body) { | |
if (err) { | |
cb(err); | |
return; | |
} | |
// remove Google Docs comments | |
body = body.replace(/\[[a-z]{1,2}\]/g,''); | |
var data = archieml.load(body); | |
cb(null, data); | |
}); | |
} | |
function retrieve(cb) { | |
getExportLink(docId,function (err,exportLink) { | |
if (err) { | |
cb(err); | |
return; | |
} | |
getData(exportLink,cb); | |
}); | |
} | |
exports.retrieve = retrieve; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment