reorg: separate frontend and backend

This commit is contained in:
2025-02-23 11:45:40 -08:00
parent b2b70f3eb1
commit b3cf5fb3c8
12 changed files with 7752 additions and 2154 deletions

102
backend/src/InvidiousAPI.ts Normal file
View File

@@ -0,0 +1,102 @@
import fetch from 'node-fetch';
interface InvidiousVideoThumbnail {
quality: string;
url: string;
width: number;
height: number;
}
interface InvidiousResult {
type: string;
title: string;
videoId: string;
playlistId: string;
author: string;
videoThumbnails?: InvidiousVideoThumbnail[];
}
export interface SearchResult {
type: string;
title: string;
author: string;
mediaUrl: string;
thumbnailUrl: string;
}
export interface ThumbnailResponse {
data: NodeJS.ReadableStream;
contentType: string;
}
const USE_INVIDIOUS = process.env.USE_INVIDIOUS || true;
const INVIDIOUS_BASE_URL = process.env.INVIDIOUS_BASE_URL || 'http://invidious.nor';
const INVIDIOUS_API_ENDPOINT = `${INVIDIOUS_BASE_URL}/api/v1`;
export const getInvidiousSearchURL = (query: string): string =>
`${INVIDIOUS_API_ENDPOINT}/search?q=${encodeURIComponent(query)}`;
export const getInvidiousThumbnailURL = (url: string): string =>
`${INVIDIOUS_BASE_URL}/${url}`;
const preferredThumbnailAPIURL = (thumbnails: InvidiousVideoThumbnail[] | undefined): string => {
if (!thumbnails || thumbnails.length === 0) {
return '/assets/placeholder.jpg';
}
const mediumThumbnail = thumbnails.find(t => t.quality === 'medium');
const thumbnail = mediumThumbnail || thumbnails[0];
return `/api/thumbnail?url=${encodeURIComponent(thumbnail.url)}`;
};
const getMediaURL = (result: InvidiousResult): string => {
if (result.type === 'video') {
return `https://www.youtube.com/watch?v=${result.videoId}`;
} else if (result.type === 'playlist') {
return `https://www.youtube.com/playlist?list=${result.playlistId}`;
}
throw new Error(`Unknown result type: ${result.type}`);
};
export const searchInvidious = async (query: string): Promise<SearchResult[]> => {
try {
const response = await fetch(getInvidiousSearchURL(query));
if (!response.ok) {
throw new Error(`Invidious HTTP error: ${response.status}`);
}
const data = await response.json() as Array<InvidiousResult>;
return data.filter(item => {
return item.type === 'video' || item.type === 'playlist';
}).map(item => ({
type: item.type,
title: item.title,
author: item.author,
mediaUrl: getMediaURL(item),
thumbnailUrl: preferredThumbnailAPIURL(item.videoThumbnails)
}));
} catch (error) {
console.error('Failed to search Invidious:', error);
throw error;
}
}
export const fetchThumbnail = async (thumbnailUrl: string): Promise<ThumbnailResponse> => {
let path = thumbnailUrl;
if (thumbnailUrl.startsWith('http://') || thumbnailUrl.startsWith('https://')) {
const url = new URL(thumbnailUrl);
path = url.pathname + url.search;
}
path = path.replace(/^\/+/, ''); // Strip leading slash
const response = await fetch(getInvidiousThumbnailURL(path));
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return {
data: response.body,
contentType: response.headers.get('content-type') || 'image/jpeg'
};
};

268
backend/src/MediaPlayer.ts Normal file
View File

@@ -0,0 +1,268 @@
import { ChildProcess, spawn } from "child_process";
import { Socket } from "net";
import { WebSocket } from "ws";
import { getLinkPreview } from "link-preview-js";
interface PendingCommand {
resolve: (value: any) => void;
reject: (reason: any) => void;
}
interface LinkMetadata {
title?: string;
description?: string;
siteName?: string;
}
interface PlaylistItem {
id: number;
filename: string;
title?: string;
playing?: boolean;
current?: boolean;
metadata?: LinkMetadata;
}
export class MediaPlayer {
private playerProcess: ChildProcess;
private socket: Socket;
private eventSubscribers: WebSocket[] = [];
private pendingCommands: Map<number, PendingCommand> = new Map();
private requestId: number = 1;
private dataBuffer: string = '';
private metadata: Map<string, LinkMetadata> = new Map();
constructor() {
const socketFilename = Math.random().toString(36).substring(2, 10);
const socketPath = `/tmp/mpv-${socketFilename}`;
console.log("Starting player process");
this.playerProcess = spawn("mpv", [
"--no-video",
"--no-terminal",
"--idle=yes",
"--input-ipc-server=" + socketPath
]);
this.socket = new Socket();
this.playerProcess.on("spawn", () => {
console.log(`Player process spawned, opening socket @ ${socketPath}`);
setTimeout(() => {
this.connectToSocket(socketPath);
}, 500);
});
}
public async getPlaylist(): Promise<PlaylistItem[]> {
return this.writeCommand("get_property", ["playlist"])
.then((response) => {
// Enhance playlist items with metadata
const playlist = response.data as PlaylistItem[];
return playlist.map((item: PlaylistItem) => ({
...item,
metadata: this.metadata.get(item.filename) || {}
}));
});
}
public async getNowPlaying(): Promise<PlaylistItem> {
const playlist = await this.getPlaylist();
const currentlyPlayingSong = playlist.find((item: PlaylistItem) => item.current);
const fetchMediaTitle = async (): Promise<string> => {
return (await this.writeCommand("get_property", ["media-title"])).data;
};
if (currentlyPlayingSong !== undefined) {
// Use media title if we don't have a title
if (currentlyPlayingSong.title === undefined && currentlyPlayingSong.metadata?.title === undefined) {
return {
...currentlyPlayingSong,
title: await fetchMediaTitle()
};
}
return currentlyPlayingSong;
}
const mediaTitle = await fetchMediaTitle();
return {
id: 0,
filename: mediaTitle,
title: mediaTitle
};
}
public async getCurrentFile(): Promise<string> {
return this.writeCommand("get_property", ["stream-open-filename"])
.then((response) => {
return response.data;
});
}
public async getPauseState(): Promise<boolean> {
return this.writeCommand("get_property", ["pause"])
.then((response) => {
return response.data;
});
}
public async getVolume(): Promise<number> {
return this.writeCommand("get_property", ["volume"])
.then((response) => {
return response.data;
});
}
public async getIdle(): Promise<boolean> {
return this.writeCommand("get_property", ["idle"])
.then((response) => {
return response.data;
});
}
public async append(url: string) {
const result = await this.modify(() => this.writeCommand("loadfile", [url, "append-play"]));
// Asynchronously fetch the metadata for this after we update the playlist
this.fetchMetadataAndNotify(url).catch(error => {
console.warn(`Failed to fetch metadata for ${url}:`, error);
});
return result;
}
public async play() {
return this.modify(() => this.writeCommand("set_property", ["pause", false]));
}
public async pause() {
return this.modify(() => this.writeCommand("set_property", ["pause", true]));
}
public async skip() {
return this.modify(() => this.writeCommand("playlist-next", []));
}
public async skipTo(index: number) {
return this.modify(() => this.writeCommand("playlist-play-index", [index]));
}
public async previous() {
return this.modify(() => this.writeCommand("playlist-prev", []));
}
public async deletePlaylistItem(index: number) {
return this.modify(() => this.writeCommand("playlist-remove", [index]));
}
public async setVolume(volume: number) {
return this.modify(() => this.writeCommand("set_property", ["volume", volume]));
}
public subscribe(ws: WebSocket) {
this.eventSubscribers.push(ws);
}
public unsubscribe(ws: WebSocket) {
this.eventSubscribers = this.eventSubscribers.filter(subscriber => subscriber !== ws);
}
private async modify<T>(func: () => Promise<T>): Promise<T> {
return func()
.then((result) => {
// Notify all subscribers
this.handleEvent("user_modify", {});
return result;
});
}
private async writeCommand(command: string, args: any[]): Promise<any> {
return new Promise((resolve, reject) => {
const id = this.requestId++;
const commandObject = JSON.stringify({
command: [command, ...args],
request_id: id
});
this.pendingCommands.set(id, { resolve, reject });
this.socket.write(commandObject + '\n');
// Add timeout to prevent hanging promises
setTimeout(() => {
if (this.pendingCommands.has(id)) {
const pending = this.pendingCommands.get(id);
if (pending) {
pending.reject(new Error('Command timed out'));
this.pendingCommands.delete(id);
}
}
}, 5000);
});
}
private async fetchMetadataAndNotify(url: string) {
try {
const metadata = await getLinkPreview(url);
this.metadata.set(url, {
title: (metadata as any)?.title,
description: (metadata as any)?.description,
siteName: (metadata as any)?.siteName,
});
// Notify clients that metadata has been updated
this.handleEvent("metadata_update", {
url,
metadata: this.metadata.get(url)
});
} catch (error) {
throw error;
}
}
private connectToSocket(path: string) {
this.socket.connect(path);
this.socket.on("data", data => this.receiveData(data.toString()));
}
private handleEvent(event: string, data: any) {
console.log("MPV Event [" + event + "]: " + JSON.stringify(data, null, 2));
// Notify all subscribers
this.eventSubscribers.forEach(subscriber => {
subscriber.send(JSON.stringify({ event, data }));
});
}
private receiveData(data: string) {
this.dataBuffer += data;
const lines = this.dataBuffer.split('\n');
// Keep last incomplete line in the buffer
this.dataBuffer = lines.pop() || '';
for (const line of lines) {
if (line.trim().length > 0) {
try {
const response = JSON.parse(line);
if (response.request_id) {
const pending = this.pendingCommands.get(response.request_id);
if (pending) {
pending.resolve(response);
this.pendingCommands.delete(response.request_id);
}
} else if (response.event) {
this.handleEvent(response.event, response);
} else {
console.log(response);
}
} catch (error) {
console.error('Error parsing JSON:', error);
}
}
}
}
}

165
backend/src/server.ts Normal file
View File

@@ -0,0 +1,165 @@
import express from "express";
import expressWs from "express-ws";
import { MediaPlayer } from "./MediaPlayer";
import { searchInvidious, getInvidiousThumbnailURL, fetchThumbnail } from "./InvidiousAPI";
import fetch from "node-fetch";
const app = express();
app.use(express.json());
expressWs(app);
const apiRouter = express.Router();
const mediaPlayer = new MediaPlayer();
const withErrorHandling = (func: (req: any, res: any) => Promise<any>) => {
return async (req: any, res: any) => {
try {
await func(req, res);
} catch (error: any) {
res.status(500).send(JSON.stringify({ success: false, error: error.message }));
}
};
};
apiRouter.get("/playlist", withErrorHandling(async (req, res) => {
const playlist = await mediaPlayer.getPlaylist();
res.send(playlist);
}));
apiRouter.post("/playlist", withErrorHandling(async (req, res) => {
const { url } = req.body as { url: string };
await mediaPlayer.append(url);
res.send(JSON.stringify({ success: true }));
}));
apiRouter.delete("/playlist/:index", withErrorHandling(async (req, res) => {
const { index } = req.params as { index: string };
await mediaPlayer.deletePlaylistItem(parseInt(index));
res.send(JSON.stringify({ success: true }));
}));
apiRouter.post("/play", withErrorHandling(async (req, res) => {
await mediaPlayer.play();
res.send(JSON.stringify({ success: true }));
}));
apiRouter.post("/pause", withErrorHandling(async (req, res) => {
await mediaPlayer.pause();
res.send(JSON.stringify({ success: true }));
}));
apiRouter.post("/skip", withErrorHandling(async (req, res) => {
await mediaPlayer.skip();
res.send(JSON.stringify({ success: true }));
}));
apiRouter.post("/skip/:index", withErrorHandling(async (req, res) => {
const { index } = req.params as { index: string };
await mediaPlayer.skipTo(parseInt(index));
res.send(JSON.stringify({ success: true }));
}));
apiRouter.post("/previous", withErrorHandling(async (req, res) => {
await mediaPlayer.previous();
res.send(JSON.stringify({ success: true }));
}));
apiRouter.get("/nowplaying", withErrorHandling(async (req, res) => {
const playingItem = await mediaPlayer.getNowPlaying();
const currentFile = await mediaPlayer.getCurrentFile();
const pauseState = await mediaPlayer.getPauseState();
const volume = await mediaPlayer.getVolume();
const idle = await mediaPlayer.getIdle();
res.send(JSON.stringify({
success: true,
playingItem: playingItem,
isPaused: pauseState,
volume: volume,
isIdle: idle,
currentFile: currentFile
}));
}));
apiRouter.post("/volume", withErrorHandling(async (req, res) => {
const { volume } = req.body as { volume: number };
await mediaPlayer.setVolume(volume);
res.send(JSON.stringify({ success: true }));
}));
apiRouter.ws("/events", (ws, req) => {
console.log("Events client connected");
mediaPlayer.subscribe(ws);
ws.on("close", () => {
console.log("Events client disconnected");
mediaPlayer.unsubscribe(ws);
});
});
apiRouter.get("/search", withErrorHandling(async (req, res) => {
const query = req.query.q as string;
if (!query) {
res.status(400)
.send(JSON.stringify({ success: false, error: "Query parameter 'q' is required" }));
return;
}
const results = await searchInvidious(query);
res.send(JSON.stringify({ success: true, results }));
}));
apiRouter.get("/thumbnail", withErrorHandling(async (req, res) => {
const thumbnailUrl = req.query.url as string;
if (!thumbnailUrl) {
res.status(400)
.send(JSON.stringify({ success: false, error: "URL parameter is required" }));
return;
}
try {
const { data, contentType } = await fetchThumbnail(thumbnailUrl);
res.set('Content-Type', contentType);
data.pipe(res);
} catch (error) {
console.error('Failed to proxy thumbnail:', error);
res.status(500)
.send(JSON.stringify({ success: false, error: 'Failed to fetch thumbnail' }));
}
}));
// Serve static files for React app (after building)
app.use(express.static("dist/frontend"));
// Mount API routes under /api
app.use("/api", apiRouter);
// Serve React app for all other routes (client-side routing)
app.get("*", (req, res) => {
res.sendFile("dist/frontend/index.html", { root: "." });
});
const port = process.env.PORT || 3000;
const server = app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
// Add graceful shutdown handling
const shutdown = async () => {
console.log('Received shutdown signal. Closing server...');
server.close(() => {
console.log('Server closed');
process.exit(0);
});
// Force termination after some timeout (10sec)
setTimeout(() => {
console.log('Forcing server shutdown');
process.exit(1);
}, 10000);
};
// Handle various shutdown signals
process.on('SIGTERM', shutdown);
process.on('SIGINT', shutdown);

View File

@@ -0,0 +1,9 @@
{
"extends": "../tsconfig.base.json",
"compilerOptions": {
"rootDir": ".",
"outDir": "../build",
"composite": true
},
"include": ["./**/*"]
}