-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.js
More file actions
97 lines (86 loc) · 2.21 KB
/
app.js
File metadata and controls
97 lines (86 loc) · 2.21 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
var express = require('express'),
extractor = require('unfluff'),
request = require('request'),
http = require('http'),
url = require('url'),
mongo = require('mongodb'),
test = require('assert'),
app = express();
const port = 3000;
const db_name = "reddit";
const mongo_url = "mongodb://mongo:27017/" + db_name;
app.use(function(req, res, next) {
// Setup cors headers.
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use(function(req, res, next) {
// Add the db to the router.
mongo.connect(mongo_url, function(err, db) {
req.db = db;
next();
});
});
/*
Database Functions
*/
var find_url = function(db, url, callback){
// If the url is in the database, return whatever json blob you get.
var collection = db.collection('unfluff');
collection.findOne({url:url}, {}, (err, doc)=>{
callback(doc);
});
}
var insert_url = function(db, url, blob, callback){
var collection = db.collection('unfluff');
collection.insertOne({
url: url,
blob: blob
}, {}, callback);
}
/*
Routes
*/
app.get('/', function (req, res) {
res.send('Unfluff-server')
});
app.get('/unfluff', function (req, res){
var unfluff_url = req.query.url;
find_url(req.db, unfluff_url, (result)=>{
if (result != null){
res.json(result.blob);
} else {
request(unfluff_url, (error, response, html)=>{
if (!error){
var data = extractor(html);
insert_url(req.db, unfluff_url, data, ()=>{
console.log("Inserted " + unfluff_url);
});
res.json(data);
} else {
res.json({
error: error
});
}
});
}
});
});
app.get('/twitter', function (req, res) {
var twitter_url = req.query.url;
var oEmbed_url = "https://publish.twitter.com/oembed?url=";
request(oEmbed_url + twitter_url, (error, response, jason)=>{
if (!error){
var parsed = JSON.parse(jason);
res.json(parsed);
} else {
res.json({
error: error
});
}
});
});
app.listen(port, function () {
console.log('redditAccessible ufluff listening on ' + port);
});