/**
* ============================================================================
* PINOMAX MTProto Streaming, Auto-Indexer & Telegram Mini App Engine
* Powered by Express.js, GramJS (MTProto), MongoDB Atlas, Firebase & Artplayer
* ============================================================================
*/
import express from 'express';
import path from 'path';
import { fileURLToPath } from 'url';
import dotenv from 'dotenv';
import axios from 'axios';
import cors from 'cors';
import helmet from 'helmet';
import mongoose from 'mongoose';
import { TelegramClient, Api } from 'telegram';
import { StringSession } from 'telegram/sessions/index.js';
import { NewMessage } from 'telegram/events/index.js';
import bigInt from 'big-integer';
import AdmZip from 'adm-zip';
import crypto from 'crypto';
if (!globalThis.crypto) globalThis.crypto = crypto;
// Ilagay ito sa tabi ng iba pang imports sa itaas ng server.js mo
import subtitleRoutes from './routes/subtitles.js';
// Load Environment Variables
dotenv.config();
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Initialize Express App
const app = express();
const PORT = process.env.PORT || 3000;
// Core Configuration
//const APP_URL = (process.env.APP_URL || 'https://streamixph05-pinomaxstreamv12026.hf.space').replace(/\/+$/, '');///
const APP_URL = (process.env.APP_URL || 'https://movie-production-57b9.up.railway.app').replace(/\/+$/, '');
const WORKER_URL = "https://pinomax-cache.roderickalmaras05.workers.dev";
const API_ID = parseInt(process.env.API_ID || '0', 10);
const API_HASH = (process.env.API_HASH || '').trim();
const BOT_TOKEN = (process.env.BOT_TOKEN || '').trim();
const ADMIN_ID = (process.env.ADMIN_ID || '').toString().trim();
const MONGODB_URI = process.env.MONGODB_URI || '';
const FIREBASE_DATABASE_URL = (process.env.FIREBASE_DATABASE_URL || 'https://jetmax-f3e8e-default-rtdb.firebaseio.com').replace(/\/+$/, '');
const TMDB_API_KEY = process.env.TMDB_API_KEY || '86fd55697899e8444fa3da3ddd24518d';
// Payment Configuration (GCash & PayPal)
const PAYMENT_CONFIG = {
gcash_number: process.env.GCASH_NUMBER || '09638924040',
gcash_name: process.env.GCASH_NAME || 'PINOMAX ADMIN',
paypal_email: process.env.PAYPAL_EMAIL || 'payments@pinomax.com',
donate_amount: '5'
};
// 🟢 TELEGRAM MEDIA IN-MEMORY CACHE (Para instant play at walang Telegram API lag)
const telegramMediaCache = new Map();
// ---------------------------------------------------------------------------
// 1. MONGODB DATABASE & SCHEMA (Collection: stream_files)
// ---------------------------------------------------------------------------
const streamFileSchema = new mongoose.Schema({
file_unique_id: { type: String, index: true },
file_id: { type: String, index: true },
unique_id: { type: String, index: true },
fileId: { type: String, index: true },
message_id: { type: Number },
messageId: { type: Number },
chat_id: { type: String },
chatId: { type: String },
channelId: { type: String, default: null },
file_name: { type: String, default: 'media.mp4' },
fileName: { type: String, default: 'media.mp4' },
file_size: { type: Number, default: 0 },
fileSize: { type: Number, default: 0 },
mime_type: { type: String, default: 'video/mp4' },
mimeType: { type: String, default: 'video/mp4' },
poster: { type: String, default: '' },
year: { type: String, default: '' },
rating: { type: String, default: '8.5' },
overview: { type: String, default: '' },
category: { type: String, default: 'Movie' },
episode: { type: String, default: '' },
uploadedBy: { type: String, default: 'Admin' },
createdAt: { type: Date, default: Date.now, index: true }
}, {
collection: 'stream_files',
timestamps: true,
strict: false
});
const inMemoryFiles = new Map();
let StreamFileModel = null;
let StreamFile = null;
let isMongoConnected = false;
if (MONGODB_URI) {
mongoose.connect(MONGODB_URI, { serverSelectionTimeoutMS: 5000 }).then(() => {
isMongoConnected = true;
console.log('✅ Connected to MongoDB Atlas.');
}).catch((err) => {
console.warn('⚠️ MongoDB fallback to memory cache:', err.message);
});
StreamFileModel = mongoose.models.StreamFile || mongoose.model('StreamFile', streamFileSchema);
StreamFile = StreamFileModel;
}
async function saveStreamFileRecord(data) {
const primaryId = data.file_unique_id || data.file_id || data.unique_id || data.fileId;
const normalized = {
...data,
file_unique_id: primaryId,
file_id: primaryId,
unique_id: primaryId,
fileId: primaryId,
chat_id: data.chat_id || data.chatId,
chatId: data.chatId || data.chat_id,
message_id: data.message_id || data.messageId,
messageId: data.messageId || data.message_id,
file_name: data.file_name || data.fileName || 'media.mp4',
fileName: data.fileName || data.file_name || 'media.mp4',
file_size: data.file_size !== undefined ? data.file_size : (data.fileSize || 0),
fileSize: data.fileSize !== undefined ? data.fileSize : (data.file_size || 0),
mime_type: data.mime_type || data.mimeType || 'video/mp4',
mimeType: data.mimeType || data.mime_type || 'video/mp4',
poster: data.poster || '',
year: data.year || '',
rating: data.rating || '8.5',
overview: data.overview || '',
category: data.category || 'Movie',
episode: data.episode || '',
updatedAt: new Date()
};
inMemoryFiles.set(primaryId, normalized);
const model = StreamFile || StreamFileModel;
if (isMongoConnected && model) {
try {
return await model.findOneAndUpdate(
{ $or: [ { file_unique_id: primaryId }, { file_id: primaryId } ] },
{ $set: normalized },
{ upsert: true, new: true }
);
} catch (e) {
console.error('MongoDB save error:', e.message);
}
}
return normalized;
}
async function getStreamFileRecord(fileId) {
if (!fileId) return null;
const idStr = String(fileId).trim();
const model = StreamFile || StreamFileModel;
if (isMongoConnected && model) {
try {
const fileRecord = await model.findOne({
$or: [
{ file_unique_id: idStr },
{ file_id: idStr },
{ unique_id: idStr },
{ fileId: idStr }
]
}).lean();
if (fileRecord) return fileRecord;
} catch (e) {
console.error('MongoDB find error:', e.message);
}
}
return inMemoryFiles.get(idStr) || null;
}
function formatBytes(bytes, decimals = 2) {
if (!bytes || bytes === 0) return '0 Bytes';
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
// ---------------------------------------------------------------------------
// 2. GRAMJS TELEGRAM MTPROTO ENGINE (AUTO-INDEXER WITH WORKER URLs)
// ---------------------------------------------------------------------------
let tgClient = null;
let isGramJsConnected = false;
if (API_ID && API_HASH && BOT_TOKEN) {
try {
const stringSession = new StringSession(process.env.SESSION_STRING || "");
tgClient = new TelegramClient(stringSession, API_ID, API_HASH, {
connectionRetries: 10,
retryDelay: 1000,
autoReconnect: true,
useIPv6: false,
timeout: 30,
floodSleepThreshold: 60
});
} catch (initErr) {
console.warn('⚠️ TelegramClient init notice:', initErr.message);
}
}
if (tgClient && API_ID && API_HASH && BOT_TOKEN) {
(async () => {
try {
console.log('Connecting Telegram GramJS MTProto client...');
await tgClient.start({ botAuthToken: process.env.BOT_TOKEN });
isGramJsConnected = true;
console.log('✅ Telegram GramJS MTProto Client successfully authenticated!');
// 🟢 I-PRINT ANG SESSION STRING (Para makopya mo sa Railway)
try {
const savedSession = tgClient.session.save();
if (savedSession) {
console.log('🔑 SESSION_STRING MO (Kopyahin ito sa Railway):', savedSession);
}
} catch (_) {}
// 🟢 AUTO-CONNECT SA MGA STORAGE CHANNELS
const rawChannels = process.env.STORAGE_CHANNELS || '';
const STORAGE_CHANNELS = rawChannels
.split(',')
.map(id => id.trim())
.filter(Boolean);
if (STORAGE_CHANNELS.length > 0) {
console.log(`🔄 Kinokonekta ang ${STORAGE_CHANNELS.length} storage channels...`);
for (const chId of STORAGE_CHANNELS) {
try {
await tgClient.getInputEntity(chId);
console.log(`✅ Channel Connected & Cached: ${chId}`);
} catch (err) {
console.warn(`⚠️ Warning: Hindi ma-cache ang channel ${chId}:`, err.message);
}
}
}
// Keep Alive
setInterval(async () => {
if (tgClient && isGramJsConnected) {
try { await tgClient.getMe(); } catch (e) {}
}
}, 40000);
// Event Handler para sa Auto-Indexing ng Videos
tgClient.addEventHandler(async (event) => {
try {
const message = event.message;
if (!message) return;
// 🟢 1. BASAHIN ANG ADMIN IDS SA TAAS (Mababasa ng lahat)
const ADMIN_IDS = (process.env.ADMIN_ID || '').split(',').map(id => id.trim()).filter(Boolean);
const senderId = message.senderId ? message.senderId.toString() : '';
const peerChannelId = message.peerId?.channelId ? message.peerId.channelId.toString() : '';
const chatId = peerChannelId ? `-100${peerChannelId}` : (message.chatId ? message.chatId.toString() : '');
const messageId = message.id;
const isChannelPost = Boolean(peerChannelId);
const isSenderAdmin = ADMIN_IDS.includes(senderId) || ADMIN_IDS.includes(chatId);
// 🟢 1. COMMAND: /start (Private Chat Welcome)
if (!isChannelPost && message.message?.startsWith('/start')) {
if (ADMIN_IDS.length > 0 && !isSenderAdmin) {
await tgClient.sendMessage(chatId, {
message: `⛔ Access Denied!\n\nYour Telegram User ID: ${senderId}\nAuthorized Admin ID: ${ADMIN_IDS.join(', ')}`,
parseMode: 'html',
});
return;
}
await tgClient.sendMessage(chatId, {
message:
`🚀 Welcome to PINOMAX MTProto Media Streaming & Downloader Engine!
⚡ Bypasses the 20MB Bot API Limit — Supports files up to 2GB!
*✨ Key Features:*
• 📺 HTTP 206 Partial Content Streaming
• 📥 Direct Attachment Downloader
• 🎬 Standalone Embed Video Player (with CC & Subtitles)
👉 Mag-forward ng movie rito o mag-upload sa Channel para mag-auto index! Gamitin ang /list para makita ang mga uploaded movies.`,
parseMode: 'html',
});
return;
}
// 🟢 2. COMMAND: /list (Ilista ang 10 pinakabagong uploaded movies)
if (!isChannelPost && message.message?.startsWith('/list')) {
try {
const model = StreamFile || StreamFileModel;
let files = [];
if (isMongoConnected && model) {
files = await model.find().sort({ createdAt: -1 }).limit(10).lean();
} else {
files = Array.from(inMemoryFiles.values()).slice(0, 10);
}
if (!files || files.length === 0) {
await tgClient.sendMessage(chatId, {
message: '📂 Wala pang naka-save na movies sa database.',
parseMode: 'html'
});
return;
}
let listText = '🎬 Recent Uploaded Movies (PINOMAX):\n\n';
files.forEach((f, idx) => {
const fId = f.file_unique_id || f.file_id || f.unique_id;
const embedUrl = `${WORKER_URL}/embed/${fId}`;
const title = f.file_name || f.fileName || 'Movie';
const size = formatBytes(f.file_size || f.fileSize || 0);
listText += `${idx + 1}. ${title} (${size})\n`;
listText += ` 👉 ${embedUrl}\n\n`;
});
await tgClient.sendMessage(chatId, {
message: listText,
parseMode: 'html'
});
} catch (err) {
console.error('List error:', err);
}
return;
}
// 🟢 3. MEDIA HANDLER (Video Auto-Indexer)
if (message.media && (message.media.document || message.media.video || message.file)) {
// Harangin ang ibang tao kapag nag-upload sa PM
if (!isChannelPost && ADMIN_IDS.length > 0 && !isSenderAdmin) {
return;
}
const doc = message.media.document || message.media;
const file = message.file;
let fileName = file?.name || '';
if (!fileName && doc?.attributes) {
const fnAttr = doc.attributes.find(a => a.className === 'DocumentAttributeFilename' || a.fileName);
if (fnAttr && fnAttr.fileName) fileName = fnAttr.fileName;
}
if (!fileName) fileName = `media_${messageId}.${file?.ext || 'mp4'}`;
const fileSize = Number(file?.size || doc?.size || 0);
const mimeType = file?.mimeType || doc?.mimeType || 'video/mp4';
const fileUniqueId = `${chatId.replace(/^-/, '')}_${messageId}`;
// 🛡️ HARANGIN ANG MGA KALAT NA FILES / INTRO TEST (< 5MB)
if (fileSize < 5 * 1024 * 1024) {
console.log(`⏩ Skipped junk/small media (${formatBytes(fileSize)}): ${fileName}`);
return; // Hindi ito ise-save sa database
}
let poster = '';
let year = '2024';
let rating = '8.5';
let overview = '';
let category = fileName.toLowerCase().includes('series') ? 'Series' : 'Movie';
let episode = '';
// ✅ SMART TMDB TITLE CLEANER & DUAL SEARCH
try {
// 1. Linisin ang mga kalat na tags, channel names, resolution, at underscores
let cleanTitle = fileName
.replace(/\.mp4|\.mkv|\.webm|\.avi/gi, '')
.replace(/@\w+/g, '') // Tanggalin ang @channel_name
.replace(/tagalog dubbed|tagdub|dubbed|pinoy|tagalog|full movie/gi, '')
.replace(/1080p|720p|480p|hdrip|bluray|web-dl|webrip|x264|x265|hevc/gi, '')
.replace(/[\(\)\[\]_\-\.]+/g, ' ') // Palitan ang _, -, at brackets ng space
.trim();
// 2. Hanapin kung may Taon (e.g. 2024, 2000, 1999)
const yearMatch = cleanTitle.match(/\b(19\d{2}|20\d{2})\b/);
let detectedYear = yearMatch ? yearMatch[1] : '';
if (detectedYear) {
cleanTitle = cleanTitle.replace(detectedYear, '').trim();
}
// 3. Unang Search sa TMDB (May Title + Year para eksakto)
let searchUrl = `https://api.themoviedb.org/3/search/multi?api_key=${TMDB_API_KEY}&query=${encodeURIComponent(cleanTitle)}${detectedYear ? '&year=' + detectedYear : ''}`;
let searchRes = await axios.get(searchUrl, { timeout: 4000 });
// 4. Fallback Search: Kung walang nahanap, mag-search uli gamit ang Title lang
if (!searchRes.data?.results?.length && detectedYear) {
searchUrl = `https://api.themoviedb.org/3/search/multi?api_key=${TMDB_API_KEY}&query=${encodeURIComponent(cleanTitle)}`;
searchRes = await axios.get(searchUrl, { timeout: 4000 });
}
if (searchRes.data?.results?.length > 0) {
const resItem = searchRes.data.results[0];
if (resItem.poster_path) {
poster = `https://image.tmdb.org/t/p/w500${resItem.poster_path}`;
}
year = (resItem.release_date || resItem.first_air_date || detectedYear || '').split('-')[0] || '2024';
rating = resItem.vote_average ? resItem.vote_average.toFixed(1) : '8.5';
overview = resItem.overview ? (resItem.overview.length > 120 ? resItem.overview.substring(0, 120) + '...' : resItem.overview) : '';
category = resItem.media_type === 'tv' ? 'Series' : 'Movie';
} else {
year = detectedYear || '2024';
}
} catch (_) {}
await saveStreamFileRecord({
chat_id: chatId.toString(),
message_id: Number(messageId),
file_name: fileName,
file_size: fileSize,
mime_type: mimeType,
poster,
year,
rating,
overview,
category,
episode,
unique_id: fileUniqueId,
uploadedBy: isChannelPost ? 'Channel Storage' : (senderId ? `@${senderId}` : 'Admin')
});
// I-cache agad ang media para ready sa streaming
telegramMediaCache.set(`${chatId}_${messageId}`, {
media: message.media,
size: fileSize,
mimeType,
timestamp: Date.now()
});
const streamUrl = `${WORKER_URL}/stream/${fileUniqueId}`;
const downloadUrl = `${WORKER_URL}/download/${fileUniqueId}?file=${encodeURIComponent(fileName)}`;
const embedUrl = `${WORKER_URL}/embed/${fileUniqueId}`;
const sizeFormatted = formatBytes(fileSize);
// 👉 FORMAT NA TUGMANG-TUGMA SA SCREENSHOT 1:
const replyHtml =
`🎬 Media Successfully Indexed (2GB MTProto Engine)!\n\n` +
`📁 File Name: ${fileName}\n` +
`📦 File Size: ${sizeFormatted}\n` +
`🏷️ Source: ${isChannelPost ? 'Channel Auto-Index' : 'Direct Upload'}\n` +
`🆔 File ID: ${fileUniqueId}\n\n` +
`━━━━━━━━━━━━━━━━━━━━\n` +
`📺 Stream URL (HTTP 206):\n` +
`${streamUrl}\n\n` +
`📥 Direct Download URL:\n` +
`${downloadUrl}\n\n` +
`🎬 Cloudflare Cached Embed URL:\n` +
`${embedUrl}\n` +
`━━━━━━━━━━━━━━━━━━━━`;
// 1. KUNG SA STORAGE CHANNEL KA NAG-UPLOAD O NAG-FORWARD:
if (isChannelPost) {
await tgClient.sendMessage(chatId, {
message: replyHtml,
replyTo: Number(messageId),
parseMode: 'html'
}).catch((e) => console.error('Channel send error:', e.message));
if (ADMIN_ID && chatId !== ADMIN_ID) {
await tgClient.sendMessage(ADMIN_ID, {
message: replyHtml,
parseMode: 'html'
}).catch((e) => console.error('Admin PM send error:', e.message));
}
}
// 2. KUNG DIRECT FORWARD MO SA PM NG BOT:
else {
await tgClient.sendMessage(chatId, {
message: replyHtml,
parseMode: 'html'
}).catch((e) => console.error('PM send error:', e.message));
}
}
} catch (err) {
console.error('Error in event handler:', err);
}
}, new NewMessage({}));
} catch (err) {
console.warn('⚠️ GramJS Error:', err.message);
}
})();
}
// ---------------------------------------------------------------------------
// 3. EXPRESS MIDDLEWARE CONFIGURATION
// ---------------------------------------------------------------------------
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cors());
app.use(helmet({ contentSecurityPolicy: false, crossOriginEmbedderPolicy: false }));
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', subtitleRoutes);
// ---------------------------------------------------------------------------
// 4. FIREBASE VIP & PAYMENT APIS (TUGMA SA AdminDashboardActivity.java)
// ---------------------------------------------------------------------------
app.get('/api/vip/status/:uid', async (req, res) => {
const { uid } = req.params;
try {
const fb = await axios.get(`${FIREBASE_DATABASE_URL}/users/${uid}.json`);
const user = fb.data || {};
let isVip = user.isVip || false;
const expiry = user.vip_expiry || 0;
if (isVip && expiry > 0 && Date.now() > expiry) {
isVip = false;
await axios.patch(`${FIREBASE_DATABASE_URL}/users/${uid}.json`, { isVip: false });
}
return res.json({
isVip,
vip_expiry: expiry,
userName: user.name || user.user_name || 'User',
active_request: user.active_request || null
});
} catch (e) {
return res.json({ isVip: false });
}
});
app.post('/api/vip/submit-request', async (req, res) => {
const { uid, userName, planName, amount, method, refNumber } = req.body;
if (!uid || !refNumber) return res.status(400).json({ error: 'Kulang ang data' });
const timestamp = Date.now();
const dateStr = new Date(timestamp).toLocaleString('en-PH', {
timeZone: 'Asia/Manila',
month: 'short',
day: '2-digit',
year: 'numeric',
hour: '2-digit',
minute: '2-digit',
hour12: true
});
const payload = {
uid: String(uid).trim(),
name: String(userName || 'Telegram User').trim(),
userName: String(userName || 'Telegram User').trim(),
plan: String(planName || 'VIP Access').trim(),
amount: String(amount || '5').trim(),
ref_number: String(refNumber).trim(),
ref: String(refNumber).trim(),
method: String(method || 'GCASH').toUpperCase().trim(),
status: 'pending',
date: dateStr,
createdAt: timestamp
};
try {
// 1. I-save sa user profile (active_request)
await axios.put(`${FIREBASE_DATABASE_URL}/users/${uid}/active_request.json`, payload);
// 2. I-save sa "requests" node (Para sa AdminDashboardActivity.java)
const reqKey = `REQ_${uid}_${timestamp}`;
await axios.put(`${FIREBASE_DATABASE_URL}/requests/${reqKey}.json`, payload);
// 3. TELEGRAM ALERT SA ADMIN PM KAPAG MAY NAG-SUBMIT
if (tgClient && ADMIN_ID && isGramJsConnected) {
try {
await tgClient.sendMessage(ADMIN_ID, {
message:
`💰 BAGONG BAYAD / DONATE SUBMISSION!\n\n` +
`👤 User: ${userName} (ID: ${uid})\n` +
`👑 Plan: ${planName}\n` +
`💵 Amount: ₱${amount}\n` +
`💳 Method: ${method}\n` +
`🔢 Ref No.: ${refNumber}\n\n` +
`👉 Buksan ang Admin Dashboard App para i-Approve!`,
parseMode: 'html'
});
} catch (_) {}
}
return res.json({ success: true, message: 'Naisumite sa Admin!' });
} catch (e) {
return res.status(500).json({ error: 'Error sa database' });
}
});
app.get('/api/payment-config', (req, res) => {
res.json(PAYMENT_CONFIG);
});
app.get('/stream/:fileId', async (req, res) => {
const fileId = req.params.fileId;
const rec = await getStreamFileRecord(fileId);
if (!rec) {
console.error(`❌ Stream Failed: File record not found in MongoDB for ID: ${fileId}`);
return res.redirect('https://vjs.zencdn.net/v/oceans.mp4');
}
if (!tgClient || !isGramJsConnected) {
console.error('❌ Stream Failed: Telegram MTProto Client not connected');
return res.redirect('https://vjs.zencdn.net/v/oceans.mp4');
}
try {
let peer = rec.chat_id || rec.chatId;
// 🟢 RESOLVE TELEGRAM PEER PARA SA LAHAT NG STORAGE CHANNELS
let targetEntity;
try {
targetEntity = await tgClient.getInputEntity(peer);
} catch (resolveErr) {
if (typeof peer === 'string' && peer.startsWith('-100')) {
peer = bigInt(peer.replace('-100', ''));
}
targetEntity = await tgClient.getInputEntity(peer);
}
const msgIdNum = Number(rec.message_id || rec.messageId);
const cacheKey = `${rec.chat_id}_${msgIdNum}`;
let mediaObj = null;
let totalSize = Number(rec.file_size || rec.fileSize || 0);
// 🟢 1. FAST MEMORY CACHE
if (telegramMediaCache.has(cacheKey)) {
const cached = telegramMediaCache.get(cacheKey);
mediaObj = cached.media;
if (cached.size) totalSize = cached.size;
} else {
const msgs = await tgClient.getMessages(targetEntity, { ids: [msgIdNum] });
const msg = msgs && msgs[0];
if (!msg || !msg.media) {
console.error(`❌ Stream Failed: Message not found in Telegram (Channel: ${peer}, Msg ID: ${msgIdNum})`);
return res.redirect('https://vjs.zencdn.net/v/oceans.mp4');
}
mediaObj = msg.media;
totalSize = Number(msg.file?.size || totalSize);
telegramMediaCache.set(cacheKey, {
media: mediaObj,
size: totalSize,
mimeType: rec.mime_type || 'video/mp4',
timestamp: Date.now()
});
}
const range = req.headers.range;
let start = 0;
let end = totalSize - 1;
const cacheHeaders = {
'Cache-Control': 'public, max-age=2592000, s-maxage=2592000, immutable',
'CDN-Cache-Control': 'max-age=2592000',
'Cloudflare-CDN-Cache-Control': 'max-age=2592000',
'Access-Control-Allow-Origin': '*',
'Accept-Ranges': 'bytes'
};
// 🟢 2. STANDARD HTTP 206
if (range) {
const parts = range.replace(/bytes=/, '').split('-');
start = parseInt(parts[0], 10);
if (parts[1]) {
end = parseInt(parts[1], 10);
}
res.writeHead(206, {
...cacheHeaders,
'Content-Range': `bytes ${start}-${end}/${totalSize}`,
'Content-Length': (end - start) + 1,
'Content-Type': rec.mime_type || 'video/mp4'
});
} else {
res.writeHead(200, {
...cacheHeaders,
'Content-Length': totalSize,
'Content-Type': rec.mime_type || 'video/mp4'
});
}
// 🟢 3. STREAMING CHUNKS (1MB CHUNK)
const stream = tgClient.iterDownload({
file: mediaObj,
offset: bigInt(start),
limit: (end - start) + 1,
requestSize: 1024 * 1024
});
let closed = false;
req.on('close', () => {
closed = true;
});
for await (const chunk of stream) {
if (closed) break;
res.write(chunk);
}
if (!closed) res.end();
} catch (e) {
console.error('❌ Stream Route Critical Error:', e.message);
if (!res.headersSent) res.redirect('https://vjs.zencdn.net/v/oceans.mp4');
}
});
// DIRECT ATTACHMENT DOWNLOADER (VIP ONLY)
app.get('/download/:fileId', async (req, res) => {
const fileId = req.params.fileId;
// ⛔ HARANGIN ANG DIRECT LINK KUNG HINDI VIP:
const isVip = req.query.vip === '1';
if (!isVip) {
return res.status(403).send('
Bumalik sa Homepage para makita ang mga bagong HD posters.
`); } catch (err) { res.status(500).send('Auto-Fix Error: ' + err.message); } }); // =========================================================================== // 🛡️ SECRET ADMIN PANEL & CRUD API // =========================================================================== // 🟢 1. API: Kunin ang listahan ng lahat ng movies app.get('/api/admin/all-movies', async (req, res) => { try { const model = StreamFile || StreamFileModel; let movies = []; if (mongoose.connection.readyState === 1 && model) { movies = await model.find().sort({ createdAt: -1 }).maxTimeMS(5000).lean(); } else { movies = Array.from(inMemoryFiles.values()); } return res.json({ success: true, movies: movies || [] }); } catch (err) { console.error('Admin API error:', err); return res.json({ success: true, movies: Array.from(inMemoryFiles.values()) }); } }); // 🟢 2. API: I-save ang edited movie details app.post('/api/admin/update-movie', async (req, res) => { try { const { id, file_name, poster, year, rating, category, overview, episode } = req.body; if (!id) return res.status(400).json({ error: 'Kulang ang ID' }); const model = StreamFile || StreamFileModel; const updateData = { file_name, fileName: file_name, poster, year, rating, category, overview, episode }; if (mongoose.connection.readyState === 1 && model) { await model.findOneAndUpdate( { $or: [{ file_unique_id: id }, { file_id: id }, { unique_id: id }] }, { $set: updateData } ); } if (inMemoryFiles.has(id)) { const existing = inMemoryFiles.get(id); inMemoryFiles.set(id, { ...existing, ...updateData }); } return res.json({ success: true, message: 'Na-update nang matagumpay!' }); } catch (err) { return res.status(500).json({ success: false, error: err.message }); } }); // 🟢 3. API: Mag-delete ng Movie app.delete('/api/admin/delete-movie/:id', async (req, res) => { try { const { id } = req.params; const model = StreamFile || StreamFileModel; if (mongoose.connection.readyState === 1 && model) { await model.deleteOne({ $or: [{ file_unique_id: id }, { file_id: id }, { unique_id: id }] }); } inMemoryFiles.delete(id); return res.json({ success: true, message: 'Movie deleted!' }); } catch (err) { return res.status(500).json({ success: false, error: err.message }); } }); // 🟢 4. SECRET ADMIN DASHBOARD WEB UI app.get('/secret-admin-portal', (req, res) => { res.send(`