EuropeanTV / server.js
arnaupq2's picture
Upload 3 files
a10973c verified
Raw History Blame Contribute Delete
10.1 kB
const express = require('express');
const fs = require('fs');
const path = require('path');
const https = require('https');
const { execSync } = require('child_process');
const app = express();
const PORT = process.env.PORT || 3000;
const VIDEOS_FILE = path.join(__dirname, 'videos.json');
const MIDNIGHT_VIDEO = 'https://youtu.be/I88qRwVirTo?si=saUHc-HWvuFQyAzS';
// YouTube Cookies from environment variable
const ytCookies = process.env.yt_cookies || '';
// Start time of the server to calculate offsets
let serverStartTime = Date.now();
let forceTickerUntil = 0;
function getYouTubeMetadata(url) {
let cookieFile = null;
try {
let cookieOption = '';
if (ytCookies) {
if (ytCookies.startsWith('# Netscape') || ytCookies.length > 100) {
// It looks like cookie content, write to a temp file
cookieFile = path.join(__dirname, 'temp_cookies.txt');
fs.writeFileSync(cookieFile, ytCookies);
cookieOption = `--cookies "${cookieFile}"`;
} else if (ytCookies.includes('/') || ytCookies.includes('\\') || ytCookies.endsWith('.txt')) {
// It looks like a file path
cookieOption = `--cookies "${ytCookies}"`;
} else {
// It looks like a browser name
cookieOption = `--cookies-from-browser ${ytCookies}`;
}
}
const cmd = `yt-dlp --get-title --get-duration --get-id -j ${cookieOption} "${url}"`;
const output = execSync(cmd, { encoding: 'utf-8' });
const data = JSON.parse(output);
// Convert duration to seconds
let seconds = 0;
if (data.duration) {
seconds = data.duration;
} else if (data.duration_string) {
const parts = data.duration_string.split(':').map(p => parseInt(p));
if (parts.length === 3) seconds = parts[0] * 3600 + parts[1] * 60 + parts[2];
else if (parts.length === 2) seconds = parts[0] * 60 + parts[1];
else seconds = parts[0];
}
return {
title: data.title,
id: data.id,
duration: seconds || 0,
url: `https://www.youtube.com/watch?v=${data.id}`
};
} catch (err) {
console.error(`Error fetching YT metadata for ${url}:`, err.message);
return null;
} finally {
if (cookieFile && fs.existsSync(cookieFile)) {
try { fs.unlinkSync(cookieFile); } catch (e) {}
}
}
}
let cachedPlaylist = [];
let lastPlaylistUpdate = 0;
function getPlaylist() {
// Cache playlist metadata for 1 hour to avoid excessive yt-dlp calls
if (Date.now() - lastPlaylistUpdate < 3600000 && cachedPlaylist.length > 0) {
return cachedPlaylist;
}
try {
const content = fs.readFileSync(VIDEOS_FILE, 'utf-8');
const videos = JSON.parse(content);
const resolved = [];
for (const v of videos) {
// If duration is already provided in JSON, use it and skip yt-dlp
if (v.duration) {
// Extract ID from URL if not provided
const idMatch = v.url.match(/(?:v=|\/)([a-zA-Z0-9_-]{11})/);
const id = v.id || (idMatch ? idMatch[1] : null);
if (id) {
resolved.push({
title: v.title,
id: id,
duration: v.duration,
url: v.url
});
continue;
}
}
const meta = getYouTubeMetadata(v.url);
if (meta) resolved.push(meta);
}
cachedPlaylist = resolved;
lastPlaylistUpdate = Date.now();
return resolved;
} catch (err) {
console.error('Error reading videos.json:', err);
return [];
}
}
// Special case for midnight video
let midnightVideoMeta = null;
function getMidnightVideo() {
if (!midnightVideoMeta) {
midnightVideoMeta = getYouTubeMetadata(MIDNIGHT_VIDEO);
// Hardcoded Fallback if yt-dlp fails due to cookies/bot detection
if (!midnightVideoMeta) {
midnightVideoMeta = {
title: "European Anthem - Special Midnight Broadcast",
id: "I88qRwVirTo",
duration: 219,
url: MIDNIGHT_VIDEO
};
}
}
return midnightVideoMeta;
}
// Improved News Fetcher (Euronews + Fallback)
async function fetchNews() {
const feeds = [
'https://www.euronews.com/rss?level=vertical&name=news',
'https://news.google.com/rss?hl=es-ES&gl=ES&ceid=ES:es'
];
for (const feed of feeds) {
try {
const res = await fetch(feed, { headers: { 'User-Agent': 'Mozilla/5.0' } });
if (!res.ok) continue;
const data = await res.text();
// Extract everything between <title> and </title>
const titles = [];
const regex = /<title>(?:<!\[CDATA\[)?(.*?)(?:\]\]>)?<\/title>/g;
let match;
while ((match = regex.exec(data)) !== null) {
const title = match[1].trim();
// Skip generic titles
if (title && !title.toLowerCase().includes('euronews') && !title.toLowerCase().includes('noticias')) {
titles.push(title);
}
if (titles.length >= 10) break;
}
if (titles.length > 0) return titles;
} catch (e) {
console.error(`Error fetching news from ${feed}:`, e.message);
}
}
return ['No se pudieron cargar noticias en tiempo real. Inténtalo más tarde.'];
}
// Weather fetcher (European Capitals)
async function fetchWeather() {
const cities = [
{ name: 'Berlin', lat: 52.52, lon: 13.41 },
{ name: 'Madrid', lat: 40.41, lon: -3.70 },
{ name: 'Warsaw', lat: 52.23, lon: 21.01 },
{ name: 'Paris', lat: 48.85, lon: 2.35 },
{ name: 'Rome', lat: 41.89, lon: 12.51 },
{ name: 'London', lat: 51.50, lon: -0.12 },
{ name: 'K\u00f6nigsberg', lat: 54.71, lon: 20.45 }
];
const lats = cities.map(c => c.lat).join(',');
const lons = cities.map(c => c.lon).join(',');
return new Promise((resolve) => {
https.get(`https://api.open-meteo.com/v1/forecast?latitude=${lats}&longitude=${lons}&current_weather=true`, (res) => {
let data = '';
res.on('data', chunk => data += chunk);
res.on('end', () => {
try {
const json = JSON.parse(data);
const weatherData = cities.map((city, i) => ({
city: city.name,
temp: Math.round(json[i].current_weather.temperature)
}));
resolve(weatherData);
} catch(e) {
resolve(cities.map(c => ({ city: c.name, temp: '?' })));
}
});
}).on('error', () => resolve([]));
});
}
app.get('/api/extra', async (req, res) => {
const news = await fetchNews();
const weather = await fetchWeather();
res.json({ news, weather });
});
app.get('/api/status', (req, res) => {
const playlist = getPlaylist();
const anthem = getMidnightVideo();
if (!anthem || playlist.length === 0) {
return res.status(500).json({ error: 'Playlist or Midnight video not loaded' });
}
const now = new Date();
const currentHour = now.getHours();
const currentMinute = now.getMinutes();
const currentSecond = now.getSeconds();
// Calculate seconds since midnight for accurate sync
const midnight = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
const secondsSinceMidnight = (Date.now() - midnight) / 1000;
// Condition 1: Midnight Video (00:00 to 00:04 approx, depending on length)
const isScheduledMidnight = currentHour === 0 && (currentMinute * 60 + currentSecond) < anthem.duration;
let currentVideo = null;
let seekTime = 0;
if (isScheduledMidnight) {
currentVideo = anthem;
seekTime = secondsSinceMidnight;
} else {
const totalDuration = playlist.reduce((acc, v) => acc + v.duration, 0);
const elapsedSinceStart = (Date.now() - serverStartTime) / 1000;
// Loop playlist
const playlistElapsed = totalDuration > 0 ? (elapsedSinceStart % totalDuration) : 0;
let cumulative = 0;
for (const video of playlist) {
if (playlistElapsed < cumulative + video.duration) {
currentVideo = video;
seekTime = playlistElapsed - cumulative;
break;
}
cumulative += video.duration;
}
if (!currentVideo && playlist.length > 0) currentVideo = playlist[0];
}
res.json({
currentVideo: {
title: currentVideo.title,
id: currentVideo.id,
duration: currentVideo.duration
},
seekTime: Math.max(0, seekTime),
serverTime: Date.now(),
forceTicker: Date.now() < forceTickerUntil,
// Show next 5 videos, looping back to start if necessary
nextVideos: [...playlist, ...playlist]
.slice(playlist.indexOf(currentVideo) + 1, playlist.indexOf(currentVideo) + 6)
.map(v => ({ title: v.title, id: v.id }))
});
});
app.use(express.static(__dirname));
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
console.log(`Playback started at: ${new Date(serverStartTime).toLocaleTimeString()}`);
});