hardlounge/src/plugins/irc-events/thumb.js

64 lines
1.5 KiB
JavaScript
Raw Normal View History

2014-08-16 19:49:28 +00:00
var _ = require("lodash");
var Msg = require("../../models/msg");
2014-08-16 21:19:15 +00:00
var config = require("../../../config.json");
var fs = require("fs");
var mkdirp = require("mkdirp");
var http = require("http");
2014-08-16 19:49:28 +00:00
module.exports = function(irc, network) {
var client = this;
irc.on("message", function(data) {
var image = "";
var split = data.message.split(" ");
_.each(split, function(w) {
var match = w.match(/^(http|https).*\.(gif|png|jpg|jpeg)$/i);
if (match !== null) {
image = w;
}
});
if (image === "") {
return;
}
var target = data.to;
var chan = _.findWhere(network.channels, {name: target.charAt(0) == "#" ? target : data.from});
if (typeof chan === "undefined") {
return;
}
2014-08-16 21:19:15 +00:00
fetchImage(image, function(name) {
var msg = new Msg({
type: Msg.Type.THUMB,
from: data.from,
text: "thumbs/" + name
});
chan.messages.push(msg);
client.emit("msg", {
chan: chan.id,
msg: msg
});
2014-08-16 19:49:28 +00:00
});
});
};
2014-08-16 21:19:15 +00:00
function fetchImage(url, callback) {
var path = process.env.HOME + "/.shout/cache/thumbs";
var name = new Date().getTime().toString()
mkdirp(path, function(e) {
if (e) {
console.log(e);
}
var stream = fs.createWriteStream(path + "/" + name);
stream.on("error", function(e) {
// ..
});
http.get(url, function(res) {
res.on("data", function(chunk) {
stream.write(chunk);
});
res.on("end", function() {
stream.end();
callback(name);
});
});
});
}