X-Git-Url: https://git.r.bdr.sh/rbdr/mobius/blobdiff_plain/3d2bd095b354c5ba84f51073b26c752290467784..d4c152a4dba0eec7c8ecd13732900909f51b1c97:/hotline/client.go?ds=sidebyside diff --git a/hotline/client.go b/hotline/client.go index 5016a50..1e2972f 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 @@ -192,13 +197,19 @@ var clientHandlers = map[uint16]clientTHandler{ 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 + msg += "\n\nAt " + time title := fmt.Sprintf("| Private Message From: %s |", t.GetField(fieldUserName).Data) msgBox := tview.NewTextView().SetScrollable(true) @@ -220,8 +231,7 @@ 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"+time, centeredFlex, true, true) c.UI.App.Draw() // TODO: errModal doesn't render without this. wtf? return res, err @@ -252,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 { @@ -263,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)) } } @@ -275,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(" %-30s %15v KB", fn.Name, size)) + node := tview.NewTreeNode(fmt.Sprintf(" %-40s %10v KB", fn.name, size)) node.SetReference(&fn) root.AddChild(node) } @@ -317,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 @@ -484,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) { @@ -507,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 } @@ -532,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 { @@ -558,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 @@ -584,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) } @@ -598,7 +617,7 @@ func (c *Client) Handshake() error { return err } - if bytes.Compare(replyBuf, ServerHandshake) == 0 { + if bytes.Equal(replyBuf, ServerHandshake) { return nil } @@ -612,8 +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(fieldUserLogin, negateString([]byte(login))), + NewField(fieldUserPassword, negateString([]byte(password))), NewField(fieldVersion, []byte{0, 2}), ), ) @@ -623,7 +642,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 { @@ -632,7 +651,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", @@ -673,18 +696,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() }