-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
82 lines (76 loc) · 1.66 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
var request = require("request");
// # Imgflipper
//
// Simple class for generating meme images using imgflip
//
// How to use:
//
// var imgflipper = new Imgflipper("user", "pass");
// imgflipper.generateMeme(123, "brace yourselves...", "the sprint planning session is coming.", cb)
//
// cb(err, imgUrl)
function Imgflipper(username, password) {
this.username = username;
this.password = password;
var me = this;
// ## generateMeme
//
// generates a meme image using imglip & returns the url
// cb(err, url)
this.generateMeme = function (templateId, text0, text1, cb) {
// format the request
var data = {
template_id: templateId,
username: me.username,
password: me.password,
text0: text0,
text1: text1
};
// send and return image if successful
request.post(
{
url: "https://api.imgflip.com/caption_image",
form: data
},
function (err, httpResponse, body) {
if (err) {
cb(err);
}
else {
try {
body = JSON.parse(body);
} catch (err) {
return cb(new Error('Imgflip did not return a json body'));
}
if (!body.success) {
cb(new Error(body.error_message));
}
else {
cb(null, body.data.url);
}
}
}
);
};
// ## generateMemeImage
//
// generates a meme image and writes to the specified file stream
// cb(err)
this.generateMemeImage = function (templateId, text0, text1, fstream, cb) {
me.generateMeme(templateId, text0, text1, function (err, url) {
if (err) {
cb(err);
}
else {
request
.get(url)
.on("error", cb)
.on("end", function () {
cb();
})
.pipe(fstream);
}
});
};
}
module.exports = Imgflipper;