| 1 |
package jmap |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"fmt" |
| 6 |
"slices" |
| 7 |
"time" |
| 8 |
|
| 9 |
"git.sr.ht/~rjarry/aerc/lib/log" |
| 10 |
"git.sr.ht/~rjarry/aerc/models" |
| 11 |
"git.sr.ht/~rjarry/aerc/worker/jmap/cache" |
| 12 |
"git.sr.ht/~rjarry/aerc/worker/types" |
| 13 |
"git.sr.ht/~rockorager/go-jmap" |
| 14 |
"git.sr.ht/~rockorager/go-jmap/core/push" |
| 15 |
"git.sr.ht/~rockorager/go-jmap/mail/email" |
| 16 |
"git.sr.ht/~rockorager/go-jmap/mail/mailbox" |
| 17 |
"git.sr.ht/~rockorager/go-jmap/mail/thread" |
| 18 |
) |
| 19 |
|
| 20 |
func (w *JMAPWorker) monitorChanges() { |
| 21 |
defer log.PanicHandler() |
| 22 |
|
| 23 |
events := push.EventSource{ |
| 24 |
Client: w.client, |
| 25 |
Handler: w.handleChange, |
| 26 |
Ping: uint(w.config.serverPing.Seconds()), |
| 27 |
} |
| 28 |
|
| 29 |
w.stop = make(chan struct{}) |
| 30 |
go func() { |
| 31 |
defer log.PanicHandler() |
| 32 |
<-w.stop |
| 33 |
w.w.Errorf("listen stopping") |
| 34 |
w.stop = nil |
| 35 |
events.Close() |
| 36 |
}() |
| 37 |
|
| 38 |
for w.stop != nil { |
| 39 |
w.w.Debugf("listening for changes") |
| 40 |
err := events.Listen() |
| 41 |
if err != nil { |
| 42 |
w.w.PostMessage(&types.Error{ |
| 43 |
Error: fmt.Errorf("jmap listen: %w", err), |
| 44 |
}, nil) |
| 45 |
time.Sleep(5 * time.Second) |
| 46 |
} |
| 47 |
} |
| 48 |
} |
| 49 |
|
| 50 |
const ( |
| 51 |
MailboxState = "Mailbox" |
| 52 |
EmailState = "Email" |
| 53 |
ThreadState = "Thread" |
| 54 |
) |
| 55 |
|
| 56 |
func (w *JMAPWorker) handleChange(s *jmap.StateChange) { |
| 57 |
newState, ok := s.Changed[w.AccountId()] |
| 58 |
if !ok { |
| 59 |
return |
| 60 |
} |
| 61 |
w.w.Debugf("state change %#v", newState) |
| 62 |
|
| 63 |
var req jmap.Request |
| 64 |
|
| 65 |
mboxState, err := w.cache.GetMailboxState() |
| 66 |
if err != nil { |
| 67 |
w.w.Debugf("GetMailboxState: %s", err) |
| 68 |
} |
| 69 |
if mboxState != "" && newState[MailboxState] != mboxState { |
| 70 |
callID := req.Invoke(&mailbox.Changes{ |
| 71 |
Account: w.AccountId(), |
| 72 |
SinceState: mboxState, |
| 73 |
}) |
| 74 |
req.Invoke(&mailbox.Get{ |
| 75 |
Account: w.AccountId(), |
| 76 |
ReferenceIDs: &jmap.ResultReference{ |
| 77 |
ResultOf: callID, |
| 78 |
Name: "Mailbox/changes", |
| 79 |
Path: "/created", |
| 80 |
}, |
| 81 |
}) |
| 82 |
req.Invoke(&mailbox.Get{ |
| 83 |
Account: w.AccountId(), |
| 84 |
ReferenceIDs: &jmap.ResultReference{ |
| 85 |
ResultOf: callID, |
| 86 |
Name: "Mailbox/changes", |
| 87 |
Path: "/updated", |
| 88 |
}, |
| 89 |
}) |
| 90 |
} |
| 91 |
|
| 92 |
queryChangesCalls := make(map[string]jmap.ID) |
| 93 |
folderContents := make(map[jmap.ID]*cache.FolderContents) |
| 94 |
for id := range w.mboxes { |
| 95 |
contents, err := w.cache.GetFolderContents(id) |
| 96 |
if err != nil { |
| 97 |
continue |
| 98 |
} |
| 99 |
filter, err := w.translateSearch(id, contents.Filter) |
| 100 |
if err != nil { |
| 101 |
continue |
| 102 |
} |
| 103 |
callID := req.Invoke(&email.QueryChanges{ |
| 104 |
Account: w.AccountId(), |
| 105 |
Filter: filter, |
| 106 |
Sort: translateSort(contents.Sort), |
| 107 |
SinceQueryState: contents.QueryState, |
| 108 |
}) |
| 109 |
queryChangesCalls[callID] = id |
| 110 |
folderContents[id] = contents |
| 111 |
} |
| 112 |
|
| 113 |
emailState, err := w.cache.GetEmailState() |
| 114 |
if err != nil { |
| 115 |
w.w.Debugf("GetEmailState: %s", err) |
| 116 |
} |
| 117 |
if emailState != "" && newState[EmailState] != emailState { |
| 118 |
callID := req.Invoke(&email.Changes{ |
| 119 |
Account: w.AccountId(), |
| 120 |
SinceState: emailState, |
| 121 |
}) |
| 122 |
req.Invoke(&email.Get{ |
| 123 |
Account: w.AccountId(), |
| 124 |
Properties: emailProperties, |
| 125 |
BodyProperties: bodyProperties, |
| 126 |
ReferenceIDs: &jmap.ResultReference{ |
| 127 |
ResultOf: callID, |
| 128 |
Name: "Email/changes", |
| 129 |
Path: "/updated", |
| 130 |
}, |
| 131 |
}) |
| 132 |
req.Invoke(&email.Get{ |
| 133 |
Account: w.AccountId(), |
| 134 |
Properties: emailProperties, |
| 135 |
BodyProperties: bodyProperties, |
| 136 |
ReferenceIDs: &jmap.ResultReference{ |
| 137 |
ResultOf: callID, |
| 138 |
Name: "Email/changes", |
| 139 |
Path: "/created", |
| 140 |
}, |
| 141 |
}) |
| 142 |
} |
| 143 |
|
| 144 |
threadState, err := w.cache.GetThreadState() |
| 145 |
if err != nil { |
| 146 |
w.w.Debugf("GetThreadState: %s", err) |
| 147 |
} |
| 148 |
if threadState != "" && newState[ThreadState] != threadState { |
| 149 |
callID := req.Invoke(&thread.Changes{ |
| 150 |
Account: w.AccountId(), |
| 151 |
SinceState: threadState, |
| 152 |
}) |
| 153 |
req.Invoke(&thread.Get{ |
| 154 |
Account: w.AccountId(), |
| 155 |
ReferenceIDs: &jmap.ResultReference{ |
| 156 |
ResultOf: callID, |
| 157 |
Name: "Thread/changes", |
| 158 |
Path: "/created", |
| 159 |
}, |
| 160 |
}) |
| 161 |
req.Invoke(&thread.Get{ |
| 162 |
Account: w.AccountId(), |
| 163 |
ReferenceIDs: &jmap.ResultReference{ |
| 164 |
ResultOf: callID, |
| 165 |
Name: "Thread/changes", |
| 166 |
Path: "/updated", |
| 167 |
}, |
| 168 |
}) |
| 169 |
} |
| 170 |
|
| 171 |
if len(req.Calls) == 0 { |
| 172 |
return |
| 173 |
} |
| 174 |
|
| 175 |
resp, err := w.Do(context.TODO(), &req) |
| 176 |
if err != nil { |
| 177 |
w.w.Errorf("handleChange: %v", err) |
| 178 |
return |
| 179 |
} |
| 180 |
|
| 181 |
var labelsChanged bool |
| 182 |
// threadEmails are email IDs from threads which changed or were |
| 183 |
// created |
| 184 |
var threadEmails []jmap.ID |
| 185 |
// addedEmails are genuinely new messages per mailbox from QueryChanges, |
| 186 |
// used to set Index and RecentFlag in GetResponse. |
| 187 |
// email ID -> mailbox ID -> position index in message store |
| 188 |
addedEmails := make(map[jmap.ID]map[jmap.ID]int) |
| 189 |
// removedEmails are messages removed from mailboxes by QueryChanges, |
| 190 |
// used to skip re-posting in GetResponse. |
| 191 |
// email ID -> mailbox ID -> true |
| 192 |
removedEmails := make(map[jmap.ID]map[jmap.ID]bool) |
| 193 |
|
| 194 |
for _, inv := range resp.Responses { |
| 195 |
switch r := inv.Args.(type) { |
| 196 |
case *mailbox.ChangesResponse: |
| 197 |
for _, id := range r.Destroyed { |
| 198 |
dir, ok := w.mbox2dir[id] |
| 199 |
if ok { |
| 200 |
w.w.Infof("mailbox %q deleted", dir) |
| 201 |
w.w.PostMessage(&types.RemoveDirectory{ |
| 202 |
Directory: dir, |
| 203 |
}, nil) |
| 204 |
} |
| 205 |
w.deleteMbox(id) |
| 206 |
err = w.cache.DeleteMailbox(id) |
| 207 |
if err != nil { |
| 208 |
w.w.Warnf("DeleteMailbox: %s", err) |
| 209 |
} |
| 210 |
labelsChanged = true |
| 211 |
} |
| 212 |
err = w.cache.PutMailboxState(r.NewState) |
| 213 |
if err != nil { |
| 214 |
w.w.Warnf("PutMailboxState: %s", err) |
| 215 |
} |
| 216 |
|
| 217 |
case *mailbox.GetResponse: |
| 218 |
for _, mbox := range r.List { |
| 219 |
if mbox.Role == mailbox.RoleArchive && w.config.useLabels { |
| 220 |
continue |
| 221 |
} |
| 222 |
err = w.cache.PutMailbox(mbox.ID, mbox) |
| 223 |
if err != nil { |
| 224 |
w.w.Warnf("PutMailbox: %s", err) |
| 225 |
} |
| 226 |
m, exist := w.mboxes[mbox.ID] |
| 227 |
if exist && mbox.Name != m.Name { |
| 228 |
w.w.Infof("mailbox %q renamed to %q", m.Name, mbox.Name) |
| 229 |
w.w.PostMessage(&types.RemoveDirectory{ |
| 230 |
Directory: w.mbox2dir[mbox.ID], |
| 231 |
}, nil) |
| 232 |
w.deleteMbox(mbox.ID) |
| 233 |
labelsChanged = true |
| 234 |
exist = false |
| 235 |
} |
| 236 |
if exist { |
| 237 |
w.w.Infof("mailbox %q counts updated", mbox.Name) |
| 238 |
w.mboxes[mbox.ID] = mbox |
| 239 |
w.w.PostMessage(&types.DirectoryInfo{ |
| 240 |
Info: &models.DirectoryInfo{ |
| 241 |
Name: w.mbox2dir[mbox.ID], |
| 242 |
Exists: int(mbox.TotalEmails), |
| 243 |
Unseen: int(mbox.UnreadEmails), |
| 244 |
}, |
| 245 |
}, nil) |
| 246 |
} else { |
| 247 |
w.w.Infof("mailbox %q created", mbox.Name) |
| 248 |
w.addMbox(mbox) |
| 249 |
w.w.PostMessage(&types.Directory{ |
| 250 |
Dir: &models.Directory{ |
| 251 |
Name: w.mbox2dir[mbox.ID], |
| 252 |
Role: jmapRole2aerc[mbox.Role], |
| 253 |
Exists: int(mbox.TotalEmails), |
| 254 |
Unseen: int(mbox.UnreadEmails), |
| 255 |
}, |
| 256 |
}, nil) |
| 257 |
labelsChanged = true |
| 258 |
} |
| 259 |
} |
| 260 |
err = w.cache.PutMailboxState(r.State) |
| 261 |
if err != nil { |
| 262 |
w.w.Warnf("PutMailboxState: %s", err) |
| 263 |
} |
| 264 |
|
| 265 |
case *email.QueryChangesResponse: |
| 266 |
mboxId := queryChangesCalls[inv.CallID] |
| 267 |
contents := folderContents[mboxId] |
| 268 |
dir := w.mbox2dir[mboxId] |
| 269 |
|
| 270 |
removed := make(map[jmap.ID]models.UID) |
| 271 |
for _, id := range r.Removed { |
| 272 |
removed[id] = models.UID(id) |
| 273 |
} |
| 274 |
for _, add := range r.Added { |
| 275 |
if _, ok := removed[add.ID]; ok { |
| 276 |
// message just changed, ignore |
| 277 |
delete(removed, add.ID) |
| 278 |
} else { |
| 279 |
// Store add index for each new message |
| 280 |
mboxes, ok := addedEmails[add.ID] |
| 281 |
if !ok { |
| 282 |
mboxes = make(map[jmap.ID]int) |
| 283 |
addedEmails[add.ID] = mboxes |
| 284 |
} |
| 285 |
mboxes[mboxId] = int(add.Index) |
| 286 |
} |
| 287 |
} |
| 288 |
|
| 289 |
// Rebuild the cached message ID list using |
| 290 |
// the original Removed/Added from the response |
| 291 |
// (not the deduped `removed` map). |
| 292 |
if contents != nil { |
| 293 |
allRemoved := make(map[jmap.ID]bool) |
| 294 |
for _, id := range r.Removed { |
| 295 |
allRemoved[id] = true |
| 296 |
} |
| 297 |
added := make(map[int]jmap.ID) |
| 298 |
for _, add := range r.Added { |
| 299 |
added[int(add.Index)] = add.ID |
| 300 |
} |
| 301 |
n := len(contents.MessageIDs) - len(allRemoved) + len(added) |
| 302 |
if n < 0 { |
| 303 |
w.w.Errorf("bug: invalid folder contents state") |
| 304 |
err = w.cache.DeleteFolderContents(mboxId) |
| 305 |
if err != nil { |
| 306 |
w.w.Warnf("DeleteFolderContents: %s", err) |
| 307 |
} |
| 308 |
} else { |
| 309 |
ids := make([]jmap.ID, 0, n) |
| 310 |
i := 0 |
| 311 |
for _, id := range contents.MessageIDs { |
| 312 |
if allRemoved[id] { |
| 313 |
continue |
| 314 |
} |
| 315 |
if addedId, ok := added[i]; ok { |
| 316 |
ids = append(ids, addedId) |
| 317 |
delete(added, i) |
| 318 |
i += 1 |
| 319 |
} |
| 320 |
ids = append(ids, id) |
| 321 |
i += 1 |
| 322 |
} |
| 323 |
for _, id := range added { |
| 324 |
ids = append(ids, id) |
| 325 |
} |
| 326 |
contents.MessageIDs = ids |
| 327 |
contents.QueryState = r.NewQueryState |
| 328 |
err = w.cache.PutFolderContents(mboxId, contents) |
| 329 |
if err != nil { |
| 330 |
w.w.Warnf("PutFolderContents: %s", err) |
| 331 |
} |
| 332 |
} |
| 333 |
} |
| 334 |
|
| 335 |
// Post MessagesDeleted for removed messages |
| 336 |
if len(removed) > 0 { |
| 337 |
deletedUids := make([]models.UID, 0, len(removed)) |
| 338 |
for id, uid := range removed { |
| 339 |
deletedUids = append(deletedUids, uid) |
| 340 |
mboxes, ok := removedEmails[id] |
| 341 |
if !ok { |
| 342 |
mboxes = make(map[jmap.ID]bool) |
| 343 |
removedEmails[id] = mboxes |
| 344 |
} |
| 345 |
mboxes[mboxId] = true |
| 346 |
} |
| 347 |
w.w.Infof("%d messages deleted from %q", len(deletedUids), dir) |
| 348 |
w.w.PostMessage(&types.MessagesDeleted{ |
| 349 |
Directory: dir, |
| 350 |
Uids: deletedUids, |
| 351 |
}, nil) |
| 352 |
} |
| 353 |
|
| 354 |
case *thread.ChangesResponse: |
| 355 |
for _, id := range r.Destroyed { |
| 356 |
err = w.cache.DeleteThread(id) |
| 357 |
if err != nil { |
| 358 |
w.w.Warnf("DeleteThread: %s", err) |
| 359 |
} |
| 360 |
} |
| 361 |
err = w.cache.PutThreadState(r.NewState) |
| 362 |
if err != nil { |
| 363 |
w.w.Warnf("PutThreadState: %s", err) |
| 364 |
} |
| 365 |
|
| 366 |
case *thread.GetResponse: |
| 367 |
for _, thread := range r.List { |
| 368 |
err = w.cache.PutThread(thread.ID, thread.EmailIDs) |
| 369 |
if err != nil { |
| 370 |
w.w.Warnf("PutThread: %s", err) |
| 371 |
} |
| 372 |
// We keep the list of all emails and check in a |
| 373 |
// subsequent request which ones we need to |
| 374 |
// fetch |
| 375 |
threadEmails = append(threadEmails, thread.EmailIDs...) |
| 376 |
} |
| 377 |
err = w.cache.PutThreadState(r.State) |
| 378 |
if err != nil { |
| 379 |
w.w.Warnf("PutThreadState: %s", err) |
| 380 |
} |
| 381 |
|
| 382 |
case *email.GetResponse: |
| 383 |
for _, m := range r.List { |
| 384 |
old, err := w.cache.GetEmail(m.ID) |
| 385 |
if err == nil { |
| 386 |
for mboxId := range old.MailboxIDs { |
| 387 |
if !m.MailboxIDs[mboxId] { |
| 388 |
dir, ok := w.mbox2dir[mboxId] |
| 389 |
if !ok { |
| 390 |
continue |
| 391 |
} |
| 392 |
w.w.PostMessage(&types.MessagesDeleted{ |
| 393 |
Directory: dir, |
| 394 |
Uids: []models.UID{models.UID(m.ID)}, |
| 395 |
}, nil) |
| 396 |
} |
| 397 |
} |
| 398 |
} |
| 399 |
err = w.cache.PutEmail(m.ID, m) |
| 400 |
if err != nil { |
| 401 |
w.w.Warnf("PutEmail: %s", err) |
| 402 |
} |
| 403 |
removedBoxes := removedEmails[m.ID] |
| 404 |
indexes, ok := addedEmails[m.ID] |
| 405 |
if ok { |
| 406 |
delete(addedEmails, m.ID) |
| 407 |
} |
| 408 |
for mboxId := range m.MailboxIDs { |
| 409 |
dir, ok := w.mbox2dir[mboxId] |
| 410 |
if !ok { |
| 411 |
continue |
| 412 |
} |
| 413 |
if removedBoxes != nil && removedBoxes[mboxId] { |
| 414 |
continue |
| 415 |
} |
| 416 |
info := w.translateMsgInfo(m, dir) |
| 417 |
if indexes != nil { |
| 418 |
i, ok := indexes[mboxId] |
| 419 |
if ok { |
| 420 |
info.Index = &i |
| 421 |
// Set recent on created messages so we |
| 422 |
// get a notification |
| 423 |
if !info.Flags.Has(models.SeenFlag) { |
| 424 |
info.Flags |= models.RecentFlag |
| 425 |
} |
| 426 |
} |
| 427 |
} |
| 428 |
w.w.Infof("message %s updated in %q", info.Envelope.MessageId, dir) |
| 429 |
w.w.PostMessage(&types.MessageInfo{ |
| 430 |
Info: info, |
| 431 |
}, nil) |
| 432 |
} |
| 433 |
} |
| 434 |
err = w.cache.PutEmailState(r.State) |
| 435 |
if err != nil { |
| 436 |
w.w.Warnf("PutEmailState: %s", err) |
| 437 |
} |
| 438 |
|
| 439 |
case *jmap.MethodError: |
| 440 |
w.w.Errorf("%s: %s", wrapMethodError(r)) |
| 441 |
if inv.Name == "Email/queryChanges" { |
| 442 |
id := queryChangesCalls[inv.CallID] |
| 443 |
w.w.Infof("flushing %q contents from cache", |
| 444 |
w.mbox2dir[id]) |
| 445 |
err := w.cache.DeleteFolderContents(id) |
| 446 |
if err != nil { |
| 447 |
w.w.Warnf("DeleteFolderContents: %s", err) |
| 448 |
} |
| 449 |
} |
| 450 |
} |
| 451 |
} |
| 452 |
|
| 453 |
if w.config.useLabels && labelsChanged { |
| 454 |
labels := make([]string, 0, len(w.dir2mbox)) |
| 455 |
for dir := range w.dir2mbox { |
| 456 |
labels = append(labels, dir) |
| 457 |
} |
| 458 |
slices.Sort(labels) |
| 459 |
w.w.PostMessage(&types.LabelList{Labels: labels}, nil) |
| 460 |
} |
| 461 |
|
| 462 |
w.refreshQueriesAndThreads(addedEmails, threadEmails) |
| 463 |
} |
| 464 |
|
| 465 |
// refreshQueriesAndThreads updates the cached query for any mailbox which was updated |
| 466 |
func (w *JMAPWorker) refreshQueriesAndThreads( |
| 467 |
addedEmails map[jmap.ID]map[jmap.ID]int, |
| 468 |
threadEmails []jmap.ID, |
| 469 |
) { |
| 470 |
if len(addedEmails) == 0 && len(threadEmails) == 0 { |
| 471 |
return |
| 472 |
} |
| 473 |
|
| 474 |
ids := make([]jmap.ID, 0, len(addedEmails)+len(threadEmails)) |
| 475 |
for i := range addedEmails { |
| 476 |
ids = append(ids, i) |
| 477 |
} |
| 478 |
ids = append(ids, threadEmails...) |
| 479 |
|
| 480 |
var req jmap.Request |
| 481 |
|
| 482 |
req.Invoke(&email.Get{ |
| 483 |
Account: w.AccountId(), |
| 484 |
Properties: emailProperties, |
| 485 |
BodyProperties: bodyProperties, |
| 486 |
IDs: ids, |
| 487 |
}) |
| 488 |
|
| 489 |
resp, err := w.Do(context.TODO(), &req) |
| 490 |
if err != nil { |
| 491 |
w.w.Errorf("%s", err) |
| 492 |
return |
| 493 |
} |
| 494 |
|
| 495 |
for _, inv := range resp.Responses { |
| 496 |
switch r := inv.Args.(type) { |
| 497 |
case *email.GetResponse: |
| 498 |
for _, m := range r.List { |
| 499 |
old, err := w.cache.GetEmail(m.ID) |
| 500 |
if err == nil { |
| 501 |
for mboxId := range old.MailboxIDs { |
| 502 |
if !m.MailboxIDs[mboxId] { |
| 503 |
dir, ok := w.mbox2dir[mboxId] |
| 504 |
if !ok { |
| 505 |
continue |
| 506 |
} |
| 507 |
w.w.PostMessage(&types.MessagesDeleted{ |
| 508 |
Directory: dir, |
| 509 |
Uids: []models.UID{models.UID(m.ID)}, |
| 510 |
}, nil) |
| 511 |
} |
| 512 |
} |
| 513 |
} |
| 514 |
err = w.cache.PutEmail(m.ID, m) |
| 515 |
if err != nil { |
| 516 |
w.w.Warnf("PutEmail: %s", err) |
| 517 |
} |
| 518 |
indexes := addedEmails[m.ID] |
| 519 |
for mboxId := range m.MailboxIDs { |
| 520 |
dir, ok := w.mbox2dir[mboxId] |
| 521 |
if !ok { |
| 522 |
continue |
| 523 |
} |
| 524 |
info := w.translateMsgInfo(m, dir) |
| 525 |
if indexes != nil { |
| 526 |
i, ok := indexes[mboxId] |
| 527 |
if ok { |
| 528 |
info.Index = &i |
| 529 |
// Set recent on created messages so we |
| 530 |
// get a notification |
| 531 |
if !info.Flags.Has(models.SeenFlag) { |
| 532 |
info.Flags |= models.RecentFlag |
| 533 |
} |
| 534 |
} |
| 535 |
} |
| 536 |
w.w.Infof("message %s added to %q", info.Envelope.MessageId, dir) |
| 537 |
w.w.PostMessage(&types.MessageInfo{ |
| 538 |
Info: info, |
| 539 |
}, nil) |
| 540 |
} |
| 541 |
} |
| 542 |
err = w.cache.PutEmailState(r.State) |
| 543 |
if err != nil { |
| 544 |
w.w.Warnf("PutEmailState: %s", err) |
| 545 |
} |
| 546 |
|
| 547 |
case *jmap.MethodError: |
| 548 |
w.w.Errorf("%s", wrapMethodError(r)) |
| 549 |
} |
| 550 |
} |
| 551 |
} |