-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.js
More file actions
76 lines (63 loc) · 2.27 KB
/
app.js
File metadata and controls
76 lines (63 loc) · 2.27 KB
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
var express = require('express');
var http = require('http');
var ejs = require('ejs');
var url = require('url');
var request = require('request');
var fs = require('fs');
var port = process.env.PORT || 3000;
var app = express();
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res) {
res.end("<p>get gif</p>" +
'<p>example: http://getgif.azurewebsites.net/gif/funny/dog.gif searches giphy for the tags "funny" and "dog" and returns the first gif it finds with those tags.</p>' +
'<p>The last term must end with ".gif" if you want to use it in hipchat.</p>'
);
})
app.get('/*', function(req, res) {
var gif = false;
var path = url.parse(req.url).pathname;
path = path.substring(5);
var terms = path.split("/").join("+");
terms = terms.split('.');
if (terms[1] === 'gif') {
var gif = true;
terms = terms[0];
} else {
var gif = false;
terms = terms[0];
}
var stuff = "http://api.giphy.com/v1/gifs/search?q=" + terms + "&api_key=dc6zaTOxFJmzC&limit=1";
request(stuff, function(error, response, body) {
try {
var image = JSON.parse(body).data[0].images.original;
// http.get(image.url).on('response', function (response) {
if (gif === true) {
res.writeHead(301,{'Content-Type':'text/html', 'Location': image.url});
} else {
var loc = 'http://getgif.azurewebsites.net/gif/' + path + '.gif';
console.log('LOC', loc);
res.writeHead(301,{'Content-Type':'text/html', 'Location': loc});
}
res.end();
// response.on('data', function(chunk) {
// res.write(chunk);
// });
// response.on('end', function() {
// res.end();
// });
// });
} catch (err) {
res.writeHead(301,{'Content-Type':'text/html', 'Location': 'http://media4.giphy.com/media/zLCiUWVfex7ji/giphy.gif'});
res.end();
// res.writeHead(200,{'Content-Type':'image/GIF'});
// var img = fs.readFileSync(__dirname + '/public/default.gif');
// res.sendFile(__dirname + '/public/default.gif')
// res.end(img, 'binary');
}
});
});
var server = app.listen(port, function() {
console.log("Listening on port %d", port);
});