litian
2024-05-28 4e1859708f3c00c9a7b79a3489ac9a6640f8f7b7
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
import { app, BrowserWindow, globalShortcut, dialog, ipcMain } from 'electron'
import path from 'path'
// import fs from 'fs'
import { init as initDownloadTask } from './downloadTask'
// import { init as initExportTask } from './exportTask'
import { checkUpdate } from './update'
 
import axios from 'axios'
import { ctx } from './config'
 
// 用于本地测试更新
// 手动设置为已打包
Object.defineProperty(app, 'isPackaged', {
  get() {
    return true
  }
})
 
let myWindow: any = null
 
const request = axios.create()
 
const development = process.env.NODE_ENV == 'development' ? true : false
 
const createWindow = () => {
  const win = new BrowserWindow({
    minWidth: development ? 1800 : 1300,
    minHeight: development ? 1000 : 800,
    width: development ? 1400 : 1300,
    height: development ? 1000 : 800,
    //窗口是否在屏幕居中. 默认值为 false
    center: true,
    //窗口是否在创建时显示。 默认值为 true。
    show: true,
    title: '数字教材阅读器',
    icon: 'public/favicon.ico',
    webPreferences: {
      // nodeIntegration: true,
      // nodeIntegrationInWorker: true,
      // contextIsolation: true,
      // sandbox: false,
      preload: path.join(__dirname, 'preload.js')
    }
  })
  win.setMenu(null)
  if (development) {
    const elePath = path.join(__dirname, '../node_modules/electron')
    require('electron-reload')('../', {
      electron: require(elePath)
    })
    win.loadURL('http://localhost:8005')
    win.webContents.openDevTools()
  } else {
    win.loadURL(path.join(__dirname, 'index.html'))
  }
 
  globalShortcut.register('CommandOrControl+Shift+i', function () {
    win.webContents.openDevTools()
  })
 
  // 解决应用启动白屏问题
  win.on('ready-to-show', () => {
    win.show()
    win.focus()
  })
 
  request.interceptors.request.use((config) => {
    if (config.url && config.url.indexOf('http') == -1) {
      config.url = ctx + config.url
    }
    return config
  })
 
  // 响应拦截器
  request.interceptors.response.use(
    (response) => {
      return response.data
    },
    (error) => {
      if (error.response && error.response.status == 401) {
        win.webContents.send('logout')
      } else {
        if (error.response && error.response.data && error.response.data.error) {
          console.error(error.response.data.error.msg)
        } else {
          console.error('请求发生错误')
        }
        // dialog.showMessageBox({
        //   type: 'error',
        //   message: '错误',
        //   detail: JSON.stringify(error.response)
        // })
      }
      return Promise.reject(error)
    }
  )
 
  // 业务主体
  // 下载器
  initDownloadTask(win, request)
  // initExportTask(win, request)
 
  checkUpdate(win, ipcMain)
 
  ipcMain.on('openSelectFileOrFolderDialog', (ev, opt) => {
    const path = dialog.showOpenDialogSync(win, opt)
    ev.returnValue = path
  })
 
  return win
}
 
// 获取单实例锁
const gotTheLock = app.requestSingleInstanceLock()
if (!gotTheLock) {
  // 如果获取失败,说明已经有实例在运行了,直接退出
  app.quit()
} else {
  app.whenReady().then(() => {
    myWindow = createWindow()
 
    app.on('activate', () => {
      if (BrowserWindow.getAllWindows().length === 0) createWindow()
    })
 
    // 注册自定义协议
    const agreement = 'DigitalTextbookReader' // 开发环境
 
    app.removeAsDefaultProtocolClient(agreement) // 每次运行都删除自定义协议 然后再重新注册
    // 开发模式下在window运行需要做兼容
    if (development) {
      // 设置electron.exe 和 app的路径
      app.setAsDefaultProtocolClient(agreement, process.execPath, [
        path.resolve(process.argv[1]),
        '--'
      ])
    }
    // 验证是否为自定义协议的链接
    const AGREEMENT_REGEXP = new RegExp(`^${agreement}://`)
 
    // mac唤醒应用 会激活open-url事件 在open-url中判断是否为自定义协议打开事件
    app.on('open-url', (event, url) => {
      const isProtocol = AGREEMENT_REGEXP.test(url)
      if (isProtocol) {
        dialog.showMessageBox({
          type: 'info',
          message: 'Mac protocol 自定义协议打开',
          detail: `自定义协议链接:${url}`
        })
      }
    })
 
    // window系统下唤醒应用会激活second-instance事件 它在ready执行之后才能被监听
    app.on('second-instance', (event, argv) => {
      if (myWindow) {
        if (myWindow.isMinimized()) myWindow.restore()
        myWindow.focus()
      }
      if (process.platform === 'win32') {
        // 开发阶段,跳过前两个参数(`electron.exe .`)
        // 打包后,跳过第一个参数(`myapp.exe`)
        const offset = app.isPackaged ? 1 : 2
        let url: any = argv.find((arg, i) => i >= offset && arg.startsWith(agreement))
        if (url) {
          url = url.replace(`${agreement}://`, '')
          url = url.substr(0, url.length - 1)
        }
        myWindow.webContents.send('openUrl', url)
      }
    })
  })
 
  app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') app.quit()
  })
}