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
|
/*******************************************************************************
* Copyright (c) 2012, 2013 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials are made
* available under the terms of the Eclipse Public License v1.0
* (http://www.eclipse.org/legal/epl-v10.html), and the Eclipse Distribution
* License v1.0 (http://www.eclipse.org/org/documents/edl-v10.html).
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
/*eslint-env node, express, compression*/
var auth = require('./lib/middleware/auth'),
express = require('express'),
http = require('http'),
https = require('https'),
fs = require('fs'),
os = require('os'),
api = require('./lib/api'),
compression = require('compression'),
path = require('path'),
socketio = require('socket.io'),
util = require('util'),
argslib = require('./lib/args'),
ttyShell = require('./lib/tty_shell'),
orion = require('./index.js'),
prefs = require('./lib/controllers/prefs');
// Get the arguments, the workspace directory, and the password file (if configured), then launch the server
var args = argslib.parseArgs(process.argv);
var PORT_LOW = 8082;
var PORT_HIGH = 10082;
var port = args.port || args.p || process.env.PORT || 8081;
var configFile = args.config || args.c || path.join(__dirname, 'orion.conf');
var configParams = argslib.readConfigFileSync(configFile) || {};
function startServer(cb) {
var workspaceArg = args.workspace || args.w;
var workspaceConfigParam = configParams.workspace;
var workspaceDir;
if (workspaceArg) {
// -workspace passed in command line is relative to cwd
workspaceDir = path.resolve(process.cwd(), workspaceArg);
} else if (workspaceConfigParam) {
// workspace param in orion.conf is relative to the server install dir.
workspaceDir = path.resolve(__dirname, workspaceConfigParam);
} else if (configParams.isElectron) {
workspaceDir = path.join(os.homedir(), '.orion', '.workspace');
} else {
workspaceDir = path.join(__dirname, '.workspace');
}
argslib.createDirs([workspaceDir], function() {
var passwordFile = args.password || args.pwd;
argslib.readPasswordFile(passwordFile, function(password) {
var dev = Object.prototype.hasOwnProperty.call(args, 'dev');
var log = Object.prototype.hasOwnProperty.call(args, 'log');
if (dev) {
console.log('Development mode: client code will not be cached.');
}
if (passwordFile) {
console.log(util.format('Using password from file: %s', passwordFile));
}
console.log(util.format('Using workspace: %s', workspaceDir));
var server;
try {
// create web server
var app = express();
if (configParams["orion.https.key"] && configParams["orion.https.cert"]) {
server = https.createServer({
key: fs.readFileSync(configParams["orion.https.key"]),
cert: fs.readFileSync(configParams["orion.https.cert"])
}, app);
} else {
server = http.createServer(app);
}
// Configure middleware
if (log) {
app.use(express.logger('tiny'));
}
if (password || configParams.pwd) {
app.use(auth(password || configParams.pwd));
}
app.use(compression());
app.use(orion({
workspaceDir: workspaceDir,
configParams: configParams,
maxAge: dev ? 0 : undefined,
}));
var io = socketio.listen(server, { 'log level': 1 });
ttyShell.install({ io: io, fileRoot: '/file', workspaceDir: workspaceDir });
server.on('listening', function() {
console.log(util.format('Listening on port %d...', port));
if (cb) {
cb();
}
});
server.on('error', function(err) {
if (err.code === "EADDRINUSE") {
port = Math.floor(Math.random() * (PORT_HIGH - PORT_LOW) + PORT_LOW);
server.listen(port);
}
});
server.listen(port);
} catch (e) {
console.error(e && e.stack);
}
});
});
}
if (process.versions.electron) {
var electron = require('electron'),
autoUpdater = require('./lib/autoUpdater'),
spawn = require('child_process').spawn,
allPrefs = prefs.readPrefs(),
feedURL = configParams["orion.autoUpdater.url"],
version = electron.app.getVersion(),
name = electron.app.getName(),
platform = os.platform(),
arch = os.arch();
configParams.isElectron = true;
electron.app.buildId = configParams["orion.buildId"];
if (feedURL) {
var updateChannel = allPrefs.user && allPrefs.user.updateChannel ? allPrefs.user.updateChannel : configParams["orion.autoUpdater.defaultChannel"],
latestUpdateURL;
if (platform === "linux") {
latestUpdateURL = feedURL + '/download/channel/' + updateChannel + '/linux';
} else {
latestUpdateURL = feedURL + '/update/channel/' + updateChannel + '/' + platform + "_" + arch + '/' + version;
}
var resolveURL = feedURL + '/api/resolve?platform=' + platform + '&channel=' + updateChannel;
autoUpdater.setResolveURL(resolveURL);
autoUpdater.setFeedURL(latestUpdateURL);
}
var handleSquirrelEvent = function() {
if (process.argv.length === 1 || os.platform() !== 'win32') { // No squirrel events to handle
return false;
}
var target = path.basename(process.execPath);
function executeSquirrelCommand(args, done) {
var updateDotExe = path.resolve(path.dirname(process.execPath), '..', 'Update.exe');
var child = spawn(updateDotExe, args, { detached: true });
child.on('close', function() {
done();
});
}
var squirrelEvent = process.argv[1];
switch (squirrelEvent) {
case '--squirrel-install':
case '--squirrel-updated':
// Install desktop and start menu shortcuts
executeSquirrelCommand(["--createShortcut", target], electron.app.quit);
setTimeout(electron.app.quit, 1000);
return true;
case '--squirrel-obsolete':
// This is called on the outgoing version of the app before
// we update to the new version - it's the opposite of
// --squirrel-updated
electron.app.quit();
return true;
case '--squirrel-uninstall':
// Remove desktop and start menu shortcuts
executeSquirrelCommand(["--removeShortcut", target], electron.app.quit);
setTimeout(electron.app.quit, 1000);
return true;
}
return false;
};
if (handleSquirrelEvent()) {
// Squirrel event handled and app will exit in 1000ms
return;
}
var readyToOpenDir, relativeFileUrl;
electron.app.on('open-file', function(event, path) {
readyToOpenDir = path;
});
electron.app.on('ready', function() {
var updateDownloaded = false,
updateDialog = false,
linuxDialog = false,
prefsWorkspace = allPrefs.user && allPrefs.user.workspace && allPrefs.user.workspace.currentWorkspace,
recentWorkspaces = allPrefs.user && allPrefs.user.workspace && allPrefs.user.workspace.recentWorkspaces,
Menu = electron.Menu;
if (prefsWorkspace) {
configParams.workspace = prefsWorkspace;
}
if(readyToOpenDir){
try{
var stats = fs.statSync(readyToOpenDir);
if(stats.isFile()){
var parentDir = path.dirname(readyToOpenDir);
var similarity = 0;
configParams.workspace = parentDir;
recentWorkspaces.forEach(function(eachRecent){
if(parentDir.lastIndexOf(eachRecent,0) === 0 && eachRecent.length > similarity){
similarity = eachRecent.length;
return configParams.workspace = eachRecent;
}
});
relativeFileUrl = api.toURLPath(readyToOpenDir.substring(configParams.workspace.length));
}else if(stats.isDirectory()){
configParams.workspace = readyToOpenDir;
}
}catch(e){}
}
if (process.platform === 'darwin') {
if (!Menu.getApplicationMenu()) {
var template = [{
label: "Application",
submenu: [
{ label: "About Application", selector: "orderFrontStandardAboutPanel:" },
{ type: "separator" },
{ label: "Quit", accelerator: "Command+Q", click: function() { electron.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: "openDevTool", accelerator: "Cmd+Option+I",visible:false, click: function (item, focusedWindow) {
//if windows, add F12 to also open dev tools - depending on electron / windows versions this might not be allowed to be rebound
if (focusedWindow) focusedWindow.webContents.toggleDevTools();
}}
]}
];
Menu.setApplicationMenu(Menu.buildFromTemplate(template));
}
} else {
//always add Ctrl+Shift+I for non-MacOS platforms - matches the browser devs tools shortcut
var template = [makeDevToolMenuItem("Devtool","Ctrl+Shift+I")];
Menu.setApplicationMenu(Menu.buildFromTemplate(template));
}
if(process.platform === "win32") {
var menu = Menu.getApplicationMenu();
//if windows, add F12 to also open dev tools - depending on electron / windows versions this might not be allowed to be rebound
menu.append(new electron.MenuItem(makeDevToolMenuItem("DevtoolforWin32","F12")));
Menu.setApplicationMenu(menu);
}
function makeDevToolMenuItem(label, accelerator){
return {
label: label,
submenu: [
{ label: "openDevTool", accelerator: accelerator, click: function (item, focusedWindow) {
if (focusedWindow) focusedWindow.webContents.toggleDevTools();
}}
]
}
}
autoUpdater.on("error", function(error) {
console.log(error);
});
autoUpdater.on("update-available-automatic", function(newVersion) {
if (platform === "linux" && !linuxDialog) {
electron.dialog.showMessageBox({
type: 'question',
message: 'Update version ' + newVersion + ' is available.',
detail: 'Use your package manager to update, or click Download to get the new package.',
buttons: ['Download', 'OK']
}, function (response) {
if (response === 0) {
electron.shell.openExternal(latestUpdateURL);
} else {
linuxDialog = false;
}
});
linuxDialog = true;
} else {
autoUpdater.checkForUpdates();
}
});
autoUpdater.on("update-downloaded", /* @callback */ function(event, releaseNotes, releaseName, releaseDate, updateURL) {
updateDownloaded = true;
if (!updateDialog) {
electron.dialog.showMessageBox({
type: 'question',
message: 'Update version ' + releaseName + ' of ' + name + ' has been downloaded.',
detail: 'Would you like to restart the app and install the update? The update will be applied automatically upon closing.',
buttons: ['Update', 'Later']
}, function (response) {
if (response === 0) {
autoUpdater.quitAndInstall();
}
});
updateDialog = true;
}
});
function scheduleUpdateChecks () {
var checkInterval = (parseInt(configParams["orion.autoUpdater.checkInterval"], 10) || 30) * 1000 * 60;
var resolveNewVersion = function() {
autoUpdater.resolveNewVersion(false);
}.bind(this);
setInterval(resolveNewVersion, checkInterval);
}
function createWindow(url){
var Url = require("url");
var windowOptions = allPrefs.windowBounds || {width: 1024, height: 800};
windowOptions.title = "Orion";
windowOptions.icon = "icon/256x256/orion.png";
var nextWindow = new electron.BrowserWindow(windowOptions);
nextWindow.setMenuBarVisibility(false); // This line only work for Window and Linux
if (windowOptions.maximized) {
nextWindow.maximize();
}
nextWindow.loadURL("file:///" + __dirname + "/lib/main.html#" + encodeURI(url));
nextWindow.webContents.on("new-window", /* @callback */ function(event, url, frameName, disposition, options){
event.preventDefault();
if (false === undefined) {// Always open new tabs for now
createWindow(url);
}
else if (Url.parse(url).hostname !== "localhost") {
electron.shell.openExternal(url);
}
else {
nextWindow.webContents.executeJavaScript('createTab("' + url + '");');
}
});
nextWindow.on("close", function(event) {
function exit() {
allPrefs = prefs.readPrefs();
allPrefs.windowBounds = nextWindow.getBounds();
allPrefs.windowBounds.maximized = nextWindow.isMaximized();
prefs.writePrefs(allPrefs);
nextWindow.destroy();
}
event.preventDefault();
if (updateDownloaded) {
nextWindow.webContents.session.clearCache(function() {
exit();
});
} else {
exit();
}
});
nextWindow.webContents.once("did-frame-finish-load", function () {
if (feedURL) {
autoUpdater.resolveNewVersion(false);
scheduleUpdateChecks();
}
});
return nextWindow;
}
startServer(function() {
var initialUrl = "http://localhost:" + port;
if(relativeFileUrl){ // Works in Mac Open Command Only
initialUrl = initialUrl + "/edit/edit.html#/file" + relativeFileUrl;
}
var mainWindow = createWindow(initialUrl);
mainWindow.on('closed', function() {
mainWindow = null;
});
});
});
electron.app.on('window-all-closed', function() {
electron.app.quit();
});
} else {
startServer();
}
|