|
|
@ -0,0 +1,88 @@ |
|
|
|
|
|
const request = require('request') |
|
|
|
|
|
const sharp = require('sharp') |
|
|
|
|
|
const { MongoClient, ObjectId } = require('mongodb') |
|
|
|
|
|
const express = require('express') |
|
|
|
|
|
const app = express() |
|
|
|
|
|
const fs = require('fs') |
|
|
|
|
|
const path = require('path') |
|
|
|
|
|
const cors = require('cors') |
|
|
|
|
|
|
|
|
|
|
|
// const resizeBox = sharp().resize(512).png()
|
|
|
|
|
|
|
|
|
|
|
|
const CTX = { |
|
|
|
|
|
dbHandler: null |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
const CFG = { |
|
|
|
|
|
port: process.env.PORT || 3000 |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
app.use(cors()) |
|
|
|
|
|
|
|
|
|
|
|
app.get('/preview/:id', function (req, res) { |
|
|
|
|
|
CTX.dbHandler |
|
|
|
|
|
.collection('hboxes') |
|
|
|
|
|
.find({_id: ObjectId(req.params.id)}) |
|
|
|
|
|
.project({preview: 1}) |
|
|
|
|
|
.limit(1) |
|
|
|
|
|
.next(function (pErr, pDoc) { |
|
|
|
|
|
if (pErr) { |
|
|
|
|
|
return res.status(404).json(pErr) |
|
|
|
|
|
} |
|
|
|
|
|
downloadBox(pDoc._id, pDoc.preview.secure_url, res) |
|
|
|
|
|
}) |
|
|
|
|
|
}) |
|
|
|
|
|
|
|
|
|
|
|
app.use('/', express.static('webapp')) |
|
|
|
|
|
|
|
|
|
|
|
MongoClient.connect('mongodb://localhost:27017', { useNewUrlParser: true }, function (pErr, pDbHandler) { |
|
|
|
|
|
if (pErr) { |
|
|
|
|
|
console.error(pErr) |
|
|
|
|
|
process.exit(1) |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
CTX.dbHandler = pDbHandler.db('hortus-box') |
|
|
|
|
|
|
|
|
|
|
|
app.listen(CFG.port, function () { |
|
|
|
|
|
console.log(`[>] pwa-server running on ${CFG.port}`) |
|
|
|
|
|
}) |
|
|
|
|
|
}) |
|
|
|
|
|
|
|
|
|
|
|
function downloadBox (pId, pUrl, res) { |
|
|
|
|
|
let cachePath = path.join('./cache', `${pId}.png`) |
|
|
|
|
|
|
|
|
|
|
|
fs.access(cachePath, fs.constants.F_OK, function (pErr) { |
|
|
|
|
|
if (pErr) { |
|
|
|
|
|
let wstream = fs.createWriteStream(cachePath) |
|
|
|
|
|
request(pUrl).pipe(wstream) |
|
|
|
|
|
wstream.on('finish', function () { |
|
|
|
|
|
resizeBox(pId, cachePath, res) |
|
|
|
|
|
}) |
|
|
|
|
|
} else { |
|
|
|
|
|
resizeBox(pId, cachePath, res) |
|
|
|
|
|
} |
|
|
|
|
|
}) |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
function resizeBox (pId, pCachePath, res) { |
|
|
|
|
|
let previewPath = path.join('./cache', `${pId}.preview.png`) |
|
|
|
|
|
|
|
|
|
|
|
fs.access(previewPath, fs.constants.F_OK, function (pErr) { |
|
|
|
|
|
if (pErr) { |
|
|
|
|
|
sharp(pCachePath) |
|
|
|
|
|
.resize(512) |
|
|
|
|
|
.toFile(previewPath, function (pErr, info) { |
|
|
|
|
|
if (pErr) { |
|
|
|
|
|
return res.status(404).json(pErr) |
|
|
|
|
|
} |
|
|
|
|
|
sendBox(previewPath, res) |
|
|
|
|
|
}) |
|
|
|
|
|
} else { |
|
|
|
|
|
sendBox(previewPath, res) |
|
|
|
|
|
} |
|
|
|
|
|
}) |
|
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
function sendBox (pPreviewPath, res) { |
|
|
|
|
|
fs.createReadStream(pPreviewPath).pipe(res) |
|
|
|
|
|
} |