move web components to web/
This commit is contained in:
149
web/backend/src/FavoritesStore.ts
Normal file
149
web/backend/src/FavoritesStore.ts
Normal 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();
|
||||
}
|
||||
}
|
||||
120
web/backend/src/InvidiousAPI.ts
Normal file
120
web/backend/src/InvidiousAPI.ts
Normal 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'
|
||||
};
|
||||
};
|
||||
483
web/backend/src/MediaPlayer.ts
Normal file
483
web/backend/src/MediaPlayer.ts
Normal 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
342
web/backend/src/server.ts
Normal 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);
|
||||
9
web/backend/src/tsconfig.json
Normal file
9
web/backend/src/tsconfig.json
Normal file
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"extends": "../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": ".",
|
||||
"outDir": "../build",
|
||||
"composite": true
|
||||
},
|
||||
"include": ["./**/*"]
|
||||
}
|
||||
32
web/backend/src/types.ts
Normal file
32
web/backend/src/types.ts
Normal 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;
|
||||
}
|
||||
Reference in New Issue
Block a user