|
| 1 | +const concat = require('concat-stream') |
| 2 | +const fs = require('fs') |
| 3 | +const http = require('http') |
| 4 | +const https = require('https') |
| 5 | +const mkdirp = require('mkdirp') |
| 6 | +const path = require('path') |
| 7 | +const parse = require('url').parse |
| 8 | + |
| 9 | +const DEFAULT_CACHE_DIRECTORY = `${process.env.HOME}/.flyle` |
| 10 | +const DEFAULT_PNG = path.resolve(__dirname, '../mastarm.png') |
| 11 | + |
| 12 | +module.exports = function (req, res) { |
| 13 | + const url = parse(req.url, true).query.url |
| 14 | + const isHttps = url.indexOf('https') !== -1 |
| 15 | + const get = isHttps ? https.get : http.get |
| 16 | + const filePath = isHttps ? url.split('https://')[1] : url.split('http://')[1] |
| 17 | + const fullPath = path.resolve(DEFAULT_CACHE_DIRECTORY, filePath) |
| 18 | + fs.stat(fullPath, (err, stats) => { |
| 19 | + if (!err && stats.isFile()) { |
| 20 | + sendImg({path: fullPath, res}) |
| 21 | + } else { |
| 22 | + get(url, (fileResponse) => { |
| 23 | + mkdirp(path.dirname(fullPath), (err) => { |
| 24 | + if (err) { |
| 25 | + logAndSend({err, res}) |
| 26 | + } else { |
| 27 | + fileResponse.pipe(concat((png) => { |
| 28 | + fs.writeFile(fullPath, png, (err) => { |
| 29 | + if (err) { |
| 30 | + logAndSend({err, res}) |
| 31 | + } else { |
| 32 | + sendImg({path: fullPath, res}) |
| 33 | + } |
| 34 | + }) |
| 35 | + })) |
| 36 | + } |
| 37 | + }) |
| 38 | + }).on('error', (err) => { |
| 39 | + logAndSend({err, res}) |
| 40 | + }) |
| 41 | + } |
| 42 | + }) |
| 43 | +} |
| 44 | + |
| 45 | +function logAndSend ({err, res}) { |
| 46 | + console.error('flyle >> sending default image: ', err.message) |
| 47 | + sendImg({ |
| 48 | + path: DEFAULT_PNG, |
| 49 | + res |
| 50 | + }) |
| 51 | +} |
| 52 | + |
| 53 | +function sendImg ({path, res}) { |
| 54 | + res.writeHead(200, { |
| 55 | + 'Content-Type': 'image/png' |
| 56 | + }) |
| 57 | + fs.createReadStream(path).pipe(res) |
| 58 | +} |
0 commit comments