'use strict'; const Promise = require("bluebird"); const functionRateLimit = require("function-rate-limit"); const validatorAdd = require("../validators/disk-images/add"); module.exports = function({db, imageStore}) { const dbDiskImages = require("../db/disk-images")({db}); let router = require("express-promise-router")(); router.get("/", (req, res) => { return Promise.try(() => { return dbDiskImages.getAll(); }).then((results) => { res.render("disk-images/list", { images: results }); }); }); router.get("/add", (req, res) => { res.render("disk-images/add"); }); router.post("/add", (req, res) => { return Promise.try(() => { return validatorAdd.validate(req.body); }).then((result) => { /* FIXME: Only allow 'local' for administrators! */ if (req.body.source === "http") { return Promise.try(() => { return imageStore.addFromUrl(req.body.url); }).then((downloadTracker) => { downloadTracker.on("progress", functionRateLimit(1, 200, (progress, description) => { /* FIXME: This is getting debounced to a point of pointlessness as it will only fire when the download is completed. Needs to be replaced by SSE events anyway, and rate-limited instead of debounced. */ console.log("Download progress:", (Math.round(progress * 10000) / 100), "%"); })); return downloadTracker.await(); }); } else if (req.body.source === "local") { return imageStore.addFromPath(req.body.path); } }).then((imageId) => { let source; if (req.body.source === "http") { source = req.body.url; } else if (req.body.source === "local") { source = req.body.path; } return dbDiskImages.addInstallISO({ userId: 0, fileId: imageId, name: req.body.name, description: req.body.description, sourceType: req.body.source, source: source, isPublic: true }); }).then(() => { res.redirect("/disk-images"); }); }); return router; }