serve-lunasqu.ee/applications/distrib-ipfs/index.js

49 lines
1.7 KiB
JavaScript
Raw Normal View History

2019-02-05 16:27:36 +00:00
const express = require('express')
const path = require('path')
const sqlite = require('sqlite')
const crypto = require('crypto')
const router = express.Router()
const cfgLoader = require(path.join('..', '..', 'config-loader'))(path.join(__dirname, 'config.json'), {
database: 'shortened.db',
gateway: 'https://distributed.icynet.eu',
tokens: {}
})
async function init () {
let config = await cfgLoader
const dbPromise = Promise.resolve()
.then(() => sqlite.open(path.join(__dirname, config.database), { Promise, cache: true }))
.then(db => db.migrate({ migrationsPath: path.join(__dirname, 'migrations') }))
router.get('/:hash', async (req, res, next) => {
let db = await dbPromise
let translation = await db.get('SELECT * FROM Translation WHERE translation = ?', req.params.hash)
if (!translation) return res.status(404).end()
res.header('Cache-Control', 'max-age=' + 7 * 24 * 60 * 60 * 1000)
res.redirect(config.gateway + '/ipfs/' + translation.file_hash)
})
router.post('/publish', async (req, res, next) => {
let token = req.header('token') || req.body.token
if (!token || !config.tokens[token]) return res.status(402).send('Forbidden')
let baseurl = config.tokens[token]
let hash = req.query.hash || req.body.hash
let filename = req.query.filename || req.body.filename
if (!hash) return res.status(400).send('Invalid request: missing IPFS hash')
if (!filename) filename = crypto.randomBytes(8).toString('hex')
let db = await dbPromise
await db.run('INSERT INTO Translation (translation,file_hash,timeat) VALUES (?,?,?)', filename, hash, new Date())
res.send(baseurl + filename)
})
return router
}
module.exports = init