-
-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathindex.js
More file actions
631 lines (558 loc) · 21.5 KB
/
Copy pathindex.js
File metadata and controls
631 lines (558 loc) · 21.5 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
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
const remoteMain = require('@electron/remote/main')
remoteMain.initialize()
// Requirements
const { app, BrowserWindow, ipcMain, Menu, shell } = require('electron')
const autoUpdater = require('electron-updater').autoUpdater
const ejse = require('ejs-electron')
const isDev = require('./app/assets/js/isdev')
const path = require('path')
const semver = require('semver')
const { pathToFileURL } = require('url')
const { AZURE_CLIENT_ID, MC_LAUNCHER_CLIENT_ID, MSFT_OPCODE, MSFT_REPLY_TYPE, MSFT_ERROR, SHELL_OPCODE } = require('./app/assets/js/ipcconstants')
const LangLoader = require('./app/assets/js/langloader')
const { default: got } = require('got')
const fs = require('fs')
const fsExtra = require('fs-extra')
const crypto = require('crypto')
app.setAsDefaultProtocolClient('numalauncher')
let deepLinkUrl = null
let win
const gotLock = app.requestSingleInstanceLock()
if (!gotLock) {
app.quit()
} else {
app.on('second-instance', (event, argv, workingDirectory) => {
const deeplinkArg = argv.find(arg => arg.startsWith('numalauncher://'))
if (deeplinkArg) {
if (win) {
if (win.isMinimized()) win.restore()
win.focus()
handleDeepLink(deeplinkArg)
} else {
deepLinkUrl = deeplinkArg
}
}
})
}
// URI起動mac用
app.on('open-url', (event, url) => {
event.preventDefault()
deepLinkUrl = url
})
// URI起動win用
app.on('ready', () => {
const args = process.argv
deepLinkUrl = args.find(arg => arg.startsWith('numalauncher://'))
})
// アプリ準備ができたら
app.whenReady().then(() => {
// ページの読み込み完了後に処理
win.webContents.once('did-finish-load', () => {
if (deepLinkUrl) {
handleDeepLink(deepLinkUrl)
deepLinkUrl = null
}
})
})
function handleDeepLink(url) {
const parsedUrl = new URL(url)
const query = parsedUrl.searchParams.get('query')
if (win && win.webContents) {
win.webContents.send('setServerOption', query)
}
}
// Setup Lang
LangLoader.setupLanguage()
// Setup auto updater.
function initAutoUpdater(event, data) {
if(data){
autoUpdater.allowPrerelease = true
} else {
// Defaults to true if application version contains prerelease components (e.g. 0.12.1-alpha.1)
// autoUpdater.allowPrerelease = true
}
if(isDev){
autoUpdater.autoInstallOnAppQuit = false
autoUpdater.updateConfigPath = path.join(__dirname, 'dev-app-update.yml')
}
if(process.platform === 'darwin'){
autoUpdater.autoDownload = false
}
autoUpdater.on('update-available', (info) => {
event.sender.send('autoUpdateNotification', 'update-available', info)
})
autoUpdater.on('update-downloaded', (info) => {
event.sender.send('autoUpdateNotification', 'update-downloaded', info)
})
autoUpdater.on('update-not-available', (info) => {
event.sender.send('autoUpdateNotification', 'update-not-available', info)
})
autoUpdater.on('checking-for-update', () => {
event.sender.send('autoUpdateNotification', 'checking-for-update')
})
autoUpdater.on('error', (err) => {
event.sender.send('autoUpdateNotification', 'realerror', err)
})
}
// Open channel to listen for update actions.
ipcMain.on('autoUpdateAction', (event, arg, data) => {
switch(arg){
case 'initAutoUpdater':
console.log('Initializing auto updater.')
initAutoUpdater(event, data)
event.sender.send('autoUpdateNotification', 'ready')
break
case 'checkForUpdate':
autoUpdater.checkForUpdates()
.catch(err => {
event.sender.send('autoUpdateNotification', 'realerror', err)
})
break
case 'allowPrereleaseChange':
if(!data){
const preRelComp = semver.prerelease(app.getVersion())
if(preRelComp != null && preRelComp.length > 0){
autoUpdater.allowPrerelease = true
} else {
autoUpdater.allowPrerelease = data
}
} else {
autoUpdater.allowPrerelease = data
}
break
case 'installUpdateNow':
autoUpdater.quitAndInstall()
break
default:
console.log('Unknown argument', arg)
break
}
})
// Redirect distribution index event from preloader to renderer.
ipcMain.on('distributionIndexDone', (event, res) => {
event.sender.send('distributionIndexDone', res)
})
// 手動ダウンロード画面
! function() {
// ウィンドウID管理
let manualWindowIndex = 0
let manualWindows = []
// ダウンロードID管理
let downloadIndex = 0
// ダウンロードフォルダ
const downloadDirectory = path.join(app.getPath('temp'), 'NumaLauncher', 'ManualDownloads')
// IDでウィンドウを閉じる
ipcMain.on('closeManualWindow', (ipcEvent, index) => {
// IDを探してウィンドウを閉じる
const window = manualWindows[index]
if (window !== undefined) {
window.win.close()
manualWindows[index] = undefined
}
})
// IDでウィンドウを閉じる
ipcMain.on('preventManualWindowRedirect', (ipcEvent, index, prevent) => {
// IDを探してリダイレクト可否フラグ変更
const window = manualWindows[index]
if (window !== undefined) {
window.preventRedirect = prevent
}
})
// 手動ダウンロード用のウィンドウを開く
ipcMain.on('openManualWindow', (ipcEvent, result) => {
// ハッシュチェック
function validateLocal(filePath, algo, hash) {
if (fs.existsSync(filePath)) {
//No hash provided, have to assume it's good.
if (hash == null) {
return true
}
let buf = fs.readFileSync(filePath)
let calcdhash = crypto.createHash(algo).update(buf).digest('hex')
return calcdhash === hash.toLowerCase()
}
return false
}
for (let manual of result.manualData) {
const index = ++manualWindowIndex
const win = new BrowserWindow({
width: 1280,
height: 720,
icon: getPlatformIcon('SealCircle'),
autoHideMenuBar: true,
webPreferences: {
preload: path.join(__dirname, 'app', 'assets', 'js', 'manualpreloader.js'),
nodeIntegration: false,
contextIsolation: true, // TODO デバッグ後はtrue
enableRemoteModule: false,
worldSafeExecuteJavaScript: true,
partition: `manual-${index}`, // パーティションを分けることでウィンドウを超えてwill-downloadイベント同士が作用しあわない
}
})
manualWindows[index] = {
win,
manual,
preventRedirect: false,
}
// セキュリティポリシー無効化
win.webContents.session.webRequest.onHeadersReceived((d, c) => {
if (d.responseHeaders['Content-Security-Policy']) {
delete d.responseHeaders['Content-Security-Policy']
} else if (d.responseHeaders['content-security-policy']) {
delete d.responseHeaders['content-security-policy']
}
c({ cancel: false, responseHeaders: d.responseHeaders })
})
// ウィンドウ開いた直後(ページ遷移時を除く)のみ最初のダイアログ表示
win.webContents.send('manual-first')
// ロードが終わったら案内情報のデータをレンダープロセスに送る
win.webContents.on('dom-ready', (event, args) => {
if (win.isDestroyed())
return
win.webContents.send('manual-data', manual, index)
})
// リダイレクトキャンセル
win.webContents.on('will-navigate', (event, args) => {
if (win.isDestroyed())
return
const window = manualWindows[index]
if (window !== undefined) {
if (window.preventRedirect)
event.preventDefault()
}
})
// ダウンロードされたらファイル名をすり替え、ハッシュチェックする
win.webContents.session.on('will-download', (event, item, webContents) => {
if (win.isDestroyed())
return
downloadIndex++
// 一時フォルダに保存
item.setSavePath(path.join(downloadDirectory, item.getFilename()))
// 進捗を送信 (開始)
win.webContents.send('download-start', {
index: downloadIndex,
name: manual.manual.name,
received: item.getReceivedBytes(),
total: item.getTotalBytes(),
})
// 進捗を送信 (進行中)
item.on('updated', (event, state) => {
if (win.isDestroyed())
return
win.webContents.send('download-progress', {
index: downloadIndex,
name: manual.manual.name,
received: item.getReceivedBytes(),
total: item.getTotalBytes(),
})
})
// 進捗を送信 (完了)
item.once('done', (event, state) => {
if (win.isDestroyed())
return
// ファイルが正しいかチェックする
const v = item.getTotalBytes() === manual.size &&
validateLocal(item.getSavePath(), 'md5', manual.MD5)
if (!v) {
// 違うファイルをダウンロードしてしまった場合
win.webContents.send('download-end', {
index: downloadIndex,
name: manual.manual.name,
state: 'hash-failed',
})
} else if (fsExtra.existsSync(manual.path)) {
// ファイルが既にあったら閉じる
win.close()
} else {
// ファイルを正しい位置に移動
fsExtra.moveSync(item.getSavePath(), manual.path)
// 完了を通知
win.webContents.send('download-end', {
index: downloadIndex,
name: manual.manual.name,
state,
})
}
})
})
// ダウンロードサイトを表示
win.loadURL(manual.manual.url)
}
})
app.on('quit', () => {
// tmpディレクトリお掃除
fsExtra.removeSync(downloadDirectory)
})
}()
// Handle trash item.
ipcMain.handle(SHELL_OPCODE.TRASH_ITEM, async (event, ...args) => {
try {
await shell.trashItem(args[0])
return {
result: true
}
} catch(error) {
return {
result: false,
error: error
}
}
})
ipcMain.on('get-launcher-skin-path', (event) => {
event.returnValue = app.getPath('appData')
})
ipcMain.on('get-home-path', (event) => {
event.returnValue = app.getPath('home')
})
// Hardware acceleration setting.
// https://electronjs.org/docs/tutorial/offscreen-rendering
const configPath = path.join(app.getPath('userData'), 'config.json')
let hardwareAcceleration = true
try {
if (fs.existsSync(configPath)) {
const config = JSON.parse(fs.readFileSync(configPath, 'utf8'))
hardwareAcceleration = config.settings?.launcher?.hardwareAcceleration ?? true
}
} catch (e) {
// Ignore errors, use default (enabled)
}
if (!hardwareAcceleration) {
app.disableHardwareAcceleration()
}
const REDIRECT_URI_PREFIX = 'https://login.microsoftonline.com/common/oauth2/nativeclient?'
const REDIRECT_URI_PREFIX_LIVE = 'https://login.live.com/oauth20_desktop.srf?'
// Microsoft Auth Login
let msftAuthWindow
let msftAuthSuccess
let msftAuthViewSuccess
let msftAuthViewOnClose
let msftAuthViewMsMcLauncherAuth
ipcMain.on(MSFT_OPCODE.OPEN_LOGIN, (ipcEvent, ...arguments_) => {
if (msftAuthWindow) {
ipcEvent.reply(MSFT_OPCODE.REPLY_LOGIN, MSFT_REPLY_TYPE.ERROR, MSFT_ERROR.ALREADY_OPEN, msftAuthViewOnClose, msftAuthViewMsMcLauncherAuth)
return
}
msftAuthSuccess = false
msftAuthViewSuccess = arguments_[0]
msftAuthViewOnClose = arguments_[1]
msftAuthViewMsMcLauncherAuth = arguments_[2]
msftAuthWindow = new BrowserWindow({
title: LangLoader.queryJS('index.microsoftLoginTitle'),
backgroundColor: '#222222',
width: 520,
height: 600,
frame: true,
icon: getPlatformIcon('SealCircle')
})
msftAuthWindow.on('closed', () => {
msftAuthWindow = undefined
})
msftAuthWindow.on('close', () => {
if(!msftAuthSuccess) {
ipcEvent.reply(MSFT_OPCODE.REPLY_LOGIN, MSFT_REPLY_TYPE.ERROR, MSFT_ERROR.NOT_FINISHED, msftAuthViewOnClose, msftAuthViewMsMcLauncherAuth)
}
})
msftAuthWindow.webContents.on('did-navigate', (_, uri) => {
// 二重処理防止
if (msftAuthSuccess) {
return
}
if (uri.startsWith(REDIRECT_URI_PREFIX) || uri.startsWith(REDIRECT_URI_PREFIX_LIVE)) {
const queryMap = {}
new URL(uri).searchParams.forEach((v, k) => {
queryMap[k] = v
})
// デバッグログ
if (queryMap.code) {
const codeLen = queryMap.code.length
const codeMasked = queryMap.code.substring(0, 5) + '...' + queryMap.code.substring(codeLen - 5)
console.log(`[MSAuth] callback: code=${codeMasked}, len=${codeLen}, hasSpace=${queryMap.code.includes(' ')}`)
}
msftAuthSuccess = true
ipcEvent.reply(MSFT_OPCODE.REPLY_LOGIN, MSFT_REPLY_TYPE.SUCCESS, queryMap, msftAuthViewSuccess, msftAuthViewMsMcLauncherAuth)
msftAuthWindow.close()
msftAuthWindow = null
}
})
msftAuthWindow.removeMenu()
if (msftAuthViewMsMcLauncherAuth) {
msftAuthWindow.loadURL(`https://login.live.com/oauth20_authorize.srf?prompt=select_account&client_id=${MC_LAUNCHER_CLIENT_ID}&response_type=code&scope=service::user.auth.xboxlive.com::MBI_SSL&lw=1&fl=dob,easi2&xsup=1&nopa=2&redirect_uri=https://login.live.com/oauth20_desktop.srf`)
} else {
msftAuthWindow.loadURL(`https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize?prompt=select_account&client_id=${AZURE_CLIENT_ID}&response_type=code&scope=XboxLive.signin%20offline_access&redirect_uri=https://login.microsoftonline.com/common/oauth2/nativeclient`)
}
})
// Microsoft Auth Logout
let msftLogoutWindow
let msftLogoutSuccess
let msftLogoutSuccessSent
ipcMain.on(MSFT_OPCODE.OPEN_LOGOUT, (ipcEvent, uuid, isLastAccount) => {
if (msftLogoutWindow) {
ipcEvent.reply(MSFT_OPCODE.REPLY_LOGOUT, MSFT_REPLY_TYPE.ERROR, MSFT_ERROR.ALREADY_OPEN)
return
}
msftLogoutSuccess = false
msftLogoutSuccessSent = false
msftLogoutWindow = new BrowserWindow({
title: LangLoader.queryJS('index.microsoftLogoutTitle'),
backgroundColor: '#222222',
width: 520,
height: 600,
frame: true,
icon: getPlatformIcon('SealCircle')
})
msftLogoutWindow.on('closed', () => {
msftLogoutWindow = undefined
})
msftLogoutWindow.on('close', () => {
if(!msftLogoutSuccess) {
ipcEvent.reply(MSFT_OPCODE.REPLY_LOGOUT, MSFT_REPLY_TYPE.ERROR, MSFT_ERROR.NOT_FINISHED)
} else if(!msftLogoutSuccessSent) {
msftLogoutSuccessSent = true
ipcEvent.reply(MSFT_OPCODE.REPLY_LOGOUT, MSFT_REPLY_TYPE.SUCCESS, uuid, isLastAccount)
}
})
msftLogoutWindow.webContents.on('did-navigate', (_, uri) => {
if(uri.startsWith('https://login.microsoftonline.com/common/oauth2/v2.0/logoutsession')) {
msftLogoutSuccess = true
setTimeout(() => {
if(!msftLogoutSuccessSent) {
msftLogoutSuccessSent = true
ipcEvent.reply(MSFT_OPCODE.REPLY_LOGOUT, MSFT_REPLY_TYPE.SUCCESS, uuid, isLastAccount)
}
if(msftLogoutWindow) {
msftLogoutWindow.close()
msftLogoutWindow = null
}
}, 5000)
}
})
msftLogoutWindow.removeMenu()
msftLogoutWindow.loadURL('https://login.microsoftonline.com/common/oauth2/v2.0/logout')
})
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
async function createWindow() {
win = new BrowserWindow({
width: 980,
height: 552,
icon: getPlatformIcon('SealCircle'),
frame: false,
webPreferences: {
preload: path.join(__dirname, 'app', 'assets', 'js', 'preloader.js'),
nodeIntegration: true,
contextIsolation: false
},
backgroundColor: '#171614'
})
remoteMain.enable(win.webContents)
// 背景画像を取得
const url = 'https://raw.githubusercontent.com/TeamKun/ModPacks/deploy/backgrounds'
const backgrounds = await got.get(`${url}/list.json`, { responseType: 'json' })
.then(res => res.body?.map(name => `${url}/${name}`))
.catch(err => {
console.error(err)
return []
})
const background = backgrounds[Math.floor(Math.random() * backgrounds.length)] ?? ''
const data = {
bkid: background,
lang: (str, placeHolders) => LangLoader.queryEJS(str, placeHolders),
appver: app.getVersion()
}
Object.entries(data).forEach(([key, val]) => ejse.data(key, val))
win.loadURL(pathToFileURL(path.join(__dirname, 'app', 'app.ejs')).toString())
/*win.once('ready-to-show', () => {
win.show()
})*/
win.removeMenu()
win.resizable = true
win.on('closed', () => {
win = null
})
}
function createMenu() {
if(process.platform === 'darwin') {
// Extend default included application menu to continue support for quit keyboard shortcut
let applicationSubMenu = {
label: 'Application',
submenu: [{
label: 'About Application',
selector: 'orderFrontStandardAboutPanel:'
}, {
type: 'separator'
}, {
label: 'Quit',
accelerator: 'Command+Q',
click: () => {
app.quit()
}
}]
}
// New edit menu adds support for text-editing keyboard shortcuts
let editSubMenu = {
label: 'Edit',
submenu: [{
label: 'Undo',
accelerator: 'CmdOrCtrl+Z',
selector: 'undo:'
}, {
label: 'Redo',
accelerator: 'Shift+CmdOrCtrl+Z',
selector: 'redo:'
}, {
type: 'separator'
}, {
label: 'Cut',
accelerator: 'CmdOrCtrl+X',
selector: 'cut:'
}, {
label: 'Copy',
accelerator: 'CmdOrCtrl+C',
selector: 'copy:'
}, {
label: 'Paste',
accelerator: 'CmdOrCtrl+V',
selector: 'paste:'
}, {
label: 'Select All',
accelerator: 'CmdOrCtrl+A',
selector: 'selectAll:'
}]
}
// Bundle submenus into a single template and build a menu object with it
let menuTemplate = [applicationSubMenu, editSubMenu]
let menuObject = Menu.buildFromTemplate(menuTemplate)
// Assign it to the application
Menu.setApplicationMenu(menuObject)
}
}
function getPlatformIcon(filename){
let ext
switch(process.platform) {
case 'win32':
ext = 'ico'
break
case 'darwin':
case 'linux':
default:
ext = 'png'
break
}
return path.join(__dirname, 'app', 'assets', 'images', `${filename}.${ext}`)
}
app.on('ready', createWindow)
app.on('ready', createMenu)
app.on('window-all-closed', () => {
// On macOS it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (win === null) {
createWindow()
}
})