aif1 / addonf1.js
gre89's picture
Update addonf1.js
6582794 verified
Raw History Blame Contribute Delete
31.9 kB
const { addonBuilder } = require("stremio-addon-sdk");
const express = require("express");
const cors = require('cors');
const Parser = require('rss-parser');
const axios = require('axios');
const { createCanvas, loadImage } = require('canvas');
const fs = require('fs').promises;
const path = require('path');
const crypto = require('crypto');
const dotenv = require('dotenv');
const cloudinary = require('cloudinary').v2;
const { Readable } = require('stream');
// Load environment variables
dotenv.config();
const ADDON_ID = process.env.ADDON_ID || "org.stremio.f1.easynews";
const ADDON_VERSION = process.env.ADDON_VERSION || "1.0.0";
const EASYNEWS_USERNAME = process.env.EASYNEWS_USERNAME;
const EASYNEWS_PASSWORD = process.env.EASYNEWS_PASSWORD;
// Simple logging functions
const logger = {
info: (message, data = {}) => {
if (Object.keys(data).length > 0) {
console.log(`[INFO] ${message}`, data);
} else {
console.log(`[INFO] ${message}`);
}
},
error: (message, data = {}) => {
if (Object.keys(data).length > 0) {
console.error(`[ERROR] ${message}`, data);
} else {
console.error(`[ERROR] ${message}`);
}
},
warn: (message, data = {}) => {
if (Object.keys(data).length > 0) {
console.warn(`[WARN] ${message}`, data);
} else {
console.warn(`[WARN] ${message}`);
}
}
};
// Configure Cloudinary
cloudinary.config({
cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_API_SECRET
});
// IMPROVED MANIFEST CONFIGURATION
const builder = new addonBuilder({
id: ADDON_ID,
version: ADDON_VERSION,
name: "Formula 1 Events with Easynews",
description: "Watch Formula 1 2025 races via Easynews",
// Define resources with proper ID prefixes for Android compatibility
resources: [
"catalog",
{
name: "meta",
types: ["sport"],
idPrefixes: ["f1_"]
},
{
name: "stream",
types: ["sport"],
idPrefixes: ["f1_"]
}
],
types: ["sport"],
catalogs: [
{
type: "sport",
id: "f1_events_catalog",
name: "Formula 1 Events (2025 Season)",
// Add extra properties for better user experience
extra: [
{
name: "search",
isRequired: false
},
{
name: "skip",
isRequired: false
}
]
}
],
// Add logo and background for better branding in Stremio
logo: process.env.LOGO_URL || "https://i.imgur.com/R6G3ged.png", // F1 logo
background: process.env.BACKGROUND_URL || "https://i.imgur.com/ijyVBvH.jpg", // F1 race background
contactEmail: process.env.CONTACT_EMAIL || "youremail@example.com" // Replace with your contact email
});
function formatDate(date) {
if (!(date instanceof Date) || isNaN(date)) {
return "Unknown date";
}
return date.toLocaleDateString('en-GB', {
day: '2-digit',
month: '2-digit',
year: 'numeric'
});
}
async function fetchEasynewsFeed() {
try {
const auth = Buffer.from(`${EASYNEWS_USERNAME}:${EASYNEWS_PASSWORD}`).toString('base64');
const response = await axios.get('https://members.easynews.com/1.0/global5/search.html', {
params: {
submit: 'Search',
gps: '',
sbj: '',
from: '',
ns: '',
fil: 'DARKSPORT formula 1 2025',
fex: '',
vc: '',
ac: '',
'fty[]': 'VIDEO',
s1: 'dtime',
s1d: '-',
s2: 'nsubject',
s2d: '+',
s3: 'nrfile',
s3d: '+',
pby: 1000,
pno: 1,
sS: 5,
u: 1,
svL: '',
d1: '',
d1t: '',
d2: '',
d2t: '',
b1: '',
b1t: '',
b2: '',
b2t: '',
px1: '',
px1t: '',
px2: '',
px2t: '',
fps1: '',
fps1t: '',
fps2: '',
fps2t: '',
bps1: '',
bps1t: '',
bps2: '',
bps2t: '',
hz1: '',
hz1t: '',
hz2: '',
hz2t: '',
rn1: '',
rn1t: '',
rn2: '',
rn2t: '',
fly: 1
},
headers: {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:133.0) Gecko/20100101 Firefox/133.0',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'en-GB,en;q=0.5',
'Accept-Encoding': 'gzip, deflate, br, zstd',
'Authorization': `Basic ${auth}`,
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1',
'Sec-Fetch-Dest': 'document',
'Sec-Fetch-Mode': 'navigate',
'Sec-Fetch-Site': 'none',
'Sec-Fetch-User': '?1',
'Priority': 'u=4',
'Pragma': 'no-cache',
'Cache-Control': 'no-cache'
}
});
if (!response.data) {
throw new Error('Empty response from Easynews');
}
const parser = new Parser();
const feed = await parser.parseString(response.data);
if (!feed || !feed.items) {
throw new Error('Invalid feed structure');
}
const items = feed.items.map(item => {
const qualityMatch = item.title.match(/(720p|1080p|2160p|4K)/i);
const quality = qualityMatch ? qualityMatch[0] : 'Unknown';
const sizeMatch = item.title.match(/(\d+(\.\d+)?\s*GB)/i);
const size = sizeMatch ? sizeMatch[0] : 'Unknown size';
return {
title: item.title,
link: item.enclosure?.url || '',
pubDate: item.pubDate,
quality: quality,
size: size
};
});
return items.filter(item => !item.title.toLowerCase().includes('sample'));
} catch (error) {
logger.error('Error fetching Easynews feed', {
error: error.message,
status: error.response?.status,
statusText: error.response?.statusText
});
throw error;
}
}
async function validateEasynewsCredentials() {
try {
const auth = Buffer.from(`${EASYNEWS_USERNAME}:${EASYNEWS_PASSWORD}`).toString('base64');
const response = await axios.get('https://members.easynews.com/1.0/global5/search.html', {
params: {
submit: 'Search',
gps: '',
fil: 'DARKSPORT formula 1',
'fty[]': 'VIDEO',
pby: 1
},
headers: {
'Authorization': `Basic ${auth}`,
'User-Agent': 'Mozilla/5.0'
}
});
return response.status === 200;
} catch (error) {
logger.error('Failed to validate Easynews credentials', {
error: error.message,
status: error.response?.status
});
return false;
}
}
// FILENAME PARSER - Extracts information from filenames
function parseEventInfo(filename) {
let grandPrix = "Formula 1";
let sessionType = "Race";
let isRace = true;
let additionalInfo = "";
// Convert to lowercase for easier matching
const lower = filename.toLowerCase();
// Extract Grand Prix
if (lower.includes("grand prix")) {
const beforeGP = filename.split(/grand prix/i)[0].trim();
grandPrix = beforeGP.split(/\s+/).map(word =>
word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()
).join(' ');
if (grandPrix.endsWith("The")) {
grandPrix = "The " + grandPrix.slice(0, -4);
}
} else if (lower.includes("winter testing")) {
grandPrix = "Bahrain Winter Testing";
isRace = false;
} else {
// Try to extract location name if "Grand Prix" not found
const locations = [
"Australian", "Chinese", "Japanese", "Bahrain", "Saudi Arabian",
"Miami", "Emilia Romagna", "Monaco", "Spanish", "Canadian",
"Austrian", "British", "Belgian", "Hungarian", "Dutch",
"Italian", "Azerbaijan", "Singapore", "United States",
"Mexico City", "Sao Paulo", "Las Vegas", "Qatar", "Abu Dhabi"
];
for (const location of locations) {
if (lower.includes(location.toLowerCase())) {
grandPrix = location;
// Add "Grand Prix" if not already a special event
if (!lower.includes("testing") && !lower.includes("show")) {
grandPrix += " Grand Prix";
}
break;
}
}
}
// Extract session type
if (lower.includes("qualifying")) {
sessionType = lower.includes("sprint qualifying") ? "Sprint Qualifying" : "Qualifying";
isRace = false;
} else if (lower.includes("practice")) {
let practiceNumber = "";
if (lower.includes("practice one") || lower.includes("practice 1")) {
practiceNumber = "1";
} else if (lower.includes("practice two") || lower.includes("practice 2")) {
practiceNumber = "2";
} else if (lower.includes("practice three") || lower.includes("practice 3")) {
practiceNumber = "3";
}
sessionType = practiceNumber ? `Practice ${practiceNumber}` : "Practice";
isRace = false;
} else if (lower.includes("sprint race") || (lower.includes("sprint") && !lower.includes("qualifying"))) {
sessionType = "Sprint Race";
isRace = true;
} else if (lower.includes("notebook")) {
sessionType = "Ted's Notebook";
isRace = false;
if (lower.includes("qualifying notebook")) {
additionalInfo = "Qualifying Analysis";
}
} else if (lower.includes("press conference")) {
if (lower.includes("drivers")) {
sessionType = "Drivers Press Conference";
} else if (lower.includes("team") || lower.includes("principal")) {
sessionType = "Team Principals Press Conference";
} else {
sessionType = "Press Conference";
}
isRace = false;
} else if (lower.includes("f1 show")) {
sessionType = "The F1 Show";
isRace = false;
if (lower.includes("season preview")) {
additionalInfo = "Season Preview";
} else if (lower.includes("lights out")) {
additionalInfo = "Lights Out";
}
} else if (lower.includes("testing")) {
if (lower.includes("session one")) {
sessionType = "Testing Session 1";
} else if (lower.includes("session two")) {
sessionType = "Testing Session 2";
} else if (lower.includes("wrap")) {
sessionType = "Testing Wrap";
} else {
sessionType = "Testing";
}
isRace = false;
}
return {
grandPrix,
sessionType,
isRace,
additionalInfo
};
}
// Function to upload image buffer to Cloudinary
async function uploadImageToCloudinary(imageBuffer, title) {
try {
// Create a hash of the title for a unique filename
const hash = crypto.createHash('md5').update(title).digest('hex');
// Upload the image to Cloudinary
return new Promise((resolve, reject) => {
const uploadStream = cloudinary.uploader.upload_stream(
{
folder: 'f1-stremio-posters',
public_id: hash,
overwrite: true,
resource_type: 'image',
quality: 90, // Increase quality to 90%
fetch_format: 'auto', // Let Cloudinary optimize the format
width: 500, // Set width to maintain size
height: 750, // Set height to maintain aspect ratio
crop: 'limit', // Limit dimension but keep aspect ratio
flags: 'lossy' // Use lossy compression for better quality/size ratio
},
(error, result) => {
if (error) {
console.error('Cloudinary upload error:', error);
reject(error);
} else {
resolve(result.secure_url);
}
}
);
// Convert buffer to stream and pipe to cloudinary
const bufferStream = new Readable();
bufferStream.push(imageBuffer);
bufferStream.push(null);
bufferStream.pipe(uploadStream);
});
} catch (error) {
logger.error('Error uploading image to Cloudinary', { error: error.message });
return null;
}
}
// POSTER GENERATOR
async function generatePoster(title, date, quality, size) {
// Extract the actual filename from the title (removes the metadata in brackets)
const filenameMatch = title.match(/\(([^)]+)\s+AutoUnRAR\)/);
let cleanFilename = filenameMatch ? filenameMatch[1] : title;
// Further clean up the title to extract just the core info
if (cleanFilename.includes('DARKSPORT')) {
const darksportMatch = cleanFilename.match(/Formula1\.2025\.(.+?)\.(?:1080p|720p|2160p|4K)/i);
if (darksportMatch) {
cleanFilename = darksportMatch[1].replace(/\./g, ' ');
}
}
// Setup canvas
const width = 500;
const height = 750;
const canvas = createCanvas(width, height);
const ctx = canvas.getContext('2d');
// Create a dynamic gradient background
const gradient = ctx.createLinearGradient(0, 0, 0, height);
gradient.addColorStop(0, '#E10600'); // F1 red
gradient.addColorStop(0.6, '#960300'); // Darker red
gradient.addColorStop(1, '#15151E'); // F1 dark blue
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, width, height);
// Parse event info from filename
const eventInfo = parseEventInfo(cleanFilename);
// Add a subtle texture overlay (racing circuit pattern)
addTextureOverlay(ctx, width, height);
// Set up text rendering with shadow for better readability
ctx.shadowColor = 'rgba(0, 0, 0, 0.5)';
ctx.shadowBlur = 5;
ctx.shadowOffsetX = 2;
ctx.shadowOffsetY = 2;
ctx.fillStyle = '#ffffff';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
// Draw F1 logo at the top
ctx.font = 'bold 48px Arial';
ctx.fillText('FORMULA 1', width / 2, 80);
// Draw "2025 CHAMPIONSHIP" subtitle
ctx.font = '24px Arial';
ctx.fillText('2025 CHAMPIONSHIP', width / 2, 115);
// Draw main event info
let yPos = 180;
// Draw Grand Prix name
ctx.font = 'bold 36px Arial';
ctx.fillText(eventInfo.grandPrix, width / 2, yPos);
yPos += 50;
// Draw divider line
ctx.strokeStyle = '#E10600';
ctx.lineWidth = 3;
ctx.beginPath();
ctx.moveTo(100, yPos);
ctx.lineTo(width - 100, yPos);
ctx.stroke();
yPos += 40;
// Draw session type with larger font
ctx.font = 'bold 42px Arial';
ctx.fillText(eventInfo.sessionType, width / 2, yPos);
yPos += 80;
// Add decorative elements
if (eventInfo.isRace) {
// Add checkered flag pattern on sides for race events
drawCheckeredFlag(ctx, 50, yPos - 40, 40, 80);
drawCheckeredFlag(ctx, width - 90, yPos - 40, 40, 80);
}
// Draw a decorative box for the quality and size
ctx.fillStyle = 'rgba(225, 6, 0, 0.7)';
const infoBoxY = yPos + 20;
ctx.fillRect(100, infoBoxY, width - 200, 60);
// Draw video quality and size in the box
ctx.fillStyle = '#ffffff';
ctx.font = 'bold 28px Arial';
ctx.fillText(`${quality} • ${size}`, width / 2, infoBoxY + 30);
yPos = infoBoxY + 100;
// Draw the date in a stylized box if available
if (date instanceof Date && !isNaN(date)) {
ctx.fillStyle = 'rgba(255, 255, 255, 0.15)';
ctx.fillRect(150, yPos, width - 300, 50);
ctx.fillStyle = '#ffffff';
ctx.font = '24px Arial';
ctx.fillText(formatDate(date), width / 2, yPos + 25);
}
// Add additional info based on event type
if (eventInfo.additionalInfo) {
yPos += 80;
ctx.font = '22px Arial';
ctx.fillText(eventInfo.additionalInfo, width / 2, yPos);
}
// Add F1 car silhouette at the bottom
drawF1CarSilhouette(ctx, width / 2 - 100, height - 150, 200);
// Add poster footer
ctx.fillStyle = '#ffffff';
ctx.font = '18px Arial';
ctx.fillText('FORMULA 1 • STREMIO ADDON', width / 2, height - 30);
try {
const buffer = canvas.toBuffer('image/png', { compressionLevel: 0 }); // Use no compression for quality
// Upload image to Cloudinary instead of saving locally
const cloudinaryUrl = await uploadImageToCloudinary(buffer, title);
if (!cloudinaryUrl) {
logger.error('Failed to get URL from Cloudinary upload', { title });
}
return cloudinaryUrl;
} catch (error) {
logger.error('Error generating and uploading poster', { title, error: error.message });
return null;
}
}
// Helper function to add texture overlay
function addTextureOverlay(ctx, width, height) {
ctx.globalAlpha = 0.1;
ctx.fillStyle = '#ffffff';
// Add random dots for a subtle texture
for (let i = 0; i < 50; i++) {
const x = Math.random() * width;
const y = Math.random() * height;
const size = Math.random() * 3 + 1;
ctx.beginPath();
ctx.arc(x, y, size, 0, Math.PI * 2);
ctx.fill();
}
// Add some curved lines resembling a race track
ctx.strokeStyle = '#ffffff';
ctx.lineWidth = 1;
// Draw a couple of curved track-like lines
ctx.beginPath();
ctx.moveTo(50, height - 200);
ctx.bezierCurveTo(width * 0.3, height - 300, width * 0.7, height - 250, width - 50, height - 220);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(70, height - 180);
ctx.bezierCurveTo(width * 0.3, height - 280, width * 0.7, height - 230, width - 70, height - 200);
ctx.stroke();
ctx.globalAlpha = 1.0;
}
// Helper function to draw checkered flag pattern
function drawCheckeredFlag(ctx, x, y, width, height) {
const squareSize = 10;
const numCols = Math.ceil(width / squareSize);
const numRows = Math.ceil(height / squareSize);
ctx.fillStyle = '#ffffff';
for (let row = 0; row < numRows; row++) {
for (let col = 0; col < numCols; col++) {
if ((row + col) % 2 === 0) {
ctx.fillRect(
x + col * squareSize,
y + row * squareSize,
squareSize,
squareSize
);
}
}
}
}
// Helper function to draw F1 car silhouette
function drawF1CarSilhouette(ctx, x, y, width) {
const height = width * 0.4;
ctx.globalAlpha = 0.2;
ctx.fillStyle = '#ffffff';
// Simple F1 car shape
ctx.beginPath();
// Front wing
ctx.moveTo(x, y + height * 0.5);
ctx.lineTo(x + width * 0.2, y + height * 0.5);
// Nose and cockpit
ctx.lineTo(x + width * 0.3, y + height * 0.3);
ctx.lineTo(x + width * 0.4, y + height * 0.1);
ctx.lineTo(x + width * 0.6, y + height * 0.1);
ctx.lineTo(x + width * 0.7, y + height * 0.3);
// Body and rear wing
ctx.lineTo(x + width * 0.8, y + height * 0.5);
ctx.lineTo(x + width, y + height * 0.5);
ctx.lineTo(x + width, y + height * 0.7);
ctx.lineTo(x + width * 0.8, y + height * 0.7);
// Bottom of the car
ctx.lineTo(x + width * 0.7, y + height * 0.7);
ctx.lineTo(x + width * 0.6, y + height * 0.9);
ctx.lineTo(x + width * 0.4, y + height * 0.9);
ctx.lineTo(x + width * 0.3, y + height * 0.7);
ctx.lineTo(x + width * 0.2, y + height * 0.7);
ctx.lineTo(x, y + height * 0.7);
ctx.closePath();
ctx.fill();
// Wheels
ctx.fillStyle = '#ffffff';
ctx.beginPath();
ctx.arc(x + width * 0.25, y + height * 0.7, height * 0.2, 0, Math.PI * 2);
ctx.fill();
ctx.beginPath();
ctx.arc(x + width * 0.75, y + height * 0.7, height * 0.2, 0, Math.PI * 2);
ctx.fill();
ctx.globalAlpha = 1.0;
}
// GENERATE CONSISTENT ID
function generateItemId(item) {
// Create a deterministic ID based on title and URL
const idBase = Buffer.from(item.title + (item.link || "")).toString('base64');
return `f1_${idBase.replace(/[+/=]/g, "")}`;
}
// META OBJECT CREATION
function createMetaObject(item, posterUrl) {
// Extract the actual filename from the title
const filenameMatch = item.title.match(/\(([^)]+)\s+AutoUnRAR\)/);
let cleanFilename = filenameMatch ? filenameMatch[1] : item.title;
// Further clean up the title
if (cleanFilename.includes('DARKSPORT')) {
const darksportMatch = cleanFilename.match(/Formula1\.2025\.(.+?)\.(?:1080p|720p|2160p|4K)/i);
if (darksportMatch) {
cleanFilename = darksportMatch[1].replace(/\./g, ' ');
}
}
// Parse event info from filename
const eventInfo = parseEventInfo(cleanFilename);
// Use the consistent ID generation function
const id = generateItemId(item);
// Format display name
const displayName = `F1 2025: ${eventInfo.grandPrix} - ${eventInfo.sessionType}`;
// Create description
const description = [
`Event: ${eventInfo.grandPrix}`,
`Session: ${eventInfo.sessionType}`,
eventInfo.additionalInfo ? `Info: ${eventInfo.additionalInfo}` : '',
`Date: ${formatDate(new Date(item.pubDate))}`,
`Quality: ${item.quality || 'Unknown'}`,
`Size: ${item.size || 'Unknown size'}`,
'',
'Formula 1 2025 Championship'
].filter(Boolean).join('\n');
return {
id: id,
type: "sport",
name: displayName,
poster: posterUrl || '',
background: posterUrl || '',
description: description,
releaseInfo: "2025",
posterShape: 'regular',
// Store streaming URL as a property
streamingUrl: item.link
};
}
// CATALOG HANDLER
const catalogHandler = async ({ type, id, extra }) => {
logger.info('Catalog requested', { type, id, extra });
if (type === "sport" && id === "f1_events_catalog") {
try {
// Always fetch fresh items
let items = await fetchEasynewsFeed();
// Log the number of items fetched
logger.info(`Fetched ${items.length} items from Easynews`);
// Handle search if provided
if (extra && extra.search) {
const searchTerm = extra.search.toLowerCase();
items = items.filter(item =>
item.title.toLowerCase().includes(searchTerm)
);
logger.info(`Search applied: "${searchTerm}" - ${items.length} results`);
}
// Handle skip for pagination
let skip = 0;
if (extra && extra.skip) {
skip = parseInt(extra.skip);
}
// Apply pagination (default 20 items per page to process faster)
const pageSize = 20;
const paginatedItems = items.slice(skip, skip + pageSize);
logger.info(`Processing ${paginatedItems.length} items for this page`);
// Generate metadata for all matching items
const metas = await Promise.all(
paginatedItems.map(async (item) => {
try {
const posterUrl = await generatePoster(
item.title,
new Date(item.pubDate),
item.quality,
item.size
);
if (!posterUrl) {
logger.warn(`Failed to generate poster for: ${item.title}`);
}
return createMetaObject(item, posterUrl);
} catch (itemError) {
logger.error(`Error processing item: ${item.title}`, { error: itemError.message });
return null;
}
})
);
const validMetas = metas.filter(Boolean);
logger.info(`Returning ${validMetas.length} valid metas`);
return { metas: validMetas };
} catch (error) {
logger.error('Error creating catalog', { error: error.message, stack: error.stack });
return { metas: [] };
}
}
return { metas: [] };
};
// META HANDLER
const metaHandler = async ({ type, id }) => {
logger.info('Meta requested', { type, id });
if (type === "sport" && id.startsWith("f1_")) {
try {
// Always fetch fresh data
const items = await fetchEasynewsFeed();
const matchedItem = items.find(item => generateItemId(item) === id);
if (matchedItem) {
const posterUrl = await generatePoster(
matchedItem.title,
new Date(matchedItem.pubDate),
matchedItem.quality,
matchedItem.size
);
const meta = createMetaObject(matchedItem, posterUrl);
if (meta) {
return { meta };
}
}
} catch (error) {
logger.error('Error serving meta', { error: error.message });
}
}
return { meta: null };
};
// STREAM HANDLER
const streamHandler = async ({ type, id }) => {
logger.info('Stream requested', { type, id });
if (type === "sport" && id.startsWith("f1_")) {
try {
// Always fetch fresh data
const items = await fetchEasynewsFeed();
const matchedItem = items.find(item => generateItemId(item) === id);
if (matchedItem && matchedItem.link) {
const auth = Buffer.from(`${EASYNEWS_USERNAME}:${EASYNEWS_PASSWORD}`).toString('base64');
return {
streams: [{
title: "Watch Formula 1",
url: matchedItem.link,
behaviorHints: {
notWebReady: true,
proxyHeaders: {
request: {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:133.0) Gecko/20100101 Firefox/133.0',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'en-GB,en;q=0.5',
'Accept-Encoding': 'gzip, deflate, br, zstd',
'Authorization': `Basic ${auth}`,
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1'
}
}
}
}]
};
}
} catch (error) {
logger.error('Error creating stream', { error: error.message });
}
return { streams: [] };
}
return { streams: [] };
};
// REGISTER HANDLERS
builder.defineCatalogHandler(catalogHandler);
builder.defineMetaHandler(metaHandler);
builder.defineStreamHandler(streamHandler);
// EXPRESS SERVER SETUP
const app = express();
app.use(cors());
app.use((req, res, next) => {
logger.info('Incoming request', {
method: req.method,
url: `${req.protocol}://${req.get('host')}${req.originalUrl}`
});
next();
});
// ROUTES
app.get('/', (req, res) => res.redirect('/manifest.json'));
app.get('/manifest.json', (req, res) => {
res.setHeader('Content-Type', 'application/json');
res.setHeader('Access-Control-Allow-Origin', '*');
res.send(builder.getInterface().manifest);
});
app.get('/catalog/:type/:id.json', async (req, res) => {
try {
const params = {
type: req.params.type,
id: req.params.id,
extra: req.query.skip ? { skip: parseInt(req.query.skip) } : {}
};
// Add search parameter if present
if (req.query.search) {
params.extra = params.extra || {};
params.extra.search = req.query.search;
}
const result = await catalogHandler(params);
res.setHeader('Content-Type', 'application/json');
res.setHeader('Access-Control-Allow-Origin', '*');
res.send(result);
} catch (error) {
logger.error('Error serving catalog', { error: error.message });
res.status(500).send({ error: 'Internal server error' });
}
});
app.get('/meta/:type/:id.json', async (req, res) => {
try {
const result = await metaHandler(req.params);
res.setHeader('Content-Type', 'application/json');
res.setHeader('Access-Control-Allow-Origin', '*');
res.send(result);
} catch (error) {
logger.error('Error serving meta', { error: error.message });
res.status(500).send({ error: 'Internal server error' });
}
});
app.get('/stream/:type/:id.json', async (req, res) => {
try {
const result = await streamHandler(req.params);
res.setHeader('Content-Type', 'application/json');
res.setHeader('Access-Control-Allow-Origin', '*');
res.send(result);
} catch (error) {
logger.error('Error serving stream', { error: error.message });
res.status(500).send({ error: 'Internal server error' });
}
});
// We're using Cloudinary for images, so no need for local static files
app.get('/health', (req, res) => {
res.json({
status: 'ok',
timestamp: new Date().toISOString(),
uptime: process.uptime(),
memoryUsage: process.memoryUsage()
});
});
// SERVER STARTUP
async function startServer() {
try {
// Validate Easynews credentials
const credentialsValid = await validateEasynewsCredentials();
if (!credentialsValid) {
throw new Error('Invalid Easynews credentials');
}
// Start the server
const PORT = process.env.PORT || 9712;
app.listen(PORT, () => {
logger.info(`Addon server is running on port ${PORT}`);
logger.info(`Manifest URL: /manifest.json`);
});
} catch (error) {
logger.error('Failed to start server', { error: error.message });
process.exit(1);
}
}
// Start the server
startServer();