1package engine
2
3import (
4	"fmt"
5	"strings"
6
7	"github.com/keybase/client/go/libkb"
8	keybase1 "github.com/keybase/client/go/protocol/keybase1"
9)
10
11type UserBlocksGet struct {
12	keybase1.GetUserBlocksArg
13	libkb.Contextified
14
15	blocks []keybase1.UserBlock
16}
17
18func NewUserBlocksGet(g *libkb.GlobalContext, args keybase1.GetUserBlocksArg) *UserBlocksGet {
19	return &UserBlocksGet{
20		GetUserBlocksArg: args,
21		Contextified:     libkb.NewContextified(g),
22	}
23}
24
25// Name is the unique engine name.
26func (e *UserBlocksGet) Name() string {
27	return "UserBlocksGet"
28}
29
30// GetPrereqs returns the engine prereqs.
31func (e *UserBlocksGet) Prereqs() Prereqs {
32	return Prereqs{}
33}
34
35// RequiredUIs returns the required UIs.
36func (e *UserBlocksGet) RequiredUIs() []libkb.UIKind {
37	return []libkb.UIKind{}
38}
39
40// SubConsumers returns the other UI consumers for this engine.
41func (e *UserBlocksGet) SubConsumers() []libkb.UIConsumer {
42	return nil
43}
44
45// Run starts the engine.
46func (e *UserBlocksGet) Run(mctx libkb.MetaContext) (err error) {
47	var usernameLog string
48	if len(e.Usernames) < 5 {
49		usernameLog = strings.Join(e.Usernames, ",")
50	} else {
51		usernameLog = fmt.Sprintf("%s... %d total", strings.Join(e.Usernames[:5], ","), len(e.Usernames))
52	}
53	defer mctx.Trace(
54		fmt.Sprintf("UserBlocksGet#Run(%s)", usernameLog),
55		&err)()
56
57	httpArgs := libkb.HTTPArgs{}
58	if len(e.Usernames) > 0 {
59		uids := make([]keybase1.UID, len(e.Usernames))
60		for i, v := range e.Usernames {
61			uids[i] = libkb.GetUIDByUsername(e.G(), v)
62		}
63		httpArgs["uids"] = libkb.S{Val: libkb.UidsToString(uids)}
64	}
65
66	apiArg := libkb.APIArg{
67		Endpoint:    "user/get_blocks",
68		Args:        httpArgs,
69		SessionType: libkb.APISessionTypeREQUIRED,
70	}
71
72	type getBlockResult struct {
73		libkb.AppStatusEmbed
74		Blocks []struct {
75			BlockUID      keybase1.UID   `json:"block_uid"`
76			BlockUsername string         `json:"block_username"`
77			CTime         *keybase1.Time `json:"ctime,omitempty"`
78			MTime         *keybase1.Time `json:"mtime,omitempty"`
79			Chat          bool           `json:"chat"`
80			Follow        bool           `json:"follow"`
81		} `json:"blocks"`
82	}
83
84	var apiRes getBlockResult
85
86	err = mctx.G().API.GetDecode(mctx, apiArg, &apiRes)
87	if err != nil {
88		return err
89	}
90
91	e.blocks = make([]keybase1.UserBlock, len(apiRes.Blocks))
92	for i, v := range apiRes.Blocks {
93		if err := libkb.AssertUsernameMatchesUID(e.G(), v.BlockUID, v.BlockUsername); err != nil {
94			return err
95		}
96		e.blocks[i] = keybase1.UserBlock{
97			Username:      v.BlockUsername,
98			ChatBlocked:   v.Chat,
99			FollowBlocked: v.Follow,
100			CreateTime:    v.CTime,
101			ModifyTime:    v.MTime,
102		}
103	}
104
105	return nil
106}
107
108func (e *UserBlocksGet) Blocks() []keybase1.UserBlock {
109	return e.blocks
110}
111