-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbulk.go
More file actions
554 lines (528 loc) · 15.2 KB
/
Copy pathbulk.go
File metadata and controls
554 lines (528 loc) · 15.2 KB
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"strings"
)
type bulkReq struct {
Action string `json:"action"` // mark_read|mark_unread|archive|unarchive|delete|mark_read_all|tag|untag
IDs []string `json:"ids"`
Tag string `json:"tag"`
// View context for mark_read_all / all_pages
View string `json:"view"` // inbox|archive|tag
TagView string `json:"tag_view"`
Q string `json:"q"`
AllPages bool `json:"all_pages"`
// Similar-message filter: tag all from same sender, optionally with
// subject and/or body containing a substring. Used by the "tag similar" modal.
FromAddr string `json:"from_addr"`
SubjectContains string `json:"subject_contains"`
BodyContains string `json:"body_contains"`
}
func handleBulkAPI(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
writeJSON(w, 405, map[string]any{"ok": false, "error": "POST only"})
return
}
var req bulkReq
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeJSON(w, 400, map[string]any{"ok": false, "error": "bad json"})
return
}
p := newPocheFromEnv()
if p.Token == "" {
writeJSON(w, 400, map[string]any{"ok": false, "error": "POCHE_TOKEN missing"})
return
}
mbID := authMailboxID(r)
isAdmin := authIsAdmin(r)
ids := req.IDs
if req.Action == "mark_read_all" || req.AllPages || req.FromAddr != "" {
var err error
if req.FromAddr != "" {
has, missing := viewLinks(req.View, req.TagView)
ids, err = collectIDsFiltered(p, has, missing, "", req.FromAddr, req.SubjectContains, req.BodyContains, mbID, isAdmin)
} else {
ids, err = collectIDsLinked(p, req.View, req.TagView, req.Q, mbID, isAdmin)
}
if err != nil {
writeJSON(w, 500, map[string]any{"ok": false, "error": err.Error()})
return
}
if req.Action == "mark_read_all" {
req.Action = "mark_read"
}
} else if !isAdmin {
// req.IDs here are client-supplied (the checked rows in the UI) and
// were NOT derived from a mailbox-scoped query like collectIDsLinked
// above — without this filter, any signed-in tenant could
// star/archive/tag/delete another tenant's mail by sending its ids
// directly, no guessing required once any two ids were ever visible
// in the same browser (e.g. via the account switcher).
ids = filterIDsOwnedByMailbox(p, ids, mbID)
}
// Destructive bulk actions are logged with who and how many: after a
// mailbox was emptied twice with no record of it, "we cannot tell what
// deleted this" was the expensive part, not the deletion itself.
if req.Action == "delete" || req.AllPages {
fmt.Fprintf(os.Stderr,
"{\"event\":\"bulk_action\",\"action\":%q,\"count\":%d,\"all_pages\":%v,\"view\":%q,\"tag_view\":%q,\"mailbox\":%q,\"admin\":%v}\n",
req.Action, len(ids), req.AllPages, req.View, req.TagView, mbID, isAdmin)
}
okN := 0
failN := 0
for _, id := range ids {
if id == "" {
continue
}
var err error
switch req.Action {
case "mark_read", "mark_unread":
err = patchBool(p, id, "unread", req.Action == "mark_unread")
case "star", "unstar":
err = patchBool(p, id, "starred", req.Action == "star")
case "archive":
err = ensureTag(p, id, tagArchive)
case "unarchive":
err = removeTag(p, id, tagArchive)
case "tag":
if req.Tag == "" {
writeJSON(w, 400, map[string]any{"ok": false, "error": "tag required"})
return
}
_ = ensureTagRow(p, req.Tag)
err = ensureTag(p, id, req.Tag)
case "untag":
if req.Tag == "" {
writeJSON(w, 400, map[string]any{"ok": false, "error": "tag required"})
return
}
err = removeTag(p, id, req.Tag)
case "delete":
err = deleteMessageWithLinks(p, id)
default:
writeJSON(w, 400, map[string]any{"ok": false, "error": "unknown action"})
return
}
if err != nil {
failN++
} else {
okN++
}
}
writeJSON(w, 200, map[string]any{"ok": true, "data": map[string]any{"action": req.Action, "ok": okN, "failed": failN}})
}
func handleTagsAPI(w http.ResponseWriter, r *http.Request) {
p := newPocheFromEnv()
if p.Token == "" {
writeJSON(w, 400, map[string]any{"ok": false, "error": "POCHE_TOKEN missing"})
return
}
if r.Method == http.MethodGet {
data, err := p.List("tags", "", 200, 0, "", false)
if err != nil {
writeJSON(w, 500, map[string]any{"ok": false, "error": err.Error()})
return
}
writeJSON(w, 200, map[string]any{"ok": true, "data": json.RawMessage(data)})
return
}
if r.Method == http.MethodPost {
var body struct {
Name string `json:"name"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
writeJSON(w, 400, map[string]any{"ok": false, "error": "bad json"})
return
}
name := sanitizeTagName(body.Name)
if name == "" {
writeJSON(w, 400, map[string]any{"ok": false, "error": "name required"})
return
}
created, err := p.Create("tags", map[string]any{"name": name})
if err != nil {
writeJSON(w, 500, map[string]any{"ok": false, "error": err.Error()})
return
}
writeJSON(w, 201, map[string]any{"ok": true, "data": json.RawMessage(created)})
return
}
// PUT {"name":"old","new_name":"new"} — rename everywhere the tag is used.
if r.Method == http.MethodPut {
var body struct {
Name string `json:"name"`
NewName string `json:"new_name"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
writeJSON(w, 400, map[string]any{"ok": false, "error": "bad json"})
return
}
if isArchiveName(body.Name) || isArchiveName(body.NewName) {
writeJSON(w, 400, map[string]any{"ok": false, "error": "archive is a system tag and cannot be renamed"})
return
}
from := sanitizeTagName(body.Name)
to := sanitizeTagName(body.NewName)
if from == "" || to == "" {
writeJSON(w, 400, map[string]any{"ok": false, "error": "name and new_name required"})
return
}
if from == to {
writeJSON(w, 200, map[string]any{"ok": true, "data": map[string]any{"renamed": 0, "name": to}})
return
}
n, err := renameTag(p, from, to)
if err != nil {
writeJSON(w, 500, map[string]any{"ok": false, "error": err.Error()})
return
}
writeJSON(w, 200, map[string]any{"ok": true, "data": map[string]any{"renamed": n, "from": from, "name": to}})
return
}
// DELETE ?name=x — drop the tag and every message link to it.
if r.Method == http.MethodDelete {
raw := r.URL.Query().Get("name")
if isArchiveName(raw) {
writeJSON(w, 400, map[string]any{"ok": false, "error": "archive is a system tag and cannot be deleted"})
return
}
name := sanitizeTagName(raw)
if name == "" {
writeJSON(w, 400, map[string]any{"ok": false, "error": "name required"})
return
}
n, err := deleteTagEverywhere(p, name)
if err != nil {
writeJSON(w, 500, map[string]any{"ok": false, "error": err.Error()})
return
}
writeJSON(w, 200, map[string]any{"ok": true, "data": map[string]any{"deleted": true, "name": name, "untagged": n}})
return
}
writeJSON(w, 405, map[string]any{"ok": false, "error": "GET, POST, PUT or DELETE"})
}
// isArchiveName spots the system tag before sanitizeTagName blanks it out.
func isArchiveName(s string) bool {
return strings.EqualFold(strings.TrimSpace(s), tagArchive)
}
type tagLink struct {
id string
messageID string
}
// listTagLinks returns the message_tags rows carrying a tag.
func listTagLinks(p *Poche, tag string) ([]tagLink, error) {
data, err := p.List("message_tags", "tag="+tag, 10000, 0, "", false)
if err != nil {
return nil, err
}
var page struct {
Items []struct {
ID string `json:"id"`
Doc struct {
MessageID string `json:"message_id"`
} `json:"doc"`
} `json:"items"`
}
if err := json.Unmarshal(data, &page); err != nil {
return nil, err
}
out := make([]tagLink, 0, len(page.Items))
for _, it := range page.Items {
out = append(out, tagLink{id: it.ID, messageID: it.Doc.MessageID})
}
return out, nil
}
// renameTag rewrites the tag row and every message link, so messages keep
// their labels instead of silently losing them.
func renameTag(p *Poche, from, to string) (int, error) {
links, err := listTagLinks(p, from)
if err != nil {
return 0, err
}
// Create the destination tag first; a partial rename that lost the tag row
// would leave links pointing at a tag the sidebar never lists.
if err := ensureTagRow(p, to); err != nil {
return 0, err
}
// message_tags is exposed for create+delete but not update, so a relabel is
// "attach the new tag, then drop the old" — the same path tagging uses.
moved := 0
for _, l := range links {
if l.messageID == "" {
continue
}
if err := ensureTag(p, l.messageID, to); err != nil {
return moved, fmt.Errorf("relabel %s: %w", l.messageID, err)
}
if err := removeTag(p, l.messageID, from); err != nil {
return moved, fmt.Errorf("drop old label %s: %w", l.messageID, err)
}
moved++
}
if err := deleteTagRow(p, from); err != nil {
return moved, err
}
return moved, nil
}
func deleteTagEverywhere(p *Poche, name string) (int, error) {
links, err := listTagLinks(p, name)
if err != nil {
return 0, err
}
removed := 0
for _, l := range links {
if err := p.Delete("message_tags", l.id); err != nil {
return removed, fmt.Errorf("untag %s: %w", l.id, err)
}
removed++
}
if err := deleteTagRow(p, name); err != nil {
return removed, err
}
return removed, nil
}
func ensureTagRow(p *Poche, name string) error {
data, err := p.List("tags", "name="+name, 1, 0, "", false)
if err != nil {
return err
}
var page struct {
Total int `json:"total"`
}
_ = json.Unmarshal(data, &page)
if page.Total > 0 {
return nil
}
_, err = p.Create("tags", map[string]any{"name": name})
return err
}
func deleteTagRow(p *Poche, name string) error {
data, err := p.List("tags", "name="+name, 10, 0, "", false)
if err != nil {
return err
}
var page struct {
Items []struct {
ID string `json:"id"`
} `json:"items"`
}
if err := json.Unmarshal(data, &page); err != nil {
return err
}
for _, it := range page.Items {
if err := p.Delete("tags", it.ID); err != nil {
return fmt.Errorf("delete tag row: %w", err)
}
}
return nil
}
func handleMessageTagsAPI(w http.ResponseWriter, r *http.Request) {
p := newPocheFromEnv()
id := r.URL.Query().Get("message_id")
if id == "" {
writeJSON(w, 400, map[string]any{"ok": false, "error": "message_id required"})
return
}
data, err := p.List("message_tags", "message_id="+id, 100, 0, "", false)
if err != nil {
writeJSON(w, 500, map[string]any{"ok": false, "error": err.Error()})
return
}
writeJSON(w, 200, map[string]any{"ok": true, "data": json.RawMessage(data)})
}
func viewLinks(view, tagView string) (has, missing []string) {
switch view {
case "archive":
has = []string{linkArchive}
case "tag":
if tagView != "" {
has = []string{"message_tags.message_id:tag=" + tagView}
}
default: // inbox
missing = []string{linkArchive}
}
return
}
// filterIDsOwnedByMailbox drops any id whose message doesn't belong to mbID
// (or that doesn't exist) — silently, so a caller's action just applies to
// fewer ids rather than erroring, matching handleBulkAPI's existing
// okN/failN counting for individual failures.
func filterIDsOwnedByMailbox(p *Poche, ids []string, mbID string) []string {
if mbID == "" {
return nil
}
out := make([]string, 0, len(ids))
for _, id := range ids {
doc, err := loadDoc(p, id)
if err != nil {
continue
}
if strField(doc, "mailbox_id") == mbID {
out = append(out, id)
}
}
return out
}
func collectIDsLinked(p *Poche, view, tagView, q string, mbID string, isAdmin bool) ([]string, error) {
has, missing := viewLinks(view, tagView)
return collectIDsFiltered(p, has, missing, q, "", "", "", mbID, isAdmin)
}
// collectIDsFiltered is the generalized collector used by both the
// all_pages bulk path (from view/tagView/q) and the "tag similar" path
// (from from_addr + subject_contains + body_contains). The where clause
// is built from search text, from_addr, subject_contains, and body_contains,
// then mailbox-scoped.
func collectIDsFiltered(p *Poche, has, missing []string, q, fromAddr, subjectContains, bodyContains, mbID string, isAdmin bool) ([]string, error) {
var clauses []string
if needle := sanitizeQ(q); needle != "" {
clauses = append(clauses, "search_text~="+needle)
}
if fromAddr != "" {
clauses = append(clauses, "from_addr="+fromAddr)
}
if subjectContains != "" {
clauses = append(clauses, "search_text~="+strings.ToLower(subjectContains))
}
if bodyContains != "" {
clauses = append(clauses, "search_text~="+strings.ToLower(bodyContains))
}
if !isAdmin && mbID != "" {
clauses = append(clauses, "mailbox_id="+mbID)
}
where := strings.Join(clauses, ",")
out := []string{}
offset := 0
for {
data, err := p.ListLinked("messages", where, has, missing, 200, offset, "created_at", true)
if err != nil {
return out, err
}
var page struct {
Items []struct {
ID string `json:"id"`
} `json:"items"`
Total int `json:"total"`
}
if err := json.Unmarshal(data, &page); err != nil {
return out, err
}
if len(page.Items) == 0 {
break
}
for _, it := range page.Items {
out = append(out, it.ID)
}
offset += len(page.Items)
if offset >= page.Total {
break
}
}
return out, nil
}
func sanitizeQ(q string) string {
out := ""
for _, r := range q {
if r == ',' {
out += " "
continue
}
out += string(r)
}
return out
}
func sanitizeTagName(name string) string {
out := ""
for _, r := range name {
if r >= 'A' && r <= 'Z' {
out += string(r + ('a' - 'A'))
continue
}
if (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || r == '-' || r == '_' {
out += string(r)
}
}
if out == "archive" {
return ""
}
return out
}
func ensureTag(p *Poche, messageID, tag string) error {
data, err := p.List("message_tags", "message_id="+messageID+",tag="+tag, 1, 0, "", false)
if err == nil {
var page struct {
Total int `json:"total"`
}
if json.Unmarshal(data, &page) == nil && page.Total > 0 {
return nil
}
}
_, err = p.Create("message_tags", map[string]any{"message_id": messageID, "tag": tag})
return err
}
func removeTag(p *Poche, messageID, tag string) error {
data, err := p.List("message_tags", "message_id="+messageID+",tag="+tag, 50, 0, "", false)
if err != nil {
return err
}
var page struct {
Items []struct {
ID string `json:"id"`
} `json:"items"`
}
if err := json.Unmarshal(data, &page); err != nil {
return err
}
for _, it := range page.Items {
if err := p.Delete("message_tags", it.ID); err != nil {
return err
}
}
return nil
}
func removeAllTags(p *Poche, messageID string) error {
data, err := p.List("message_tags", "message_id="+messageID, 200, 0, "", false)
if err != nil {
return err
}
var page struct {
Items []struct {
ID string `json:"id"`
} `json:"items"`
}
if err := json.Unmarshal(data, &page); err != nil {
return err
}
for _, it := range page.Items {
_ = p.Delete("message_tags", it.ID)
}
return nil
}
func loadDoc(p *Poche, id string) (map[string]any, error) {
raw, err := p.Get("messages", id)
if err != nil {
return nil, err
}
var wrap struct {
Doc json.RawMessage `json:"doc"`
}
if err := json.Unmarshal(raw, &wrap); err != nil {
return nil, err
}
doc := map[string]any{}
if err := json.Unmarshal(wrap.Doc, &doc); err != nil {
return nil, err
}
return doc, nil
}
func patchBool(p *Poche, id, field string, val bool) error {
doc, err := loadDoc(p, id)
if err != nil {
return err
}
doc[field] = val
_, err = p.Update("messages", id, doc)
return err
}