aboutsummaryrefslogtreecommitdiff
path: root/worker/jmap/set.go
blob: d5d4990e8c83c7fc96373e4247734f3837529dc3 (plain)
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
package jmap

import (
	"fmt"

	"git.sr.ht/~rjarry/aerc/models"
	"git.sr.ht/~rockorager/go-jmap"
	"git.sr.ht/~rockorager/go-jmap/mail/email"
)

func (w *JMAPWorker) updateFlags(uids []uint32, flags models.Flags, enable bool) error {
	var req jmap.Request
	update := make(map[jmap.ID]jmap.Patch)

	for _, uid := range uids {
		id, ok := w.uidStore.GetKey(uid)
		if !ok {
			return fmt.Errorf("bug: unknown uid %d", uid)
		}
		update[jmap.ID(id)] = jmap.Patch{}
		for kw := range flagsToKeywords(flags) {
			path := fmt.Sprintf("keywords/%s", kw)
			if enable {
				update[jmap.ID(id)][path] = true
			} else {
				update[jmap.ID(id)][path] = nil
			}
		}
	}

	req.Invoke(&email.Set{
		Account: w.accountId(),
		Update:  update,
	})

	resp, err := w.client.Do(&req)
	if err != nil {
		return err
	}

	for _, inv := range resp.Responses {
		switch r := inv.Args.(type) {
		case *email.SetResponse:
			for _, err := range r.NotUpdated {
				var s string
				if err.Description != nil {
					s = *err.Description
				} else {
					s = err.Type
					if err.Properties != nil {
						s += fmt.Sprintf(" %v", *err.Properties)
					}
				}
				return fmt.Errorf("flag update failed: %s", s)
			}
		}
	}

	return nil
}

func (w *JMAPWorker) moveCopy(uids []uint32, destDir string, move bool) error {
	var req jmap.Request
	var dest jmap.ID
	var ok bool

	update := make(map[jmap.ID]jmap.Patch)

	dest, ok = w.dir2mbox[destDir]
	if !ok && destDir != "" {
		return fmt.Errorf("unknown destination mailbox")
	}

	for _, uid := range uids {
		id, ok := w.uidStore.GetKey(uid)
		if !ok {
			return fmt.Errorf("bug: unknown uid %d", uid)
		}
		patch := jmap.Patch{}
		if dest != "" {
			patch[fmt.Sprintf("mailboxIds/%s", dest)] = true
		}
		if move {
			patch[fmt.Sprintf("mailboxIds/%s", w.selectedMbox)] = nil
		}
		update[jmap.ID(id)] = patch
	}

	req.Invoke(&email.Set{
		Account: w.accountId(),
		Update:  update,
	})

	resp, err := w.client.Do(&req)
	if err != nil {
		return err
	}

	for _, inv := range resp.Responses {
		switch r := inv.Args.(type) {
		case *email.SetResponse:
			for _, err := range r.NotUpdated {
				var s string
				if err.Description != nil {
					s = *err.Description
				} else {
					s = err.Type
					if err.Properties != nil {
						s += fmt.Sprintf(" %v", *err.Properties)
					}
				}
				return fmt.Errorf("mailbox change failed: %s", s)
			}
		}
	}

	return nil
}