forked from realbestia1/EasyProxy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
231 lines (188 loc) · 9.52 KB
/
app.py
File metadata and controls
231 lines (188 loc) · 9.52 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
import logging
import sys
import os
import asyncio
from aiohttp import web
# Aggiungi path corrente per import moduli
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from services.hls_proxy import HLSProxy
from services.ffmpeg_manager import FFmpegManager
from config import PORT, DVR_ENABLED, RECORDINGS_DIR, MAX_RECORDING_DURATION, RECORDINGS_RETENTION_DAYS
# Only import DVR components if enabled
if DVR_ENABLED:
from services.recording_manager import RecordingManager
from routes.recordings import setup_recording_routes
# Configurazione logging (già configurata in config.py ma utile per il main)
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(name)s - %(message)s'
)
# --- Logica di Avvio ---
def create_app():
"""Crea e configura l'applicazione aiohttp."""
# Start proxy and ffmpeg manager
ffmpeg_manager = FFmpegManager()
# Clean up any leftover processes on start
# asyncio.create_task(ffmpeg_manager.cleanup_loop()) # Should be started in on_startup
proxy = HLSProxy(ffmpeg_manager=ffmpeg_manager)
app = web.Application()
app['ffmpeg_manager'] = ffmpeg_manager # Make accessible for routes
app.ffmpeg_manager = ffmpeg_manager # Hack for access in route handler above function
# Initialize recording manager for DVR functionality (only if enabled)
if DVR_ENABLED:
recording_manager = RecordingManager(
recordings_dir=RECORDINGS_DIR,
max_duration=MAX_RECORDING_DURATION,
retention_days=RECORDINGS_RETENTION_DAYS
)
app['recording_manager'] = recording_manager
# Registra le route
app.router.add_get('/', proxy.handle_root)
app.router.add_get('/docs', proxy.handle_docs)
app.router.add_get('/redoc', proxy.handle_redoc)
app.router.add_get('/openapi.json', proxy.handle_openapi)
app.router.add_get('/favicon.ico', proxy.handle_favicon) # ✅ Route Favicon
# ✅ Route Static Files (con path assoluto e creazione automatica)
static_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static')
if not os.path.exists(static_path):
os.makedirs(static_path)
app.router.add_static('/static', static_path)
app.router.add_get('/builder', proxy.handle_builder)
app.router.add_get('/playlist/builder', proxy.handle_builder)
app.router.add_get('/url-generator', proxy.handle_url_generator)
app.router.add_get('/info', proxy.handle_info_page)
app.router.add_get('/api/info', proxy.handle_api_info)
app.router.add_get('/key', proxy.handle_key_request)
app.router.add_get('/proxy/manifest.m3u8', proxy.handle_proxy_request)
app.router.add_get('/proxy/hls/manifest.m3u8', proxy.handle_proxy_request)
app.router.add_get('/proxy/mpd/manifest.m3u8', proxy.handle_proxy_request)
# ✅ NUOVO: Endpoint generico per stream (compatibilità MFP)
app.router.add_get('/proxy/stream', proxy.handle_proxy_request)
app.router.add_get('/extractor', proxy.handle_extractor_request)
# ✅ NUOVO: Endpoint compatibilità MFP per estrazione
app.router.add_get('/extractor/video', proxy.handle_extractor_request)
# ✅ NUOVO: Route per segmenti con estensioni corrette per compatibilità player
app.router.add_get('/proxy/hls/segment.ts', proxy.handle_proxy_request)
app.router.add_get('/proxy/hls/segment.m4s', proxy.handle_proxy_request)
app.router.add_get('/proxy/hls/segment.mp4', proxy.handle_proxy_request)
app.router.add_get('/playlist', proxy.handle_playlist_request)
app.router.add_get('/segment/{segment}', proxy.handle_ts_segment)
app.router.add_get('/decrypt/segment.mp4', proxy.handle_decrypt_segment) # ClearKey decryption for legacy mode
app.router.add_get('/decrypt/segment.ts', proxy.handle_decrypt_segment) # TS variant for legacy mode
# ✅ NUOVO: Route per licenze DRM (GET e POST)
app.router.add_get('/license', proxy.handle_license_request)
app.router.add_post('/license', proxy.handle_license_request)
# ✅ NUOVO: Endpoint per generazione URL (compatibilità MFP)
app.router.add_post('/generate_urls', proxy.handle_generate_urls)
# --- PROXY ROUTES GENERICI ---
async def proxy_hls_stream(request):
"""Serve segments generated by FFmpeg"""
stream_id = request.match_info['stream_id']
filename = request.match_info['filename']
file_path = os.path.join("temp_hls", stream_id, filename)
# Security check: ensure path is within temp_hls
try:
if not os.path.abspath(file_path).startswith(os.path.abspath("temp_hls")):
return web.Response(status=403, text="Access denied")
except:
return web.Response(status=403, text="Access denied")
if not os.path.exists(file_path):
return web.Response(status=404, text="Segment not found")
# Notify manager to keep stream alive
if hasattr(app, 'ffmpeg_manager'):
app.ffmpeg_manager.touch_stream(stream_id)
if not os.path.exists(file_path):
return web.Response(status=404, text="Segment not found")
# Notify manager to keep stream alive
if hasattr(app, 'ffmpeg_manager'):
app.ffmpeg_manager.touch_stream(stream_id)
headers = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, HEAD, OPTIONS",
"Access-Control-Allow-Headers": "*",
"Cache-Control": "no-cache, no-store, must-revalidate",
"Connection": "keep-alive"
}
# Special handling for m3u8: read content and return 200 OK (no Range)
if filename.endswith('.m3u8'):
try:
# Add a small delay/retry read loop if file is being written?
# Usually OS allows reading while writing, but empty file is possible.
content = ""
for _ in range(3):
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
if content:
break
await asyncio.sleep(0.05)
return web.Response(
text=content,
content_type='application/vnd.apple.mpegurl',
headers=headers
)
except Exception as e:
logging.error(f"Error reading playlist {file_path}: {e}")
return web.Response(status=500, text="Internal Server Error")
elif filename.endswith('.ts'):
# For segments, correct mime type
# We can still use FileResponse for efficiency, usually players handle range or 206 for segments fine.
# But let's force expected headers.
# aiohttp FileResponse handles ranges automatically.
pass
# web.FileResponse doesn't easily allow overriding headers in constructor in older versions,
# but we can set them on the response object if we create it differently or subclass.
# Actually, standard FileResponse takes headers.
# Explicit content type for TS
if filename.endswith('.ts'):
# Create response, add headers, then prepare? No, FileResponse is unexpected.
# Just pass headers.
headers['Content-Type'] = 'video/MP2T'
return web.FileResponse(file_path, headers=headers)
return web.FileResponse(file_path, headers=headers)
app.router.add_get('/ffmpeg_stream/{stream_id}/{filename}', proxy_hls_stream)
# ✅ NUOVO: Endpoint per ottenere l'IP pubblico
app.router.add_get('/proxy/ip', proxy.handle_proxy_ip)
# Setup recording/DVR routes (only if enabled)
if DVR_ENABLED:
setup_recording_routes(app, recording_manager)
# Gestore OPTIONS generico per CORS
app.router.add_route('OPTIONS', '/{tail:.*}', proxy.handle_options)
async def cleanup_handler(app):
await proxy.cleanup()
app.on_cleanup.append(cleanup_handler)
async def on_startup(app):
asyncio.create_task(ffmpeg_manager.cleanup_loop())
if DVR_ENABLED:
asyncio.create_task(recording_manager.cleanup_loop())
app.on_startup.append(on_startup)
async def on_shutdown(app):
if DVR_ENABLED:
await recording_manager.shutdown()
app.on_shutdown.append(on_shutdown)
return app
# Crea l'istanza "privata" dell'applicazione aiohttp.
app = create_app()
def main():
"""Funzione principale per avviare il server."""
# Workaround per il bug di asyncio su Windows con ConnectionResetError
if sys.platform == 'win32':
# Silenzia il logger di asyncio per evitare spam di ConnectionResetError
logging.getLogger('asyncio').setLevel(logging.CRITICAL)
print("🚀 Starting HLS Proxy Server...")
print(f"📡 Server available at: http://localhost:{PORT}")
print(f"📡 Or: http://server-ip:{PORT}")
print("🔗 Endpoints:")
print(" • / - Main page")
print(" • /builder - Web interface for playlist builder")
print(" • /info - Server information page")
print(" • /recordings - DVR/Recording interface")
print(" • /proxy/manifest.m3u8?url=<URL> - Main stream proxy")
print(" • /playlist?url=<definitions> - Playlist generator")
print("=" * 50)
web.run_app(
app, # Usa l'istanza aiohttp originale per il runner integrato
host='0.0.0.0',
port=PORT
)
if __name__ == '__main__':
main()