~bfiedler/go-threema

ref: b9d47ab3d8b6d8c6f4cf9a11dc2da55622ea45fd go-threema/cmd/tcli/main.go -rw-r--r-- 6.4 KiB
b9d47ab3 — Ben Fiedler tcli: Fix grammar 1 year, 8 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
// Provides a simple cli to the gateway functions.
package main

import (
	"encoding/hex"
	"errors"
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"strings"

	"github.com/spf13/pflag"

	"git.sr.ht/~bfiedler/go-threema/client"
)

var (
	id         = pflag.String("id", os.Getenv("THREEMA_CLI_ID"), "Threema ID to use, required. Can also be set using the environment variable THREEMA_CLI_ID")
	apiSecret  = pflag.String("api-secret", os.Getenv("THREEMA_CLI_API_SECRET"), "API secret, required. Can also be set using the environment variable THREEMA_CLI_API_SECRET")
	mode       = pflag.String("mode", os.Getenv("THREEMA_CLI_MODE"), "Mode to use (simple/e2e). Defaults to simple, only relevant for sending messages. Can also be set using the environment variable THREEMA_CLI_MODE")
	privateKey = pflag.String("private-key", os.Getenv("THREEMA_CLI_PRIVATE_KEY"), "Hex-encoded private key to derive shared keys for sent messages. Required if mode is e2e. Can also be set using the environment variable THREEMA_CLI_PRIVATE_KEY")

	email = pflag.BoolP("email", "e", false, "Specify recipient by E-Mail address, mutually exclusive with -p")
	phone = pflag.BoolP("phone", "p", false, "Specify recipient by phone number, mutually exclusive with -e")

	pk client.PrivateKey
)

func usage() {
	fmt.Fprintf(os.Stderr, "Usage: %s [flags] command\n", os.Args[0])
	fmt.Fprintf(os.Stderr, "Flags\n")
	pflag.PrintDefaults()
	fmt.Fprintf(os.Stderr, "Command list\n")
	fmt.Fprintf(os.Stderr, "  credits                   Prints the remaining credits for this account\n")
	fmt.Fprintf(os.Stderr, "  qr                        Displays the client's public key in Threema-compatible QR-form (E2E only). Requires qrencode to be installed.\n")
	fmt.Fprintf(os.Stderr, "  lookup <recipient>        Looks up recipient's Threema ID\n")
	fmt.Fprintf(os.Stderr, "  send   <recipient>        Reads a message from stdin and sends it to <recipient>\n")
	fmt.Fprintf(os.Stderr, "By default the recipient is addressed using his Threema ID, this can be controlled using the -p and -e flags.\n")
}

type command interface {
	run(c client.Client) error
}

func main() {
	pflag.Parse()
	checkFlags()

	cmd, err := parseCommand()
	if err != nil {
		log.Printf("error parsing command: %v", err)
		usage()
		return
	}

	var c client.Client
	switch *mode {
	case "simple":
		c, err = client.NewSimpleClient(*id, *apiSecret)
	case "e2e":
		c, err = client.NewE2EClient(*id, *apiSecret, pk)
	}
	if err != nil {
		log.Fatalf("could not create client: %v", err)
	}

	err = cmd.run(c)
	if err != nil {
		log.Fatalf("error running command: %v", err)
	}
}

func checkFlags() {
	fatal := false
	if *id == "" {
		log.Printf("flag id missing, this is required")
		fatal = true
	}

	if *apiSecret == "" {
		log.Printf("flag apiSecret missing, this is required")
		fatal = true
	}

	if *mode == "" {
		log.Printf("mode missing, defaulting to 'simple'")
		*mode = "simple"
	}

	switch *mode {
	case "simple":
		// intentionally left blank
	case "e2e":
		if *privateKey == "" {
			log.Printf("private key missing, this is requried for mode 'e2e'")
			fatal = true
		} else {
			decodedLen := hex.DecodedLen(len(*privateKey))
			if decodedLen != len(pk) {
				log.Fatalf("private key length error, expected: %v, got: %v", len(pk), decodedLen)
			}

			_, err := hex.Decode(pk[:], []byte(*privateKey))
			if err != nil {
				log.Fatalf("could not decode private key: %v", err)
			}
		}
	default:
		log.Printf("unknown mode, valid modes are 'simple' and 'e2e': %v", *mode)
		fatal = true
	}

	if *email && *phone {
		log.Printf("only one of -e and -p must be provided")
		fatal = true
	}

	if fatal {
		log.Printf("fatal configuration error")
		usage()
		os.Exit(1)
	}
}

func parseCommand() (command, error) {
	if pflag.NArg() == 0 {
		return nil, errors.New("expected command, got none")
	}

	args := pflag.Args()
	c := args[0]
	expArgs, err := expectedArgs(c)
	if err != nil {
		return nil, err
	}

	if expArgs != pflag.NArg() {
		return nil, fmt.Errorf("unexpected number of arguments for '%s', expected: %v, got: %v", c, expArgs, pflag.NArg())
	}

	var cmd command
	switch c {
	case "credits":
		cmd = &creditsCommand{}
	case "qr":
		cmd = &qrCommand{}
	case "lookup":
		cmd = &lookupCommand{arg: args[1]}
	case "send":
		cmd = &sendCommand{recipient: args[1]}
	}
	return cmd, nil
}

func expectedArgs(command string) (int, error) {
	switch command {
	case "credits":
		return 1, nil
	case "qr":
		return 1, nil
	case "lookup":
		return 2, nil
	case "send":
		return 2, nil
	default:
		return 0, fmt.Errorf("unknown command '%s'", command)
	}
}

type creditsCommand struct{}

type qrCommand struct{}

type lookupCommand struct {
	arg string
}

type sendCommand struct {
	recipient string
}

func (creditsCommand) run(c client.Client) error {
	n, err := c.GetRemainingCredits()
	if err != nil {
		return err
	}
	fmt.Printf("remaining credits: %d\n", n)
	return nil
}

func (qrCommand) run(c client.Client) error {
	e2eClient, ok := c.(*client.E2EClient)
	if !ok {
		return errors.New("The 'qr' command only makes sense for E2E mode, as only an E2E client has a private key.")
	}

	qrencode, err := exec.LookPath("qrencode")
	if err != nil {
		return errors.New("The shell command 'qrencode' ist required for this to work.")
	}

	pubKey := e2eClient.PublicKey()
	// 3mid == Threema ID I guess?
	inp := fmt.Sprintf("3mid:%s,%s", c.ID(), hex.EncodeToString(pubKey[:]))
	fmt.Println(inp)

	cmd := exec.Command(qrencode, "-t", "ANSI")
	cmd.Stdin = strings.NewReader(inp)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	return cmd.Run()
}

func (cmd lookupCommand) run(c client.Client) error {
	var id client.ThreemaID
	var err error
	if *email {
		id, err = c.LookupIDByEmailHash(cmd.arg)
	} else if *phone {
		id, err = c.LookupIDByPhoneHash(cmd.arg)
	} else {
		fmt.Printf("recipient is already a Threema ID, not looking up")
		return nil
	}

	if err == client.ErrNotFound {
		fmt.Printf("no Threema ID associated with %v", cmd.arg)
	} else if err == nil {
		fmt.Printf("Threema ID for '%s' is %s", cmd.arg, id)
	}
	return err
}

func (cmd sendCommand) run(c client.Client) error {
	var msg []byte
	fmt.Fprintf(os.Stderr, "reading message from stdin\n")

	msg, err := ioutil.ReadAll(os.Stdin)
	if err != nil {
		log.Fatalf("could not read message: %v", err)
	}

	if *email {
		err = c.SendTextMessageToEmail(cmd.recipient, string(msg))
	} else if *phone {
		err = c.SendTextMessageToPhone(cmd.recipient, string(msg))
	} else {
		err = c.SendTextMessage(cmd.recipient, string(msg))
	}
	return err
}