reikernx commited on
Commit
4cbcde0
Β·
verified Β·
1 Parent(s): d169ddc

Upload constituent server files

Browse files
Files changed (3) hide show
  1. Dockerfile +43 -0
  2. package.json +11 -0
  3. server.js +1137 -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 constituent-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": "trial",
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,1137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ });
415
+ });
416
+
417
+ // ═══════════════════════════════════════════════════════════════════════════
418
+ // HLS PLAYLIST ENDPOINT
419
+ // ═══════════════════════════════════════════════════════════════════════════
420
+
421
+ app.get('/stream-hls/:streamId/live.m3u8', async (req, res) => {
422
+ const streamId = req.params.streamId;
423
+ const POLL_MS = 300;
424
+ const TIMEOUT_MS = 30000;
425
+ let waited = 0;
426
+
427
+ while (waited < TIMEOUT_MS) {
428
+ const state = hlsState[streamId];
429
+ if (state && state.segments.length > 0) break;
430
+ if (!streams[streamId]) return res.status(404).send('Stream not found');
431
+ if (state && !state.generating) {
432
+ return res.status(500).send('HLS generation failed');
433
+ }
434
+ await new Promise(r => setTimeout(r, POLL_MS));
435
+ waited += POLL_MS;
436
+ }
437
+
438
+ const state = hlsState[streamId];
439
+ if (!state || state.segments.length === 0) {
440
+ return res.status(503).set('Retry-After', '3').send('HLS generation timed out, retry shortly');
441
+ }
442
+ const stream = streams[streamId];
443
+ let elapsed = 0;
444
+ if (stream && stream.songStartTime) {
445
+ const current = stream.queue[0];
446
+ const withinSong = (Date.now() - stream.songStartTime) / 1000;
447
+ const hlsStart = (current && current._hlsStart !== undefined) ? current._hlsStart : (stream.streamTimeOffset || 0);
448
+ elapsed = hlsStart + withinSong;
449
+ }
450
+ pruneOldSegments(streamId, elapsed);
451
+ const playlist = buildLivePlaylistAt(streamId, elapsed);
452
+ if (!playlist) return res.status(503).set('Retry-After', '2').send('Segments not ready yet');
453
+ res.setHeader('Content-Type', 'application/vnd.apple.mpegurl');
454
+ res.setHeader('Cache-Control', 'no-cache, no-store');
455
+ res.setHeader('Access-Control-Allow-Origin', '*');
456
+ res.send(playlist);
457
+ });
458
+
459
+ // ─── Current track ────────────────────────────────────────────────────────────
460
+ app.get('/stream/:streamId/currentTrack', (req, res) => {
461
+ const streamId = req.params.streamId;
462
+ const stream = streams[streamId];
463
+ if (!stream) return res.status(404).json({ error: 'Stream not found' });
464
+ const current = stream.queue[0];
465
+ if (!current) return res.json({ queue: [], currentIndex: 0, elapsed: 0, withinSong: 0, hlsUrl: null });
466
+ const songDuration = (current.meta.duration > 0) ? current.meta.duration : (typeof current._hlsEnd === 'number' && typeof current._hlsStart === 'number') ? (current._hlsEnd - current._hlsStart) : 0;
467
+ const hlsStartOfSong = current._hlsStart !== undefined ? current._hlsStart : (stream.streamTimeOffset || 0);
468
+ const rawWithin = stream.songStartTime ? (Date.now() - stream.songStartTime) / 1000 : 0;
469
+ const withinSong = Math.max(0, Math.min(rawWithin, songDuration));
470
+ const elapsed = hlsStartOfSong + withinSong;
471
+ const hlsStateNow = hlsState[streamId];
472
+ const hlsReady = !!(hlsStateNow && hlsStateNow.segments.length > 0 && !hlsStateNow.generating);
473
+ 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 });
474
+ });
475
+
476
+ // ─── HLS status ───────────────────────────────────────────────────────────────
477
+ app.get('/stream/:streamId/hlsStatus', (req, res) => {
478
+ const streamId = req.params.streamId;
479
+ const stream = streams[streamId];
480
+ if (!stream) return res.status(404).json({ error: 'Stream not found' });
481
+ const state = hlsState[streamId];
482
+ const current = stream.queue[0];
483
+ const generating = !!(state && state.generating);
484
+ const ready = !!(state && state.segments.length > 0);
485
+ 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 });
486
+ });
487
+
488
+ // ─── Skip song (owner only via main server) ───────────────────────────────────
489
+ app.post('/constituent/skip/:streamId', requireMainServer, (req, res) => {
490
+ const { streamId } = req.params;
491
+ const stream = streams[streamId];
492
+ if (!stream) return res.status(404).json({ success: false, error: 'Stream not found' });
493
+ advanceToNextSong(streamId, false);
494
+ res.json({ success: true });
495
+ });
496
+
497
+ // ═══════════════════════════════════════════════════════════════════════════
498
+ // SOCKET.IO β€” real-time updates for stream viewers
499
+ // ═══════════════════════════════════════════════════════════════════════════
500
+
501
+ io.on('connection', (socket) => {
502
+ const streamId = socket.handshake.query.streamId;
503
+ if (!streamId) { socket.emit('message', { type: 'error', message: 'streamId required' }); socket.disconnect(); return; }
504
+ const stream = streams[streamId];
505
+ if (!stream) { socket.emit('message', { type: 'error', message: 'Stream not found' }); socket.disconnect(); return; }
506
+ socket.join(`stream:${streamId}`);
507
+ stream.lastActivity = Date.now();
508
+ sendStreamUpdate(streamId, socket);
509
+ socket.on('disconnect', () => { console.log(`Socket disconnected from stream ${streamId}`); });
510
+ });
511
+
512
+ function sendStreamUpdate(streamId, specificSocket = null) {
513
+ const stream = streams[streamId];
514
+ if (!stream || (!stream.isActive && stream.queue.length === 0)) return;
515
+ const current = stream.queue[0];
516
+ if (!current) return;
517
+ const hlsStateNow = hlsState[streamId];
518
+ const hlsReady = !!(hlsStateNow && hlsStateNow.segments.length > 0 && !hlsStateNow.generating);
519
+ const songDuration = (current.meta.duration > 0) ? current.meta.duration : (typeof current._hlsEnd === 'number' && typeof current._hlsStart === 'number') ? (current._hlsEnd - current._hlsStart) : 0;
520
+ const hlsStartOfSong = current._hlsStart !== undefined ? current._hlsStart : (stream.streamTimeOffset || 0);
521
+ const rawWithin = stream.songStartTime ? (Date.now() - stream.songStartTime) / 1000 : 0;
522
+ const withinSong = Math.max(0, Math.min(rawWithin, songDuration));
523
+ const absoluteElapsed = hlsStartOfSong + withinSong;
524
+ const nextSong = stream.queue.length > 1 ? stream.queue[1] : null;
525
+ const payload = {
526
+ type: 'update',
527
+ elapsed: absoluteElapsed,
528
+ withinSong,
529
+ streamTimeOffset: hlsStartOfSong,
530
+ currentIndex: 0,
531
+ hlsReady,
532
+ current: { file: `/songs/${current.fileName}`, meta: current.meta, isVideo: !!current.meta.videoUrl, _sid: current._sid, tmdb: current.tmdb || null },
533
+ songId: current._sid,
534
+ next: nextSong ? { file: `/songs/${nextSong.fileName}`, meta: nextSong.meta, isVideo: !!nextSong.meta.videoUrl, tmdb: nextSong.tmdb || null } : null,
535
+ queue: stream.queue,
536
+ queueLength: stream.queue.length,
537
+ hlsUrl: `/stream-hls/${streamId}/live.m3u8`
538
+ };
539
+ if (specificSocket) specificSocket.emit('message', payload);
540
+ else io.to(`stream:${streamId}`).emit('message', payload);
541
+ }
542
+
543
+ // ═══════════════════════════════════════════════════════════════════════════
544
+ // HLS ENGINE (exact logic from main server)
545
+ // ═══════════════════════════════════════════════════════════════════════════
546
+
547
+ function ensureHlsDir(streamId) {
548
+ const dir = path.join(HLS_DIR, streamId);
549
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
550
+ return dir;
551
+ }
552
+
553
+ function killActiveFFmpeg(streamId) {
554
+ hlsGeneration[streamId] = (hlsGeneration[streamId] || 0) + 1;
555
+ const cmd = activeFFmpeg[streamId];
556
+ if (cmd) {
557
+ try { cmd.kill('SIGKILL'); } catch {}
558
+ delete activeFFmpeg[streamId];
559
+ console.log(`πŸ”ͺ FFmpeg killed for stream ${streamId}`);
560
+ }
561
+ hlsMutex[streamId] = Promise.resolve();
562
+ if (hlsState[streamId]) hlsState[streamId].generating = false;
563
+ }
564
+
565
+ function buildLivePlaylistAt(streamId, elapsed) {
566
+ const state = hlsState[streamId];
567
+ if (!state || !state.segments.length) return null;
568
+ const segs = state.segments;
569
+ let startIdx = -1;
570
+ for (let i = 0; i < segs.length; i++) {
571
+ if (segs[i].streamEnd > elapsed) { startIdx = i; break; }
572
+ }
573
+ if (startIdx === -1) return null;
574
+ const window = segs.slice(startIdx, startIdx + HLS_PLAYLIST_WINDOW);
575
+ const mediaSeq = state.mediaSeq + startIdx;
576
+ const lines = ['#EXTM3U','#EXT-X-VERSION:3','#EXT-X-TARGETDURATION:10',`#EXT-X-MEDIA-SEQUENCE:${mediaSeq}`];
577
+ let prevSid = null;
578
+ for (const seg of window) {
579
+ if (prevSid !== null && seg.ownerSid && seg.ownerSid !== prevSid) {
580
+ lines.push('#EXT-X-DISCONTINUITY');
581
+ }
582
+ prevSid = seg.ownerSid || prevSid;
583
+ lines.push(`#EXTINF:${seg.duration.toFixed(6)},`);
584
+ lines.push(seg.uri);
585
+ }
586
+ return lines.join('\n') + '\n';
587
+ }
588
+
589
+ function pruneOldSegments(streamId, elapsed) {
590
+ const state = hlsState[streamId];
591
+ if (!state) return;
592
+ const dropBefore = elapsed - HLS_PLAYLIST_WINDOW * 10 * 3;
593
+ let dropped = 0;
594
+ while (state.segments.length > HLS_MAX_SEGMENTS && state.segments[0].streamEnd < dropBefore) {
595
+ const seg = state.segments.shift();
596
+ dropped++;
597
+ const dir = ensureHlsDir(streamId);
598
+ const file = path.join(dir, path.basename(seg.uri));
599
+ try { if (fs.existsSync(file)) fs.unlinkSync(file); } catch {}
600
+ }
601
+ if (dropped > 0) console.log(`πŸ—‘οΈ Pruned ${dropped} segments for stream ${streamId}`);
602
+ }
603
+
604
+ function parseM3u8Durations(playlistPath) {
605
+ if (!fs.existsSync(playlistPath)) return [];
606
+ const lines = fs.readFileSync(playlistPath, 'utf8').split('\n');
607
+ const entries = [];
608
+ for (let i = 0; i < lines.length; i++) {
609
+ if (lines[i].startsWith('#EXTINF:')) {
610
+ const dur = parseFloat(lines[i].replace('#EXTINF:', ''));
611
+ const file = (lines[i + 1] || '').trim();
612
+ if (file && !file.startsWith('#')) entries.push({ file, dur });
613
+ }
614
+ }
615
+ return entries;
616
+ }
617
+
618
+ function watchForSegments(streamId, dir, segPrefix, songHlsStart, onFirstSeg, ownerSid, state) {
619
+ let cursor = songHlsStart, firstFlushed = false;
620
+ const stitched = new Set();
621
+ const playlistPath = path.join(dir, segPrefix + '.m3u8');
622
+ let pollCount = 0;
623
+ console.log(`πŸ‘ watchForSegments created: ownerSid=${ownerSid?.slice(0,8)} songHlsStart=${songHlsStart} playlistPath=${playlistPath}`);
624
+
625
+ const flush = () => {
626
+ pollCount++;
627
+ const entries = parseM3u8Durations(playlistPath);
628
+ if (pollCount <= 3 || entries.length > 0) {
629
+ console.log(`πŸ‘ watch poll #${pollCount} [${ownerSid?.slice(0,8)}]: playlist=${fs.existsSync(playlistPath)} entries=${entries.length} stitched=${stitched.size} firstFlushed=${firstFlushed}`);
630
+ }
631
+ for (const { file, dur } of entries) {
632
+ if (stitched.has(file)) continue;
633
+ const segPath = path.join(dir, file);
634
+ try { if (fs.statSync(segPath).size < 188) continue; } catch { continue; }
635
+ stitched.add(file);
636
+ const seg = { uri: `/hls/${streamId}/${file}`, _path: segPath, streamStart: cursor, streamEnd: cursor + dur, duration: dur, ownerSid };
637
+ cursor += dur;
638
+ state.segments.push(seg);
639
+ state.totalDuration = cursor;
640
+ if (!firstFlushed) {
641
+ firstFlushed = true;
642
+ state.generating = false;
643
+ if (streams[streamId]?.queue.length > 0) {
644
+ const q0 = streams[streamId].queue[0];
645
+ const sidMatch = ownerSid ? q0._sid === ownerSid : true;
646
+ const startMatch = typeof q0._hlsStart === 'number' && songHlsStart === q0._hlsStart;
647
+ console.log(`πŸ”‘ Ownership check: sid=${q0._sid?.slice(0,8)}==${ownerSid?.slice(0,8)}:${sidMatch} hlsStart=${q0._hlsStart}==${songHlsStart}:${startMatch}`);
648
+ if (sidMatch && startMatch) {
649
+ streams[streamId].songStartTime = Date.now();
650
+ console.log(`⏱️ songStartTime reset for "${q0.meta.title}" [${q0._sid}] (first segment ready)`);
651
+ } else if (sidMatch && q0._hlsStart === undefined) {
652
+ // brief window before _hlsStart is set β€” harmless
653
+ } else {
654
+ console.log(`⚠️ watchForSegments ownership mismatch β€” skipping songStartTime reset. watcher=[${ownerSid}@${songHlsStart}] queue[0]=[${q0._sid}@${q0._hlsStart}]`);
655
+ }
656
+ }
657
+ if (onFirstSeg) onFirstSeg();
658
+ }
659
+ }
660
+ };
661
+
662
+ let lastEntryCount = -1;
663
+ let stablePolls = 0;
664
+ const STABLE_NEEDED = 3;
665
+
666
+ const iv = setInterval(() => {
667
+ flush();
668
+ const entries = parseM3u8Durations(playlistPath);
669
+ if (entries.length === lastEntryCount && !activeFFmpeg[streamId]) {
670
+ stablePolls++;
671
+ if (stablePolls >= STABLE_NEEDED) {
672
+ console.log(`πŸ›‘ watchForSegments auto-stop [${ownerSid?.slice(0,8)}]: stable for ${STABLE_NEEDED} polls, FFmpeg done`);
673
+ clearInterval(iv);
674
+ }
675
+ } else {
676
+ stablePolls = 0;
677
+ lastEntryCount = entries.length;
678
+ }
679
+ }, 800);
680
+ const markDone = () => { flush(); clearInterval(iv); return cursor; };
681
+ return { stop: () => clearInterval(iv), markDone };
682
+ }
683
+
684
+ async function generateSegmentsForSong(streamId, songInfo, isVideo, state) {
685
+ const dir = ensureHlsDir(streamId);
686
+ const songPath = path.join(SONGS_DIR, songInfo.fileName);
687
+ const segPrefix = `seg_${streamId}_${Date.now()}`;
688
+
689
+ console.log(`🎬 FFmpeg starting: ${songPath} isVideo=${isVideo}`);
690
+ if (!fs.existsSync(songPath)) throw new Error(`Source file missing: ${songPath}`);
691
+ const fileStat = fs.statSync(songPath);
692
+ if (fileStat.size === 0) throw new Error('Source file is empty');
693
+ console.log(`πŸ“ Source file: ${(fileStat.size / 1024 / 1024).toFixed(1)}MB`);
694
+
695
+ const segPattern = path.join(dir, segPrefix + '_%03d.ts');
696
+ const playlistPath = path.join(dir, segPrefix + '.m3u8');
697
+ const songHlsStart = state.totalDuration;
698
+ console.log(`🎯 segPrefix=${segPrefix} songHlsStart=${songHlsStart} ownerSid=${songInfo._sid?.slice(0,8)}`);
699
+
700
+ return new Promise((resolve, reject) => {
701
+ const cmd = ffmpeg(songPath);
702
+ if (isVideo) {
703
+ cmd.outputOptions([
704
+ '-map','0:v:0','-map','0:a:0',
705
+ '-c:v','libx264','-preset','ultrafast','-crf','28',
706
+ '-profile:v','main','-level','3.1','-pix_fmt','yuv420p',
707
+ '-vf','scale=854:480',
708
+ '-c:a','aac','-b:a','128k',
709
+ '-f','segment','-segment_time','8',
710
+ '-segment_list',playlistPath,'-segment_list_flags','+live','-segment_format','mpegts',
711
+ ]);
712
+ } else {
713
+ cmd.outputOptions(['-vn','-c:a','aac','-b:a','128k','-f','segment','-segment_time','8','-segment_list',playlistPath,'-segment_list_flags','+live','-segment_format','mpegts']);
714
+ }
715
+ let watcher = null;
716
+ cmd.output(segPattern)
717
+ .on('start', () => {
718
+ activeFFmpeg[streamId] = cmd;
719
+ console.log(`🎬 FFmpeg process started [${streamId}] gen=${hlsGeneration[streamId]}`);
720
+ watcher = watchForSegments(streamId, dir, segPrefix, songHlsStart, () => {
721
+ console.log(`⚑ First segment ready for stream ${streamId}`);
722
+ sendStreamUpdate(streamId);
723
+ }, songInfo._sid, state);
724
+ })
725
+ .on('stderr', line => {
726
+ if (line.includes('Error') || line.includes('error') || line.includes('Invalid')) {
727
+ console.error(`FFmpeg stderr: ${line}`);
728
+ }
729
+ })
730
+ .on('end', () => {
731
+ console.log(`βœ… FFmpeg done for ${streamId}`);
732
+ delete activeFFmpeg[streamId];
733
+ if (!watcher) { resolve(0); return; }
734
+ const finalCursor = watcher.markDone();
735
+ console.log(`πŸ“ Final cursor from playlist: ${finalCursor.toFixed(3)}s`);
736
+ state.totalDuration = finalCursor;
737
+ try { fs.unlinkSync(playlistPath); } catch {}
738
+ resolve(finalCursor);
739
+ })
740
+ .on('error', (err) => {
741
+ console.log(`πŸ’₯ FFmpeg error for ${streamId}: ${err.message}`);
742
+ delete activeFFmpeg[streamId];
743
+ if (err.message && (err.message.includes('SIGKILL') || err.message.includes('killed'))) {
744
+ console.log(`⚑ FFmpeg killed cleanly for ${streamId} (skip)`);
745
+ if (watcher) watcher.stop();
746
+ resolve(0);
747
+ return;
748
+ }
749
+ console.error(`❌ FFmpeg error for ${streamId}:`, err.message);
750
+ if (watcher) watcher.stop();
751
+ reject(err);
752
+ })
753
+ .run();
754
+ });
755
+ }
756
+
757
+ async function appendSongToHls(streamId, songInfo) {
758
+ if (!hlsState[streamId]) {
759
+ hlsState[streamId] = { mediaSeq: 0, segments: [], totalDuration: 0, generating: true };
760
+ console.log(`πŸ“¦ appendSongToHls: created fresh hlsState for ${streamId}`);
761
+ }
762
+ const myGeneration = hlsGeneration[streamId] || 0;
763
+ const prev = hlsMutex[streamId] || Promise.resolve();
764
+ console.log(`πŸ“Œ appendSongToHls queued: "${songInfo.meta.title}" [${songInfo._sid?.slice(0,8)}] gen=${myGeneration}`);
765
+ const next = prev.then(async () => {
766
+ const currentGen = hlsGeneration[streamId] || 0;
767
+ if (currentGen !== myGeneration) {
768
+ console.log(`⏩ Skipping stale appendSongToHls for "${songInfo.meta.title}" (gen ${myGeneration} vs ${currentGen})`);
769
+ return;
770
+ }
771
+ const isVideo = !!(songInfo.meta && songInfo.meta.videoUrl);
772
+ const state = hlsState[streamId];
773
+ if (!state) {
774
+ console.log(`⏩ Skipping appendSongToHls for "${songInfo.meta.title}" β€” hlsState gone`);
775
+ return;
776
+ }
777
+ state.generating = true;
778
+ songInfo._hlsStart = state.totalDuration;
779
+ console.log(`πŸ“ _hlsStart set to ${songInfo._hlsStart.toFixed(2)}s for "${songInfo.meta.title}"`);
780
+ try {
781
+ const finalCursor = await generateSegmentsForSong(streamId, songInfo, isVideo, state);
782
+ if (typeof finalCursor === 'number' && finalCursor > 0) {
783
+ songInfo._hlsEnd = finalCursor;
784
+ const actualDuration = finalCursor - songInfo._hlsStart;
785
+ if (actualDuration > 0 && Math.abs(actualDuration - (songInfo.meta.duration || 0)) > 30) {
786
+ console.log(`πŸ“ Correcting meta.duration for "${songInfo.meta.title}": ${(songInfo.meta.duration || 0).toFixed(1)}s β†’ ${actualDuration.toFixed(1)}s`);
787
+ songInfo.meta.duration = actualDuration;
788
+ }
789
+ songInfo._hlsDurationTrusted = true;
790
+ } else {
791
+ songInfo._hlsEnd = state.totalDuration;
792
+ console.log(`⚑ Encode killed for "${songInfo.meta.title}" β€” hlsEnd set to ${songInfo._hlsEnd?.toFixed(2)}s`);
793
+ }
794
+ state.generating = false;
795
+ console.log(`πŸ“Ί HLS done for "${songInfo.meta.title}": hlsStart=${songInfo._hlsStart?.toFixed(2)}s hlsEnd=${songInfo._hlsEnd?.toFixed(2)}s segs=${state.segments.length}`);
796
+ const finalGen = hlsGeneration[streamId] || 0;
797
+ const liveStream = streams[streamId];
798
+ if (finalGen === myGeneration && liveStream && liveStream.queue[0]?._sid === songInfo._sid) {
799
+ if (!liveStream.songStartTime) {
800
+ liveStream.songStartTime = Date.now();
801
+ console.log(`⏱️ songStartTime set post-encode for "${songInfo.meta.title}" [${songInfo._sid}]`);
802
+ sendStreamUpdate(streamId);
803
+ }
804
+ preGenerateNextSong(streamId).catch(console.error);
805
+ }
806
+ } catch (err) {
807
+ console.error(`HLS generation failed for stream ${streamId}:`, err);
808
+ if (hlsState[streamId]) hlsState[streamId].generating = false;
809
+ }
810
+ });
811
+ hlsMutex[streamId] = next;
812
+ return next;
813
+ }
814
+
815
+ async function preGenerateNextSong(streamId) {
816
+ const stream = streams[streamId];
817
+ if (!stream || stream.queue.length < 2) return;
818
+ const nextSong = stream.queue[1];
819
+ if (!nextSong || nextSong._hlsPregened || nextSong._hlsPregenInProgress) return;
820
+ nextSong._hlsPregenInProgress = true;
821
+ const sid = nextSong._sid;
822
+ console.log(`πŸ”„ Pre-generating HLS for next: ${nextSong.meta.title} [${sid}]`);
823
+ try {
824
+ await appendSongToHls(streamId, nextSong);
825
+ } catch (err) {
826
+ nextSong._hlsPregenInProgress = false;
827
+ console.error(`Pre-gen failed for "${nextSong.meta.title}":`, err.message);
828
+ return;
829
+ }
830
+ const streamNow = streams[streamId];
831
+ const stillQueued = streamNow && streamNow.queue.some(s => s._sid === sid);
832
+ const encodingFinished = typeof nextSong._hlsEnd === 'number' && typeof nextSong._hlsStart === 'number' && nextSong._hlsEnd > nextSong._hlsStart;
833
+ if (stillQueued && encodingFinished) {
834
+ nextSong._hlsPregened = true;
835
+ console.log(`βœ… Pre-gen confirmed for "${nextSong.meta.title}" [${sid}]: hlsStart=${nextSong._hlsStart.toFixed(2)}s hlsEnd=${nextSong._hlsEnd.toFixed(2)}s`);
836
+ } else {
837
+ nextSong._hlsPregened = false;
838
+ nextSong._hlsPregenInProgress = false;
839
+ delete nextSong._hlsStart;
840
+ delete nextSong._hlsEnd;
841
+ console.log(`⚠️ Pre-gen invalidated for "${nextSong.meta.title}" [${sid}]`);
842
+ }
843
+ }
844
+
845
+ function advanceToNextSong(streamId, autoAdvance = false) {
846
+ const stream = streams[streamId];
847
+ if (!stream) return false;
848
+ if (autoAdvance) stream._notifyOnStart = true;
849
+ else delete stream._notifyOnStart;
850
+ killActiveFFmpeg(streamId);
851
+ const finishedSong = stream.queue.shift();
852
+ const filePath = path.join(SONGS_DIR, finishedSong.fileName);
853
+ if (fs.existsSync(filePath)) { try { fs.unlinkSync(filePath); } catch {} }
854
+
855
+ if (stream.queue.length === 0) {
856
+ stream.isActive = false;
857
+ stream.streamTimeOffset = 0;
858
+ stream.songStartTime = null;
859
+ if (hlsState[streamId]) {
860
+ const hlsDir = path.join(HLS_DIR, streamId);
861
+ if (fs.existsSync(hlsDir)) {
862
+ try { const files = fs.readdirSync(hlsDir); for (const f of files) { try { fs.unlinkSync(path.join(hlsDir, f)); } catch {} } } catch {}
863
+ }
864
+ delete hlsState[streamId]; delete hlsMutex[streamId];
865
+ }
866
+ hlsGeneration[streamId] = (hlsGeneration[streamId] || 0) + 1;
867
+ console.log(`πŸ”„ Stream ${streamId} queue empty β€” HLS state reset for fresh start`);
868
+ io.to(`stream:${streamId}`).emit('message', { type: 'stream_ended', message: 'Queue is empty.' });
869
+ return false;
870
+ }
871
+
872
+ const nextSong = stream.queue[0];
873
+ const pregenIsValid = nextSong._hlsPregened && typeof nextSong._hlsStart === 'number' && typeof nextSong._hlsEnd === 'number' && nextSong._hlsEnd > nextSong._hlsStart;
874
+
875
+ if (pregenIsValid) {
876
+ stream.streamTimeOffset = nextSong._hlsStart;
877
+ stream.songStartTime = Date.now();
878
+ stream.lastActivity = Date.now();
879
+ stream.isActive = true;
880
+ delete stream._notifyOnStart;
881
+ sendStreamUpdate(streamId);
882
+ preGenerateNextSong(streamId).catch(console.error);
883
+ } else {
884
+ nextSong._hlsPregened = nextSong._hlsPregenInProgress = false;
885
+ delete nextSong._hlsStart; delete nextSong._hlsEnd;
886
+ if (hlsState[streamId]) {
887
+ const hlsDir = path.join(HLS_DIR, streamId);
888
+ if (fs.existsSync(hlsDir)) {
889
+ try { const files = fs.readdirSync(hlsDir); for (const f of files) { try { fs.unlinkSync(path.join(hlsDir, f)); } catch {} } } catch {}
890
+ }
891
+ delete hlsState[streamId]; delete hlsMutex[streamId];
892
+ }
893
+ hlsGeneration[streamId] = (hlsGeneration[streamId] || 0) + 1;
894
+ stream.songStartTime = null;
895
+ stream.lastActivity = Date.now();
896
+ stream.isActive = true;
897
+ appendSongToHls(streamId, nextSong).then(() => {
898
+ sendStreamUpdate(streamId);
899
+ preGenerateNextSong(streamId).catch(console.error);
900
+ }).catch(console.error);
901
+ }
902
+ return true;
903
+ }
904
+
905
+ function enqueueToStream(streamId, songInfo) {
906
+ if (!streams[streamId]) {
907
+ songInfo._sid = crypto.randomUUID();
908
+ streams[streamId] = { queue: [songInfo], songStartTime: null, streamTimeOffset: 0, users: new Map(), ownerId: streamId, lastActivity: Date.now(), isActive: true };
909
+ appendSongToHls(streamId, songInfo).then(() => sendStreamUpdate(streamId)).catch(console.error);
910
+ return { songInfo, position: 1, started: true };
911
+ }
912
+ const stream = streams[streamId];
913
+ songInfo._sid = crypto.randomUUID();
914
+ stream.queue.push(songInfo);
915
+ stream.lastActivity = Date.now();
916
+ const position = stream.queue.length;
917
+ if (!stream.isActive && position === 1 && !stream._showplayInProgress) {
918
+ // Stream was idle/ended β€” ensure HLS state is fresh so this song starts at t=0.
919
+ if (!hlsState[streamId] || hlsState[streamId].totalDuration > 0) {
920
+ if (hlsState[streamId]) {
921
+ const hlsDir = path.join(HLS_DIR, streamId);
922
+ if (fs.existsSync(hlsDir)) {
923
+ try { const files = fs.readdirSync(hlsDir); for (const f of files) { try { fs.unlinkSync(path.join(hlsDir, f)); } catch {} } } catch {}
924
+ }
925
+ delete hlsState[streamId]; delete hlsMutex[streamId];
926
+ }
927
+ hlsGeneration[streamId] = (hlsGeneration[streamId] || 0) + 1;
928
+ }
929
+ stream.streamTimeOffset = 0;
930
+ stream.songStartTime = null;
931
+ stream.isActive = true;
932
+ appendSongToHls(streamId, songInfo).then(() => sendStreamUpdate(streamId)).catch(console.error);
933
+ return { songInfo, position, started: true };
934
+ }
935
+ if (stream.isActive && position >= 2) preGenerateNextSong(streamId).catch(console.error);
936
+ sendStreamUpdate(streamId);
937
+ return { songInfo, position, started: false };
938
+ }
939
+
940
+ // ═══════════════════════════════════════════════════════════════════════════
941
+ // DOWNLOAD HELPERS
942
+ // ═══════════════════════════════════════════════════════════════════════════
943
+
944
+ const DIRECT_VIDEO_EXTS = /\.(mkv|mp4|mov|avi|webm|m4v|flv|wmv|ts)(\?.*)?$/i;
945
+ function isDirectVideoUrl(url) {
946
+ if (!url) return false;
947
+ try { return DIRECT_VIDEO_EXTS.test(new URL(url).pathname); } catch { return DIRECT_VIDEO_EXTS.test(url); }
948
+ }
949
+
950
+ function getAudioMeta(filePath) {
951
+ return new Promise((resolve, reject) => {
952
+ ffmpeg.ffprobe(filePath, (err, metadata) => {
953
+ if (err) return reject(err);
954
+ function parseDurationTag(tag) {
955
+ if (!tag || typeof tag !== 'string') return 0;
956
+ const m = tag.match(/^(\d+):(\d+):(\d+(?:\.\d+)?)$/);
957
+ if (!m) return 0;
958
+ return parseInt(m[1], 10) * 3600 + parseInt(m[2], 10) * 60 + parseFloat(m[3]);
959
+ }
960
+ const candidates = [
961
+ parseFloat(metadata.format?.duration) || 0,
962
+ ...(metadata.streams || []).flatMap(s => [
963
+ parseFloat(s.duration) || 0,
964
+ parseDurationTag(s.tags?.DURATION),
965
+ parseDurationTag(s.tags?.duration),
966
+ ]),
967
+ ];
968
+ const duration = Math.max(...candidates.filter(n => isFinite(n) && n > 0), 0);
969
+ resolve({ duration, size: metadata.format.size, bit_rate: metadata.format.bit_rate });
970
+ });
971
+ });
972
+ }
973
+
974
+ async function downloadVideoFile(downloadUrl) {
975
+ const fileName = crypto.randomUUID() + '.mp4';
976
+ const filePath = path.join(SONGS_DIR, fileName);
977
+ const writer = fs.createWriteStream(filePath);
978
+ try {
979
+ const response = await axios({ url: downloadUrl, method: 'GET', responseType: 'stream', httpsAgent: httpsAgentNoVerify });
980
+ const contentLength = parseInt(response.headers['content-length'] || '0', 10);
981
+ let bytesWritten = 0;
982
+ response.data.on('data', chunk => { bytesWritten += chunk.length; });
983
+ response.data.pipe(writer);
984
+ await new Promise((resolve, reject) => {
985
+ writer.on('finish', resolve);
986
+ writer.on('error', reject);
987
+ response.data.on('error', reject);
988
+ });
989
+ if (contentLength > 0 && bytesWritten < contentLength * 0.95) {
990
+ throw new Error(`Download truncated: got ${bytesWritten} of ${contentLength} bytes`);
991
+ }
992
+ } catch (err) {
993
+ writer.destroy();
994
+ if (fs.existsSync(filePath)) { try { fs.unlinkSync(filePath); } catch {} }
995
+ throw err;
996
+ }
997
+ return { fileName, filePath };
998
+ }
999
+
1000
+ async function showplayEnqueueLink(streamId, pendingLink, pendingTitle, thumbnail, tmdbInfo = null) {
1001
+ if (!streams[streamId]) {
1002
+ streams[streamId] = { queue: [], songStartTime: null, streamTimeOffset: 0, users: new Map(), ownerId: streamId, lastActivity: Date.now(), isActive: false };
1003
+ }
1004
+ streams[streamId]._showplayInProgress = (streams[streamId]._showplayInProgress || 0) + 1;
1005
+
1006
+ let directUrl;
1007
+ if (isDirectVideoUrl(pendingLink)) {
1008
+ directUrl = pendingLink;
1009
+ } else {
1010
+ let extractRes;
1011
+ try {
1012
+ extractRes = await axios.get(`https://downw.vercel.app/extract?url=${encodeURIComponent(pendingLink)}`, { timeout: 60000, httpsAgent: httpsAgentNoVerify });
1013
+ } catch (err) { throw new Error(`Extract API failed: ${err.message}`); }
1014
+ directUrl = extractRes.data?.downloadUrl;
1015
+ if (!directUrl) throw new Error('No download URL returned by extractor');
1016
+ }
1017
+
1018
+ let fileName, filePath;
1019
+ try { ({ fileName, filePath } = await downloadVideoFile(directUrl)); }
1020
+ catch (err) { throw new Error(`Download failed: ${err.message}`); }
1021
+
1022
+ let mediaMeta;
1023
+ try { mediaMeta = await getAudioMeta(filePath); }
1024
+ catch (e) { try { fs.unlinkSync(filePath); } catch {} throw new Error('ffprobe could not read the video file'); }
1025
+
1026
+ if (mediaMeta.size > SHOWPLAY_MAX_FILE_SIZE) {
1027
+ try { fs.unlinkSync(filePath); } catch {}
1028
+ throw new Error(`File too large (${(mediaMeta.size / (1024 ** 3)).toFixed(2)} GB). Max 2 GB.`);
1029
+ }
1030
+ if (mediaMeta.duration > SHOWPLAY_MAX_DURATION) {
1031
+ try { fs.unlinkSync(filePath); } catch {}
1032
+ throw new Error(`Video too long. Max 6 hours.`);
1033
+ }
1034
+
1035
+ if (streams[streamId]) streams[streamId]._showplayInProgress = Math.max(0, (streams[streamId]._showplayInProgress || 1) - 1);
1036
+
1037
+ const effectivePoster = tmdbInfo?.poster || thumbnail || DEFAULT_ARTWORK;
1038
+ const songInfo = {
1039
+ fileName,
1040
+ meta: {
1041
+ title: tmdbInfo?.title || pendingTitle || 'Unknown',
1042
+ thumbnail: effectivePoster,
1043
+ duration: mediaMeta.duration || 0,
1044
+ views: 'N/A',
1045
+ published: tmdbInfo?.releaseDate || 'N/A',
1046
+ source: pendingLink,
1047
+ videoUrl: pendingLink || 'showplay',
1048
+ },
1049
+ tmdb: tmdbInfo || null,
1050
+ isShowplay: true,
1051
+ };
1052
+
1053
+ enqueueToStream(streamId, songInfo);
1054
+ return { title: songInfo.meta.title, duration: mediaMeta.duration, thumbnail: effectivePoster };
1055
+ }
1056
+
1057
+ // ═══════════════════════════════════════════════════════════════════════════
1058
+ // BACKGROUND TIMERS
1059
+ // ═══════════════════════════════════════════════════════════════════════════
1060
+
1061
+ // Auto-advance
1062
+ setInterval(async () => {
1063
+ try {
1064
+ for (const streamId in streams) {
1065
+ const stream = streams[streamId];
1066
+ if (!stream.isActive) continue;
1067
+ const current = stream.queue[0];
1068
+ if (!current) continue;
1069
+ let songDuration;
1070
+ if (current._hlsDurationTrusted && typeof current._hlsEnd === 'number' && typeof current._hlsStart === 'number') {
1071
+ songDuration = current._hlsEnd - current._hlsStart;
1072
+ } else if (current.meta.duration > 0) {
1073
+ songDuration = current.meta.duration;
1074
+ } else if (typeof current._hlsEnd === 'number' && typeof current._hlsStart === 'number') {
1075
+ songDuration = current._hlsEnd - current._hlsStart;
1076
+ } else continue;
1077
+ if (songDuration < 5 || !stream.songStartTime) continue;
1078
+ const elapsed = (Date.now() - stream.songStartTime) / 1000;
1079
+ if (elapsed >= songDuration + 3) {
1080
+ if (stream._advancingFromSid === current._sid) continue;
1081
+ stream._advancingFromSid = current._sid;
1082
+ console.log(`⏭️ Auto-advance "${current.meta.title}": elapsed=${elapsed.toFixed(1)}s duration=${songDuration.toFixed(1)}s`);
1083
+ advanceToNextSong(streamId, true);
1084
+ if (stream._advancingFromSid === current._sid) delete stream._advancingFromSid;
1085
+ }
1086
+ }
1087
+ } catch (err) { console.error('Auto-advance error:', err); }
1088
+ }, 1000);
1089
+
1090
+ // Segment pruning
1091
+ setInterval(() => {
1092
+ for (const streamId in streams) {
1093
+ const stream = streams[streamId];
1094
+ if (!stream.isActive || !stream.songStartTime) continue;
1095
+ const current = stream.queue[0];
1096
+ if (!current) continue;
1097
+ const hlsStart = current._hlsStart !== undefined ? current._hlsStart : (stream.streamTimeOffset || 0);
1098
+ const withinSong = (Date.now() - stream.songStartTime) / 1000;
1099
+ pruneOldSegments(streamId, hlsStart + withinSong);
1100
+ }
1101
+ }, 30 * 1000);
1102
+
1103
+ // Inactivity cleanup
1104
+ setInterval(() => {
1105
+ const now = Date.now(), toDelete = [];
1106
+ for (const streamId in streams) {
1107
+ const stream = streams[streamId];
1108
+ if ((!stream.users || stream.users.size === 0) && (now - (stream.lastActivity || 0)) > STREAM_CLEANUP_INTERVAL) {
1109
+ toDelete.push(streamId);
1110
+ }
1111
+ }
1112
+ for (const streamId of toDelete) {
1113
+ const stream = streams[streamId];
1114
+ killActiveFFmpeg(streamId);
1115
+ for (const song of stream.queue) { const fp = path.join(SONGS_DIR, song.fileName); if (fs.existsSync(fp)) { try { fs.unlinkSync(fp); } catch {} } }
1116
+ const hlsStreamDir = path.join(HLS_DIR, streamId);
1117
+ if (fs.existsSync(hlsStreamDir)) { try { fs.rmSync(hlsStreamDir, { recursive: true }); } catch {} }
1118
+ delete streams[streamId]; delete hlsState[streamId]; delete hlsMutex[streamId]; delete hlsGeneration[streamId];
1119
+ console.log(`🧹 Cleaned up stream: ${streamId}`);
1120
+ }
1121
+ }, 10 * 60 * 1000);
1122
+
1123
+ // ═══════════════════════════════════════════════════════════════════════════
1124
+ // LAUNCH
1125
+ // ═══════════════════════════════════════════════════════════════════════════
1126
+
1127
+ server.listen(PORT, async () => {
1128
+ console.log(`πŸš€ Constituent server running on port ${PORT}`);
1129
+ console.log(`πŸ‘€ Owner ID: ${CONSTITUENT_OWNER_ID}`);
1130
+ try {
1131
+ const ipRes = await axios.get('https://api.ipify.org?format=json', { timeout: 5000 });
1132
+ console.log(`🌐 Public IP: ${ipRes.data.ip}`);
1133
+ } catch {}
1134
+ });
1135
+
1136
+ process.once('SIGINT', () => { server.close(); process.exit(0); });
1137
+ process.once('SIGTERM', () => { server.close(); process.exit(0); });