]> git.r.bdr.sh - rbdr/mobius/blobdiff - hotline/client.go
Improve handling of client config default path
[rbdr/mobius] / hotline / client.go
index 84126d3d4dd2b0d768b9bc6841b5adfd2c1e2f94..1e2972f6c8aa18c3e48a6985776641f1142c76ed 100644 (file)
@@ -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"
@@ -61,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
        }
@@ -90,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 {
@@ -105,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
 
@@ -200,6 +197,12 @@ 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) {
@@ -259,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 {
@@ -270,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))
                        }
                }
 
@@ -284,16 +287,19 @@ func handleGetFileNameList(c *Client, t *Transaction) (res []Transaction, err er
 
        for _, f := range t.Fields {
                var fn FileNameWithInfo
-               _, _ = fn.Read(f.Data)
+               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("   %-40s %10v KB", fn.Name, size))
+                       node := tview.NewTreeNode(fmt.Sprintf("   %-40s %10v KB", fn.name, size))
                        node.SetReference(&fn)
                        root.AddChild(node)
                }
@@ -328,8 +334,8 @@ func handleGetMsgs(c *Client, t *Transaction) (res []Transaction, err error) {
        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
@@ -489,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) {
@@ -512,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
 }
@@ -563,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
@@ -589,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)
        }
@@ -603,7 +617,7 @@ func (c *Client) Handshake() error {
                return err
        }
 
-       if bytes.Compare(replyBuf, ServerHandshake) == 0 {
+       if bytes.Equal(replyBuf, ServerHandshake) {
                return nil
        }
 
@@ -628,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 {
@@ -637,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",
@@ -678,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()
 }