Debian Codegraph @

server/backend/api.go

raw
1 package backend
2
3 import (
4 "encoding/base64"
5 "errors"
6 "fmt"
7 "strings"
8
9 "github.com/ProtonMail/gluon/rfc822"
10 "github.com/ProtonMail/gopenpgp/v2/crypto"
11 "github.com/bradenaw/juniper/xslices"
12 "github.com/henrybear327/go-proton-api"
13 "golang.org/x/exp/maps"
14 "golang.org/x/exp/slices"
15 )
16
17 func (b *Backend) GetUser(userID string) (proton.User, error) {
18 return withAcc(b, userID, func(acc *account) (proton.User, error) {
19 return acc.toUser(), nil
20 })
21 }
22
23 func (b *Backend) GetKeySalts(userID string) ([]proton.Salt, error) {
24 return withAcc(b, userID, func(acc *account) ([]proton.Salt, error) {
25 return xslices.Map(acc.keys, func(key key) proton.Salt {
26 return proton.Salt{
27 ID: key.keyID,
28 KeySalt: base64.StdEncoding.EncodeToString(acc.salt),
29 }
30 }), nil
31 })
32 }
33
34 func (b *Backend) GetMailSettings(userID string) (proton.MailSettings, error) {
35 return withAcc(b, userID, func(acc *account) (proton.MailSettings, error) {
36 return acc.mailSettings.toMailSettings(), nil
37 })
38 }
39
40 func (b *Backend) SetMailSettingsAttachPublicKey(userID string, attach bool) (proton.MailSettings, error) {
41 return withAcc(b, userID, func(acc *account) (proton.MailSettings, error) {
42 acc.mailSettings.attachPubKey = attach
43 return acc.mailSettings.toMailSettings(), nil
44 })
45 }
46
47 func (b *Backend) GetUserSettings(userID string) (proton.UserSettings, error) {
48 return withAcc(b, userID, func(acc *account) (proton.UserSettings, error) {
49 return acc.userSettings, nil
50 })
51 }
52
53 func (b *Backend) SetUserSettingsTelemetry(userID string, telemetry proton.SettingsBool) (proton.UserSettings, error) {
54 return withAcc(b, userID, func(acc *account) (proton.UserSettings, error) {
55 if telemetry != proton.SettingDisabled && telemetry != proton.SettingEnabled {
56 return proton.UserSettings{}, errors.New("bad value")
57 }
58 acc.userSettings.Telemetry = telemetry
59
60 updateID, err := b.newUpdate(&userSettingsUpdate{settings: acc.userSettings})
61 if err != nil {
62 return acc.userSettings, err
63 }
64
65 acc.updateIDs = append(acc.updateIDs, updateID)
66
67 return acc.userSettings, nil
68 })
69 }
70
71 func (b *Backend) SetUserSettingsCrashReports(userID string, crashReports proton.SettingsBool) (proton.UserSettings, error) {
72 return withAcc(b, userID, func(acc *account) (proton.UserSettings, error) {
73 if crashReports != proton.SettingDisabled && crashReports != proton.SettingEnabled {
74 return proton.UserSettings{}, errors.New("bad value")
75 }
76 acc.userSettings.CrashReports = crashReports
77
78 updateID, err := b.newUpdate(&userSettingsUpdate{settings: acc.userSettings})
79 if err != nil {
80 return acc.userSettings, err
81 }
82
83 acc.updateIDs = append(acc.updateIDs, updateID)
84
85 return acc.userSettings, nil
86 })
87 }
88
89 func (b *Backend) GetAddressID(email string) (string, error) {
90 return withAccEmail(b, email, func(acc *account) (string, error) {
91 addr, ok := acc.getAddr(email)
92 if !ok {
93 return "", fmt.Errorf("no such address: %s", email)
94 }
95
96 return addr.addrID, nil
97 })
98 }
99
100 func (b *Backend) GetAddress(userID, addrID string) (proton.Address, error) {
101 return withAcc(b, userID, func(acc *account) (proton.Address, error) {
102 if addr, ok := acc.addresses[addrID]; ok {
103 return addr.toAddress(), nil
104 }
105
106 return proton.Address{}, errors.New("no such address")
107 })
108 }
109
110 func (b *Backend) GetAddresses(userID string) ([]proton.Address, error) {
111 return withAcc(b, userID, func(acc *account) ([]proton.Address, error) {
112 return xslices.Map(maps.Values(acc.addresses), func(add *address) proton.Address {
113 return add.toAddress()
114 }), nil
115 })
116 }
117
118 func (b *Backend) EnableAddress(userID, addrID string) error {
119 return b.withAcc(userID, func(acc *account) error {
120 acc.addresses[addrID].status = proton.AddressStatusEnabled
121
122 updateID, err := b.newUpdate(&addressUpdated{addressID: addrID})
123 if err != nil {
124 return err
125 }
126
127 acc.updateIDs = append(acc.updateIDs, updateID)
128
129 return nil
130 })
131 }
132
133 func (b *Backend) DisableAddress(userID, addrID string) error {
134 return b.withAcc(userID, func(acc *account) error {
135 acc.addresses[addrID].status = proton.AddressStatusDisabled
136
137 updateID, err := b.newUpdate(&addressUpdated{addressID: addrID})
138 if err != nil {
139 return err
140 }
141
142 acc.updateIDs = append(acc.updateIDs, updateID)
143
144 return nil
145 })
146 }
147
148 func (b *Backend) DeleteAddress(userID, addrID string) error {
149 return b.withAcc(userID, func(acc *account) error {
150 if acc.addresses[addrID].status != proton.AddressStatusDisabled {
151 return errors.New("address is not disabled")
152 }
153
154 delete(acc.addresses, addrID)
155
156 updateID, err := b.newUpdate(&addressDeleted{addressID: addrID})
157 if err != nil {
158 return err
159 }
160
161 acc.updateIDs = append(acc.updateIDs, updateID)
162
163 return nil
164 })
165 }
166
167 func (b *Backend) SetAddressOrder(userID string, addrIDs []string) error {
168 return b.withAcc(userID, func(acc *account) error {
169 for i, addrID := range addrIDs {
170 if add, ok := acc.addresses[addrID]; ok {
171 add.order = i + 1
172 } else {
173 return fmt.Errorf("no such address: %s", addrID)
174 }
175 }
176
177 return nil
178 })
179 }
180
181 func (b *Backend) HasLabel(userID, labelName string) (string, bool, error) {
182 labels, err := b.GetLabels(userID)
183 if err != nil {
184 return "", false, err
185 }
186
187 for _, label := range labels {
188 if label.Name == labelName {
189 return label.ID, true, nil
190 }
191 }
192
193 return "", false, nil
194 }
195
196 func (b *Backend) GetLabel(userID, labelID string) (proton.Label, error) {
197 labels, err := b.GetLabels(userID)
198 if err != nil {
199 return proton.Label{}, err
200 }
201
202 for _, label := range labels {
203 if label.ID == labelID {
204 return label, nil
205 }
206 }
207
208 return proton.Label{}, fmt.Errorf("no such label: %s", labelID)
209 }
210
211 func (b *Backend) GetLabels(userID string, types ...proton.LabelType) ([]proton.Label, error) {
212 return withAcc(b, userID, func(acc *account) ([]proton.Label, error) {
213 return withLabels(b, func(labels map[string]*label) ([]proton.Label, error) {
214 res := xslices.Map(acc.labelIDs, func(labelID string) proton.Label {
215 return labels[labelID].toLabel(labels)
216 })
217
218 for labelName, labelID := range map[string]string{
219 "Inbox": proton.InboxLabel,
220 "AllDrafts": proton.AllDraftsLabel,
221 "AllSent": proton.AllSentLabel,
222 "Trash": proton.TrashLabel,
223 "Spam": proton.SpamLabel,
224 "All Mail": proton.AllMailLabel,
225 "Archive": proton.ArchiveLabel,
226 "Sent": proton.SentLabel,
227 "Drafts": proton.DraftsLabel,
228 "Outbox": proton.OutboxLabel,
229 "Starred": proton.StarredLabel,
230 "Scheduled": proton.AllScheduledLabel,
231 } {
232 res = append(res, proton.Label{
233 ID: labelID,
234 Name: labelName,
235 Path: []string{labelName},
236 Type: proton.LabelTypeSystem,
237 })
238 }
239
240 if len(types) > 0 {
241 res = xslices.Filter(res, func(label proton.Label) bool {
242 return slices.Contains(types, label.Type)
243 })
244 }
245
246 return res, nil
247 })
248 })
249 }
250
251 func (b *Backend) CreateLabel(userID, labelName, parentID string, labelType proton.LabelType) (proton.Label, error) {
252 return withAcc(b, userID, func(acc *account) (proton.Label, error) {
253 return withLabels(b, func(labels map[string]*label) (proton.Label, error) {
254 if parentID != "" {
255 if labelType != proton.LabelTypeFolder {
256 return proton.Label{}, fmt.Errorf("parentID can only be set for folders")
257 }
258
259 if _, ok := labels[parentID]; !ok {
260 return proton.Label{}, fmt.Errorf("no such parent label: %s", parentID)
261 }
262 }
263
264 label := newLabel(labelName, parentID, labelType)
265
266 labels[label.labelID] = label
267
268 updateID, err := b.newUpdate(&labelCreated{labelID: label.labelID})
269 if err != nil {
270 return proton.Label{}, err
271 }
272
273 acc.labelIDs = append(acc.labelIDs, label.labelID)
274 acc.updateIDs = append(acc.updateIDs, updateID)
275
276 return label.toLabel(labels), nil
277 })
278 })
279 }
280
281 func (b *Backend) UpdateLabel(userID, labelID, name, parentID string) (proton.Label, error) {
282 return withAcc(b, userID, func(acc *account) (proton.Label, error) {
283 return withLabels(b, func(labels map[string]*label) (proton.Label, error) {
284 if parentID != "" {
285 if labels[labelID].labelType != proton.LabelTypeFolder {
286 return proton.Label{}, fmt.Errorf("parentID can only be set for folders")
287 }
288
289 if _, ok := labels[parentID]; !ok {
290 return proton.Label{}, fmt.Errorf("no such parent label: %s", parentID)
291 }
292 }
293
294 labels[labelID].name = name
295 labels[labelID].parentID = parentID
296
297 updateID, err := b.newUpdate(&labelUpdated{labelID: labelID})
298 if err != nil {
299 return proton.Label{}, err
300 }
301
302 acc.updateIDs = append(acc.updateIDs, updateID)
303
304 return labels[labelID].toLabel(labels), nil
305 })
306 })
307 }
308
309 func (b *Backend) DeleteLabel(userID, labelID string) error {
310 return b.withAcc(userID, func(acc *account) error {
311 return b.withLabels(func(labels map[string]*label) error {
312 if _, ok := labels[labelID]; !ok {
313 return errors.New("label not found")
314 }
315
316 for _, labelID := range getLabelIDsToDelete(labelID, labels) {
317 delete(labels, labelID)
318
319 updateID, err := b.newUpdate(&labelDeleted{labelID: labelID})
320 if err != nil {
321 return err
322 }
323
324 acc.labelIDs = xslices.Filter(acc.labelIDs, func(otherID string) bool { return otherID != labelID })
325 acc.updateIDs = append(acc.updateIDs, updateID)
326 }
327
328 return nil
329 })
330 })
331 }
332
333 func (b *Backend) CountMessages(userID string) (int, error) {
334 return withAcc(b, userID, func(acc *account) (int, error) {
335 return len(acc.messageIDs), nil
336 })
337 }
338
339 func (b *Backend) GetMessageIDs(userID string, afterID string, limit int) ([]string, error) {
340 return withAcc(b, userID, func(acc *account) ([]string, error) {
341 if len(acc.messageIDs) == 0 {
342 return nil, nil
343 }
344
345 var lo, hi int
346
347 if afterID == "" {
348 lo = 0
349 } else {
350 lo = slices.Index(acc.messageIDs, afterID) + 1
351 }
352
353 if limit == 0 {
354 hi = len(acc.messageIDs)
355 } else {
356 hi = lo + limit
357
358 if hi > len(acc.messageIDs) {
359 hi = len(acc.messageIDs)
360 }
361 }
362
363 return acc.messageIDs[lo:hi], nil
364 })
365 }
366
367 func (b *Backend) GetMessages(userID string, page, pageSize int, filter proton.MessageFilter) ([]proton.MessageMetadata, error) {
368 return withAcc(b, userID, func(acc *account) ([]proton.MessageMetadata, error) {
369 return withMessages(b, func(messages map[string]*message) ([]proton.MessageMetadata, error) {
370 metadata, err := withAtts(b, func(atts map[string]*attachment) ([]proton.MessageMetadata, error) {
371 return xslices.Map(acc.messageIDs, func(messageID string) proton.MessageMetadata {
372 return messages[messageID].toMetadata(b.attData, atts)
373 }), nil
374 })
375 if err != nil {
376 return nil, err
377 }
378
379 if filter.Desc {
380 xslices.Reverse(metadata)
381 }
382
383 // Note that this not a perfect replacement as we don't handle the case where this message could have been
384 // deleted in between this metadata request. The backend has the information stored differently and can
385 // resolve these gaps.
386 if filter.EndID != "" {
387 index := xslices.IndexFunc(metadata, func(metadata proton.MessageMetadata) bool {
388 return metadata.ID == filter.EndID
389 })
390
391 if index >= 0 {
392 metadata = metadata[index:]
393 }
394 }
395
396 metadata = xslices.Filter(metadata, func(metadata proton.MessageMetadata) bool {
397 if len(filter.ID) > 0 {
398 if !slices.Contains(filter.ID, metadata.ID) {
399 return false
400 }
401 }
402
403 if filter.Subject != "" {
404 if !strings.Contains(metadata.Subject, filter.Subject) {
405 return false
406 }
407 }
408
409 if filter.AddressID != "" {
410 if filter.AddressID != metadata.AddressID {
411 return false
412 }
413 }
414
415 if filter.ExternalID != "" {
416 if filter.ExternalID != metadata.ExternalID {
417 return false
418 }
419 }
420
421 if filter.LabelID != "" {
422 if !slices.Contains(metadata.LabelIDs, filter.LabelID) {
423 return false
424 }
425 }
426
427 return true
428 })
429
430 pages := xslices.Chunk(metadata, pageSize)
431 if page >= len(pages) {
432 return nil, nil
433 }
434
435 return pages[page], nil
436 })
437 })
438 }
439
440 func (b *Backend) GetMessage(userID, messageID string) (proton.Message, error) {
441 return withAcc(b, userID, func(acc *account) (proton.Message, error) {
442 return withMessages(b, func(messages map[string]*message) (proton.Message, error) {
443 return withAtts(b, func(atts map[string]*attachment) (proton.Message, error) {
444 message, ok := messages[messageID]
445 if !ok {
446 return proton.Message{}, errors.New("no such message")
447 }
448
449 return message.toMessage(b.attData, atts), nil
450 })
451 })
452 })
453 }
454
455 func (b *Backend) SetMessagesRead(userID string, read bool, messageIDs ...string) error {
456 return b.withAcc(userID, func(acc *account) error {
457 return b.withMessages(func(messages map[string]*message) error {
458 for _, messageID := range messageIDs {
459 messages[messageID].unread = !read
460
461 updateID, err := b.newUpdate(&messageUpdated{messageID: messageID})
462 if err != nil {
463 return err
464 }
465
466 acc.updateIDs = append(acc.updateIDs, updateID)
467 }
468
469 return nil
470 })
471 })
472 }
473 func (b *Backend) LabelMessages(userID, labelID string, messageIDs ...string) error {
474 return b.labelMessages(userID, labelID, true, messageIDs...)
475 }
476
477 func (b *Backend) LabelMessagesNoEvents(userID, labelID string, messageIDs ...string) error {
478 return b.labelMessages(userID, labelID, false, messageIDs...)
479 }
480
481 func (b *Backend) labelMessages(userID, labelID string, doEvents bool, messageIDs ...string) error {
482 if labelID == proton.AllMailLabel || labelID == proton.AllDraftsLabel || labelID == proton.AllSentLabel {
483 return fmt.Errorf("not allowed")
484 }
485
486 return b.withAcc(userID, func(acc *account) error {
487 return b.withMessages(func(messages map[string]*message) error {
488 return b.withLabels(func(labels map[string]*label) error {
489 for _, messageID := range messageIDs {
490 message, ok := messages[messageID]
491 if !ok {
492 continue
493 }
494
495 message.addLabel(labelID, labels)
496
497 if doEvents {
498 updateID, err := b.newUpdate(&messageUpdated{messageID: messageID})
499 if err != nil {
500 return err
501 }
502
503 acc.updateIDs = append(acc.updateIDs, updateID)
504 }
505 }
506
507 return nil
508 })
509 })
510 })
511 }
512
513 func (b *Backend) UnlabelMessages(userID, labelID string, messageIDs ...string) error {
514 if labelID == proton.AllMailLabel || labelID == proton.AllDraftsLabel || labelID == proton.AllSentLabel {
515 return fmt.Errorf("not allowed")
516 }
517
518 return b.withAcc(userID, func(acc *account) error {
519 return b.withMessages(func(messages map[string]*message) error {
520 return b.withLabels(func(labels map[string]*label) error {
521 for _, messageID := range messageIDs {
522 messages[messageID].remLabel(labelID, labels)
523
524 updateID, err := b.newUpdate(&messageUpdated{messageID: messageID})
525 if err != nil {
526 return err
527 }
528
529 acc.updateIDs = append(acc.updateIDs, updateID)
530 }
531
532 return nil
533 })
534 })
535 })
536 }
537
538 func (b *Backend) DeleteMessage(userID, messageID string) error {
539 return b.withAcc(userID, func(acc *account) error {
540 return b.withMessages(func(messages map[string]*message) error {
541 message, ok := messages[messageID]
542 if !ok {
543 return errors.New("no such message")
544 }
545
546 for _, attID := range message.attIDs {
547 if xslices.CountFunc(maps.Values(b.attachments), func(att *attachment) bool {
548 return att.attDataID == b.attachments[attID].attDataID
549 }) == 1 {
550 delete(b.attData, b.attachments[attID].attDataID)
551 }
552
553 delete(b.attachments, attID)
554 }
555
556 delete(b.messages, messageID)
557
558 updateID, err := b.newUpdate(&messageDeleted{messageID: messageID})
559 if err != nil {
560 return err
561 }
562
563 acc.messageIDs = xslices.Filter(acc.messageIDs, func(otherID string) bool { return otherID != messageID })
564 acc.updateIDs = append(acc.updateIDs, updateID)
565
566 return nil
567 })
568 })
569 }
570
571 func (b *Backend) CreateDraft(userID, addrID string, draft proton.DraftTemplate, parentID string) (proton.Message, error) {
572 return withAcc(b, userID, func(acc *account) (proton.Message, error) {
573 return withMessages(b, func(messages map[string]*message) (proton.Message, error) {
574 return withLabels(b, func(labels map[string]*label) (proton.Message, error) {
575 // Convert the parentID into externalRef.\
576 var parentRef string
577 if parentID != "" {
578 parentMsg, ok := messages[parentID]
579 if ok {
580 parentRef = "<" + parentMsg.externalID + ">"
581 }
582 }
583 msg := newMessageFromTemplate(addrID, draft, parentRef)
584 // Drafts automatically get the sysLabel "Drafts".
585 msg.addLabel(proton.DraftsLabel, labels)
586
587 messages[msg.messageID] = msg
588
589 updateID, err := b.newUpdate(&messageCreated{messageID: msg.messageID})
590 if err != nil {
591 return proton.Message{}, err
592 }
593
594 acc.messageIDs = append(acc.messageIDs, msg.messageID)
595 acc.updateIDs = append(acc.updateIDs, updateID)
596
597 return msg.toMessage(nil, nil), nil
598 })
599 })
600 })
601 }
602
603 func (b *Backend) UpdateDraft(userID, draftID string, changes proton.DraftTemplate) (proton.Message, error) {
604 if changes.Sender == nil {
605 return proton.Message{}, errors.New("the Sender is required")
606 }
607
608 if changes.Sender.Address == "" {
609 return proton.Message{}, errors.New("the Address is required")
610 }
611
612 if changes.MIMEType != rfc822.TextPlain && changes.MIMEType != rfc822.TextHTML {
613 return proton.Message{}, errors.New("the MIMEType must be text/plain or text/html")
614 }
615
616 return withAcc(b, userID, func(acc *account) (proton.Message, error) {
617 return withMessages(b, func(messages map[string]*message) (proton.Message, error) {
618 return withAtts(b, func(atts map[string]*attachment) (proton.Message, error) {
619 if _, ok := messages[draftID]; !ok {
620 return proton.Message{}, fmt.Errorf("message %q not found", draftID)
621 }
622
623 messages[draftID].applyChanges(changes)
624
625 updateID, err := b.newUpdate(&messageUpdated{messageID: draftID})
626 if err != nil {
627 return proton.Message{}, err
628 }
629
630 acc.updateIDs = append(acc.updateIDs, updateID)
631
632 return messages[draftID].toMessage(b.attData, atts), nil
633 })
634 })
635 })
636 }
637
638 func (b *Backend) SendMessage(userID, messageID string, packages []*proton.MessagePackage) (proton.Message, error) {
639 return withAcc(b, userID, func(acc *account) (proton.Message, error) {
640 return withMessages(b, func(messages map[string]*message) (proton.Message, error) {
641 return withLabels(b, func(labels map[string]*label) (proton.Message, error) {
642 return withAtts(b, func(atts map[string]*attachment) (proton.Message, error) {
643 msg := messages[messageID]
644 msg.flags |= proton.MessageFlagSent
645 msg.addLabel(proton.SentLabel, labels)
646
647 updateID, err := b.newUpdate(&messageUpdated{messageID: messageID})
648 if err != nil {
649 return proton.Message{}, err
650 }
651
652 acc.updateIDs = append(acc.updateIDs, updateID)
653
654 for _, pkg := range packages {
655 bodyData, err := base64.StdEncoding.DecodeString(pkg.Body)
656 if err != nil {
657 return proton.Message{}, err
658 }
659
660 for email, recipient := range pkg.Addresses {
661 if recipient.Type != proton.InternalScheme {
662 continue
663 }
664
665 if err := b.withAccEmail(email, func(acc *account) error {
666 bodyKey, err := base64.StdEncoding.DecodeString(recipient.BodyKeyPacket)
667 if err != nil {
668 return err
669 }
670
671 armBody, err := crypto.NewPGPSplitMessage(bodyKey, bodyData).GetPGPMessage().GetArmored()
672 if err != nil {
673 return err
674 }
675
676 addrID, err := b.GetAddressID(email)
677 if err != nil {
678 return err
679 }
680
681 newMsg := newMessageFromSent(addrID, armBody, msg)
682 newMsg.flags |= proton.MessageFlagReceived
683 newMsg.addLabel(proton.InboxLabel, labels)
684 newMsg.unread = true
685 messages[newMsg.messageID] = newMsg
686
687 for _, attID := range msg.attIDs {
688 attKey, err := base64.StdEncoding.DecodeString(recipient.AttachmentKeyPackets[attID])
689 if err != nil {
690 return err
691 }
692
693 att := newAttachment(
694 atts[attID].filename,
695 atts[attID].mimeType,
696 atts[attID].disposition,
697 attKey,
698 atts[attID].attDataID,
699 atts[attID].armSig,
700 )
701 atts[att.attachID] = att
702 messages[newMsg.messageID].attIDs = append(messages[newMsg.messageID].attIDs, att.attachID)
703 }
704
705 updateID, err := b.newUpdate(&messageCreated{messageID: newMsg.messageID})
706 if err != nil {
707 return err
708 }
709
710 acc.messageIDs = append(acc.messageIDs, newMsg.messageID)
711 acc.updateIDs = append(acc.updateIDs, updateID)
712
713 return nil
714 }); err != nil {
715 return proton.Message{}, err
716 }
717 }
718 }
719
720 return msg.toMessage(b.attData, atts), nil
721 })
722 })
723 })
724 })
725 }
726
727 func (b *Backend) CreateAttachment(
728 userID string,
729 messageID string,
730 filename string,
731 mimeType rfc822.MIMEType,
732 disposition proton.Disposition,
733 contentID string,
734 keyPackets, dataPacket []byte,
735 armSig string,
736 ) (proton.Attachment, error) {
737 if disposition != proton.InlineDisposition && disposition != proton.AttachmentDisposition {
738 return proton.Attachment{}, errors.New("The Disposition only allows 'attachment', or 'inline'")
739 }
740
741 if disposition == proton.InlineDisposition && contentID == "" {
742 return proton.Attachment{}, errors.New("The 'inline' Disposition is only allowed with Content ID")
743 }
744
745 return withAcc(b, userID, func(acc *account) (proton.Attachment, error) {
746 return withMessages(b, func(messages map[string]*message) (proton.Attachment, error) {
747 return withAtts(b, func(atts map[string]*attachment) (proton.Attachment, error) {
748 att := newAttachment(
749 filename,
750 mimeType,
751 disposition,
752 keyPackets,
753 b.createAttData(dataPacket),
754 armSig,
755 )
756
757 atts[att.attachID] = att
758
759 messages[messageID].attIDs = append(messages[messageID].attIDs, att.attachID)
760
761 updateID, err := b.newUpdate(&messageUpdated{messageID: messageID})
762 if err != nil {
763 return proton.Attachment{}, err
764 }
765
766 acc.updateIDs = append(acc.updateIDs, updateID)
767
768 return att.toAttachment(), nil
769 })
770 })
771 })
772 }
773
774 func (b *Backend) GetAttachment(attachID string) ([]byte, error) {
775 return withAtts(b, func(atts map[string]*attachment) ([]byte, error) {
776 att, ok := atts[attachID]
777 if !ok {
778 return nil, fmt.Errorf("no such attachment: %s", attachID)
779 }
780
781 return b.attData[att.attDataID], nil
782 })
783 }
784
785 func (b *Backend) GetLatestEventID(userID string) (string, error) {
786 return withAcc(b, userID, func(acc *account) (string, error) {
787 return acc.updateIDs[len(acc.updateIDs)-1].String(), nil
788 })
789 }
790
791 func getLastUpdateIndex(total, first, max int) int {
792 if max <= 0 || first+max > total {
793 return total
794 }
795
796 return first + max
797 }
798
799 func (b *Backend) GetEvent(userID, rawEventID string) (event proton.Event, more bool, err error) {
800 var eventID ID
801
802 if err := eventID.FromString(rawEventID); err != nil {
803 return proton.Event{}, false, fmt.Errorf("invalid event ID: %s", rawEventID)
804 }
805
806 more = false
807
808 event, err = withAcc(b, userID, func(acc *account) (proton.Event, error) {
809 return withMessages(b, func(messages map[string]*message) (proton.Event, error) {
810 return withLabels(b, func(labels map[string]*label) (proton.Event, error) {
811 return withAtts(b, func(attachments map[string]*attachment) (proton.Event, error) {
812 firstUpdate := xslices.Index(acc.updateIDs, eventID) + 1
813 lastUpdate := getLastUpdateIndex(len(acc.updateIDs), firstUpdate, b.maxUpdatesPerEvent)
814
815 updates, err := withUpdates(b, func(updates map[ID]update) ([]update, error) {
816 return merge(xslices.Map(acc.updateIDs[firstUpdate:lastUpdate], func(updateID ID) update {
817 return updates[updateID]
818 })), nil
819 })
820 if err != nil {
821 return proton.Event{}, fmt.Errorf("failed to merge updates: %w", err)
822 }
823
824 more = lastUpdate != len(acc.updateIDs)
825
826 return buildEvent(updates, acc.addresses, messages, labels, acc.updateIDs[lastUpdate-1].String(), b.attData, attachments), nil
827 })
828 })
829 })
830 })
831
832 if err != nil {
833 return proton.Event{}, false, err
834 }
835
836 return event, more, nil
837 }
838
839 func (b *Backend) GetPublicKeys(email string) ([]proton.PublicKey, error) {
840 return withAccEmail(b, email, func(acc *account) ([]proton.PublicKey, error) {
841 var keys []proton.PublicKey
842
843 for _, addr := range acc.addresses {
844 if addr.email == email {
845 for _, key := range addr.keys {
846 pubKey, err := key.getPubKey()
847 if err != nil {
848 return nil, err
849 }
850
851 armKey, err := pubKey.GetArmoredPublicKey()
852 if err != nil {
853 return nil, err
854 }
855
856 keys = append(keys, proton.PublicKey{
857 Flags: proton.KeyStateTrusted | proton.KeyStateActive,
858 PublicKey: armKey,
859 })
860 }
861 }
862 }
863
864 return keys, nil
865 })
866 }
867
868 func getLabelIDsToDelete(labelID string, labels map[string]*label) []string {
869 labelIDs := []string{labelID}
870
871 for _, label := range labels {
872 if label.parentID == labelID {
873 labelIDs = append(labelIDs, getLabelIDsToDelete(label.labelID, labels)...)
874 }
875 }
876
877 return labelIDs
878 }
879
880 func (b *Backend) AddAddressCreatedUpdate(userID, addrID string) error {
881 return b.withAcc(userID, func(acc *account) error {
882 updateID, err := b.newUpdate(&addressCreated{addressID: addrID})
883 if err != nil {
884 return err
885 }
886
887 acc.updateIDs = append(acc.updateIDs, updateID)
888
889 return nil
890 })
891 }
892
893 func (b *Backend) AddLabelCreatedUpdate(userID, labelID string) error {
894 return b.withAcc(userID, func(acc *account) error {
895 updateID, err := b.newUpdate(&labelCreated{labelID: labelID})
896 if err != nil {
897 return err
898 }
899
900 acc.updateIDs = append(acc.updateIDs, updateID)
901
902 return nil
903 })
904 }
905
906 func (b *Backend) AddMessageCreatedUpdate(userID, messageID string) error {
907 return b.withAcc(userID, func(acc *account) error {
908 updateID, err := b.newUpdate(&messageCreated{messageID: messageID})
909 if err != nil {
910 return err
911 }
912
913 acc.updateIDs = append(acc.updateIDs, updateID)
914
915 return nil
916 })
917 }
918
919 func (b *Backend) GetMessageGroupCount(userID string) ([]proton.MessageGroupCount, error) {
920 var result []proton.MessageGroupCount
921 err := b.withAcc(userID, func(acc *account) error {
922 return b.withMessages(func(m map[string]*message) error {
923 type stats struct {
924 total int
925 unread int
926 }
927
928 labelStats := make(map[string]stats)
929
930 for _, msg := range m {
931 for _, lbl := range msg.getLabelIDs() {
932 v, ok := labelStats[lbl]
933 if !ok {
934 v = stats{}
935 }
936 v.total++
937 if msg.unread {
938 v.unread++
939 }
940
941 labelStats[lbl] = v
942 }
943 }
944
945 result = make([]proton.MessageGroupCount, 0, len(labelStats))
946
947 for lbl, stats := range labelStats {
948 result = append(result, proton.MessageGroupCount{
949 LabelID: lbl,
950 Total: stats.total,
951 Unread: stats.unread,
952 })
953 }
954
955 return nil
956 })
957 })
958
959 return result, err
960 }
961
962 func buildEvent(
963 updates []update,
964 addresses map[string]*address,
965 messages map[string]*message,
966 labels map[string]*label,
967 eventID string,
968 attachmentData map[string][]byte,
969 attachments map[string]*attachment,
970
971 ) proton.Event {
972 event := proton.Event{EventID: eventID}
973
974 for _, update := range updates {
975 switch update := update.(type) {
976 case *userRefreshed:
977 event.Refresh = update.refresh
978
979 case *messageCreated:
980 event.Messages = append(event.Messages, proton.MessageEvent{
981 EventItem: proton.EventItem{
982 ID: update.messageID,
983 Action: proton.EventCreate,
984 },
985
986 Message: messages[update.messageID].toMetadata(attachmentData, attachments),
987 })
988
989 case *messageUpdated:
990 event.Messages = append(event.Messages, proton.MessageEvent{
991 EventItem: proton.EventItem{
992 ID: update.messageID,
993 Action: proton.EventUpdate,
994 },
995
996 Message: messages[update.messageID].toMetadata(attachmentData, attachments),
997 })
998
999 case *messageDeleted:
1000 event.Messages = append(event.Messages, proton.MessageEvent{
1001 EventItem: proton.EventItem{
1002 ID: update.messageID,
1003 Action: proton.EventDelete,
1004 },
1005 })
1006
1007 case *labelCreated:
1008 event.Labels = append(event.Labels, proton.LabelEvent{
1009 EventItem: proton.EventItem{
1010 ID: update.labelID,
1011 Action: proton.EventCreate,
1012 },
1013
1014 Label: labels[update.labelID].toLabel(labels),
1015 })
1016
1017 case *labelUpdated:
1018 event.Labels = append(event.Labels, proton.LabelEvent{
1019 EventItem: proton.EventItem{
1020 ID: update.labelID,
1021 Action: proton.EventUpdate,
1022 },
1023
1024 Label: labels[update.labelID].toLabel(labels),
1025 })
1026
1027 case *labelDeleted:
1028 event.Labels = append(event.Labels, proton.LabelEvent{
1029 EventItem: proton.EventItem{
1030 ID: update.labelID,
1031 Action: proton.EventDelete,
1032 },
1033 })
1034
1035 case *addressCreated:
1036 event.Addresses = append(event.Addresses, proton.AddressEvent{
1037 EventItem: proton.EventItem{
1038 ID: update.addressID,
1039 Action: proton.EventCreate,
1040 },
1041
1042 Address: addresses[update.addressID].toAddress(),
1043 })
1044
1045 case *addressUpdated:
1046 event.Addresses = append(event.Addresses, proton.AddressEvent{
1047 EventItem: proton.EventItem{
1048 ID: update.addressID,
1049 Action: proton.EventUpdate,
1050 },
1051
1052 Address: addresses[update.addressID].toAddress(),
1053 })
1054
1055 case *addressDeleted:
1056 event.Addresses = append(event.Addresses, proton.AddressEvent{
1057 EventItem: proton.EventItem{
1058 ID: update.addressID,
1059 Action: proton.EventDelete,
1060 },
1061 })
1062
1063 case *userSettingsUpdate:
1064 event.UserSettings = &proton.UserSettings{
1065 Telemetry: update.settings.Telemetry,
1066 CrashReports: update.settings.CrashReports,
1067 }
1068 }
1069 }
1070
1071 return event
1072 }