OSDN Git Service

Merge branch 'master' into electron
[bytom/bytom-electron.git] / main.js
1 const {app, BrowserWindow, ipcMain, shell} = require('electron')
2 const spawn = require('child_process').spawn
3 const glob = require('glob')
4 const url = require('url')
5 const path = require('path')
6 const fs = require('fs')
7 const toml = require('toml')
8 const logger = require('./main-process/logger')
9 const log = logger.create('main')
10 const bytomdLog = logger.create('bytomd')
11
12 let win, bytomdInit, bytomdMining
13
14 global.fileExist = false
15 global.mining = {isMining: false}
16
17 function initialize () {
18
19   function createWindow() {
20     // Create browser Window
21
22     const icon_path = path.join(__dirname, '/static/images/app-icon/png/app.png')
23     win = new BrowserWindow({
24       width: 1024 + 208,
25       height: 768,
26       'webPreferences': {
27         'webSecurity': !process.env.DEV_URL,
28         'preload': path.join(__dirname, '/main-process/preload.js')
29       },
30       icon: icon_path
31     })
32
33     const startUrl = process.env.DEV_URL ||
34       url.format({
35         pathname: path.join(__dirname, '/public/index.html'),
36         protocol: 'file:',
37         slashes: true
38       })
39     win.loadURL(startUrl)
40
41     if(process.env.DEV){
42       win.webContents.openDevTools()
43     }
44
45     win.webContents.on('new-window', function(e, url) {
46       e.preventDefault()
47       shell.openExternal(url)
48     })
49
50
51     win.on('closed', () => {
52       win = null
53       app.quit()
54     })
55   }
56
57   app.on('ready', () => {
58
59     loadMenu()
60
61     setupConfigure()
62
63     bytomd()
64
65     createWindow()
66   })
67
68 //All window Closed
69   app.on('window-all-closed', () => {
70     if (process.platform !== 'darwin') {
71       app.quit()
72     }
73   })
74
75   app.on('activate', () => {
76     if (win === null) {
77       createWindow()
78     }
79   })
80
81   app.on('before-quit', () => {
82     if(bytomdInit){
83       bytomdInit.kill('SIGINT')
84       log.info('Kill bytomd Init command...')
85     }
86     if(bytomdMining){
87       bytomdMining.kill('SIGINT')
88       const killTimeout = setTimeout(() => {
89         bytomdMining.kill('SIGKILL')
90       }, 8000 /* 8 seconds */)
91
92       bytomdMining.once('close', () => {
93         clearTimeout(killTimeout)
94         bytomdMining = null
95       })
96
97       log.info('Kill bytomd Mining command...')
98     }
99   })
100 }
101 const bytomdPath = process.env.DEV?
102   path.join(__dirname, '/bytomd/bytomd-darwin_amd64'):
103   glob.sync( path.join(__dirname, '/bytomd/bytomd*').replace('app.asar', 'app.asar.unpacked'))
104
105 let bytomdDataPath
106 switch (process.platform){
107   case 'win32':
108     bytomdDataPath = `${app.getPath('appData')}/Bytom`
109     break
110   case 'darwin':
111     bytomdDataPath = `${app.getPath('home')}/Library/Bytom`
112     break
113   case 'linux':
114     bytomdDataPath = `${app.getPath('home')}/.bytom`
115 }
116
117 function setBytomMining(event) {
118   bytomdMining = spawn( `${bytomdPath}`, ['node', '--web.closed'] )
119
120   bytomdMining.stdout.on('data', function(data) {
121     bytomdLog.info(`bytomd mining: ${data}`)
122   })
123
124   bytomdMining.stderr.on('data', function(data) {
125     bytomdLog.info(`bytomd mining: ${data}`)
126     if(data.includes('msg="Started node"') && event){
127       event.sender.send('ConfiguredNetwork','startNode')
128     }
129   })
130
131   bytomdMining.on('exit', function (code) {
132     bytomdLog.info('bytom Mining exited with code ' + code)
133     app.quit()
134   })
135 }
136
137 function setBytomInit(event, bytomNetwork) {
138   // Init bytomd
139   bytomdInit = spawn(`${bytomdPath}`, ['init', '--chain_id',  `${bytomNetwork}`] )
140
141   bytomdInit.stdout.on('data', function(data) {
142     bytomdLog.info(`bytomd init: ${data}`)
143   })
144
145   bytomdInit.stderr.on('data', function(data) {
146     bytomdLog.info(`bytomd init: ${data}`)
147   })
148
149   bytomdInit.on('exit', function (code) {
150     event.sender.send('ConfiguredNetwork','init')
151     setBytomMining(event)
152     bytomdLog.info('bytom init exited with code ' + code)
153   })
154
155   bytomdInit.once('close', () => {
156     bytomdInit = null
157   })
158 }
159
160 function bytomd(){
161   const filePath = path.join(`${bytomdDataPath}/config.toml`)
162
163   fs.stat(`${filePath}`, function(err) {
164     if(err == null) {
165       log.info('Bytomd Network has been inited')
166       global.fileExist = true
167       setBytomMining()
168
169       let genesisFile = fs.readFileSync(filePath)
170       genesisFile = toml.parse(genesisFile)
171
172       global.networkStatus = genesisFile.chain_id
173
174     } else if(err.code == 'ENOENT') {
175       //wait for the int network call
176       log.info('Init Bytomd Network')
177       ipcMain.on('bytomdInitNetwork', (event, arg) => {
178         setBytomInit( event,  arg )
179         global.networkStatus = arg
180       })
181     } else {
182       log.error('Some other error: ', err.code)
183     }
184   })
185 }
186
187 // Require each JS file in the main-process dir
188 function loadMenu () {
189   const files = glob.sync(path.join(__dirname, 'main-process/menus/*.js'))
190   files.forEach((file) => { require(file) })
191 }
192
193 function setupConfigure(){
194   const logFolder = {logFolder: path.join(app.getPath('userData'), 'logs')}
195   const loggerOptions = Object.assign(logFolder)
196   logger.setup(loggerOptions)
197 }
198
199 // Handle Squirrel on Windows startup events
200 switch (process.argv[1]) {
201   case '--squirrel-install':
202   case '--squirrel-uninstall':
203   case '--squirrel-obsolete':
204   case '--squirrel-updated':
205     app.quit()
206     break
207   default:
208     initialize()
209 }
210