-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmds.go
432 lines (387 loc) · 11 KB
/
cmds.go
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
package main
import (
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"strings"
"github.com/bluesky-social/indigo/api"
comatproto "github.com/bluesky-social/indigo/api/atproto"
"github.com/bluesky-social/indigo/api/bsky"
cliutil "github.com/bluesky-social/indigo/cmd/gosky/util"
"github.com/bluesky-social/indigo/repo"
"github.com/bluesky-social/indigo/xrpc"
"github.com/ipfs/go-cid"
"github.com/polydawn/refmt/cbor"
rejson "github.com/polydawn/refmt/json"
"github.com/polydawn/refmt/shared"
"github.com/thepudds/bluesky-aux/appkey"
"github.com/urfave/cli/v2"
"golang.org/x/exp/slices"
)
// newXrpcClient returns an unauthenticated client
func newXrpcClient() (*xrpc.Client, error) {
xrpcc := &xrpc.Client{
Client: cliutil.NewHttpClient(),
Host: pdsServer,
Auth: nil,
}
return xrpcc, nil
}
// authenticate authenticates an xrpc.Client
func authenticate(xrpcc *xrpc.Client) error {
user, appKey, err := authFlags()
if err != nil {
return err // don't wrap this error
}
ses, err := comatproto.ServerCreateSession(context.TODO(), xrpcc, &comatproto.ServerCreateSession_Input{
Identifier: user,
Password: appKey,
})
if err != nil {
return fmt.Errorf("authenticate: %w", err)
}
// validate this is a app key, not master pw
err = appkey.Check(ses)
if err != nil {
return fmt.Errorf("authenticate: %w", err)
}
xrpcc.Auth = &xrpc.AuthInfo{
AccessJwt: ses.AccessJwt,
RefreshJwt: ses.RefreshJwt,
Handle: ses.Handle,
Did: ses.Did,
}
return nil
}
type resolvedUser struct {
handle string // should not include leading @. consumers add if needed.
did string // should be prefixed with "did"
}
func doListMutesCmd(c *cli.Context, xrpcc *xrpc.Client) error {
printHeader(c, "users my account has muted", nil)
resolvedUsers, err := listMutes(xrpcc)
if err != nil {
return err
}
printResolvedUsers(c, resolvedUsers)
return nil
}
func doMuteCmd(c *cli.Context, xrpcc *xrpc.Client, handles []string) error {
fmt.Println("muting...")
resolvedUsers, err := resolveHandles(xrpcc, trimAts(handles))
if err != nil {
return fmt.Errorf("muting: %w", err)
}
err = muteUsers(xrpcc, didsFromUsers(resolvedUsers))
if err != nil {
return err
}
return nil
}
func doMuteFromUserBlocksCmd(c *cli.Context, xrpcc *xrpc.Client, handles []string) error {
ctx := context.TODO()
fmt.Println("getting blocks set by the supplied users...")
resolvedUsers, err := resolveHandles(xrpcc, trimAts(handles))
if err != nil {
return fmt.Errorf("muting from user blocks: %w", err)
}
blockedUsers, err := listBlocks(ctx, xrpcc, resolvedUsers)
if err != nil {
return err
}
if len(blockedUsers) == 0 {
fmt.Println("no blocks found")
return nil
}
err = muteUsers(xrpcc, didsFromUsers(blockedUsers))
if err != nil {
return err
}
return nil
}
// TODO: dids should be usernames, probably with @ and error if @ missing.
func doListBlocksCmd(c *cli.Context, xrpcc *xrpc.Client, handles []string) error {
ctx := context.TODO()
printHeader(c, "users blocked", handles)
resolvedUsers, err := resolveHandles(xrpcc, trimAts(handles))
if err != nil {
return fmt.Errorf("list blocks: %w", err)
}
blockedUsers, err := listBlocks(ctx, xrpcc, resolvedUsers)
if err != nil {
return err
}
// Emit ~nicely formatted results.
printResolvedUsers(c, blockedUsers)
// Done!
if len(blockedUsers) == 0 {
fmt.Println("no blocked users found")
}
return nil
}
func listMutes(xrpcc *xrpc.Client) ([]resolvedUser, error) {
var resolvedUsers []resolvedUser
var cursor string
for {
mutes, err := bsky.GraphGetMutes(context.TODO(), xrpcc, cursor, 100)
if err != nil {
return nil, fmt.Errorf("list mutes: %w", err)
}
for _, f := range mutes.Mutes {
// TODO: consider flag to also include DisplayName
resolvedUsers = append(resolvedUsers, resolvedUser{handle: f.Handle, did: f.Did})
}
// fmt.Println("cursor:", cursor)
if mutes.Cursor == nil {
break
}
cursor = *mutes.Cursor
}
return resolvedUsers, nil
}
func resolveHandles(xrpcc *xrpc.Client, handles []string) ([]resolvedUser, error) {
ctx := context.TODO()
var result []resolvedUser
for _, handle := range handles {
out, err := comatproto.IdentityResolveHandle(ctx, xrpcc, handle)
// TODO: consider allowing partial results?
if err != nil {
return nil, fmt.Errorf("resolve handles: %v: %w", handle, err)
}
result = append(result, resolvedUser{handle: handle, did: out.Did})
}
return result, nil
}
func resolveDids(dids []string) ([]resolvedUser, error) {
ctx := context.TODO()
s := &api.PLCServer{ // TODO: probably reuse this?
Host: plcServer,
}
var result []resolvedUser
for _, did := range dids {
doc, err := s.GetDocument(ctx, did)
if err != nil {
return nil, err
}
if len(doc.AlsoKnownAs) == 0 {
// TODO: probably get all AlsoKnownAs?
continue
}
handle := doc.AlsoKnownAs[0]
// TODO: should we confirm "at://" is present?
handle = strings.TrimPrefix(handle, "at://")
result = append(result, resolvedUser{handle: handle, did: did})
}
return result, nil
}
func muteUsers(xrpcc *xrpc.Client, dids []string) error {
// don't mute users that are already muted. might be friendlier to the server?
alreadyMuted, err := listMutes(xrpcc)
if err != nil {
return fmt.Errorf("check for already muted users: %w", err)
}
alreadyMutedDids := didsFromUsers(alreadyMuted)
// TODO: we should subtract based on dids, not did & handle
notYetMuted := subtract(dids, alreadyMutedDids)
switch {
case len(notYetMuted) == 0:
fmt.Printf("all %d users already muted, nothing more to do\n", len(dids))
return nil
case len(dids)-len(notYetMuted) > 0:
fmt.Printf("%d of %d users already muted\n", len(dids)-len(notYetMuted), len(dids))
}
for _, did := range notYetMuted {
// fmt.Println("muting did:", u.did)
err := bsky.GraphMuteActor(context.TODO(),
xrpcc,
&bsky.GraphMuteActor_Input{Actor: did})
if err != nil {
return fmt.Errorf("failed to mute: %s: %w", did, err)
}
}
fmt.Printf("successfully muted %d users\n", len(notYetMuted))
return nil
}
func listBlocks(ctx context.Context, xrpcc *xrpc.Client, resolvedUsers []resolvedUser) (blockedUsers []resolvedUser, err error) {
seenDids := make(map[string]bool)
for _, u := range resolvedUsers {
var blockedDids []string
repob, err := comatproto.SyncGetRepo(ctx, xrpcc, u.did, "", "")
if err != nil {
return nil, fmt.Errorf("list blocks for %v: %w", u.did, err)
}
rr, err := repo.ReadRepoFromCar(ctx, bytes.NewReader(repob))
if err != nil {
return nil, fmt.Errorf("list blocks for %v: %w", u.did, err)
}
// get the blocks
collection := "app.bsky.graph.block"
err = rr.ForEach(context.TODO(), collection, func(k string, v cid.Cid) error {
if !strings.HasPrefix(k, collection) {
return repo.ErrDoneIterating
}
// fmt.Print("k: ", k, " ")
b, err := rr.Blockstore().Get(ctx, v)
if err != nil {
return fmt.Errorf("list blocks for %v: %w", u.did, err)
}
// TODO: probably rookie mistake, but for now, convert from cbor to json
// and pull what we need out of the json
convb, err := cborToJson(b.RawData())
if err != nil {
return fmt.Errorf("list blocks for %v: %w", u.did, err)
}
// fmt.Println(string(convb))
var data map[string]any
err = json.Unmarshal(convb, &data)
if err != nil {
return fmt.Errorf("list blocks for %v: %w", u.did, err)
}
did, ok := data["subject"].(string)
if !ok {
return fmt.Errorf("unexpected blocked subject %T: %v", data["subject"], data["subject"])
}
// dedup and store
if !seenDids[did] {
// TODO: add a test that sees duplicate dids
blockedDids = append(blockedDids, did)
seenDids[did] = true
}
return nil
})
// Done getting the blocks for this user.
// TODO: consider emitting partial results when error (here, below)?
if err != nil {
return nil, fmt.Errorf("list blocks for %v: %w", u.did, err)
}
// TODO: resolveDids might be more expensive than some other things?
resolvedUsers, err := resolveDids(blockedDids)
if err != nil {
return nil, fmt.Errorf("list blocks for %v: %w", u.did, err)
}
blockedUsers = append(blockedUsers, resolvedUsers...)
}
return blockedUsers, nil
}
func didsFromUsers(users []resolvedUser) (dids []string) {
for _, u := range users {
dids = append(dids, u.did)
}
return dids
}
func trimAts(handles []string) []string {
var res []string
for _, h := range handles {
res = append(res, strings.TrimPrefix(h, "@"))
}
return res
}
func printHeader(c *cli.Context, header string, handles []string) {
if !c.Bool("verbose") {
// DIDs are what make the output useful for sharing and re-use by gomoderate (currently, anyway).
// No header if we include DIDs -- keep it clean in case this output is stored to file and reused.
// TODO: maybe no header for --oneline too? It's non-default, and they did ask for one line...
msgHandles := slices.Clone(handles)
if len(msgHandles) > 2 {
msgHandles = append(msgHandles[:2], "...")
}
by := " by "
if len(handles) == 0 {
by = ""
}
fmt.Printf("\n%s%s%s", header, by, strings.Join(msgHandles, ", "))
}
// Finish up the header.
switch {
case c.Bool("oneline"):
fmt.Print(":\n\n")
case !c.Bool("verbose"):
fmt.Print("\n", strings.Repeat("-", 60), "\n")
case c.Bool("verbose"):
// Keep it clean.
}
}
func printResolvedUsers(c *cli.Context, resolvedUsers []resolvedUser) {
for i, u := range resolvedUsers {
switch {
case c.Bool("oneline"):
if i > 0 {
fmt.Print(" ")
}
fmt.Print("@" + u.handle)
case c.Bool("verbose"):
// TODO: display name?
fmt.Println(u.did, "@"+u.handle)
default:
fmt.Println("@" + u.handle)
}
}
}
func parseUserList(r io.Reader) (dids []string, err error) {
scanner := bufio.NewScanner(r)
for scanner.Scan() {
line := scanner.Text()
if strings.TrimSpace(line) == "" {
continue
}
var did string
for i := range line {
if line[i] == ' ' || line[i] == '\t' {
did = line[:i]
break
}
}
if did == "" {
did = line
}
if !strings.HasPrefix(did, "did:plc:") {
return nil, fmt.Errorf("bad DID in go-mod-user-list on line: %s", line)
}
dids = append(dids, did)
}
if err := scanner.Err(); err != nil {
return nil, err
}
return dids, nil
}
// borrowed from indigo/gosky
func cborToJson(data []byte) ([]byte, error) {
defer func() {
if r := recover(); r != nil {
fmt.Println("panic: ", r)
fmt.Printf("bad blob: %x\n", data)
}
}()
buf := new(bytes.Buffer)
enc := rejson.NewEncoder(buf, rejson.EncodeOptions{})
dec := cbor.NewDecoder(cbor.DecodeOptions{}, bytes.NewReader(data))
err := shared.TokenPump{TokenSource: dec, TokenSink: enc}.Run()
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// subtract does an order preserving set subtraction,
// removing from a any common elements in b.
func subtract[T comparable](a, b []T) []T {
res := []T{}
inB := map[T]bool{}
for _, v := range b {
inB[v] = true
}
for _, v := range a {
if !inB[v] {
res = append(res, v)
}
}
return res
}
// func stringOrNone(s *string) string {
// if s == nil {
// return "none"
// }
// return *s
// }