OSDN Git Service

update the port retry logic
[bytom/bytom-electron.git] / main.js
diff --git a/main.js b/main.js
index 5713424..c1dc180 100644 (file)
--- a/main.js
+++ b/main.js
@@ -1,18 +1,25 @@
+require('babel-register')
+require('events').EventEmitter.defaultMaxListeners = 100
 const {app, BrowserWindow, ipcMain, shell} = require('electron')
 const spawn = require('child_process').spawn
 const glob = require('glob')
 const url = require('url')
 const path = require('path')
 const fs = require('fs')
-const toml = require('toml')
-const logger = require('./main-process/logger')
+const logger = require('./modules/logger')
 const log = logger.create('main')
 const bytomdLog = logger.create('bytomd')
+const Settings = require('./modules/settings')
 
-let win, bytomdInit, bytomdMining
+const tcpPortUsed = require('tcp-port-used');
+
+let win, bytomdInit, bytomdNode
 
 global.fileExist = false
 global.mining = {isMining: false}
+let startnode = false
+
+Settings.init()
 
 function initialize () {
 
@@ -25,7 +32,7 @@ function initialize () {
       height: 768,
       'webPreferences': {
         'webSecurity': !process.env.DEV_URL,
-        'preload': path.join(__dirname, '/main-process/preload.js')
+        'preload': path.join(__dirname, '/modules/preload.js')
       },
       icon: icon_path
     })
@@ -47,6 +54,11 @@ function initialize () {
       shell.openExternal(url)
     })
 
+    win.webContents.on('did-finish-load', function () {
+      if(startnode){
+        win.webContents.send('ConfiguredNetwork', 'startNode')
+      }
+    })
 
     win.on('closed', () => {
       win = null
@@ -83,71 +95,65 @@ function initialize () {
       bytomdInit.kill('SIGINT')
       log.info('Kill bytomd Init command...')
     }
-    if(bytomdMining){
-      bytomdMining.kill('SIGINT')
+    if(bytomdNode){
+      bytomdNode.kill('SIGINT')
       const killTimeout = setTimeout(() => {
-        bytomdMining.kill('SIGKILL')
+        bytomdNode.kill('SIGKILL')
       }, 8000 /* 8 seconds */)
 
-      bytomdMining.once('close', () => {
+      bytomdNode.once('close', () => {
         clearTimeout(killTimeout)
-        bytomdMining = null
+        bytomdNode = null
       })
 
       log.info('Kill bytomd Mining command...')
     }
   })
 }
-const bytomdPath = process.env.DEV?
-  path.join(__dirname, '/bytomd/bytomd-darwin_amd64'):
-  glob.sync( path.join(__dirname, '/bytomd/bytomd*').replace('app.asar', 'app.asar.unpacked'))
-
-let bytomdDataPath
-switch (process.platform){
-  case 'win32':
-    bytomdDataPath = `${app.getPath('appData')}/Bytom`
-    break
-  case 'darwin':
-    bytomdDataPath = `${app.getPath('home')}/Library/Bytom`
-    break
-  case 'linux':
-    bytomdDataPath = `${app.getPath('home')}/.bytom`
-}
 
-function setBytomMining(event) {
-  bytomdMining = spawn( `${bytomdPath}`, ['node', '--web.closed'] )
+function setBytomNode(event) {
+  bytomdNode = spawn( `${Settings.bytomdPath}`, ['node', '--web.closed'] )
 
-  bytomdMining.stdout.on('data', function(data) {
-    bytomdLog.info(`bytomd mining stdout: ${data}`)
+  bytomdNode.stdout.on('data', function(data) {
+    bytomdLog.info(`bytomd node: ${data}`)
   })
 
-  bytomdMining.stderr.on('data', function(data) {
-    bytomdLog.info(`bytomd mining stderr: ${data}`)
-    if(data.includes('msg="Started node"') && event){
-      event.sender.send('ConfiguredNetwork','startNode')
-    }
+  bytomdNode.stderr.on('data', function(data) {
+    bytomdNode.on('exit', function (code) {
+      bytomdLog.info('bytom Node exited with code ' + code)
+      app.quit()
+    })
   })
 
-  bytomdMining.on('exit', function (code) {
-    bytomdLog.info('bytom Mining exited with code ' + code)
-  })
+  tcpPortUsed.waitUntilUsed(9888, 500, 20000)
+    .then(function() {
+      if (event) {
+        event.sender.send('ConfiguredNetwork', 'startNode')
+      }
+      else {
+        startnode = true
+        win.webContents.send('ConfiguredNetwork', 'startNode')
+      }
+    }, function(err) {
+      bytomdLog.info('Error:', err.message);
+    });
 }
 
 function setBytomInit(event, bytomNetwork) {
   // Init bytomd
-  bytomdInit = spawn(`${bytomdPath}`, ['init', '--chain_id',  `${bytomNetwork}`] )
+  bytomdInit = spawn(`${Settings.bytomdPath}`, ['init', '--chain_id',  `${bytomNetwork}`] )
 
   bytomdInit.stdout.on('data', function(data) {
-    bytomdLog.info(`bytomd init stdout: ${data}`)
+    bytomdLog.info(`bytomd init: ${data}`)
   })
 
   bytomdInit.stderr.on('data', function(data) {
-    bytomdLog.info(`bytomd init stderr: ${data}`)
+    bytomdLog.info(`bytomd init: ${data}`)
   })
 
   bytomdInit.on('exit', function (code) {
     event.sender.send('ConfiguredNetwork','init')
-    setBytomMining(event)
+    setBytomNode(event)
     bytomdLog.info('bytom init exited with code ' + code)
   })
 
@@ -157,35 +163,22 @@ function setBytomInit(event, bytomNetwork) {
 }
 
 function bytomd(){
-  const filePath = path.join(`${bytomdDataPath}/config.toml`)
-
-  fs.stat(`${filePath}`, function(err) {
-    if(err == null) {
-      log.info('Bytomd Network has been inited')
-      global.fileExist = true
-      setBytomMining()
-
-      let genesisFile = fs.readFileSync(filePath)
-      genesisFile = toml.parse(genesisFile)
-
-      global.networkStatus = genesisFile.chain_id
-
-    } else if(err.code == 'ENOENT') {
-      //wait for the int network call
-      log.info('Init Bytomd Network')
-      ipcMain.on('bytomdInitNetwork', (event, arg) => {
-        setBytomInit( event,  arg )
-        global.networkStatus = arg
-      })
-    } else {
-      log.error('Some other error: ', err.code)
-    }
-  })
+  const filePath = path.join(`${Settings.bytomdDataPath}/config.toml`)
+  if (fs.existsSync(filePath)) {
+    log.info('Bytomd Network has been inited')
+    global.fileExist = true
+    setBytomNode()
+  }else {
+    log.info('Init Bytomd Network...')
+    ipcMain.on('bytomdInitNetwork', (event, arg) => {
+      setBytomInit( event,  arg )
+    })
+  }
 }
 
 // Require each JS file in the main-process dir
 function loadMenu () {
-  const files = glob.sync(path.join(__dirname, 'main-process/menus/*.js'))
+  const files = glob.sync(path.join(__dirname, 'modules/menus/*.js'))
   files.forEach((file) => { require(file) })
 }
 
@@ -195,6 +188,7 @@ function setupConfigure(){
   logger.setup(loggerOptions)
 }
 
+
 // Handle Squirrel on Windows startup events
 switch (process.argv[1]) {
   case '--squirrel-install':