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

73 lines
1.6 KiB
JavaScript
Raw Normal View History

2014-08-17 21:40:08 +00:00
var _ = require("lodash");
var Msg = require("../../models/msg");
2014-09-13 16:41:11 +00:00
var config = require("../../../config");
2014-08-17 21:40:08 +00:00
var fs = require("fs");
var mkdirp = require("mkdirp");
var request = require("superagent");
var Helper = require("../../helper");
2014-08-17 21:40:08 +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-09-14 18:49:42 +00:00
var self = false;
if (data.from.toLowerCase() == irc.me.toLowerCase()) {
self = true;
}
2014-08-17 21:40:08 +00:00
fetchImage(image, function(name) {
var msg = new Msg({
type: Msg.Type.IMAGE,
from: data.from,
text: "thumbs/" + name,
2014-09-14 18:49:42 +00:00
self: self
2014-08-17 21:40:08 +00:00
});
chan.messages.push(msg);
client.emit("msg", {
chan: chan.id,
msg: msg
});
});
});
};
function fetchImage(url, callback) {
var path = Helper.resolveHomePath("cache", "thumbs");
2014-08-17 21:40:08 +00:00
var name = new Date().getTime().toString();
mkdirp(path, function(e) {
if (e) {
console.log(e);
2014-08-18 23:54:14 +00:00
return;
2014-08-17 21:40:08 +00:00
}
2014-08-18 23:54:14 +00:00
var stream = fs.createWriteStream(
path + "/" + name,
{mode: "0777"}
);
2014-08-17 21:40:08 +00:00
var req = request.get(url);
req.pipe(stream);
2014-08-18 23:54:14 +00:00
req.on("error", function(e) {
console.log(e);
});
2014-08-19 00:06:52 +00:00
req.on("end", function() {
if (this.req.res.statusCode == 200) {
callback(name);
2014-08-19 00:06:52 +00:00
}
2014-08-17 21:40:08 +00:00
});
2014-08-17 21:40:08 +00:00
});
}