-
Notifications
You must be signed in to change notification settings - Fork 310
Expand file tree
/
Copy pathindex.js
More file actions
603 lines (543 loc) · 19.4 KB
/
index.js
File metadata and controls
603 lines (543 loc) · 19.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
// -- Streambert main process entry point ---------------------------------------
// Responsible for: window creation, session setup, ad-blocking, scheduled
// backup trigger, and app lifecycle. All heavy IPC logic lives in src/ipc/.
const {
app,
BrowserWindow,
ipcMain,
session,
webContents,
Notification,
} = require("electron");
const path = require("path");
// -- RAM / performance flags ---------------------------------------------------
app.commandLine.appendSwitch(
"js-flags",
"--max-old-space-size=256 --expose-gc",
);
app.commandLine.appendSwitch(
"disable-features",
"HardwareMediaKeyHandling,MediaSessionService,UseSandboxedXdgPortal",
);
// Run the network stack in the browser process → one less utility process
app.commandLine.appendSwitch("enable-features", "NetworkServiceInProcess2");
// NOTE: enable-low-end-device-mode removed, it cuts the GPU texture tile budget
// and causes visible seams/stripes/dots on large images.
// Cap disk cache and limit renderer processes (prevents RAM growth on multi-page navigation)
app.commandLine.appendSwitch("disk-cache-size", String(80 * 1024 * 1024));
app.commandLine.appendSwitch("renderer-process-limit", "3");
// -- Startup benchmark ---------------------------------------------------------
const _t0 = Date.now();
const _bench = (label) =>
console.log(`[boot] ${label}: +${Date.now() - _t0}ms`);
// -- Sub-modules ---------------------------------------------------------------
const blockStats = require("./src/ipc/blockStats");
const storageIpc = require("./src/ipc/storage");
const downloadsIpc = require("./src/ipc/downloads");
const subtitlesIpc = require("./src/ipc/subtitles");
const allmangaIpc = require("./src/ipc/allmanga");
const playerIpc = require("./src/ipc/player");
// -- Ad/tracker block list -----------------------------------------------------
const BLOCKED_HOSTS = [
"*://www.google-analytics.com/*",
"*://analytics.google.com/*",
"*://googletagmanager.com/*",
"*://www.googletagmanager.com/*",
"*://googletagservices.com/*",
"*://doubleclick.net/*",
"*://*.doubleclick.net/*",
"*://adservice.google.com/*",
"*://adservice.google.de/*",
"*://pagead2.googlesyndication.com/*",
"*://stats.g.doubleclick.net/*",
"*://yt3.ggpht.com/ytc/*",
"*://fonts.googleapis.com/*",
"*://fonts.gstatic.com/*",
"*://googleapis.com/*",
"*://gstatic.com/*",
"*://cdn.adx1.com/*",
"*://intelligenceadx.com/*",
"*://adsco.re/*",
"*://mc.yandex.com/*",
"*://mc.yandex.ru/*",
"*://bvtpk.com/*",
"*://my.rtmark.net/*",
"*://bvtpk.com/*",
"*://b7510.com/*",
"*://gt.unbrownunflat.com/*",
"*://im.malocacomals.com/*",
"*://users.videasy.net/*",
"*://nf.sixmossin.com/*",
"*://realizationnewestfangs.com/*",
"*://acscdn.com/*",
"*://lt.taloseempest.com/*",
"*://pl26708123.profitableratecpm.com/*",
"*://preferencenail.com/*",
"*://protrafficinspector.com/*",
"*://s10.histats.com/*",
"*://weirdopt.com/*",
"*://static.cloudflareinsights.com/*",
"*://kettledroopingcontinuation.com/*",
"*://wayfarerorthodox.com/*",
"*://woxaglasuy.net/*",
"*://adeptspiritual.com/*",
"*://www.calculating-laugh.com/*",
"*://amavhxdlofklxjg.xyz/*",
"*://7jtjubf8p5kq7x3z2.u3qleufcm6vure326ktfpbj.cfd/*",
"*://5mq.get64t9vqg8pnbex1y463o.rest/*",
"*://usrpubtrk.com/*",
"*://adexchangeclear.com/*",
"*://rzjzjnavztycv.online/*",
"*://tmstr4.cloudnestra.com/*",
"*://tmstr4.neonhorizonworkshops.com/*",
];
// -- Module-level state --------------------------------------------------------
let mainWindow = null;
const getMainWindow = () => mainWindow;
const playerWcIds = new Set();
let sessionsConfigured = false;
function setupSession(playerSession, trailerSession) {
const stripHeaders = (details, callback) => {
const headers = { ...details.responseHeaders };
for (const key of Object.keys(headers)) {
const lower = key.toLowerCase();
if (lower === "x-frame-options" || lower === "content-security-policy")
delete headers[key];
}
callback({ responseHeaders: headers });
};
const UA =
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36";
playerSession.setUserAgent(UA);
trailerSession.setUserAgent(UA);
playerSession.webRequest.onHeadersReceived(
{ urls: ["*://*/*"] },
stripHeaders,
);
trailerSession.webRequest.onHeadersReceived(
{ urls: ["*://*/*"] },
stripHeaders,
);
// Trailer: block ads only (no media intercept needed)
trailerSession.webRequest.onBeforeRequest({ urls: BLOCKED_HOSTS }, (_, cb) =>
cb({ cancel: true }),
);
// Player session: block ads + intercept m3u8/vtt URLs for renderer
const MEDIA_URLS = [
"*://*/*.m3u8*",
"*://*/*.m3u8",
"*://*/*.vtt*",
"*://*/*.vtt",
];
playerSession.webRequest.onBeforeRequest(
{ urls: [...BLOCKED_HOSTS, ...MEDIA_URLS] },
(details, callback) => {
const { url } = details;
const isMedia = url.includes(".m3u8") || url.includes(".vtt");
if (!isMedia) {
blockStats.recordBlockedRequest(url);
callback({ cancel: true });
return;
}
// Media URL: check if it also happens to be on a blocked domain
try {
const host = new URL(url).hostname;
const blocked = BLOCKED_HOSTS.some((pat) => {
const hostPat = pat.replace(/^\*:\/\//, "").split("/")[0];
return hostPat.startsWith("*.")
? host.endsWith(hostPat.slice(1))
: host === hostPat || host === hostPat.replace(/^\*\./, "");
});
if (blocked) {
blockStats.recordBlockedRequest(url);
callback({ cancel: true });
return;
}
} catch {}
// Pass through + notify renderer
const mw = getMainWindow();
if (mw && !mw.isDestroyed()) {
if (url.includes(".m3u8")) {
mw.webContents.send("m3u8-found", url);
} else if (url.includes(".vtt")) {
const { extractSubtitleLang } = require("./src/ipc/subtitles");
mw.webContents.send("subtitle-found", {
url,
lang: extractSubtitleLang(url),
});
}
}
callback({});
},
);
// YouTube consent cookie → suppress consent gate in both sessions
const ytCookie = {
url: "https://www.youtube.com",
name: "SOCS",
value: "CAI",
path: "/",
secure: true,
httpOnly: false,
sameSite: "no_restriction",
expirationDate: Math.floor(Date.now() / 1000) + 60 * 60 * 24 * 365 * 2,
};
for (const domain of [".youtube.com", ".youtube-nocookie.com"]) {
const cookie = { ...ytCookie, domain };
trailerSession.cookies.set(cookie).catch(() => {});
playerSession.cookies.set(cookie).catch(() => {});
}
}
function createWindow() {
storageIpc.applySecretMigrationIfNeeded();
downloadsIpc.loadDownloads();
blockStats.loadBlockStats();
mainWindow = new BrowserWindow({
width: 1400,
height: 900,
minWidth: 900,
minHeight: 600,
backgroundColor: "#0a0a0a",
icon: process.platform === "linux"
? path.join(__dirname, "public/sized/256x256.png")
: undefined,
titleBarStyle: process.platform === "darwin" ? "hiddenInset" : "hidden",
frame: process.platform !== "win32",
webPreferences: {
preload: path.join(__dirname, "preload.js"),
contextIsolation: true,
nodeIntegration: false,
webviewTag: true,
backgroundThrottling: true,
spellcheck: false,
// Caps the renderer's V8 heap + exposes gc() for manual GC hints after navigation
additionalArguments: ["--js-flags=--max-old-space-size=256 --expose-gc"],
},
});
// Force long-lived disk caching for TMDB images in the default session.
session.defaultSession.webRequest.onHeadersReceived(
{ urls: ["*://image.tmdb.org/*"] },
(details, callback) => {
const headers = { ...details.responseHeaders };
headers["cache-control"] = ["public, max-age=604800, immutable"]; // 7 days
delete headers["pragma"];
delete headers["expires"];
callback({ responseHeaders: headers });
},
);
// -- Lazy session setup ----------------------------------------------------
// Player/trailer sessions are configured on the first webview attach or
// when the pop-out window opens, whichever comes first.
// Block popups from webviews, intercept fullscreen, lazy-init sessions
mainWindow.webContents.on("did-attach-webview", (_, wc) => {
if (!sessionsConfigured) {
sessionsConfigured = true;
const playerSession = session.fromPartition("persist:player");
const trailerSession = session.fromPartition("persist:trailer");
setupSession(playerSession, trailerSession);
}
// Track player webviews for cleanup on player-stopped
try {
if (wc.session === session.fromPartition("persist:player")) {
playerWcIds.add(wc.id);
wc.once("destroyed", () => playerWcIds.delete(wc.id));
}
} catch {}
wc.setWindowOpenHandler(() => ({ action: "deny" }));
wc.on("enter-html-full-screen", () =>
mainWindow.webContents.send("webview-enter-fullscreen"),
);
wc.on("leave-html-full-screen", () =>
mainWindow.webContents.send("webview-leave-fullscreen"),
);
});
mainWindow.loadFile(path.join(__dirname, "dist/index.html"));
// Trigger scheduled backup after load
mainWindow.webContents.once("did-finish-load", () => {
_bench("renderer loaded");
const sbSettings = storageIpc.loadScheduledBackupSettings();
if (storageIpc.shouldRunScheduledBackup(sbSettings)) {
mainWindow.webContents.send("scheduled-backup-requested");
}
});
// Intercept close if downloads are active
let closeResponsePending = false;
mainWindow.on("close", (e) => {
const running = downloadsIpc
.getDownloads()
.filter((d) => d.status === "downloading");
if (running.length === 0) return;
e.preventDefault();
if (closeResponsePending) return;
closeResponsePending = true;
mainWindow.webContents.send("confirm-close", { count: running.length });
});
ipcMain.on("close-response", (_, confirmed) => {
closeResponsePending = false;
if (confirmed) {
downloadsIpc.killAllDownloads();
mainWindow.destroy();
}
});
mainWindow.on("closed", () => {
mainWindow = null;
app.quit();
});
}
// -- Register all IPC modules --------------------------------------------------
storageIpc.register();
downloadsIpc.register(getMainWindow);
subtitlesIpc.register({
getDownloads: downloadsIpc.getDownloads,
saveDownloads: downloadsIpc.saveDownloads,
});
allmangaIpc.register();
playerIpc.register(getMainWindow, {
writeSecretMigration: storageIpc.writeSecretMigration,
});
blockStats.init(getMainWindow);
// get-block-stats lives with its data
ipcMain.handle("get-block-stats", () => blockStats.getBlockStats());
// -- Player memory cleanup ---------------------------------------------
// Called by MoviePage / TVPage on component unmount.
// Destroys the player webview WebContents by tracked ID, then flushes caches and GCs.
ipcMain.on("player-stopped", () => {
// Step 1: Mute + destroy all tracked player WebContents by ID.
for (const id of playerWcIds) {
try {
const wc = webContents.fromId(id);
if (wc && !wc.isDestroyed()) {
try {
wc.setAudioMuted(true);
} catch {}
wc.destroy();
}
} catch {}
}
playerWcIds.clear();
// Step 2: Flush HTTP + shader caches from the player session.
try {
const ps = session.fromPartition("persist:player");
ps.clearCache().catch(() => {});
ps.clearStorageData({ storages: ["shadercache", "cachestorage"] }).catch(
() => {},
);
} catch {}
// Step 3: GC hints
if (typeof global.gc === "function") global.gc();
const mw = mainWindow;
if (mw && !mw.isDestroyed()) {
mw.webContents
.executeJavaScript("if(typeof gc==='function') gc();")
.catch(() => {});
}
});
// -- Wyzie API Key Redemption Window ------------------------------------------
// Opens https://sub.wyzie.io/redeem in a child BrowserWindow, watches the DOM
// for the api-key-display element, extracts the key, and sends it back.
ipcMain.handle("wyzie-open-redeem", async () => {
return new Promise((resolve) => {
const { BrowserWindow: BW, session: electronSession } = require("electron");
// Use a non-persistent session so NO cookies/storage are saved after the window closes
const redeemSession = electronSession.fromPartition(
"partition:wyzie-redeem",
);
// Strip restrictive CSP so the page styles load correctly
redeemSession.webRequest.onHeadersReceived((details, callback) => {
const headers = { ...details.responseHeaders };
delete headers["content-security-policy"];
delete headers["Content-Security-Policy"];
callback({ responseHeaders: headers });
});
const win = new BW({
width: 960,
height: 720,
title: "Claim your Wyzie API Key",
webPreferences: {
contextIsolation: true,
nodeIntegration: false,
session: redeemSession,
},
backgroundColor: "#ffffff",
autoHideMenuBar: true,
});
let resolved = false;
let timeout = null;
const finish = (result) => {
if (resolved) return;
resolved = true;
clearTimeout(timeout);
if (!win.isDestroyed()) win.close();
resolve(result);
};
win.on("closed", () => {
if (!resolved) resolve({ ok: false, key: null, cancelled: true });
clearTimeout(timeout);
});
// Start the 20 s timer only once the page has finished loading
win.webContents.once("did-finish-load", () => {
timeout = setTimeout(() => {
finish({ ok: false, key: null, timeout: true });
}, 20000);
});
// The redeem page redirects to /notice?key=wyzie-... after captcha success
const checkUrl = (url) => {
try {
const u = new URL(url);
if (u.hostname === "sub.wyzie.io" && u.pathname === "/notice") {
const key = u.searchParams.get("key");
if (key && key.startsWith("wyzie-") && key.length > 10) {
finish({ ok: true, key });
return true;
}
}
} catch {}
return false;
};
win.webContents.on("will-navigate", (_, url) => checkUrl(url));
win.webContents.on("did-navigate", (_, url) => checkUrl(url));
win.webContents.on("did-navigate-in-page", (_, url) => checkUrl(url));
win.loadURL("https://sub.wyzie.io/redeem");
});
});
// -- Wyzie API Key Validation --------------------------------------------------
ipcMain.handle("wyzie-validate-key", async (_, key) => {
try {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 10000);
// Key goes as query-param, not Authorization header
const res = await fetch(
`https://sub.wyzie.io/search?id=550&format=srt&key=${encodeURIComponent(key)}`,
{ signal: controller.signal },
).finally(() => clearTimeout(timer));
if (res.status === 401 || res.status === 403)
return { ok: false, error: "Invalid or expired key" };
return { ok: true };
} catch (e) {
return { ok: false, error: e.message };
}
});
// -- Desktop notifications -----------------------------------------------------
// Called from the renderer whenever it wants a native OS notification.
ipcMain.handle(
"show-notification",
(_event, { title, body, silent = false }) => {
try {
if (!Notification.isSupported()) return;
const n = new Notification({
title: String(title),
body: String(body),
silent,
});
n.show();
} catch {}
},
);
// -- Picture-in-Picture / Pop-Out window --------------------------------------
// Opens the player URL in a small always-on-top BrowserWindow (full site UI,
// with subtitles and controls). The Main Window closes the stream to avoid duplication.
let pipWindow = null;
const getPipWindow = () => pipWindow;
ipcMain.handle("open-pip-window", (_, { url, title }) => {
if (!url || url === "about:blank") return { ok: false, reason: "no-url" };
// Guarantee tracker/ad blocking is active in persist:player before any load
if (!sessionsConfigured) {
sessionsConfigured = true;
const playerSession = session.fromPartition("persist:player");
const trailerSession = session.fromPartition("persist:trailer");
setupSession(playerSession, trailerSession);
}
if (pipWindow && !pipWindow.isDestroyed()) {
pipWindow.loadURL(url);
pipWindow.focus();
return { ok: true };
}
pipWindow = new BrowserWindow({
width: 640,
height: 360,
minWidth: 320,
minHeight: 180,
alwaysOnTop: true,
title: title ? `${title} - Pop-out` : "Pop-out Player",
backgroundColor: "#000000",
// Same custom title bar as the main window
titleBarStyle: process.platform === "darwin" ? "hiddenInset" : "hidden",
frame: process.platform !== "win32",
webPreferences: {
partition: "persist:player",
nodeIntegration: false,
contextIsolation: true,
// Injects the custom title bar and wires window-control IPC
preload: path.join(__dirname, "popout-preload.js"),
},
});
// Block all popup windows from the streaming site and any nested frames
pipWindow.webContents.setWindowOpenHandler(() => ({ action: "deny" }));
// If the site uses <webview> elements (unlikely but safe), block there too
pipWindow.webContents.on("did-attach-webview", (_, wc) => {
wc.setWindowOpenHandler(() => ({ action: "deny" }));
});
pipWindow.loadURL(url);
// Push maximize state into the popout renderer so the title bar icon updates
pipWindow.on("maximize", () => {
if (!pipWindow.isDestroyed())
pipWindow.webContents.send("popout-window-maximized", true);
});
pipWindow.on("unmaximize", () => {
if (!pipWindow.isDestroyed())
pipWindow.webContents.send("popout-window-maximized", false);
});
const notifyMain = (channel) => {
const mw = getMainWindow();
if (mw && !mw.isDestroyed()) mw.webContents.send(channel);
};
pipWindow.on("closed", () => {
pipWindow = null;
notifyMain("pip-window-closed");
});
notifyMain("pip-window-opened");
return { ok: true };
});
ipcMain.handle("close-pip-window", () => {
if (pipWindow && !pipWindow.isDestroyed()) pipWindow.close();
});
ipcMain.handle("get-pip-webcontents-id", () => {
if (pipWindow && !pipWindow.isDestroyed()) return pipWindow.webContents.id;
return null;
});
// -- Popout window controls (used by popout-preload.js title bar buttons) -----
ipcMain.handle("popout-window-minimize", () => {
if (pipWindow && !pipWindow.isDestroyed()) pipWindow.minimize();
});
ipcMain.handle("popout-window-toggle-maximize", () => {
if (!pipWindow || pipWindow.isDestroyed()) return;
if (pipWindow.isMaximized()) pipWindow.unmaximize();
else pipWindow.maximize();
});
ipcMain.handle("popout-window-close", () => {
if (pipWindow && !pipWindow.isDestroyed()) pipWindow.close();
});
ipcMain.handle("popout-window-is-maximized", () => {
return pipWindow && !pipWindow.isDestroyed()
? pipWindow.isMaximized()
: false;
});
// -- Single-instance lock ------------------------------------------------------
const gotTheLock = app.requestSingleInstanceLock();
if (!gotTheLock) {
app.quit();
} else {
app.on("second-instance", () => {
if (mainWindow) {
if (mainWindow.isMinimized()) mainWindow.restore();
mainWindow.focus();
}
});
app.whenReady().then(() => {
_bench("app ready");
createWindow();
});
app.on("window-all-closed", () => app.quit());
app.on("activate", () => {
if (mainWindow === null) createWindow();
});
}