Skip to content

Instantly share code, notes, and snippets.

@ykzts
Created May 9, 2010 10:49
Show Gist options
  • Save ykzts/395079 to your computer and use it in GitHub Desktop.
Save ykzts/395079 to your computer and use it in GitHub Desktop.
var re = {
'tumblr': /^http:\/\/[^.]+\.tumblr\.com\/post\//,
'flickr': /^http:\/\/(www\.)?flickr.com\/photos\/[^/]+\/(\d+)/
};
var flickr_api_key = 'b64ebb97d85e8ab9571ea101bba30bcc';
function InlineImageInsert() {
arguments.callee.prototype = {
init: function(uri, api_uri, exp, line) {
this.uri = uri;
this.api_uri = api_uri;
this.exp = exp;
this.line = line;
this.e();
},
e: function() {
var self = this;
var req = new XMLHttpRequest()
req.open('get', self.api_uri, false);
req.onreadystatechange = function() {
if (req.readyState != 4) return;
self.insertInlineImageNode(self.xpath(self.exp, req.responseXML), self.uri);
};
req.send(null);
},
insertInlineImageNode: function(image_uri, uri) {
var line = this.line;
var doc = line.ownerDocument;
var inlineImageAnchorNode = doc.createElement('a');
var inlineImageNode = doc.createElement('img');
inlineImageNode.setAttribute('src', image_uri);
inlineImageNode.setAttribute('class', 'inlineimage');
inlineImageAnchorNode.setAttribute('href', uri);
inlineImageAnchorNode.insertBefore(inlineImageNode, inlineImageAnchorNode.nextSibling);
line.parentNode.insertBefore(doc.createElement('br'), line.nextSibling);
line.parentNode.insertBefore(inlineImageAnchorNode, line.nextSibling);
},
xpath: function(exp, context) {
var result = context.evaluate(exp, context, null, 2, null);
return result.stringValue;
}
};
}
function processLine(e) {
var iii = new InlineImageInsert();
var line = e.target;
if (line.getAttribute('class') != 'line text') return;
var anchor = line.getElementsByClassName('url').item(0);
if (!anchor) return;
var uri = anchor.textContent;
if (re.tumblr.test(uri)) {
iii.init(uri, uri + '/xml', '//photo-url[@max-width="1280"]', line);
} else if (re.flickr.test(uri)) {
api_uri = 'http://api.flickr.com/services/rest/?' + [
'method=flickr.photos.getInfo',
'api_key=' + flickr_api_key,
'photo_id=' + RegExp.$2].join('&');
iii.init(uri, api_uri, 'concat("http://farm", //photo/@farm, ".static.flickr.com/", //photo/@server, "/", //photo/@id, "_", //photo/@secret, ".jpg")', line);
}
}
document.addEventListener('DOMNodeInserted', processLine, true);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment