cli: Separate UI logic and fix client threadsafety

This commit is contained in:
John Brooks 2016-10-15 22:57:16 -06:00
parent 99d44e1278
commit c8bfe4663e
3 changed files with 190 additions and 132 deletions

View File

@ -3,13 +3,10 @@ package main
import ( import (
"fmt" "fmt"
rpc "github.com/special/notricochet/rpc" rpc "github.com/special/notricochet/rpc"
"golang.org/x/net/context"
"google.golang.org/grpc" "google.golang.org/grpc"
"gopkg.in/readline.v1" "gopkg.in/readline.v1"
"log" "log"
"os" "os"
"strconv"
"strings"
) )
const ( const (
@ -32,108 +29,20 @@ func main() {
defer input.Close() defer input.Close()
log.SetOutput(input.Stdout()) log.SetOutput(input.Stdout())
c := &Client{ client := &Client{
Backend: rpc.NewRicochetCoreClient(conn), Backend: rpc.NewRicochetCoreClient(conn),
Input: input,
} }
ui := &UI{
Input: input,
Client: client,
}
client.Ui = ui
if err := c.Initialize(); err != nil { if err := client.Initialize(); err != nil {
fmt.Println(err) fmt.Println(err)
os.Exit(1) os.Exit(1)
} }
go c.Run() go client.Run()
ui.CommandLoop()
input.SetPrompt("> ")
for {
line := input.Line()
if line.CanContinue() {
continue
} else if line.CanBreak() {
break
}
words := strings.SplitN(line.Line, " ", 1)
if id, err := strconv.Atoi(words[0]); err == nil {
contact := c.Contacts.ById(int32(id))
if contact != nil {
c.SetCurrentContact(contact)
} else {
fmt.Printf("no contact %d\n", id)
}
continue
}
if c.CurrentContact != nil {
if len(words[0]) > 0 && words[0][0] == '/' {
words[0] = words[0][1:]
} else {
_, err := c.Backend.SendMessage(context.Background(), &rpc.Message{
Sender: &rpc.Entity{IsSelf: true},
Recipient: &rpc.Entity{
ContactId: c.CurrentContact.Data.Id,
Address: c.CurrentContact.Data.Address,
},
Text: line.Line,
})
if err != nil {
fmt.Printf("send message error: %v\n", err)
}
continue
}
}
switch words[0] {
case "clear":
readline.ClearScreen(readline.Stdout)
case "quit":
os.Exit(0)
case "status":
fmt.Printf("server: %v\n", c.ServerStatus)
fmt.Printf("identity: %v\n", c.Identity)
case "connect":
status, err := c.Backend.StartNetwork(context.Background(), &rpc.StartNetworkRequest{})
if err != nil {
fmt.Printf("start network error: %v\n", err)
} else {
fmt.Printf("network started: %v\n", status)
}
case "disconnect":
status, err := c.Backend.StopNetwork(context.Background(), &rpc.StopNetworkRequest{})
if err != nil {
fmt.Printf("stop network error: %v\n", err)
} else {
fmt.Printf("network stopped: %v\n", status)
}
case "contacts":
byStatus := make(map[rpc.Contact_Status][]*Contact)
for _, contact := range c.Contacts.Contacts {
byStatus[contact.Data.Status] = append(byStatus[contact.Data.Status], contact)
}
order := []rpc.Contact_Status{rpc.Contact_ONLINE, rpc.Contact_UNKNOWN, rpc.Contact_OFFLINE, rpc.Contact_REQUEST, rpc.Contact_REJECTED}
for _, status := range order {
contacts := byStatus[status]
if len(contacts) == 0 {
continue
}
fmt.Printf(". %s\n", strings.ToLower(status.String()))
for _, contact := range contacts {
fmt.Printf("... [%d] %s\n", contact.Data.Id, contact.Data.Nickname)
}
}
case "help":
fallthrough
default:
fmt.Println("Commands: clear, quit, status, connect, disconnect, contacts, help")
}
}
} }

View File

@ -4,23 +4,22 @@ import (
"fmt" "fmt"
"github.com/special/notricochet/rpc" "github.com/special/notricochet/rpc"
"golang.org/x/net/context" "golang.org/x/net/context"
"gopkg.in/readline.v1"
"log" "log"
"strings"
) )
type Client struct { type Client struct {
Backend ricochet.RicochetCoreClient Backend ricochet.RicochetCoreClient
Input *readline.Instance Ui *UI
ServerStatus ricochet.ServerStatusReply ServerStatus ricochet.ServerStatusReply
Identity ricochet.Identity Identity ricochet.Identity
NetworkStatus ricochet.NetworkStatus NetworkStatus ricochet.NetworkStatus
Contacts *ContactList Contacts *ContactList
CurrentContact *Contact
monitorsChannel chan interface{} monitorsChannel chan interface{}
blockChannel chan struct{}
unblockChannel chan struct{}
populatedContacts bool populatedContacts bool
} }
@ -28,6 +27,8 @@ type Client struct {
func (c *Client) Initialize() error { func (c *Client) Initialize() error {
c.Contacts = NewContactList() c.Contacts = NewContactList()
c.monitorsChannel = make(chan interface{}, 10) c.monitorsChannel = make(chan interface{}, 10)
c.blockChannel = make(chan struct{})
c.unblockChannel = make(chan struct{})
// Query server status and version // Query server status and version
status, err := c.Backend.GetServerStatus(context.Background(), &ricochet.ServerStatusRequest{ status, err := c.Backend.GetServerStatus(context.Background(), &ricochet.ServerStatusRequest{
@ -71,24 +72,18 @@ func (c *Client) Run() {
default: default:
log.Panicf("Unknown event type on monitor channel: %v", event) log.Panicf("Unknown event type on monitor channel: %v", event)
} }
case <-c.blockChannel:
<-c.unblockChannel
} }
} }
} }
func (c *Client) SetCurrentContact(contact *Contact) { func (c *Client) Block() {
c.CurrentContact = contact c.blockChannel <- struct{}{}
if c.CurrentContact != nil {
config := *c.Input.Config
config.Prompt = fmt.Sprintf("%s > ", c.CurrentContact.Data.Nickname)
config.UniqueEditLine = true
c.Input.SetConfig(&config)
fmt.Printf("--- %s (%s) ---\n", c.CurrentContact.Data.Nickname, strings.ToLower(c.CurrentContact.Data.Status.String()))
} else {
config := *c.Input.Config
config.Prompt = "> "
config.UniqueEditLine = false
c.Input.SetConfig(&config)
} }
func (c *Client) Unblock() {
c.unblockChannel <- struct{}{}
} }
func (c *Client) monitorNetwork() { func (c *Client) monitorNetwork() {
@ -206,8 +201,8 @@ func (c *Client) onContactEvent(event *ricochet.ContactEvent) {
contact, _ := c.Contacts.Deleted(data) contact, _ := c.Contacts.Deleted(data)
if c.CurrentContact == contact { if c.Ui.CurrentContact == contact {
c.SetCurrentContact(nil) c.Ui.SetCurrentContact(nil)
} }
default: default:
@ -241,16 +236,7 @@ func (c *Client) onConversationEvent(event *ricochet.ConversationEvent) {
return return
} }
if remoteContact == c.CurrentContact { c.Ui.PrintMessage(remoteContact, message.Sender.IsSelf, message.Text)
// XXX so unsafe
if message.Sender.IsSelf {
fmt.Fprintf(c.Input.Stdout(), "\r%s > %s\n", remoteContact.Data.Nickname, message.Text)
} else {
fmt.Fprintf(c.Input.Stdout(), "\r%s < %s\n", remoteContact.Data.Nickname, message.Text)
}
} else if !message.Sender.IsSelf {
fmt.Fprintf(c.Input.Stdout(), "\r---- %s < %s\n", remoteContact.Data.Nickname, message.Text)
}
if !message.Sender.IsSelf { if !message.Sender.IsSelf {
backend := c.Backend backend := c.Backend

163
cli/ui.go Normal file
View File

@ -0,0 +1,163 @@
package main
import (
"errors"
"fmt"
"github.com/special/notricochet/rpc"
"golang.org/x/net/context"
"gopkg.in/readline.v1"
"strconv"
"strings"
)
type UI struct {
Input *readline.Instance
Client *Client
CurrentContact *Contact
}
func (ui *UI) CommandLoop() {
ui.Input.SetPrompt("> ")
for {
line, err := ui.Input.Readline()
if err != nil {
return
}
if err := ui.Execute(line); err != nil {
return
}
}
}
func (ui *UI) Execute(line string) error {
// Block client event handlers for threadsafety
ui.Client.Block()
defer ui.Client.Unblock()
words := strings.SplitN(line, " ", 1)
if ui.CurrentContact != nil {
if len(words[0]) > 0 && words[0][0] == '/' {
words[0] = words[0][1:]
} else {
ui.SendMessage(line)
return nil
}
}
if id, err := strconv.Atoi(words[0]); err == nil {
contact := ui.Client.Contacts.ById(int32(id))
if contact != nil {
ui.SetCurrentContact(contact)
} else {
fmt.Printf("no contact %d\n", id)
}
return nil
}
switch words[0] {
case "clear":
readline.ClearScreen(readline.Stdout)
case "quit":
return errors.New("Quitting")
case "status":
fmt.Printf("server: %v\n", ui.Client.ServerStatus)
fmt.Printf("identity: %v\n", ui.Client.Identity)
case "connect":
status, err := ui.Client.Backend.StartNetwork(context.Background(), &ricochet.StartNetworkRequest{})
if err != nil {
fmt.Printf("start network error: %v\n", err)
} else {
fmt.Printf("network started: %v\n", status)
}
case "disconnect":
status, err := ui.Client.Backend.StopNetwork(context.Background(), &ricochet.StopNetworkRequest{})
if err != nil {
fmt.Printf("stop network error: %v\n", err)
} else {
fmt.Printf("network stopped: %v\n", status)
}
case "contacts":
ui.ListContacts()
case "help":
fallthrough
default:
fmt.Println("Commands: clear, quit, status, connect, disconnect, contacts, help")
}
return nil
}
func (ui *UI) PrintMessage(contact *Contact, outbound bool, text string) {
if contact == ui.CurrentContact {
if outbound {
fmt.Fprintf(ui.Input.Stdout(), "\r%s > %s\n", contact.Data.Nickname, text)
} else {
fmt.Fprintf(ui.Input.Stdout(), "\r%s < %s\n", contact.Data.Nickname, text)
}
} else if !outbound {
fmt.Fprintf(ui.Input.Stdout(), "\r---- %s < %s\n", contact.Data.Nickname, text)
}
}
func (ui *UI) SendMessage(text string) {
_, err := ui.Client.Backend.SendMessage(context.Background(), &ricochet.Message{
Sender: &ricochet.Entity{IsSelf: true},
Recipient: &ricochet.Entity{
ContactId: ui.CurrentContact.Data.Id,
Address: ui.CurrentContact.Data.Address,
},
Text: text,
})
if err != nil {
fmt.Printf("send message error: %v\n", err)
}
}
func (ui *UI) ListContacts() {
byStatus := make(map[ricochet.Contact_Status][]*Contact)
for _, contact := range ui.Client.Contacts.Contacts {
byStatus[contact.Data.Status] = append(byStatus[contact.Data.Status], contact)
}
order := []ricochet.Contact_Status{ricochet.Contact_ONLINE, ricochet.Contact_UNKNOWN, ricochet.Contact_OFFLINE, ricochet.Contact_REQUEST, ricochet.Contact_REJECTED}
for _, status := range order {
contacts := byStatus[status]
if len(contacts) == 0 {
continue
}
fmt.Printf(". %s\n", strings.ToLower(status.String()))
for _, contact := range contacts {
fmt.Printf("... [%d] %s\n", contact.Data.Id, contact.Data.Nickname)
}
}
}
func (ui *UI) SetCurrentContact(contact *Contact) {
if ui.CurrentContact == contact {
return
}
ui.CurrentContact = contact
if ui.CurrentContact != nil {
config := *ui.Input.Config
config.Prompt = fmt.Sprintf("%s > ", contact.Data.Nickname)
config.UniqueEditLine = true
ui.Input.SetConfig(&config)
fmt.Printf("--- %s (%s) ---\n", contact.Data.Nickname, strings.ToLower(contact.Data.Status.String()))
} else {
config := *ui.Input.Config
config.Prompt = "> "
config.UniqueEditLine = false
ui.Input.SetConfig(&config)
}
}