-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworking_new.py
More file actions
664 lines (605 loc) · 36.1 KB
/
Copy pathworking_new.py
File metadata and controls
664 lines (605 loc) · 36.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
import asyncio
import logging
import os
import shlex
import socket
import subprocess
import threading
import shutil
import time
from urllib.parse import quote
from aiohttp import web, ClientSession
# --- 1. Centralized Logging Configuration ---
logging.basicConfig(level=logging.INFO, format='%(asctime)s [%(levelname)s] %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
# --- 2. State Management & Concurrency Control ---
active_streams = {}
streams_lock = threading.Lock()
STREAMS_BASE_DIR = os.path.join(os.getcwd(), "streams")
# --- 3. Configuration ---
SESSION_TIMEOUT_SECONDS = 45
REAPER_INTERVAL_SECONDS = 30
COMPLETED_SESSION_CLEANUP_SECONDS = 3600
STATUS_API_URL = "https://rsd.ovh/status?url="
STREAM_API_URL = "https://rsd.ovh/stream?url="
FILES_API_URL = "https://rsd.ovh/files?url="
PROGRESS_POLL_INTERVAL_SECONDS = 2
# --- 4. Main Application HTML ---
APP_HTML = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Multi-User HLS Streamer</title>
<script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
<style>
:root {
--twitter-blue: #1DA1F2; --twitter-green: #17BF63; --twitter-red: #E0245E;
--twitter-black: #14171A; --twitter-dark-gray: #657786; --twitter-light-gray: #AAB8C2;
--twitter-white: #FFFFFF; --background-color: #15202B; --card-background: #192734;
--border-color: #38444d; --font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
--square-radius: 8px;
}
body { background-color: var(--background-color); color: var(--twitter-white); font-family: var(--font-family); margin: 0; padding: 20px; box-sizing: border-box; display: flex; justify-content: center; align-items: center; min-height: 100vh; }
.wrapper { display: flex; flex-direction: column; align-items: center; width: 100%; max-width: 600px; }
.container { width: 100%; text-align: center; }
#status-container { display: flex; justify-content: flex-end; width: 100%; gap: 12px; margin-bottom: 20px; font-size: 14px; color: var(--twitter-light-gray); }
.status-item { display: flex; align-items: center; gap: 8px; background-color: var(--card-background); padding: 6px 12px; border-radius: var(--square-radius); border: 1px solid var(--border-color); transition: opacity 0.5s; opacity: 0; }
.status-item.visible { opacity: 1; }
.icon svg { width: 18px; height: 18px; vertical-align: middle; display: block; }
.status-item.success { color: var(--twitter-green); }
.status-item.error { color: var(--twitter-red); }
#player-section { display: none; }
.card { background-color: var(--card-background); border: 1px solid var(--border-color); border-radius: var(--square-radius); padding: 24px; margin-bottom: 0; }
.card + button, .card + a.button { margin-top: 16px; }
.card-header { text-align: center; margin-bottom: 16px; }
.card-header h1 { font-size: 23px; font-weight: bold; margin: 0; color: var(--twitter-white); }
.card-header p { color: var(--twitter-light-gray); font-size: 15px; margin-top: 4px; }
#url-input { background-color: var(--background-color); border: 1px solid var(--twitter-dark-gray); border-radius: var(--square-radius); color: var(--twitter-white); font-size: 15px; padding: 16px; width: 100%; box-sizing: border-box; margin: 0; transition: border-color 0.2s; }
#url-input:focus { outline: none; border-color: var(--twitter-blue); }
button, a.button { background-color: var(--twitter-blue); color: var(--twitter-black); border: none; border-radius: var(--square-radius); font-size: 15px; font-weight: bold; padding: 16px 24px; width: 100%; cursor: pointer; transition: background-color 0.2s; text-decoration: none; display: inline-block; box-sizing: border-box; }
button:hover, a.button:hover { background-color: #1A91DA; }
button:disabled { background-color: var(--twitter-dark-gray); cursor: not-allowed; }
#loading-message { padding: 40px 0; }
#loading-message h2 { font-size: 20px; margin-bottom: 12px; animation: pulse 1.5s infinite ease-in-out; }
#loading-message p { color: var(--twitter-light-gray); font-size: 15px; overflow-wrap: break-word; word-wrap: break-word; word-break: break-word; }
@keyframes pulse { 0% { opacity: 1; } 50% { opacity: 0.6; } 100% { opacity: 1; } }
.modal-overlay { display: none; position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.6); align-items: center; justify-content: center; }
.modal-content { text-align: left; background-color: var(--card-background); border: 1px solid var(--border-color); border-radius: var(--square-radius); padding: 25px; width: 90%; max-width: 500px; position: relative; }
.modal-close-btn { position: absolute; top: 10px; right: 15px; color: var(--twitter-light-gray); font-size: 28px; font-weight: bold; cursor: pointer; }
.file-list-modal { max-height: 150px; overflow-y: auto; border: 1px solid var(--border-color); border-radius: 5px; padding: 10px; background-color: var(--background-color); }
/* Video container and player adjustments */
#video-container {
position: relative;
width: 100%;
padding-top: 56.25%; /* 16:9 Aspect Ratio */
display: none;
background-color: #000;
border-radius: var(--square-radius);
overflow: hidden;
}
video {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
object-fit: contain;
}
/* Progress container styling */
#progress-container {
display: none;
margin-top: 16px;
padding: 16px;
background-color: var(--card-background);
border: 1px solid var(--border-color);
border-radius: var(--square-radius);
font-size: 14px;
text-align: left;
color: var(--twitter-light-gray);
overflow-x: auto;
white-space: nowrap;
}
.progress-items {
display: flex;
flex-direction: row;
gap: 20px;
justify-content: space-between;
min-width: max-content;
}
.progress-item {
display: flex;
flex-direction: column;
min-width: 100px;
}
.progress-label {
font-weight: bold;
color: var(--twitter-white);
margin-bottom: 4px;
}
.progress-value {
color: var(--twitter-light-gray);
}
</style>
</head>
<body>
<div class="wrapper">
<div id="status-container">
<div class="status-item" id="ffmpeg-status"><span>ffmpeg</span><span class="icon"></span></div>
<div class="status-item" id="mpv-status"><span>mpv</span><span class="icon"></span></div>
</div>
<main class="container">
<form id="stream-form"><div id="form-container"><div class="card"><div class="card-header"><h1>HLS Video Streamer</h1><p>Enter a magnet link to begin.</p></div><input type="text" id="url-input" placeholder="Paste a magnet link" required></div><button type="submit">Select Files</button></div></form>
<div id="player-section">
<h3 id="torrent-name-display" style="text-align: center; display: none; margin-bottom: 12px; color: var(--twitter-light-gray); font-weight: normal; word-break: break-all;"></h3>
<div class="card">
<div id="loading-message"><h2>Preparing stream...</h2><p id="loading-details">Connecting to source...</p></div>
<div id="video-container"><video id="video" controls autoplay preload="auto"></video></div>
</div>
<div id="progress-container">
<div class="progress-items">
<div class="progress-item">
<span class="progress-label">Progress</span>
<span class="progress-value" id="progress-percentage">--</span>
</div>
<div class="progress-item">
<span class="progress-label">Speed</span>
<span class="progress-value" id="progress-speed">--</span>
</div>
<div class="progress-item">
<span class="progress-label">Peers</span>
<span class="progress-value" id="progress-peers">--</span>
</div>
<div class="progress-item">
<span class="progress-label">Size</span>
<span class="progress-value" id="progress-size">--</span>
</div>
</div>
</div>
<a href="#" id="stream-another" role="button" class="button" style="margin-top: 16px;">Stream Another Video</a>
</div>
</main>
</div>
<div id="file-selection-modal" class="modal-overlay">
<div class="modal-content">
<span id="file-modal-close-btn" class="modal-close-btn">×</span>
<h2>Select Files to Stream</h2>
<p>Choose the primary video file and an optional subtitle.</p>
<div id="file-selection-container" style="margin-top: 20px;">
<h4 style="margin: 1rem 0 0.5rem;">Video Files</h4>
<div id="video-file-list" class="file-list-modal"></div>
<div id="subtitle-section" style="display: none;">
<h4 style="margin: 1rem 0 0.5rem;">Subtitle Files</h4>
<div id="subtitle-file-list" class="file-list-modal"></div>
</div>
</div>
<button id="confirm-stream-btn" class="button" style="margin-top: 25px;">Start Stream</button>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
const FILES_API_ENDPOINT = "{files_api_url}";
const playerSection = document.getElementById('player-section'), streamForm = document.getElementById('stream-form'), urlInput = document.getElementById('url-input'), loadingMessage = document.getElementById('loading-message'), loadingDetails = document.getElementById('loading-details'), videoContainer = document.getElementById('video-container'), video = document.getElementById('video'), streamAnotherBtn = document.getElementById('stream-another');
const fileSelectionModal = document.getElementById('file-selection-modal'), fileModalCloseBtn = document.getElementById('file-modal-close-btn'), confirmStreamBtn = document.getElementById('confirm-stream-btn'), videoFileList = document.getElementById('video-file-list'), subtitleFileList = document.getElementById('subtitle-file-list');
let hls = null, pollingInterval = null, sessionId = null, heartbeatInterval = null, progressInterval = null, currentMagnet = null, isNameSet = false;
const iconSuccess = `<svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"></path></svg>`;
const iconError = `<svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z"></path></svg>`;
function checkDependencies(){fetch('/status').then(r=>r.json()).then(data=>{const setStatus=(el,name,success)=>{el.classList.add(success?'success':'error');el.querySelector('.icon').innerHTML=success?iconSuccess:iconError;el.classList.add('visible')};setStatus(document.getElementById('ffmpeg-status'),'ffmpeg',data.ffmpeg);setStatus(document.getElementById('mpv-status'),'mpv',data.mpv)})};checkDependencies();const HEARTBEAT_INTERVAL_MS=15000,MIN_SEGMENTS_TO_START=3;
function generateSessionId(){if(window.crypto&&window.crypto.randomUUID)return window.crypto.randomUUID();return'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,c=>{const r=Math.random()*16|0,v=c=='x'?r:r&3|8;return v.toString(16)})}
function getSessionId() {const key='hlsStreamerSessionId';let id=sessionStorage.getItem(key);if(id){return id}let newId=generateSessionId();sessionStorage.setItem(key,newId);return newId;}
sessionId=getSessionId();
function startHeartbeat(){if(heartbeatInterval)clearInterval(heartbeatInterval);heartbeatInterval=setInterval(()=>{fetch(`/heartbeat/${sessionId}`,{method:'POST'})},HEARTBEAT_INTERVAL_MS)}
function stopHeartbeat(){if(heartbeatInterval)clearInterval(heartbeatInterval);heartbeatInterval=null}
function showFormView() {
if(hls)hls.destroy();if(pollingInterval)clearInterval(pollingInterval);if(progressInterval)clearInterval(progressInterval);
stopHeartbeat();video.pause();video.src="";video.innerHTML='';
const torrentNameDisplay=document.getElementById('torrent-name-display');
torrentNameDisplay.style.display = 'none';
torrentNameDisplay.textContent = '';
isNameSet = false;
fetch(`/stop/${sessionId}?hard=true`,{method:'POST'}).finally(() => {
playerSection.style.display='none';streamForm.style.display='block';
loadingMessage.style.display='block';videoContainer.style.display='none';
loadingDetails.textContent='Connecting to source...';
document.querySelector("#stream-form button").textContent = 'Select Files';
});
}
function showPlayerView(isMagnet){
streamForm.style.display='none';
playerSection.style.display='block';
startPollingForPlaylist();
startHeartbeat();
if(isMagnet){
document.getElementById('progress-container').style.display = 'flex';
startPollingForProgress();
}
}
const startPlayback=(playlistUrl, subtitleUrl)=>{
loadingMessage.style.display='none';
videoContainer.style.display='block';
video.volume=.5;
if(Hls.isSupported()){
if(hls)hls.destroy();
hls=new Hls({startPosition:0, maxBufferHole:.5,nudgeMaxRetry:10,nudgeOffset:0.4});
// This event fires whenever HLS.js attaches to the video element, ensuring subtitles persist after seeking.
hls.on(Hls.Events.MEDIA_ATTACHED, function () {
if (subtitleUrl) {
Array.from(video.querySelectorAll('track')).forEach(t => t.remove()); // Clear old tracks
const trackEl = document.createElement('track');
trackEl.kind = 'subtitles';
trackEl.label = 'English';
trackEl.srclang = 'en';
trackEl.src = subtitleUrl;
trackEl.default = true;
video.appendChild(trackEl);
// Set the track mode to 'showing' to make them visible
setTimeout(() => {
if (video.textTracks.length > 0) {
video.textTracks[0].mode = 'showing';
}
}, 100);
}
});
hls.loadSource(playlistUrl);
hls.attachMedia(video);
} else if(video.canPlayType('application/vnd.apple.mpegurl')){
video.src = playlistUrl;
if (subtitleUrl) {
Array.from(video.querySelectorAll('track')).forEach(t => t.remove());
const trackEl = document.createElement('track');
trackEl.kind = 'subtitles';
trackEl.label = 'English';
trackEl.srclang = 'en';
trackEl.src = subtitleUrl;
trackEl.default = true;
video.appendChild(trackEl);
if (video.textTracks.length > 0) {
video.textTracks[0].mode = 'showing';
}
}
} else {
loadingDetails.textContent = "HLS not supported in this browser";
}
};
const startPollingForPlaylist=()=>{
const p=`/streams/${sessionId}/playlist.m3u8`;
const s=`/streams/${sessionId}/subtitle.vtt`;
pollingInterval=setInterval(()=>{
fetch(p).then(r=>{
if(r.ok)return r.text();
throw new Error('Playlist not found')
}).then(c=>{
if(c&&c.includes(".ts")){
const n=(c.match(/\\.ts/g)||[]).length;
loadingDetails.textContent=`Buffered ${n} segment(s)...`;
if(n>=MIN_SEGMENTS_TO_START){
clearInterval(pollingInterval);pollingInterval=null;
// Check if subtitle exists before starting playback
fetch(s).then(response => {
const subtitleUrl = response.ok ? s : null;
startPlayback(p, subtitleUrl);
}).catch(() => {
// Start playback even if subtitle check fails
startPlayback(p, null);
});
}
}
}).catch(e=>{})
},1000);
};
const startPollingForProgress = () => {
if (progressInterval) clearInterval(progressInterval);
const torrentNameEl = document.getElementById('torrent-name-display');
const percentageEl = document.getElementById('progress-percentage');
const speedEl = document.getElementById('progress-speed');
const peersEl = document.getElementById('progress-peers');
const sizeEl = document.getElementById('progress-size');
progressInterval = setInterval(() => {
fetch(`/progress/${sessionId}`)
.then(r => r.json())
.then(data => {
if (!data || !data.infoHash) return;
if (!isNameSet && data.name) {
torrentNameEl.textContent = data.name;
torrentNameEl.style.display = 'block';
isNameSet = true;
}
percentageEl.textContent = `${data.percentageCompleted.toFixed(2)}%`;
speedEl.textContent = data.downloadSpeedHuman;
peersEl.textContent = data.connectedPeers;
const completedGB = (data.bytesCompleted / 1e9).toFixed(2);
const totalGB = (data.totalBytes / 1e9).toFixed(2);
sizeEl.textContent = `${completedGB} GB / ${totalGB} GB`;
})
.catch(e => {});
}, 2000);
};
function populateFileSelectionModal(data) {
videoFileList.innerHTML = '';
subtitleFileList.innerHTML = '';
const videoFileExtensions = ['.mkv', '.mp4', '.avi', '.mov', '.webm'];
const subtitleFileExtensions = ['.srt', '.vtt', '.sub', '.ass'];
let largestVideo = { index: -1, size: -1 };
let hasSubtitleFiles = false;
const files = data.files;
files.forEach((file, index) => {
if (videoFileExtensions.some(ext => file.path.toLowerCase().endsWith(ext))) {
if (file.size > largestVideo.size) {
largestVideo = { index, size: file.size };
}
}
});
files.forEach((file, index) => {
const item = document.createElement('div');
item.style.marginBottom = '8px';
const input = document.createElement('input');
const label = document.createElement('label');
label.htmlFor = `file-index-${index}`;
label.textContent = ` ${file.path} (${(file.size / 1e6).toFixed(2)} MB)`;
input.id = `file-index-${index}`;
input.value = index;
if (videoFileExtensions.some(ext => file.path.toLowerCase().endsWith(ext))) {
input.type = 'radio';
input.name = 'video-file';
if (index === largestVideo.index) input.checked = true;
item.appendChild(input);
item.appendChild(label);
videoFileList.appendChild(item);
} else if (subtitleFileExtensions.some(ext => file.path.toLowerCase().endsWith(ext))) {
input.type = 'radio';
input.name = 'subtitle-file';
item.appendChild(input);
item.appendChild(label);
subtitleFileList.appendChild(item);
hasSubtitleFiles = true;
}
});
const subtitleSection = document.getElementById('subtitle-section');
if (hasSubtitleFiles) {
subtitleSection.style.display = 'block';
const noSubItem = document.createElement('div');
noSubItem.innerHTML = `<input type="radio" id="no-subtitle" name="subtitle-file" value="-1" checked><label for="no-subtitle"> None</label>`;
subtitleFileList.insertBefore(noSubItem, subtitleFileList.firstChild);
} else {
subtitleSection.style.display = 'none';
}
fileSelectionModal.style.display = 'flex';
}
fileModalCloseBtn.onclick = () => {
fileSelectionModal.style.display = 'none';
};
streamForm.addEventListener('submit', function(e) {
e.preventDefault();
currentMagnet = urlInput.value.trim();
if (!currentMagnet) return;
const submitButton = e.target.querySelector('button');
submitButton.disabled = true;
submitButton.textContent = 'Getting file list...';
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 65000);
const apiUrl = `${FILES_API_ENDPOINT}${encodeURIComponent(currentMagnet)}`;
fetch(apiUrl, { signal: controller.signal })
.then(response => {
clearTimeout(timeoutId);
if (!response.ok) {
return response.text().then(text => {
throw new Error(`Error ${response.status}: ${text || response.statusText}`);
});
}
return response.json();
})
.then(data => {
if (!data.Files) throw new Error("Invalid API response: 'Files' key not found.");
const standardizedData = { files: data.Files };
populateFileSelectionModal(standardizedData);
})
.catch(err => {
if (err.name === 'AbortError') {
alert('Error: Request timed out. The torrent may have no seeds or the service is slow.');
} else {
alert('Error fetching file list: ' + err.message);
}
}).finally(() => {
submitButton.disabled = false;
submitButton.textContent = 'Select Files';
});
});
confirmStreamBtn.addEventListener('click', function() {
const selectedVideo = document.querySelector('input[name="video-file"]:checked');
const selectedSubtitle = document.querySelector('input[name="subtitle-file"]:checked');
if (!selectedVideo) {
alert("Please select a video file to stream.");
return;
}
fileSelectionModal.style.display = 'none';
const body = new URLSearchParams();
body.append('url', currentMagnet);
body.append('video_index', selectedVideo.value);
if (selectedSubtitle && selectedSubtitle.value !== "-1") {
body.append('subtitle_index', selectedSubtitle.value);
}
fetch(`/stream/${sessionId}`, { method: 'POST', body: body })
.then(r => {
if (r.ok) {
showPlayerView(true);
} else {
r.json().then(e => alert(e.error)).catch(() => alert('Error starting stream.'));
}
});
});
streamAnotherBtn.addEventListener('click', function(e) { e.preventDefault(); showFormView() });
});
</script>
</body>
</html>
"""
# --- 5. Backend Logic ---
def log_pipe_output(pipe):
try:
for line in iter(pipe.readline, b''): logging.info(f"[ffmpeg/mpv]: {line.decode('utf-8', errors='ignore').strip()}")
except Exception: pass
def stop_stream_process(session_id, cleanup_files=False):
with streams_lock:
session_data = active_streams.get(session_id)
if not session_data and cleanup_files:
session_dir = os.path.join(STREAMS_BASE_DIR, str(session_id))
if os.path.isdir(session_dir): shutil.rmtree(session_dir, ignore_errors=True)
return
if not session_data: return
if (task := session_data.get('progress_task')) and not task.done(): task.cancel()
if (proc := session_data.get('process')) and proc.poll() is None:
logging.info(f"Stopping stream process for session {session_id} (PID: {proc.pid})")
proc.terminate()
try: proc.wait(timeout=5)
except subprocess.TimeoutExpired: proc.kill(); proc.wait()
session_data['process_running'] = False
session_data['last_seen'] = time.time()
if cleanup_files:
active_streams.pop(session_id, None)
session_dir = os.path.join(STREAMS_BASE_DIR, str(session_id))
if os.path.isdir(session_dir): shutil.rmtree(session_dir, ignore_errors=True)
def start_stream_process(session_id, video_url):
stop_stream_process(session_id, cleanup_files=True)
session_dir = os.path.join(STREAMS_BASE_DIR, str(session_id))
os.makedirs(session_dir, exist_ok=True)
command = (
f"mpv {shlex.quote(video_url)} --no-terminal --o=- --of=mpegts --oac=aac --ovc=libx264 "
f"--ovcopts=preset=ultrafast | ffmpeg "
f"-fflags +genpts -i - -map 0 -c copy -async 1 -f hls "
f"-hls_time 4 -hls_playlist_type event "
f"-hls_segment_filename 'segment%05d.ts' playlist.m3u8"
)
process = subprocess.Popen(command, shell=True, cwd=session_dir, stderr=subprocess.PIPE, stdout=subprocess.DEVNULL)
with streams_lock:
active_streams[session_id] = { 'process': process, 'last_seen': time.time(), 'process_running': True, 'progress_data': {}, 'progress_task': None }
threading.Thread(target=log_pipe_output, args=(process.stderr,), daemon=True).start()
async def download_and_convert_subtitle(app, session_id, magnet_url, subtitle_index):
logging.info(f"Attempting to download subtitle at index {subtitle_index} for session {session_id}")
subtitle_stream_url = f"{STREAM_API_URL}{quote(magnet_url)}&index={subtitle_index}"
try:
async with app['http_client'].get(subtitle_stream_url, timeout=30) as response:
if response.status == 200:
content = await response.text(encoding='utf-8', errors='ignore')
session_dir = os.path.join(STREAMS_BASE_DIR, str(session_id))
os.makedirs(session_dir, exist_ok=True)
subtitle_path = os.path.join(session_dir, 'subtitle.vtt')
with open(subtitle_path, 'w', encoding='utf-8') as f:
if not content.strip().startswith("WEBVTT"): f.write("WEBVTT\n\n")
f.write(content.replace(',', '.'))
logging.info(f"Subtitle file created for session {session_id} at {subtitle_path}")
else:
logging.warning(f"Failed to download subtitle file (HTTP {response.status}) for session {session_id}")
except Exception as e: logging.error(f"Exception during subtitle download for {session_id}: {e}", exc_info=True)
async def poll_stream_progress(app, session_id, magnet_url):
api_endpoint = f"{STATUS_API_URL}{quote(magnet_url)}"
while True:
try:
with streams_lock:
if session_id not in active_streams: break
async with app['http_client'].get(api_endpoint, timeout=10) as response:
if response.status == 200:
data = await response.json()
with streams_lock:
if session_id in active_streams: active_streams[session_id]['progress_data'] = data
await asyncio.sleep(PROGRESS_POLL_INTERVAL_SECONDS)
except asyncio.CancelledError: break
except Exception: await asyncio.sleep(PROGRESS_POLL_INTERVAL_SECONDS * 2)
async def reaper_task(app):
while True:
try:
await asyncio.sleep(REAPER_INTERVAL_SECONDS)
sessions_to_kill, sessions_to_delete = [], []
with streams_lock:
for sid, data in list(active_streams.items()):
is_running, last_seen = data.get('process_running', False), data.get('last_seen', 0)
if is_running and (p := data.get('process')) and p.poll() is not None: data['process_running'] = False; is_running = False
if is_running and time.time() - last_seen > SESSION_TIMEOUT_SECONDS: sessions_to_kill.append(sid)
elif not is_running and time.time() - last_seen > COMPLETED_SESSION_CLEANUP_SECONDS: sessions_to_delete.append(sid)
for sid in sessions_to_kill: stop_stream_process(sid, cleanup_files=False)
for sid in sessions_to_delete: stop_stream_process(sid, cleanup_files=True)
except asyncio.CancelledError: break
except Exception: logging.error("Error in reaper task:", exc_info=True)
# --- 6. aiohttp Web Handlers ---
@web.middleware
async def error_middleware(request, handler):
try: return await handler(request)
except Exception: logging.error("Unhandled exception for %s", request.path, exc_info=True); return web.json_response({'error': 'Internal server error'}, status=500)
def validate_session_id(session_id):
if not session_id or '/' in session_id or '..' in session_id: raise web.HTTPBadRequest(reason="Invalid Session ID.")
async def handle_root(request):
return web.Response(text=APP_HTML.replace("{files_api_url}", FILES_API_URL), content_type='text/html')
async def handle_status(request): return web.json_response(request.app['dependency_status'])
async def handle_stream_post(request):
session_id = request.match_info.get('session_id'); validate_session_id(session_id)
data = await request.post()
video_url, video_index = data.get('url', '').strip(), data.get('video_index')
if not video_url or video_index is None: raise web.HTTPBadRequest(reason="URL/video_index missing")
is_magnet = video_url.startswith("magnet:?")
processed_url = f"{STREAM_API_URL}{quote(video_url)}&index={video_index}" if is_magnet else video_url
await asyncio.to_thread(start_stream_process, session_id, processed_url)
if is_magnet:
if (sub_idx := data.get('subtitle_index')) and sub_idx.isdigit():
asyncio.create_task(download_and_convert_subtitle(request.app, session_id, video_url, int(sub_idx)))
task = asyncio.create_task(poll_stream_progress(request.app, session_id, video_url))
with streams_lock:
if session_id in active_streams: active_streams[session_id]['progress_task'] = task
return web.json_response({"status": "ok"})
async def handle_stop_stream(request):
session_id = request.match_info.get('session_id'); validate_session_id(session_id)
hard_reset = request.query.get('hard', 'false').lower() == 'true'
if hard_reset: logging.info(f"Performing hard reset for session {session_id}. All files will be deleted.")
stop_stream_process(session_id, cleanup_files=hard_reset)
return web.json_response({"status": "stopped"})
async def handle_heartbeat(request):
session_id = request.match_info.get('session_id'); validate_session_id(session_id)
with streams_lock:
if session_id in active_streams:
active_streams[session_id]['last_seen'] = time.time(); return web.json_response({"status": "ok"})
return web.json_response({"status": "session_not_found"}, status=404)
async def handle_progress(request):
session_id = request.match_info.get('session_id'); validate_session_id(session_id)
with streams_lock: data = active_streams.get(session_id, {}).get('progress_data', {})
return web.json_response(data)
async def handle_subtitle_vtt(request):
session_id = request.match_info.get('session_id'); validate_session_id(session_id)
vtt_path = os.path.join(STREAMS_BASE_DIR, session_id, 'subtitle.vtt')
if os.path.exists(vtt_path):
return web.FileResponse(
vtt_path,
headers={
'Content-Type': 'text/vtt; charset=utf-8',
'Cache-Control': 'no-cache, no-store, must-revalidate',
'Pragma': 'no-cache',
'Expires': '0',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-Type, Range',
'Access-Control-Expose-Headers': 'Content-Length, Content-Range'
}
)
return web.Response(status=404, text="Subtitle file not found.")
async def start_background_tasks(app):
app['reaper_task'] = asyncio.create_task(reaper_task(app)); app['http_client'] = ClientSession()
async def cleanup_on_shutdown(app):
app['reaper_task'].cancel(); await asyncio.gather(app['reaper_task'], return_exceptions=True); await app['http_client'].close()
for sid in list(active_streams.keys()): stop_stream_process(sid, cleanup_files=True)
# --- 7. Application Factory and Main Execution ---
def init_app():
app = web.Application(middlewares=[error_middleware])
app['dependency_status'] = {"ffmpeg": shutil.which("ffmpeg") is not None, "mpv": shutil.which("mpv") is not None}
app.router.add_get('/', handle_root); app.router.add_get('/status', handle_status)
app.router.add_post('/stream/{session_id}', handle_stream_post)
app.router.add_post('/stop/{session_id}', handle_stop_stream); app.router.add_post('/heartbeat/{session_id}', handle_heartbeat)
app.router.add_get('/progress/{session_id}', handle_progress)
app.router.add_get('/streams/{session_id}/subtitle.vtt', handle_subtitle_vtt)
app.router.add_static('/streams', path=STREAMS_BASE_DIR, name='streams')
app.on_startup.append(start_background_tasks); app.on_cleanup.append(cleanup_on_shutdown)
return app
def main():
if not os.path.ismount(STREAMS_BASE_DIR):
logging.warning(f"PERFORMANCE WARNING: For optimal performance, mount a RAM disk at {os.path.abspath(STREAMS_BASE_DIR)}")
port = 8000
try:
os.makedirs(STREAMS_BASE_DIR, exist_ok=True); web.run_app(init_app(), port=port)
except Exception as e: logging.critical("Failed to start application:", exc_info=True)
if __name__ == '__main__':
main()