Initial commit

This commit is contained in:
Trevor Mears
2025-12-27 14:16:40 -08:00
commit 4f9ec55874
30 changed files with 9148 additions and 0 deletions
+268
View File
@@ -0,0 +1,268 @@
const fs = require('fs');
const path = require('path');
// Ensure data directory exists
const dataDir = path.join(__dirname, '..', 'data');
if (!fs.existsSync(dataDir)) {
fs.mkdirSync(dataDir, { recursive: true });
}
const dbPath = path.join(dataDir, 'db.json');
// Initialize database structure
function loadDb() {
try {
if (fs.existsSync(dbPath)) {
const data = JSON.parse(fs.readFileSync(dbPath, 'utf-8'));
// Ensure all keys exist
return {
sources: data.sources || [],
hiddenItems: data.hiddenItems || [],
favorites: data.favorites || [],
nextId: data.nextId || 1
};
}
} catch (err) {
console.error('Error loading database:', err);
}
return {
sources: [],
hiddenItems: [],
favorites: [],
nextId: 1
};
}
function saveDb(data) {
fs.writeFileSync(dbPath, JSON.stringify(data, null, 2));
}
// Source CRUD operations
const sources = {
getAll() {
const db = loadDb();
return db.sources;
},
getById(id) {
const db = loadDb();
return db.sources.find(s => s.id === parseInt(id));
},
getByType(type) {
const db = loadDb();
return db.sources.filter(s => s.type === type && s.enabled);
},
create(source) {
const db = loadDb();
const newSource = {
id: db.nextId++,
...source,
enabled: true,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString()
};
db.sources.push(newSource);
saveDb(db);
return newSource;
},
update(id, updates) {
const db = loadDb();
const index = db.sources.findIndex(s => s.id === parseInt(id));
if (index === -1) return null;
db.sources[index] = {
...db.sources[index],
...updates,
updated_at: new Date().toISOString()
};
saveDb(db);
return db.sources[index];
},
delete(id) {
const db = loadDb();
db.sources = db.sources.filter(s => s.id !== parseInt(id));
// Also delete related hidden items
db.hiddenItems = db.hiddenItems.filter(h => h.source_id !== parseInt(id));
saveDb(db);
},
toggleEnabled(id) {
const db = loadDb();
const source = db.sources.find(s => s.id === parseInt(id));
if (source) {
source.enabled = !source.enabled;
source.updated_at = new Date().toISOString();
saveDb(db);
}
return source;
}
};
// Hidden items operations
const hiddenItems = {
getAll(sourceId = null) {
const db = loadDb();
if (sourceId) {
return db.hiddenItems.filter(h => h.source_id === parseInt(sourceId));
}
return db.hiddenItems;
},
hide(sourceId, itemType, itemId) {
const db = loadDb();
// Check if already hidden
const exists = db.hiddenItems.find(
h => h.source_id === parseInt(sourceId) && h.item_type === itemType && h.item_id === itemId
);
if (!exists) {
db.hiddenItems.push({
id: db.nextId++,
source_id: parseInt(sourceId),
item_type: itemType,
item_id: itemId
});
saveDb(db);
}
},
show(sourceId, itemType, itemId) {
const db = loadDb();
db.hiddenItems = db.hiddenItems.filter(
h => !(h.source_id === parseInt(sourceId) && h.item_type === itemType && h.item_id === itemId)
);
saveDb(db);
},
isHidden(sourceId, itemType, itemId) {
const db = loadDb();
return db.hiddenItems.some(
h => h.source_id === parseInt(sourceId) && h.item_type === itemType && h.item_id === itemId
);
},
bulkHide(items) {
const db = loadDb();
let modified = false;
items.forEach(item => {
const { sourceId, itemType, itemId } = item;
const exists = db.hiddenItems.find(
h => h.source_id === parseInt(sourceId) && h.item_type === itemType && h.item_id === itemId
);
if (!exists) {
db.hiddenItems.push({
id: db.nextId++,
source_id: parseInt(sourceId),
item_type: itemType,
item_id: itemId
});
modified = true;
}
});
if (modified) {
saveDb(db);
}
return true;
},
bulkShow(items) {
const db = loadDb();
const initialLength = db.hiddenItems.length;
// Create a set of "signatures" for O(1) lookup of items to remove
const toRemove = new Set(items.map(i => `${i.sourceId}:${i.itemType}:${i.itemId}`));
db.hiddenItems = db.hiddenItems.filter(h =>
!toRemove.has(`${h.source_id}:${h.item_type}:${h.item_id}`)
);
if (db.hiddenItems.length !== initialLength) {
saveDb(db);
}
return true;
}
};
// Favorites operations
const favorites = {
getAll(sourceId = null, itemType = null) {
const db = loadDb();
let results = db.favorites;
if (sourceId) {
results = results.filter(f => f.source_id === parseInt(sourceId));
}
if (itemType) {
results = results.filter(f => f.item_type === itemType);
}
return results;
},
add(sourceId, itemId, itemType = 'channel') {
const db = loadDb();
// Check if already favorited
const exists = db.favorites.find(
f => f.source_id === parseInt(sourceId) && f.item_id === String(itemId) && f.item_type === itemType
);
if (!exists) {
db.favorites.push({
id: db.nextId++,
source_id: parseInt(sourceId),
item_id: String(itemId),
item_type: itemType, // 'channel', 'movie', 'series'
created_at: new Date().toISOString()
});
saveDb(db);
}
return true;
},
remove(sourceId, itemId, itemType = 'channel') {
const db = loadDb();
db.favorites = db.favorites.filter(
f => !(f.source_id === parseInt(sourceId) && f.item_id === String(itemId) && f.item_type === itemType)
);
saveDb(db);
return true;
},
isFavorite(sourceId, itemId, itemType = 'channel') {
const db = loadDb();
return db.favorites.some(
f => f.source_id === parseInt(sourceId) && f.item_id === String(itemId) && f.item_type === itemType
);
}
};
// EPG cache operations (simple in-memory for now)
const epgCache = {
cache: new Map(),
get(channelId) {
return this.cache.get(channelId);
},
set(sourceId, channelId, data) {
this.cache.set(channelId, { sourceId, data, updated_at: new Date() });
},
clear(sourceId = null) {
if (sourceId) {
for (const [key, value] of this.cache) {
if (value.sourceId === sourceId) {
this.cache.delete(key);
}
}
} else {
this.cache.clear();
}
}
};
module.exports = { sources, hiddenItems, favorites, epgCache };
+33
View File
@@ -0,0 +1,33 @@
const express = require('express');
const path = require('path');
// Initialize database
require('./db');
const app = express();
const PORT = process.env.PORT || 3000;
// Middleware
app.use(express.json({ limit: '50mb' }));
app.use(express.static(path.join(__dirname, '..', 'public')));
// API Routes
app.use('/api/sources', require('./routes/sources'));
app.use('/api/proxy', require('./routes/proxy'));
app.use('/api/channels', require('./routes/channels'));
app.use('/api/favorites', require('./routes/favorites'));
// SPA fallback - serve index.html for all non-API routes
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '..', 'public', 'index.html'));
});
// Error handling
app.use((err, req, res, next) => {
console.error('Server error:', err);
res.status(500).json({ error: 'Internal server error' });
});
app.listen(PORT, () => {
console.log(`NodeCast TV server running on http://localhost:${PORT}`);
});
+106
View File
@@ -0,0 +1,106 @@
const express = require('express');
const router = express.Router();
const { hiddenItems } = require('../db');
// Get all hidden items
router.get('/hidden', (req, res) => {
try {
const { sourceId } = req.query;
const items = hiddenItems.getAll(sourceId ? parseInt(sourceId) : null);
res.json(items);
} catch (err) {
console.error('Error getting hidden items:', err);
res.status(500).json({ error: 'Failed to get hidden items' });
}
});
// Hide a channel or group
router.post('/hide', (req, res) => {
try {
const { sourceId, itemType, itemId } = req.body;
if (!sourceId || !itemType || !itemId) {
return res.status(400).json({ error: 'sourceId, itemType, and itemId are required' });
}
if (!['channel', 'group'].includes(itemType)) {
return res.status(400).json({ error: 'itemType must be "channel" or "group"' });
}
hiddenItems.hide(sourceId, itemType, itemId);
res.json({ success: true });
} catch (err) {
console.error('Error hiding item:', err);
res.status(500).json({ error: 'Failed to hide item' });
}
});
// Show (unhide) a channel or group
router.post('/show', (req, res) => {
try {
const { sourceId, itemType, itemId } = req.body;
if (!sourceId || !itemType || !itemId) {
return res.status(400).json({ error: 'sourceId, itemType, and itemId are required' });
}
hiddenItems.show(sourceId, itemType, itemId);
res.json({ success: true });
} catch (err) {
console.error('Error showing item:', err);
res.status(500).json({ error: 'Failed to show item' });
}
});
// Check if item is hidden
router.get('/hidden/check', (req, res) => {
try {
const { sourceId, itemType, itemId } = req.query;
if (!sourceId || !itemType || !itemId) {
return res.status(400).json({ error: 'sourceId, itemType, and itemId are required' });
}
const isHidden = hiddenItems.isHidden(parseInt(sourceId), itemType, itemId);
res.json({ hidden: isHidden });
} catch (err) {
console.error('Error checking hidden status:', err);
res.status(500).json({ error: 'Failed to check hidden status' });
}
});
// Bulk hide channels and groups
router.post('/hide/bulk', (req, res) => {
try {
const { items } = req.body;
if (!items || !Array.isArray(items) || items.length === 0) {
return res.status(400).json({ error: 'items array is required' });
}
hiddenItems.bulkHide(items);
res.json({ success: true, count: items.length });
} catch (err) {
console.error('Error bulk hiding items:', err);
res.status(500).json({ error: 'Failed to bulk hide items' });
}
});
// Bulk show channels and groups
router.post('/show/bulk', (req, res) => {
try {
const { items } = req.body;
if (!items || !Array.isArray(items) || items.length === 0) {
return res.status(400).json({ error: 'items array is required' });
}
hiddenItems.bulkShow(items);
res.json({ success: true, count: items.length });
} catch (err) {
console.error('Error bulk showing items:', err);
res.status(500).json({ error: 'Failed to bulk show items' });
}
});
module.exports = router;
+61
View File
@@ -0,0 +1,61 @@
const express = require('express');
const router = express.Router();
const { favorites } = require('../db');
// Get all favorites
router.get('/', (req, res) => {
try {
const { sourceId, itemType } = req.query;
const items = favorites.getAll(sourceId, itemType);
res.json(items);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Add favorite
router.post('/', (req, res) => {
try {
const { sourceId, itemId, itemType = 'channel' } = req.body;
if (!sourceId || !itemId) {
return res.status(400).json({ error: 'Source ID and Item ID are required' });
}
favorites.add(sourceId, itemId, itemType);
res.json({ success: true });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Remove favorite
router.delete('/', (req, res) => {
try {
const { sourceId, itemId, itemType = 'channel' } = req.body;
if (!sourceId || !itemId) {
return res.status(400).json({ error: 'Source ID and Item ID are required' });
}
favorites.remove(sourceId, itemId, itemType);
res.json({ success: true });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// Check if item is favorited
router.get('/check', (req, res) => {
try {
const { sourceId, itemId, itemType = 'channel' } = req.query;
if (!sourceId || !itemId) {
return res.status(400).json({ error: 'Source ID and Item ID are required' });
}
const isFav = favorites.isFavorite(sourceId, itemId, itemType);
res.json({ isFavorite: isFav });
} catch (err) {
res.status(500).json({ error: err.message });
}
});
module.exports = router;
+287
View File
@@ -0,0 +1,287 @@
const express = require('express');
const router = express.Router();
const { sources } = require('../db');
const xtreamApi = require('../services/xtreamApi');
const m3uParser = require('../services/m3uParser');
const epgParser = require('../services/epgParser');
/**
* Proxy Xtream API calls
* GET /api/proxy/xtream/:sourceId/:action
*/
router.get('/xtream/:sourceId/:action', async (req, res) => {
try {
const source = sources.getById(req.params.sourceId);
if (!source || source.type !== 'xtream') {
return res.status(404).json({ error: 'Xtream source not found' });
}
const api = xtreamApi.createFromSource(source);
const { action } = req.params;
const { category_id, stream_id, vod_id, series_id, limit } = req.query;
let data;
switch (action) {
case 'auth':
data = await api.authenticate();
break;
case 'live_categories':
data = await api.getLiveCategories();
break;
case 'live_streams':
data = await api.getLiveStreams(category_id);
break;
case 'vod_categories':
data = await api.getVodCategories();
break;
case 'vod_streams':
data = await api.getVodStreams(category_id);
break;
case 'vod_info':
data = await api.getVodInfo(vod_id);
break;
case 'series_categories':
data = await api.getSeriesCategories();
break;
case 'series':
data = await api.getSeries(category_id);
break;
case 'series_info':
data = await api.getSeriesInfo(series_id);
break;
case 'short_epg':
data = await api.getShortEpg(stream_id, limit);
break;
default:
return res.status(400).json({ error: 'Unknown action' });
}
res.json(data);
} catch (err) {
console.error('Xtream proxy error:', err);
res.status(500).json({ error: err.message });
}
});
/**
* Get Xtream stream URL
* GET /api/proxy/xtream/:sourceId/stream/:streamId
*/
router.get('/xtream/:sourceId/stream/:streamId/:type?', (req, res) => {
try {
const source = sources.getById(req.params.sourceId);
if (!source || source.type !== 'xtream') {
return res.status(404).json({ error: 'Xtream source not found' });
}
const api = xtreamApi.createFromSource(source);
const { streamId, type = 'live' } = req.params;
const { container = 'm3u8' } = req.query;
const url = api.buildStreamUrl(streamId, type, container);
res.json({ url });
} catch (err) {
console.error('Stream URL error:', err);
res.status(500).json({ error: err.message });
}
});
/**
* Fetch and parse M3U playlist
* GET /api/proxy/m3u/:sourceId
*/
router.get('/m3u/:sourceId', async (req, res) => {
try {
const source = sources.getById(req.params.sourceId);
if (!source || source.type !== 'm3u') {
return res.status(404).json({ error: 'M3U source not found' });
}
const data = await m3uParser.fetchAndParse(source.url);
res.json(data);
} catch (err) {
console.error('M3U proxy error:', err);
res.status(500).json({ error: err.message });
}
});
/**
* EPG cache - in-memory for performance
* Structure: { [sourceId]: { data, fetchedAt } }
*/
const epgMemoryCache = {};
/**
* Fetch and parse EPG (with caching)
* GET /api/proxy/epg/:sourceId
* Query params:
* - refresh=1 Force refresh, bypass cache
* - maxAge=N Max cache age in hours (default 24)
*/
router.get('/epg/:sourceId', async (req, res) => {
try {
const sourceId = req.params.sourceId;
const source = sources.getById(sourceId);
if (!source || (source.type !== 'epg' && source.type !== 'xtream')) {
return res.status(404).json({ error: 'Valid EPG source not found' });
}
const forceRefresh = req.query.refresh === '1';
const maxAgeHours = parseInt(req.query.maxAge) || 24;
const maxAgeMs = maxAgeHours * 60 * 60 * 1000;
// Check cache (unless force refresh)
if (!forceRefresh && epgMemoryCache[sourceId]) {
const cached = epgMemoryCache[sourceId];
const age = Date.now() - cached.fetchedAt;
if (age < maxAgeMs) {
return res.json(cached.data);
}
}
// Fetch fresh data
let url = source.url;
if (source.type === 'xtream') {
const api = xtreamApi.createFromSource(source);
url = api.getXmltvUrl();
}
const data = await epgParser.fetchAndParse(url);
// Store in cache
epgMemoryCache[sourceId] = {
data,
fetchedAt: Date.now()
};
res.json(data);
} catch (err) {
console.error('EPG proxy error:', err);
res.status(500).json({ error: err.message });
}
});
/**
* Clear EPG cache for a source
* DELETE /api/proxy/epg/:sourceId/cache
*/
router.delete('/epg/:sourceId/cache', (req, res) => {
const sourceId = req.params.sourceId;
delete epgMemoryCache[sourceId];
res.json({ success: true });
});
/**
* Get EPG for specific channels
* POST /api/proxy/epg/:sourceId/channels
*/
router.post('/epg/:sourceId/channels', async (req, res) => {
try {
const source = sources.getById(req.params.sourceId);
if (!source || source.type !== 'epg') {
return res.status(404).json({ error: 'EPG source not found' });
}
const { channelIds } = req.body;
if (!channelIds || !Array.isArray(channelIds)) {
return res.status(400).json({ error: 'channelIds array required' });
}
const data = await epgParser.fetchAndParse(source.url);
// Filter programmes for requested channels
const result = {};
for (const channelId of channelIds) {
result[channelId] = epgParser.getCurrentAndUpcoming(data.programmes, channelId);
}
res.json(result);
} catch (err) {
console.error('EPG channels error:', err);
res.status(500).json({ error: err.message });
}
});
/**
* Proxy stream for playback
* This handles CORS for streams that don't allow cross-origin
*/
router.get('/stream', async (req, res) => {
try {
let { url } = req.query;
if (!url) {
return res.status(400).json({ error: 'URL required' });
}
// Forward some headers to be more "transparent" back to the origin
const isPluto = url.includes('pluto.tv');
const headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
'Accept': '*/*',
'Accept-Language': 'en-US,en;q=0.9',
// Using https and matching the origin of the request
'Origin': isPluto ? 'https://pluto.tv' : new URL(url).origin,
'Referer': isPluto ? 'https://pluto.tv/' : new URL(url).origin + '/'
};
const response = await fetch(url, { headers });
if (!response.ok) {
console.error(`Upstream error for ${url}: ${response.status} ${response.statusText}`);
return res.status(response.status).send(`Failed to fetch stream: ${response.statusText}`);
}
const contentType = response.headers.get('content-type') || '';
res.set('Access-Control-Allow-Origin', '*');
// Check if it's an HLS manifest
const isHls = contentType.includes('mpegurl') || contentType.includes('application/x-mpegURL') || url.toLowerCase().includes('.m3u8');
if (isHls) {
let manifest = await response.text();
// Rewrite URLs inside manifest
if (manifest.trim().startsWith('#EXTM3U')) {
res.set('Content-Type', 'application/vnd.apple.mpegurl');
const urlObj = new URL(url);
const baseUrl = urlObj.origin + urlObj.pathname.substring(0, urlObj.pathname.lastIndexOf('/') + 1);
manifest = manifest.split('\n').map(line => {
const trimmed = line.trim();
if (trimmed === '' || trimmed.startsWith('#')) {
if (trimmed.includes('URI="')) {
return line.replace(/URI="([^"]+)"/g, (match, p1) => {
try {
const absoluteUrl = new URL(p1, baseUrl).href;
return `URI="${req.protocol}://${req.get('host')}${req.baseUrl}/stream?url=${encodeURIComponent(absoluteUrl)}"`;
} catch (e) { return match; }
});
}
return line;
}
try {
const absoluteUrl = new URL(trimmed, baseUrl).href;
return `${req.protocol}://${req.get('host')}${req.baseUrl}/stream?url=${encodeURIComponent(absoluteUrl)}`;
} catch (e) { return line; }
}).join('\n');
return res.send(manifest);
}
}
// Binary content (segments)
res.set('Content-Type', contentType);
const buffer = await response.arrayBuffer();
return res.send(Buffer.from(buffer));
} catch (err) {
console.error('Stream proxy error:', err);
if (!res.headersSent) {
res.status(500).json({ error: err.message });
}
}
});
module.exports = router;
+147
View File
@@ -0,0 +1,147 @@
const express = require('express');
const router = express.Router();
const { sources } = require('../db');
const xtreamApi = require('../services/xtreamApi');
// Get all sources
router.get('/', (req, res) => {
try {
const allSources = sources.getAll();
// Don't expose passwords in list view
const sanitized = allSources.map(s => ({
...s,
password: s.password ? '••••••••' : null
}));
res.json(sanitized);
} catch (err) {
console.error('Error getting sources:', err);
res.status(500).json({ error: 'Failed to get sources' });
}
});
// Get sources by type
router.get('/type/:type', (req, res) => {
try {
const typeSources = sources.getByType(req.params.type);
res.json(typeSources);
} catch (err) {
console.error('Error getting sources by type:', err);
res.status(500).json({ error: 'Failed to get sources' });
}
});
// Get single source
router.get('/:id', (req, res) => {
try {
const source = sources.getById(req.params.id);
if (!source) {
return res.status(404).json({ error: 'Source not found' });
}
res.json(source);
} catch (err) {
console.error('Error getting source:', err);
res.status(500).json({ error: 'Failed to get source' });
}
});
// Create source
router.post('/', (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' });
}
const source = sources.create({ type, name, url, username, password });
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', (req, res) => {
try {
const existing = sources.getById(req.params.id);
if (!existing) {
return res.status(404).json({ error: 'Source not found' });
}
const { name, url, username, password } = req.body;
const updated = sources.update(req.params.id, {
name: name || existing.name,
url: url || existing.url,
username: username !== undefined ? username : existing.username,
password: password !== undefined ? password : existing.password
});
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', (req, res) => {
try {
const existing = sources.getById(req.params.id);
if (!existing) {
return res.status(404).json({ error: 'Source not found' });
}
sources.delete(req.params.id);
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', (req, res) => {
try {
const updated = sources.toggleEnabled(req.params.id);
if (!updated) {
return res.status(404).json({ error: 'Source not found' });
}
res.json(updated);
} catch (err) {
console.error('Error toggling source:', err);
res.status(500).json({ error: 'Failed to toggle source' });
}
});
// Test source connection
router.post('/:id/test', async (req, res) => {
try {
const source = sources.getById(req.params.id);
if (!source) {
return res.status(404).json({ error: 'Source not found' });
}
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('<tv') || text.includes('<?xml');
res.json({ success: isValid, message: isValid ? 'Valid EPG XML' : 'Invalid EPG format' });
}
} catch (err) {
console.error('Error testing source:', err);
res.json({ success: false, error: err.message });
}
});
module.exports = router;
+177
View File
@@ -0,0 +1,177 @@
/**
* EPG (XMLTV) Parser
* Parses XMLTV format EPG data and extracts channel/programme information
*/
const { parseString } = require('xml2js');
const { promisify } = require('util');
const parseXml = promisify(parseString);
/**
* Parse XMLTV date format (YYYYMMDDHHmmss +ZZZZ)
* @param {string} dateStr - XMLTV format date string
* @returns {Date}
*/
function parseXmltvDate(dateStr) {
if (!dateStr) return null;
// Format: 20231225120000 +0000
const match = dateStr.match(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\s*([+-]\d{4})?$/);
if (!match) {
// Try ISO format fallback
return new Date(dateStr);
}
const [, year, month, day, hour, minute, second, tz] = match;
let isoStr = `${year}-${month}-${day}T${hour}:${minute}:${second}`;
if (tz) {
const tzHours = tz.substring(0, 3);
const tzMins = tz.substring(3);
isoStr += `${tzHours}:${tzMins}`;
} else {
isoStr += 'Z';
}
return new Date(isoStr);
}
/**
* Parse XMLTV content
* @param {string} content - Raw XMLTV content
* @returns {Promise<{ channels: Array, programmes: Array }>}
*/
async function parse(content) {
const result = await parseXml(content, {
explicitArray: false,
mergeAttrs: true
});
if (!result.tv) {
throw new Error('Invalid XMLTV format: missing <tv> root element');
}
const tv = result.tv;
const channels = [];
const programmes = [];
// Parse channels
const channelList = Array.isArray(tv.channel) ? tv.channel : (tv.channel ? [tv.channel] : []);
for (const ch of channelList) {
const channel = {
id: ch.id,
name: extractText(ch['display-name']),
icon: ch.icon ? (ch.icon.src || ch.icon) : null,
url: extractText(ch.url)
};
channels.push(channel);
}
// Parse programmes
const programmeList = Array.isArray(tv.programme) ? tv.programme : (tv.programme ? [tv.programme] : []);
for (const prog of programmeList) {
const programme = {
channelId: prog.channel,
start: parseXmltvDate(prog.start),
stop: parseXmltvDate(prog.stop),
title: extractText(prog.title),
subtitle: extractText(prog['sub-title']),
description: extractText(prog.desc),
category: extractCategories(prog.category),
icon: prog.icon ? (prog.icon.src || prog.icon) : null,
date: extractText(prog.date),
episodeNum: extractEpisodeNum(prog['episode-num'])
};
programmes.push(programme);
}
return { channels, programmes };
}
/**
* Extract text from XMLTV element (handles both string and object formats)
*/
function extractText(element) {
if (!element) return null;
if (typeof element === 'string') return element;
if (Array.isArray(element)) {
// Prefer English or first item
const en = element.find(e => e.lang === 'en' || !e.lang);
return extractText(en || element[0]);
}
if (element._) return element._;
if (element['#text']) return element['#text'];
return String(element);
}
/**
* Extract categories array
*/
function extractCategories(category) {
if (!category) return [];
const cats = Array.isArray(category) ? category : [category];
return cats.map(c => extractText(c)).filter(Boolean);
}
/**
* Extract episode number
*/
function extractEpisodeNum(episodeNum) {
if (!episodeNum) return null;
const nums = Array.isArray(episodeNum) ? episodeNum : [episodeNum];
for (const num of nums) {
if (typeof num === 'string') return num;
if (num._ || num['#text']) {
return num._ || num['#text'];
}
}
return null;
}
/**
* Get programmes for a specific channel
*/
function getProgrammesForChannel(programmes, channelId) {
return programmes.filter(p => p.channelId === channelId);
}
/**
* Get current and upcoming programmes for a channel
*/
function getCurrentAndUpcoming(programmes, channelId, count = 5) {
const now = new Date();
const channelProgrammes = getProgrammesForChannel(programmes, channelId);
// Sort by start time
channelProgrammes.sort((a, b) => a.start - b.start);
// Find current and upcoming
const current = channelProgrammes.find(p => p.start <= now && p.stop > now);
const upcoming = channelProgrammes
.filter(p => p.start > now)
.slice(0, count);
return { current, upcoming };
}
/**
* Fetch and parse XMLTV from URL
*/
async function fetchAndParse(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Failed to fetch EPG: ${response.status} ${response.statusText}`);
}
const content = await response.text();
return parse(content);
}
module.exports = {
parse,
parseXmltvDate,
fetchAndParse,
getProgrammesForChannel,
getCurrentAndUpcoming
};
+155
View File
@@ -0,0 +1,155 @@
/**
* M3U Playlist Parser
* Parses EXTM3U format playlists and extracts channel information
*/
/**
* Generate a simple stable ID from name and group
* @param {string} name - Channel name
* @param {string} group - Group title
* @returns {string} Stable ID
*/
function generateStableId(name, group) {
const str = `${name || 'unknown'}:${group || 'unknown'}`;
// Simple hash function
let hash = 0;
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash; // Convert to 32bit integer
}
return `m3u_${Math.abs(hash).toString(36)}`;
}
/**
* Parse M3U playlist content
* @param {string} content - Raw M3U playlist content
* @returns {{ channels: Array, groups: Array }}
*/
function parse(content) {
const lines = content.split('\n').map(line => line.trim());
const channels = [];
const groupsSet = new Set();
// Verify it's a valid M3U file
if (!lines[0] || !lines[0].startsWith('#EXTM3U')) {
throw new Error('Invalid M3U format: missing #EXTM3U header');
}
let currentInfo = null;
let currentGroup = null;
for (let i = 1; i < lines.length; i++) {
const line = lines[i];
if (line.startsWith('#EXTINF:')) {
// Parse EXTINF line
currentInfo = parseExtinf(line);
if (currentInfo.groupTitle) {
groupsSet.add(currentInfo.groupTitle);
currentGroup = currentInfo.groupTitle;
}
} else if (line.startsWith('#EXTGRP:')) {
// Parse EXTGRP line (alternative group specification)
currentGroup = line.substring(8).trim();
groupsSet.add(currentGroup);
if (currentInfo) {
currentInfo.groupTitle = currentGroup;
}
} else if (line && !line.startsWith('#')) {
// This is a stream URL
if (currentInfo) {
const groupTitle = currentInfo.groupTitle || currentGroup || 'Uncategorized';
// Generate a stable ID: use tvgId if present, otherwise hash name+group
const stableId = currentInfo.tvgId || generateStableId(currentInfo.name, groupTitle);
channels.push({
...currentInfo,
id: stableId,
url: line,
groupTitle: groupTitle
});
currentInfo = null;
}
}
}
// Convert groups to array of objects
const groups = Array.from(groupsSet).map((name, index) => ({
id: `group_${index}`,
name,
channelCount: channels.filter(c => c.groupTitle === name).length
}));
return { channels, groups };
}
/**
* Parse EXTINF line and extract attributes
* @param {string} line - EXTINF line
* @returns {Object} Parsed channel info
*/
function parseExtinf(line) {
const info = {
duration: -1,
tvgId: null,
tvgName: null,
tvgLogo: null,
groupTitle: null,
name: null
};
// Extract duration and rest
const match = line.match(/#EXTINF:(-?\d+\.?\d*)\s*(.*)/);
if (!match) return info;
info.duration = parseFloat(match[1]);
const rest = match[2];
// Extract attributes using regex
const attrPatterns = {
tvgId: /tvg-id="([^"]*)"/i,
tvgName: /tvg-name="([^"]*)"/i,
tvgLogo: /tvg-logo="([^"]*)"/i,
groupTitle: /group-title="([^"]*)"/i
};
for (const [key, pattern] of Object.entries(attrPatterns)) {
const attrMatch = rest.match(pattern);
if (attrMatch) {
info[key] = attrMatch[1];
}
}
// Extract channel name (after the comma)
const commaIndex = rest.lastIndexOf(',');
if (commaIndex !== -1) {
info.name = rest.substring(commaIndex + 1).trim();
} else {
// Fallback: use tvg-name or the whole rest
info.name = info.tvgName || rest.trim();
}
// Generate ID if not present
if (!info.tvgId) {
info.tvgId = info.name ? info.name.toLowerCase().replace(/\s+/g, '_') : `channel_${Date.now()}`;
}
return info;
}
/**
* Fetch and parse M3U from URL
* @param {string} url - M3U playlist URL
* @returns {Promise<{ channels: Array, groups: Array }>}
*/
async function fetchAndParse(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Failed to fetch M3U: ${response.status} ${response.statusText}`);
}
const content = await response.text();
return parse(content);
}
module.exports = { parse, parseExtinf, fetchAndParse };
+161
View File
@@ -0,0 +1,161 @@
/**
* Xtream Codes API v2 Client
* Handles authentication and API calls to Xtream servers
*/
class XtreamApi {
constructor(baseUrl, username, password) {
// Clean up base URL
this.baseUrl = baseUrl.replace(/\/+$/, '');
this.username = username;
this.password = password;
}
/**
* Build API URL with authentication
*/
buildApiUrl(action, params = {}) {
const url = new URL(`${this.baseUrl}/player_api.php`);
url.searchParams.set('username', this.username);
url.searchParams.set('password', this.password);
if (action) {
url.searchParams.set('action', action);
}
for (const [key, value] of Object.entries(params)) {
if (value !== undefined && value !== null) {
url.searchParams.set(key, value);
}
}
return url.toString();
}
/**
* Make API request
*/
async request(action, params = {}) {
const url = this.buildApiUrl(action, params);
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Xtream API error: ${response.status} ${response.statusText}`);
}
return response.json();
}
/**
* Authenticate and get server/user info
*/
async authenticate() {
const data = await this.request(null);
if (!data.user_info) {
throw new Error('Invalid credentials or server response');
}
return data;
}
/**
* Get live channel categories
*/
async getLiveCategories() {
return this.request('get_live_categories');
}
/**
* Get live streams, optionally filtered by category
*/
async getLiveStreams(categoryId = null) {
return this.request('get_live_streams', { category_id: categoryId });
}
/**
* Get VOD categories
*/
async getVodCategories() {
return this.request('get_vod_categories');
}
/**
* Get VOD streams, optionally filtered by category
*/
async getVodStreams(categoryId = null) {
return this.request('get_vod_streams', { category_id: categoryId });
}
/**
* Get VOD info
*/
async getVodInfo(vodId) {
return this.request('get_vod_info', { vod_id: vodId });
}
/**
* Get series categories
*/
async getSeriesCategories() {
return this.request('get_series_categories');
}
/**
* Get series, optionally filtered by category
*/
async getSeries(categoryId = null) {
return this.request('get_series', { category_id: categoryId });
}
/**
* Get series info
*/
async getSeriesInfo(seriesId) {
return this.request('get_series_info', { series_id: seriesId });
}
/**
* Get short EPG for a stream
*/
async getShortEpg(streamId, limit = 10) {
return this.request('get_short_epg', { stream_id: streamId, limit });
}
/**
* Get full EPG for a stream
*/
async getSimpleDateTable(streamId) {
return this.request('get_simple_data_table', { stream_id: streamId });
}
/**
* Build stream URL for playback
*/
buildStreamUrl(streamId, type = 'live', container = 'ts') {
const typeMap = {
live: 'live',
vod: 'movie',
series: 'series'
};
const streamType = typeMap[type] || 'live';
return `${this.baseUrl}/${streamType}/${this.username}/${this.password}/${streamId}.${container}`;
}
/**
* Get XMLTV EPG URL
*/
getXmltvUrl() {
return `${this.baseUrl}/xmltv.php?username=${this.username}&password=${this.password}`;
}
}
/**
* Factory function to create API instance from source
*/
function createFromSource(source) {
return new XtreamApi(source.url, source.username, source.password);
}
/**
* Static authenticate for testing
*/
async function authenticate(url, username, password) {
const api = new XtreamApi(url, username, password);
return api.authenticate();
}
module.exports = { XtreamApi, createFromSource, authenticate };