-
-
Notifications
You must be signed in to change notification settings - Fork 43
/
cli.js
executable file
·587 lines (538 loc) · 17.5 KB
/
cli.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
#!/usr/bin/env node
var Client = require('cabal-client')
var minimist = require('minimist')
var fs = require('fs')
var path = require('path')
var yaml = require('js-yaml')
var mkdirp = require('mkdirp')
var frontend = require('./neat-screen.js')
var chalk = require('chalk')
var captureQrCode = require('node-camera-qr-reader')
var fe = null
const onExit = require('signal-exit')
const { version: packageJSONVersion } = require('./package.json')
var args = minimist(process.argv.slice(2))
const version = getClientVersion()
// set terminal window title
process.stdout.write('\x1B]0;cabal\x07')
var rootdir = null
if (args.config && fs.statSync(args.config).isDirectory()) {
rootdir = path.join(args.config, `v${Client.getDatabaseVersion()}`)
} else if (args.config) {
rootdir = path.join(
path.dirname(path.resolve(args.config)),
`v${Client.getDatabaseVersion()}`
)
} else {
rootdir = Client.getCabalDirectory()
}
var rootconfig = `${rootdir}/config.yml`
var archivesdir = `${rootdir}/archives/`
const defaultMessageTimeformat = '%T'
const defaultMessageIndent = 'nick'
var usage = `Usage
Create a new cabal:
cabal --new
Create a new cabal and name it locally:
cabal --new --alias <name>
Join a cabal by its key:
cabal cabal://key
Join a cabal by an alias:
cabal <your saved --alias of a cabal>
Save a cabal, adding it to the list of cabals to autojoin:
cabal --save cabal://key
Join all of your saved cabals by running just \`cabal\`:
cabal
Join a cabal by a QR code:
cabal --qr
Options:
--seed Start a headless seed for the specified cabal key
--port Listen for cabal traffic on the passed in port (default: 13331)
--new Start a new cabal
--nick Your nickname
--alias Save an alias for the specified cabal. Used with --key.
--alias <name> --key <cabal>
--aliases Print out your saved cabal aliases
--cabals Print out your saved cabals
--forget Forgets the specified cabal. Works on aliases and keys persisted with --save
--clear Clears out all aliases
--save Save the specified cabal to the config
--save <cabal>
--key Specify a cabal key. Used with --alias.
--alias <name> --key <cabal>
--config Specify a full path to a cabal config
--qr Capture a frame from a connected camera to read a cabal key from a QR code
--temp Start the cli with a temporary in-memory database. Useful for debugging
--version Print out which version of cabal you're running
--help Print this help message
--message Publish a single message; then quit after \`timeout\`
--channel Channel name to publish to for \`message\` option; default: "default"
--timeout Delay in milliseconds to wait on swarm before quitting for \`message\` option; default: 5000
--type Message type set to message for \`message\` option; default: "chat/text"
Work in progress! Learn more at https://github.com/cabal-club
`
if (args.version || args.v) {
console.log(version)
process.exit(0)
}
if (args.help || args.h) {
process.stderr.write(usage)
process.exit(1)
}
var config
var cabalKeys = []
var configFilePath = findConfigPath()
mkdirp.sync(path.dirname(configFilePath))
var maxFeeds = 1000
// make sure the .cabal/v<databaseVersion> folder exists
mkdirp.sync(rootdir)
// create a default config in rootdir if it doesn't exist
if (!fs.existsSync(rootconfig)) {
saveConfig(rootconfig, {
cabals: [],
aliases: {},
preferredPort: 0,
cache: {},
frontend: {
messageTimeformat: defaultMessageTimeformat,
messageIndent: defaultMessageIndent
}
})
}
// Attempt to load local or homedir config file
try {
if (configFilePath) {
if (fs.existsSync(configFilePath)) {
config = yaml.safeLoad(fs.readFileSync(configFilePath, 'utf8'))
} else {
config = {}
}
if (!config.cabals) { config.cabals = [] }
if (!config.aliases) { config.aliases = {} }
if (!config.preferredPort) { config.preferredPort = 0 }
if (!config.cache) { config.cache = {} }
if (!config.frontend) { config.frontend = {} }
if (!config.frontend.messageTimeformat) {
config.frontend.messageTimeformat = defaultMessageTimeformat
}
if (!config.frontend.messageIndent) {
config.frontend.messageIndent = defaultMessageIndent
}
cabalKeys = config.cabals
}
} catch (e) {
logError(e)
process.exit(1)
}
const client = new Client({
maxFeeds: maxFeeds,
config: {
dbdir: archivesdir,
temp: args.temp,
preferredPort: args.port || config.preferredPort
},
commands: {
// todo: custom commands
more: {
help: () => 'adds more messages to the backlog of current channel',
category: ['misc'],
call: (cabal, res, arg) => {
fe.moreBacklog()
}
},
panes: {
help: () => 'set pane to navigate up and down in. panes: channels, cabals',
category: ['misc'],
call: (cabal, res, arg) => {
if (arg === '' || !['channels', 'cabals'].includes(arg)) return
fe.setPane(arg)
}
},
quit: {
help: () => 'exit the cabal process',
category: ['basics'],
call: (cabal, res, arg) => {
process.exit(0)
}
},
exit: {
help: () => 'exit the cabal process',
category: ['basics'],
call: (cabal, res, arg) => {
process.exit(0)
}
},
help: {
help: () => 'display this help message',
category: ['basics'],
call: (cabal, res, arg) => {
const hotkeysExplanation = `
ctrl-l
redraw the screen
ctrl-u
clear input line
ctrl-w
delete last word in input
up-arrow
cycle through command history
down-arrow
cycle through command history
ctrl-a, home
go to start of input line
ctrl-e, end
go to end of input line
ctrl-n
go to next channel
ctrl-p
go to previous channel
ctrl-r
go to next unread channel
pageup
scroll up through backlog
pagedown
scroll down through backlog
shift-pageup
scroll up through nicklist
shift-pagedown
scroll down through nicklist
alt-[1,9]
select channels 1-9
alt-n
tab between the cabals & channels panes
ctrl-{n,p}
move up/down channels/cabals
alt-l
toggle id suffixes on/off
`
const categories = new Set(['hotkeys'])
function printCategories () {
for (const cat of Array.from(categories).sort((a, b) => a.localeCompare(b))) {
fe.writeLine(`/help ${chalk.cyan(cat)}`)
}
}
var foundAliases = {}
const commands = {}
for (const key in cabal.client.commands) {
if (!cabal.client.commands[key].category) { continue }
cabal.client.commands[key].category.forEach(cat => {
if (!commands[cat]) commands[cat] = []
commands[cat].push(key)
categories.add(cat)
})
}
if (!arg) {
fe.writeLine('the help command is split into sections:')
printCategories()
} else if (arg && !categories.has(arg)) {
fe.writeLine(`${arg} is not a help section, try:`)
printCategories()
} else {
fe.writeLine(`help: ${chalk.cyan(arg)}`)
if (arg === 'hotkeys') {
fe.writeLine(hotkeysExplanation)
return
}
// print all commands from the category defined by `arg`
commands[arg].forEach(key => {
if (foundAliases[key]) { return }
const slash = chalk.gray('/')
let command = key
if (cabal.client.aliases[key]) {
foundAliases[cabal.client.aliases[key]] = true
command += `, ${slash}${cabal.client.aliases[key]}`
}
fe.writeLine(`${slash}${command}`)
fe.writeLine(` ${cabal.client.commands[key].help()}`)
})
}
}
}
},
persistentCache: {
read: async function (name, err) {
if (name in config.cache) {
var cache = config.cache[name]
if (cache.expiresAt < Date.now()) { // if ttl has expired: warn, but keep using
console.error(`${chalk.redBright('Note:')} the TTL for ${name} has expired`)
}
return cache.key
}
// dns record wasn't found online and wasn't in the cache
return null
},
write: async function (name, key, ttl) {
var expireOffset = +(new Date(ttl * 1000)) // convert to epoch time
var expiredTime = Date.now() + expireOffset
if (!config.cache) config.cache = {}
config.cache[name] = { key: key, expiresAt: expiredTime }
saveConfig(configFilePath, config)
}
}
})
// Close all cabals on exit.
onExit(function () {
for (const cabal of client.cabals.values()) {
cabal._destroy(() => {
})
}
})
if (args.clear) {
delete config.aliases
saveConfig(configFilePath, config)
process.stdout.write('Aliases cleared\n')
process.exit(0)
}
if (args.forget) {
let success = false
/* eslint no-inner-declarations: "off" */
function forgetCabal (k) {
const index = config.cabals.indexOf(k)
if (index >= 0) {
config.cabals.splice(index, 1)
success = true
}
}
if (config.aliases[args.forget]) {
const aliasedKey = config.aliases[args.forget]
success = true
delete config.aliases[args.forget]
// forget any potential reuses of the aliased key in config.cabals array
forgetCabal(aliasedKey)
}
// check if key is among saved cabals
if (!success) forgetCabal(args.forget)
if (success) {
saveConfig(configFilePath, config)
console.log(`${args.forget} has been forgotten`)
} else { console.log('no such cabal') }
process.exit(0)
}
if (args.aliases) {
var aliases = Object.keys(config.aliases)
if (aliases.length === 0) {
process.stdout.write("You don't have any saved aliases.\n\n")
process.stdout.write('Save an alias by running\n')
process.stdout.write(`${chalk.magentaBright('cabal: ')} ${chalk.greenBright('--key cabal://c001..c4b41')} `)
process.stdout.write(`${chalk.blueBright('--alias your-alias-name')}\n`)
} else {
aliases.forEach(function (alias) {
process.stdout.write(`${chalk.blueBright(alias)}\t\t ${chalk.greenBright(config.aliases[alias])}\n`)
})
}
process.exit(0)
}
if (args.cabals) {
var savedCabals = config.cabals
if (savedCabals.length === 0) {
process.stdout.write("You don't have any saved cabals.\n\n")
process.stdout.write('Save a cabal by running\n')
process.stdout.write(`${chalk.magentaBright('cabal: ')} ${chalk.greenBright('--save cabal://c001..c4b41')} `)
} else {
savedCabals.forEach(function (saved) {
process.stdout.write(`${chalk.greenBright(saved)}\n`)
})
}
process.exit(0)
}
if (args.alias && !args.new && !args.key) {
logError('the --alias option needs to be used together with --key')
process.exit(1)
}
// user wants to alias a cabal:// key with a name
if (args.alias && args.key) {
saveKeyAsAlias(args.key, args.alias)
process.exit(0)
}
if (args.port) {
const port = parseInt(args.port)
if (isNaN(port) || port < 0 || port > 65535) {
logError(`${args.port} is not a valid port number`)
process.exit(1)
}
args.port = port
}
if (args.key) {
// If a key is provided, place it at the top of the keys provided from the config
cabalKeys.unshift(args.key)
} else if (args.temp && args.temp.length > 0) {
// don't eat the key if it was passed in as `cabal --temp <key>`
cabalKeys = [args.temp]
} else if (args._.length > 0) {
// the cli was run as `cabal <alias|key> ... <alias|key>`
// replace keys from config with the keys from the args
cabalKeys = args._.map(getKey)
}
// join and save the passed in cabal keys
if (args.save) {
cabalKeys = args._.map(getKey)
if (args.save.length > 0) cabalKeys = cabalKeys.concat(getKey(args.save))
if (!cabalKeys.length) {
console.log(`${chalk.magentaBright('cabal:')} error, need cabal keys to save. example:`)
console.log(`${chalk.greenBright('cabal --save cabal://key')}`)
process.exit(1)
}
config.cabals = config.cabals.concat(cabalKeys)
saveConfig(configFilePath, config)
// output message about keys having been saved
if (cabalKeys.length === 1) {
console.log(`${chalk.magentaBright('cabal:')} saved ${chalk.greenBright(cabalKeys[0])}`)
} else {
console.log(`${chalk.magentaBright('cabal:')} saved the following keys:`)
cabalKeys.forEach((key) => { console.log(`${chalk.greenBright(key)}`) })
}
process.exit(0)
}
// try to initiate the frontend using either qr codes via webcam, using cabal keys passed via cli,
// or starting an entirely new cabal per --new
if (args.qr) {
console.log('Cabal is looking for a QR code...')
console.log('Press ctrl-c to stop.')
captureQrCode({ retry: true }).then((key) => {
if (key) {
console.log('\u0007') // system bell
start([key], config.frontend)
} else {
console.log('No QR code detected.')
process.exit(0)
}
}).catch((e) => {
console.error('Webcam capture failed. Have you installed the appropriate drivers? See the documentation for more information.')
console.error('Mac OSX: brew install imagesnap')
console.error('Linux: sudo apt-get install fswebcam')
})
} else if (cabalKeys.length || args.new) {
start(cabalKeys, config.frontend)
} else {
// no keys, no qr, and not trying to start a new cabal => print help info
process.stderr.write(usage)
process.exit(1)
}
function start (keys, frontendConfig) {
if (args.key && args.message) {
publishSingleMessage({
key: args.key,
channel: args.channel,
message: args.message,
messageType: args.type,
timeout: args.timeout
})
return
}
keys = Array.from(new Set(keys)) // remove duplicates
var pendingCabals = args.new ? [client.createCabal()] : keys.map(client.addCabal.bind(client))
Promise.all(pendingCabals).then(() => {
if (args.new) {
console.error(`created the cabal: ${chalk.greenBright('cabal://' + client.getCurrentCabal().key)}`) // log to terminal output (stdout is occupied by interface)
// allow saving newly created cabal as alias
if (args.alias) { saveKeyAsAlias(client.getCurrentCabal().key, args.alias) }
keys = [client.getCurrentCabal().key]
}
// edgecase: if the config is empty we remember the first joined cabals in it
if (!config.cabals.length) {
config.cabals = keys
saveConfig(configFilePath, config)
}
if (args.nick && args.nick.length > 0) client.getCurrentCabal().publishNick(args.nick)
if (!args.seed) {
fe = frontend({ client, frontendConfig })
} else {
const seedKeys = []
for (const details of client.cabals.keys()) {
seedKeys.push(details.key)
}
seedKeys.forEach((k) => {
console.log('Seeding', k)
console.log()
console.log('@: new peer')
console.log('x: peer left')
console.log('^: uploaded a chunk')
console.log('.: downloaded a chunk')
console.log()
trackAndPrintEvents(client._getCabalByKey(k))
})
}
}).catch((e) => {
if (!e || e.toString() === 'Error: dns failed to resolve') {
console.error("Error: Couldn't resolve one of the following cabal keys:", chalk.yellow(keys.join(' ')))
} else {
console.error(e)
}
process.exit(1)
})
}
function trackAndPrintEvents (cabal) {
cabal.ready(() => {
// Listen for feeds
cabal.kcore._logs.feeds().forEach(listen)
cabal.kcore._logs.on('feed', listen)
function listen (feed) {
feed.on('download', idx => {
process.stdout.write('.')
})
feed.on('upload', idx => {
process.stdout.write('^')
})
}
cabal.on('peer-added', () => {
process.stdout.write('@')
})
cabal.on('peer-dropped', () => {
process.stdout.write('x')
})
})
}
function getKey (str) {
// return key if what was passed in was a saved alias
if (str in config.aliases) { return config.aliases[str] }
// else assume it's a cabal key
return str
}
function logError (msg) {
console.error(`${chalk.red('cabal:')} ${msg}`)
}
function findConfigPath () {
var currentDirConfigFilename = '.cabal.yml'
if (args.config && fs.statSync(args.config).isDirectory()) {
return path.join(args.config, `v${Client.getDatabaseVersion()}`, 'config.yml')
} else if (args.config && fs.existsSync(args.config)) {
return args.config
} else if (fs.existsSync(currentDirConfigFilename)) {
return currentDirConfigFilename
}
return rootconfig
}
function saveConfig (path, config) {
// make sure config is well-formatted (contains all config options)
if (!config.cabals) { config.cabals = [] }
config.cabals = Array.from(new Set(config.cabals)) // dedupe array entries
if (!config.aliases) { config.aliases = {} }
const data = yaml.safeDump(config, {
sortKeys: true
})
fs.writeFileSync(path, data, 'utf8')
}
function saveKeyAsAlias (key, alias) {
config.aliases[alias] = key
saveConfig(configFilePath, config)
console.log(`${chalk.magentaBright('cabal:')} saved ${chalk.greenBright(key)} as ${chalk.blueBright(alias)}`)
}
function publishSingleMessage ({ key, channel, message, messageType, timeout }) {
console.log(`Publishing message to channel - ${channel || 'default'}: ${message}`)
client.addCabal(key).then(cabal => cabal.publishMessage({
type: messageType || 'chat/text',
content: {
channel: channel || 'default',
text: message
}
})
)
setTimeout(function () { process.exit(0) }, timeout || 5000)
}
function getClientVersion () {
if (packageJSONVersion) {
return packageJSONVersion
}
console
.error('failed to read cabal\'s package.json -- something is wrong with your installation')
process.exit(1)
}