Skip to content

Instantly share code, notes, and snippets.

@danyx23
Last active September 1, 2016 08:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danyx23/96f9d560e3e1608445aee22cf35ef88e to your computer and use it in GitHub Desktop.
Save danyx23/96f9d560e3e1608445aee22cf35ef88e to your computer and use it in GitHub Desktop.
// This script will insert images for all the inchis it finds
// in a google document
//How to use this scipt:
// Go to a google document where you want this script to work
// Choose from the Menu: Tools -> Script editor
// Delete everything in the editor that opens
// Paste in this entire script
// Save it and close the window
//
// Now close the document
// Reopen the document and wait a little
// You should see a new Menu called "Douglas Connect Tools"
// Go there and click "Get Images for Inchis"
// Wait a little and you will get images for all found inchis
// appended at the end of the document
function onOpen() {
var ui = DocumentApp.getUi();
// Or DocumentApp or FormApp.
ui.createMenu('Douglas Connect Tools')
.addItem('Get Images for Inchis', 'getImageForInchi')
.addToUi();
}
function searchInchi(body, nextSearchStart) {
var inchiRegex = "(InChI=)[^\s]{6,}"
if (nextSearchStart != undefined)
return body.findText(inchiRegex, nextSearchStart);
else
return body.findText(inchiRegex);
}
function getImageForInchi() {
Logger.log("Getting document, starting search for inchi")
var document = DocumentApp.getActiveDocument()
var body = document.getBody()
var errors = ""
var searchResult = searchInchi(body);
while (searchResult != null) {
Logger.log("Found inchi")
var matchedparagraph = searchResult.getElement().asText().getText();
var text = matchedparagraph
.substring(searchResult.getStartOffset(), searchResult.getEndOffsetInclusive()+1);
var nextSearchStart = searchResult
Logger.log(text);
// Download a file now (GET), so we can upload it in the HTTP POST below.
Logger.log("https://cactus.nci.nih.gov/chemical/structure/" + text + "/image");
var response = UrlFetchApp.fetch("https://cactus.nci.nih.gov/chemical/structure/" + text + "/image", { escaping: true });
if (response.getResponseCode() == 200) {
Logger.log("Download successful");
var fileBlob = response.getAs('image/png');
try {
body.appendImage(fileBlob);
}
catch (err) {
Logger.log("Error appending file, image was probably invalid")
errors = errors + "Could not get valid image for inchi: " + text + "\n"
}
}
else
Logger.log("Download failed with code " + response.getResponseCode());
if (nextSearchStart != null && nextSearchStart != undefined)
searchResult = searchInchi(body, nextSearchStart);
else
searchResult = null
}
if (errors != "")
body.appendParagraph("The following errors occured:\n" + errors)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment