X-Git-Url: https://git.r.bdr.sh/rbdr/mobius/blobdiff_plain/d005ef04cfaa26943e6dd33807d741577ffb232a..382c53d3b8ea8db13a0bac08cfdbd12bfae62ab4:/hotline/client.go diff --git a/hotline/client.go b/hotline/client.go index 6abe623..3353095 100644 --- a/hotline/client.go +++ b/hotline/client.go @@ -3,15 +3,15 @@ package hotline import ( "bufio" "bytes" + "context" "embed" "encoding/binary" "errors" "fmt" "github.com/gdamore/tcell/v2" "github.com/rivo/tview" - "github.com/stretchr/testify/mock" - "go.uber.org/zap" "gopkg.in/yaml.v3" + "log/slog" "math/big" "math/rand" "net" @@ -49,10 +49,8 @@ func (cp *ClientPrefs) IconBytes() []byte { return iconBytes } -func (cp *ClientPrefs) AddBookmark(name, addr, login, pass string) error { +func (cp *ClientPrefs) AddBookmark(name, addr, login, pass string) { cp.Bookmarks = append(cp.Bookmarks, Bookmark{Addr: addr, Login: login, Password: pass}) - - return nil } func readConfig(cfgPath string) (*ClientPrefs, error) { @@ -76,31 +74,37 @@ type Client struct { UserAccess []byte filePath []string UserList []User - Logger *zap.SugaredLogger + Logger *slog.Logger activeTasks map[uint32]*Transaction serverName string Pref *ClientPrefs - Handlers map[uint16]ClientTHandler + Handlers map[uint16]ClientHandler UI *UI Inbox chan *Transaction } -func NewClient(username string, logger *zap.SugaredLogger) *Client { +type ClientHandler func(context.Context, *Client, *Transaction) ([]Transaction, error) + +func (c *Client) HandleFunc(transactionID uint16, handler ClientHandler) { + c.Handlers[transactionID] = handler +} + +func NewClient(username string, logger *slog.Logger) *Client { c := &Client{ Logger: logger, activeTasks: make(map[uint32]*Transaction), - Handlers: make(map[uint16]ClientTHandler), + Handlers: make(map[uint16]ClientHandler), } c.Pref = &ClientPrefs{Username: username} return c } -func NewUIClient(cfgPath string, logger *zap.SugaredLogger) *Client { +func NewUIClient(cfgPath string, logger *slog.Logger) *Client { c := &Client{ cfgPath: cfgPath, Logger: logger, @@ -111,7 +115,8 @@ func NewUIClient(cfgPath string, logger *zap.SugaredLogger) *Client { prefs, err := readConfig(cfgPath) if err != nil { - logger.Fatal(fmt.Sprintf("unable to read config file %s\n", cfgPath)) + logger.Error(fmt.Sprintf("unable to read config file %s\n", cfgPath)) + os.Exit(1) } c.Pref = prefs @@ -154,70 +159,27 @@ type ClientTHandler interface { Handle(*Client, *Transaction) ([]Transaction, error) } -type mockClientHandler struct { - mock.Mock -} - -func (mh *mockClientHandler) Handle(cc *Client, t *Transaction) ([]Transaction, error) { - args := mh.Called(cc, t) - return args.Get(0).([]Transaction), args.Error(1) -} - -var clientHandlers = map[uint16]ClientTHandler{ - // Server initiated - TranChatMsg: ClientTransaction{ - Name: "TranChatMsg", - Handler: handleClientChatMsg, - }, - TranLogin: ClientTransaction{ - Name: "TranLogin", - Handler: handleClientTranLogin, - }, - TranShowAgreement: ClientTransaction{ - Name: "TranShowAgreement", - Handler: handleClientTranShowAgreement, - }, - TranUserAccess: ClientTransaction{ - Name: "TranUserAccess", - Handler: handleClientTranUserAccess, - }, - TranGetUserNameList: ClientTransaction{ - Name: "TranGetUserNameList", - Handler: handleClientGetUserNameList, - }, - TranNotifyChangeUser: ClientTransaction{ - Name: "TranNotifyChangeUser", - Handler: handleNotifyChangeUser, - }, - TranNotifyDeleteUser: ClientTransaction{ - Name: "TranNotifyDeleteUser", - Handler: handleNotifyDeleteUser, - }, - TranGetMsgs: ClientTransaction{ - Name: "TranNotifyDeleteUser", - Handler: handleGetMsgs, - }, - TranGetFileNameList: ClientTransaction{ - Name: "TranGetFileNameList", - Handler: handleGetFileNameList, - }, - TranServerMsg: ClientTransaction{ - Name: "TranServerMsg", - Handler: handleTranServerMsg, - }, - TranKeepAlive: ClientTransaction{ - Name: "TranKeepAlive", - Handler: func(client *Client, transaction *Transaction) (t []Transaction, err error) { - return t, err - }, +var clientHandlers = map[uint16]ClientHandler{ + TranChatMsg: handleClientChatMsg, + TranLogin: handleClientTranLogin, + TranShowAgreement: handleClientTranShowAgreement, + TranUserAccess: handleClientTranUserAccess, + TranGetUserNameList: handleClientGetUserNameList, + TranNotifyChangeUser: handleNotifyChangeUser, + TranNotifyDeleteUser: handleNotifyDeleteUser, + TranGetMsgs: handleGetMsgs, + TranGetFileNameList: handleGetFileNameList, + TranServerMsg: handleTranServerMsg, + TranKeepAlive: func(ctx context.Context, client *Client, transaction *Transaction) (t []Transaction, err error) { + return t, err }, } -func handleTranServerMsg(c *Client, t *Transaction) (res []Transaction, err error) { - time := time.Now().Format(time.RFC850) +func handleTranServerMsg(ctx context.Context, c *Client, t *Transaction) (res []Transaction, err error) { + now := time.Now().Format(time.RFC850) msg := strings.ReplaceAll(string(t.GetField(FieldData).Data), "\r", "\n") - msg += "\n\nAt " + time + msg += "\n\nAt " + now title := fmt.Sprintf("| Private Message From: %s |", t.GetField(FieldUserName).Data) msgBox := tview.NewTextView().SetScrollable(true) @@ -226,7 +188,7 @@ func handleTranServerMsg(c *Client, t *Transaction) (res []Transaction, err erro msgBox.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey { switch event.Key() { case tcell.KeyEscape: - c.UI.Pages.RemovePage("serverMsgModal" + time) + c.UI.Pages.RemovePage("serverMsgModal" + now) } return event }) @@ -239,14 +201,14 @@ func handleTranServerMsg(c *Client, t *Transaction) (res []Transaction, err erro AddItem(nil, 0, 1, false), 0, 2, true). AddItem(nil, 0, 1, false) - c.UI.Pages.AddPage("serverMsgModal"+time, centeredFlex, true, true) + c.UI.Pages.AddPage("serverMsgModal"+now, centeredFlex, true, true) c.UI.App.Draw() // TODO: errModal doesn't render without this. wtf? return res, err } func (c *Client) showErrMsg(msg string) { - time := time.Now().Format(time.RFC850) + t := time.Now().Format(time.RFC850) title := "| Error |" @@ -256,7 +218,7 @@ func (c *Client) showErrMsg(msg string) { msgBox.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey { switch event.Key() { case tcell.KeyEscape: - c.UI.Pages.RemovePage("serverMsgModal" + time) + c.UI.Pages.RemovePage("serverMsgModal" + t) } return event }) @@ -269,14 +231,13 @@ func (c *Client) showErrMsg(msg string) { AddItem(nil, 0, 1, false), 0, 2, true). AddItem(nil, 0, 1, false) - c.UI.Pages.AddPage("serverMsgModal"+time, centeredFlex, true, true) + c.UI.Pages.AddPage("serverMsgModal"+t, centeredFlex, true, true) c.UI.App.Draw() // TODO: errModal doesn't render without this. wtf? } -func handleGetFileNameList(c *Client, t *Transaction) (res []Transaction, err error) { +func handleGetFileNameList(ctx context.Context, c *Client, t *Transaction) (res []Transaction, err error) { if t.IsError() { c.showErrMsg(string(t.GetField(FieldError).Data)) - c.Logger.Infof("Error: %s", t.GetField(FieldError).Data) return res, err } @@ -297,7 +258,7 @@ func handleGetFileNameList(c *Client, t *Transaction) (res []Transaction, err er f := NewField(FieldFilePath, EncodeFilePath(strings.Join(c.filePath, "/"))) if err := c.UI.HLClient.Send(*NewTransaction(TranGetFileNameList, nil, f)); err != nil { - c.UI.HLClient.Logger.Errorw("err", "err", err) + c.UI.HLClient.Logger.Error("err", "err", err) } return event } @@ -305,17 +266,17 @@ func handleGetFileNameList(c *Client, t *Transaction) (res []Transaction, err er entry := selectedNode.GetReference().(*FileNameWithInfo) if bytes.Equal(entry.Type[:], []byte("fldr")) { - c.Logger.Infow("get new directory listing", "name", string(entry.name)) + c.Logger.Info("get new directory listing", "name", string(entry.name)) c.filePath = append(c.filePath, string(entry.name)) f := NewField(FieldFilePath, EncodeFilePath(strings.Join(c.filePath, "/"))) if err := c.UI.HLClient.Send(*NewTransaction(TranGetFileNameList, nil, f)); err != nil { - c.UI.HLClient.Logger.Errorw("err", "err", err) + c.UI.HLClient.Logger.Error("err", "err", err) } } else { // TODO: initiate file download - c.Logger.Infow("download file", "name", string(entry.name)) + c.Logger.Info("download file", "name", string(entry.name)) } } @@ -345,7 +306,6 @@ func handleGetFileNameList(c *Client, t *Transaction) (res []Transaction, err er node.SetReference(&fn) root.AddChild(node) } - } centerFlex := tview.NewFlex(). @@ -363,7 +323,7 @@ func handleGetFileNameList(c *Client, t *Transaction) (res []Transaction, err er return res, err } -func handleGetMsgs(c *Client, t *Transaction) (res []Transaction, err error) { +func handleGetMsgs(ctx context.Context, c *Client, t *Transaction) (res []Transaction, err error) { newsText := string(t.GetField(FieldData).Data) newsText = strings.ReplaceAll(newsText, "\r", "\n") @@ -383,7 +343,7 @@ func handleGetMsgs(c *Client, t *Transaction) (res []Transaction, err error) { return res, err } -func handleNotifyChangeUser(c *Client, t *Transaction) (res []Transaction, err error) { +func handleNotifyChangeUser(ctx context.Context, c *Client, t *Transaction) (res []Transaction, err error) { newUser := User{ ID: t.GetField(FieldUserID).Data, Name: string(t.GetField(FieldUserName).Data), @@ -399,7 +359,6 @@ func handleNotifyChangeUser(c *Client, t *Transaction) (res []Transaction, err e var newUserList []User updatedUser := false for _, u := range c.UserList { - c.Logger.Debugw("Comparing Users", "userToUpdate", newUser.ID, "myID", u.ID, "userToUpdateName", newUser.Name, "myname", u.Name) if bytes.Equal(newUser.ID, u.ID) { oldName = u.Name u.Name = newUser.Name @@ -422,7 +381,7 @@ func handleNotifyChangeUser(c *Client, t *Transaction) (res []Transaction, err e return res, err } -func handleNotifyDeleteUser(c *Client, t *Transaction) (res []Transaction, err error) { +func handleNotifyDeleteUser(ctx context.Context, c *Client, t *Transaction) (res []Transaction, err error) { exitUser := t.GetField(FieldUserID).Data var newUserList []User @@ -439,7 +398,7 @@ func handleNotifyDeleteUser(c *Client, t *Transaction) (res []Transaction, err e return res, err } -func handleClientGetUserNameList(c *Client, t *Transaction) (res []Transaction, err error) { +func handleClientGetUserNameList(ctx context.Context, c *Client, t *Transaction) (res []Transaction, err error) { var users []User for _, field := range t.Fields { // The Hotline protocol docs say that ClientGetUserNameList should only return FieldUsernameWithInfo (300) @@ -464,7 +423,7 @@ func (c *Client) renderUserList() { c.UI.userList.Clear() for _, u := range c.UserList { flagBitmap := big.NewInt(int64(binary.BigEndian.Uint16(u.Flags))) - if flagBitmap.Bit(userFlagAdmin) == 1 { + if flagBitmap.Bit(UserFlagAdmin) == 1 { _, _ = fmt.Fprintf(c.UI.userList, "[red::b]%s[-:-:-]\n", u.Name) } else { _, _ = fmt.Fprintf(c.UI.userList, "%s\n", u.Name) @@ -473,7 +432,7 @@ func (c *Client) renderUserList() { } } -func handleClientChatMsg(c *Client, t *Transaction) (res []Transaction, err error) { +func handleClientChatMsg(ctx context.Context, c *Client, t *Transaction) (res []Transaction, err error) { if c.Pref.EnableBell { fmt.Println("\a") } @@ -483,13 +442,13 @@ func handleClientChatMsg(c *Client, t *Transaction) (res []Transaction, err erro return res, err } -func handleClientTranUserAccess(c *Client, t *Transaction) (res []Transaction, err error) { +func handleClientTranUserAccess(ctx context.Context, c *Client, t *Transaction) (res []Transaction, err error) { c.UserAccess = t.GetField(FieldUserAccess).Data return res, err } -func handleClientTranShowAgreement(c *Client, t *Transaction) (res []Transaction, err error) { +func handleClientTranShowAgreement(ctx context.Context, c *Client, t *Transaction) (res []Transaction, err error) { agreement := string(t.GetField(FieldData).Data) agreement = strings.ReplaceAll(agreement, "\r", "\n") @@ -521,7 +480,7 @@ func handleClientTranShowAgreement(c *Client, t *Transaction) (res []Transaction return res, err } -func handleClientTranLogin(c *Client, t *Transaction) (res []Transaction, err error) { +func handleClientTranLogin(ctx context.Context, c *Client, t *Transaction) (res []Transaction, err error) { if !bytes.Equal(t.ErrorCode, []byte{0, 0, 0, 0}) { errMsg := string(t.GetField(FieldError).Data) errModal := tview.NewModal() @@ -542,7 +501,7 @@ func handleClientTranLogin(c *Client, t *Transaction) (res []Transaction, err er c.UI.App.SetFocus(c.UI.chatInput) if err := c.Send(*NewTransaction(TranGetUserNameList, nil)); err != nil { - c.Logger.Errorw("err", "err", err) + c.Logger.Error("err", "err", err) } return res, err } @@ -571,11 +530,12 @@ func (c *Client) Connect(address, login, passwd string) (err error) { return nil } +const keepaliveInterval = 300 * time.Second + func (c *Client) keepalive() error { for { - time.Sleep(300 * time.Second) + time.Sleep(keepaliveInterval) _ = c.Send(*NewTransaction(TranKeepAlive, nil)) - c.Logger.Infow("Sent keepalive ping") } } @@ -628,25 +588,22 @@ func (c *Client) LogIn(login string, password string) error { func (c *Client) Send(t Transaction) error { requestNum := binary.BigEndian.Uint16(t.Type) - tID := binary.BigEndian.Uint32(t.ID) - - // handler := TransactionHandlers[requestNum] // if transaction is NOT reply, add it to the list to transactions we're expecting a response for if t.IsReply == 0 { - c.activeTasks[tID] = &t + c.activeTasks[binary.BigEndian.Uint32(t.ID)] = &t } - var n int - var err error b, err := t.MarshalBinary() if err != nil { return err } + + var n int if n, err = c.Connection.Write(b); err != nil { return err } - c.Logger.Debugw("Sent Transaction", + c.Logger.Debug("Sent Transaction", "IsReply", t.IsReply, "type", requestNum, "sentBytes", n, @@ -654,7 +611,7 @@ func (c *Client) Send(t Transaction) error { return nil } -func (c *Client) HandleTransaction(t *Transaction) error { +func (c *Client) HandleTransaction(ctx context.Context, t *Transaction) error { var origT Transaction if t.IsReply == 1 { requestID := binary.BigEndian.Uint32(t.ID) @@ -662,19 +619,26 @@ func (c *Client) HandleTransaction(t *Transaction) error { t.Type = origT.Type } - requestNum := binary.BigEndian.Uint16(t.Type) - c.Logger.Debugw("Received Transaction", "RequestType", requestNum) - - if handler, ok := c.Handlers[requestNum]; ok { - outT, _ := handler.Handle(c, t) + if handler, ok := c.Handlers[binary.BigEndian.Uint16(t.Type)]; ok { + c.Logger.Debug( + "Received transaction", + "IsReply", t.IsReply, + "type", binary.BigEndian.Uint16(t.Type), + ) + outT, err := handler(ctx, c, t) + if err != nil { + c.Logger.Error("error handling transaction", "err", err) + } for _, t := range outT { - c.Send(t) + if err := c.Send(t); err != nil { + return err + } } } else { - c.Logger.Debugw( - "Unimplemented transaction type received", - "RequestID", requestNum, - "TransactionID", t.ID, + c.Logger.Debug( + "Unimplemented transaction type", + "IsReply", t.IsReply, + "type", binary.BigEndian.Uint16(t.Type), ) } @@ -685,7 +649,8 @@ func (c *Client) Disconnect() error { return c.Connection.Close() } -func (c *Client) HandleTransactions() error { + +func (c *Client) HandleTransactions(ctx context.Context) error { // Create a new scanner for parsing incoming bytes into transaction tokens scanner := bufio.NewScanner(c.Connection) scanner.Split(transactionScanner) @@ -702,8 +667,9 @@ func (c *Client) HandleTransactions() error { if err != nil { break } - if err := c.HandleTransaction(&t); err != nil { - c.Logger.Errorw("Error handling transaction", "err", err) + + if err := c.HandleTransaction(ctx, &t); err != nil { + c.Logger.Error("Error handling transaction", "err", err) } }