X-Git-Url: https://git.r.bdr.sh/rbdr/mobius/blobdiff_plain/43ecc0f42eaeface5f640479df7372bfb8021f23..46b48603ea0e69aab8084a3ce32b31995b31b09c:/hotline/client.go?ds=sidebyside diff --git a/hotline/client.go b/hotline/client.go index 70e1d56..3a6584a 100644 --- a/hotline/client.go +++ b/hotline/client.go @@ -10,7 +10,7 @@ import ( "github.com/rivo/tview" "github.com/stretchr/testify/mock" "go.uber.org/zap" - "gopkg.in/yaml.v2" + "gopkg.in/yaml.v3" "math/big" "math/rand" "net" @@ -21,6 +21,7 @@ import ( const ( trackerListPage = "trackerList" + serverUIPage = "serverUI" ) //go:embed banners/*.txt @@ -46,6 +47,12 @@ func (cp *ClientPrefs) IconBytes() []byte { return iconBytes } +func (cp *ClientPrefs) AddBookmark(name, addr, login, pass string) error { + cp.Bookmarks = append(cp.Bookmarks, Bookmark{Addr: addr, Login: login, Password: pass}) + + return nil +} + func readConfig(cfgPath string) (*ClientPrefs, error) { fh, err := os.Open(cfgPath) if err != nil { @@ -54,7 +61,6 @@ func readConfig(cfgPath string) (*ClientPrefs, error) { prefs := ClientPrefs{} decoder := yaml.NewDecoder(fh) - decoder.SetStrict(true) if err := decoder.Decode(&prefs); err != nil { return nil, err } @@ -75,6 +81,7 @@ type Client struct { UserList []User Logger *zap.SugaredLogger activeTasks map[uint32]*Transaction + serverName string pref *ClientPrefs @@ -82,8 +89,7 @@ type Client struct { UI *UI - outbox chan *Transaction - Inbox chan *Transaction + Inbox chan *Transaction } func NewClient(cfgPath string, logger *zap.SugaredLogger) *Client { @@ -97,8 +103,7 @@ func NewClient(cfgPath string, logger *zap.SugaredLogger) *Client { prefs, err := readConfig(cfgPath) if err != nil { - fmt.Printf("unable to read config file %s", cfgPath) - os.Exit(1) + logger.Fatal(fmt.Sprintf("unable to read config file %s\n", cfgPath)) } c.pref = prefs @@ -114,7 +119,7 @@ func (db *DebugBuffer) Write(p []byte) (int, error) { return db.TextView.Write(p) } -// Sync is a noop function that exists to satisfy the zapcore.WriteSyncer interface +// Sync is a noop function that dataFile to satisfy the zapcore.WriteSyncer interface func (db *DebugBuffer) Sync() error { return nil } @@ -188,6 +193,48 @@ var clientHandlers = map[uint16]clientTHandler{ 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 + }, + }, +} + +func handleTranServerMsg(c *Client, t *Transaction) (res []Transaction, err error) { + time := time.Now().Format(time.RFC850) + + msg := strings.ReplaceAll(string(t.GetField(fieldData).Data), "\r", "\n") + msg += "\n\nAt " + time + title := fmt.Sprintf("| Private Message From: %s |", t.GetField(fieldUserName).Data) + + msgBox := tview.NewTextView().SetScrollable(true) + msgBox.SetText(msg).SetBackgroundColor(tcell.ColorDarkSlateBlue) + msgBox.SetTitle(title).SetBorder(true) + msgBox.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey { + switch event.Key() { + case tcell.KeyEscape: + c.UI.Pages.RemovePage("serverMsgModal" + time) + } + return event + }) + + centeredFlex := tview.NewFlex(). + AddItem(nil, 0, 1, false). + AddItem(tview.NewFlex().SetDirection(tview.FlexRow). + AddItem(nil, 0, 1, false). + AddItem(msgBox, 0, 2, true). + AddItem(nil, 0, 1, false), 0, 2, true). + AddItem(nil, 0, 1, false) + + c.UI.Pages.AddPage("serverMsgModal"+time, centeredFlex, true, true) + c.UI.App.Draw() // TODO: errModal doesn't render without this. wtf? + + return res, err } func handleGetFileNameList(c *Client, t *Transaction) (res []Transaction, err error) { @@ -215,10 +262,10 @@ 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)) + if bytes.Equal(entry.Type[:], []byte("fldr")) { + c.Logger.Infow("get new directory listing", "name", string(entry.name)) - c.filePath = append(c.filePath, 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 { @@ -226,7 +273,7 @@ func handleGetFileNameList(c *Client, t *Transaction) (res []Transaction, err er } } else { // TODO: initiate file download - c.Logger.Infow("download file", "name", string(entry.Name)) + c.Logger.Infow("download file", "name", string(entry.name)) } } @@ -238,20 +285,21 @@ func handleGetFileNameList(c *Client, t *Transaction) (res []Transaction, err er root.AddChild(node) } - var fileList []FileNameWithInfo for _, f := range t.Fields { var fn FileNameWithInfo - _, _ = fn.Read(f.Data) - fileList = append(fileList, fn) + err = fn.UnmarshalBinary(f.Data) + if err != nil { + return nil, nil + } - if bytes.Equal(fn.Type, []byte("fldr")) { - node := tview.NewTreeNode(fmt.Sprintf("[blue::]📁 %s[-:-:-]", fn.Name)) + if bytes.Equal(fn.Type[:], []byte("fldr")) { + node := tview.NewTreeNode(fmt.Sprintf("[blue::]📁 %s[-:-:-]", fn.name)) node.SetReference(&fn) root.AddChild(node) } else { - size := binary.BigEndian.Uint32(fn.FileSize) / 1024 + size := binary.BigEndian.Uint32(fn.FileSize[:]) / 1024 - node := tview.NewTreeNode(fmt.Sprintf(" %-10s %10v KB", fn.Name, size)) + node := tview.NewTreeNode(fmt.Sprintf(" %-40s %10v KB", fn.name, size)) node.SetReference(&fn) root.AddChild(node) } @@ -264,7 +312,7 @@ func handleGetFileNameList(c *Client, t *Transaction) (res []Transaction, err er SetDirection(tview.FlexRow). AddItem(nil, 0, 1, false). AddItem(fTree, 20, 1, true). - AddItem(nil, 0, 1, false), 40, 1, true). + AddItem(nil, 0, 1, false), 60, 1, true). AddItem(nil, 0, 1, false) c.UI.Pages.AddPage("files", centerFlex, true, true) @@ -280,14 +328,14 @@ func handleGetMsgs(c *Client, t *Transaction) (res []Transaction, err error) { newsTextView := tview.NewTextView(). SetText(newsText). SetDoneFunc(func(key tcell.Key) { - c.UI.Pages.SwitchToPage("serverUI") + c.UI.Pages.SwitchToPage(serverUIPage) c.UI.App.SetFocus(c.UI.chatInput) }) newsTextView.SetBorder(true).SetTitle("News") c.UI.Pages.AddPage("news", newsTextView, true, true) - //c.UI.Pages.SwitchToPage("news") - //c.UI.App.SetFocus(newsTextView) + // c.UI.Pages.SwitchToPage("news") + // c.UI.App.SetFocus(newsTextView) c.UI.App.Draw() return res, err @@ -447,7 +495,7 @@ func handleClientTranShowAgreement(c *Client, t *Transaction) (res []Transaction agreement := string(t.GetField(fieldData).Data) agreement = strings.ReplaceAll(agreement, "\r", "\n") - c.UI.agreeModal = tview.NewModal(). + agreeModal := tview.NewModal(). SetText(agreement). AddButtons([]string{"Agree", "Disagree"}). SetDoneFunc(func(buttonIndex int, buttonLabel string) { @@ -470,10 +518,7 @@ func handleClientTranShowAgreement(c *Client, t *Transaction) (res []Transaction }, ) - c.Logger.Debug("show agreement page") - c.UI.Pages.AddPage("agreement", c.UI.agreeModal, false, true) - c.UI.Pages.ShowPage("agreement ") - c.UI.App.Draw() + c.UI.Pages.AddPage("agreement", agreeModal, false, true) return res, err } @@ -495,7 +540,7 @@ func handleClientTranLogin(c *Client, t *Transaction) (res []Transaction, err er c.Logger.Error(string(t.GetField(fieldError).Data)) return nil, errors.New("login error: " + string(t.GetField(fieldError).Data)) } - c.UI.Pages.AddAndSwitchToPage("serverUI", c.UI.renderServerUI(), true) + c.UI.Pages.AddAndSwitchToPage(serverUIPage, c.UI.renderServerUI(), true) c.UI.App.SetFocus(c.UI.chatInput) if err := c.Send(*NewTransaction(tranGetUserNameList, nil)); err != nil { @@ -521,9 +566,20 @@ func (c *Client) JoinServer(address, login, passwd string) error { return err } + // start keepalive go routine + go func() { _ = c.keepalive() }() + return nil } +func (c *Client) keepalive() error { + for { + time.Sleep(300 * time.Second) + _ = c.Send(*NewTransaction(tranKeepAlive, nil)) + c.Logger.Infow("Sent keepalive ping") + } +} + // connect establishes a connection with a Server by sending handshake sequence func (c *Client) connect(address string) error { var err error @@ -547,10 +603,10 @@ var ServerHandshake = []byte{ } func (c *Client) Handshake() error { - //Protocol ID 4 ‘TRTP’ 0x54 52 54 50 - //Sub-protocol ID 4 User defined - //Version 2 1 Currently 1 - //Sub-version 2 User defined + // Protocol ID 4 ‘TRTP’ 0x54 52 54 50 + // Sub-protocol ID 4 User defined + // Version 2 1 Currently 1 + // Sub-version 2 User defined if _, err := c.Connection.Write(ClientHandshake); err != nil { return fmt.Errorf("handshake write err: %s", err) } @@ -561,7 +617,7 @@ func (c *Client) Handshake() error { return err } - if bytes.Compare(replyBuf, ServerHandshake) == 0 { + if bytes.Equal(replyBuf, ServerHandshake) { return nil } @@ -575,9 +631,8 @@ func (c *Client) LogIn(login string, password string) error { tranLogin, nil, NewField(fieldUserName, []byte(c.pref.Username)), NewField(fieldUserIconID, c.pref.IconBytes()), - NewField(fieldUserLogin, []byte(NegatedUserString([]byte(login)))), - NewField(fieldUserPassword, []byte(NegatedUserString([]byte(password)))), - NewField(fieldVersion, []byte{0, 2}), + NewField(fieldUserLogin, negateString([]byte(login))), + NewField(fieldUserPassword, negateString([]byte(password))), ), ) } @@ -586,7 +641,7 @@ func (c *Client) Send(t Transaction) error { requestNum := binary.BigEndian.Uint16(t.Type) tID := binary.BigEndian.Uint32(t.ID) - //handler := TransactionHandlers[requestNum] + // 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 { @@ -595,7 +650,11 @@ func (c *Client) Send(t Transaction) error { var n int var err error - if n, err = c.Connection.Write(t.Payload()); err != nil { + b, err := t.MarshalBinary() + if err != nil { + return err + } + if n, err = c.Connection.Write(b); err != nil { return err } c.Logger.Debugw("Sent Transaction", @@ -636,18 +695,6 @@ func (c *Client) HandleTransaction(t *Transaction) error { return nil } -func (c *Client) Connected() bool { - // c.Agreed == true && - if c.UserAccess != nil { - return true - } - return false -} - func (c *Client) Disconnect() error { - err := c.Connection.Close() - if err != nil { - return err - } - return nil + return c.Connection.Close() }