organize.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. package email
  2. /*
  3. organize.go
  4. Labels and snoozing, kept locally per ArozOS user.
  5. IMAP keywords would be the natural home for labels, but Gmail and Outlook
  6. do not accept custom keywords over IMAP, so labels and snoozes are stored
  7. here and work the same for every provider. Messages are identified by
  8. account + Message-ID, which survives moving a message between folders;
  9. mail without a Message-ID falls back to folder + UID.
  10. A snoozed message stays where it is on the server; the app hides it until
  11. the snooze ends, then it reappears marked unread.
  12. */
  13. import (
  14. "context"
  15. "errors"
  16. "sort"
  17. "strconv"
  18. "strings"
  19. "github.com/emersion/go-imap/v2"
  20. "github.com/emersion/go-imap/v2/imapclient"
  21. )
  22. // Label is a user-defined, coloured tag.
  23. type Label struct {
  24. ID string `json:"id"`
  25. Name string `json:"name"`
  26. Color string `json:"color"`
  27. }
  28. // localMessage is a labelled or snoozed message with the summary needed to
  29. // list it without asking the server.
  30. type localMessage struct {
  31. Key string `json:"key"`
  32. Labels []string `json:"labels,omitempty"`
  33. Until int64 `json:"until,omitempty"` //Snooze end, unix ms
  34. Summary MessageSummary `json:"summary"`
  35. }
  36. var defaultLabels = []Label{
  37. {ID: "work", Name: "Work", Color: "#3b82f6"},
  38. {ID: "personal", Name: "Personal", Color: "#22c55e"},
  39. {ID: "important", Name: "Important", Color: "#ef4444"},
  40. {ID: "followup", Name: "Follow Up", Color: "#f59e0b"},
  41. {ID: "newsletters", Name: "Newsletters", Color: "#a855f7"},
  42. }
  43. func localKey(accountID string, messageID string, folder string, uid uint32) string {
  44. messageID = strings.ToLower(strings.Trim(strings.TrimSpace(messageID), "<>"))
  45. if messageID != "" {
  46. return accountID + ":mid:" + messageID
  47. }
  48. return accountID + ":uid:" + folder + ":" + strconv.FormatUint(uint64(uid), 10)
  49. }
  50. func summaryKey(summary MessageSummary) string {
  51. return localKey(summary.AccountID, summary.MessageID, summary.Folder, summary.UID)
  52. }
  53. // Labels returns the user's label definitions.
  54. func (m *Manager) Labels(p Principal) []Label {
  55. labels := []Label{}
  56. if m.store.db.KeyExists(tableLabels, p.Username) {
  57. if err := m.store.db.Read(tableLabels, p.Username, &labels); err == nil {
  58. return labels
  59. }
  60. }
  61. return append(labels, defaultLabels...)
  62. }
  63. // SaveLabels replaces the label definitions. Labels removed from the list are
  64. // also removed from every message.
  65. func (m *Manager) SaveLabels(p Principal, labels []Label) ([]Label, error) {
  66. if len(labels) > 60 {
  67. return nil, errors.New("too many labels")
  68. }
  69. cleaned := []Label{}
  70. seen := map[string]bool{}
  71. for _, label := range labels {
  72. label.Name = strings.TrimSpace(label.Name)
  73. if label.Name == "" {
  74. continue
  75. }
  76. if len([]rune(label.Name)) > 40 {
  77. label.Name = string([]rune(label.Name)[:40])
  78. }
  79. if label.ID == "" {
  80. label.ID = randomID(5)
  81. }
  82. if seen[label.ID] {
  83. continue
  84. }
  85. seen[label.ID] = true
  86. if !strings.HasPrefix(label.Color, "#") || len(label.Color) > 9 {
  87. label.Color = "#64748b"
  88. }
  89. cleaned = append(cleaned, label)
  90. }
  91. m.store.mutex.Lock()
  92. defer m.store.mutex.Unlock()
  93. if err := m.store.db.Write(tableLabels, p.Username, cleaned); err != nil {
  94. return nil, err
  95. }
  96. //Strip deleted labels from messages
  97. records, _ := listOwned[localMessage](m.store, tableLabelMap, p.Username)
  98. for _, record := range records {
  99. kept := []string{}
  100. for _, id := range record.Labels {
  101. if seen[id] {
  102. kept = append(kept, id)
  103. }
  104. }
  105. key := ownerKey(p.Username, record.Key)
  106. if len(kept) == 0 {
  107. m.store.db.Delete(tableLabelMap, key)
  108. } else if len(kept) != len(record.Labels) {
  109. record.Labels = kept
  110. m.store.db.Write(tableLabelMap, key, record)
  111. }
  112. }
  113. return cleaned, nil
  114. }
  115. // SetMessageLabels assigns labels to a message.
  116. func (m *Manager) SetMessageLabels(p Principal, summary MessageSummary, labelIDs []string) error {
  117. if _, err := m.account(p, summary.AccountID); err != nil {
  118. return err
  119. }
  120. known := map[string]bool{}
  121. for _, label := range m.Labels(p) {
  122. known[label.ID] = true
  123. }
  124. labels := []string{}
  125. for _, id := range labelIDs {
  126. if known[id] {
  127. labels = append(labels, id)
  128. }
  129. }
  130. m.store.mutex.Lock()
  131. defer m.store.mutex.Unlock()
  132. key := summaryKey(summary)
  133. dbKey := ownerKey(p.Username, key)
  134. if len(labels) == 0 {
  135. if m.store.db.KeyExists(tableLabelMap, dbKey) {
  136. return m.store.db.Delete(tableLabelMap, dbKey)
  137. }
  138. return nil
  139. }
  140. summary.Labels = labels
  141. summary.Preview = previewText(summary.Preview, 180)
  142. return m.store.db.Write(tableLabelMap, dbKey, localMessage{Key: key, Labels: labels, Summary: summary})
  143. }
  144. // LabelMessages lists the messages carrying a label, newest first.
  145. func (m *Manager) LabelMessages(p Principal, labelID string) ([]MessageSummary, error) {
  146. records, err := listOwned[localMessage](m.store, tableLabelMap, p.Username)
  147. if err != nil {
  148. return nil, err
  149. }
  150. results := []MessageSummary{}
  151. for _, record := range records {
  152. for _, id := range record.Labels {
  153. if id == labelID {
  154. summary := record.Summary
  155. summary.Labels = record.Labels
  156. results = append(results, summary)
  157. break
  158. }
  159. }
  160. }
  161. sort.Slice(results, func(i, j int) bool { return results[i].Received > results[j].Received })
  162. m.applyLocalState(p, results)
  163. return results, nil
  164. }
  165. // Snooze hides a message until a time (unix ms).
  166. func (m *Manager) Snooze(p Principal, summary MessageSummary, until int64) error {
  167. if _, err := m.account(p, summary.AccountID); err != nil {
  168. return err
  169. }
  170. if until <= m.now().UnixMilli() {
  171. return errors.New("choose a time in the future")
  172. }
  173. key := summaryKey(summary)
  174. summary.Preview = previewText(summary.Preview, 180)
  175. m.store.mutex.Lock()
  176. defer m.store.mutex.Unlock()
  177. return m.store.db.Write(tableSnooze, ownerKey(p.Username, key), localMessage{Key: key, Until: until, Summary: summary})
  178. }
  179. // Unsnooze brings a snoozed message back now.
  180. func (m *Manager) Unsnooze(p Principal, summary MessageSummary) error {
  181. dbKey := ownerKey(p.Username, summaryKey(summary))
  182. m.store.mutex.Lock()
  183. defer m.store.mutex.Unlock()
  184. if m.store.db.KeyExists(tableSnooze, dbKey) {
  185. return m.store.db.Delete(tableSnooze, dbKey)
  186. }
  187. return nil
  188. }
  189. // SnoozedMessages lists snoozed mail, soonest first.
  190. func (m *Manager) SnoozedMessages(p Principal) ([]MessageSummary, error) {
  191. m.wakeSnoozed(p)
  192. records, err := listOwned[localMessage](m.store, tableSnooze, p.Username)
  193. if err != nil {
  194. return nil, err
  195. }
  196. sort.Slice(records, func(i, j int) bool { return records[i].Until < records[j].Until })
  197. results := []MessageSummary{}
  198. for _, record := range records {
  199. summary := record.Summary
  200. summary.SnoozedUntil = record.Until
  201. results = append(results, summary)
  202. }
  203. m.applyLocalState(p, results)
  204. return results, nil
  205. }
  206. // wakeSnoozed ends expired snoozes and marks those messages unread so they
  207. // stand out when they come back.
  208. func (m *Manager) wakeSnoozed(p Principal) {
  209. records, err := listOwned[localMessage](m.store, tableSnooze, p.Username)
  210. if err != nil {
  211. return
  212. }
  213. now := m.now().UnixMilli()
  214. woken := map[string][]MessageSummary{}
  215. m.store.mutex.Lock()
  216. for _, record := range records {
  217. if record.Until > now {
  218. continue
  219. }
  220. m.store.db.Delete(tableSnooze, ownerKey(p.Username, record.Key))
  221. woken[record.Summary.AccountID] = append(woken[record.Summary.AccountID], record.Summary)
  222. }
  223. m.store.mutex.Unlock()
  224. for accountID, summaries := range woken {
  225. account, err := m.account(p, accountID)
  226. if err != nil {
  227. continue
  228. }
  229. go func(account *Account, summaries []MessageSummary) {
  230. m.withIMAP(context.Background(), p, account, func(c *imapclient.Client) error {
  231. byFolder := map[string][]imap.UID{}
  232. for _, summary := range summaries {
  233. byFolder[summary.Folder] = append(byFolder[summary.Folder], imap.UID(summary.UID))
  234. }
  235. for folder, uids := range byFolder {
  236. if _, err := selectFolder(c, folder); err != nil {
  237. continue
  238. }
  239. c.Store(imap.UIDSetNum(uids...), &imap.StoreFlags{Op: imap.StoreFlagsDel, Silent: true, Flags: []imap.Flag{imap.FlagSeen}}, nil).Close()
  240. }
  241. return nil
  242. })
  243. }(account, summaries)
  244. }
  245. }
  246. // applyLocalState attaches labels and snooze times to listed messages.
  247. func (m *Manager) applyLocalState(p Principal, summaries []MessageSummary) {
  248. if len(summaries) == 0 {
  249. return
  250. }
  251. labelled, _ := listOwned[localMessage](m.store, tableLabelMap, p.Username)
  252. snoozed, _ := listOwned[localMessage](m.store, tableSnooze, p.Username)
  253. if len(labelled) == 0 && len(snoozed) == 0 {
  254. return
  255. }
  256. labels := map[string][]string{}
  257. for _, record := range labelled {
  258. labels[record.Key] = record.Labels
  259. }
  260. until := map[string]int64{}
  261. for _, record := range snoozed {
  262. until[record.Key] = record.Until
  263. }
  264. for i := range summaries {
  265. key := summaryKey(summaries[i])
  266. if assigned, ok := labels[key]; ok {
  267. summaries[i].Labels = assigned
  268. }
  269. if end, ok := until[key]; ok {
  270. summaries[i].SnoozedUntil = end
  271. }
  272. }
  273. }
  274. // forgetLocalState drops folder+UID keyed records of messages that moved or
  275. // were deleted; Message-ID keyed records stay valid.
  276. func (m *Manager) forgetLocalState(p Principal, accountID string, folder string, uids []uint32) {
  277. m.store.mutex.Lock()
  278. defer m.store.mutex.Unlock()
  279. for _, uid := range uids {
  280. key := ownerKey(p.Username, localKey(accountID, "", folder, uid))
  281. for _, table := range []string{tableLabelMap, tableSnooze} {
  282. if m.store.db.KeyExists(table, key) {
  283. m.store.db.Delete(table, key)
  284. }
  285. }
  286. }
  287. }
  288. // LocatedMessage is where a message currently lives.
  289. type LocatedMessage struct {
  290. Folder string `json:"folder"`
  291. UID uint32 `json:"uid"`
  292. }
  293. // LocateMessage finds a message by Message-ID after it moved, searching the
  294. // likely folders first.
  295. func (m *Manager) LocateMessage(ctx context.Context, p Principal, accountID string, messageID string, hint string) (*LocatedMessage, error) {
  296. messageID = strings.Trim(strings.TrimSpace(messageID), "<>")
  297. if messageID == "" {
  298. return nil, ErrMessageNotFound
  299. }
  300. account, err := m.account(p, accountID)
  301. if err != nil {
  302. return nil, err
  303. }
  304. key := poolKey(p.Username, account.ID)
  305. var located *LocatedMessage
  306. err = m.withIMAP(ctx, p, account, func(c *imapclient.Client) error {
  307. folders, err := m.foldersQuick(c, key)
  308. if err != nil {
  309. return err
  310. }
  311. order := []string{}
  312. seen := map[string]bool{}
  313. add := func(name string) {
  314. if name != "" && !seen[name] {
  315. seen[name] = true
  316. order = append(order, name)
  317. }
  318. }
  319. add(hint)
  320. add("INBOX")
  321. for _, role := range []string{RoleAll, RoleArchive, RoleSent, RoleDrafts, RoleJunk, RoleTrash} {
  322. if folder, ok := folderByRole(folders, role); ok {
  323. add(folder.Name)
  324. }
  325. }
  326. for _, folder := range folders {
  327. if folder.Selectable && len(order) < 40 {
  328. add(folder.Name)
  329. }
  330. }
  331. criteria := &imap.SearchCriteria{Header: []imap.SearchCriteriaHeaderField{{Key: "Message-ID", Value: messageID}}}
  332. for _, folder := range order {
  333. if _, err := selectFolder(c, folder); err != nil {
  334. continue
  335. }
  336. data, err := c.UIDSearch(criteria, nil).Wait()
  337. if err != nil {
  338. continue
  339. }
  340. if uids := data.AllUIDs(); len(uids) > 0 {
  341. located = &LocatedMessage{Folder: folder, UID: uint32(uids[len(uids)-1])}
  342. return nil
  343. }
  344. }
  345. return ErrMessageNotFound
  346. })
  347. return located, err
  348. }