-
Notifications
You must be signed in to change notification settings - Fork 897
/
Copy pathindex.js
1823 lines (1580 loc) · 55.6 KB
/
index.js
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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
app, BrowserWindow, dialog, Menu, ipcMain,
powerSaveBlocker, screen, session, shell,
nativeTheme, net, protocol, clipboard
} from 'electron'
import path from 'path'
import cp from 'child_process'
import {
IpcChannels,
DBActions,
SyncEvents,
ABOUT_BITCOIN_ADDRESS,
} from '../constants'
import * as baseHandlers from '../datastores/handlers/base'
import { extractExpiryTimestamp, ImageCache } from './ImageCache'
import { existsSync } from 'fs'
import asyncFs from 'fs/promises'
import { promisify } from 'util'
import { brotliDecompress } from 'zlib'
import contextMenu from 'electron-context-menu'
import packageDetails from '../../package.json'
import { generatePoToken } from './poTokenGenerator'
const brotliDecompressAsync = promisify(brotliDecompress)
if (process.argv.includes('--version')) {
app.exit()
} else {
runApp()
}
function runApp() {
/** @type {Set<string>} */
let ALLOWED_RENDERER_FILES
if (process.env.NODE_ENV === 'production') {
// __FREETUBE_ALLOWED_PATHS__ is replaced by the injectAllowedPaths.mjs script
// eslint-disable-next-line no-undef
ALLOWED_RENDERER_FILES = new Set(__FREETUBE_ALLOWED_PATHS__)
protocol.registerSchemesAsPrivileged([{
scheme: 'app',
privileges: {
standard: true,
secure: true,
supportFetchAPI: true
}
}])
}
contextMenu({
showSearchWithGoogle: false,
showSaveImageAs: true,
showCopyImageAddress: true,
showSelectAll: false,
showCopyLink: false,
prepend: (defaultActions, parameters, browserWindow) => [
{
label: 'Open in a New Window',
// Only show the option for in-app URLs and not external ones
visible: parameters.linkURL.split('#')[0] === browserWindow.webContents.getURL().split('#')[0],
click: () => {
createWindow({ replaceMainWindow: false, windowStartupUrl: parameters.linkURL, showWindowNow: true })
}
},
// Only show select all in text fields
{
label: 'Select All',
enabled: parameters.editFlags.canSelectAll,
visible: parameters.isEditable,
click: () => {
browserWindow.webContents.selectAll()
}
}
],
// only show the copy link entry for external links and the /playlist, /channel and /watch in-app URLs
// the /playlist, /channel and /watch in-app URLs get transformed to their equivalent YouTube or Invidious URLs
append: (defaultActions, parameters, browserWindow) => {
let visible = false
const urlParts = parameters.linkURL.split('#')
const isInAppUrl = urlParts[0] === browserWindow.webContents.getURL().split('#')[0]
if (parameters.linkURL.length > 0) {
if (isInAppUrl) {
const path = urlParts[1]
if (path) {
visible = ['/channel', '/watch', '/hashtag', '/post'].some(p => path.startsWith(p)) ||
// Only show copy link entry for non user playlists
(path.startsWith('/playlist') && !/playlistType=user/.test(path))
}
} else {
visible = true
}
}
const copy = (url) => {
if (parameters.linkText) {
clipboard.write({
bookmark: parameters.linkText,
text: url
})
} else {
clipboard.writeText(url)
}
}
const transformURL = (toYouTube) => {
let origin
if (toYouTube) {
origin = 'https://www.youtube.com'
} else {
origin = 'https://redirect.invidious.io'
}
const [path, query] = urlParts[1].split('?')
const [route, id] = path.split('/').filter(p => p)
switch (route) {
case 'playlist':
return `${origin}/playlist?list=${id}`
case 'channel':
return `${origin}/channel/${id}`
case 'hashtag':
return `${origin}/hashtag/${id}`
case 'watch': {
let url
if (toYouTube) {
url = new URL(`https://youtu.be/${id}`)
} else {
url = new URL(`https://redirect.invidious.io/watch?v=${id}`)
}
if (query) {
const params = new URLSearchParams(query)
const newParams = new URLSearchParams(url.search)
let hasParams = false
if (params.has('playlistId') && params.get('playlistType') !== 'user') {
newParams.set('list', params.get('playlistId'))
hasParams = true
}
if (params.has('timestamp')) {
newParams.set('t', params.get('timestamp'))
hasParams = true
}
if (hasParams) {
url.search = newParams.toString()
}
}
return url.toString()
}
case 'post': {
if (query) {
const authorId = new URLSearchParams(query).get('authorId')
if (authorId) {
if (toYouTube) {
return `${origin}/channel/${authorId}/community?lb=${id}`
} else {
return `${origin}/post/${id}?ucid=${authorId}`
}
}
}
return `${origin}/post/${id}`
}
}
}
return [
{
label: 'Copy Lin&k',
visible: visible && !isInAppUrl,
click: () => {
copy(parameters.linkURL)
}
},
{
label: 'Copy YouTube Link',
visible: visible && isInAppUrl,
click: () => {
copy(transformURL(true))
}
},
{
label: 'Copy Invidious Link',
visible: visible && isInAppUrl,
click: () => {
copy(transformURL(false))
}
}
]
}
})
// disable electron warning
process.env.ELECTRON_DISABLE_SECURITY_WARNINGS = 'true'
const isDebug = process.argv.includes('--debug')
let mainWindow
let startupUrl
if (process.platform === 'linux') {
// Enable hardware acceleration via VA-API with OpenGL if no other feature flags are found
// https://chromium.googlesource.com/chromium/src/+/refs/heads/main/docs/gpu/vaapi.md
if (!app.commandLine.hasSwitch('enable-features')) {
app.commandLine.appendSwitch('enable-features', 'VaapiVideoDecodeLinuxGL')
}
}
const userDataPath = app.getPath('userData')
// command line switches need to be added before the app ready event first
// that means we can't use the normal settings system as that is asynchronous,
// doing it synchronously ensures that we add it before the event fires
const REPLACE_HTTP_CACHE_PATH = `${userDataPath}/experiment-replace-http-cache`
const replaceHttpCache = existsSync(REPLACE_HTTP_CACHE_PATH)
if (replaceHttpCache) {
// the http cache causes excessive disk usage during video playback
// we've got a custom image cache to make up for disabling the http cache
// experimental as it increases RAM use in favour of reduced disk use
app.commandLine.appendSwitch('disable-http-cache')
}
const PLAYER_CACHE_PATH = `${userDataPath}/player_cache`
// See: https://stackoverflow.com/questions/45570589/electron-protocol-handler-not-working-on-windows
// remove so we can register each time as we run the app.
app.removeAsDefaultProtocolClient('freetube')
// If we are running a non-packaged version of the app && on windows
if (process.env.NODE_ENV === 'development' && process.platform === 'win32') {
// Set the path of electron.exe and your app.
// These two additional parameters are only available on windows.
app.setAsDefaultProtocolClient('freetube', process.execPath, [path.resolve(process.argv[1])])
} else {
app.setAsDefaultProtocolClient('freetube')
}
if (process.env.NODE_ENV !== 'development') {
// Only allow single instance of the application
const gotTheLock = app.requestSingleInstanceLock()
if (!gotTheLock) {
app.quit()
}
app.on('second-instance', (_, commandLine, __) => {
// Someone tried to run a second instance, we should focus our window
if (typeof commandLine !== 'undefined') {
const url = getLinkUrl(commandLine)
if (mainWindow && mainWindow.webContents) {
if (mainWindow.isMinimized()) mainWindow.restore()
mainWindow.focus()
if (url) mainWindow.webContents.send(IpcChannels.OPEN_URL, url)
} else {
if (url) startupUrl = url
createWindow()
}
}
})
}
app.on('ready', async (_, __) => {
if (process.env.NODE_ENV === 'production') {
protocol.handle('app', async (request) => {
if (request.method !== 'GET') {
return new Response(null, {
status: 405,
headers: {
Allow: 'GET'
}
})
}
const { host, pathname } = new URL(request.url)
if (host !== 'bundle' || !ALLOWED_RENDERER_FILES.has(pathname)) {
return new Response(null, {
status: 400
})
}
const contents = await asyncFs.readFile(path.join(__dirname, pathname))
if (pathname.endsWith('.json.br')) {
const decompressed = await brotliDecompressAsync(contents)
return new Response(decompressed.buffer, {
status: 200,
headers: {
'Content-Type': 'application/json',
'Content-Encoding': 'br'
}
})
} else {
return new Response(contents.buffer, {
status: 200,
headers: {
'Content-Type': contentTypeFromFileExtension(pathname.split('.').at(-1))
}
})
}
})
}
// Electron defaults to approving all permission checks and permission requests.
// FreeTube only needs a few permissions, so we reject requests for other permissions
// and reject all requests on non-FreeTube URLs.
//
// FreeTube needs the following permissions:
// - "fullscreen": So that the video player can enter full screen
// - "clipboard-sanitized-write": To allow the user to copy video URLs and error messages
session.defaultSession.setPermissionCheckHandler((webContents, permission, requestingOrigin) => {
if (!isFreeTubeUrl(requestingOrigin)) {
return false
}
return permission === 'fullscreen' || permission === 'clipboard-sanitized-write'
})
session.defaultSession.setPermissionRequestHandler((webContents, permission, callback) => {
if (!isFreeTubeUrl(webContents.getURL())) {
// eslint-disable-next-line n/no-callback-literal
callback(false)
return
}
callback(permission === 'fullscreen' || permission === 'clipboard-sanitized-write')
})
let docArray
try {
docArray = await baseHandlers.settings._findAppReadyRelatedSettings()
} catch (err) {
console.error(err)
app.exit()
return
}
let disableSmoothScrolling = false
let useProxy = false
let proxyProtocol = 'socks5'
let proxyHostname = '127.0.0.1'
let proxyPort = '9050'
if (docArray?.length > 0) {
docArray.forEach((doc) => {
switch (doc._id) {
case 'disableSmoothScrolling':
disableSmoothScrolling = doc.value
break
case 'useProxy':
useProxy = doc.value
break
case 'proxyProtocol':
proxyProtocol = doc.value
break
case 'proxyHostname':
proxyHostname = doc.value
break
case 'proxyPort':
proxyPort = doc.value
break
}
})
}
if (disableSmoothScrolling) {
app.commandLine.appendSwitch('disable-smooth-scrolling')
} else {
app.commandLine.appendSwitch('enable-smooth-scrolling')
}
if (useProxy) {
session.defaultSession.setProxy({
proxyRules: `${proxyProtocol}://${proxyHostname}:${proxyPort}`
})
}
const fixedUserAgent = session.defaultSession.getUserAgent()
.split(' ')
.filter(part => !part.includes('Electron') && !part.includes(packageDetails.productName))
.join(' ')
session.defaultSession.setUserAgent(fixedUserAgent)
// Set CONSENT cookie on reasonable domains
const consentCookieDomains = [
'https://www.youtube.com',
'https://youtube.com'
]
consentCookieDomains.forEach(url => {
session.defaultSession.cookies.set({
url: url,
name: 'CONSENT',
value: 'YES+',
sameSite: 'no_restriction'
})
})
session.defaultSession.cookies.set({
url: 'https://www.youtube.com',
name: 'SOCS',
value: 'CAI',
sameSite: 'no_restriction',
})
const onBeforeSendHeadersRequestFilter = {
urls: ['https://*/*', 'http://*/*'],
types: ['xhr', 'media', 'image']
}
session.defaultSession.webRequest.onBeforeSendHeaders(onBeforeSendHeadersRequestFilter, ({ requestHeaders, url, webContents }, callback) => {
const urlObj = new URL(url)
if (url.startsWith('https://www.youtube.com/youtubei/')) {
// make InnerTube requests work with the fetch function
// InnerTube rejects requests if the referer isn't YouTube or empty
requestHeaders.Referer = 'https://www.youtube.com/'
requestHeaders.Origin = 'https://www.youtube.com'
requestHeaders['Sec-Fetch-Site'] = 'same-origin'
requestHeaders['Sec-Fetch-Mode'] = 'same-origin'
requestHeaders['X-Youtube-Bootstrap-Logged-In'] = 'false'
} else if (urlObj.origin.endsWith('.googlevideo.com') && urlObj.pathname === '/videoplayback') {
requestHeaders.Referer = 'https://www.youtube.com/'
requestHeaders.Origin = 'https://www.youtube.com'
// YouTube doesn't send the Content-Type header for the media requests, so we shouldn't either
delete requestHeaders['Content-Type']
} else if (webContents) {
const invidiousAuthorization = invidiousAuthorizations.get(webContents.id)
if (invidiousAuthorization && url.startsWith(invidiousAuthorization.url)) {
requestHeaders.Authorization = invidiousAuthorization.authorization
}
}
callback({ requestHeaders })
})
// when we create a real session on the watch page, youtube returns tracking cookies, which we definitely don't want
const trackingCookieRequestFilter = { urls: ['https://www.youtube.com/sw.js_data', 'https://www.youtube.com/iframe_api'] }
session.defaultSession.webRequest.onHeadersReceived(trackingCookieRequestFilter, ({ responseHeaders }, callback) => {
if (responseHeaders) {
delete responseHeaders['set-cookie']
}
callback({ responseHeaders })
})
if (replaceHttpCache) {
// in-memory image cache
const imageCache = new ImageCache()
protocol.handle('imagecache', (request) => {
const [requestUrl, rawWebContentsId] = request.url.split('#')
return new Promise((resolve, reject) => {
const url = decodeURIComponent(requestUrl.substring(13))
if (imageCache.has(url)) {
const cached = imageCache.get(url)
resolve(new Response(cached.data, {
headers: { 'content-type': cached.mimeType }
}))
return
}
let headers
if (rawWebContentsId) {
const invidiousAuthorization = invidiousAuthorizations.get(parseInt(rawWebContentsId))
if (invidiousAuthorization && url.startsWith(invidiousAuthorization.url)) {
headers = {
Authorization: invidiousAuthorization.authorization
}
}
}
const newRequest = net.request({
method: request.method,
url,
headers
})
// Electron doesn't allow certain headers to be set:
// https://www.electronjs.org/docs/latest/api/client-request#requestsetheadername-value
// also blacklist Origin and Referrer as we don't want to let YouTube know about them
const blacklistedHeaders = ['content-length', 'host', 'trailer', 'te', 'upgrade', 'cookie2', 'keep-alive', 'transfer-encoding', 'origin', 'referrer']
for (const header of Object.keys(request.headers)) {
if (!blacklistedHeaders.includes(header.toLowerCase())) {
newRequest.setHeader(header, request.headers[header])
}
}
newRequest.on('response', (response) => {
const chunks = []
response.on('data', (chunk) => {
chunks.push(chunk)
})
response.on('end', () => {
const data = Buffer.concat(chunks)
const expiryTimestamp = extractExpiryTimestamp(response.headers)
const mimeType = response.headers['content-type']
imageCache.add(url, mimeType, data, expiryTimestamp)
resolve(new Response(data, {
headers: { 'content-type': mimeType }
}))
})
response.on('error', (error) => {
console.error('image cache error', error)
reject(error)
})
})
newRequest.on('error', (err) => {
console.error(err)
})
newRequest.end()
})
})
const imageRequestFilter = { urls: ['https://*/*', 'http://*/*'], types: ['image'] }
session.defaultSession.webRequest.onBeforeRequest(imageRequestFilter, (details, callback) => {
// the requests made by the imagecache:// handler to fetch the image,
// are allowed through, as their resourceType is 'other'
let redirectURL = `imagecache://${encodeURIComponent(details.url)}`
if (details.webContents) {
redirectURL += `#${details.webContents.id}`
}
callback({
redirectURL
})
})
// --- end of `if experimentsDisableDiskCache` ---
}
await createWindow()
if (process.env.NODE_ENV === 'development') {
try {
require('vue-devtools').install()
} catch (err) {
console.error(err)
}
}
if (isDebug) {
mainWindow.webContents.openDevTools()
}
})
/**
* @param {string} extension
*/
function contentTypeFromFileExtension(extension) {
switch (extension) {
case 'html':
return 'text/html'
case 'css':
return 'text/css'
case 'js':
return 'text/javascript'
case 'ttf':
return 'font/ttf'
case 'woff2':
return 'font/woff2'
case 'svg':
return 'image/svg+xml'
case 'png':
return 'image/png'
case 'json':
return 'application/json'
case 'txt':
return 'text/plain'
default:
return 'application/octet-stream'
}
}
/**
* @param {string} urlString
*/
function isFreeTubeUrl(urlString) {
const { protocol, host, pathname } = new URL(urlString)
if (process.env.NODE_ENV === 'development') {
return protocol === 'http:' && host === 'localhost:9080' && (pathname === '/' || pathname === '/index.html')
} else {
return protocol === 'app:' && host === 'bundle' && pathname === '/index.html'
}
}
async function createWindow(
{
replaceMainWindow = true,
windowStartupUrl = null,
showWindowNow = false,
searchQueryText = null
} = { }) {
// Syncing new window background to theme choice.
const windowBackground = await baseHandlers.settings._findTheme().then((setting) => {
if (!setting) {
return nativeTheme.shouldUseDarkColors ? '#212121' : '#f1f1f1'
}
// Determine window color to be shown (shown most prominently during initial app load)
// Uses the --bg-color for each corresponding theme
switch (setting.value) {
case 'dark':
return '#212121'
case 'light':
return '#f1f1f1'
case 'black':
return '#000000'
case 'dracula':
return '#282a36'
case 'catppuccin-mocha':
return '#1e1e2e'
case 'pastel-pink':
return '#ffd1dc'
case 'hot-pink':
return '#de1c85'
case 'nordic':
return '#2b2f3a'
case 'solarized-dark':
return '#002B36'
case 'solarized-light':
return '#fdf6e3'
case 'gruvbox-dark':
return '#282828'
case 'gruvbox-light':
return '#fbf1c7'
case 'catppuccin-frappe':
return '#303446'
case 'everforest-dark-hard':
return '#1E2326'
case 'everforest-dark-medium':
return '#232A2E'
case 'everforest-dark-low':
return '#293136'
case 'everforest-light-hard':
return '#F2EFDF'
case 'everforest-light-medium':
return '#EFE8D4'
case 'everforest-light-low':
return '#E5DFC5'
case 'system':
default:
return nativeTheme.shouldUseDarkColors ? '#212121' : '#f1f1f1'
}
}).catch((error) => {
console.error(error)
// Default to nativeTheme settings if nothing is found.
return nativeTheme.shouldUseDarkColors ? '#212121' : '#f1f1f1'
})
/**
* Initial window options
*/
const commonBrowserWindowOptions = {
backgroundColor: windowBackground,
darkTheme: nativeTheme.shouldUseDarkColors,
icon: process.env.NODE_ENV === 'development'
? path.join(__dirname, '../../_icons/iconColor.png')
/* eslint-disable-next-line n/no-path-concat */
: `${__dirname}/_icons/iconColor.png`,
autoHideMenuBar: true,
// useContentSize: true,
webPreferences: {
nodeIntegration: true,
nodeIntegrationInWorker: false,
webSecurity: false,
backgroundThrottling: false,
contextIsolation: false
},
minWidth: 340,
minHeight: 380
}
const newWindow = new BrowserWindow(
Object.assign(
{
// It will be shown later when ready via `ready-to-show` event
show: showWindowNow
},
commonBrowserWindowOptions
)
)
// region Ensure child windows use same options since electron 14
// https://github.com/electron/electron/blob/14-x-y/docs/api/window-open.md#native-window-example
newWindow.webContents.setWindowOpenHandler((details) => {
createWindow({
replaceMainWindow: false,
showWindowNow: true,
windowStartupUrl: details.url
})
return {
action: 'deny'
}
})
// endregion Ensure child windows use same options since electron 14
if (replaceMainWindow) {
mainWindow = newWindow
}
newWindow.setBounds({
width: 1200,
height: 800
})
const boundsDoc = await baseHandlers.settings._findBounds()
if (typeof boundsDoc?.value === 'object') {
const { maximized, fullScreen, ...bounds } = boundsDoc.value
const windowVisible = screen.getAllDisplays().some(display => {
const { x, y, width, height } = display.bounds
return !(bounds.x > x + width || bounds.x + bounds.width < x || bounds.y > y + height || bounds.y + bounds.height < y)
})
if (windowVisible) {
newWindow.setBounds({
x: bounds.x,
y: bounds.y,
width: bounds.width,
height: bounds.height
})
}
if (maximized) {
newWindow.maximize()
}
if (fullScreen) {
newWindow.setFullScreen(true)
}
}
// If called multiple times
// Duplicate menu items will be added
if (replaceMainWindow) {
setMenu()
}
// load root file/url
if (process.env.NODE_ENV === 'development') {
let devStartupURL = 'http://localhost:9080'
if (windowStartupUrl != null) {
devStartupURL = windowStartupUrl
}
newWindow.loadURL(devStartupURL)
} else {
if (windowStartupUrl != null) {
newWindow.loadURL(windowStartupUrl)
} else {
newWindow.loadURL('app://bundle/index.html')
}
}
if (typeof searchQueryText === 'string' && searchQueryText.length > 0) {
ipcMain.once(IpcChannels.SEARCH_INPUT_HANDLING_READY, () => {
newWindow.webContents.send(IpcChannels.UPDATE_SEARCH_INPUT_TEXT, searchQueryText)
})
}
// Show when loaded
newWindow.once('ready-to-show', () => {
if (newWindow.isVisible()) {
// only open the dev tools if they aren't already open
if (process.env.NODE_ENV === 'development' && !newWindow.webContents.isDevToolsOpened()) {
newWindow.webContents.openDevTools({ activate: false })
}
return
}
newWindow.show()
newWindow.focus()
if (process.env.NODE_ENV === 'development') {
newWindow.webContents.openDevTools({ activate: false })
}
})
newWindow.once('close', async () => {
if (BrowserWindow.getAllWindows().length !== 1) {
return
}
const value = {
...newWindow.getNormalBounds(),
maximized: newWindow.isMaximized(),
fullScreen: newWindow.isFullScreen()
}
await baseHandlers.settings._updateBounds(value)
})
newWindow.once('closed', () => {
const allWindows = BrowserWindow.getAllWindows()
if (allWindows.length !== 0 && newWindow === mainWindow) {
// Replace mainWindow to avoid accessing `mainWindow.webContents`
// Which raises "Object has been destroyed" error
mainWindow = allWindows[0]
}
})
}
ipcMain.on(IpcChannels.APP_READY, () => {
if (startupUrl) {
mainWindow.webContents.send(IpcChannels.OPEN_URL, startupUrl, { isLaunchLink: true })
}
startupUrl = null
})
function relaunch() {
if (process.env.NODE_ENV === 'development') {
app.exit(parseInt(process.env.FREETUBE_RELAUNCH_EXIT_CODE))
return
}
// The AppImage and Windows portable formats must be accounted for
// because `process.execPath` points at the temporarily extracted
// executables, not the executables themselves
//
// It's possible to detect these formats and identify their
// executables' paths by checking the environmental variables
const { env: { APPIMAGE, PORTABLE_EXECUTABLE_FILE } } = process
if (!APPIMAGE) {
// If it's a Windows portable, PORTABLE_EXECUTABLE_FILE will
// hold a value.
// Otherwise, `process.execPath` should be used instead.
app.relaunch({
args: process.argv.slice(1),
execPath: PORTABLE_EXECUTABLE_FILE || process.execPath
})
} else {
// If it's an AppImage, things must be done the "hard way"
// `app.relaunch` doesn't work because of FUSE limitations
// Spawn a new process using the APPIMAGE env variable
const subprocess = cp.spawn(APPIMAGE, { detached: true, stdio: 'ignore' })
subprocess.unref()
}
app.quit()
}
ipcMain.once(IpcChannels.RELAUNCH_REQUEST, () => {
relaunch()
})
nativeTheme.on('updated', () => {
const allWindows = BrowserWindow.getAllWindows()
allWindows.forEach((window) => {
window.webContents.send(IpcChannels.NATIVE_THEME_UPDATE, nativeTheme.shouldUseDarkColors)
})
})
ipcMain.handle(IpcChannels.GENERATE_PO_TOKEN, (_, visitorData) => {
return generatePoToken(visitorData)
})
ipcMain.on(IpcChannels.ENABLE_PROXY, (_, url) => {
session.defaultSession.setProxy({
proxyRules: url
})
session.defaultSession.closeAllConnections()
})
ipcMain.on(IpcChannels.DISABLE_PROXY, () => {
session.defaultSession.setProxy({})
session.defaultSession.closeAllConnections()
})
// #region navigation history
const NAV_HISTORY_DISPLAY_LIMIT = 15
// Math.trunc but with a bitwise OR so that it can be calcuated at build time and the number inlined
const HALF_OF_NAV_HISTORY_DISPLAY_LIMIT = (NAV_HISTORY_DISPLAY_LIMIT / 2) | 0
ipcMain.handle(IpcChannels.GET_NAVIGATION_HISTORY, ({ sender }) => {
const activeIndex = sender.navigationHistory.getActiveIndex()
const length = sender.navigationHistory.length()
let end
if (activeIndex < HALF_OF_NAV_HISTORY_DISPLAY_LIMIT) {
end = Math.min(length - 1, NAV_HISTORY_DISPLAY_LIMIT - 1)
} else if (length - activeIndex < HALF_OF_NAV_HISTORY_DISPLAY_LIMIT + 1) {
end = length - 1
} else {
end = activeIndex + HALF_OF_NAV_HISTORY_DISPLAY_LIMIT
}
const dropdownOptions = []
for (let index = end; index >= Math.max(0, end + 1 - NAV_HISTORY_DISPLAY_LIMIT); --index) {
const routeLabel = sender.navigationHistory.getEntryAtIndex(index)?.title
dropdownOptions.push({
label: routeLabel,
value: index - activeIndex,
active: index === activeIndex
})
}
return dropdownOptions
})
// #endregion navigation history
ipcMain.handle(IpcChannels.OPEN_EXTERNAL_LINK, (_, url) => {
if (typeof url === 'string') {
let parsedURL
try {
parsedURL = new URL(url)
} catch {
// If it's not a valid URL don't open it
return false
}
if (
parsedURL.protocol === 'http:' || parsedURL.protocol === 'https:' ||
// Email address on the about page and Autolinker detects and links email addresses
parsedURL.protocol === 'mailto:' ||
// Autolinker detects and links phone numbers
parsedURL.protocol === 'tel:' ||
// Donation links on the about page
(parsedURL.protocol === 'bitcoin:' && parsedURL.pathname === ABOUT_BITCOIN_ADDRESS)
) {
shell.openExternal(url)
return true
}
}
return false
})
ipcMain.handle(IpcChannels.GET_SYSTEM_LOCALE, () => {
// we should switch to getPreferredSystemLanguages at some point and iterate through until we find a supported locale
return app.getSystemLocale()
})
ipcMain.handle(IpcChannels.GET_PICTURES_PATH, () => {
return app.getPath('pictures')
})
ipcMain.handle(IpcChannels.SHOW_OPEN_DIALOG, async ({ sender }, options) => {
const senderWindow = findSenderWindow(sender)
if (senderWindow) {
return await dialog.showOpenDialog(senderWindow, options)
}
return await dialog.showOpenDialog(options)
})
ipcMain.handle(IpcChannels.SHOW_SAVE_DIALOG, async ({ sender }, options) => {
const senderWindow = findSenderWindow(sender)
if (senderWindow) {
return await dialog.showSaveDialog(senderWindow, options)
}
return await dialog.showSaveDialog(options)
})
function findSenderWindow(sender) {
return BrowserWindow.getAllWindows().find((window) => {
return window.webContents.id === sender.id
})
}