forked from OpenBazaar/OpenBazaar-Client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
420 lines (362 loc) · 11.9 KB
/
main.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
"use strict";
// Check that the deps in node_modules match what's in package.json.
var safestart = require('safestart');
safestart(__dirname);
var fs = require('fs');
var path = require('path');
var argv = require('yargs').argv;
var app = require('app'); // Module to control application life.
var electron = require('electron');
var BrowserWindow = electron.BrowserWindow; // Module to create native browser window.
var request = require('request');
var os = require('os');
var autoUpdater = require('auto-updater');
var menu = require('menu');
var tray = require('tray');
var ipcMain = require('ipc-main');
var ini = require('ini');
var dialog = require('electron').dialog;
var launched_from_installer = false;
var platform = os.platform();
switch(platform) {
case "darwin":
platform = "mac";
}
var version = app.getVersion();
var trayMenu = null;
var subpy = null;
var open_url = null; // This is for if someone opens a URL before the client is open
if (argv.userData) {
try {
app.setPath('userData', argv.userData);
} catch (e) {
throw new Error('The passed in userData directory does not appear to be valid: ' + e);
}
}
var handleStartupEvent = function() {
if (process.platform !== 'win32') {
return false;
}
var squirrelCommand = process.argv[1];
function exeSquirrelCommand(args, cb) {
var updateDotExe = path.resolve(path.dirname(process.execPath), '..', 'update.exe');
var child = require('child_process').spawn(updateDotExe, args, { detached: true });
child.on('close', function() {
cb();
});
};
function install(cb) {
var target = path.basename(process.execPath);
exeSquirrelCommand(["--createShortcut", target], cb);
};
function uninstall(cb) {
var target = path.basename(process.execPath);
exeSquirrelCommand(["--removeShortcut", target], cb);
};
switch (squirrelCommand) {
case '--squirrel-install':
install(app.quit);
case '--squirrel-updated':
// Always quit when done
app.quit();
return true;
case '--squirrel-uninstall':
// Always quit when done
uninstall(app.quit);
return true;
case '--squirrel-obsolete':
// This is called on the outgoing version of your app before
// we update to the new version - it's the opposite of
// --squirrel-updated
app.quit();
return true;
}
};
if (handleStartupEvent()) {
console.log('Client started on Windows...');
}
// Set daemon binary name
var daemon = "openbazaard.exe";
if(platform == "mac" || platform == "linux") {
daemon = "openbazaard";
}
var serverPath = __dirname + path.sep + '..' + path.sep + 'OpenBazaar-Server' + path.sep;
var serverOut = '';
var start_local_server = function() {
if(fs.existsSync(serverPath)) {
var random_port = Math.floor((Math.random() * 10000) + 30000);
subpy = require('child_process').spawn(serverPath + daemon, ['start', '--testnet', '--loglevel', 'debug', '-p', random_port], {
detach: false,
cwd: __dirname + path.sep + '..' + path.sep + 'OpenBazaar-Server'
});
var stdout = '';
var stderr = '';
subpy.stdout.on('data', function (buf) {
console.log('[STR] stdout "%s"', String(buf));
stdout += buf;
serverOut += buf;
});
subpy.stderr.on('data', function (buf) {
console.log('[STR] stderr "%s"', String(buf));
stderr += buf;
});
subpy.on('error', function (err) {
console.log('Python error %s', String(err));
});
subpy.on('close', function (code) {
console.log('exited with ' + code);
console.log('[END] stdout "%s"', stdout);
console.log('[END] stderr "%s"', stderr);
});
subpy.unref();
}
if (fs.existsSync(__dirname + path.sep + '..' + path.sep + 'gpg')) {
process.env.PATH = __dirname + path.sep + '..' + path.sep + 'gpg' + path.sep + 'pub' + path.sep + ';' + process.env.PATH;
}
};
// Check if we need to kick off the python server-daemon (Desktop app)
if(fs.existsSync(__dirname + path.sep + ".." + path.sep + "OpenBazaar-Server" + path.sep + daemon)) {
launched_from_installer = true;
console.log('Starting OpenBazaar Server');
start_local_server();
}
// Report crashes to our server.
//require('crash-reporter').start();
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is GCed.
var mainWindow = null;
// Quit when all windows are closed.
app.on('window-all-closed', function() {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (platform != 'mac') {
app.quit();
}
});
// You can use 'before-quit' instead of (or with) the close event
app.on('before-quit', function (e) {
// Handle menu-item or keyboard shortcut quit here
console.log('Closing Application');
if(launched_from_installer) {
console.log('Shutting down server daemon');
subpy.kill();
}
});
app.commandLine.appendSwitch('ignore-certificate-errors', true);
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', function() {
// Application Menu
var appMenu = menu.buildFromTemplate([
{
label: 'OpenBazaar',
submenu: [
{
label: 'Quit OpenBazaar',
accelerator: 'CmdOrCtrl+Q',
click: function() {
app.quit();
}
}
]
},
{
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:" }
]
},
{
label: 'View',
submenu: [
{
label: 'Reload',
accelerator: 'CmdOrCtrl+R',
click: function(item, focusedWindow) {
if (focusedWindow) {
focusedWindow.reload();
}
}
},
{
label: 'Toggle Developer Tools',
accelerator: (function() {
if (platform == 'mac') {
return 'Alt+Command+I';
} else {
return 'Ctrl+Shift+I';
}
})(),
click: function(item, focusedWindow) {
if (focusedWindow) {
focusedWindow.toggleDevTools();
}
}
},
{
label: 'Toggle Full Screen',
accelerator: (function() {
if (platform == 'mac') {
return 'Ctrl+Command+F';
} else {
return 'F11';
}
})(),
click: function(item, focusedWindow) {
var fullScreen;
if (mainWindow) {
fullScreen = !mainWindow.isFullScreen();
mainWindow.setFullScreen(fullScreen);
if (fullScreen) {
mainWindow.webContents.send('fullscreen-enter');
} else {
mainWindow.webContents.send('fullscreen-exit');
}
}
}
},
]
},
{
label: 'Window',
submenu: [
{
label: 'Minimize',
accelerator: 'Command+M',
selector: 'performMiniaturize:'
},
{
label: 'Close',
accelerator: 'Command+W',
selector: 'performClose:'
},
{
type: 'separator'
},
{
label: 'Bring All to Front',
selector: 'arrangeInFront:'
}
]
}
]);
menu.setApplicationMenu(appMenu);
// put logic here to set tray icon based on OS
var osTrayIcon = 'openbazaar-mac-system-tray.png';
trayMenu = new tray(__dirname + '/imgs/' + osTrayIcon);
var contextMenu = menu.buildFromTemplate([
{
label: 'Start Local Server', type: 'normal', click: function () {
start_local_server();
}
},
{
label: 'Shutdown Local Server', type: 'normal', click: function () {
request('http://localhost:18469/api/v1/shutdown', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log('Shutting down server');
} else {
console.log('Server does not seem to be running.');
}
});
}
},
{type: 'separator'},
{label: 'View Debug Log', type: 'normal', click: function() {
var debugPath = serverPath + path.sep + 'debug.txt';
fs.writeFile(debugPath, serverOut, (err) => {
if (err) {
dialog.showErrorBox('Unable To Open Debug Log',
'There was an error and we are unable to open the server debug log at this time.\n\n' + err);
}
require('open')(debugPath);
});
}},
{type: 'separator'},
{
label: 'Quit', type: 'normal', accelerator: 'Command+Q', click: function () {
app.quit();
}
}
]);
trayMenu.setContextMenu(contextMenu);
// Create the browser window.
mainWindow = new BrowserWindow({
"width": 1200,
"height": 720,
"min-width": 1024,
"min-height": 700,
"center": true,
"title": "OpenBazaar",
"frame": false,
"icon": "imgs/openbazaar-icon.png",
"title-bar-style": "hidden"
});
// and load the index.html of the app.
if(open_url) {
mainWindow.loadURL('file://' + __dirname + '/index.html' + open_url);
} else {
mainWindow.loadURL('file://' + __dirname + '/index.html');
}
// Open the devtools.
// Uncomment if you want tools to open on startup
//mainWindow.openDevTools({detach: true});
// Emitted when the window is closed.
mainWindow.on('closed', function() {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null;
if(subpy) {
if(platform == "mac" || platform == "linux") {
subpy.kill('SIGHUP');
} else {
require('child_process').spawn("taskkill", ["/pid", subpy.pid, '/f', '/t']);
}
}
});
mainWindow.on('close', function() {
app.quit();
});
app.on('activate', function() {
mainWindow.show();
});
autoUpdater.on("error", function(err, msg) {
console.log(msg); //print msg , you can find the cash reason.
});
autoUpdater.on("update-not-available", function(msg) {
mainWindow.webContents.executeJavaScript("console.log('Update not available! Your software is up to date.')");
});
autoUpdater.on("update-available", function() {
mainWindow.webContents.executeJavaScript("console.log('Update available! Downloading now...')");
});
autoUpdater.on("update-downloaded", function(e, releaseNotes, releaseName, releaseDate, updateUrl, quitAndUpdate) {
mainWindow.webContents.executeJavaScript("console.log('Update downloaded." + updateUrl + "')");
mainWindow.webContents.executeJavaScript('$(".js-softwareUpdate").removeClass("softwareUpdateHidden");');
});
ipcMain.on('installUpdate', function(event) {
console.log('Installing Update');
autoUpdater.quitAndInstall();
});
var feedURL = 'http://updates.openbazaar.org:5000/update/' + platform + '/' + version;
autoUpdater.setFeedURL(feedURL);
mainWindow.webContents.executeJavaScript("console.log('Checking for new versions at " + feedURL + " ...')");
autoUpdater.checkForUpdates();
});
app.on('open-url', function(event, uri) {
var split_uri = uri.split('://');
uri = split_uri[1];
global.externalRoute = uri;
if (mainWindow) {
// if our app router is fully loaded it will process the event sent below, otherwise
// the global.externalRoute will be used
mainWindow.webContents.send('external-route', uri);
}
event.preventDefault();
});