forked from joshuabenuck/wiki-electrified
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
689 lines (641 loc) · 17.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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
const debug = require('debug')
//debug.enable('*')
//debug.enable('express:*')
const crypto = require('crypto')
const origCreateDecipheriv = crypto.createDecipheriv
crypto.createDecipheriv = (alg, key, iv) => {
if (alg == 'aes256') alg = 'aes-256-ctr'
console.log('createDecipheriv', alg)
return origCreateDecipheriv.call(crypto, alg, key, iv)
}
const origCreateCipheriv = crypto.createCipheriv
crypto.createCipheriv = (alg, key, iv) => {
if (alg == 'aes256') alg = 'aes-256-ctr'
console.log('createCipheriv', alg)
return origCreateCipheriv.call(crypto, alg, key, iv)
}
const {
app, Menu, BrowserWindow, BrowserView, ipcMain, getCurrentWindow, shell
} = require('electron')
const optimist = require('optimist')
const cc = require('config-chain')
const server = require('wiki-server')
const path = require('path')
const farm = require('./farm')
const fs = require('fs')
//require("electron-reload")(__dirname)
// begin: taken from wiki/cli.coffee
getUserHome = () => {
return process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE
}
argv = optimist
.usage('Usage: $0')
.options('port', {
alias : 'p',
describe : 'Port'
})
.options('data', {
alias : 'd',
describe : 'location of flat file data'
})
.options('root', {
alias : 'r',
describe : 'Application root folder'
})
.options('farm', {
alias : 'f',
describe : 'Turn on the farm?'
})
.options('security_type', {
describe : 'The security plugin to use, see documentation for additional parameters'
})
.options('secure_cookie', {
describe : 'When true, session cookie will only be sent over SSL.',
boolean : false
})
.options('session_duration', {
describe : 'The wiki logon, session, duration in days'
})
.options('id', {
describe : 'Set the location of the owner identity file'
})
.options('autoseed', {
describe : 'Seed all sites in a farm to each other site in the farm.',
boolean : true
})
.options('allowed', {
describe : 'comma separated list of allowed host names for farm mode.'
})
.options('wikiDomains', {
describe : 'use in farm mode to define allowed wiki domains and any wiki domain specific configuration, see documentation.'
})
.options('uploadLimit', {
describe : 'Set the upload size limit, limits the size page content items, and pages that can be forked'
})
.options('help', {
alias : 'h',
boolean : true,
describe : 'Show this help info and exit'
})
.options('config', {
alias : 'conf',
describe : 'Optional config file.'
})
.options('wikis', {
describe : 'List of wikis to open.'
})
.options('version', {
alias : 'v',
describe : 'Show version number and exit'
})
.argv
if (argv.wikis) {
argv.wikis = argv.wikis.split(",")
argv.wikis.map((w) => w.replace(/^\s+|\s+$/g, ''))
}
config = cc(argv,
argv.config,
'config.json',
path.join(__dirname, '..', 'config.json'),
path.join(getUserHome(), '.wiki', 'config.json'),
cc.env('wiki_'), {
port: 31371,
root: path.dirname(require.resolve('wiki-server')),
home: 'welcome-visitors',
security_type: './security',
data: path.join(getUserHome(), '.wiki'), // see also defaultargs
packageDir: path.resolve(path.join(__dirname, 'node_modules')),
cookieSecret: require('crypto').randomBytes(64).toString('hex')
}).store
// If h/help is set print the generated help message and exit.
if (argv.help) {
optimist.showHelp()
return
}
// If v/version is set print the version of the wiki components and exit.
if (argv.version) {
console.log('wiki: ' + require('./package').version)
console.log('wiki-server: ' + require('wiki-server/package').version)
console.log('wiki-client: ' + require('wiki-client/package').version)
glob('wiki-security-*', {cwd: config.packageDir}, (e, plugins) => {
plugins.map((plugin) => {
console.log(plugin + ": " + require(plugin + "/package").version)
})
})
glob('wiki-plugin-*', {cwd: config.packageDir}, (e, plugins) => {
plugins.map((plugin) => {
console.log(plugin + ': ' + require(plugin + '/package').version)
})
return
})
}
// end: taken from wiki/cli.coffee
const cleanup = (e) => {
win.setBrowserView(null)
BrowserView.getAllViews().forEach((v) => {
v.removeAllListeners()
v.destroy()
})
win.removeAllListeners()
for (id of Object.keys(wikis)) {
wikis[id].destroy()
delete wikis[id]
}
//events.forEach((e) => win.webContents.on(e, (...args) => console.log('win', e, args)))
}
const template = [
{
label: 'Electrified',
submenu: [
{
label: 'Open Wiki',
accelerator: 'CmdOrCtrl+O',
click: () => {
win.webContents.executeJavaScript(`openSite()`)
}
},
{
label: 'Close Wiki',
accelerator: 'CmdOrCtrl+W',
click: () => {
win.webContents.executeJavaScript(`wikiBar.remove(wikiBar.active)`)
}
}
].concat([1, 2, 3, 4, 5, 6, 7, 8, 9].map((i) => {
return {
label: `Show Wiki ${i}`,
accelerator: `CmdOrCtrl+${i}`,
click: () => {
console.log(`Activating wiki: ${i}`)
win.webContents.executeJavaScript(`wikiBar.activateByIndex(${i-1})`)
}
}
}))
},
{
label: 'Edit',
submenu: [
{ role: 'undo' },
{ role: 'redo' },
{ type: 'separator' },
{ role: 'cut' },
{ role: 'copy' },
{ role: 'paste' },
{ role: 'pasteandmatchstyle' },
{ role: 'delete' },
{ role: 'selectall' }
]
},
{
label: 'View',
submenu: [
{
label: 'History Back',
accelerator: 'Alt+Left',
click: () => win.getBrowserView().webContents.goBack()
},
{
label: 'History Forward',
accelerator: 'Alt+Right',
click: () => win.getBrowserView().webContents.goForward()
},
{
label: 'Reload Wiki',
accelerator: 'CmdOrCtrl+R',
click: () => {
let webContents = win.getBrowserView().webContents
webContents.loadURL(webContents.getURL())
}
},
{
label: 'Reload Electrified',
accelerator: 'Shift+CmdOrCtrl+R',
click: () => {
cleanup()
win.reload()
//win.on('close', cleanup)
}
},
{
label: 'Toggle Electrified DevTools',
accelerator: 'Shift+CmdOrCtrl+I',
click: () => {
win.webContents.isDevToolsOpened() ?
win.webContents.closeDevTools() :
win.webContents.openDevTools({mode: 'undocked'})
}
},
{
label: 'Toggle Wiki DevTools',
accelerator: 'Alt+CmdOrCtrl+I',
click: () => {
win.getBrowserView().webContents.isDevToolsOpened() ?
win.getBrowserView().webContents.closeDevTools() :
win.getBrowserView().webContents.openDevTools({mode: 'right'})
}
},
{
label: 'Toggle Wiki Visibility',
accelerator: 'CmdOrCtrl+H',
click: () => win.webContents.executeJavaScript(
"wikiBar.toggleWikiVisibility()"
)
},
{ type: 'separator' },
{
// NOTE: While the recommendation is to use a role for these zoom commands,
// we need to customize the click handler so we are stuck reimplmenting
// some of this which others get for free.
label: 'Actual Size',
accelerator: 'CmdOrCtrl+0',
click: () => resetZoom()
},
{
label: 'Zoom In',
accelerator: 'CmdOrCtrl+Plus',
click: () => zoomIn()
},
{
label: 'Zoom Out',
accelerator: 'CmdOrCtrl+-',
click: () => zoomOut()
},
{ type: 'separator' },
{ role: 'togglefullscreen' }
]
},
{
role: 'window',
submenu: [
{ role: 'minimize' },
{
label: 'Close',
accelerator: 'CmdOrCtrl+Q',
role: 'close'
}
]
}
]
const menu = Menu.buildFromTemplate(template)
Menu.setApplicationMenu(menu)
const followLink = (url) => {
if (url.indexOf('http://') == 0 || url.indexOf('https://') == 0) {
shell.openExternal(url)
}
}
class Wiki {
constructor(url) {
this.view = null
this.url = new URL(url)
this.favicon = new URL('favicon.png', this.url.origin).toString()
this.queuedListeners = []
this.id = this._itemId()
this.listeners = {}
this.localEvents = ['activate', 'icon-changed']
this.localEvents.forEach((e) => { this.listeners[e] = [] })
}
// begin: from random.coffee
_randomByte() {
return (((1+Math.random())*0x100)|0).toString(16).substring(1)
}
_randomBytes(n) {
let results = [];
for (let i=1; i <= n; i++) {
results.push(this._randomByte());
}
return results.join('');
}
_itemId() {
return this._randomBytes(8)
}
// end: from random.coffee
_createView() {
// This must not be called until ready to display.
// Site will fail to initialize otherwise as scrollLeft always returns 0.
this.view = new BrowserView({
webPreferences: {
nodeIntegration: false,
preload: `${__dirname}/preload.js`,
nativeWindowOpen: false,
zoomFactor: this.zoomFactor
}
})
win.setBrowserView(this.view)
this.view.webContents.on('page-favicon-updated', (e, urls) => {
this.favicon = urls[0]
win.webContents.send('wiki-icon-changed', this.id, this.favicon)
})
this.view.webContents.on('did-navigate', (e, url) => {
this.url = new URL(url)
win.setTitle(this.url.origin)
persistLoadedWikis()
})
this.view.webContents.on('did-navigate-in-page', (e, url) => {
this.url = new URL(url)
win.setTitle(this.url.origin)
persistLoadedWikis()
})
this.view.webContents.on('new-window', (
e, url, frameName, disposition, options, additionalFeatures, referrer
) => {
if(url.indexOf('loginDialog') != -1) {
console.log('allowing login popup.')
return
}
e.preventDefault()
if(disposition == 'foreground-tab') {
followLink(url)
return
}
let origin = new URL(url).origin
if (origin == this.url.origin) {
this.view.webContents.loadURL(url)
}
})
for (let listener of this.queuedListeners) {
this.on.apply(this, listener)
}
this.queuedListeners = []
this.view.setAutoResize({ width: true, height: true })
this.view.webContents.loadURL(this.url.toString())
return this.view
}
updateBounds() {
if (this.view) {
let [width, height] = win.getContentSize()
// setBounds doesn't like floating point params
this.view.setBounds({
x: Math.floor(xoffset*zoomFactor), y: yoffset,
width: Math.floor(width-(xoffset*zoomFactor)), height: height
})
this.view.webContents.setZoomFactor(zoomFactor)
}
}
activate() {
this._display()
//this.listeners['activate'].forEach((l) => { l() })
win.webContents.send('wiki-activated', this.id)
}
_display() {
if (!this.view) { this._createView() }
win.webContents.focus()
win.setBrowserView(this.view)
this.updateBounds()
this.view.webContents.focus()
//this.view.webContents.openDevTools()
}
toggleVisibility() {
if (!this.view) { this._display(); return }
let view = win.getBrowserView() ? null : this.view
win.setBrowserView(view)
}
hide() {
win.setBrowserView(null)
}
destroy() {
this.queuedListeners = []
if (!this.view) return
win.setBrowserView(null)
this.view.destroy()
}
on(...args) {
if(this.view) {
let eventName = args[0]
if (this.localEvents.includes(eventName)) {
let listener = args[1]
//this.listeners[eventName].push(listener)
return
}
this.view.webContents.on.apply(this, args)
}
else this.queuedListeners.push(args)
}
off(...args) {
this.view.webContents.off.apply(args)
}
}
events = [
'did-finish-frame-load',
'did-fail-load',
'did-frame-finish-load',
'did-start-loading',
'did-stop-loading',
'dom-ready',
'page-favicon-updated',
'new-window',
'will-navigate',
'did-start-navigation',
'will-redirect',
'did-redirect-navigation',
'did-navigate',
'did-frame-navigate',
'did-navigate-in-page',
'will-prevent-upload',
'crashed',
'unresponsive',
'responsive',
'plugin-crashed',
'destroyed',
//'before-input-event',
'devtools-opened',
'devtools-closed',
'devtools-focused',
'certificate-error',
'select-client-certificate',
'login',
'found-in-page',
'media-started-playing',
'media-paused',
'did-change-theme-color',
'update-target-url',
//'cursor-changed',
'context-menu',
'select-bluetooth-device',
'paint',
'devtools-reload-page',
'will-attach-webview',
'did-attach-webview',
//'console-message',
'remote-require',
'remote-get-global',
'remote-get-builtin',
'remote-get-current-window',
'remote-get-current-web-contents',
'remote-get-guest-web-contents'
]
winEvents = [
'page-title-updated',
'close',
'closed',
'unresponsive',
'responsive',
'blur',
'focus',
'show',
'hide',
'read-to-show',
'maximize',
'unmaximize',
'minimize',
'restore',
'resize',
'move',
'enter-full-screen'
]
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let win
let wikis = {}
let zoomFactor = 1.0
let xoffset = 0
let yoffset = 0
// TODO: Is this call needed?
ipcMain.on('toggle-wiki-visibility', (evt, id) => {
wikis[id].toggleVisibility()
})
ipcMain.on('set-display-offsets', (evt, _xoffset, _yoffset) => {
xoffset = _xoffset
yoffset = _yoffset
Object.keys(wikis).forEach((id) => wikis[id].updateBounds())
})
ipcMain.on('activate-wiki', (evt, id) => {
console.log('activating wiki:', id)
wikis[id].activate()
})
ipcMain.on('hide-wiki', (evt, id) => {
wikis[id].hide()
})
ipcMain.on('add-wiki', (evt, site) => {
addWiki(site)
})
ipcMain.on('add-and-activate-wiki', (evt, site) => {
let id = addWiki(site)
wikis[id].activate()
})
ipcMain.on('remove-wiki', (evt, id) => {
wikis[id].destroy()
persistLoadedWikis()
delete wikis[id]
})
const _zoom = (opts) => {
if (opts.target) {
zoomFactor = opts.target
}
if (opts.delta) {
zoomFactor = zoomFactor + opts.delta
}
win.webContents.setZoomFactor(zoomFactor)
Object.keys(wikis).forEach((id) => wikis[id].updateBounds())
}
const zoomIn = () => {
_zoom({delta: +0.1})
}
const zoomOut = () => {
_zoom({delta: -0.1})
}
const resetZoom = () => {
_zoom({target: 1.0})
}
const addWiki = (site) => {
console.log('adding wiki:', site)
let wiki = new Wiki(site)
wikis[wiki.id] = wiki
persistLoadedWikis()
//events.forEach((e) => wiki.on(e, (...args) => console.log('view', e, args)))
win.webContents.send('add-wiki', wiki.id, wiki.favicon)
return wiki.id
}
function createWindow () {
// Create the browser window.
win = new BrowserWindow({
webPreferences: {
nodeIntegration: true
},
autoHideMenuBar: true,
width: 800,
height: 600,
useContentSize: true
})
win.webContents.getZoomFactor((zf) => {
zoomFactor = zf
//winEvents.forEach((e) => win.on(e, (...args) => console.log('win event', e, args)))
win.loadURL(`file://${__dirname}/electrified.html`)
})
persistLoadedWikis = () => {
fs.writeFileSync(path.join(config.data, 'loaded-wikis.json'),
JSON.stringify(Object.values(wikis).map((w) => w.url)))
}
readLoadedWikis = () => {
try {
return fs.readFileSync(path.join(config.data, 'loaded-wikis.json'))
}
catch(e) {
console.log('Unable to read previously loaded wikis:', e.message)
}
}
win.webContents.on('did-finish-load', () => {
let wikiUrls = ["http://localhost:31371"]
console.log('Getting previous wiki urls.')
let previousWikis = readLoadedWikis()
if (previousWikis) {
wikiUrls = JSON.parse(previousWikis)
console.log('Previous wiki urls:', wikiUrls)
}
if (config.wikis) {
wikiUrls = config.wikis
console.log('Command line wiki urls:', wikiUrls)
}
console.log('Using wiki urls:', wikiUrls)
wikiUrls.forEach((u) => addWiki(u))
win.on('focus', () => {
win.webContents.executeJavaScript(`wikiBar.activate(wikiBar.active)`)
})
//let wikiUrls = config.wikis
//wikiUrls.forEach((u) => addWiki(u))
})
// Emitted when the window is closed.
win.on('closed', () => {
// 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.
win = null
})
}
let wikiApp, wikiServer
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', () => {
if(config.farm) {
console.log('Wiki starting in Farm mode, navigate to a specific server to start it.\n')
if(!argv.wikiDomains && !argv.allowed) {
console.log('WARNING : Starting Wiki Farm in promiscous mode\n')
}
if(argv.security_type == './security') {
console.log('INFORMATION : Using default security - Wiki Farm will be read-only\n')
}
wikiServer = farm(config)
}
else {
wikiApp = server(config)
wikiApp.on('owner-set', (e) => {
wikiServer = wikiApp.listen(wikiApp.startOpts.port, wikiApp.startOpts.host)
console.log("Federated Wiki server listening on", wikiApp.startOpts.port,
"in mode:", wikiApp.settings.env)
if(argv.security_type == './security') {
console.log('INFORMATION : Using default security - Wiki will be read-only\n')
}
wikiApp.emit('running-serv', wikiServer)
})
}
createWindow()
})
// Quit when all windows are closed.
app.on('window-all-closed', () => {
wikiServer.close()
app.quit()
})
app.on('activate', () => {
})
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.