move web components to web/

This commit is contained in:
2025-10-10 23:13:03 -07:00
parent 623b562e8d
commit 52968df567
46 changed files with 0 additions and 0 deletions

33
web/backend/package.json Normal file
View File

@@ -0,0 +1,33 @@
{
"name": "mpvqueue",
"version": "1.0.0",
"main": "build/server.js",
"scripts": {
"build": "tsc -b",
"dev": "concurrently \"tsc -w -p src\" \"nodemon build/server.js\"",
"start": "node build/index.js"
},
"author": "",
"license": "ISC",
"description": "",
"devDependencies": {
"@types/express": "^5.0.0",
"@types/express-ws": "^3.0.5",
"@types/node": "^22.13.4",
"@types/ws": "^8.5.14",
"concurrently": "^9.1.2",
"nodemon": "^3.1.9",
"typescript": "^5.7.3"
},
"dependencies": {
"@types/node-fetch": "^2.6.12",
"bonjour-service": "^1.3.0",
"classnames": "^2.5.1",
"express": "^4.21.2",
"express-ws": "^5.0.2",
"link-preview-js": "^3.0.14",
"node-fetch": "^2.7.0",
"react-icons": "^5.4.0",
"ws": "^8.18.0"
}
}

View File

@@ -0,0 +1,149 @@
/*
* FavoritesStore.ts
* Copyleft 2025 James Magahern <buzzert@buzzert.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import fs from 'fs/promises';
import path from 'path';
import os from 'os';
import { PlaylistItem } from './types';
import { getLinkPreview } from 'link-preview-js';
export class FavoritesStore {
onFavoritesChanged: (favorites: PlaylistItem[]) => void = () => {};
private storePath: string;
private favorites: PlaylistItem[] = [];
constructor() {
this.storePath = this.determineStorePath();
this.loadFavorites();
}
private determineStorePath(): string {
const storeFilename = 'favorites.json';
var storePath = path.join(os.tmpdir(), 'queuecube');
// Check for explicitly set path
if (process.env.STORE_PATH) {
storePath = path.resolve(process.env.STORE_PATH);
}
// In production (in a container), use /app/data
else if (process.env.NODE_ENV === 'production') {
storePath = path.resolve('/app/data');
}
fs.mkdir(storePath, { recursive: true }).catch(err => {
console.error('Failed to create intermediate directory:', err);
});
const fullPath = path.join(storePath, storeFilename);
console.log("Favorites store path: " + fullPath);
return fullPath;
}
private async loadFavorites() {
try {
// Ensure parent directory exists
await fs.mkdir(path.dirname(this.storePath), { recursive: true });
const data = await fs.readFile(this.storePath, 'utf-8');
this.favorites = JSON.parse(data);
} catch (error) {
// If file doesn't exist or is invalid, start with empty array
this.favorites = [];
await this.saveFavorites();
}
}
private async saveFavorites() {
await fs.writeFile(this.storePath, JSON.stringify(this.favorites, null, 2));
this.onFavoritesChanged(this.favorites);
}
async getFavorites(): Promise<PlaylistItem[]> {
return this.favorites;
}
async addFavorite(filename: string): Promise<void> {
// Check if the item already exists by filename
const exists = this.favorites.some(f => f.filename === filename);
if (!exists) {
this.favorites.push({
filename: filename,
id: this.favorites.length // Generate new ID
});
await this.saveFavorites();
// Fetch metadata for the new favorite
await this.fetchMetadata(filename);
}
}
private async fetchMetadata(filename: string): Promise<void> {
console.log("Fetching metadata for " + filename);
const metadata = await getLinkPreview(filename);
const item: PlaylistItem = {
filename: filename,
id: this.favorites.length,
metadata: {
title: (metadata as any)?.title,
description: (metadata as any)?.description,
siteName: (metadata as any)?.siteName,
},
};
console.log("Metadata fetched for " + item.filename);
console.log(item);
const index = this.favorites.findIndex(f => f.filename === filename);
if (index !== -1) {
this.favorites[index] = item;
await this.saveFavorites();
}
}
async removeFavorite(filename: string): Promise<void> {
console.log("Removing favorite " + filename);
this.favorites = this.favorites.filter(f => f.filename !== filename);
await this.saveFavorites();
}
async updateFavoriteTitle(filename: string, title: string): Promise<void> {
console.log(`Updating title for favorite ${filename} to "${title}"`);
const index = this.favorites.findIndex(f => f.filename === filename);
if (index !== -1) {
// Create metadata object if it doesn't exist
if (!this.favorites[index].metadata) {
this.favorites[index].metadata = {};
}
// Update the title in metadata
this.favorites[index].metadata!.title = title;
await this.saveFavorites();
} else {
throw new Error(`Favorite with filename ${filename} not found`);
}
}
async clearFavorites(): Promise<void> {
this.favorites = [];
await this.saveFavorites();
}
}

View File

@@ -0,0 +1,120 @@
/*
* InvidiousAPI.ts
* Copyleft 2025 James Magahern <buzzert@buzzert.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
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 || process.env.INVIDIOUS_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'
};
};

View File

@@ -0,0 +1,483 @@
/*
* MediaPlayer.ts
* Copyleft 2025 James Magahern <buzzert@buzzert.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { ChildProcess, spawn } from "child_process";
import { Socket } from "net";
import { WebSocket } from "ws";
import { getLinkPreview } from "link-preview-js";
import { PlaylistItem, LinkMetadata } from './types';
import { FavoritesStore } from "./FavoritesStore";
import { Bonjour } from "bonjour-service";
import os from 'os';
interface PendingCommand {
resolve: (value: any) => void;
reject: (reason: any) => void;
}
enum UserEvent {
PlaylistUpdate = "playlist_update",
NowPlayingUpdate = "now_playing_update",
VolumeUpdate = "volume_update",
FavoritesUpdate = "favorites_update",
MetadataUpdate = "metadata_update",
MPDUpdate = "mpd_update",
}
export interface Features {
video: boolean;
screenshare: boolean;
browserPlayback: boolean;
}
export class MediaPlayer {
private playerProcess: ChildProcess | null = null;
private socket: Promise<Socket>;
private eventSubscribers: WebSocket[] = [];
private favoritesStore: FavoritesStore;
private pendingCommands: Map<number, PendingCommand> = new Map();
private requestId: number = 1;
private dataBuffer: string = '';
private metadata: Map<string, LinkMetadata> = new Map();
private bonjourInstance: Bonjour | null = null;
constructor() {
this.socket = this.tryRespawnPlayerProcess();
this.favoritesStore = new FavoritesStore();
this.favoritesStore.onFavoritesChanged = (favorites) => {
this.handleEvent(UserEvent.FavoritesUpdate, { favorites });
};
this.getFeatures().then(features => {
console.log("Features: ", features);
});
}
public startZeroconfService(port: number) {
if (this.bonjourInstance) {
console.log("Zeroconf service already running");
return;
}
this.bonjourInstance = new Bonjour();
const service = this.bonjourInstance.publish({
name: `QueueCube Media Server (${os.hostname()})`,
type: 'queuecube',
port: port,
txt: {
version: '1.0.0',
features: 'playlist,favorites,screenshare'
}
});
service.on('up', () => {
console.log(`Zeroconf service advertised: ${service.name} on port ${port}`);
});
service.on('error', (err: Error) => {
console.error('Zeroconf service error:', err);
});
}
public stopZeroconfService() {
if (this.bonjourInstance) {
this.bonjourInstance.destroy();
this.bonjourInstance = null;
console.log("Zeroconf service stopped");
}
}
private tryRespawnPlayerProcess(): Promise<Socket> {
const socketFilename = Math.random().toString(36).substring(2, 10);
const socketPath = `/tmp/mpv-${socketFilename}`;
const enableVideo = process.env.ENABLE_VIDEO || false;
const logfilePath = `/tmp/mpv-logfile.txt`;
console.log("Starting player process (video: " + (enableVideo ? "enabled" : "disabled") + ")");
this.playerProcess = spawn("mpv", [
"--video=" + (enableVideo ? "auto" : "no"),
"--fullscreen",
"--no-terminal",
"--idle=yes",
"--input-ipc-server=" + socketPath,
"--log-file=" + logfilePath,
"--msg-level=all=v"
]);
let socketReady!: (s: Socket) => void;
let socketPromise = new Promise<Socket>(resolve => {
socketReady = resolve;
});
this.playerProcess.on("spawn", () => {
console.log(`Player process spawned, opening socket @ ${socketPath}`);
setTimeout(() => {
let socket = this.connectToSocket(socketPath);
socketReady(socket);
}, 500);
});
this.playerProcess.on("error", (error) => {
console.error("Player process error:", error);
console.log("Continuing without mpv player...");
});
return socketPromise;
}
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 | null> => {
try {
return (await this.writeCommand("get_property", ["media-title"])).data;
} catch (err) {
return null;
}
};
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() || currentlyPlayingSong.filename
};
}
return currentlyPlayingSong;
}
const mediaTitle = await fetchMediaTitle() || "";
return {
id: 0,
filename: mediaTitle,
title: mediaTitle
};
}
public async getCurrentFile(): Promise<string | null> {
return this.writeCommand("get_property", ["stream-open-filename"])
.then((response) => {
return response.data;
}, (reject) => { return null; });
}
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 getTimePosition(): Promise<number | null> {
return this.writeCommand("get_property", ["time-pos"])
.then((response) => {
return response.data;
}, (rejected) => { return null; });
}
public async getDuration(): Promise<number | null> {
return this.writeCommand("get_property", ["duration"])
.then((response) => {
return response.data;
}, (rejected) => { return null; });
}
public async getSeekable(): Promise<boolean | null> {
return this.writeCommand("get_property", ["seekable"])
.then((response) => {
return response.data;
}, (rejected) => { return null; });
}
public async getIdle(): Promise<boolean> {
return this.writeCommand("get_property", ["idle"])
.then((response) => {
return response.data;
});
}
public async append(url: string) {
await this.loadFile(url, "append-play");
}
public async replace(url: string) {
await this.loadFile(url, "replace");
}
public async initiateScreenSharing(url: string) {
console.log(`Initiating screen sharing with file: ${url}`);
this.metadata.set(url, {
title: "Screen Sharing",
description: "Screen Sharing",
siteName: "Screen Sharing",
});
// Special options for mpv to better handle screen sharing (AI recommended...)
await this.loadFile(url, "replace", false, [
"demuxer-lavf-o=fflags=+nobuffer+discardcorrupt", // Reduce buffering and discard corrupt frames
"demuxer-lavf-o=analyzeduration=100000", // Reduce analyze duration
"demuxer-lavf-o=probesize=1000000", // Reduce probe size
"untimed=yes", // Ignore timing info
"cache=no", // Disable cache
"force-seekable=yes", // Force seekable
"no-cache=yes", // Disable cache
"demuxer-max-bytes=500K", // Limit demuxer buffer
"demuxer-readahead-secs=0.1", // Reduce readahead
"hr-seek=no", // Disable high-res seeking
"video-sync=display-resample", // Better sync mode
"video-latency-hacks=yes", // Enable latency hacks
"audio-sync=yes", // Enable audio sync
"audio-buffer=0.1", // Reduce audio buffer
"audio-channels=stereo", // Force stereo audio
"audio-samplerate=44100", // Match sample rate
"audio-format=s16", // Use 16-bit audio
]);
// Make sure it's playing
setTimeout(() => this.play(), 100);
}
public async play() {
return this.modify(UserEvent.NowPlayingUpdate, () => this.writeCommand("set_property", ["pause", false]));
}
public async pause() {
return this.modify(UserEvent.NowPlayingUpdate, () => this.writeCommand("set_property", ["pause", true]));
}
public async stop() {
return this.modify(UserEvent.NowPlayingUpdate, () => this.writeCommand("stop", []));
}
public async skip() {
return this.modify(UserEvent.PlaylistUpdate, () => this.writeCommand("playlist-next", []));
}
public async skipTo(index: number) {
return this.modify(UserEvent.PlaylistUpdate, () => this.writeCommand("playlist-play-index", [index]));
}
public async previous() {
return this.modify(UserEvent.PlaylistUpdate, () => this.writeCommand("playlist-prev", []));
}
public async deletePlaylistItem(index: number) {
return this.modify(UserEvent.PlaylistUpdate, () => this.writeCommand("playlist-remove", [index]));
}
public async setVolume(volume: number) {
return this.modify(UserEvent.VolumeUpdate, () => this.writeCommand("set_property", ["volume", volume]));
}
public async seek(time: number) {
return this.modify(UserEvent.NowPlayingUpdate, () => this.writeCommand("seek", [time, "absolute"]));
}
public subscribe(ws: WebSocket) {
this.eventSubscribers.push(ws);
}
public unsubscribe(ws: WebSocket) {
this.eventSubscribers = this.eventSubscribers.filter(subscriber => subscriber !== ws);
}
public async getFavorites(): Promise<PlaylistItem[]> {
return this.favoritesStore.getFavorites();
}
public async addFavorite(filename: string) {
return this.modify(UserEvent.FavoritesUpdate, () => this.favoritesStore.addFavorite(filename));
}
public async removeFavorite(filename: string) {
return this.modify(UserEvent.FavoritesUpdate, () => this.favoritesStore.removeFavorite(filename));
}
public async clearFavorites() {
return this.modify(UserEvent.FavoritesUpdate, () => this.favoritesStore.clearFavorites());
}
public async updateFavoriteTitle(filename: string, title: string) {
return this.modify(UserEvent.FavoritesUpdate, () => this.favoritesStore.updateFavoriteTitle(filename, title));
}
public async getFeatures(): Promise<Features> {
return {
video: !!process.env.ENABLE_VIDEO,
screenshare: !!process.env.ENABLE_SCREENSHARE,
browserPlayback: !!process.env.ENABLE_BROWSER_PLAYBACK
};
}
private async loadFile(url: string, mode: string, fetchMetadata: boolean = true, options: string[] = []) {
this.modify(UserEvent.PlaylistUpdate, () => this.writeCommand("loadfile", [url, mode, "-1", options.join(',')]));
if (fetchMetadata) {
this.fetchMetadataAndNotify(url).catch(error => {
console.warn(`Failed to fetch metadata for ${url}:`, error);
});
}
}
private async modify<T>(event: UserEvent, func: () => Promise<T>): Promise<T> {
return func()
.then((result) => {
// Notify all subscribers
this.handleEvent(event, {});
return result;
}, (reject) => {
console.log("Error modifying playlist: " + reject);
return reject;
});
}
private async writeCommand(command: string, args: any[]): Promise<any> {
// Wait for socket to become available.
let socket = await this.socket;
return new Promise((resolve, reject) => {
const id = this.requestId++;
const commandObject = JSON.stringify({
command: [command, ...args],
request_id: id
});
try {
this.pendingCommands.set(id, { resolve, reject });
socket.write(commandObject + '\n');
} catch (e: any) {
console.error(`Error writing to socket: ${e}. Trying to respawn.`)
this.tryRespawnPlayerProcess();
}
// 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 {
console.log("Fetching metadata for " + url);
const metadata = await getLinkPreview(url);
this.metadata.set(url, {
title: (metadata as any)?.title,
description: (metadata as any)?.description,
siteName: (metadata as any)?.siteName,
});
console.log("Metadata fetched for " + url);
console.log(this.metadata.get(url));
// Notify clients that metadata has been updated
this.handleEvent(UserEvent.MetadataUpdate, {
url,
metadata: this.metadata.get(url)
});
} catch (error) {
throw error;
}
}
private connectToSocket(path: string): Socket {
let socket = new Socket();
socket.connect(path);
socket.on("data", data => this.receiveData(data.toString()));
return socket;
}
private handleEvent(event: string, data: any) {
console.log("Event [" + event + "]: ", data);
// 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) {
if (response.error == "success") {
pending.resolve(response);
} else {
pending.reject(response.error);
}
this.pendingCommands.delete(response.request_id);
}
} else if (response.event) {
this.handleEvent(UserEvent.MPDUpdate, response);
} else {
console.log(response);
}
} catch (error) {
console.error('Error parsing JSON:', error);
}
}
}
}
}

342
web/backend/src/server.ts Normal file
View File

@@ -0,0 +1,342 @@
/*
* server.ts
* Copyleft 2025 James Magahern <buzzert@buzzert.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import express from "express";
import expressWs from "express-ws";
import path from "path";
import fs from "fs";
import os from "os";
import { MediaPlayer } from "./MediaPlayer";
import { searchInvidious, fetchThumbnail } from "./InvidiousAPI";
import { PlaylistItem } from './types';
import { PassThrough } from "stream";
import { AddressInfo } from "net";
const app = express();
app.use(express.json());
expressWs(app);
const apiRouter = express.Router();
const mediaPlayer = new MediaPlayer();
// Create a shared stream that both endpoints can access
let activeScreenshareStream: PassThrough | null = null;
let activeScreenshareMimeType: string | null = null;
const withErrorHandling = (func: (req: any, res: any) => Promise<any>) => {
return async (req: any, res: any) => {
try {
await func(req, res);
} catch (error: any) {
console.log(`Error (${func.name}): ${error}`);
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("/playlist/replace", withErrorHandling(async (req, res) => {
const { url } = req.body as { url: string };
await mediaPlayer.replace(url);
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("/stop", withErrorHandling(async (req, res) => {
await mediaPlayer.stop();
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();
const timePosition = await mediaPlayer.getTimePosition();
const duration = await mediaPlayer.getDuration();
const seekable = await mediaPlayer.getSeekable();
res.send(JSON.stringify({
success: true,
playingItem: playingItem,
isPaused: pauseState,
volume: volume,
isIdle: idle,
currentFile: currentFile,
timePosition: timePosition,
duration: duration,
seekable: seekable
}));
}));
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.post("/player/seek", withErrorHandling(async (req, res) => {
const { time } = req.body as { time: number };
await mediaPlayer.seek(time);
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);
});
});
// This is effectively a "private" endpoint that only the MPV instance accesses. We're
// using the fact that QueueCube/MPV is based all around streaming URLs, so the active
// screenshare stream manifests as just another URL to play.
apiRouter.get("/screenshareStream", withErrorHandling(async (req, res) => {
res.setHeader("Content-Type", activeScreenshareMimeType || "video/mp4");
res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
res.setHeader("Pragma", "no-cache");
res.setHeader("Expires", "0");
res.setHeader("Connection", "keep-alive");
res.setHeader("Transfer-Encoding", "chunked");
if (!activeScreenshareStream) {
res.status(503).send("No active screen sharing session");
return;
}
// Handle client disconnection
req.on('close', () => {
console.log("Screenshare viewer disconnected");
});
// Configure stream for low latency
activeScreenshareStream.setMaxListeners(0);
// Pipe with immediate flush
activeScreenshareStream.pipe(res, { end: false });
}));
apiRouter.ws("/screenshare", (ws, req) => {
const mimeType = req.query.mimeType as string;
console.log("Screen sharing client connected with mimeType: " + mimeType);
ws.binaryType = "arraybuffer";
let firstChunk = false;
// Configure WebSocket for low latency
ws.setMaxListeners(0);
ws.binaryType = "arraybuffer";
ws.on('message', (data: any) => {
const buffer = data instanceof Buffer ? data : Buffer.from(data);
if (!firstChunk) {
firstChunk = true;
const port = (server.address() as AddressInfo).port;
const url = `http://localhost:${port}/api/screenshareStream`;
console.log(`Starting screen share stream at ${url}`);
// Create new shared stream with immediate flush
activeScreenshareStream = new PassThrough({
highWaterMark: 1024 * 1024, // 1MB buffer
allowHalfOpen: false
});
activeScreenshareStream.write(buffer);
mediaPlayer.initiateScreenSharing(url);
} else if (activeScreenshareStream) {
// Write with immediate flush
activeScreenshareStream.write(buffer, () => {
activeScreenshareStream?.cork();
activeScreenshareStream?.uncork();
});
}
});
ws.on('close', () => {
console.log("Screen sharing client disconnected");
if (activeScreenshareStream) {
activeScreenshareStream.end();
activeScreenshareStream = null;
}
mediaPlayer.stop();
});
});
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' }));
}
}));
apiRouter.get("/favorites", withErrorHandling(async (req, res) => {
const favorites = await mediaPlayer.getFavorites();
res.send(JSON.stringify(favorites));
}));
apiRouter.post("/favorites", withErrorHandling(async (req, res) => {
const { filename } = req.body as { filename: string };
console.log("Adding favorite: " + filename);
await mediaPlayer.addFavorite(filename);
res.send(JSON.stringify({ success: true }));
}));
apiRouter.delete("/favorites/:filename", withErrorHandling(async (req, res) => {
const { filename } = req.params as { filename: string };
await mediaPlayer.removeFavorite(filename);
res.send(JSON.stringify({ success: true }));
}));
apiRouter.delete("/favorites", withErrorHandling(async (req, res) => {
await mediaPlayer.clearFavorites();
res.send(JSON.stringify({ success: true }));
}));
apiRouter.put("/favorites/:filename/title", withErrorHandling(async (req, res) => {
const { filename } = req.params as { filename: string };
const { title } = req.body as { title: string };
if (!title) {
res.status(400).send(JSON.stringify({
success: false,
error: "Title is required"
}));
return;
}
await mediaPlayer.updateFavoriteTitle(filename, title);
res.send(JSON.stringify({ success: true }));
}));
apiRouter.get("/features", withErrorHandling(async (req, res) => {
const features = await mediaPlayer.getFeatures();
res.send(JSON.stringify(features));
}));
// Serve static files for React app (after building)
app.use(express.static(path.join(__dirname, "../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(path.join(__dirname, "../dist/frontend/index.html"));
});
const port = process.env.PORT || 3000;
const server = app.listen(port, () => {
console.log(`Server is running on port ${port}`);
// Start zeroconf service advertisement
mediaPlayer.startZeroconfService(Number(port));
});
// Add graceful shutdown handling
const shutdown = async () => {
console.log('Received shutdown signal. Closing server...');
// Stop zeroconf service
mediaPlayer.stopZeroconfService();
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": ["./**/*"]
}

32
web/backend/src/types.ts Normal file
View File

@@ -0,0 +1,32 @@
/*
* types.ts
* Copyleft 2025 James Magahern <buzzert@buzzert.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
export interface LinkMetadata {
title?: string;
description?: string;
siteName?: string;
}
export interface PlaylistItem {
id: number;
filename: string;
title?: string;
playing?: boolean;
current?: boolean;
metadata?: LinkMetadata;
}

View File

@@ -0,0 +1,10 @@
{
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}

116
web/backend/tsconfig.json Normal file
View File

@@ -0,0 +1,116 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */
/* Projects */
"composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
/* Modules */
"module": "commonjs", /* Specify what module code is generated. */
"rootDir": "./src",
"outDir": "./build",
// "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
// "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
// "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
// "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
// "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
// "resolveJsonModule": true, /* Enable importing .json files. */
// "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
/* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
// "removeComments": true, /* Disable emitting comments. */
// "noEmit": true, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
/* Type Checking */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
},
"include": ["src/**/*"], // Only include backend files
"exclude": ["../frontend/**/*"], // Explicitly exclude frontend files
"files": [],
"references": [
{ "path": "./src" }, // Backend reference
{ "path": "../frontend" } // Frontend reference
]
}