Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Client updates [archiving support] #208

Merged
merged 7 commits into from
Mar 6, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 20 additions & 23 deletions cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -159,29 +159,29 @@ const client = new Client({
// todo: custom commands
panes: {
help: () => 'set pane to navigate up and down in. panes: channels, cabals',
category: ["misc"],
category: ['misc'],
call: (cabal, res, arg) => {
if (arg === '' || !['channels', 'cabals'].includes(arg)) return
fe.setPane(arg)
}
},
quit: {
help: () => 'exit the cabal process',
category: ["basics"],
category: ['basics'],
call: (cabal, res, arg) => {
process.exit(0)
}
},
exit: {
help: () => 'exit the cabal process',
category: ["basics"],
category: ['basics'],
call: (cabal, res, arg) => {
process.exit(0)
}
},
help: {
help: () => 'display this help message',
category: ["basics"],
category: ['basics'],
call: (cabal, res, arg) => {
const hotkeysExplanation = `
ctrl-l
Expand Down Expand Up @@ -221,12 +221,12 @@ ctrl-{n,p}
alt-l
toggle id suffixes on/off
`
let categories = new Set(["hotkeys"])
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 = {}
Expand All @@ -239,16 +239,14 @@ alt-l
})
}
if (!arg) {
fe.writeLine("the help command is split into sections:")
fe.writeLine('the help command is split into sections:')
printCategories()
return
} else if (arg && !categories.has(arg)) {
fe.writeLine(`${arg} is not a help section, try:`)
printCategories()
return
} else {
fe.writeLine(`help: ${chalk.cyan(arg)}`)
if (arg === "hotkeys") {
if (arg === 'hotkeys') {
fe.writeLine(hotkeysExplanation)
return
}
Expand Down Expand Up @@ -308,7 +306,7 @@ if (args.clear) {
if (args.forget) {
let success = false
/* eslint no-inner-declarations: "off" */
function forgetCabal(k) {
function forgetCabal (k) {
const index = config.cabals.indexOf(k)
if (index >= 0) {
config.cabals.splice(index, 1)
Expand Down Expand Up @@ -372,15 +370,14 @@ if (args.alias && args.key) {
}

if (args.port) {
let port = parseInt(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)
Expand Down Expand Up @@ -441,7 +438,7 @@ if (args.qr) {
process.exit(1)
}

function start(keys, frontendConfig) {
function start (keys, frontendConfig) {
if (args.key && args.message) {
publishSingleMessage({
key: args.key,
Expand Down Expand Up @@ -491,13 +488,13 @@ function start(keys, frontendConfig) {
})
}

function trackAndPrintEvents(cabal) {
function trackAndPrintEvents (cabal) {
cabal.ready(() => {
// Listen for feeds
cabal.kcore._logs.feeds().forEach(listen)
cabal.kcore._logs.on('feed', listen)

function listen(feed) {
function listen (feed) {
feed.on('download', idx => {
process.stdout.write('.')
})
Expand All @@ -516,18 +513,18 @@ function trackAndPrintEvents(cabal) {
})
}

function getKey(str) {
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) {
function logError (msg) {
console.error(`${chalk.red('cabal:')} ${msg}`)
}

function findConfigPath() {
function findConfigPath () {
var currentDirConfigFilename = '.cabal.yml'
if (args.config && fs.statSync(args.config).isDirectory()) {
return path.join(args.config, `v${Client.getDatabaseVersion()}`, 'config.yml')
Expand All @@ -539,7 +536,7 @@ function findConfigPath() {
return rootconfig
}

function saveConfig(path, config) {
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
Expand All @@ -550,13 +547,13 @@ function saveConfig(path, config) {
fs.writeFileSync(path, data, 'utf8')
}

function saveKeyAsAlias(key, alias) {
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 }) {
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',
Expand All @@ -569,7 +566,7 @@ function publishSingleMessage({ key, channel, message, messageType, timeout }) {
setTimeout(function () { process.exit(0) }, timeout || 5000)
}

function getClientVersion() {
function getClientVersion () {
if (packageJSONVersion) {
return packageJSONVersion
}
Expand Down
28 changes: 16 additions & 12 deletions commands.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
var util = require('./util')
var chalk = require('chalk')
var views = require('./views')

function Commander (view, client) {
if (!(this instanceof Commander)) return new Commander(view, client)
Expand All @@ -10,7 +11,7 @@ function Commander (view, client) {
this.view = view
this.pattern = (/^\/(\w*)\s*(.*)/)
this.history = []
this.historyIndex = -1 // negative: new msg. >=0: index from the last item
this.historyIndex = -1 // negative: new msg, >=0: index from the last item
}

Commander.prototype.setActiveCabal = function (cabal) {
Expand All @@ -19,17 +20,20 @@ Commander.prototype.setActiveCabal = function (cabal) {
this.cabal.on('info', (msg) => {
var txt = typeof msg === 'string' ? msg : (msg && msg.text ? msg.text : '')
txt = util.sanitizeString(txt)
if (msg.command) {
switch (msg.command) {
case "channels":
var {joined, channel, userCount, topic} = msg
var userPart = `${userCount} ${userCount === 1 ? 'person' : 'people'}`
userPart = userCount > 0 ? ": " + chalk.cyan(userPart) : ''
var shortTopic = topic.length > 40 ? topic.slice(0, 40) + '..' : topic || ''
shortTopic = util.sanitizeString(shortTopic)
channel = util.sanitizeString(channel)
txt = `${joined ? '*' : ' '} ${channel}${userPart} ${shortTopic}`
break
const meta = msg.meta
if (meta.command) {
switch (meta.command) {
case 'channels':
if (meta.seq === 0) break // don't rewrite the payload of the first `/channels` message
var { joined, channel, userCount, topic } = msg
var userPart = `${userCount} ${userCount === 1 ? 'person' : 'people'}`
userPart = userCount > 0 ? ': ' + chalk.cyan(userPart) : ''
var maxTopicLength = views.getChatWidth() - `00:00:00 -status- ${channel}: 999 people `.length - 2 /* misc unknown padding that just makes it work v0v */
var shortTopic = topic && topic.length > maxTopicLength ? topic.slice(0, maxTopicLength - 2) + '..' : topic || ''
shortTopic = util.sanitizeString(shortTopic)
channel = util.sanitizeString(channel)
txt = `${joined ? '*' : ' '} ${channel}${userPart} ${shortTopic}`
break
}
}
this.view.writeLine(txt)
Expand Down
17 changes: 15 additions & 2 deletions neat-screen.js
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ function NeatScreen (props) {

// redraw the screen
this.neat.input.on('ctrl-l', () => {
this.neat.clear()
this.neat.clear()
})

// cycle to next unread channel
Expand Down Expand Up @@ -397,6 +397,19 @@ NeatScreen.prototype.registerUpdateHandler = function (cabal) {
}
// register an event handler for all updates from the cabal
cabal.on('update', this._updateHandler[cabal.key])
// create & register event handlers for channel archiving events
const processChannelArchiving = (type, { channel, reason, key, isLocal }) => {
const issuer = this.client.getUsers()[key]
if (!issuer || isLocal) { return }
reason = reason ? `(${chalk.cyan('reason:')} ${reason})` : ''
const issuerName = issuer && issuer.name ? issuer.name : key.slice(0, 8)
const action = type === 'archive' ? 'archived' : 'unarchived'
const text = `${issuerName} ${chalk.magenta(action)} channel ${chalk.cyan(channel)} ${reason}`
this.client.addStatusMessage({ text })
this.bus.emit('render')
}
cabal.on('channel-archive', (envelope) => { processChannelArchiving('archive', envelope) })
cabal.on('channel-unarchive', (envelope) => { processChannelArchiving('unarchive', envelope) })
}

NeatScreen.prototype._pagesize = function () {
Expand All @@ -415,7 +428,7 @@ NeatScreen.prototype.processMessages = function (opts, cb) {
this.state.messages = []
msgs.forEach((msg, i) => {
const user = this.client.getUsers()[msg.key]
if (user && user.isHidden()) return
if (user && user.isHidden(opts.channel)) return
this.state.messages.push(this.formatMessage(msg))
})
this.bus.emit('render')
Expand Down
Loading