thelounge/src/plugins/irc-events/link.js

92 lines
1.7 KiB
JavaScript
Raw Normal View History

2014-09-27 21:17:05 +02:00
var _ = require("lodash");
2014-09-27 22:39:14 +02:00
var cheerio = require("cheerio");
2014-09-27 21:17:05 +02:00
var Msg = require("../../models/msg");
var request = require("superagent");
2014-10-10 23:12:01 +02:00
var Helper = require("../../helper");
2014-09-27 21:17:05 +02:00
module.exports = function(irc, network) {
var client = this;
irc.on("message", function(data) {
2014-10-10 23:12:01 +02:00
var config = Helper.getConfig();
if (!config.prefetch) {
return;
}
2014-09-27 21:17:05 +02:00
var links = [];
var split = data.message.split(" ");
_.each(split, function(w) {
var match = w.indexOf("http://") === 0 || w.indexOf("https://") === 0;
if (match) {
links.push(w);
}
});
if (links.length === 0) {
return;
}
var self = data.to.toLowerCase() == irc.me.toLowerCase();
var chan = _.findWhere(network.channels, {name: self ? data.from : data.to});
if (typeof chan === "undefined") {
return;
}
var msg = new Msg({
type: Msg.Type.TOGGLE,
time: ""
});
chan.messages.push(msg);
client.emit("msg", {
chan: chan.id,
msg: msg
});
_.each(links, function(url) {
fetch(url, function(res) {
2014-09-28 01:47:04 +02:00
parse(msg, url, res, client);
2014-09-27 21:17:05 +02:00
});
});
});
};
2014-09-28 01:47:04 +02:00
function parse(msg, url, res, client) {
var toggle = msg.toggle = {
id: msg.id,
type: "",
head: "",
body: "",
link: url
};
2014-09-27 21:17:05 +02:00
switch (res.type) {
case "text/html":
2014-09-27 22:39:14 +02:00
var $ = cheerio.load(res.res.text);
2014-09-28 01:47:04 +02:00
toggle.type = "link";
toggle.head = $("title").text();
toggle.body = $('meta[name=description]').attr('content') ||
$('meta[property="og:description"]').attr('content') || "";
2014-09-27 21:17:05 +02:00
break;
case "image/png":
case "image/gif":
case "image/jpg":
case "image/jpeg":
2014-09-28 01:47:04 +02:00
toggle.type = "image";
2014-09-27 21:17:05 +02:00
break;
default:
return;
}
2014-09-28 01:47:04 +02:00
client.emit("toggle", toggle);
2014-09-27 21:17:05 +02:00
}
function fetch(url, cb) {
var req = request.get(url);
req.end(function(e, res) {
if (res) {
cb(res);
}
});
}