116 lines
2.4 KiB
Go
Raw Normal View History

2019-02-25 08:29:35 +01:00
package main
import (
"bytes"
"errors"
"strings"
"github.com/ethereum/go-ethereum/crypto"
2019-02-25 08:29:35 +01:00
"github.com/jroimartin/gocui"
2019-08-05 18:25:44 +02:00
status "github.com/status-im/status-protocol-go"
statusproto "github.com/status-im/status-protocol-go/types"
2019-02-25 08:29:35 +01:00
)
const DefaultMultiplexerPrefix = "default"
type CmdHandler func([]byte) error
type InputMultiplexer struct {
handlers map[string]CmdHandler // map string prefix to handler
}
func NewInputMultiplexer() *InputMultiplexer {
return &InputMultiplexer{
handlers: make(map[string]CmdHandler),
}
}
func (m *InputMultiplexer) BindingHandler(g *gocui.Gui, v *gocui.View) error {
if v == nil {
return nil
}
var buf bytes.Buffer
if err := EnterHandler(&buf)(g, v); err != nil {
return err
}
inputStr := buf.String()
inputBytes := bytes.TrimSpace(buf.Bytes())
for prefix, h := range m.handlers {
if strings.HasPrefix(inputStr, prefix) {
return h(inputBytes)
}
}
if h, ok := m.handlers[DefaultMultiplexerPrefix]; ok {
return h(inputBytes)
}
return nil
}
func (m *InputMultiplexer) AddHandler(prefix string, h CmdHandler) {
m.handlers[prefix] = h
}
func bytesToArgs(b []byte) []string {
args := bytes.Split(b, []byte(" "))
argsStr := make([]string, len(args))
for i, arg := range args {
argsStr[i] = string(arg)
}
return argsStr
}
func chatAddCmdHandler(args []string) (chat status.Chat, err error) {
if len(args) == 1 {
2019-05-15 14:00:04 +03:00
name := args[0]
chat = status.CreatePublicChat(name)
} else if len(args) == 2 {
publicKeyBytes, err := statusproto.DecodeHex(args[0])
if err != nil {
return chat, err
}
publicKey, err := crypto.UnmarshalPubkey(publicKeyBytes)
if err != nil {
return chat, err
}
chat = status.CreateOneToOneChat(args[1], publicKey)
} else {
err = errors.New("/chat: incorrect arguments to add subcommand")
2019-02-25 08:29:35 +01:00
}
return
}
func ChatCmdFactory(chatsvc *ChatsViewController, chatvc *MessagesViewController) CmdHandler {
2019-02-25 08:29:35 +01:00
return func(b []byte) error {
args := bytesToArgs(b)[1:] // remove first item, i.e. "/chat"
switch args[0] {
case "add":
chat, err := chatAddCmdHandler(args[1:])
if err != nil {
return err
}
if err := chatsvc.Add(chat); err != nil {
return err
}
// TODO: fix removing chats
// case "remove":
2019-05-15 14:00:04 +03:00
// if len(args) == 2 {
// if err := c.Remove(args[1]); err != nil {
// return err
// }
// c.Refresh()
// return nil
// }
// return errors.New("/chat: incorect arguments to remove subcommand")
2019-02-25 08:29:35 +01:00
}
return nil
}
2019-08-05 18:25:44 +02:00
}