server: move mediainfo function from util to api

This commit is contained in:
Jesse Chan
2020-10-28 11:25:55 +08:00
parent 9505a62204
commit e90cdcdc22
2 changed files with 41 additions and 51 deletions
+41 -3
View File
@@ -1,3 +1,4 @@
import childProcess from 'child_process';
import createTorrent from 'create-torrent';
import express from 'express';
import fs from 'fs';
@@ -23,7 +24,6 @@ import {
import {accessDeniedError, isAllowedPath, sanitizePath} from '../../util/fileUtil';
import ajaxUtil from '../../util/ajaxUtil';
import {getTempPath} from '../../models/TemporaryStorage';
import mediainfo from '../../util/mediainfo';
const router = express.Router();
@@ -530,8 +530,46 @@ router.get('/:hash/details', async (req, res) => {
* @param {string} hash.path
* @return {{output: string}} - 200 - success response - application/json
*/
router.get('/:hash/mediainfo', (req, res) => {
mediainfo.getMediainfo(req.services, req.params.hash, ajaxUtil.getResponseFn(res));
router.get('/:hash/mediainfo', async (req, res) => {
const {hash} = req.params;
const callback = ajaxUtil.getResponseFn(res);
const {torrentService} = req.services || {};
if (typeof hash !== 'string' || torrentService == null) {
callback(null, new Error());
return;
}
const torrent = torrentService.getTorrent(hash);
if (torrent == null) {
callback(null, new Error());
return;
}
try {
const mediainfoProcess = childProcess.execFile(
'mediainfo',
[torrent.basePath],
{maxBuffer: 1024 * 2000},
(error, stdout, stderr) => {
if (error) {
callback(null, error);
return;
}
if (stderr) {
callback(null, Error(stderr));
return;
}
callback({output: stdout});
},
);
req.on('close', () => mediainfoProcess.kill('SIGTERM'));
} catch (childProcessError) {
callback(null, Error(childProcessError));
}
});
/**
-48
View File
@@ -1,48 +0,0 @@
import {TorrentProperties} from '@shared/types/Torrent';
import childProcess from 'child_process';
import type {Request} from 'express';
export default {
getMediainfo(
services: Request['services'],
hash: TorrentProperties['hash'],
callback: (data: {output: string} | null, error?: Error) => void,
) {
const torrentService = services?.torrentService;
if (torrentService == null) {
callback(null, Error('Torrent service is not initialized'));
return;
}
if (hash == null) {
callback(null, Error('Hash must be defined'));
return;
}
const selectedTorrent = torrentService.getTorrent(hash);
try {
childProcess.execFile(
'mediainfo',
[selectedTorrent.basePath],
{maxBuffer: 1024 * 2000},
(error, stdout, stderr) => {
if (error) {
callback(null, error);
return;
}
if (stderr) {
callback(null, Error(stderr));
return;
}
callback({output: stdout});
},
);
} catch (childProcessError) {
callback(null, Error(childProcessError));
}
},
};