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
|
/**
* Service scrapes Instagram for pictures since they've ruined their API.
* Set it up in services config with the following options:
instagram: {
username: 'annapurnapics',
frequency: 60 * 60 * 1000,
},
*/
var request = require('request')
function OKInstagram (options) {
if (!(this instanceof OKInstagram)) return new OKInstagram(options)
options = options || {}
if (!options.express)
throw new Error('Express not provided to OKInstagram');
if (!options.config || !options.config.username)
throw new Error('Username not provided to OKInstagram');
var express = options.express
var router = express.Router()
var username = options.config.username
var frequency = options.config.frequency || 60 * 60 * 1000 // hourly
var posts = []
router.get('/', function (req, res) {
res.set('Content-Type', 'application/json; charset=utf-8')
res.send(posts)
})
router.get('/fetch', function (req, res) {
res.send('Fetching now')
setTimeout(fetch)
})
function go () {
fetch(function(){
setTimeout(go, frequency)
})
}
function fetch (cb) {
request('https://www.instagram.com/' + username + '/', function (err, response, body) {
if (err || response.statusCode !== 200) {
console.error("error fetching instagrams")
cb && cb()
return
}
if (! body.match(/"nodes": \[/)) {
console.error("instagram format has changed")
cb && cb()
return
}
var node_first = body.split(/"nodes": \[/)[1]
var node_list = node_first.split(/\]/)[0]
var nodes = JSON.parse("[" + node_list + "]")
posts = nodes.map(function(node){
var post = {
url: "https://www.instagram.com/p/" + node.code,
img: node.thumbnail_src,
caption: node.caption || "",
}
return post
})
cb && cb()
})
}
router.post('*', function (req, res) {
throw new Error('OKInstagram POST requests not implemented')
})
if (frequency)
go()
this._router = router
}
OKInstagram.prototype.middleware = function () {
return this._router
}
module.exports = OKInstagram
|