You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
video-player/index.js

141 lines
2.6 KiB
JavaScript

const fs = require('fs');
const path = require('path');
const express = require('express');
const app = express();
const fileUpload = require('express-fileupload');
app.use(express.json());
app.use(fileUpload());
const port = 8080;
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
app.use(express.static('public'));
let videoDirs = [
'./public/videos',
'/media/pi',
'/video'
];
let fileEndings = [
'.mp4',
'.mkv',
'.avi',
'.mov',
'.flv',
'.wmv',
'.webm',
'.m4v',
'.mpg',
'.mpeg',
'.3gp',
'.3g2',
'.m2v',
'.m4v'
];
app.get('/videos', (req, res) => {
const list = [];
for (const dir of videoDirs) {
try {
if (!fs.existsSync(dir)) {
continue;
}
fs.readdirSync(dir, { recursive: true }).forEach(fileName => {
if (!fileEndings.includes(path.extname(fileName))) {
return;
}
const file = {
name: fileName,
path: path.resolve(dir, fileName)
};
list.push(file);
});
}
catch (error) {
console.error(error);
}
}
res.json(list);
});
let process = null;
let mayRestart = false;
// if (fs.existsSync('/tmp/video')) {
// const initialVideo = fs.readFileSync('/tmp/video');
// startVideo(initialVideo);
// }
function startVideo(path) {
process = require('child_process').spawn('ffplay', ['-fs', '-loop', '2147483647', '-hide_banner', '-loglevel', 'error', path]);
process.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});
process.stderr.on('data', (data) => {
console.error(`stderr: ${data}`);
});
process.on("exit", () => {
if (!mayRestart) {
startVideo(path);
}
});
}
fs.mkdirSync('/video', { recursive: true });
app.post('/play', (req, res) => {
if (process) {
mayRestart = true;
process.kill();
mayRestart = false;
}
let video = req.query.video;
console.log(video);
if (video.startsWith('/media/pi')) {
fs.copyFileSync(video, path.join('/video/', path.basename(video)));
video = path.join('/video/', path.basename(video))
}
fs.writeFileSync('/tmp/video', video);
startVideo(video);
res.json({ status: 'ok' });
});
app.post('/upload', function (req, res) {
if (!req.files || Object.keys(req.files).length === 0) {
return res.status(400).send('No files were uploaded.');
}
// The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file
const uploadPath = path.join(__dirname, '/public/videos/');
req.files.file.mv(uploadPath + "video.mp4", function (err) {
if (err) {
return res.status(500);
}
});
try {
require('child_process').spawn('sudo', ['systemctl', 'restart', 'video-player2.service']);
} catch (error) {
console.error(error);
}
res.redirect('/');
});