/** * 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