maotube/index.js

176 lines
5.9 KiB
JavaScript
Raw Permalink Normal View History

2024-01-18 23:45:23 +00:00
import express from "express";
import cors from "cors";
import bcrypt from "bcrypt";
import fileUpload from "express-fileupload";
import path from "path";
import childProcess from "child_process";
2024-01-19 02:10:56 +00:00
import levenshtein from "js-levenshtein";
2024-01-19 02:44:55 +00:00
import cookieParser from "cookie-parser";
import { fileURLToPath } from 'url';
2024-01-18 23:45:23 +00:00
const users = [];
let sessions = [];
const videos = [];
function randomString(length) {
const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789";
let result = "";
for (let i = 0; i < length; ++i) {
2024-01-19 02:44:55 +00:00
result += chars[Math.floor(chars.length * Math.random())];
2024-01-18 23:45:23 +00:00
}
return result;
}
2024-01-19 02:44:55 +00:00
function dirname() {
return path.dirname(fileURLToPath(import.meta.url));
}
2024-01-18 23:45:23 +00:00
const app = express();
app.use(cors());
app.use(express.json());
2024-01-19 02:44:55 +00:00
app.use(cookieParser());
2024-01-18 23:45:23 +00:00
app.use(express.urlencoded({ extended: true }));
app.use("/", express.static("public/"));
app.use("/videos", express.static("videos/"));
app.post("/api/register", async (req, res) => {
const { username, password } = req.body;
if (typeof username !== "string" || typeof password !== "string") {
return res.status(400).json({ ok: false, error: "bad request" });
}
const existingUser = users.find(user => user.username === username);
2024-01-19 02:10:56 +00:00
if (existingUser !== undefined) {
2024-01-18 23:45:23 +00:00
return res.status(400).json({ ok: false, error: "username taken" });
}
const passwordHash = await bcrypt.hash(password, 10);
const id = users.length;
2024-01-19 20:56:47 +00:00
const user = { id, username, passwordHash };
2024-01-18 23:45:23 +00:00
users.push(user);
return res.status(200).json({ ok: true, user });
});
app.post("/api/login", async (req, res) => {
const { username, password } = req.body;
if (typeof username !== "string" || typeof password !== "string") {
return res.status(400).json({ ok: false, error: "bad request" });
}
const user = users.find(user => user.username === username);
if (user === undefined) {
return res.status(400).json({ ok: false, error: "wrong username/password" });
}
2024-01-19 20:56:47 +00:00
if (!await bcrypt.compare(password, user.passwordHash)) {
2024-01-18 23:45:23 +00:00
return res.status(400).json({ ok: false, error: "wrong username/password" });
}
sessions = sessions.filter(session => session.userId !== user.id);
const token = randomString(64);
const session = { userId: user.id, token };
sessions.push(session);
res.clearCookie("token");
res.cookie("token", token);
return res.status(200).json({ ok: true, session });
});
2024-01-19 02:10:56 +00:00
app.get("/api/search", async (req, res) => {
const page = +req.query.page || 0;
const search = req.query.query;
if (!search) {
return res.status(400).json({ ok: false, error: "bad request" });
}
const [start, end] = [20 * page, 20 * (page + 1)];
2024-01-19 03:22:22 +00:00
const withDistance = videos
2024-01-19 07:43:13 +00:00
.map(video => ({ dist: levenshtein(search, video.title), ...video }));
2024-01-19 03:22:22 +00:00
withDistance.sort((a, b) => a.dist - b.dist);
const returnedVideos = withDistance
2024-01-19 02:10:56 +00:00
.slice(start, end)
.map(video => {
2024-01-19 02:44:55 +00:00
const user = users.find(user => user.id === video.userId);
2024-01-19 02:10:56 +00:00
if (!user) {
2024-01-19 07:43:13 +00:00
return { ...video, author: "[Liberal]" };
2024-01-19 02:10:56 +00:00
}
2024-01-19 07:43:13 +00:00
return { ...video, author: user.username };
2024-01-19 02:10:56 +00:00
});
return res.status(200).json({ ok: true, videos: returnedVideos, total: videos.length });
});
2024-01-18 23:45:23 +00:00
function authorized() {
return (req, res, next) => {
const token = (() => {
2024-01-19 02:44:55 +00:00
if (req.cookies && "token" in req.cookies) {
2024-01-18 23:45:23 +00:00
return req.cookies["token"];
} else if ("token" in req.query) {
return req.query["token"];
} else if (req.method === "post" && "token" in req.body) {
return req.body["token"];
} else {
return null;
}
})();
if (token === null) {
2024-01-19 02:44:55 +00:00
return res.status(400).json({ ok: false, error: "unauthorized" });
2024-01-18 23:45:23 +00:00
}
const session = sessions.find(session => session.token === token);
if (session === undefined) {
2024-01-19 02:44:55 +00:00
return res.status(400).json({ ok: false, error: "unauthorized" });
2024-01-18 23:45:23 +00:00
}
2024-01-19 02:44:55 +00:00
const user = users.find(user => user.id === session.userId);
2024-01-18 23:45:23 +00:00
if (user === undefined) {
throw new Error("error: session with invalid userId");
}
req.user = user;
next();
}
}
app.get("/api/logout", authorized(), (req, res) => {
sessions = sessions.filter(session => session.userId !== req.user.id);
return res.status(200).json({ ok: true });
});
app.post("/api/upload_video", authorized(), fileUpload({ limits: { fileSize: 2 ** 26 }, useTempFiles: true }), async (req, res) => {
const { title } = req.body;
2024-01-19 02:44:55 +00:00
if (!req.files || !req.files.video) {
2024-01-18 23:45:23 +00:00
return res.status(400).json({ ok: false, error: "bad request" });
}
2024-01-19 02:44:55 +00:00
if (req.files.video.mimetype !== "video/mp4") {
2024-01-18 23:45:23 +00:00
return res.status(400).json({ ok: false, error: "bad mimetype" });
}
const userId = req.user.id;
const id = randomString(4);
2024-01-19 02:44:55 +00:00
const tempPath = req.files.video.tempFilePath;
const newPath = path.join(dirname(), "videos", `${id}.mp4`);
console.log(newPath);
2024-01-18 23:45:23 +00:00
const exitCode = await new Promise((resolve, _reject) => {
2024-01-19 07:43:13 +00:00
const process = childProcess.spawn("HandBrakeCLI", ["-i", tempPath, "-o", newPath, "-Z", "Social 25 MB 5 Minutes 360p60"]);
2024-01-18 23:45:23 +00:00
process.stderr.on("data", (data) => {
2024-01-19 02:44:55 +00:00
console.error(data.toString());
2024-01-18 23:45:23 +00:00
});
process.on("close", (code) => {
resolve(code);
})
2024-01-19 02:44:55 +00:00
})
2024-01-18 23:45:23 +00:00
if (exitCode !== 0) {
2024-01-19 03:22:22 +00:00
throw new Error("handbrake failed");
2024-01-18 23:45:23 +00:00
}
const video = {
id,
userId,
title,
path: newPath,
};
videos.push(video);
return res.status(200).json({ ok: true, video });
})
app.use((err, req, res, next) => {
console.error(err);
res.status(500).json({ ok: false, error: "server error" })
});
app.listen(8000, () => {
console.log("app at http://localhost:8000/");
})