-
Notifications
You must be signed in to change notification settings - Fork 42
/
mailbox.go
296 lines (245 loc) · 7.31 KB
/
mailbox.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
package textile
import (
"context"
"encoding/json"
"errors"
"os"
"os/user"
"path/filepath"
"github.com/FleekHQ/space-daemon/config"
"github.com/FleekHQ/space-daemon/core/space/domain"
"github.com/FleekHQ/space-daemon/core/textile/model"
"github.com/FleekHQ/space-daemon/log"
crypto "github.com/libp2p/go-libp2p-crypto"
"github.com/textileio/go-threads/core/thread"
"github.com/textileio/textile/v2/api/users/client"
"github.com/textileio/textile/v2/cmd"
mail "github.com/textileio/textile/v2/mail/local"
)
type GrpcMailboxNotifier interface {
SendNotificationEvent(notif *domain.Notification)
}
const mailboxSetupFlagStoreKey = "mailboxSetupFlag"
type UsersClient interface {
ListInboxMessages(ctx context.Context, opts ...client.ListOption) ([]client.Message, error)
SendMessage(ctx context.Context, from thread.Identity, to thread.PubKey, body []byte) (msg client.Message, err error)
SetupMailbox(ctx context.Context) (mailbox thread.ID, err error)
}
type Mailbox interface {
ListInboxMessages(ctx context.Context, opts ...client.ListOption) ([]client.Message, error)
SendMessage(ctx context.Context, to thread.PubKey, body []byte) (msg client.Message, err error)
WatchInbox(ctx context.Context, mevents chan<- mail.MailboxEvent, offline bool) (<-chan cmd.WatchState, error)
Identity() thread.Identity
}
func (tc *textileClient) parseMessage(ctx context.Context, msgs []client.Message) ([]*domain.Notification, error) {
ns := make([]*domain.Notification, 0)
ids := []string{}
for _, n := range msgs {
ids = append(ids, n.ID)
}
fileschemas, err := tc.GetModel().FindReceivedFilesByIds(ctx, ids)
if err != nil {
return nil, err
}
// make map so we dont have to iterate each time
fsmap := make(map[string]*model.ReceivedFileSchema)
for _, fs := range fileschemas {
fsmap[fs.InvitationId] = fs
}
for _, msg := range msgs {
p, err := msg.Open(ctx, tc.mb.Identity())
if err != nil {
return nil, err
}
b := &domain.MessageBody{}
err = json.Unmarshal(p, b)
if err != nil {
log.Error("Error parsing message into MessageBody type", err)
// returning generic notification since body was not able to be parsed
n := &domain.Notification{
ID: msg.ID,
Body: string(p),
CreatedAt: msg.CreatedAt.Unix(),
ReadAt: msg.ReadAt.Unix(),
}
ns = append(ns, n)
continue
}
n := &domain.Notification{
ID: msg.ID,
Body: string(p),
NotificationType: (*b).Type,
CreatedAt: msg.CreatedAt.Unix(),
ReadAt: msg.ReadAt.Unix(),
}
switch (*b).Type {
case domain.INVITATION:
i := &domain.Invitation{}
err := json.Unmarshal((*b).Body, i)
if err != nil {
return nil, err
}
if fsmap[msg.ID] == nil {
i.Status = domain.PENDING
} else {
if fsmap[msg.ID].Accepted {
i.Status = domain.ACCEPTED
} else {
i.Status = domain.REJECTED
}
}
i.InvitationID = msg.ID
n.InvitationValue = *i
n.RelatedObject = *i
case domain.USAGEALERT:
u := &domain.UsageAlert{}
err := json.Unmarshal((*b).Body, u)
if err != nil {
return nil, err
}
n.UsageAlertValue = *u
n.RelatedObject = *u
default:
}
ns = append(ns, n)
}
return ns, nil
}
func (tc *textileClient) SendMessage(ctx context.Context, recipient crypto.PubKey, body []byte) (*client.Message, error) {
if err := tc.requiresHubConnection(); err != nil {
return nil, err
}
var err error
ctx, err = tc.getHubCtx(ctx)
if err != nil {
return nil, err
}
msg, err := tc.mb.SendMessage(ctx, thread.NewLibp2pPubKey(recipient), body)
if err != nil {
return nil, err
}
return &msg, nil
}
func (tc *textileClient) GetMailAsNotifications(ctx context.Context, seek string, limit int) ([]*domain.Notification, error) {
if err := tc.requiresHubConnection(); err != nil {
return nil, err
}
var err error
ctx, err = tc.getHubCtx(ctx)
if err != nil {
return nil, err
}
notifs, err := tc.mb.ListInboxMessages(ctx, client.WithSeek(seek), client.WithLimit(limit))
if err != nil {
return nil, err
}
ns, err := tc.parseMessage(ctx, notifs)
if err != nil {
return nil, err
}
return ns, nil
}
type handleMessage func(context.Context, interface{}) error
func (tc *textileClient) listenForMessages(ctx context.Context) error {
if tc.mbNotifier == nil {
return errors.New("no mailbox notifier, run AttachMailboxNotifier first")
}
log.Info("Starting to listen for mailbox messages")
var err error
ctx, err = tc.getHubCtx(ctx)
if err != nil {
return err
}
// Handle mailbox events as they arrive
go func() {
for e := range tc.mailEvents {
switch e.Type {
case mail.NewMessage:
// handle new message
log.Info("Received mail: " + e.MessageID.String())
// need to fetch the message again because the event
// payload doesn't have the full deets, will remove
// once its fixed on txl end
msg, err := tc.mb.ListInboxMessages(ctx, client.WithSeek(e.MessageID.String()), client.WithLimit(1))
if err != nil {
return
}
p, err := tc.parseMessage(ctx, msg)
if err != nil {
log.Error("Unable to parse incoming message: ", err)
}
tc.mbNotifier.SendNotificationEvent(p[0])
case mail.MessageRead:
// handle message read (inbox only)
case mail.MessageDeleted:
// handle message deleted
}
}
}()
// Start watching (the third param indicates we want to keep watching when offline)
go func() {
state, err := tc.mb.WatchInbox(ctx, tc.mailEvents, true)
if err != nil {
log.Error("Unable to watch mailbox, ", err)
return
}
// TODO: handle connectivity state if needed
for s := range state {
log.Info("received inbox watch state: " + s.State.String())
}
}()
return nil
}
// Attachs a handler for mailbox notification events
func (tc *textileClient) AttachMailboxNotifier(notif GrpcMailboxNotifier) {
tc.mbNotifier = notif
}
func (tc *textileClient) createMailBox(ctx context.Context, maillib *mail.Mail, mbpath string) (*mail.Mailbox, error) {
// create
priv, _, err := tc.kc.GetStoredKeyPairInLibP2PFormat()
if err != nil {
return nil, err
}
id := thread.NewLibp2pIdentity(priv)
mailbox, err := maillib.NewMailbox(ctx, mail.Config{
Path: mbpath,
Identity: id,
APIKey: tc.cfg.GetString(config.TextileUserKey, ""),
APISecret: tc.cfg.GetString(config.TextileUserSecret, ""),
})
if err != nil {
return nil, err
}
tc.store.Set([]byte(mailboxSetupFlagStoreKey), []byte("true"))
return mailbox, nil
}
func getMailboxPath() string {
usr, _ := user.Current()
mbpath := filepath.Join(usr.HomeDir, ".fleek-space/textile/mail")
return mbpath
}
func (tc *textileClient) setupOrCreateMailBox(ctx context.Context) (*mail.Mailbox, error) {
maillib := mail.NewMail(cmd.NewClients(tc.cfg.GetString(config.TextileHubTarget, ""), true), mail.DefaultConfConfig())
mbpath := getMailboxPath()
var mailbox *mail.Mailbox
dbid, err := tc.store.Get([]byte(mailboxSetupFlagStoreKey))
if err == nil && len(dbid) > 0 {
// restore
mailbox, err = maillib.GetLocalMailbox(ctx, mbpath)
if err != nil {
return nil, err
}
} else {
mailbox, err = tc.createMailBox(ctx, maillib, mbpath)
if err != nil {
return nil, err
}
}
mid := mailbox.Identity()
log.Info("Mailbox identity: " + mid.GetPublic().String())
return mailbox, nil
}
func (tc *textileClient) clearLocalMailbox() error {
mbpath := getMailboxPath()
return os.RemoveAll(mbpath)
}