'use strict'; const router = require('express').Router(); const {Torrent} = require('>/models'); const organize = require('>/controller/organize'); function authTorrent(torrent, req){ if(torrent && torrent.isPrivate && torrent.added_by !== req.user.username){ let error = new Error('TorrentNotFound'); error.name = 'TorrentNotFound'; error.message = 'Torrent not found'; error.status = 404; throw error; } return torrent; } router.get('/', async function(req, res, next){ try{ let username = req.query.username || req.user.username; let where = {added_by: username}; if(username !== req.user.username) where.isPrivate = false; res.json({results: await Torrent.findAll({ where, limit: req.query.limit, offset: req.query.offset, order: [ ['createdAt', 'DESC'], ], })}); }catch(error){ next(error); } }); router.post("/", async function(req, res, next){ try{ res.json(await Torrent.create({...req.body, added_by: req.user.username})) }catch(error){ next(error); } }); router.get('/server', async function(req, res, next){ try{ res.json(await Torrent.trClient.sessionStats()) }catch(error){ next(error); } }); router.get("/:hashString", async function(req, res, next){ try{ let torrent = authTorrent(await Torrent.findByPk(req.params.hashString), req); if('latest' in req.query){ torrent = await torrent.getTorrentData(); } res.json({result: torrent}); }catch(error){ next(error); } }); router.delete("/:hashString", async function(req, res, next){ try{ let torrent = authTorrent(await Torrent.findByPk(req.params.hashString), req); res.json({result: torrent, activity: await torrent.destroy()}); }catch(error){ next(error); } }); router.post("/:hashString/stop", async function(req, res, next){ try{ let torrent = authTorrent(await Torrent.findByPk(req.params.hashString), req); res.json({result: torrent, activity: await torrent.stop()}); }catch(error){ next(error); } }); router.post("/:hashString/start", async function(req, res, next){ try{ let torrent = authTorrent(await Torrent.findByPk(req.params.hashString), req); res.json({result: torrent, activity: await torrent.start()}); }catch(error){ next(error); } }); // Manually (re)run organization for a finished torrent. router.post("/:hashString/organize", async function(req, res, next){ try{ let torrent = authTorrent(await Torrent.findByPk(req.params.hashString), req); if(!torrent){ let e = new Error('TorrentNotFound'); e.status = 404; throw e; } res.json(await organize.fileTorrent(torrent)); }catch(error){ next(error); } }); // Correct a wrong match: re-file an already-organized torrent under a chosen TMDB id. router.post("/:hashString/organize/match", async function(req, res, next){ try{ let torrent = authTorrent(await Torrent.findByPk(req.params.hashString), req); if(!torrent){ let e = new Error('TorrentNotFound'); e.status = 404; throw e; } res.json(await organize.refileWithMatch(torrent, req.body.tmdbId, req.body.mediaType)); }catch(error){ next(error); } }); module.exports = router;