7 Commits
v2.0.2 ... main

Author SHA1 Message Date
2be41ab217 Add option to send nonblocking chat messages 2021-01-15 13:51:59 -05:00
c927ffad89 Add more chat tests 2020-05-17 15:00:58 -04:00
ce9bb9601b Add tests 2020-05-17 00:38:23 -04:00
0a8e68baf4 Remove print statement that was left in by accident... woops! 2020-05-12 18:50:55 -04:00
acc3e3ddec Fix ListConvsOnName 2020-05-12 14:45:50 -04:00
22396f8276 Add ListConvsOnName 2020-05-12 01:39:29 -04:00
c9a2bd80bc Add New() for creating new keybase objects.
This function accepts functional options, and allows you to set an alternate home dir for keybase
2020-05-11 22:48:30 -04:00
5 changed files with 332 additions and 6 deletions

45
chat.go
View File

@ -5,7 +5,6 @@ import (
"encoding/json"
"errors"
"fmt"
"os/exec"
"time"
"samhofi.us/x/keybase/v2/types/chat1"
@ -37,7 +36,15 @@ func getNewMessages(k *Keybase, subs *subscriptionChannels, execOptions []string
execString = append(execString, execOptions...)
}
for {
execCmd := exec.Command(k.Path, execString...)
cmd := make([]string, 0)
if k.HomePath != "" {
cmd = append(cmd, "--home", k.HomePath)
}
cmd = append(cmd, execString...)
execCmd := execCommand(k.ExePath, cmd...)
stdOut, _ := execCmd.StdoutPipe()
execCmd.Start()
scanner := bufio.NewScanner(stdOut)
@ -744,3 +751,37 @@ func (k *Keybase) ListMembersOfConversation(convID chat1.ConvIDStr) (chat1.ChatM
}
return k.ListMembers(opts)
}
// ListConvsOnName returns a list of all conversations for a chat1.ChatChannel
func (k *Keybase) ListConvsOnName(channel chat1.ChatChannel) (*[]chat1.ConvSummary, error) {
type result struct {
Conversations []chat1.ConvSummary `json:"conversations"`
}
type res struct {
Result result `json:"result"`
Error *Error `json:"error,omitempty"`
}
var r res
arg := newListConvsOnNameArg(channel)
jsonBytes, _ := json.Marshal(arg)
cmdOut, err := k.Exec("chat", "api", "-m", string(jsonBytes))
if err != nil {
return nil, err
}
err = json.Unmarshal(cmdOut, &r)
if err != nil {
return nil, err
}
if r.Error != nil {
return nil, fmt.Errorf("%v", r.Error.Message)
}
return &r.Result.Conversations, nil
}

135
chat_test.go Normal file
View File

@ -0,0 +1,135 @@
package keybase
import (
"os/exec"
"testing"
"samhofi.us/x/keybase/v2/types/chat1"
)
func TestListConvsOnName(t *testing.T) {
execCommand = createFakeExecCommand("listconvsonname")
defer func() { execCommand = exec.Command }()
channel := chat1.ChatChannel{
Name: "mkbot",
MembersType: TEAM,
}
k := New()
res, err := k.ListConvsOnName(channel)
if err != nil {
t.Errorf("Expected nil error, got %#v", err)
}
channelcount := 10
if len(*res) != channelcount {
t.Errorf("Expected %d channels, got %d channels", channelcount, len(*res))
}
}
func TestSendMessageByChannel(t *testing.T) {
execCommand = createFakeExecCommand("send")
defer func() { execCommand = exec.Command }()
channel := chat1.ChatChannel{
Name: "user1,user2",
MembersType: USER,
}
k := New()
res, err := k.SendMessageByChannel(channel, "Hello!")
if err != nil {
t.Errorf("Expected nil error, got %#v", err)
}
if expected := "message sent"; res.Message != expected {
t.Errorf(`res.Message: expected "%s", got "%v"`, expected, res.Message)
}
if expected := uint(894); uint(*res.MessageID) != expected {
t.Errorf(`res.MessageID: expected %d, got %d`, expected, uint(*res.MessageID))
}
}
func TestSendMessageByConvID(t *testing.T) {
execCommand = createFakeExecCommand("send")
defer func() { execCommand = exec.Command }()
k := New()
res, err := k.SendMessageByConvID(chat1.ConvIDStr("000049d2395435dff0c865c18832d9645eb69fd74a2814ef55310b294092ba6d"), "Hello!")
if err != nil {
t.Errorf("Expected nil error, got %#v", err)
}
if expected := "message sent"; res.Message != expected {
t.Errorf(`res.Message: expected "%s", got "%v"`, expected, res.Message)
}
if expected := uint(894); uint(*res.MessageID) != expected {
t.Errorf(`res.MessageID: expected %d, got %d`, expected, uint(*res.MessageID))
}
}
func TestCreateFilterString(t *testing.T) {
tables := []struct {
channel chat1.ChatChannel
expected string
}{
{
chat1.ChatChannel{},
``,
},
{
chat1.ChatChannel{Name: "faketeam", MembersType: TEAM},
`{"name":"faketeam","members_type":"team"}`,
},
{
chat1.ChatChannel{Name: "user1,user2", MembersType: USER},
`{"name":"user1,user2","members_type":"impteamnative"}`,
},
}
for _, table := range tables {
if result := createFilterString(table.channel); result != table.expected {
t.Errorf(`Expected "%s", got "%s"`, table.expected, result)
}
}
}
func TestCreateFiltersString(t *testing.T) {
tables := []struct {
channel []chat1.ChatChannel
expected string
}{
{
[]chat1.ChatChannel{},
``,
},
{
[]chat1.ChatChannel{
chat1.ChatChannel{Name: "faketeam1", MembersType: TEAM},
chat1.ChatChannel{Name: "faketeam2", MembersType: TEAM},
},
`[{"name":"faketeam1","members_type":"team"},{"name":"faketeam2","members_type":"team"}]`,
},
{
[]chat1.ChatChannel{
chat1.ChatChannel{Name: "user1,user2", MembersType: USER},
chat1.ChatChannel{Name: "user3,user4", MembersType: USER},
},
`[{"name":"user1,user2","members_type":"impteamnative"},{"name":"user3,user4","members_type":"impteamnative"}]`,
},
{
[]chat1.ChatChannel{
chat1.ChatChannel{Name: "user1,user2", MembersType: USER},
chat1.ChatChannel{Name: "faketeam1", MembersType: TEAM},
},
`[{"name":"user1,user2","members_type":"impteamnative"},{"name":"faketeam1","members_type":"team"}]`,
},
}
for _, table := range tables {
if result := createFiltersString(table.channel); result != table.expected {
t.Errorf(`Expected "%s", got "%s"`, table.expected, result)
}
}
}

View File

@ -9,6 +9,9 @@ import (
"samhofi.us/x/keybase/v2/types/chat1"
)
// Used for testing
var execCommand = exec.Command
// Possible MemberTypes
const (
TEAM string = "team"
@ -21,13 +24,33 @@ const (
CHAT string = "chat"
)
// New returns a new Keybase
func New(opts ...KeybaseOpt) *Keybase {
k := &Keybase{ExePath: "keybase"}
for _, opt := range opts {
opt.apply(k)
}
s := k.status()
k.Version = k.version()
k.LoggedIn = s.LoggedIn
if k.LoggedIn {
k.Username = s.Username
k.Device = s.Device.Name
}
return k
}
// NewKeybase returns a new Keybase. Optionally, you can pass a string containing the path to the Keybase executable as the first argument.
// This is deprecated and will be removed in a future update. Use New() instead.
func NewKeybase(path ...string) *Keybase {
k := &Keybase{}
if len(path) < 1 {
k.Path = "keybase"
k.ExePath = "keybase"
} else {
k.Path = path[0]
k.ExePath = path[0]
}
s := k.status()
@ -42,7 +65,15 @@ func NewKeybase(path ...string) *Keybase {
// Exec executes the given Keybase command
func (k *Keybase) Exec(command ...string) ([]byte, error) {
out, err := exec.Command(k.Path, command...).Output()
cmd := make([]string, 0)
if k.HomePath != "" {
cmd = append(cmd, "--home", k.HomePath)
}
cmd = append(cmd, command...)
out, err := execCommand(k.ExePath, cmd...).Output()
if err != nil {
return []byte{}, err
}

68
keybase_test.go Normal file
View File

@ -0,0 +1,68 @@
package keybase
import (
"fmt"
"os"
"os/exec"
"testing"
)
func createFakeExecCommand(caller string) func(command string, args ...string) *exec.Cmd {
return func(command string, args ...string) *exec.Cmd {
cs := []string{"-test.run=ExecHelper", "--"}
cs = append(cs, args...)
cmd := exec.Command(os.Args[0], cs...)
cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1", "GO_WANT_HELPER_CALLER=" + caller}
return cmd
}
}
func TestNew(t *testing.T) {
execCommand = createFakeExecCommand("new")
defer func() { execCommand = exec.Command }()
k := New()
if expected := "keybase"; k.ExePath != expected {
t.Errorf(`k.ExePath: expected "%s", got "%s"`, expected, k.ExePath)
}
if expected := ""; k.HomePath != expected {
t.Errorf(`k.HomePath: expected "%s", got "%s"`, expected, k.HomePath)
}
k = New(
SetExePath("/path/to/exepath"),
SetHomePath("/path/to/homepath"),
)
if expected := "/path/to/exepath"; k.ExePath != expected {
t.Errorf(`k.ExePath: expected "%s", got "%s"`, expected, k.ExePath)
}
if expected := "/path/to/homepath"; k.HomePath != expected {
t.Errorf(`k.HomePath: expected "%s", got "%s"`, expected, k.HomePath)
}
}
func TestExecHelper(t *testing.T) {
if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" {
return
}
var (
listconvsonname = `{"result":{"conversations":[{"id":"0000b9d9be8586029d4876af2192b94d6705603cf6859fc27c746de94befd45c","channel":{"name":"mkbot","members_type":"team","topic_type":"chat"},"is_default_conv":false,"unread":true,"active_at":1589468132,"active_at_ms":1589468132734,"member_status":"active","creator_info":{"ctime":1551848940888,"username":"dxb"}},{"id":"0000d2c4d915aa04c093a25b9496cd885ff510f4eeeacac5a7249f65d82ed0ad","channel":{"name":"mkbot","members_type":"team","topic_type":"chat"},"is_default_conv":false,"unread":false,"active_at":1589633805,"active_at_ms":1589633805970,"member_status":"active","creator_info":{"ctime":1551848919282,"username":"dxb"}},{"id":"0000e967261971be5aae47d1cfd7d77e695d4a2f90e2ee35236ef3472b2884d4","channel":{"name":"mkbot","members_type":"team","topic_type":"chat","topic_name":"gameroom"},"is_default_conv":false,"unread":true,"active_at":1589468113,"active_at_ms":1589468113173,"member_status":"active","creator_info":{"ctime":1566244683161,"username":"dxb"}},{"id":"0000d5ae3da566307f6c9906881e5bd08dc9a0bf8c341b5769240026e367c478","channel":{"name":"mkbot","members_type":"team","topic_type":"chat","topic_name":"general"},"is_default_conv":true,"unread":false,"active_at":1589348381,"active_at_ms":1589348381358,"member_status":"active","creator_info":{"ctime":1551840458201,"username":"dxb"}},{"id":"0000d7cf1e6f51d75f9a354c2cb7c3bd30415f184bbb9eba0c57aa50827b7663","channel":{"name":"mkbot","members_type":"team","topic_type":"chat","topic_name":"test1"},"is_default_conv":false,"unread":true,"active_at":1589468203,"active_at_ms":1589468203686,"member_status":"active","creator_info":{"ctime":1551849049656,"username":"dxb"}},{"id":"0000d0cf70804671490e7f8f21c207a1ac6a8bc2ee05db804fb4531ab6c06f05","channel":{"name":"mkbot","members_type":"team","topic_type":"chat","topic_name":"test2"},"is_default_conv":false,"unread":true,"active_at":1589468118,"active_at_ms":1589468118254,"member_status":"active","creator_info":{"ctime":1551849050007,"username":"dxb"}},{"id":"000044e620fef1e84b623350faff06ebef7a0cd7e403ba81a1b35d311976b9f6","channel":{"name":"mkbot","members_type":"team","topic_type":"chat","topic_name":"test3"},"is_default_conv":false,"unread":true,"active_at":1589468117,"active_at_ms":1589468117094,"member_status":"active","creator_info":{"ctime":1551849050351,"username":"dxb"}},{"id":"0000a8dd5969f6bb414562278a5abf8f3bd80b39d7cdcf0d3df5045f05fbac77","channel":{"name":"mkbot","members_type":"team","topic_type":"chat","topic_name":"test4"},"is_default_conv":false,"unread":true,"active_at":1589468197,"active_at_ms":1589468197735,"member_status":"active","creator_info":{"ctime":1551849050729,"username":"dxb"}},{"id":"00004380e20bf4d56cf5e80a7435d594e07ebe043da93468c93c9bf0080f9ef5","channel":{"name":"mkbot","members_type":"team","topic_type":"chat","topic_name":"test5"},"is_default_conv":false,"unread":true,"active_at":1589468203,"active_at_ms":1589468203980,"member_status":"active","creator_info":{"ctime":1551849051084,"username":"dxb"}},{"id":"00003bd0aa429c33eee546f20efb76c9e0a9854b0ca18278300bcf6fc4c4fb93","channel":{"name":"mkbot","members_type":"team","topic_type":"chat","topic_name":"trivia"},"is_default_conv":false,"unread":false,"active_at":1589468113,"active_at_ms":1589468113074,"member_status":"active","creator_info":{"ctime":1580428008401,"username":"dxb"}}],"offline":false}}`
send = `{"result":{"message":"message sent","id":894,"ratelimits":[{"tank":"chat","capacity":9000,"reset":155,"gas":8991}]}}`
)
var jsonOut string
switch os.Getenv("GO_WANT_HELPER_CALLER") {
case "listconvsonname":
jsonOut = listconvsonname
case "send":
jsonOut = send
default:
jsonOut = ""
}
fmt.Fprintf(os.Stdout, jsonOut)
os.Exit(0)
}

View File

@ -20,6 +20,37 @@ type RunOptions struct {
FilterChannels []chat1.ChatChannel // Only subscribe to messages from specified channels
}
// KeybaseOpt configures a Keybase
type KeybaseOpt interface {
apply(kb *Keybase)
}
// SetExePath sets the path to the Keybase executable
func SetExePath(path string) KeybaseOpt {
return setExePath{path}
}
type setExePath struct {
path string
}
func (o setExePath) apply(kb *Keybase) {
kb.ExePath = o.path
}
// SetHomePath sets the path to the Keybase home directory
func SetHomePath(path string) KeybaseOpt {
return setHomePath{path}
}
type setHomePath struct {
path string
}
func (o setHomePath) apply(kb *Keybase) {
kb.HomePath = o.path
}
type subscriptionType struct {
Type string `json:"type"`
}
@ -83,6 +114,7 @@ type SendMessageOptions struct {
ReplyTo *chat1.MessageID `json:"reply_to,omitempty"`
ExplodingLifetime *ExplodingLifetime `json:"exploding_lifetime,omitempty"`
UnreadOnly bool `json:"unread_only,omitempty"`
NonBlock bool `json:"nonblock,omitempty"`
}
type sendMessageParams struct {
@ -207,6 +239,24 @@ func newListMembersArg(options ListMembersOptions) listMembersArg {
}
}
type listConvsOnNameParams struct {
Options chat1.ChatChannel
}
type listConvsOnNameArg struct {
Method string
Params listConvsOnNameParams
}
func newListConvsOnNameArg(channel chat1.ChatChannel) listConvsOnNameArg {
return listConvsOnNameArg{
Method: "listconvsonname",
Params: listConvsOnNameParams{
Options: channel,
},
}
}
// KVOptions holds a set of options to be passed to the KV methods
type KVOptions struct {
Team *string `json:"team"`
@ -954,7 +1004,8 @@ type userBlocks struct {
// Keybase holds basic information about the local Keybase executable
type Keybase struct {
Path string
HomePath string
ExePath string
Username string
LoggedIn bool
Version string