const express = require('express'); const router = express.Router(); const { sources } = require('../db'); const { getDb } = require('../db/sqlite'); const xtreamApi = require('../services/xtreamApi'); const syncService = require('../services/syncService'); const m3uParser = require('../services/m3uParser'); const { requireAuth, requireAdmin, isAdminRole } = require('../auth'); const { canUserAccessSource, getAccessibleSourceIds } = require('../sourceAccess'); router.use(requireAuth); function sanitizeSourceList(list) { return list.map((s) => ({ ...s, password: s.password ? '••••••••' : null })); } function parseOwnerId(body) { const raw = body.ownerId; if (raw === undefined || raw === null || raw === '') return null; const n = parseInt(raw, 10); return Number.isNaN(n) ? null : n; } // Estimate by URL (must stay before /:id routes) const M3U_LARGE_THRESHOLD = 50000; router.post('/estimate', async (req, res) => { try { const { url, type } = req.body; if (!url) { return res.status(400).json({ error: 'URL is required' }); } if (type !== 'm3u') { return res.json({ count: 0, needsWarning: false, threshold: M3U_LARGE_THRESHOLD }); } const count = await m3uParser.countEntries(url); res.json({ count, needsWarning: count > M3U_LARGE_THRESHOLD, threshold: M3U_LARGE_THRESHOLD }); } catch (err) { console.error('Error estimating M3U size:', err); res.status(500).json({ error: 'Failed to estimate playlist size', message: err.message }); } }); // Global sync — admin only router.post('/sync-all', requireAdmin, async (req, res) => { try { syncService.syncAll().catch(console.error); res.json({ success: true, message: 'Global sync started' }); } catch (err) { console.error('Error starting global sync:', err); res.status(500).json({ error: 'Failed to start global sync' }); } }); // Get all sources (filtered by access) router.get('/', async (req, res) => { try { const allSources = await sources.getAll(); const filtered = allSources.filter((s) => canUserAccessSource(req.user, s)); res.json(sanitizeSourceList(filtered)); } catch (err) { console.error('Error getting sources:', err); res.status(500).json({ error: 'Failed to get sources' }); } }); // Get sync status (filtered for non-admins) router.get('/status', async (req, res) => { try { const db = getDb(); let statuses = db.prepare('SELECT * FROM sync_status').all(); if (req.user.role !== 'admin') { const allowed = new Set(await getAccessibleSourceIds(req, sources)); statuses = statuses.filter((row) => allowed.has(row.source_id)); } res.json(statuses); } catch (err) { console.error('Error getting sync status:', err); res.status(500).json({ error: 'Failed to get sync status' }); } }); // Get sources by type router.get('/type/:type', async (req, res) => { try { const typeSources = await sources.getByType(req.params.type); const filtered = typeSources.filter((s) => canUserAccessSource(req.user, s)); res.json(sanitizeSourceList(filtered)); } catch (err) { console.error('Error getting sources by type:', err); res.status(500).json({ error: 'Failed to get sources' }); } }); // Estimate by source ID (before bare GET /:id — same base path length) router.get('/:id/estimate', async (req, res) => { try { const source = await sources.getById(req.params.id); if (!source) { return res.status(404).json({ error: 'Source not found' }); } if (!canUserAccessSource(req.user, source)) { return res.status(403).json({ error: 'No access to this source' }); } if (source.type !== 'm3u') { return res.json({ count: 0, needsWarning: false, threshold: M3U_LARGE_THRESHOLD }); } const count = await m3uParser.countEntries(source.url); res.json({ count, needsWarning: count > M3U_LARGE_THRESHOLD, threshold: M3U_LARGE_THRESHOLD }); } catch (err) { console.error('Error estimating M3U size:', err); res.status(500).json({ error: 'Failed to estimate playlist size', message: err.message }); } }); // Get single source router.get('/:id', async (req, res) => { try { const source = await sources.getById(req.params.id); if (!source) { return res.status(404).json({ error: 'Source not found' }); } if (!canUserAccessSource(req.user, source)) { return res.status(403).json({ error: 'No access to this source' }); } res.json(source); } catch (err) { console.error('Error getting source:', err); res.status(500).json({ error: 'Failed to get source' }); } }); // Create source router.post('/', async (req, res) => { try { const { type, name, url, username, password } = req.body; if (!type || !name || !url) { return res.status(400).json({ error: 'Type, name, and URL are required' }); } if (!['xtream', 'm3u', 'epg'].includes(type)) { return res.status(400).json({ error: 'Invalid source type' }); } let ownerId = null; if (isAdminRole(req.user)) { ownerId = parseOwnerId(req.body); } else { const uid = req.user.id != null ? Number(req.user.id) : NaN; ownerId = Number.isNaN(uid) ? null : uid; } const source = await sources.create({ type, name, url, username, password, ownerId }); syncService.syncSource(source.id).catch(console.error); res.status(201).json(source); } catch (err) { console.error('Error creating source:', err); res.status(500).json({ error: 'Failed to create source' }); } }); // Update source router.put('/:id', async (req, res) => { try { const existing = await sources.getById(req.params.id); if (!existing) { return res.status(404).json({ error: 'Source not found' }); } if (!canUserAccessSource(req.user, existing)) { return res.status(403).json({ error: 'No access to this source' }); } const { name, url, username, password } = req.body; const updates = { name: name || existing.name, url: url || existing.url, username: username !== undefined ? username : existing.username, password: password !== undefined ? password : existing.password }; if (isAdminRole(req.user) && req.body.ownerId !== undefined) { updates.ownerId = parseOwnerId(req.body); } const updated = await sources.update(req.params.id, updates); syncService.syncSource(parseInt(req.params.id, 10)).catch(console.error); res.json(updated); } catch (err) { console.error('Error updating source:', err); res.status(500).json({ error: 'Failed to update source' }); } }); // Delete source router.delete('/:id', async (req, res) => { try { const sourceId = parseInt(req.params.id, 10); const existing = await sources.getById(sourceId); if (!existing) { return res.status(404).json({ error: 'Source not found' }); } if (!canUserAccessSource(req.user, existing)) { return res.status(403).json({ error: 'No access to this source' }); } const db = getDb(); const deleteCategories = db.prepare('DELETE FROM categories WHERE source_id = ?'); const deleteItems = db.prepare('DELETE FROM playlist_items WHERE source_id = ?'); const deleteEpg = db.prepare('DELETE FROM epg_programs WHERE source_id = ?'); const deleteSyncStatus = db.prepare('DELETE FROM sync_status WHERE source_id = ?'); const catResult = deleteCategories.run(sourceId); const itemResult = deleteItems.run(sourceId); const epgResult = deleteEpg.run(sourceId); deleteSyncStatus.run(sourceId); console.log(`[Source] Cascade delete for source ${sourceId}: ${catResult.changes} categories, ${itemResult.changes} items, ${epgResult.changes} EPG programs`); await sources.delete(sourceId); res.json({ success: true }); } catch (err) { console.error('Error deleting source:', err); res.status(500).json({ error: 'Failed to delete source' }); } }); // Toggle source enabled/disabled router.post('/:id/toggle', async (req, res) => { try { const existing = await sources.getById(req.params.id); if (!existing) { return res.status(404).json({ error: 'Source not found' }); } if (!canUserAccessSource(req.user, existing)) { return res.status(403).json({ error: 'No access to this source' }); } const updated = await sources.toggleEnabled(req.params.id); if (!updated) { return res.status(404).json({ error: 'Source not found' }); } if (updated.enabled) { syncService.syncSource(parseInt(req.params.id, 10)).catch(console.error); } res.json(updated); } catch (err) { console.error('Error toggling source:', err); res.status(500).json({ error: 'Failed to toggle source' }); } }); // Manual Sync router.post('/:id/sync', async (req, res) => { try { const id = parseInt(req.params.id, 10); const source = await sources.getById(id); if (!source) return res.status(404).json({ error: 'Source not found' }); if (!canUserAccessSource(req.user, source)) { return res.status(403).json({ error: 'No access to this source' }); } syncService.syncSource(id).catch(console.error); res.json({ success: true, message: 'Sync started' }); } catch (err) { console.error('Error starting sync:', err); res.status(500).json({ error: 'Failed to start sync' }); } }); // Test source connection router.post('/:id/test', async (req, res) => { try { const source = await sources.getById(req.params.id); if (!source) { return res.status(404).json({ error: 'Source not found' }); } if (!canUserAccessSource(req.user, source)) { return res.status(403).json({ error: 'No access to this source' }); } if (source.type === 'xtream') { const result = await xtreamApi.authenticate(source.url, source.username, source.password); res.json({ success: true, data: result }); } else if (source.type === 'm3u') { const response = await fetch(source.url); const text = await response.text(); const isValid = text.includes('#EXTM3U'); res.json({ success: isValid, message: isValid ? 'Valid M3U playlist' : 'Invalid M3U format' }); } else if (source.type === 'epg') { const response = await fetch(source.url); const text = await response.text(); const isValid = text.includes('