txtorg commited on
Commit
4e3b382
Β·
verified Β·
1 Parent(s): 7000b77

Upload constituent server files

Browse files
Files changed (3) hide show
  1. Dockerfile +43 -0
  2. package.json +11 -0
  3. server.js +1200 -0
Dockerfile ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ═══════════════════════════════════════════════════════════════════════════
2
+ # CONSTITUENT DOCKERFILE
3
+ # HuggingFace Docker Space β€” Node.js + FFmpeg streaming server
4
+ # ═══════════════════════════════════════════════════════════════════════════
5
+
6
+ FROM node:20-slim
7
+
8
+ # Install ffmpeg and system utilities
9
+ RUN apt-get update && apt-get install -y \
10
+ ffmpeg \
11
+ procps \
12
+ curl \
13
+ && rm -rf /var/lib/apt/lists/*
14
+
15
+ WORKDIR /app
16
+
17
+ # Copy package files first for layer caching
18
+ COPY package.json ./
19
+
20
+ # Install dependencies
21
+ RUN npm install --omit=dev
22
+
23
+ # Copy application files
24
+ COPY server.js ./server.js
25
+
26
+ # Create required directories
27
+ RUN mkdir -p others/temp others/songs others/hls others/data
28
+
29
+ # HuggingFace Spaces runs on port 7860 by default
30
+ EXPOSE 7860
31
+
32
+ # Environment variables that MUST be set as HuggingFace Space secrets:
33
+ # CONSTITUENT_OWNER_ID β€” the userId from your main DB who owns this space
34
+ # MAIN_SERVER_SECRET β€” shared secret so only your main server can call add-movie
35
+ # TMDB_KEY β€” (optional) for TMDB enrichment
36
+ ENV PORT=7860
37
+ ENV NODE_ENV=production
38
+
39
+ # Health check β€” HuggingFace polls this to decide if the space is healthy
40
+ HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
41
+ CMD curl -f http://localhost:7860/constituent/health || exit 1
42
+
43
+ CMD ["node", "server.js"]
package.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "clippy",
3
+ "version": "1.0.0",
4
+ "main": "server.js",
5
+ "dependencies": {
6
+ "express": "^4.18.2",
7
+ "axios": "^1.6.0",
8
+ "fluent-ffmpeg": "^2.1.2",
9
+ "socket.io": "^4.7.2"
10
+ }
11
+ }
server.js ADDED
@@ -0,0 +1,1200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ═══════════════════════════════════════════════════════════════════════════
2
+ // CONSTITUENT SERVER
3
+ // Runs inside a HuggingFace Docker Space.
4
+ // Handles all HLS/FFmpeg streaming logic + constituent-specific APIs.
5
+ // Main web server communicates with this via HTTP only.
6
+ // config.json is auto-created on first boot storing the constituent owner id.
7
+ // ═══════════════════════════════════════════════════════════════════════════
8
+
9
+ const fs = require('fs');
10
+ const path = require('path');
11
+ const crypto = require('crypto');
12
+ const https = require('https');
13
+ const ffmpeg = require('fluent-ffmpeg');
14
+ const axios = require('axios');
15
+ const express = require('express');
16
+ const http = require('http');
17
+ const { Server: SocketIOServer } = require('socket.io');
18
+ const os = require('os');
19
+
20
+ // ── Config ────────────────────────────────────────────────────────────────────
21
+ // CONSTITUENT_OWNER_ID must be set as a HuggingFace Space secret/env var.
22
+ // It is the userId from your main database that "owns" this constituent.
23
+ const CONSTITUENT_OWNER_ID = process.env.CONSTITUENT_OWNER_ID;
24
+ const MAIN_SERVER_SECRET = process.env.MAIN_SERVER_SECRET || 'mysecretkeyforogudupaogeuwuwuhdg'; // shared secret to authenticate main server calls
25
+ const PORT = parseInt(process.env.PORT || '7860', 10);
26
+ const TMDB_KEY = process.env.TMDB_KEY || null;
27
+ const TMDB_BASE = 'https://api.themoviedb.org/3';
28
+ const TMDB_IMG = 'https://image.tmdb.org/t/p/w500';
29
+
30
+ if (!CONSTITUENT_OWNER_ID) {
31
+ console.error('CONSTITUENT_OWNER_ID env var is required. Set it as a HuggingFace Space secret.');
32
+ process.exit(1);
33
+ }
34
+ console.log(`πŸ”‘ MAIN_SERVER_SECRET: ${process.env.MAIN_SERVER_SECRET ? 'loaded from env' : 'using built-in default'}`);
35
+
36
+ // ── Auto-create config.json ───────────────────────────────────────────────────
37
+ const CONFIG_PATH = path.join(__dirname, 'config.json');
38
+ let constituentConfig = {};
39
+ if (fs.existsSync(CONFIG_PATH)) {
40
+ try { constituentConfig = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8')); }
41
+ catch { constituentConfig = {}; }
42
+ }
43
+ if (!constituentConfig.ownerId) {
44
+ constituentConfig.ownerId = CONSTITUENT_OWNER_ID;
45
+ constituentConfig.createdAt = new Date().toISOString();
46
+ fs.writeFileSync(CONFIG_PATH, JSON.stringify(constituentConfig, null, 2));
47
+ console.log(`βœ… config.json created for owner: ${CONSTITUENT_OWNER_ID}`);
48
+ }
49
+
50
+ // ── Dirs & constants ──────────────────────────────────────────────────────────
51
+ const TEMP_DIR = path.join(__dirname, 'others', 'temp');
52
+ const SONGS_DIR = path.join(__dirname, 'others', 'songs');
53
+ const HLS_DIR = path.join(__dirname, 'others', 'hls');
54
+ const DATA_DIR = path.join(__dirname, 'others', 'data');
55
+ fs.mkdirSync(TEMP_DIR, { recursive: true });
56
+ fs.mkdirSync(SONGS_DIR, { recursive: true });
57
+ fs.mkdirSync(HLS_DIR, { recursive: true });
58
+ fs.mkdirSync(DATA_DIR, { recursive: true });
59
+
60
+ const SHOWPLAY_MAX_FILE_SIZE = 2 * 1024 * 1024 * 1024; // 2 GB
61
+ const SHOWPLAY_MAX_DURATION = 6 * 60 * 60; // 6 hrs
62
+ const MAX_FILE_SIZE = 50 * 1024 * 1024; // 50 MB (audio)
63
+ const MAX_DURATION = 15 * 60; // 15 min (audio)
64
+ const STREAM_CLEANUP_INTERVAL = 30 * 60 * 1000;
65
+ const DEFAULT_ARTWORK = 'https://touchio.vercel.app/tf14k0.jpeg';
66
+ const HLS_PLAYLIST_WINDOW = 6;
67
+ const HLS_MAX_SEGMENTS = 800;
68
+
69
+ // ── SSL agent ─────────────────────────────────────────────────────────────────
70
+ const httpsAgentNoVerify = new https.Agent({ rejectUnauthorized: false });
71
+ axios.defaults.httpsAgent = httpsAgentNoVerify;
72
+
73
+ // ── Express + Socket.IO ───────────────────────────────────────────────────────
74
+ const app = express();
75
+ const server = http.createServer(app);
76
+ const io = new SocketIOServer(server, {
77
+ cors: { origin: true, credentials: true, methods: ['GET', 'POST'] },
78
+ transports: ['websocket', 'polling']
79
+ });
80
+
81
+ app.use(express.json());
82
+ app.use('/hls', express.static(HLS_DIR, {
83
+ setHeaders: (res, filePath) => {
84
+ if (filePath.endsWith('.m3u8')) {
85
+ res.setHeader('Content-Type', 'application/vnd.apple.mpegurl');
86
+ res.setHeader('Cache-Control', 'no-cache, no-store');
87
+ res.setHeader('Access-Control-Allow-Origin', '*');
88
+ }
89
+ if (filePath.endsWith('.ts')) {
90
+ res.setHeader('Content-Type', 'video/MP2T');
91
+ res.setHeader('Cache-Control', 'public, max-age=3600');
92
+ res.setHeader('Access-Control-Allow-Origin', '*');
93
+ }
94
+ }
95
+ }));
96
+ app.use('/songs', express.static(SONGS_DIR));
97
+
98
+ // ── In-memory streaming state ─────────────────────────────────────────────────
99
+ const streams = {};
100
+ const hlsState = {};
101
+ const hlsMutex = {};
102
+ const hlsGeneration = {};
103
+ const activeFFmpeg = {};
104
+
105
+ // ── Auth middleware for main-server calls ─────────────────────────────────────
106
+ function requireMainServer(req, res, next) {
107
+ const secret = req.headers['x-constituent-secret'];
108
+ if (!secret || secret !== MAIN_SERVER_SECRET) {
109
+ return res.status(403).json({ success: false, error: 'Forbidden: invalid or missing secret' });
110
+ }
111
+ next();
112
+ }
113
+
114
+ // ═══════════════════════════════════════════════════════════════════════════
115
+ // HEALTH / STATUS API
116
+ // Called by main server to check if this constituent is alive and ready.
117
+ // ═══════════════════════════════════════════════════════════════════════════
118
+
119
+ app.get('/constituent/health', (req, res) => {
120
+ const totalMem = os.totalmem();
121
+ const freeMem = os.freemem();
122
+ const usedMem = totalMem - freeMem;
123
+ const cpuLoad = os.loadavg()[0]; // 1-min average
124
+
125
+ // Disk usage via df (Linux only β€” fine for HF Docker)
126
+ let diskTotal = null, diskUsed = null, diskFree = null;
127
+ try {
128
+ const { execSync } = require('child_process');
129
+ const dfOut = execSync("df -k / | tail -1").toString().trim().split(/\s+/);
130
+ diskTotal = parseInt(dfOut[1]) * 1024;
131
+ diskUsed = parseInt(dfOut[2]) * 1024;
132
+ diskFree = parseInt(dfOut[3]) * 1024;
133
+ } catch {}
134
+
135
+ const activeStreamCount = Object.keys(streams).filter(id => streams[id]?.isActive).length;
136
+
137
+ res.json({
138
+ success: true,
139
+ status: 'running',
140
+ ownerId: constituentConfig.ownerId,
141
+ createdAt: constituentConfig.createdAt,
142
+ uptime: process.uptime(),
143
+ memory: {
144
+ totalMB: Math.round(totalMem / 1024 / 1024),
145
+ usedMB: Math.round(usedMem / 1024 / 1024),
146
+ freeMB: Math.round(freeMem / 1024 / 1024),
147
+ usedPct: Math.round((usedMem / totalMem) * 100),
148
+ },
149
+ cpu: { loadAvg1min: cpuLoad.toFixed(2) },
150
+ disk: diskTotal ? {
151
+ totalGB: (diskTotal / 1024 ** 3).toFixed(1),
152
+ usedGB: (diskUsed / 1024 ** 3).toFixed(1),
153
+ freeGB: (diskFree / 1024 ** 3).toFixed(1),
154
+ usedPct: Math.round((diskUsed / diskTotal) * 100),
155
+ } : null,
156
+ streams: {
157
+ active: activeStreamCount,
158
+ total: Object.keys(streams).length,
159
+ },
160
+ });
161
+ });
162
+
163
+ // ═══════════════════════════════════════════════════════════════════════════
164
+ // SHOWPLAY API β€” search by title name (no raw link needed)
165
+ // Called by main server when a user (who owns this constituent) adds a movie or episode.
166
+ // Only the constituent's owner can trigger this.
167
+ //
168
+ // POST /constituent/add-movie β€” body: { streamId, title }
169
+ // Searches iktracks for the title, picks the first movie result, downloads it.
170
+ //
171
+ // POST /constituent/add-episode β€” body: { streamId, title, season, episode }
172
+ // Searches iktracks for the series, finds the matching S/E, downloads it.
173
+ // ═══════════════════════════════════════════════════════════════════════════
174
+
175
+ const IKTRACKS_BASE = 'https://iktracks.vercel.app';
176
+
177
+ function spSeriesName(title) {
178
+ return (title || '').replace(/\s*\(?\d{4}\)?\s*$/, '').trim() || title;
179
+ }
180
+
181
+ function extractAllEpisodes(details) {
182
+ const allEps = [];
183
+ for (const season of (details.seasons || [])) {
184
+ for (const ep of (season.episodes || [])) {
185
+ if (ep && ep.downloadLink) {
186
+ allEps.push({ season: season.season, episode: ep.episode, downloadLink: ep.downloadLink });
187
+ }
188
+ }
189
+ }
190
+ return allEps;
191
+ }
192
+
193
+ app.post('/constituent/add-movie', requireMainServer, async (req, res) => {
194
+ // Supports two modes:
195
+ // 1. { streamId, movieLink, movieTitle, thumbnail?, tmdbInfo? } β€” direct link from server.js
196
+ // 2. { streamId, title } β€” search by name (legacy / direct constituent use)
197
+ const { streamId, movieLink, movieTitle, title: titleOnly, thumbnail, tmdbInfo } = req.body;
198
+
199
+ if (!streamId) {
200
+ return res.status(400).json({ success: false, error: 'streamId is required' });
201
+ }
202
+ if (streamId !== constituentConfig.ownerId) {
203
+ return res.status(403).json({ success: false, error: 'Only the constituent owner can add movies to this server' });
204
+ }
205
+
206
+ // ── Mode 1: direct link provided ───────────────────────────────────────────
207
+ if (movieLink && movieTitle) {
208
+ res.json({ success: true, message: 'Movie queued for download and encoding', streamId, title: movieTitle });
209
+ setImmediate(async () => {
210
+ try {
211
+ const result = await showplayEnqueueLink(streamId, movieLink, movieTitle, thumbnail || DEFAULT_ARTWORK, tmdbInfo || null);
212
+ console.log(`βœ… Movie added to stream ${streamId}: ${result.title}`);
213
+ } catch (err) {
214
+ console.error(`❌ Failed to add movie to stream ${streamId}:`, err.message);
215
+ }
216
+ });
217
+ return;
218
+ }
219
+
220
+ // ── Mode 2: search by title ────────────────────────────────────────────────
221
+ const title = titleOnly || movieTitle;
222
+ if (!title) {
223
+ return res.status(400).json({ success: false, error: 'Either (movieLink + movieTitle) or title is required' });
224
+ }
225
+
226
+ // Search for the title
227
+ let searchResults;
228
+ try {
229
+ const r = await axios.get(`${IKTRACKS_BASE}/search?query=${encodeURIComponent(title)}`, { timeout: 15000 });
230
+ searchResults = (r.data?.results || []).filter(r => r && r.link);
231
+ } catch (err) {
232
+ return res.status(500).json({ success: false, error: `Search failed: ${err.message}` });
233
+ }
234
+ if (!searchResults.length) {
235
+ return res.status(404).json({ success: false, error: `No results found for "${title}"` });
236
+ }
237
+
238
+ // Pick the first movie result (prefer type==='movie', fall back to first result)
239
+ const movieResult = searchResults.find(r => r.type === 'movie') || searchResults[0];
240
+
241
+ // Fetch details to get the download link
242
+ let details;
243
+ try {
244
+ const r = await axios.get(`${IKTRACKS_BASE}/details?url=${encodeURIComponent(movieResult.link)}`, { timeout: 15000 });
245
+ details = r.data;
246
+ if (!details) throw new Error('Empty details response');
247
+ } catch (err) {
248
+ return res.status(500).json({ success: false, error: `Details fetch failed: ${err.message}` });
249
+ }
250
+
251
+ if (details.type === 'series') {
252
+ return res.status(400).json({ success: false, error: 'This title is a series. Use /constituent/add-episode instead.' });
253
+ }
254
+
255
+ const link = details.downloadLinks?.[0]?.downloadLink;
256
+ if (!link) {
257
+ return res.status(404).json({ success: false, error: 'No download link found for this title' });
258
+ }
259
+
260
+ const pendingTitle = details.title || movieResult.title || title;
261
+ const pendingThumb = details.thumbnail || movieResult.thumbnail || DEFAULT_ARTWORK;
262
+
263
+ res.json({ success: true, message: 'Movie queued for download and encoding', streamId, title: pendingTitle });
264
+
265
+ setImmediate(async () => {
266
+ try {
267
+ const result = await showplayEnqueueLink(streamId, link, pendingTitle, pendingThumb, tmdbInfo || null);
268
+ console.log(`βœ… Movie added to stream ${streamId}: ${result.title}`);
269
+ } catch (err) {
270
+ console.error(`❌ Failed to add movie to stream ${streamId}:`, err.message);
271
+ }
272
+ });
273
+ });
274
+
275
+ // POST /constituent/add-episode β€” body: { streamId, title, season, episode }
276
+ app.post('/constituent/add-episode', requireMainServer, async (req, res) => {
277
+ const { streamId, title, season, episode } = req.body;
278
+
279
+ if (!streamId || !title) {
280
+ return res.status(400).json({ success: false, error: 'streamId and title are required' });
281
+ }
282
+ if (season == null || episode == null) {
283
+ return res.status(400).json({ success: false, error: 'season and episode are required' });
284
+ }
285
+ if (streamId !== constituentConfig.ownerId) {
286
+ return res.status(403).json({ success: false, error: 'Only the constituent owner can add episodes to this server' });
287
+ }
288
+
289
+ // Search for the series
290
+ let searchResults;
291
+ try {
292
+ const r = await axios.get(`${IKTRACKS_BASE}/search?query=${encodeURIComponent(title)}`, { timeout: 15000 });
293
+ searchResults = (r.data?.results || []).filter(r => r && r.link);
294
+ } catch (err) {
295
+ return res.status(500).json({ success: false, error: `Search failed: ${err.message}` });
296
+ }
297
+ if (!searchResults.length) {
298
+ return res.status(404).json({ success: false, error: `No results found for "${title}"` });
299
+ }
300
+
301
+ // Pick best series result
302
+ const seriesResult = searchResults.find(r => r.type === 'series') || searchResults[0];
303
+
304
+ // Fetch details
305
+ let details;
306
+ try {
307
+ const r = await axios.get(`${IKTRACKS_BASE}/details?url=${encodeURIComponent(seriesResult.link)}`, { timeout: 15000 });
308
+ details = r.data;
309
+ if (!details) throw new Error('Empty details response');
310
+ } catch (err) {
311
+ return res.status(500).json({ success: false, error: `Details fetch failed: ${err.message}` });
312
+ }
313
+
314
+ const allEps = extractAllEpisodes(details);
315
+ if (!allEps.length) {
316
+ return res.status(404).json({ success: false, error: 'No downloadable episodes found for this title' });
317
+ }
318
+
319
+ const ep = allEps.find(e => String(e.season) === String(season) && String(e.episode) === String(episode));
320
+ if (!ep) {
321
+ return res.status(404).json({ success: false, error: `Episode S${season}E${episode} not found` });
322
+ }
323
+
324
+ const seriesName = spSeriesName(details.title || seriesResult.title || title);
325
+ const epLabel = `S${String(ep.season).padStart(2,'0')} E${String(ep.episode).padStart(2,'0')}`;
326
+ const pendingTitle = `${seriesName} β€’ ${epLabel}`;
327
+ const thumbnail = details.thumbnail || seriesResult.thumbnail || DEFAULT_ARTWORK;
328
+
329
+ res.json({ success: true, message: 'Episode queued for download and encoding', streamId, title: pendingTitle });
330
+
331
+ setImmediate(async () => {
332
+ try {
333
+ const result = await showplayEnqueueLink(streamId, ep.downloadLink, pendingTitle, thumbnail, null);
334
+ console.log(`βœ… Episode added to stream ${streamId}: ${result.title}`);
335
+ } catch (err) {
336
+ console.error(`❌ Failed to add episode to stream ${streamId}:`, err.message);
337
+ }
338
+ });
339
+ });
340
+
341
+ // POST /constituent/add-song β€” body: { streamId, songUrl, title, thumbnail? }
342
+ // Accepts a direct audio URL + title, downloads and enqueues without searching.
343
+ app.post('/constituent/add-song', requireMainServer, async (req, res) => {
344
+ const { streamId, songUrl, title, thumbnail } = req.body;
345
+
346
+ if (!streamId || !songUrl || !title) {
347
+ return res.status(400).json({ success: false, error: 'streamId, songUrl, and title are required' });
348
+ }
349
+ if (streamId !== constituentConfig.ownerId) {
350
+ return res.status(403).json({ success: false, error: 'Only the constituent owner can add songs to this server' });
351
+ }
352
+
353
+ res.json({ success: true, message: 'Song queued for download and encoding', streamId, title });
354
+
355
+ setImmediate(async () => {
356
+ try {
357
+ if (!streams[streamId]) {
358
+ streams[streamId] = { queue: [], songStartTime: null, streamTimeOffset: 0, users: new Map(), ownerId: streamId, lastActivity: Date.now(), isActive: false };
359
+ }
360
+
361
+ // Download the audio
362
+ const fileName = crypto.randomUUID() + '.mp3';
363
+ const filePath = require('path').join(SONGS_DIR, fileName);
364
+ const writer = require('fs').createWriteStream(filePath);
365
+ const response = await axios({ url: songUrl, method: 'GET', responseType: 'stream', httpsAgent: httpsAgentNoVerify });
366
+ response.data.pipe(writer);
367
+ await new Promise((resolve, reject) => {
368
+ writer.on('finish', resolve);
369
+ writer.on('error', (e) => { writer.destroy(); reject(e); });
370
+ response.data.on('error', reject);
371
+ });
372
+
373
+ const mediaMeta = await getAudioMeta(filePath);
374
+ const songInfo = {
375
+ fileName,
376
+ meta: {
377
+ title,
378
+ thumbnail: thumbnail || DEFAULT_ARTWORK,
379
+ duration: mediaMeta.duration || 0,
380
+ views: 'N/A',
381
+ published: 'N/A',
382
+ source: songUrl,
383
+ videoUrl: null,
384
+ },
385
+ };
386
+ enqueueToStream(streamId, songInfo);
387
+ console.log(`βœ… Song added to stream ${streamId}: ${title}`);
388
+ } catch (err) {
389
+ console.error(`❌ Failed to add song to stream ${streamId}:`, err.message);
390
+ }
391
+ });
392
+ });
393
+
394
+ // ─── Queue status for a stream ────────────────────────────────────────────────
395
+ app.get('/constituent/queue/:streamId', requireMainServer, (req, res) => {
396
+ const { streamId } = req.params;
397
+ const stream = streams[streamId];
398
+ if (!stream) return res.json({ success: true, streamId, queue: [], isActive: false });
399
+
400
+ const queue = stream.queue.map(s => ({
401
+ _sid: s._sid,
402
+ title: s.meta.title,
403
+ thumbnail: s.meta.thumbnail,
404
+ duration: s.meta.duration,
405
+ isVideo: !!s.meta.videoUrl,
406
+ hlsReady: !!(s._hlsPregened && typeof s._hlsStart === 'number'),
407
+ }));
408
+ res.json({
409
+ success: true,
410
+ streamId,
411
+ isActive: stream.isActive,
412
+ queue,
413
+ hlsUrl: stream.isActive ? `/stream-hls/${streamId}/live.m3u8` : null,
414
+ showplayInProgress: stream._showplayInProgress || 0,
415
+ });
416
+ });
417
+
418
+ // ═══════════════════════════════════════════════════════════════════════════
419
+ // HLS PLAYLIST ENDPOINT
420
+ // ═══════════════════════════════════════════════════════════════════════════
421
+
422
+ app.get('/stream-hls/:streamId/live.m3u8', async (req, res) => {
423
+ const streamId = req.params.streamId;
424
+ const POLL_MS = 300;
425
+ const TIMEOUT_MS = 30000;
426
+ let waited = 0;
427
+
428
+ while (waited < TIMEOUT_MS) {
429
+ const state = hlsState[streamId];
430
+ if (state && state.segments.length > 0) break;
431
+ if (!streams[streamId]) return res.status(404).send('Stream not found');
432
+ if (state && !state.generating) {
433
+ return res.status(500).send('HLS generation failed');
434
+ }
435
+ await new Promise(r => setTimeout(r, POLL_MS));
436
+ waited += POLL_MS;
437
+ }
438
+
439
+ const state = hlsState[streamId];
440
+ if (!state || state.segments.length === 0) {
441
+ return res.status(503).set('Retry-After', '3').send('HLS generation timed out, retry shortly');
442
+ }
443
+ const stream = streams[streamId];
444
+ let elapsed = 0;
445
+ if (stream && stream.songStartTime) {
446
+ const current = stream.queue[0];
447
+ const withinSong = (Date.now() - stream.songStartTime) / 1000;
448
+ const hlsStart = (current && current._hlsStart !== undefined) ? current._hlsStart : (stream.streamTimeOffset || 0);
449
+ elapsed = hlsStart + withinSong;
450
+ }
451
+ pruneOldSegments(streamId, elapsed);
452
+ const playlist = buildLivePlaylistAt(streamId, elapsed);
453
+ if (!playlist) return res.status(503).set('Retry-After', '2').send('Segments not ready yet');
454
+ res.setHeader('Content-Type', 'application/vnd.apple.mpegurl');
455
+ res.setHeader('Cache-Control', 'no-cache, no-store');
456
+ res.setHeader('Access-Control-Allow-Origin', '*');
457
+ res.send(playlist);
458
+ });
459
+
460
+ // ─── Current track ────────────────────────────────────────────────────────────
461
+ app.get('/stream/:streamId/currentTrack', (req, res) => {
462
+ const streamId = req.params.streamId;
463
+ const stream = streams[streamId];
464
+ if (!stream) return res.status(404).json({ error: 'Stream not found' });
465
+ const current = stream.queue[0];
466
+ if (!current) return res.json({ queue: [], currentIndex: 0, elapsed: 0, withinSong: 0, hlsUrl: null });
467
+ const songDuration = (current.meta.duration > 0) ? current.meta.duration : (typeof current._hlsEnd === 'number' && typeof current._hlsStart === 'number') ? (current._hlsEnd - current._hlsStart) : 0;
468
+ const hlsStartOfSong = current._hlsStart !== undefined ? current._hlsStart : (stream.streamTimeOffset || 0);
469
+ const rawWithin = stream.songStartTime ? (Date.now() - stream.songStartTime) / 1000 : 0;
470
+ const withinSong = Math.max(0, Math.min(rawWithin, songDuration));
471
+ const elapsed = hlsStartOfSong + withinSong;
472
+ const hlsStateNow = hlsState[streamId];
473
+ const hlsReady = !!(hlsStateNow && hlsStateNow.segments.length > 0 && !hlsStateNow.generating);
474
+ res.json({ queue: stream.queue.map(s => ({ _sid: s._sid, meta: s.meta, tmdb: s.tmdb || null })), currentIndex: 0, elapsed, withinSong, streamTimeOffset: hlsStartOfSong, hlsUrl: `/stream-hls/${streamId}/live.m3u8`, isVideo: !!current.meta.videoUrl, hlsReady, songId: current._sid || null, tmdb: current.tmdb || null });
475
+ });
476
+
477
+ // ─── HLS status ───────────────────────────────────────────────────────────────
478
+ app.get('/stream/:streamId/hlsStatus', (req, res) => {
479
+ const streamId = req.params.streamId;
480
+ const stream = streams[streamId];
481
+ if (!stream) return res.status(404).json({ error: 'Stream not found' });
482
+ const state = hlsState[streamId];
483
+ const current = stream.queue[0];
484
+ const generating = !!(state && state.generating);
485
+ const ready = !!(state && state.segments.length > 0);
486
+ res.json({ ready, generating, segmentsReady: ready, totalSegments: state ? state.segments.length : 0, currentSong: current ? current.meta.title : null, hlsUrl: ready ? `/stream-hls/${streamId}/live.m3u8` : null });
487
+ });
488
+
489
+ // POST /constituent/stop/:streamId β€” stop the stream entirely (owner only via main server)
490
+ app.post('/constituent/stop/:streamId', requireMainServer, (req, res) => {
491
+ const { streamId } = req.params;
492
+ const stream = streams[streamId];
493
+ if (!stream) return res.json({ success: true, message: 'No active stream' });
494
+
495
+ killActiveFFmpeg(streamId);
496
+ for (const song of stream.queue) {
497
+ const fp = path.join(SONGS_DIR, song.fileName);
498
+ if (fs.existsSync(fp)) { try { fs.unlinkSync(fp); } catch {} }
499
+ }
500
+ stream.queue = [];
501
+ stream.isActive = false;
502
+ stream.songStartTime = null;
503
+ stream.streamTimeOffset = 0;
504
+ if (hlsState[streamId]) {
505
+ const hlsStreamDir = path.join(HLS_DIR, streamId);
506
+ if (fs.existsSync(hlsStreamDir)) {
507
+ try { const files = fs.readdirSync(hlsStreamDir); for (const f of files) { try { fs.unlinkSync(path.join(hlsStreamDir, f)); } catch {} } } catch {}
508
+ }
509
+ delete hlsState[streamId]; delete hlsMutex[streamId];
510
+ }
511
+ hlsGeneration[streamId] = (hlsGeneration[streamId] || 0) + 1;
512
+ io.to(`stream:${streamId}`).emit('message', { type: 'stream_ended', message: 'Stream stopped by owner.' });
513
+ res.json({ success: true, message: 'Stream stopped.' });
514
+ });
515
+
516
+ // POST /constituent/skip/:streamId
517
+ app.post('/constituent/skip/:streamId', requireMainServer, (req, res) => {
518
+ const { streamId } = req.params;
519
+ const stream = streams[streamId];
520
+ if (!stream) return res.status(404).json({ success: false, error: 'Stream not found' });
521
+ advanceToNextSong(streamId, false);
522
+ res.json({ success: true });
523
+ });
524
+
525
+ // ═══════════════════════════════════════════════════════════════════════════
526
+ // SOCKET.IO β€” real-time updates for stream viewers
527
+ // ═══════════════════════════════════════════════════════════════════════════
528
+
529
+ io.on('connection', (socket) => {
530
+ const streamId = socket.handshake.query.streamId;
531
+ if (!streamId) { socket.emit('message', { type: 'error', message: 'streamId required' }); socket.disconnect(); return; }
532
+
533
+ socket.join(`stream:${streamId}`);
534
+
535
+ // Initialize stream entry if missing (e.g. adding media not started yet)
536
+ if (!streams[streamId]) {
537
+ streams[streamId] = { queue: [], songStartTime: null, streamTimeOffset: 0, users: new Map(), ownerId: streamId, lastActivity: Date.now(), isActive: false };
538
+ }
539
+
540
+ const stream = streams[streamId];
541
+ stream.lastActivity = Date.now();
542
+
543
+ if (stream.queue.length > 0) sendStreamUpdate(streamId, socket);
544
+
545
+ // If media is being added, immediately notify this socket
546
+ if (stream._showplayInProgress) {
547
+ socket.emit('message', { type: 'showplay_progress', stage: 'processing', title: stream.queue[0]?.meta?.title || 'media' });
548
+ }
549
+
550
+ socket.on('join-stream', (data) => {
551
+ const sid = data?.streamId || streamId;
552
+ socket.join(`stream:${sid}`);
553
+ if (streams[sid]) {
554
+ streams[sid].lastActivity = Date.now();
555
+ sendStreamUpdate(sid, socket);
556
+ }
557
+ });
558
+
559
+ socket.on('heartbeat', (data) => {
560
+ const sid = data?.streamId || streamId;
561
+ if (streams[sid]) streams[sid].lastActivity = Date.now();
562
+ });
563
+
564
+ socket.on('disconnect', () => { console.log(`Socket disconnected from stream ${streamId}`); });
565
+ });
566
+
567
+ function sendStreamUpdate(streamId, specificSocket = null) {
568
+ const stream = streams[streamId];
569
+ if (!stream || (!stream.isActive && stream.queue.length === 0)) return;
570
+ const current = stream.queue[0];
571
+ if (!current) return;
572
+ const hlsStateNow = hlsState[streamId];
573
+ const hlsReady = !!(hlsStateNow && hlsStateNow.segments.length > 0 && !hlsStateNow.generating);
574
+ const songDuration = (current.meta.duration > 0) ? current.meta.duration : (typeof current._hlsEnd === 'number' && typeof current._hlsStart === 'number') ? (current._hlsEnd - current._hlsStart) : 0;
575
+ const hlsStartOfSong = current._hlsStart !== undefined ? current._hlsStart : (stream.streamTimeOffset || 0);
576
+ const rawWithin = stream.songStartTime ? (Date.now() - stream.songStartTime) / 1000 : 0;
577
+ const withinSong = Math.max(0, Math.min(rawWithin, songDuration));
578
+ const absoluteElapsed = hlsStartOfSong + withinSong;
579
+ const nextSong = stream.queue.length > 1 ? stream.queue[1] : null;
580
+ const payload = {
581
+ type: 'update',
582
+ elapsed: absoluteElapsed,
583
+ withinSong,
584
+ streamTimeOffset: hlsStartOfSong,
585
+ currentIndex: 0,
586
+ hlsReady,
587
+ current: { file: `/songs/${current.fileName}`, meta: current.meta, isVideo: !!current.meta.videoUrl, _sid: current._sid, tmdb: current.tmdb || null },
588
+ songId: current._sid,
589
+ next: nextSong ? { file: `/songs/${nextSong.fileName}`, meta: nextSong.meta, isVideo: !!nextSong.meta.videoUrl, tmdb: nextSong.tmdb || null } : null,
590
+ queue: stream.queue,
591
+ queueLength: stream.queue.length,
592
+ hlsUrl: `/stream-hls/${streamId}/live.m3u8`
593
+ };
594
+ if (specificSocket) specificSocket.emit('message', payload);
595
+ else io.to(`stream:${streamId}`).emit('message', payload);
596
+ }
597
+
598
+ // ═══════════════════════════════════════════════════════════════════════════
599
+ // HLS ENGINE (exact logic from main server)
600
+ // ═══════════════════════════════════════════════════════════════════════════
601
+
602
+ function ensureHlsDir(streamId) {
603
+ const dir = path.join(HLS_DIR, streamId);
604
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
605
+ return dir;
606
+ }
607
+
608
+ function killActiveFFmpeg(streamId) {
609
+ hlsGeneration[streamId] = (hlsGeneration[streamId] || 0) + 1;
610
+ const cmd = activeFFmpeg[streamId];
611
+ if (cmd) {
612
+ try { cmd.kill('SIGKILL'); } catch {}
613
+ delete activeFFmpeg[streamId];
614
+ console.log(`πŸ”ͺ FFmpeg killed for stream ${streamId}`);
615
+ }
616
+ hlsMutex[streamId] = Promise.resolve();
617
+ if (hlsState[streamId]) hlsState[streamId].generating = false;
618
+ }
619
+
620
+ function buildLivePlaylistAt(streamId, elapsed) {
621
+ const state = hlsState[streamId];
622
+ if (!state || !state.segments.length) return null;
623
+ const segs = state.segments;
624
+ let startIdx = -1;
625
+ for (let i = 0; i < segs.length; i++) {
626
+ if (segs[i].streamEnd > elapsed) { startIdx = i; break; }
627
+ }
628
+ if (startIdx === -1) return null;
629
+ const window = segs.slice(startIdx, startIdx + HLS_PLAYLIST_WINDOW);
630
+ const mediaSeq = state.mediaSeq + startIdx;
631
+ const lines = ['#EXTM3U','#EXT-X-VERSION:3','#EXT-X-TARGETDURATION:10',`#EXT-X-MEDIA-SEQUENCE:${mediaSeq}`];
632
+ let prevSid = null;
633
+ for (const seg of window) {
634
+ if (prevSid !== null && seg.ownerSid && seg.ownerSid !== prevSid) {
635
+ lines.push('#EXT-X-DISCONTINUITY');
636
+ }
637
+ prevSid = seg.ownerSid || prevSid;
638
+ lines.push(`#EXTINF:${seg.duration.toFixed(6)},`);
639
+ lines.push(seg.uri);
640
+ }
641
+ return lines.join('\n') + '\n';
642
+ }
643
+
644
+ function pruneOldSegments(streamId, elapsed) {
645
+ const state = hlsState[streamId];
646
+ if (!state) return;
647
+ const dropBefore = elapsed - HLS_PLAYLIST_WINDOW * 10 * 3;
648
+ let dropped = 0;
649
+ while (state.segments.length > HLS_MAX_SEGMENTS && state.segments[0].streamEnd < dropBefore) {
650
+ const seg = state.segments.shift();
651
+ dropped++;
652
+ const dir = ensureHlsDir(streamId);
653
+ const file = path.join(dir, path.basename(seg.uri));
654
+ try { if (fs.existsSync(file)) fs.unlinkSync(file); } catch {}
655
+ }
656
+ if (dropped > 0) console.log(`πŸ—‘οΈ Pruned ${dropped} segments for stream ${streamId}`);
657
+ }
658
+
659
+ function parseM3u8Durations(playlistPath) {
660
+ if (!fs.existsSync(playlistPath)) return [];
661
+ const lines = fs.readFileSync(playlistPath, 'utf8').split('\n');
662
+ const entries = [];
663
+ for (let i = 0; i < lines.length; i++) {
664
+ if (lines[i].startsWith('#EXTINF:')) {
665
+ const dur = parseFloat(lines[i].replace('#EXTINF:', ''));
666
+ const file = (lines[i + 1] || '').trim();
667
+ if (file && !file.startsWith('#')) entries.push({ file, dur });
668
+ }
669
+ }
670
+ return entries;
671
+ }
672
+
673
+ function watchForSegments(streamId, dir, segPrefix, songHlsStart, onFirstSeg, ownerSid, state) {
674
+ let cursor = songHlsStart, firstFlushed = false;
675
+ const stitched = new Set();
676
+ const playlistPath = path.join(dir, segPrefix + '.m3u8');
677
+ let pollCount = 0;
678
+ console.log(`πŸ‘ watchForSegments created: ownerSid=${ownerSid?.slice(0,8)} songHlsStart=${songHlsStart} playlistPath=${playlistPath}`);
679
+
680
+ const flush = () => {
681
+ pollCount++;
682
+ const entries = parseM3u8Durations(playlistPath);
683
+ if (pollCount <= 3 || entries.length > 0) {
684
+ console.log(`πŸ‘ watch poll #${pollCount} [${ownerSid?.slice(0,8)}]: playlist=${fs.existsSync(playlistPath)} entries=${entries.length} stitched=${stitched.size} firstFlushed=${firstFlushed}`);
685
+ }
686
+ for (const { file, dur } of entries) {
687
+ if (stitched.has(file)) continue;
688
+ const segPath = path.join(dir, file);
689
+ try { if (fs.statSync(segPath).size < 188) continue; } catch { continue; }
690
+ stitched.add(file);
691
+ const seg = { uri: `/hls/${streamId}/${file}`, _path: segPath, streamStart: cursor, streamEnd: cursor + dur, duration: dur, ownerSid };
692
+ cursor += dur;
693
+ state.segments.push(seg);
694
+ state.totalDuration = cursor;
695
+ if (!firstFlushed) {
696
+ firstFlushed = true;
697
+ state.generating = false;
698
+ if (streams[streamId]?.queue.length > 0) {
699
+ const q0 = streams[streamId].queue[0];
700
+ const sidMatch = ownerSid ? q0._sid === ownerSid : true;
701
+ const startMatch = typeof q0._hlsStart === 'number' && songHlsStart === q0._hlsStart;
702
+ console.log(`πŸ”‘ Ownership check: sid=${q0._sid?.slice(0,8)}==${ownerSid?.slice(0,8)}:${sidMatch} hlsStart=${q0._hlsStart}==${songHlsStart}:${startMatch}`);
703
+ if (sidMatch && startMatch) {
704
+ streams[streamId].songStartTime = Date.now();
705
+ console.log(`⏱️ songStartTime reset for "${q0.meta.title}" [${q0._sid}] (first segment ready)`);
706
+ } else if (sidMatch && q0._hlsStart === undefined) {
707
+ // brief window before _hlsStart is set β€” harmless
708
+ } else {
709
+ console.log(`⚠️ watchForSegments ownership mismatch β€” skipping songStartTime reset. watcher=[${ownerSid}@${songHlsStart}] queue[0]=[${q0._sid}@${q0._hlsStart}]`);
710
+ }
711
+ }
712
+ if (onFirstSeg) onFirstSeg();
713
+ }
714
+ }
715
+ };
716
+
717
+ let lastEntryCount = -1;
718
+ let stablePolls = 0;
719
+ const STABLE_NEEDED = 3;
720
+
721
+ const iv = setInterval(() => {
722
+ flush();
723
+ const entries = parseM3u8Durations(playlistPath);
724
+ if (entries.length === lastEntryCount && !activeFFmpeg[streamId]) {
725
+ stablePolls++;
726
+ if (stablePolls >= STABLE_NEEDED) {
727
+ console.log(`πŸ›‘ watchForSegments auto-stop [${ownerSid?.slice(0,8)}]: stable for ${STABLE_NEEDED} polls, FFmpeg done`);
728
+ clearInterval(iv);
729
+ }
730
+ } else {
731
+ stablePolls = 0;
732
+ lastEntryCount = entries.length;
733
+ }
734
+ }, 800);
735
+ const markDone = () => { flush(); clearInterval(iv); return cursor; };
736
+ return { stop: () => clearInterval(iv), markDone };
737
+ }
738
+
739
+ async function generateSegmentsForSong(streamId, songInfo, isVideo, state) {
740
+ const dir = ensureHlsDir(streamId);
741
+ const songPath = path.join(SONGS_DIR, songInfo.fileName);
742
+ const segPrefix = `seg_${streamId}_${Date.now()}`;
743
+
744
+ console.log(`🎬 FFmpeg starting: ${songPath} isVideo=${isVideo}`);
745
+ if (!fs.existsSync(songPath)) throw new Error(`Source file missing: ${songPath}`);
746
+ const fileStat = fs.statSync(songPath);
747
+ if (fileStat.size === 0) throw new Error('Source file is empty');
748
+ console.log(`πŸ“ Source file: ${(fileStat.size / 1024 / 1024).toFixed(1)}MB`);
749
+
750
+ const segPattern = path.join(dir, segPrefix + '_%03d.ts');
751
+ const playlistPath = path.join(dir, segPrefix + '.m3u8');
752
+ const songHlsStart = state.totalDuration;
753
+ console.log(`🎯 segPrefix=${segPrefix} songHlsStart=${songHlsStart} ownerSid=${songInfo._sid?.slice(0,8)}`);
754
+
755
+ return new Promise((resolve, reject) => {
756
+ const cmd = ffmpeg(songPath);
757
+ if (isVideo) {
758
+ cmd.outputOptions([
759
+ '-map','0:v:0','-map','0:a:0',
760
+ '-c:v','libx264','-preset','ultrafast','-crf','28',
761
+ '-profile:v','main','-level','3.1','-pix_fmt','yuv420p',
762
+ '-vf','scale=854:480',
763
+ '-c:a','aac','-b:a','128k',
764
+ '-f','segment','-segment_time','8',
765
+ '-segment_list',playlistPath,'-segment_list_flags','+live','-segment_format','mpegts',
766
+ ]);
767
+ } else {
768
+ cmd.outputOptions(['-vn','-c:a','aac','-b:a','128k','-f','segment','-segment_time','8','-segment_list',playlistPath,'-segment_list_flags','+live','-segment_format','mpegts']);
769
+ }
770
+ let watcher = null;
771
+ cmd.output(segPattern)
772
+ .on('start', () => {
773
+ activeFFmpeg[streamId] = cmd;
774
+ console.log(`🎬 FFmpeg process started [${streamId}] gen=${hlsGeneration[streamId]}`);
775
+ watcher = watchForSegments(streamId, dir, segPrefix, songHlsStart, () => {
776
+ console.log(`⚑ First segment ready for stream ${streamId}`);
777
+ sendStreamUpdate(streamId);
778
+ }, songInfo._sid, state);
779
+ })
780
+ .on('stderr', line => {
781
+ if (line.includes('Error') || line.includes('error') || line.includes('Invalid')) {
782
+ console.error(`FFmpeg stderr: ${line}`);
783
+ }
784
+ })
785
+ .on('end', () => {
786
+ console.log(`βœ… FFmpeg done for ${streamId}`);
787
+ delete activeFFmpeg[streamId];
788
+ if (!watcher) { resolve(0); return; }
789
+ const finalCursor = watcher.markDone();
790
+ console.log(`πŸ“ Final cursor from playlist: ${finalCursor.toFixed(3)}s`);
791
+ state.totalDuration = finalCursor;
792
+ try { fs.unlinkSync(playlistPath); } catch {}
793
+ resolve(finalCursor);
794
+ })
795
+ .on('error', (err) => {
796
+ console.log(`πŸ’₯ FFmpeg error for ${streamId}: ${err.message}`);
797
+ delete activeFFmpeg[streamId];
798
+ if (err.message && (err.message.includes('SIGKILL') || err.message.includes('killed'))) {
799
+ console.log(`⚑ FFmpeg killed cleanly for ${streamId} (skip)`);
800
+ if (watcher) watcher.stop();
801
+ resolve(0);
802
+ return;
803
+ }
804
+ console.error(`❌ FFmpeg error for ${streamId}:`, err.message);
805
+ if (watcher) watcher.stop();
806
+ reject(err);
807
+ })
808
+ .run();
809
+ });
810
+ }
811
+
812
+ async function appendSongToHls(streamId, songInfo) {
813
+ if (!hlsState[streamId]) {
814
+ hlsState[streamId] = { mediaSeq: 0, segments: [], totalDuration: 0, generating: true };
815
+ console.log(`πŸ“¦ appendSongToHls: created fresh hlsState for ${streamId}`);
816
+ }
817
+ const myGeneration = hlsGeneration[streamId] || 0;
818
+ const prev = hlsMutex[streamId] || Promise.resolve();
819
+ console.log(`πŸ“Œ appendSongToHls queued: "${songInfo.meta.title}" [${songInfo._sid?.slice(0,8)}] gen=${myGeneration}`);
820
+ const next = prev.then(async () => {
821
+ const currentGen = hlsGeneration[streamId] || 0;
822
+ if (currentGen !== myGeneration) {
823
+ console.log(`⏩ Skipping stale appendSongToHls for "${songInfo.meta.title}" (gen ${myGeneration} vs ${currentGen})`);
824
+ return;
825
+ }
826
+ const isVideo = !!(songInfo.meta && songInfo.meta.videoUrl);
827
+ const state = hlsState[streamId];
828
+ if (!state) {
829
+ console.log(`⏩ Skipping appendSongToHls for "${songInfo.meta.title}" β€” hlsState gone`);
830
+ return;
831
+ }
832
+ state.generating = true;
833
+ songInfo._hlsStart = state.totalDuration;
834
+ console.log(`πŸ“ _hlsStart set to ${songInfo._hlsStart.toFixed(2)}s for "${songInfo.meta.title}"`);
835
+ try {
836
+ const finalCursor = await generateSegmentsForSong(streamId, songInfo, isVideo, state);
837
+ if (typeof finalCursor === 'number' && finalCursor > 0) {
838
+ songInfo._hlsEnd = finalCursor;
839
+ const actualDuration = finalCursor - songInfo._hlsStart;
840
+ if (actualDuration > 0 && Math.abs(actualDuration - (songInfo.meta.duration || 0)) > 30) {
841
+ console.log(`πŸ“ Correcting meta.duration for "${songInfo.meta.title}": ${(songInfo.meta.duration || 0).toFixed(1)}s β†’ ${actualDuration.toFixed(1)}s`);
842
+ songInfo.meta.duration = actualDuration;
843
+ }
844
+ songInfo._hlsDurationTrusted = true;
845
+ } else {
846
+ songInfo._hlsEnd = state.totalDuration;
847
+ console.log(`⚑ Encode killed for "${songInfo.meta.title}" β€” hlsEnd set to ${songInfo._hlsEnd?.toFixed(2)}s`);
848
+ }
849
+ state.generating = false;
850
+ console.log(`πŸ“Ί HLS done for "${songInfo.meta.title}": hlsStart=${songInfo._hlsStart?.toFixed(2)}s hlsEnd=${songInfo._hlsEnd?.toFixed(2)}s segs=${state.segments.length}`);
851
+ const finalGen = hlsGeneration[streamId] || 0;
852
+ const liveStream = streams[streamId];
853
+ if (finalGen === myGeneration && liveStream && liveStream.queue[0]?._sid === songInfo._sid) {
854
+ if (!liveStream.songStartTime) {
855
+ liveStream.songStartTime = Date.now();
856
+ console.log(`⏱️ songStartTime set post-encode for "${songInfo.meta.title}" [${songInfo._sid}]`);
857
+ sendStreamUpdate(streamId);
858
+ }
859
+ preGenerateNextSong(streamId).catch(console.error);
860
+ }
861
+ } catch (err) {
862
+ console.error(`HLS generation failed for stream ${streamId}:`, err);
863
+ if (hlsState[streamId]) hlsState[streamId].generating = false;
864
+ }
865
+ });
866
+ hlsMutex[streamId] = next;
867
+ return next;
868
+ }
869
+
870
+ async function preGenerateNextSong(streamId) {
871
+ const stream = streams[streamId];
872
+ if (!stream || stream.queue.length < 2) return;
873
+ const nextSong = stream.queue[1];
874
+ if (!nextSong || nextSong._hlsPregened || nextSong._hlsPregenInProgress) return;
875
+ nextSong._hlsPregenInProgress = true;
876
+ const sid = nextSong._sid;
877
+ console.log(`πŸ”„ Pre-generating HLS for next: ${nextSong.meta.title} [${sid}]`);
878
+ try {
879
+ await appendSongToHls(streamId, nextSong);
880
+ } catch (err) {
881
+ nextSong._hlsPregenInProgress = false;
882
+ console.error(`Pre-gen failed for "${nextSong.meta.title}":`, err.message);
883
+ return;
884
+ }
885
+ const streamNow = streams[streamId];
886
+ const stillQueued = streamNow && streamNow.queue.some(s => s._sid === sid);
887
+ const encodingFinished = typeof nextSong._hlsEnd === 'number' && typeof nextSong._hlsStart === 'number' && nextSong._hlsEnd > nextSong._hlsStart;
888
+ if (stillQueued && encodingFinished) {
889
+ nextSong._hlsPregened = true;
890
+ console.log(`βœ… Pre-gen confirmed for "${nextSong.meta.title}" [${sid}]: hlsStart=${nextSong._hlsStart.toFixed(2)}s hlsEnd=${nextSong._hlsEnd.toFixed(2)}s`);
891
+ } else {
892
+ nextSong._hlsPregened = false;
893
+ nextSong._hlsPregenInProgress = false;
894
+ delete nextSong._hlsStart;
895
+ delete nextSong._hlsEnd;
896
+ console.log(`⚠️ Pre-gen invalidated for "${nextSong.meta.title}" [${sid}]`);
897
+ }
898
+ }
899
+
900
+ function advanceToNextSong(streamId, autoAdvance = false) {
901
+ const stream = streams[streamId];
902
+ if (!stream) return false;
903
+ if (autoAdvance) stream._notifyOnStart = true;
904
+ else delete stream._notifyOnStart;
905
+ killActiveFFmpeg(streamId);
906
+ const finishedSong = stream.queue.shift();
907
+ const filePath = path.join(SONGS_DIR, finishedSong.fileName);
908
+ if (fs.existsSync(filePath)) { try { fs.unlinkSync(filePath); } catch {} }
909
+
910
+ if (stream.queue.length === 0) {
911
+ stream.isActive = false;
912
+ stream.streamTimeOffset = 0;
913
+ stream.songStartTime = null;
914
+ if (hlsState[streamId]) {
915
+ const hlsDir = path.join(HLS_DIR, streamId);
916
+ if (fs.existsSync(hlsDir)) {
917
+ try { const files = fs.readdirSync(hlsDir); for (const f of files) { try { fs.unlinkSync(path.join(hlsDir, f)); } catch {} } } catch {}
918
+ }
919
+ delete hlsState[streamId]; delete hlsMutex[streamId];
920
+ }
921
+ hlsGeneration[streamId] = (hlsGeneration[streamId] || 0) + 1;
922
+ console.log(`πŸ”„ Stream ${streamId} queue empty β€” HLS state reset for fresh start`);
923
+ io.to(`stream:${streamId}`).emit('message', { type: 'stream_ended', message: 'Queue is empty.' });
924
+ return false;
925
+ }
926
+
927
+ const nextSong = stream.queue[0];
928
+ const pregenIsValid = nextSong._hlsPregened && typeof nextSong._hlsStart === 'number' && typeof nextSong._hlsEnd === 'number' && nextSong._hlsEnd > nextSong._hlsStart;
929
+
930
+ if (pregenIsValid) {
931
+ stream.streamTimeOffset = nextSong._hlsStart;
932
+ stream.songStartTime = Date.now();
933
+ stream.lastActivity = Date.now();
934
+ stream.isActive = true;
935
+ delete stream._notifyOnStart;
936
+ sendStreamUpdate(streamId);
937
+ preGenerateNextSong(streamId).catch(console.error);
938
+ } else {
939
+ nextSong._hlsPregened = nextSong._hlsPregenInProgress = false;
940
+ delete nextSong._hlsStart; delete nextSong._hlsEnd;
941
+ if (hlsState[streamId]) {
942
+ const hlsDir = path.join(HLS_DIR, streamId);
943
+ if (fs.existsSync(hlsDir)) {
944
+ try { const files = fs.readdirSync(hlsDir); for (const f of files) { try { fs.unlinkSync(path.join(hlsDir, f)); } catch {} } } catch {}
945
+ }
946
+ delete hlsState[streamId]; delete hlsMutex[streamId];
947
+ }
948
+ hlsGeneration[streamId] = (hlsGeneration[streamId] || 0) + 1;
949
+ stream.songStartTime = null;
950
+ stream.lastActivity = Date.now();
951
+ stream.isActive = true;
952
+ appendSongToHls(streamId, nextSong).then(() => {
953
+ sendStreamUpdate(streamId);
954
+ preGenerateNextSong(streamId).catch(console.error);
955
+ }).catch(console.error);
956
+ }
957
+ return true;
958
+ }
959
+
960
+ function enqueueToStream(streamId, songInfo) {
961
+ if (!streams[streamId]) {
962
+ songInfo._sid = crypto.randomUUID();
963
+ streams[streamId] = { queue: [songInfo], songStartTime: null, streamTimeOffset: 0, users: new Map(), ownerId: streamId, lastActivity: Date.now(), isActive: true };
964
+ appendSongToHls(streamId, songInfo).then(() => sendStreamUpdate(streamId)).catch(console.error);
965
+ return { songInfo, position: 1, started: true };
966
+ }
967
+ const stream = streams[streamId];
968
+ songInfo._sid = crypto.randomUUID();
969
+ stream.queue.push(songInfo);
970
+ stream.lastActivity = Date.now();
971
+ const position = stream.queue.length;
972
+ if (!stream.isActive && position === 1 && !stream._showplayInProgress) {
973
+ // Stream was idle/ended β€” ensure HLS state is fresh so this song starts at t=0.
974
+ if (!hlsState[streamId] || hlsState[streamId].totalDuration > 0) {
975
+ if (hlsState[streamId]) {
976
+ const hlsDir = path.join(HLS_DIR, streamId);
977
+ if (fs.existsSync(hlsDir)) {
978
+ try { const files = fs.readdirSync(hlsDir); for (const f of files) { try { fs.unlinkSync(path.join(hlsDir, f)); } catch {} } } catch {}
979
+ }
980
+ delete hlsState[streamId]; delete hlsMutex[streamId];
981
+ }
982
+ hlsGeneration[streamId] = (hlsGeneration[streamId] || 0) + 1;
983
+ }
984
+ stream.streamTimeOffset = 0;
985
+ stream.songStartTime = null;
986
+ stream.isActive = true;
987
+ appendSongToHls(streamId, songInfo).then(() => sendStreamUpdate(streamId)).catch(console.error);
988
+ return { songInfo, position, started: true };
989
+ }
990
+ if (stream.isActive && position >= 2) preGenerateNextSong(streamId).catch(console.error);
991
+ sendStreamUpdate(streamId);
992
+ return { songInfo, position, started: false };
993
+ }
994
+
995
+ // ═══════════════════════════════════════════════════════════════════════════
996
+ // DOWNLOAD HELPERS
997
+ // ═══════════════════════════════════════════════════════════════════════════
998
+
999
+ const DIRECT_VIDEO_EXTS = /\.(mkv|mp4|mov|avi|webm|m4v|flv|wmv|ts)(\?.*)?$/i;
1000
+ function isDirectVideoUrl(url) {
1001
+ if (!url) return false;
1002
+ try { return DIRECT_VIDEO_EXTS.test(new URL(url).pathname); } catch { return DIRECT_VIDEO_EXTS.test(url); }
1003
+ }
1004
+
1005
+ function getAudioMeta(filePath) {
1006
+ return new Promise((resolve, reject) => {
1007
+ ffmpeg.ffprobe(filePath, (err, metadata) => {
1008
+ if (err) return reject(err);
1009
+ function parseDurationTag(tag) {
1010
+ if (!tag || typeof tag !== 'string') return 0;
1011
+ const m = tag.match(/^(\d+):(\d+):(\d+(?:\.\d+)?)$/);
1012
+ if (!m) return 0;
1013
+ return parseInt(m[1], 10) * 3600 + parseInt(m[2], 10) * 60 + parseFloat(m[3]);
1014
+ }
1015
+ const candidates = [
1016
+ parseFloat(metadata.format?.duration) || 0,
1017
+ ...(metadata.streams || []).flatMap(s => [
1018
+ parseFloat(s.duration) || 0,
1019
+ parseDurationTag(s.tags?.DURATION),
1020
+ parseDurationTag(s.tags?.duration),
1021
+ ]),
1022
+ ];
1023
+ const duration = Math.max(...candidates.filter(n => isFinite(n) && n > 0), 0);
1024
+ resolve({ duration, size: metadata.format.size, bit_rate: metadata.format.bit_rate });
1025
+ });
1026
+ });
1027
+ }
1028
+
1029
+ async function downloadVideoFile(downloadUrl) {
1030
+ const fileName = crypto.randomUUID() + '.mp4';
1031
+ const filePath = path.join(SONGS_DIR, fileName);
1032
+ const writer = fs.createWriteStream(filePath);
1033
+ try {
1034
+ const response = await axios({ url: downloadUrl, method: 'GET', responseType: 'stream', httpsAgent: httpsAgentNoVerify });
1035
+ const contentLength = parseInt(response.headers['content-length'] || '0', 10);
1036
+ let bytesWritten = 0;
1037
+ response.data.on('data', chunk => { bytesWritten += chunk.length; });
1038
+ response.data.pipe(writer);
1039
+ await new Promise((resolve, reject) => {
1040
+ writer.on('finish', resolve);
1041
+ writer.on('error', reject);
1042
+ response.data.on('error', reject);
1043
+ });
1044
+ if (contentLength > 0 && bytesWritten < contentLength * 0.95) {
1045
+ throw new Error(`Download truncated: got ${bytesWritten} of ${contentLength} bytes`);
1046
+ }
1047
+ } catch (err) {
1048
+ writer.destroy();
1049
+ if (fs.existsSync(filePath)) { try { fs.unlinkSync(filePath); } catch {} }
1050
+ throw err;
1051
+ }
1052
+ return { fileName, filePath };
1053
+ }
1054
+
1055
+ async function showplayEnqueueLink(streamId, pendingLink, pendingTitle, thumbnail, tmdbInfo = null) {
1056
+ if (!streams[streamId]) {
1057
+ streams[streamId] = { queue: [], songStartTime: null, streamTimeOffset: 0, users: new Map(), ownerId: streamId, lastActivity: Date.now(), isActive: false };
1058
+ }
1059
+ streams[streamId]._showplayInProgress = (streams[streamId]._showplayInProgress || 0) + 1;
1060
+
1061
+ // Notify listeners that download is starting
1062
+ io.to(`stream:${streamId}`).emit('message', { type: 'showplay_progress', stage: 'downloading', title: pendingTitle });
1063
+ console.log(`πŸ“₯ Downloading: ${pendingTitle}`);
1064
+
1065
+ let directUrl;
1066
+ if (isDirectVideoUrl(pendingLink)) {
1067
+ directUrl = pendingLink;
1068
+ } else {
1069
+ let extractRes;
1070
+ try {
1071
+ extractRes = await axios.get(`https://downw.vercel.app/extract?url=${encodeURIComponent(pendingLink)}`, { timeout: 60000, httpsAgent: httpsAgentNoVerify });
1072
+ } catch (err) { throw new Error(`Extract API failed: ${err.message}`); }
1073
+ directUrl = extractRes.data?.downloadUrl;
1074
+ if (!directUrl) throw new Error('No download URL returned by extractor');
1075
+ }
1076
+
1077
+ let fileName, filePath;
1078
+ try { ({ fileName, filePath } = await downloadVideoFile(directUrl)); }
1079
+ catch (err) { throw new Error(`Download failed: ${err.message}`); }
1080
+
1081
+ // Notify listeners that encoding is starting
1082
+ io.to(`stream:${streamId}`).emit('message', { type: 'showplay_progress', stage: 'encoding', title: pendingTitle });
1083
+ console.log(`βš™οΈ Encoding: ${pendingTitle}`);
1084
+
1085
+ let mediaMeta;
1086
+ try { mediaMeta = await getAudioMeta(filePath); }
1087
+ catch (e) { try { fs.unlinkSync(filePath); } catch {} throw new Error('ffprobe could not read the video file'); }
1088
+
1089
+ if (mediaMeta.size > SHOWPLAY_MAX_FILE_SIZE) {
1090
+ try { fs.unlinkSync(filePath); } catch {}
1091
+ throw new Error(`File too large (${(mediaMeta.size / (1024 ** 3)).toFixed(2)} GB). Max 2 GB.`);
1092
+ }
1093
+ if (mediaMeta.duration > SHOWPLAY_MAX_DURATION) {
1094
+ try { fs.unlinkSync(filePath); } catch {}
1095
+ throw new Error(`Video too long. Max 6 hours.`);
1096
+ }
1097
+
1098
+ if (streams[streamId]) streams[streamId]._showplayInProgress = Math.max(0, (streams[streamId]._showplayInProgress || 1) - 1);
1099
+
1100
+ const effectivePoster = tmdbInfo?.poster || thumbnail || DEFAULT_ARTWORK;
1101
+ const songInfo = {
1102
+ fileName,
1103
+ meta: {
1104
+ title: tmdbInfo?.title || pendingTitle || 'Unknown',
1105
+ thumbnail: effectivePoster,
1106
+ duration: mediaMeta.duration || 0,
1107
+ views: 'N/A',
1108
+ published: tmdbInfo?.releaseDate || 'N/A',
1109
+ source: pendingLink,
1110
+ videoUrl: pendingLink || 'showplay',
1111
+ },
1112
+ tmdb: tmdbInfo || null,
1113
+ isShowplay: true,
1114
+ };
1115
+
1116
+ enqueueToStream(streamId, songInfo);
1117
+ return { title: songInfo.meta.title, duration: mediaMeta.duration, thumbnail: effectivePoster };
1118
+ }
1119
+
1120
+ // ═══════════════════════════════════════════════════════════════════════════
1121
+ // BACKGROUND TIMERS
1122
+ // ═══════════════════════════════════════════════════════════════════════════
1123
+
1124
+ // Auto-advance
1125
+ setInterval(async () => {
1126
+ try {
1127
+ for (const streamId in streams) {
1128
+ const stream = streams[streamId];
1129
+ if (!stream.isActive) continue;
1130
+ const current = stream.queue[0];
1131
+ if (!current) continue;
1132
+ let songDuration;
1133
+ if (current._hlsDurationTrusted && typeof current._hlsEnd === 'number' && typeof current._hlsStart === 'number') {
1134
+ songDuration = current._hlsEnd - current._hlsStart;
1135
+ } else if (current.meta.duration > 0) {
1136
+ songDuration = current.meta.duration;
1137
+ } else if (typeof current._hlsEnd === 'number' && typeof current._hlsStart === 'number') {
1138
+ songDuration = current._hlsEnd - current._hlsStart;
1139
+ } else continue;
1140
+ if (songDuration < 5 || !stream.songStartTime) continue;
1141
+ const elapsed = (Date.now() - stream.songStartTime) / 1000;
1142
+ if (elapsed >= songDuration + 3) {
1143
+ if (stream._advancingFromSid === current._sid) continue;
1144
+ stream._advancingFromSid = current._sid;
1145
+ console.log(`⏭️ Auto-advance "${current.meta.title}": elapsed=${elapsed.toFixed(1)}s duration=${songDuration.toFixed(1)}s`);
1146
+ advanceToNextSong(streamId, true);
1147
+ if (stream._advancingFromSid === current._sid) delete stream._advancingFromSid;
1148
+ }
1149
+ }
1150
+ } catch (err) { console.error('Auto-advance error:', err); }
1151
+ }, 1000);
1152
+
1153
+ // Segment pruning
1154
+ setInterval(() => {
1155
+ for (const streamId in streams) {
1156
+ const stream = streams[streamId];
1157
+ if (!stream.isActive || !stream.songStartTime) continue;
1158
+ const current = stream.queue[0];
1159
+ if (!current) continue;
1160
+ const hlsStart = current._hlsStart !== undefined ? current._hlsStart : (stream.streamTimeOffset || 0);
1161
+ const withinSong = (Date.now() - stream.songStartTime) / 1000;
1162
+ pruneOldSegments(streamId, hlsStart + withinSong);
1163
+ }
1164
+ }, 30 * 1000);
1165
+
1166
+ // Inactivity cleanup
1167
+ setInterval(() => {
1168
+ const now = Date.now(), toDelete = [];
1169
+ for (const streamId in streams) {
1170
+ const stream = streams[streamId];
1171
+ if ((!stream.users || stream.users.size === 0) && (now - (stream.lastActivity || 0)) > STREAM_CLEANUP_INTERVAL) {
1172
+ toDelete.push(streamId);
1173
+ }
1174
+ }
1175
+ for (const streamId of toDelete) {
1176
+ const stream = streams[streamId];
1177
+ killActiveFFmpeg(streamId);
1178
+ for (const song of stream.queue) { const fp = path.join(SONGS_DIR, song.fileName); if (fs.existsSync(fp)) { try { fs.unlinkSync(fp); } catch {} } }
1179
+ const hlsStreamDir = path.join(HLS_DIR, streamId);
1180
+ if (fs.existsSync(hlsStreamDir)) { try { fs.rmSync(hlsStreamDir, { recursive: true }); } catch {} }
1181
+ delete streams[streamId]; delete hlsState[streamId]; delete hlsMutex[streamId]; delete hlsGeneration[streamId];
1182
+ console.log(`🧹 Cleaned up stream: ${streamId}`);
1183
+ }
1184
+ }, 10 * 60 * 1000);
1185
+
1186
+ // ═══════════════════════════════════════════════════════════════════════════
1187
+ // LAUNCH
1188
+ // ═══════════════════════════════════════════════════════════════════════════
1189
+
1190
+ server.listen(PORT, async () => {
1191
+ console.log(`πŸš€ Constituent server running on port ${PORT}`);
1192
+ console.log(`πŸ‘€ Owner ID: ${CONSTITUENT_OWNER_ID}`);
1193
+ try {
1194
+ const ipRes = await axios.get('https://api.ipify.org?format=json', { timeout: 5000 });
1195
+ console.log(`🌐 Public IP: ${ipRes.data.ip}`);
1196
+ } catch {}
1197
+ });
1198
+
1199
+ process.once('SIGINT', () => { server.close(); process.exit(0); });
1200
+ process.once('SIGTERM', () => { server.close(); process.exit(0); });