Streamixph05 commited on
Commit
3d040f4
·
verified ·
1 Parent(s): a076bde

Upload server.js

Browse files
Files changed (1) hide show
  1. server.js +1418 -0
server.js ADDED
@@ -0,0 +1,1418 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * ============================================================================
3
+ * PINOMAX MTProto Streaming, Auto-Indexer & Telegram Mini App Engine
4
+ * Powered by Express.js, GramJS (MTProto), MongoDB Atlas, Firebase & Artplayer
5
+ * ============================================================================
6
+ */
7
+
8
+ import express from 'express';
9
+ import path from 'path';
10
+ import { fileURLToPath } from 'url';
11
+ import dotenv from 'dotenv';
12
+ import axios from 'axios';
13
+ import cors from 'cors';
14
+ import helmet from 'helmet';
15
+ import mongoose from 'mongoose';
16
+ import { TelegramClient, Api } from 'telegram';
17
+ import { StringSession } from 'telegram/sessions/index.js';
18
+ import { NewMessage } from 'telegram/events/index.js';
19
+ import bigInt from 'big-integer';
20
+ import AdmZip from 'adm-zip';
21
+ import crypto from 'crypto';
22
+ if (!globalThis.crypto) globalThis.crypto = crypto;
23
+ // Ilagay ito sa tabi ng iba pang imports sa itaas ng server.js mo
24
+ import subtitleRoutes from './routes/subtitles.js';
25
+
26
+ // Load Environment Variables
27
+ dotenv.config();
28
+
29
+ const __filename = fileURLToPath(import.meta.url);
30
+ const __dirname = path.dirname(__filename);
31
+
32
+ // Initialize Express App
33
+ const app = express();
34
+ const PORT = process.env.PORT || 3000;
35
+
36
+ // Core Configuration
37
+ //const APP_URL = (process.env.APP_URL || 'https://streamixph05-pinomaxstreamv12026.hf.space').replace(/\/+$/, '');///
38
+ const APP_URL = (process.env.APP_URL || 'https://movie-production-57b9.up.railway.app').replace(/\/+$/, '');
39
+ const WORKER_URL = "https://pinomax-cache.roderickalmaras05.workers.dev";
40
+ const API_ID = parseInt(process.env.API_ID || '0', 10);
41
+ const API_HASH = (process.env.API_HASH || '').trim();
42
+ const BOT_TOKEN = (process.env.BOT_TOKEN || '').trim();
43
+ const ADMIN_ID = (process.env.ADMIN_ID || '').toString().trim();
44
+ const MONGODB_URI = process.env.MONGODB_URI || '';
45
+ const FIREBASE_DATABASE_URL = (process.env.FIREBASE_DATABASE_URL || 'https://jetmax-f3e8e-default-rtdb.firebaseio.com').replace(/\/+$/, '');
46
+ const TMDB_API_KEY = process.env.TMDB_API_KEY || '86fd55697899e8444fa3da3ddd24518d';
47
+
48
+ // Payment Configuration (GCash & PayPal)
49
+ const PAYMENT_CONFIG = {
50
+ gcash_number: process.env.GCASH_NUMBER || '09638924040',
51
+ gcash_name: process.env.GCASH_NAME || 'PINOMAX ADMIN',
52
+ paypal_email: process.env.PAYPAL_EMAIL || 'payments@pinomax.com',
53
+ donate_amount: '5'
54
+ };
55
+ // 🟢 TELEGRAM MEDIA IN-MEMORY CACHE (Para instant play at walang Telegram API lag)
56
+ const telegramMediaCache = new Map();
57
+
58
+ // ---------------------------------------------------------------------------
59
+ // 1. MONGODB DATABASE & SCHEMA (Collection: stream_files)
60
+ // ---------------------------------------------------------------------------
61
+ const streamFileSchema = new mongoose.Schema({
62
+ file_unique_id: { type: String, index: true },
63
+ file_id: { type: String, index: true },
64
+ unique_id: { type: String, index: true },
65
+ fileId: { type: String, index: true },
66
+ message_id: { type: Number },
67
+ messageId: { type: Number },
68
+ chat_id: { type: String },
69
+ chatId: { type: String },
70
+ channelId: { type: String, default: null },
71
+ file_name: { type: String, default: 'media.mp4' },
72
+ fileName: { type: String, default: 'media.mp4' },
73
+ file_size: { type: Number, default: 0 },
74
+ fileSize: { type: Number, default: 0 },
75
+ mime_type: { type: String, default: 'video/mp4' },
76
+ mimeType: { type: String, default: 'video/mp4' },
77
+ poster: { type: String, default: '' },
78
+ year: { type: String, default: '' },
79
+ rating: { type: String, default: '8.5' },
80
+ overview: { type: String, default: '' },
81
+ category: { type: String, default: 'Movie' },
82
+ episode: { type: String, default: '' },
83
+ uploadedBy: { type: String, default: 'Admin' },
84
+ createdAt: { type: Date, default: Date.now, index: true }
85
+ }, {
86
+ collection: 'stream_files',
87
+ timestamps: true,
88
+ strict: false
89
+ });
90
+
91
+ const inMemoryFiles = new Map();
92
+ let StreamFileModel = null;
93
+ let StreamFile = null;
94
+ let isMongoConnected = false;
95
+
96
+ if (MONGODB_URI) {
97
+ mongoose.connect(MONGODB_URI, { serverSelectionTimeoutMS: 5000 }).then(() => {
98
+ isMongoConnected = true;
99
+ console.log('✅ Connected to MongoDB Atlas.');
100
+ }).catch((err) => {
101
+ console.warn('⚠️ MongoDB fallback to memory cache:', err.message);
102
+ });
103
+ StreamFileModel = mongoose.models.StreamFile || mongoose.model('StreamFile', streamFileSchema);
104
+ StreamFile = StreamFileModel;
105
+ }
106
+
107
+ async function saveStreamFileRecord(data) {
108
+ const primaryId = data.file_unique_id || data.file_id || data.unique_id || data.fileId;
109
+ const normalized = {
110
+ ...data,
111
+ file_unique_id: primaryId,
112
+ file_id: primaryId,
113
+ unique_id: primaryId,
114
+ fileId: primaryId,
115
+ chat_id: data.chat_id || data.chatId,
116
+ chatId: data.chatId || data.chat_id,
117
+ message_id: data.message_id || data.messageId,
118
+ messageId: data.messageId || data.message_id,
119
+ file_name: data.file_name || data.fileName || 'media.mp4',
120
+ fileName: data.fileName || data.file_name || 'media.mp4',
121
+ file_size: data.file_size !== undefined ? data.file_size : (data.fileSize || 0),
122
+ fileSize: data.fileSize !== undefined ? data.fileSize : (data.file_size || 0),
123
+ mime_type: data.mime_type || data.mimeType || 'video/mp4',
124
+ mimeType: data.mimeType || data.mime_type || 'video/mp4',
125
+ poster: data.poster || '',
126
+ year: data.year || '',
127
+ rating: data.rating || '8.5',
128
+ overview: data.overview || '',
129
+ category: data.category || 'Movie',
130
+ episode: data.episode || '',
131
+ updatedAt: new Date()
132
+ };
133
+
134
+ inMemoryFiles.set(primaryId, normalized);
135
+ const model = StreamFile || StreamFileModel;
136
+ if (isMongoConnected && model) {
137
+ try {
138
+ return await model.findOneAndUpdate(
139
+ { $or: [ { file_unique_id: primaryId }, { file_id: primaryId } ] },
140
+ { $set: normalized },
141
+ { upsert: true, new: true }
142
+ );
143
+ } catch (e) {
144
+ console.error('MongoDB save error:', e.message);
145
+ }
146
+ }
147
+ return normalized;
148
+ }
149
+
150
+ async function getStreamFileRecord(fileId) {
151
+ if (!fileId) return null;
152
+ const idStr = String(fileId).trim();
153
+ const model = StreamFile || StreamFileModel;
154
+ if (isMongoConnected && model) {
155
+ try {
156
+ const fileRecord = await model.findOne({
157
+ $or: [
158
+ { file_unique_id: idStr },
159
+ { file_id: idStr },
160
+ { unique_id: idStr },
161
+ { fileId: idStr }
162
+ ]
163
+ }).lean();
164
+ if (fileRecord) return fileRecord;
165
+ } catch (e) {
166
+ console.error('MongoDB find error:', e.message);
167
+ }
168
+ }
169
+ return inMemoryFiles.get(idStr) || null;
170
+ }
171
+
172
+ function formatBytes(bytes, decimals = 2) {
173
+ if (!bytes || bytes === 0) return '0 Bytes';
174
+ const k = 1024;
175
+ const dm = decimals < 0 ? 0 : decimals;
176
+ const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
177
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
178
+ return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
179
+ }
180
+
181
+ // ---------------------------------------------------------------------------
182
+ // 2. GRAMJS TELEGRAM MTPROTO ENGINE (AUTO-INDEXER WITH WORKER URLs)
183
+ // ---------------------------------------------------------------------------
184
+ let tgClient = null;
185
+ let isGramJsConnected = false;
186
+
187
+ if (API_ID && API_HASH && BOT_TOKEN) {
188
+ try {
189
+ const stringSession = new StringSession(process.env.SESSION_STRING || "");
190
+ tgClient = new TelegramClient(stringSession, API_ID, API_HASH, {
191
+ connectionRetries: 10,
192
+ retryDelay: 1000,
193
+ autoReconnect: true,
194
+ useIPv6: false,
195
+ timeout: 30,
196
+ floodSleepThreshold: 60
197
+ });
198
+ } catch (initErr) {
199
+ console.warn('⚠️ TelegramClient init notice:', initErr.message);
200
+ }
201
+ }
202
+
203
+ if (tgClient && API_ID && API_HASH && BOT_TOKEN) {
204
+ (async () => {
205
+ try {
206
+ console.log('Connecting Telegram GramJS MTProto client...');
207
+ await tgClient.start({ botAuthToken: process.env.BOT_TOKEN });
208
+ isGramJsConnected = true;
209
+ console.log('✅ Telegram GramJS MTProto Client successfully authenticated!');
210
+
211
+ // 🟢 I-PRINT ANG SESSION STRING (Para makopya mo sa Railway)
212
+ try {
213
+ const savedSession = tgClient.session.save();
214
+ if (savedSession) {
215
+ console.log('🔑 SESSION_STRING MO (Kopyahin ito sa Railway):', savedSession);
216
+ }
217
+ } catch (_) {}
218
+
219
+ // 🟢 AUTO-CONNECT SA MGA STORAGE CHANNELS
220
+ const rawChannels = process.env.STORAGE_CHANNELS || '';
221
+ const STORAGE_CHANNELS = rawChannels
222
+ .split(',')
223
+ .map(id => id.trim())
224
+ .filter(Boolean);
225
+
226
+ if (STORAGE_CHANNELS.length > 0) {
227
+ console.log(`🔄 Kinokonekta ang ${STORAGE_CHANNELS.length} storage channels...`);
228
+ for (const chId of STORAGE_CHANNELS) {
229
+ try {
230
+ await tgClient.getInputEntity(chId);
231
+ console.log(`✅ Channel Connected & Cached: ${chId}`);
232
+ } catch (err) {
233
+ console.warn(`⚠️ Warning: Hindi ma-cache ang channel ${chId}:`, err.message);
234
+ }
235
+ }
236
+ }
237
+ // Keep Alive
238
+ setInterval(async () => {
239
+ if (tgClient && isGramJsConnected) {
240
+ try { await tgClient.getMe(); } catch (e) {}
241
+ }
242
+ }, 40000);
243
+
244
+ // Event Handler para sa Auto-Indexing ng Videos
245
+ tgClient.addEventHandler(async (event) => {
246
+ try {
247
+ const message = event.message;
248
+ if (!message) return;
249
+
250
+ // 🟢 1. BASAHIN ANG ADMIN IDS SA TAAS (Mababasa ng lahat)
251
+ const ADMIN_IDS = (process.env.ADMIN_ID || '').split(',').map(id => id.trim()).filter(Boolean);
252
+
253
+ const senderId = message.senderId ? message.senderId.toString() : '';
254
+ const peerChannelId = message.peerId?.channelId ? message.peerId.channelId.toString() : '';
255
+ const chatId = peerChannelId ? `-100${peerChannelId}` : (message.chatId ? message.chatId.toString() : '');
256
+ const messageId = message.id;
257
+ const isChannelPost = Boolean(peerChannelId);
258
+ const isSenderAdmin = ADMIN_IDS.includes(senderId) || ADMIN_IDS.includes(chatId);
259
+
260
+ // 🟢 1. COMMAND: /start (Private Chat Welcome)
261
+ if (!isChannelPost && message.message?.startsWith('/start')) {
262
+ if (ADMIN_IDS.length > 0 && !isSenderAdmin) {
263
+ await tgClient.sendMessage(chatId, {
264
+ message: `⛔ <b>Access Denied!</b>\n\nYour Telegram User ID: <code>${senderId}</code>\nAuthorized Admin ID: <code>${ADMIN_IDS.join(', ')}</code>`,
265
+ parseMode: 'html',
266
+ });
267
+ return;
268
+ }
269
+
270
+ await tgClient.sendMessage(chatId, {
271
+ message:
272
+ `🚀 <b>Welcome to PINOMAX MTProto Media Streaming & Downloader Engine!</b>
273
+
274
+ ⚡ <b>Bypasses the 20MB Bot API Limit</b> — Supports files up to <b>2GB</b>!
275
+
276
+ *✨ Key Features:*
277
+ • 📺 <b>HTTP 206 Partial Content Streaming</b>
278
+ • 📥 <b>Direct Attachment Downloader</b>
279
+ • 🎬 <b>Standalone Embed Video Player (with CC & Subtitles)</b>
280
+
281
+ 👉 <i>Mag-forward ng movie rito o mag-upload sa Channel para mag-auto index! Gamitin ang <b>/list</b> para makita ang mga uploaded movies.</i>`,
282
+ parseMode: 'html',
283
+ });
284
+ return;
285
+ }
286
+
287
+ // 🟢 2. COMMAND: /list (Ilista ang 10 pinakabagong uploaded movies)
288
+ if (!isChannelPost && message.message?.startsWith('/list')) {
289
+ try {
290
+ const model = StreamFile || StreamFileModel;
291
+ let files = [];
292
+ if (isMongoConnected && model) {
293
+ files = await model.find().sort({ createdAt: -1 }).limit(10).lean();
294
+ } else {
295
+ files = Array.from(inMemoryFiles.values()).slice(0, 10);
296
+ }
297
+
298
+ if (!files || files.length === 0) {
299
+ await tgClient.sendMessage(chatId, {
300
+ message: '📂 <b>Wala pang naka-save na movies sa database.</b>',
301
+ parseMode: 'html'
302
+ });
303
+ return;
304
+ }
305
+
306
+ let listText = '🎬 <b>Recent Uploaded Movies (PINOMAX):</b>\n\n';
307
+ files.forEach((f, idx) => {
308
+ const fId = f.file_unique_id || f.file_id || f.unique_id;
309
+ const embedUrl = `${WORKER_URL}/embed/${fId}`;
310
+ const title = f.file_name || f.fileName || 'Movie';
311
+ const size = formatBytes(f.file_size || f.fileSize || 0);
312
+ listText += `${idx + 1}. <b>${title}</b> (${size})\n`;
313
+ listText += ` 👉 <code>${embedUrl}</code>\n\n`;
314
+ });
315
+
316
+ await tgClient.sendMessage(chatId, {
317
+ message: listText,
318
+ parseMode: 'html'
319
+ });
320
+ } catch (err) {
321
+ console.error('List error:', err);
322
+ }
323
+ return;
324
+ }
325
+
326
+ // 🟢 3. MEDIA HANDLER (Video Auto-Indexer)
327
+ if (message.media && (message.media.document || message.media.video || message.file)) {
328
+ // Harangin ang ibang tao kapag nag-upload sa PM
329
+ if (!isChannelPost && ADMIN_IDS.length > 0 && !isSenderAdmin) {
330
+ return;
331
+ }
332
+
333
+ const doc = message.media.document || message.media;
334
+ const file = message.file;
335
+
336
+ let fileName = file?.name || '';
337
+ if (!fileName && doc?.attributes) {
338
+ const fnAttr = doc.attributes.find(a => a.className === 'DocumentAttributeFilename' || a.fileName);
339
+ if (fnAttr && fnAttr.fileName) fileName = fnAttr.fileName;
340
+ }
341
+ if (!fileName) fileName = `media_${messageId}.${file?.ext || 'mp4'}`;
342
+
343
+ const fileSize = Number(file?.size || doc?.size || 0);
344
+ const mimeType = file?.mimeType || doc?.mimeType || 'video/mp4';
345
+ const fileUniqueId = `${chatId.replace(/^-/, '')}_${messageId}`;
346
+ // 🛡️ HARANGIN ANG MGA KALAT NA FILES / INTRO TEST (< 5MB)
347
+ if (fileSize < 5 * 1024 * 1024) {
348
+ console.log(`⏩ Skipped junk/small media (${formatBytes(fileSize)}): ${fileName}`);
349
+ return; // Hindi ito ise-save sa database
350
+ }
351
+
352
+ let poster = '';
353
+ let year = '2024';
354
+ let rating = '8.5';
355
+ let overview = '';
356
+ let category = fileName.toLowerCase().includes('series') ? 'Series' : 'Movie';
357
+ let episode = '';
358
+
359
+ // ✅ SMART TMDB TITLE CLEANER & DUAL SEARCH
360
+ try {
361
+ // 1. Linisin ang mga kalat na tags, channel names, resolution, at underscores
362
+ let cleanTitle = fileName
363
+ .replace(/\.mp4|\.mkv|\.webm|\.avi/gi, '')
364
+ .replace(/@\w+/g, '') // Tanggalin ang @channel_name
365
+ .replace(/tagalog dubbed|tagdub|dubbed|pinoy|tagalog|full movie/gi, '')
366
+ .replace(/1080p|720p|480p|hdrip|bluray|web-dl|webrip|x264|x265|hevc/gi, '')
367
+ .replace(/[\(\)\[\]_\-\.]+/g, ' ') // Palitan ang _, -, at brackets ng space
368
+ .trim();
369
+
370
+ // 2. Hanapin kung may Taon (e.g. 2024, 2000, 1999)
371
+ const yearMatch = cleanTitle.match(/\b(19\d{2}|20\d{2})\b/);
372
+ let detectedYear = yearMatch ? yearMatch[1] : '';
373
+ if (detectedYear) {
374
+ cleanTitle = cleanTitle.replace(detectedYear, '').trim();
375
+ }
376
+
377
+ // 3. Unang Search sa TMDB (May Title + Year para eksakto)
378
+ let searchUrl = `https://api.themoviedb.org/3/search/multi?api_key=${TMDB_API_KEY}&query=${encodeURIComponent(cleanTitle)}${detectedYear ? '&year=' + detectedYear : ''}`;
379
+ let searchRes = await axios.get(searchUrl, { timeout: 4000 });
380
+
381
+ // 4. Fallback Search: Kung walang nahanap, mag-search uli gamit ang Title lang
382
+ if (!searchRes.data?.results?.length && detectedYear) {
383
+ searchUrl = `https://api.themoviedb.org/3/search/multi?api_key=${TMDB_API_KEY}&query=${encodeURIComponent(cleanTitle)}`;
384
+ searchRes = await axios.get(searchUrl, { timeout: 4000 });
385
+ }
386
+
387
+ if (searchRes.data?.results?.length > 0) {
388
+ const resItem = searchRes.data.results[0];
389
+ if (resItem.poster_path) {
390
+ poster = `https://image.tmdb.org/t/p/w500${resItem.poster_path}`;
391
+ }
392
+ year = (resItem.release_date || resItem.first_air_date || detectedYear || '').split('-')[0] || '2024';
393
+ rating = resItem.vote_average ? resItem.vote_average.toFixed(1) : '8.5';
394
+ overview = resItem.overview ? (resItem.overview.length > 120 ? resItem.overview.substring(0, 120) + '...' : resItem.overview) : '';
395
+ category = resItem.media_type === 'tv' ? 'Series' : 'Movie';
396
+ } else {
397
+ year = detectedYear || '2024';
398
+ }
399
+ } catch (_) {}
400
+
401
+
402
+
403
+ await saveStreamFileRecord({
404
+ chat_id: chatId.toString(),
405
+ message_id: Number(messageId),
406
+ file_name: fileName,
407
+ file_size: fileSize,
408
+ mime_type: mimeType,
409
+ poster,
410
+ year,
411
+ rating,
412
+ overview,
413
+ category,
414
+ episode,
415
+ unique_id: fileUniqueId,
416
+ uploadedBy: isChannelPost ? 'Channel Storage' : (senderId ? `@${senderId}` : 'Admin')
417
+ });
418
+
419
+ // I-cache agad ang media para ready sa streaming
420
+ telegramMediaCache.set(`${chatId}_${messageId}`, {
421
+ media: message.media,
422
+ size: fileSize,
423
+ mimeType,
424
+ timestamp: Date.now()
425
+ });
426
+
427
+ const streamUrl = `${WORKER_URL}/stream/${fileUniqueId}`;
428
+ const downloadUrl = `${WORKER_URL}/download/${fileUniqueId}?file=${encodeURIComponent(fileName)}`;
429
+ const embedUrl = `${WORKER_URL}/embed/${fileUniqueId}`;
430
+ const sizeFormatted = formatBytes(fileSize);
431
+
432
+ // 👉 FORMAT NA TUGMANG-TUGMA SA SCREENSHOT 1:
433
+ const replyHtml =
434
+ `🎬 <b>Media Successfully Indexed (2GB MTProto Engine)!</b>\n\n` +
435
+ `📁 <b>File Name:</b> ${fileName}\n` +
436
+ `📦 <b>File Size:</b> ${sizeFormatted}\n` +
437
+ `🏷️ <b>Source:</b> ${isChannelPost ? 'Channel Auto-Index' : 'Direct Upload'}\n` +
438
+ `🆔 <b>File ID:</b> ${fileUniqueId}\n\n` +
439
+ `━━━━━━━━━━━━━━━━━━━━\n` +
440
+ `📺 <b>Stream URL (HTTP 206):</b>\n` +
441
+ `${streamUrl}\n\n` +
442
+ `📥 <b>Direct Download URL:</b>\n` +
443
+ `${downloadUrl}\n\n` +
444
+ `🎬 <b>Cloudflare Cached Embed URL:</b>\n` +
445
+ `${embedUrl}\n` +
446
+ `━━━━━━━━━━━━━━━━━━━━`;
447
+
448
+ // 1. KUNG SA STORAGE CHANNEL KA NAG-UPLOAD O NAG-FORWARD:
449
+ if (isChannelPost) {
450
+ await tgClient.sendMessage(chatId, {
451
+ message: replyHtml,
452
+ replyTo: Number(messageId),
453
+ parseMode: 'html'
454
+ }).catch((e) => console.error('Channel send error:', e.message));
455
+
456
+ if (ADMIN_ID && chatId !== ADMIN_ID) {
457
+ await tgClient.sendMessage(ADMIN_ID, {
458
+ message: replyHtml,
459
+ parseMode: 'html'
460
+ }).catch((e) => console.error('Admin PM send error:', e.message));
461
+ }
462
+ }
463
+ // 2. KUNG DIRECT FORWARD MO SA PM NG BOT:
464
+ else {
465
+ await tgClient.sendMessage(chatId, {
466
+ message: replyHtml,
467
+ parseMode: 'html'
468
+ }).catch((e) => console.error('PM send error:', e.message));
469
+ }
470
+ }
471
+ } catch (err) {
472
+ console.error('Error in event handler:', err);
473
+ }
474
+ }, new NewMessage({}));
475
+
476
+ } catch (err) {
477
+ console.warn('⚠️ GramJS Error:', err.message);
478
+ }
479
+ })();
480
+ }
481
+
482
+ // ---------------------------------------------------------------------------
483
+ // 3. EXPRESS MIDDLEWARE CONFIGURATION
484
+ // ---------------------------------------------------------------------------
485
+ app.use(express.json());
486
+ app.use(express.urlencoded({ extended: true }));
487
+ app.use(cors());
488
+ app.use(helmet({ contentSecurityPolicy: false, crossOriginEmbedderPolicy: false }));
489
+ app.set('view engine', 'ejs');
490
+ app.set('views', path.join(__dirname, 'views'));
491
+ app.use(express.static(path.join(__dirname, 'public')));
492
+
493
+ app.use('/', subtitleRoutes);
494
+ // ---------------------------------------------------------------------------
495
+ // 4. FIREBASE VIP & PAYMENT APIS (TUGMA SA AdminDashboardActivity.java)
496
+ // ---------------------------------------------------------------------------
497
+ app.get('/api/vip/status/:uid', async (req, res) => {
498
+ const { uid } = req.params;
499
+ try {
500
+ const fb = await axios.get(`${FIREBASE_DATABASE_URL}/users/${uid}.json`);
501
+ const user = fb.data || {};
502
+ let isVip = user.isVip || false;
503
+ const expiry = user.vip_expiry || 0;
504
+
505
+ if (isVip && expiry > 0 && Date.now() > expiry) {
506
+ isVip = false;
507
+ await axios.patch(`${FIREBASE_DATABASE_URL}/users/${uid}.json`, { isVip: false });
508
+ }
509
+
510
+ return res.json({
511
+ isVip,
512
+ vip_expiry: expiry,
513
+ userName: user.name || user.user_name || 'User',
514
+ active_request: user.active_request || null
515
+ });
516
+ } catch (e) {
517
+ return res.json({ isVip: false });
518
+ }
519
+ });
520
+
521
+ app.post('/api/vip/submit-request', async (req, res) => {
522
+ const { uid, userName, planName, amount, method, refNumber } = req.body;
523
+ if (!uid || !refNumber) return res.status(400).json({ error: 'Kulang ang data' });
524
+
525
+ const timestamp = Date.now();
526
+ const dateStr = new Date(timestamp).toLocaleString('en-PH', {
527
+ timeZone: 'Asia/Manila',
528
+ month: 'short',
529
+ day: '2-digit',
530
+ year: 'numeric',
531
+ hour: '2-digit',
532
+ minute: '2-digit',
533
+ hour12: true
534
+ });
535
+
536
+ const payload = {
537
+ uid: String(uid).trim(),
538
+ name: String(userName || 'Telegram User').trim(),
539
+ userName: String(userName || 'Telegram User').trim(),
540
+ plan: String(planName || 'VIP Access').trim(),
541
+ amount: String(amount || '5').trim(),
542
+ ref_number: String(refNumber).trim(),
543
+ ref: String(refNumber).trim(),
544
+ method: String(method || 'GCASH').toUpperCase().trim(),
545
+ status: 'pending',
546
+ date: dateStr,
547
+ createdAt: timestamp
548
+ };
549
+
550
+ try {
551
+ // 1. I-save sa user profile (active_request)
552
+ await axios.put(`${FIREBASE_DATABASE_URL}/users/${uid}/active_request.json`, payload);
553
+
554
+ // 2. I-save sa "requests" node (Para sa AdminDashboardActivity.java)
555
+ const reqKey = `REQ_${uid}_${timestamp}`;
556
+ await axios.put(`${FIREBASE_DATABASE_URL}/requests/${reqKey}.json`, payload);
557
+
558
+ // 3. TELEGRAM ALERT SA ADMIN PM KAPAG MAY NAG-SUBMIT
559
+ if (tgClient && ADMIN_ID && isGramJsConnected) {
560
+ try {
561
+ await tgClient.sendMessage(ADMIN_ID, {
562
+ message:
563
+ `💰 <b>BAGONG BAYAD / DONATE SUBMISSION!</b>\n\n` +
564
+ `👤 <b>User:</b> <code>${userName}</code> (ID: <code>${uid}</code>)\n` +
565
+ `👑 <b>Plan:</b> <code>${planName}</code>\n` +
566
+ `💵 <b>Amount:</b> ₱${amount}\n` +
567
+ `💳 <b>Method:</b> <code>${method}</code>\n` +
568
+ `🔢 <b>Ref No.:</b> <code>${refNumber}</code>\n\n` +
569
+ `👉 <i>Buksan ang Admin Dashboard App para i-Approve!</i>`,
570
+ parseMode: 'html'
571
+ });
572
+ } catch (_) {}
573
+ }
574
+
575
+ return res.json({ success: true, message: 'Naisumite sa Admin!' });
576
+ } catch (e) {
577
+ return res.status(500).json({ error: 'Error sa database' });
578
+ }
579
+ });
580
+
581
+ app.get('/api/payment-config', (req, res) => {
582
+ res.json(PAYMENT_CONFIG);
583
+ });
584
+
585
+ app.get('/stream/:fileId', async (req, res) => {
586
+ const fileId = req.params.fileId;
587
+ const rec = await getStreamFileRecord(fileId);
588
+
589
+ if (!rec) {
590
+ console.error(`❌ Stream Failed: File record not found in MongoDB for ID: ${fileId}`);
591
+ return res.redirect('https://vjs.zencdn.net/v/oceans.mp4');
592
+ }
593
+
594
+ if (!tgClient || !isGramJsConnected) {
595
+ console.error('❌ Stream Failed: Telegram MTProto Client not connected');
596
+ return res.redirect('https://vjs.zencdn.net/v/oceans.mp4');
597
+ }
598
+
599
+ try {
600
+ let peer = rec.chat_id || rec.chatId;
601
+
602
+ // 🟢 RESOLVE TELEGRAM PEER PARA SA LAHAT NG STORAGE CHANNELS
603
+ let targetEntity;
604
+ try {
605
+ targetEntity = await tgClient.getInputEntity(peer);
606
+ } catch (resolveErr) {
607
+ if (typeof peer === 'string' && peer.startsWith('-100')) {
608
+ peer = bigInt(peer.replace('-100', ''));
609
+ }
610
+ targetEntity = await tgClient.getInputEntity(peer);
611
+ }
612
+
613
+ const msgIdNum = Number(rec.message_id || rec.messageId);
614
+ const cacheKey = `${rec.chat_id}_${msgIdNum}`;
615
+ let mediaObj = null;
616
+ let totalSize = Number(rec.file_size || rec.fileSize || 0);
617
+
618
+ // 🟢 1. FAST MEMORY CACHE
619
+ if (telegramMediaCache.has(cacheKey)) {
620
+ const cached = telegramMediaCache.get(cacheKey);
621
+ mediaObj = cached.media;
622
+ if (cached.size) totalSize = cached.size;
623
+ } else {
624
+ const msgs = await tgClient.getMessages(targetEntity, { ids: [msgIdNum] });
625
+ const msg = msgs && msgs[0];
626
+
627
+ if (!msg || !msg.media) {
628
+ console.error(`❌ Stream Failed: Message not found in Telegram (Channel: ${peer}, Msg ID: ${msgIdNum})`);
629
+ return res.redirect('https://vjs.zencdn.net/v/oceans.mp4');
630
+ }
631
+
632
+ mediaObj = msg.media;
633
+ totalSize = Number(msg.file?.size || totalSize);
634
+
635
+ telegramMediaCache.set(cacheKey, {
636
+ media: mediaObj,
637
+ size: totalSize,
638
+ mimeType: rec.mime_type || 'video/mp4',
639
+ timestamp: Date.now()
640
+ });
641
+ }
642
+
643
+ const range = req.headers.range;
644
+ let start = 0;
645
+ let end = totalSize - 1;
646
+
647
+ const cacheHeaders = {
648
+ 'Cache-Control': 'public, max-age=2592000, s-maxage=2592000, immutable',
649
+ 'CDN-Cache-Control': 'max-age=2592000',
650
+ 'Cloudflare-CDN-Cache-Control': 'max-age=2592000',
651
+ 'Access-Control-Allow-Origin': '*',
652
+ 'Accept-Ranges': 'bytes'
653
+ };
654
+
655
+ // 🟢 2. STANDARD HTTP 206
656
+ if (range) {
657
+ const parts = range.replace(/bytes=/, '').split('-');
658
+ start = parseInt(parts[0], 10);
659
+ if (parts[1]) {
660
+ end = parseInt(parts[1], 10);
661
+ }
662
+ res.writeHead(206, {
663
+ ...cacheHeaders,
664
+ 'Content-Range': `bytes ${start}-${end}/${totalSize}`,
665
+ 'Content-Length': (end - start) + 1,
666
+ 'Content-Type': rec.mime_type || 'video/mp4'
667
+ });
668
+ } else {
669
+ res.writeHead(200, {
670
+ ...cacheHeaders,
671
+ 'Content-Length': totalSize,
672
+ 'Content-Type': rec.mime_type || 'video/mp4'
673
+ });
674
+ }
675
+
676
+ // 🟢 3. STREAMING CHUNKS (1MB CHUNK)
677
+ const stream = tgClient.iterDownload({
678
+ file: mediaObj,
679
+ offset: bigInt(start),
680
+ limit: (end - start) + 1,
681
+ requestSize: 1024 * 1024
682
+ });
683
+
684
+ let closed = false;
685
+ req.on('close', () => {
686
+ closed = true;
687
+ });
688
+
689
+ for await (const chunk of stream) {
690
+ if (closed) break;
691
+ res.write(chunk);
692
+ }
693
+ if (!closed) res.end();
694
+
695
+ } catch (e) {
696
+ console.error('❌ Stream Route Critical Error:', e.message);
697
+ if (!res.headersSent) res.redirect('https://vjs.zencdn.net/v/oceans.mp4');
698
+ }
699
+ });
700
+
701
+ // DIRECT ATTACHMENT DOWNLOADER (VIP ONLY)
702
+ app.get('/download/:fileId', async (req, res) => {
703
+ const fileId = req.params.fileId;
704
+
705
+ // ⛔ HARANGIN ANG DIRECT LINK KUNG HINDI VIP:
706
+ const isVip = req.query.vip === '1';
707
+ if (!isVip) {
708
+ return res.status(403).send('<h1 style="color:red;text-align:center;margin-top:50px;font-family:sans-serif;">⛔ 403 Forbidden: VIP Only Download Feature</h1>');
709
+ }
710
+
711
+ const rec = await getStreamFileRecord(fileId);
712
+ if (!rec || !tgClient || !isGramJsConnected) {
713
+ return res.redirect('https://vjs.zencdn.net/v/oceans.mp4');
714
+ }
715
+
716
+ try {
717
+ let peer = rec.chat_id;
718
+ if (typeof peer === 'string' && peer.startsWith('-100')) {
719
+ peer = bigInt(peer.replace('-100', ''));
720
+ }
721
+ const msgs = await tgClient.getMessages(peer, { ids: [Number(rec.message_id)] });
722
+ const msg = msgs && msgs[0];
723
+ if (!msg || !msg.media) return res.redirect('https://vjs.zencdn.net/v/oceans.mp4');
724
+
725
+ const totalSize = Number(msg.file?.size || rec.file_size || 0);
726
+ const fileName = rec.file_name || rec.fileName || `media_${fileId}.mp4`;
727
+ const cleanFileName = encodeURIComponent(fileName);
728
+
729
+ res.writeHead(200, {
730
+ 'Content-Length': totalSize,
731
+ 'Content-Type': 'application/octet-stream',
732
+ 'Content-Disposition': `attachment; filename="${cleanFileName}"; filename*=UTF-8''${cleanFileName}`,
733
+ 'Access-Control-Allow-Origin': '*'
734
+ });
735
+
736
+ const stream = tgClient.iterDownload({
737
+ file: msg.media,
738
+ offset: bigInt(0),
739
+ limit: totalSize,
740
+ requestSize: 1024 * 1024
741
+ });
742
+
743
+ let closed = false;
744
+ req.on('close', () => { closed = true; });
745
+ for await (const chunk of stream) {
746
+ if (closed) break;
747
+ res.write(chunk);
748
+ }
749
+ if (!closed) res.end();
750
+ } catch (e) {
751
+ if (!res.headersSent) res.status(500).send('Download Error: ' + e.message);
752
+ }
753
+ });
754
+
755
+ app.get('/embed/:fileId', async (req, res) => {
756
+ const { fileId } = req.params;
757
+ const rec = await getStreamFileRecord(fileId) || { file_name: 'Pinomax Video' };
758
+ const streamUrl = `${WORKER_URL}/stream/${fileId}`;
759
+ const downloadUrl = `${WORKER_URL}/download/${fileId}`;
760
+ const movieTitle = rec.file_name || rec.fileName || 'Movie';
761
+
762
+ res.render('embed_player', {
763
+ streamUrl: streamUrl,
764
+ downloadUrl: downloadUrl,
765
+ title: movieTitle,
766
+ poster: rec.poster || ''
767
+ });
768
+ });
769
+
770
+ // ---------------------------------------------------------------------------
771
+ // 7. CATALOG ROUTE (PARA SA MINI APP & WEB)
772
+ // ---------------------------------------------------------------------------
773
+ app.get(['/', '/newapp', '/pinomax'], async (req, res) => {
774
+ res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0');
775
+ res.setHeader('Pragma', 'no-cache');
776
+ res.setHeader('Expires', '0');
777
+
778
+ try {
779
+ let movies = [];
780
+ const model = StreamFile || StreamFileModel;
781
+ if (isMongoConnected && model) {
782
+ movies = await model.find().sort({ createdAt: -1 }).limit(100).lean();
783
+ } else {
784
+ movies = Array.from(inMemoryFiles.values());
785
+ }
786
+
787
+ const q = (req.query.q || '').trim().toLowerCase();
788
+ let filtered = movies;
789
+ if (q) {
790
+ filtered = movies.filter(m => (m.file_name || m.fileName || '').toLowerCase().includes(q));
791
+ }
792
+
793
+ res.render('index', {
794
+ movies: filtered.map(m => ({
795
+ id: m.file_unique_id || m.file_id || m.unique_id,
796
+ title: m.file_name || m.fileName || 'Movie',
797
+ image: m.poster || '',
798
+ rating: m.rating || '8.5',
799
+ year: m.year || '2024',
800
+ genre: m.category || 'Movie',
801
+ size: formatBytes(m.file_size || m.fileSize || 0)
802
+ })),
803
+ totalCount: movies.length,
804
+ searchQuery: req.query.q || '',
805
+ paymentConfig: PAYMENT_CONFIG
806
+ });
807
+ } catch (err) {
808
+ res.render('index', { movies: [], totalCount: 0, searchQuery: '', paymentConfig: PAYMENT_CONFIG });
809
+ }
810
+ });
811
+
812
+ // ---------------------------------------------------------------------------
813
+ // 8. SUBTITLE SCRAPER & IN-MEMORY UNZIPPER (SUBDL)
814
+ // ---------------------------------------------------------------------------
815
+ app.get('/api/subtitles/:query', async (req, res) => {
816
+ let { query } = req.params;
817
+ if (!query || query === 'undefined') {
818
+ return res.json({ success: false, subtitles: [] });
819
+ }
820
+
821
+ try {
822
+ let tmdbId = query;
823
+
824
+ if (isNaN(Number(query))) {
825
+ const cleanTitle = query
826
+ .replace(/\.mp4|\.mkv|\.webm/gi, '')
827
+ .replace(/tagalog dubbed|tagdub|dubbed|1080p|720p|hd/gi, '')
828
+ .replace(/[\(\)\[\]]/g, '')
829
+ .trim();
830
+
831
+ const searchUrl = `https://api.themoviedb.org/3/search/movie?api_key=${TMDB_API_KEY}&query=${encodeURIComponent(cleanTitle)}`;
832
+ const searchRes = await axios.get(searchUrl, { timeout: 6000 });
833
+ if (searchRes.data?.results?.length > 0) {
834
+ tmdbId = searchRes.data.results[0].id;
835
+ } else {
836
+ return res.json({ success: false, subtitles: [] });
837
+ }
838
+ }
839
+
840
+ const subdlKey = "subdl_NMbBKczp6Un1tAIRELW0fR0F2lLPbCFbsDxn0MwUK8Q";
841
+ const subdlUrl = `https://api.subdl.com/api/v1/subtitles?api_key=${subdlKey}&tmdb_id=${tmdbId}&languages=tl,en`;
842
+
843
+ const subRes = await axios.get(subdlUrl, {
844
+ headers: { 'User-Agent': 'Mozilla/5.0 (Linux; Android 10; K)' },
845
+ timeout: 8000
846
+ });
847
+
848
+ const subtitlesData = subRes.data?.subtitles || [];
849
+ const formatted = subtitlesData.map(sub => {
850
+ const isTag = (sub.lang || sub.language || '').toLowerCase().includes('tag') || (sub.lang || '').toLowerCase().includes('tl') || (sub.lang || '').toLowerCase().includes('fil');
851
+ const rawUrl = sub.url.startsWith('/') ? `https://dl.subdl.com${sub.url}` : sub.url;
852
+ const release = sub.release_name ? sub.release_name.substring(0, 16) : 'HD';
853
+
854
+ return {
855
+ name: isTag ? `🇵🇭 Tagalog (${release})` : `🇬🇧 English (${release})`,
856
+ url: `/api/sub-content?url=${encodeURIComponent(rawUrl)}`,
857
+ type: 'vtt'
858
+ };
859
+ });
860
+
861
+ res.json({ success: formatted.length > 0, subtitles: formatted, tmdbId });
862
+ } catch (err) {
863
+ res.json({ success: false, subtitles: [] });
864
+ }
865
+ });
866
+
867
+ app.get('/api/sub-content', async (req, res) => {
868
+ const targetUrl = req.query.url;
869
+ if (!targetUrl) return res.status(400).send('URL required');
870
+
871
+ try {
872
+ const response = await axios.get(targetUrl, {
873
+ responseType: 'arraybuffer',
874
+ headers: {
875
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
876
+ 'Accept': '*/*'
877
+ },
878
+ maxRedirects: 5,
879
+ timeout: 12000
880
+ });
881
+
882
+ let srtText = '';
883
+ const buffer = Buffer.from(response.data);
884
+
885
+ // 1. KUNG ZIP FILE ANG SUBTITLE:
886
+ if (targetUrl.toLowerCase().includes('.zip') || (buffer[0] === 0x50 && buffer[1] === 0x4B)) {
887
+ const zip = new AdmZip(buffer);
888
+ const zipEntries = zip.getEntries();
889
+
890
+ // 🛡️ Alisin ang macOS hidden files at kunin ang totoong .srt o .vtt:
891
+ const validEntries = zipEntries.filter(e => !e.isDirectory && !e.entryName.includes('__MACOSX'));
892
+ const srtEntry = validEntries.find(e => e.entryName.toLowerCase().endsWith('.srt') || e.entryName.toLowerCase().endsWith('.vtt')) || validEntries[0];
893
+
894
+ if (srtEntry) {
895
+ srtText = srtEntry.getData().toString('utf8');
896
+ } else {
897
+ return res.status(404).send('No valid subtitle found inside zip');
898
+ }
899
+ } else {
900
+ srtText = buffer.toString('utf8');
901
+ }
902
+
903
+ // 2. LINISIN ANG BOM AT I-CONVERT SA WEBVTT:
904
+ srtText = srtText.replace(/^\uFEFF/, '').trim(); // Tanggalin ang invisible BOM error
905
+
906
+ if (!srtText.startsWith('WEBVTT')) {
907
+ // Palitan ang comma (,) ng tuldok (.) para sa tamang VTT timestamp
908
+ srtText = 'WEBVTT\n\n' + srtText.replace(/(\d{2}:\d{2}:\d{2}),(\d{3})/g, '$1.$2');
909
+ }
910
+
911
+ res.writeHead(200, {
912
+ 'Content-Type': 'text/vtt; charset=utf-8',
913
+ 'Access-Control-Allow-Origin': '*',
914
+ 'Access-Control-Allow-Headers': '*',
915
+ 'Cache-Control': 'public, max-age=86400'
916
+ });
917
+ res.end(srtText);
918
+ } catch (err) {
919
+ console.error('Subtitle parse error:', err.message);
920
+ res.status(500).send('Failed to process subtitle');
921
+ }
922
+ });
923
+
924
+ // ---------------------------------------------------------------------------
925
+ // 9. RENDER KEEP-ALIVE PINGER
926
+ // ---------------------------------------------------------------------------
927
+ app.get('/ping', (req, res) => {
928
+ res.status(200).json({ status: 'OK', uptime: process.uptime() });
929
+ });
930
+
931
+ setInterval(async () => {
932
+ try {
933
+ await axios.get(`${APP_URL}/ping`, { timeout: 8000 });
934
+ } catch (_) {}
935
+ }, 10 * 60 * 1000);
936
+
937
+ // ---------------------------------------------------------------------------
938
+ // 🛠️ 1-CLICK POSTER & RESOLUTION AUTO-FIXER PARA SA LAHAT NG LUMANG MOVIES
939
+ // ---------------------------------------------------------------------------
940
+ app.get('/api/admin/fix-posters', async (req, res) => {
941
+ try {
942
+ const model = StreamFile || StreamFileModel;
943
+ if (!isMongoConnected || !model) {
944
+ return res.status(500).send('Database not connected.');
945
+ }
946
+
947
+ const allFiles = await model.find();
948
+ let updatedCount = 0;
949
+
950
+ for (const file of allFiles) {
951
+ const fileName = file.file_name || file.fileName || '';
952
+ if (!fileName) continue;
953
+
954
+ // 1. I-detect ang Resolution (4K, 1080p, 720p, 480p)
955
+ let quality = '1080P FHD';
956
+ if (/4k|2160p|uhd/i.test(fileName)) quality = '4K UHD';
957
+ else if (/1080p|fhd/i.test(fileName)) quality = '1080P FHD';
958
+ else if (/720p|hd/i.test(fileName)) quality = '720P HD';
959
+ else if (/480p|sd/i.test(fileName)) quality = '480P SD';
960
+
961
+ // 2. Linisin ang Title mula sa kalat at resolution
962
+ let cleanTitle = fileName
963
+ .replace(/\.mp4|\.mkv|\.webm|\.avi/gi, '')
964
+ .replace(/@\w+/g, '')
965
+ .replace(/4k|2160p|1080p|720p|480p|uhd|fhd|hdrip|bluray|web-dl|webrip|x264|x265|hevc/gi, '')
966
+ .replace(/tagalog dubbed|tagdub|dubbed|pinoy|tagalog|full movie/gi, '')
967
+ .replace(/[\(\)\[\]_\-\.]+/g, ' ')
968
+ .trim();
969
+
970
+ const yearMatch = cleanTitle.match(/\b(19\d{2}|20\d{2})\b/);
971
+ let detectedYear = yearMatch ? yearMatch[1] : '';
972
+ if (detectedYear) {
973
+ cleanTitle = cleanTitle.replace(detectedYear, '').trim();
974
+ }
975
+
976
+ // 3. Search sa TMDB
977
+ let poster = file.poster || '';
978
+ let rating = file.rating || '8.5';
979
+ let year = file.year || detectedYear || '2024';
980
+ let overview = file.overview || '';
981
+
982
+ try {
983
+ let searchUrl = `https://api.themoviedb.org/3/search/multi?api_key=${TMDB_API_KEY}&query=${encodeURIComponent(cleanTitle)}${detectedYear ? '&year=' + detectedYear : ''}`;
984
+ let searchRes = await axios.get(searchUrl, { timeout: 4000 });
985
+
986
+ if (!searchRes.data?.results?.length && detectedYear) {
987
+ searchUrl = `https://api.themoviedb.org/3/search/multi?api_key=${TMDB_API_KEY}&query=${encodeURIComponent(cleanTitle)}`;
988
+ searchRes = await axios.get(searchUrl, { timeout: 4000 });
989
+ }
990
+
991
+ if (searchRes.data?.results?.length > 0) {
992
+ const resItem = searchRes.data.results[0];
993
+ if (resItem.poster_path) {
994
+ poster = `https://image.tmdb.org/t/p/w500${resItem.poster_path}`;
995
+ }
996
+ year = (resItem.release_date || resItem.first_air_date || detectedYear || '').split('-')[0] || year;
997
+ rating = resItem.vote_average ? resItem.vote_average.toFixed(1) : rating;
998
+ overview = resItem.overview ? (resItem.overview.length > 120 ? resItem.overview.substring(0, 120) + '...' : resItem.overview) : overview;
999
+ }
1000
+ } catch (_) {}
1001
+
1002
+ // 4. I-save pabalik sa MongoDB Atlas
1003
+ await model.updateOne(
1004
+ { _id: file._id },
1005
+ {
1006
+ $set: {
1007
+ poster,
1008
+ rating,
1009
+ year,
1010
+ overview,
1011
+ episode: quality // I-save ang resolution badge
1012
+ }
1013
+ }
1014
+ );
1015
+ updatedCount++;
1016
+ }
1017
+
1018
+ res.send(`<h1>✅ Tagumpay! Na-update ang ${updatedCount} na pelikula!</h1><p>Bumalik sa <a href="/">Homepage</a> para makita ang mga bagong HD posters.</p>`);
1019
+ } catch (err) {
1020
+ res.status(500).send('Auto-Fix Error: ' + err.message);
1021
+ }
1022
+ });
1023
+
1024
+ // ===========================================================================
1025
+ // 🛡️ SECRET ADMIN PANEL & CRUD API
1026
+ // ===========================================================================
1027
+
1028
+ // 🟢 1. API: Kunin ang listahan ng lahat ng movies
1029
+ app.get('/api/admin/all-movies', async (req, res) => {
1030
+ try {
1031
+ const model = StreamFile || StreamFileModel;
1032
+ let movies = [];
1033
+ if (mongoose.connection.readyState === 1 && model) {
1034
+ movies = await model.find().sort({ createdAt: -1 }).maxTimeMS(5000).lean();
1035
+ } else {
1036
+ movies = Array.from(inMemoryFiles.values());
1037
+ }
1038
+ return res.json({ success: true, movies: movies || [] });
1039
+ } catch (err) {
1040
+ console.error('Admin API error:', err);
1041
+ return res.json({ success: true, movies: Array.from(inMemoryFiles.values()) });
1042
+ }
1043
+ });
1044
+
1045
+ // 🟢 2. API: I-save ang edited movie details
1046
+ app.post('/api/admin/update-movie', async (req, res) => {
1047
+ try {
1048
+ const { id, file_name, poster, year, rating, category, overview, episode } = req.body;
1049
+ if (!id) return res.status(400).json({ error: 'Kulang ang ID' });
1050
+
1051
+ const model = StreamFile || StreamFileModel;
1052
+ const updateData = {
1053
+ file_name,
1054
+ fileName: file_name,
1055
+ poster,
1056
+ year,
1057
+ rating,
1058
+ category,
1059
+ overview,
1060
+ episode
1061
+ };
1062
+
1063
+ if (mongoose.connection.readyState === 1 && model) {
1064
+ await model.findOneAndUpdate(
1065
+ { $or: [{ file_unique_id: id }, { file_id: id }, { unique_id: id }] },
1066
+ { $set: updateData }
1067
+ );
1068
+ }
1069
+
1070
+ if (inMemoryFiles.has(id)) {
1071
+ const existing = inMemoryFiles.get(id);
1072
+ inMemoryFiles.set(id, { ...existing, ...updateData });
1073
+ }
1074
+
1075
+ return res.json({ success: true, message: 'Na-update nang matagumpay!' });
1076
+ } catch (err) {
1077
+ return res.status(500).json({ success: false, error: err.message });
1078
+ }
1079
+ });
1080
+
1081
+ // 🟢 3. API: Mag-delete ng Movie
1082
+ app.delete('/api/admin/delete-movie/:id', async (req, res) => {
1083
+ try {
1084
+ const { id } = req.params;
1085
+ const model = StreamFile || StreamFileModel;
1086
+
1087
+ if (mongoose.connection.readyState === 1 && model) {
1088
+ await model.deleteOne({
1089
+ $or: [{ file_unique_id: id }, { file_id: id }, { unique_id: id }]
1090
+ });
1091
+ }
1092
+ inMemoryFiles.delete(id);
1093
+
1094
+ return res.json({ success: true, message: 'Movie deleted!' });
1095
+ } catch (err) {
1096
+ return res.status(500).json({ success: false, error: err.message });
1097
+ }
1098
+ });
1099
+
1100
+ // 🟢 4. SECRET ADMIN DASHBOARD WEB UI
1101
+ app.get('/secret-admin-portal', (req, res) => {
1102
+ res.send(`<!DOCTYPE html>
1103
+ <html lang="tl">
1104
+ <head>
1105
+ <meta charset="UTF-8">
1106
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
1107
+ <title>PINOMAX Admin Manager</title>
1108
+ <style>
1109
+ :root {
1110
+ --bg: #0c0d14;
1111
+ --card-bg: #161824;
1112
+ --accent: #e50914;
1113
+ --text: #f0f2f5;
1114
+ --text-muted: #8c93a8;
1115
+ --border: #23273a;
1116
+ --input-bg: #090a0f;
1117
+ }
1118
+ * { margin:0; padding:0; box-sizing:border-box; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; }
1119
+ body { background: var(--bg); color: var(--text); padding: 16px; }
1120
+
1121
+ .header {
1122
+ display: flex; justify-content: space-between; align-items: center;
1123
+ flex-wrap: wrap; gap: 12px; margin-bottom: 20px;
1124
+ padding-bottom: 12px; border-bottom: 1px solid var(--border);
1125
+ }
1126
+ .search-box {
1127
+ padding: 10px 14px; background: var(--card-bg); border: 1px solid var(--border);
1128
+ border-radius: 8px; color: #fff; width: 260px; max-width: 100%; outline: none; font-size: 13px;
1129
+ }
1130
+
1131
+ .grid {
1132
+ display: grid;
1133
+ grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
1134
+ gap: 14px;
1135
+ }
1136
+ .movie-card {
1137
+ background: var(--card-bg); border-radius: 10px; border: 1px solid var(--border);
1138
+ overflow: hidden; display: flex; flex-direction: column;
1139
+ }
1140
+ .card-top { display: flex; gap: 12px; padding: 12px; }
1141
+ .card-poster {
1142
+ width: 70px; height: 100px; border-radius: 6px; object-fit: cover;
1143
+ background: #222; flex-shrink: 0;
1144
+ }
1145
+ .card-info { flex: 1; overflow: hidden; }
1146
+ .card-title { font-size: 13px; font-weight: bold; margin-bottom: 4px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; color:#fff; }
1147
+ .card-id { font-size: 10px; font-family: monospace; color: #ff7b7b; margin-bottom: 4px; }
1148
+ .badge {
1149
+ display: inline-block; font-size: 9px; padding: 2px 6px; border-radius: 4px;
1150
+ background: #2a2e45; color: #8cb4ff; margin-right: 4px; font-weight: 600;
1151
+ }
1152
+ .badge-star { background: #3d3000; color: #ffd700; }
1153
+ .card-overview {
1154
+ font-size: 11px; color: var(--text-muted); margin-top: 6px;
1155
+ display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden;
1156
+ }
1157
+ .card-actions {
1158
+ display: flex; border-top: 1px solid var(--border); background: rgba(0,0,0,0.25);
1159
+ }
1160
+ .card-actions button {
1161
+ flex: 1; padding: 10px; background: transparent; border: none;
1162
+ color: #fff; font-size: 12px; font-weight: bold; cursor: pointer;
1163
+ }
1164
+ .btn-edit { color: #58a6ff !important; border-right: 1px solid var(--border); }
1165
+ .btn-delete { color: #f85149 !important; }
1166
+
1167
+ #editModal {
1168
+ position: fixed; inset: 0; background: rgba(0,0,0,0.85);
1169
+ display: none; align-items: center; justify-content: center; z-index: 1000; padding: 15px;
1170
+ }
1171
+ .modal-content {
1172
+ background: var(--card-bg); border-radius: 12px; width: 100%; max-width: 480px;
1173
+ max-height: 90vh; overflow-y: auto; padding: 20px; border: 1px solid var(--border);
1174
+ }
1175
+ .form-group { margin-bottom: 10px; }
1176
+ .form-group label { display: block; font-size: 11px; color: var(--text-muted); margin-bottom: 3px; }
1177
+ .form-group input, .form-group textarea, .form-group select {
1178
+ width: 100%; padding: 8px 10px; background: var(--input-bg); border: 1px solid var(--border);
1179
+ border-radius: 6px; color: #fff; font-size: 12px; outline: none;
1180
+ }
1181
+ .modal-buttons { display: flex; gap: 10px; margin-top: 15px; }
1182
+ .modal-buttons button { flex: 1; padding: 10px; border-radius: 6px; border: none; font-weight: bold; cursor: pointer; }
1183
+ .btn-save { background: var(--accent); color: #fff; }
1184
+ .btn-cancel { background: #30363d; color: #fff; }
1185
+ </style>
1186
+ </head>
1187
+ <body>
1188
+
1189
+ <div class="header">
1190
+ <div>
1191
+ <h1 style="font-size:20px; font-weight:900; color:var(--accent);">🎬 PINOMAX Media Manager</h1>
1192
+ <span id="totalBadge" style="font-size:12px; color:var(--text-muted);">Kinukuha ang database...</span>
1193
+ </div>
1194
+ <div style="display:flex; gap:8px;">
1195
+ <input type="text" class="search-box" id="searchInput" placeholder="🔍 Maghanap..." oninput="renderMovies()" />
1196
+ <button onclick="loadMovies()" style="padding:0 12px; background:#21262d; border:1px solid var(--border); color:#fff; border-radius:8px; cursor:pointer; font-size:12px;">🔄 Refresh</button>
1197
+ </div>
1198
+ </div>
1199
+
1200
+ <div class="grid" id="moviesContainer"></div>
1201
+
1202
+ <!-- EDIT MODAL -->
1203
+ <div id="editModal">
1204
+ <div class="modal-content">
1205
+ <h3 style="margin-bottom:12px; color:var(--accent); font-size:16px;">✏️ Edit Movie</h3>
1206
+
1207
+ <div class="form-group">
1208
+ <label>File ID:</label>
1209
+ <input type="text" id="editId" disabled style="opacity:0.5;" />
1210
+ </div>
1211
+
1212
+ <div class="form-group">
1213
+ <label>Title / File Name:</label>
1214
+ <div style="display:flex; gap:6px;">
1215
+ <input type="text" id="editTitle" />
1216
+ <button type="button" onclick="fetchTMDB()" style="padding:0 10px; background:#238636; border:none; border-radius:6px; color:#fff; font-size:11px; cursor:pointer;">TMDB</button>
1217
+ </div>
1218
+ </div>
1219
+
1220
+ <div class="form-group">
1221
+ <label>Poster URL:</label>
1222
+ <input type="text" id="editPoster" />
1223
+ </div>
1224
+
1225
+ <div style="display:flex; gap:8px;">
1226
+ <div class="form-group" style="flex:1;">
1227
+ <label>Year:</label>
1228
+ <input type="text" id="editYear" />
1229
+ </div>
1230
+ <div class="form-group" style="flex:1;">
1231
+ <label>Rating:</label>
1232
+ <input type="text" id="editRating" />
1233
+ </div>
1234
+ </div>
1235
+
1236
+ <div class="form-group">
1237
+ <label>Category:</label>
1238
+ <select id="editCategory">
1239
+ <option value="Movie">Movie</option>
1240
+ <option value="Series">Series</option>
1241
+ </select>
1242
+ </div>
1243
+
1244
+ <div class="form-group">
1245
+ <label>Overview:</label>
1246
+ <textarea id="editOverview" rows="3"></textarea>
1247
+ </div>
1248
+
1249
+ <div class="modal-buttons">
1250
+ <button class="btn-cancel" onclick="closeModal()">Kansela</button>
1251
+ <button class="btn-save" onclick="saveMovie()">I-save</button>
1252
+ </div>
1253
+ </div>
1254
+ </div>
1255
+
1256
+ <script>
1257
+ var allMovies = [];
1258
+
1259
+ window.addEventListener('DOMContentLoaded', loadMovies);
1260
+
1261
+ function loadMovies() {
1262
+ document.getElementById('totalBadge').innerText = 'Kinukuha ang mga pelikula...';
1263
+ fetch('/api/admin/all-movies')
1264
+ .then(function(res) { return res.json(); })
1265
+ .then(function(data) {
1266
+ allMovies = data.movies || [];
1267
+ document.getElementById('totalBadge').innerText = 'Kabuuang Pelikula: ' + allMovies.length;
1268
+ renderMovies();
1269
+ })
1270
+ .catch(function(err) {
1271
+ document.getElementById('totalBadge').innerText = 'Error: Hindi ma-load ang database';
1272
+ });
1273
+ }
1274
+
1275
+ function renderMovies() {
1276
+ var q = (document.getElementById('searchInput').value || '').toLowerCase().trim();
1277
+ var container = document.getElementById('moviesContainer');
1278
+ container.innerHTML = '';
1279
+
1280
+ var filtered = allMovies.filter(function(m) {
1281
+ var name = (m.file_name || m.fileName || '').toLowerCase();
1282
+ var id = (m.file_unique_id || m.file_id || m.unique_id || '').toLowerCase();
1283
+ return name.indexOf(q) !== -1 || id.indexOf(q) !== -1;
1284
+ });
1285
+
1286
+ if (filtered.length === 0) {
1287
+ container.innerHTML = '<div style="color:var(--text-muted); grid-column: 1/-1; text-align:center; padding:30px;">Walang pelikula.</div>';
1288
+ return;
1289
+ }
1290
+
1291
+ filtered.forEach(function(m) {
1292
+ var id = m.file_unique_id || m.file_id || m.unique_id || m._id;
1293
+ var title = m.file_name || m.fileName || 'Untitled';
1294
+ var poster = m.poster || 'https://via.placeholder.com/150x225/111/fff?text=NO+POSTER';
1295
+ var year = m.year || '2024';
1296
+ var rating = m.rating || '8.5';
1297
+ var overview = m.overview || 'Walang synopsis.';
1298
+
1299
+ var card = document.createElement('div');
1300
+ card.className = 'movie-card';
1301
+ card.innerHTML =
1302
+ '<div class="card-top">' +
1303
+ '<img class="card-poster" src="' + poster + '" onerror="this.src=\\'https://via.placeholder.com/150x225/111/fff?text=NO+POSTER\\'" />' +
1304
+ '<div class="card-info">' +
1305
+ '<div class="card-title">' + title + '</div>' +
1306
+ '<div class="card-id">ID: ' + id + '</div>' +
1307
+ '<div>' +
1308
+ '<span class="badge badge-star">⭐ ' + rating + '</span>' +
1309
+ '<span class="badge">' + year + '</span>' +
1310
+ '</div>' +
1311
+ '<div class="card-overview">' + overview + '</div>' +
1312
+ '</div>' +
1313
+ '</div>' +
1314
+ '<div class="card-actions">' +
1315
+ '<button class="btn-edit" onclick="openEdit(\\'' + encodeURIComponent(id) + '\\')">✏️ Edit</button>' +
1316
+ '<button class="btn-delete" onclick="deleteItem(\\'' + encodeURIComponent(id) + '\\')">🗑️ Delete</button>' +
1317
+ '</div>';
1318
+ container.appendChild(card);
1319
+ });
1320
+ }
1321
+
1322
+ function openEdit(encId) {
1323
+ var id = decodeURIComponent(encId);
1324
+ var m = allMovies.find(function(item) {
1325
+ return (item.file_unique_id || item.file_id || item.unique_id || item._id) === id;
1326
+ });
1327
+ if (!m) return;
1328
+
1329
+ document.getElementById('editId').value = id;
1330
+ document.getElementById('editTitle').value = m.file_name || m.fileName || '';
1331
+ document.getElementById('editPoster').value = m.poster || '';
1332
+ document.getElementById('editYear').value = m.year || '2024';
1333
+ document.getElementById('editRating').value = m.rating || '8.5';
1334
+ document.getElementById('editCategory').value = m.category || 'Movie';
1335
+ document.getElementById('editOverview').value = m.overview || '';
1336
+
1337
+ document.getElementById('editModal').style.display = 'flex';
1338
+ }
1339
+
1340
+ function closeModal() {
1341
+ document.getElementById('editModal').style.display = 'none';
1342
+ }
1343
+
1344
+ function fetchTMDB() {
1345
+ var title = document.getElementById('editTitle').value;
1346
+ if (!title) return alert('Lagyan ng Title!');
1347
+
1348
+ var clean = title.replace(/\\.[a-zA-Z0-9]+$/g, '').replace(/@\\w+/g, '').replace(/[\\(\\)\\[\\]_\\-\\.]+/g, ' ').trim();
1349
+ var yearMatch = clean.match(/\\b(19\\d{2}|20\\d{2})\\b/);
1350
+ var yr = yearMatch ? yearMatch[1] : '';
1351
+ if (yr) clean = clean.replace(yr, '').trim();
1352
+
1353
+ fetch('https://api.themoviedb.org/3/search/multi?api_key=86fd55697899e8444fa3da3ddd24518d&query=' + encodeURIComponent(clean) + (yr ? '&year=' + yr : ''))
1354
+ .then(function(r) { return r.json(); })
1355
+ .then(function(d) {
1356
+ if (d.results && d.results.length > 0) {
1357
+ var item = d.results[0];
1358
+ if (item.poster_path) document.getElementById('editPoster').value = 'https://image.tmdb.org/t/p/w500' + item.poster_path;
1359
+ document.getElementById('editYear').value = (item.release_date || item.first_air_date || yr || '2024').split('-')[0];
1360
+ document.getElementById('editRating').value = item.vote_average ? item.vote_average.toFixed(1) : '8.5';
1361
+ document.getElementById('editOverview').value = item.overview || '';
1362
+ alert('✅ TMDB Match: ' + (item.title || item.name));
1363
+ } else {
1364
+ alert('Walang nahanap sa TMDB.');
1365
+ }
1366
+ }).catch(function() { alert('TMDB Fetch Error'); });
1367
+ }
1368
+
1369
+ function saveMovie() {
1370
+ var payload = {
1371
+ id: document.getElementById('editId').value,
1372
+ file_name: document.getElementById('editTitle').value,
1373
+ poster: document.getElementById('editPoster').value,
1374
+ year: document.getElementById('editYear').value,
1375
+ rating: document.getElementById('editRating').value,
1376
+ category: document.getElementById('editCategory').value,
1377
+ overview: document.getElementById('editOverview').value
1378
+ };
1379
+
1380
+ fetch('/api/admin/update-movie', {
1381
+ method: 'POST',
1382
+ headers: { 'Content-Type': 'application/json' },
1383
+ body: JSON.stringify(payload)
1384
+ })
1385
+ .then(function(r) { return r.json(); })
1386
+ .then(function(d) {
1387
+ if (d.success) {
1388
+ closeModal();
1389
+ loadMovies();
1390
+ } else {
1391
+ alert('Error: ' + d.error);
1392
+ }
1393
+ });
1394
+ }
1395
+
1396
+ function deleteItem(encId) {
1397
+ var id = decodeURIComponent(encId);
1398
+ if (!confirm('Burahin ang pelikulang ito?')) return;
1399
+
1400
+ fetch('/api/admin/delete-movie/' + encodeURIComponent(id), { method: 'DELETE' })
1401
+ .then(function(r) { return r.json(); })
1402
+ .then(function(d) {
1403
+ if (d.success) {
1404
+ loadMovies();
1405
+ } else {
1406
+ alert('Failed to delete');
1407
+ }
1408
+ });
1409
+ }
1410
+ </script>
1411
+ </body>
1412
+ </html>`);
1413
+ });
1414
+ // 10. SERVER START
1415
+ // ---------------------------------------------------------------------------
1416
+ app.listen(PORT, '0.0.0.0', () => {
1417
+ console.log(`🚀 PINOMAX Server live on port ${PORT}`);
1418
+ });