Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
581 lines (523 loc) · 22.7 KB
/
Copy pathindex.js
File metadata and controls
581 lines (523 loc) · 22.7 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
const express = require('express');
const cors = require('cors');
const { addonBuilder } = require('stremio-addon-sdk');
const PlaylistTransformer = require('./playlist-transformer');
const { catalogHandler, streamHandler } = require('./handlers');
const metaHandler = require('./meta-handler');
const EPGManager = require('./epg-manager');
const config = require('./config');
const CacheManager = require('./cache-manager')(config);
const { renderConfigPage } = require('./views');
const PythonRunner = require('./python-runner');
const ResolverStreamManager = require('./resolver-stream-manager')();
const PythonResolver = require('./python-resolver');
const fs = require('fs');
const path = require('path');
const app = express();
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Route principale - supporta sia il vecchio che il nuovo sistema
app.get('/', async (req, res) => {
const protocol = req.headers['x-forwarded-proto'] || req.protocol;
const host = req.headers['x-forwarded-host'] || req.get('host');
res.send(renderConfigPage(protocol, host, req.query, config.manifest));
});
// Nuova route per la configurazione codificata
app.get('/:config/configure', async (req, res) => {
try {
const protocol = req.headers['x-forwarded-proto'] || req.protocol;
const host = req.headers['x-forwarded-host'] || req.get('host');
const configString = Buffer.from(req.params.config, 'base64').toString();
const decodedConfig = Object.fromEntries(new URLSearchParams(configString));
// Inizializza il generatore Python se configurato
if (decodedConfig.python_script_url) {
console.log('Inizializzazione Script Python Generatore dalla configurazione');
try {
// Scarica lo script Python se non già scaricato
await PythonRunner.downloadScript(decodedConfig.python_script_url);
// Se è stato definito un intervallo di aggiornamento, impostalo
if (decodedConfig.python_update_interval) {
console.log('Impostazione dell\'aggiornamento automatico del generatore Python');
PythonRunner.scheduleUpdate(decodedConfig.python_update_interval);
}
} catch (pythonError) {
console.error('Errore nell\'inizializzazione dello script Python:', pythonError);
}
}
res.send(renderConfigPage(protocol, host, decodedConfig, config.manifest));
} catch (error) {
console.error('Errore nella configurazione:', error);
res.redirect('/');
}
});
// Route per il manifest - supporta sia il vecchio che il nuovo sistema
app.get('/manifest.json', async (req, res) => {
try {
const protocol = req.headers['x-forwarded-proto'] || req.protocol;
const host = req.headers['x-forwarded-host'] || req.get('host');
const configUrl = `${protocol}://${host}/?${new URLSearchParams(req.query)}`;
if (req.query.resolver_update_interval) {
configUrl += `&resolver_update_interval=${encodeURIComponent(req.query.resolver_update_interval)}`;
}
if (req.query.m3u && CacheManager.cache.m3uUrl !== req.query.m3u) {
await CacheManager.rebuildCache(req.query.m3u);
}
const { genres } = CacheManager.getCachedData();
const manifestConfig = {
...config.manifest,
catalogs: [{
...config.manifest.catalogs[0],
extra: [
{
name: 'genre',
isRequired: false,
options: genres
},
{
name: 'search',
isRequired: false
},
{
name: 'skip',
isRequired: false
}
]
}],
behaviorHints: {
configurable: true,
configurationURL: configUrl,
reloadRequired: true
}
};
const builder = new addonBuilder(manifestConfig);
if (req.query.epg_enabled === 'true') {
// Se non è stato fornito manualmente un EPG URL, usa quello della playlist
const epgToUse = req.query.epg ||
(CacheManager.getCachedData().epgUrls &&
CacheManager.getCachedData().epgUrls.length > 0
? CacheManager.getCachedData().epgUrls.join(',')
: null);
if (epgToUse) {
await EPGManager.initializeEPG(epgToUse);
}
}
builder.defineCatalogHandler(async (args) => catalogHandler({ ...args, config: req.query }));
builder.defineStreamHandler(async (args) => streamHandler({ ...args, config: req.query }));
builder.defineMetaHandler(async (args) => metaHandler({ ...args, config: req.query }));
res.setHeader('Content-Type', 'application/json');
res.send(builder.getInterface().manifest);
} catch (error) {
console.error('Error creating manifest:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// Nuova route per il manifest con configurazione codificata
app.get('/:config/manifest.json', async (req, res) => {
try {
const protocol = req.headers['x-forwarded-proto'] || req.protocol;
const host = req.headers['x-forwarded-host'] || req.get('host');
const configString = Buffer.from(req.params.config, 'base64').toString();
const decodedConfig = Object.fromEntries(new URLSearchParams(configString));
if (decodedConfig.m3u && CacheManager.cache.m3uUrl !== decodedConfig.m3u) {
await CacheManager.rebuildCache(decodedConfig.m3u);
}
if (decodedConfig.resolver_script) {
console.log('Inizializzazione Script Resolver dalla configurazione');
try {
// Scarica lo script Resolver
const resolverDownloaded = await PythonResolver.downloadScript(decodedConfig.resolver_script);
// Se è stato definito un intervallo di aggiornamento, impostalo
if (decodedConfig.resolver_update_interval) {
console.log('Impostazione dell\'aggiornamento automatico del resolver');
PythonResolver.scheduleUpdate(decodedConfig.resolver_update_interval);
}
} catch (resolverError) {
console.error('Errore nell\'inizializzazione dello script Resolver:', resolverError);
}
}
// Inizializza il generatore Python se configurato
if (decodedConfig.python_script_url) {
console.log('Inizializzazione Script Python Generatore dalla configurazione');
try {
// Scarica lo script Python se non già scaricato
await PythonRunner.downloadScript(decodedConfig.python_script_url);
// Se è stato definito un intervallo di aggiornamento, impostalo
if (decodedConfig.python_update_interval) {
console.log('Impostazione dell\'aggiornamento automatico del generatore Python');
PythonRunner.scheduleUpdate(decodedConfig.python_update_interval);
}
} catch (pythonError) {
console.error('Errore nell\'inizializzazione dello script Python:', pythonError);
}
}
const { genres } = CacheManager.getCachedData();
const manifestConfig = {
...config.manifest,
catalogs: [{
...config.manifest.catalogs[0],
extra: [
{
name: 'genre',
isRequired: false,
options: genres
},
{
name: 'search',
isRequired: false
},
{
name: 'skip',
isRequired: false
}
]
}],
behaviorHints: {
configurable: true,
configurationURL: `${protocol}://${host}/${req.params.config}/configure`,
reloadRequired: true
}
};
const builder = new addonBuilder(manifestConfig);
if (decodedConfig.epg_enabled === 'true') {
// Se non è stato fornito manualmente un EPG URL, usa quello della playlist
const epgToUse = decodedConfig.epg ||
(CacheManager.getCachedData().epgUrls &&
CacheManager.getCachedData().epgUrls.length > 0
? CacheManager.getCachedData().epgUrls.join(',')
: null);
if (epgToUse) {
await EPGManager.initializeEPG(epgToUse);
}
}
builder.defineCatalogHandler(async (args) => catalogHandler({ ...args, config: decodedConfig }));
builder.defineStreamHandler(async (args) => streamHandler({ ...args, config: decodedConfig }));
builder.defineMetaHandler(async (args) => metaHandler({ ...args, config: decodedConfig }));
res.setHeader('Content-Type', 'application/json');
res.send(builder.getInterface().manifest);
} catch (error) {
console.error('Error creating manifest:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// Manteniamo la route esistente per gli altri endpoint
app.get('/:resource/:type/:id/:extra?.json', async (req, res, next) => {
const { resource, type, id } = req.params;
const extra = req.params.extra
? safeParseExtra(req.params.extra)
: {};
try {
let result;
switch (resource) {
case 'stream':
result = await streamHandler({ type, id, config: req.query });
break;
case 'catalog':
result = await catalogHandler({ type, id, extra, config: req.query });
break;
case 'meta':
result = await metaHandler({ type, id, config: req.query });
break;
default:
next();
return;
}
res.setHeader('Content-Type', 'application/json');
res.send(result);
} catch (error) {
console.error('Error handling request:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
//route download template
app.get('/api/resolver/download-template', (req, res) => {
const PythonResolver = require('./python-resolver');
const fs = require('fs');
try {
if (fs.existsSync(PythonResolver.scriptPath)) {
res.setHeader('Content-Type', 'text/plain');
res.setHeader('Content-Disposition', 'attachment; filename="resolver_script.py"');
res.sendFile(PythonResolver.scriptPath);
} else {
res.status(404).json({ success: false, message: 'Template non trovato. Crealo prima con la funzione "Crea Template".' });
}
} catch (error) {
console.error('Errore nel download del template:', error);
res.status(500).json({ success: false, message: error.message });
}
});
function cleanupTempFolder() {
console.log('\n=== Pulizia cartella temp all\'avvio ===');
const tempDir = path.join(__dirname, 'temp');
// Controlla se la cartella temp esiste
if (!fs.existsSync(tempDir)) {
console.log('Cartella temp non trovata, la creo...');
fs.mkdirSync(tempDir, { recursive: true });
return;
}
try {
// Leggi tutti i file nella cartella temp
const files = fs.readdirSync(tempDir);
let deletedCount = 0;
// Elimina ogni file
for (const file of files) {
try {
const filePath = path.join(tempDir, file);
// Controlla se è un file e non una cartella
if (fs.statSync(filePath).isFile()) {
fs.unlinkSync(filePath);
deletedCount++;
}
} catch (fileError) {
console.error(`❌ Errore nell'eliminazione del file ${file}:`, fileError.message);
}
}
console.log(`✓ Eliminati ${deletedCount} file temporanei`);
console.log('=== Pulizia cartella temp completata ===\n');
} catch (error) {
console.error('❌ Errore nella pulizia della cartella temp:', error.message);
}
}
function safeParseExtra(extraParam) {
try {
if (!extraParam) return {};
const decodedExtra = decodeURIComponent(extraParam);
// Supporto per skip con genere
if (decodedExtra.includes('genre=') && decodedExtra.includes('&skip=')) {
const parts = decodedExtra.split('&');
const genre = parts.find(p => p.startsWith('genre=')).split('=')[1];
const skip = parts.find(p => p.startsWith('skip=')).split('=')[1];
return {
genre,
skip: parseInt(skip, 10) || 0
};
}
if (decodedExtra.startsWith('skip=')) {
return { skip: parseInt(decodedExtra.split('=')[1], 10) || 0 };
}
if (decodedExtra.startsWith('genre=')) {
return { genre: decodedExtra.split('=')[1] };
}
if (decodedExtra.startsWith('search=')) {
return { search: decodedExtra.split('=')[1] };
}
try {
return JSON.parse(decodedExtra);
} catch {
return {};
}
} catch (error) {
console.error('Error parsing extra:', error);
return {};
}
}
// Per il catalog con config codificato
app.get('/:config/catalog/:type/:id/:extra?.json', async (req, res) => {
try {
const configString = Buffer.from(req.params.config, 'base64').toString();
const decodedConfig = Object.fromEntries(new URLSearchParams(configString));
const extra = req.params.extra
? safeParseExtra(req.params.extra)
: {};
const result = await catalogHandler({
type: req.params.type,
id: req.params.id,
extra,
config: decodedConfig
});
res.setHeader('Content-Type', 'application/json');
res.send(result);
} catch (error) {
console.error('Error handling catalog request:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// Per lo stream con config codificato
app.get('/:config/stream/:type/:id.json', async (req, res) => {
try {
const configString = Buffer.from(req.params.config, 'base64').toString();
const decodedConfig = Object.fromEntries(new URLSearchParams(configString));
const result = await streamHandler({
type: req.params.type,
id: req.params.id,
config: decodedConfig
});
res.setHeader('Content-Type', 'application/json');
res.send(result);
} catch (error) {
console.error('Error handling stream request:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// Per il meta con config codificato
app.get('/:config/meta/:type/:id.json', async (req, res) => {
try {
const configString = Buffer.from(req.params.config, 'base64').toString();
const decodedConfig = Object.fromEntries(new URLSearchParams(configString));
const result = await metaHandler({
type: req.params.type,
id: req.params.id,
config: decodedConfig
});
res.setHeader('Content-Type', 'application/json');
res.send(result);
} catch (error) {
console.error('Error handling meta request:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
// Route per servire il file M3U generato
app.get('/generated-m3u', (req, res) => {
const m3uContent = PythonRunner.getM3UContent();
if (m3uContent) {
res.setHeader('Content-Type', 'text/plain');
res.send(m3uContent);
} else {
res.status(404).send('File M3U non trovato. Eseguire prima lo script Python.');
}
});
app.post('/api/resolver', async (req, res) => {
const { action, url, interval } = req.body;
try {
if (action === 'download' && url) {
const success = await PythonResolver.downloadScript(url);
if (success) {
res.json({ success: true, message: 'Script resolver scaricato con successo' });
} else {
res.status(500).json({ success: false, message: PythonResolver.getStatus().lastError });
}
} else if (action === 'create-template') {
const success = await PythonResolver.createScriptTemplate();
if (success) {
res.json({
success: true,
message: 'Template script resolver creato con successo',
scriptPath: PythonResolver.scriptPath
});
} else {
res.status(500).json({ success: false, message: PythonResolver.getStatus().lastError });
}
} else if (action === 'check-health') {
const isHealthy = await PythonResolver.checkScriptHealth();
res.json({
success: isHealthy,
message: isHealthy ? 'Script resolver valido' : PythonResolver.getStatus().lastError
});
} else if (action === 'status') {
res.json(PythonResolver.getStatus());
} else if (action === 'clear-cache') {
PythonResolver.clearCache();
res.json({ success: true, message: 'Cache resolver svuotata' });
} else if (action === 'schedule' && interval) {
const success = PythonResolver.scheduleUpdate(interval);
if (success) {
res.json({
success: true,
message: `Aggiornamento automatico impostato ogni ${interval}`
});
} else {
res.status(500).json({ success: false, message: PythonResolver.getStatus().lastError });
}
} else if (action === 'stopSchedule') {
const stopped = PythonResolver.stopScheduledUpdates();
res.json({
success: true,
message: stopped ? 'Aggiornamento automatico fermato' : 'Nessun aggiornamento pianificato da fermare'
});
} else {
res.status(400).json({ success: false, message: 'Azione non valida' });
}
} catch (error) {
console.error('Errore API Resolver:', error);
res.status(500).json({ success: false, message: error.message });
}
});
app.post('/api/rebuild-cache', async (req, res) => {
try {
const m3uUrl = req.body.m3u;
if (!m3uUrl) {
return res.status(400).json({ success: false, message: 'URL M3U richiesto' });
}
console.log('🔄 Richiesta di ricostruzione cache ricevuta');
await CacheManager.rebuildCache(req.body.m3u, req.body);
if (req.body.epg_enabled === 'true') {
console.log('📡 Ricostruzione EPG in corso...');
const epgToUse = req.body.epg ||
(CacheManager.getCachedData().epgUrls && CacheManager.getCachedData().epgUrls.length > 0
? CacheManager.getCachedData().epgUrls.join(',')
: null);
if (epgToUse) {
await EPGManager.initializeEPG(epgToUse);
}
}
res.json({ success: true, message: 'Cache e EPG ricostruiti con successo' });
} catch (error) {
console.error('Errore nella ricostruzione della cache:', error);
res.status(500).json({ success: false, message: error.message });
}
});
// Endpoint API per le operazioni sullo script Python
app.post('/api/python-script', async (req, res) => {
const { action, url, interval } = req.body;
try {
if (action === 'download' && url) {
const success = await PythonRunner.downloadScript(url);
if (success) {
res.json({ success: true, message: 'Script scaricato con successo' });
} else {
res.status(500).json({ success: false, message: PythonRunner.getStatus().lastError });
}
} else if (action === 'execute') {
const success = await PythonRunner.executeScript();
if (success) {
res.json({
success: true,
message: 'Script eseguito con successo',
m3uUrl: `${req.protocol}://${req.get('host')}/generated-m3u`
});
} else {
res.status(500).json({ success: false, message: PythonRunner.getStatus().lastError });
}
} else if (action === 'status') {
res.json(PythonRunner.getStatus());
} else if (action === 'schedule' && interval) {
const success = PythonRunner.scheduleUpdate(interval);
if (success) {
res.json({
success: true,
message: `Aggiornamento automatico impostato ogni ${interval}`
});
} else {
res.status(500).json({ success: false, message: PythonRunner.getStatus().lastError });
}
} else if (action === 'stopSchedule') {
const stopped = PythonRunner.stopScheduledUpdates();
res.json({
success: true,
message: stopped ? 'Aggiornamento automatico fermato' : 'Nessun aggiornamento pianificato da fermare'
});
} else {
res.status(400).json({ success: false, message: 'Azione non valida' });
}
} catch (error) {
console.error('Errore API Python:', error);
res.status(500).json({ success: false, message: error.message });
}
});
async function startAddon() {
cleanupTempFolder();
try {
const port = process.env.PORT || 10000;
app.listen(port, () => {
console.log('=============================\n');
console.log('OMG ADDON Avviato con successo');
console.log('Visita la pagina web per generare la configurazione del manifest e installarla su stremio');
console.log('Link alla pagina di configurazione:', `http://localhost:${port}`);
console.log('=============================\n');
});
} catch (error) {
console.error('Failed to start addon:', error);
process.exit(1);
}
}
startAddon();