1// Copyright 2015 Keybase, Inc. All rights reserved. Use of
2// this source code is governed by the included BSD license.
3
4package libkb
5
6import (
7	"path"
8
9	keybase1 "github.com/keybase/client/go/protocol/keybase1"
10)
11
12// InviteArg contains optional invitation arguments.
13type InviteArg struct {
14	Message    string
15	NoteToSelf string
16}
17
18type Invitation struct {
19	ID        string
20	ShortCode string
21	Throttled bool
22}
23
24func (i Invitation) Link() string {
25	if i.Throttled {
26		return ""
27	}
28	return path.Join(CanonicalHost, "inv", i.ID[0:10])
29}
30
31func (i InviteArg) ToHTTPArgs() HTTPArgs {
32	return HTTPArgs{
33		"invitation_message": S{Val: i.Message},
34		"note_to_self":       S{Val: i.NoteToSelf},
35	}
36}
37
38func SendInvitation(mctx MetaContext, email string, arg InviteArg) (*Invitation, error) {
39	hargs := arg.ToHTTPArgs()
40	hargs["email"] = S{Val: email}
41	return callSendInvitation(mctx, hargs)
42}
43
44func GenerateInvitationCode(mctx MetaContext, arg InviteArg) (*Invitation, error) {
45	return callSendInvitation(mctx, arg.ToHTTPArgs())
46}
47
48func GenerateInvitationCodeForAssertion(mctx MetaContext, assertion keybase1.SocialAssertion, arg InviteArg) (*Invitation, error) {
49	hargs := arg.ToHTTPArgs()
50	hargs["assertion"] = S{Val: assertion.String()}
51	return callSendInvitation(mctx, hargs)
52}
53
54func callSendInvitation(mctx MetaContext, params HTTPArgs) (*Invitation, error) {
55	arg := APIArg{
56		Endpoint:       "send_invitation",
57		SessionType:    APISessionTypeREQUIRED,
58		Args:           params,
59		AppStatusCodes: []int{SCOk, SCThrottleControl},
60	}
61	res, err := mctx.G().API.Post(mctx, arg)
62	if err != nil {
63		return nil, err
64	}
65
66	var inv Invitation
67
68	if res.AppStatus.Code == SCThrottleControl {
69		mctx.Debug("send_invitation returned SCThrottleControl: user is out of invites")
70		inv.Throttled = true
71		return &inv, nil
72	}
73
74	inv.ID, err = res.Body.AtKey("invitation_id").GetString()
75	if err != nil {
76		return nil, err
77	}
78	inv.ShortCode, err = res.Body.AtKey("short_code").GetString()
79	if err != nil {
80		return nil, err
81	}
82	return &inv, nil
83}
84