actions.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. package email
  2. /*
  3. actions.go
  4. Changing messages: flags, move / copy, delete, archive, junk, mark all
  5. read, empty folder, and appending new messages (drafts, sent copies,
  6. imported .eml files).
  7. Delete follows what users expect from every mainstream client: outside the
  8. Trash it moves to Trash, inside Trash (or Junk) it deletes for good.
  9. Archive on Gmail moves to "All Mail", which is how Gmail archives over IMAP.
  10. */
  11. import (
  12. "context"
  13. "errors"
  14. "strings"
  15. "time"
  16. "github.com/emersion/go-imap/v2"
  17. "github.com/emersion/go-imap/v2/imapclient"
  18. )
  19. // Flag names accepted by SetFlag.
  20. var flagNames = map[string]imap.Flag{
  21. "seen": imap.FlagSeen,
  22. "flagged": imap.FlagFlagged,
  23. "answered": imap.FlagAnswered,
  24. "forwarded": imap.FlagForwarded,
  25. "draft": imap.FlagDraft,
  26. }
  27. // ActionResult reports what a bulk action did.
  28. type ActionResult struct {
  29. Count int `json:"count"`
  30. Destination string `json:"destination,omitempty"`
  31. Permanent bool `json:"permanent,omitempty"`
  32. }
  33. func uidSetOf(uids []uint32) (imap.UIDSet, error) {
  34. if len(uids) == 0 {
  35. return nil, errors.New("no messages selected")
  36. }
  37. set := imap.UIDSet{}
  38. for _, uid := range uids {
  39. if uid == 0 {
  40. return nil, errors.New("invalid message id")
  41. }
  42. set.AddNum(imap.UID(uid))
  43. }
  44. return set, nil
  45. }
  46. // SetFlag adds or removes a flag on messages.
  47. func (m *Manager) SetFlag(ctx context.Context, p Principal, accountID string, folder string, uids []uint32, flag string, value bool) (*ActionResult, error) {
  48. imapFlag, ok := flagNames[strings.ToLower(flag)]
  49. if !ok {
  50. return nil, errors.New("unknown flag " + flag)
  51. }
  52. set, err := uidSetOf(uids)
  53. if err != nil {
  54. return nil, err
  55. }
  56. account, err := m.account(p, accountID)
  57. if err != nil {
  58. return nil, err
  59. }
  60. err = m.withIMAP(ctx, p, account, func(c *imapclient.Client) error {
  61. if _, err := selectFolder(c, folder); err != nil {
  62. return err
  63. }
  64. op := imap.StoreFlagsAdd
  65. if !value {
  66. op = imap.StoreFlagsDel
  67. }
  68. return c.Store(set, &imap.StoreFlags{Op: op, Silent: true, Flags: []imap.Flag{imapFlag}}, nil).Close()
  69. })
  70. if err != nil {
  71. return nil, err
  72. }
  73. return &ActionResult{Count: len(uids)}, nil
  74. }
  75. // Move moves messages to another folder of the same account.
  76. func (m *Manager) Move(ctx context.Context, p Principal, accountID string, folder string, uids []uint32, destination string) (*ActionResult, error) {
  77. if destination == "" || destination == folder {
  78. return nil, errors.New("choose a different folder")
  79. }
  80. set, err := uidSetOf(uids)
  81. if err != nil {
  82. return nil, err
  83. }
  84. account, err := m.account(p, accountID)
  85. if err != nil {
  86. return nil, err
  87. }
  88. err = m.withIMAP(ctx, p, account, func(c *imapclient.Client) error {
  89. if _, err := selectFolder(c, folder); err != nil {
  90. return err
  91. }
  92. _, err := c.Move(set, destination).Wait()
  93. return err
  94. })
  95. if err != nil {
  96. return nil, err
  97. }
  98. m.forgetLocalState(p, account.ID, folder, uids)
  99. return &ActionResult{Count: len(uids), Destination: destination}, nil
  100. }
  101. // Copy copies messages to another folder of the same account.
  102. func (m *Manager) Copy(ctx context.Context, p Principal, accountID string, folder string, uids []uint32, destination string) (*ActionResult, error) {
  103. set, err := uidSetOf(uids)
  104. if err != nil {
  105. return nil, err
  106. }
  107. account, err := m.account(p, accountID)
  108. if err != nil {
  109. return nil, err
  110. }
  111. err = m.withIMAP(ctx, p, account, func(c *imapclient.Client) error {
  112. if _, err := selectFolder(c, folder); err != nil {
  113. return err
  114. }
  115. _, err := c.Copy(set, destination).Wait()
  116. return err
  117. })
  118. if err != nil {
  119. return nil, err
  120. }
  121. return &ActionResult{Count: len(uids), Destination: destination}, nil
  122. }
  123. // MoveToRole moves messages to the folder playing a role (trash, archive,
  124. // junk, inbox), creating that folder when the server has none.
  125. func (m *Manager) MoveToRole(ctx context.Context, p Principal, accountID string, folder string, uids []uint32, role string) (*ActionResult, error) {
  126. set, err := uidSetOf(uids)
  127. if err != nil {
  128. return nil, err
  129. }
  130. account, err := m.account(p, accountID)
  131. if err != nil {
  132. return nil, err
  133. }
  134. key := poolKey(p.Username, account.ID)
  135. result := &ActionResult{Count: len(uids)}
  136. err = m.withIMAP(ctx, p, account, func(c *imapclient.Client) error {
  137. folders, err := m.foldersQuick(c, key)
  138. if err != nil {
  139. return err
  140. }
  141. currentRole := roleOf(folders, folder)
  142. var destination string
  143. switch role {
  144. case RoleInbox:
  145. destination = "INBOX"
  146. case RoleArchive:
  147. //Gmail archives by moving out of the inbox into All Mail
  148. if archive, ok := folderByRole(folders, RoleArchive); ok {
  149. destination = archive.Name
  150. } else if all, ok := folderByRole(folders, RoleAll); ok {
  151. destination = all.Name
  152. } else {
  153. destination, err = m.ensureRoleFolder(c, key, RoleArchive)
  154. }
  155. default:
  156. destination, err = m.ensureRoleFolder(c, key, role)
  157. }
  158. if err != nil {
  159. return err
  160. }
  161. if destination == folder || (role == RoleArchive && (currentRole == RoleAll || currentRole == RoleArchive)) {
  162. return errors.New("the messages are already there")
  163. }
  164. if _, err := selectFolder(c, folder); err != nil {
  165. return err
  166. }
  167. if role == RoleJunk || (role == RoleInbox && currentRole == RoleJunk) {
  168. //Train the provider's spam filter where keywords are supported
  169. junkFlag, otherFlag := imap.FlagJunk, imap.FlagNotJunk
  170. if role == RoleInbox {
  171. junkFlag, otherFlag = imap.FlagNotJunk, imap.FlagJunk
  172. }
  173. c.Store(set, &imap.StoreFlags{Op: imap.StoreFlagsAdd, Silent: true, Flags: []imap.Flag{junkFlag}}, nil).Close()
  174. c.Store(set, &imap.StoreFlags{Op: imap.StoreFlagsDel, Silent: true, Flags: []imap.Flag{otherFlag}}, nil).Close()
  175. }
  176. _, err = c.Move(set, destination).Wait()
  177. result.Destination = destination
  178. return err
  179. })
  180. if err != nil {
  181. return nil, err
  182. }
  183. m.forgetLocalState(p, account.ID, folder, uids)
  184. return result, nil
  185. }
  186. // Delete moves messages to Trash, or removes them for good when they already
  187. // are in Trash / Junk or permanent is set.
  188. func (m *Manager) Delete(ctx context.Context, p Principal, accountID string, folder string, uids []uint32, permanent bool) (*ActionResult, error) {
  189. set, err := uidSetOf(uids)
  190. if err != nil {
  191. return nil, err
  192. }
  193. account, err := m.account(p, accountID)
  194. if err != nil {
  195. return nil, err
  196. }
  197. key := poolKey(p.Username, account.ID)
  198. result := &ActionResult{Count: len(uids)}
  199. err = m.withIMAP(ctx, p, account, func(c *imapclient.Client) error {
  200. folders, err := m.foldersQuick(c, key)
  201. if err != nil {
  202. return err
  203. }
  204. currentRole := roleOf(folders, folder)
  205. if !permanent && currentRole != RoleTrash && currentRole != RoleJunk {
  206. trash, err := m.ensureRoleFolder(c, key, RoleTrash)
  207. if err != nil {
  208. //Never fall back to a silent permanent delete
  209. return errors.New("no Trash folder is available on this account (" + err.Error() + "), delete permanently instead")
  210. }
  211. if trash != folder {
  212. if _, err := selectFolder(c, folder); err != nil {
  213. return err
  214. }
  215. _, err = c.Move(set, trash).Wait()
  216. result.Destination = trash
  217. return err
  218. }
  219. }
  220. result.Permanent = true
  221. if _, err := selectFolder(c, folder); err != nil {
  222. return err
  223. }
  224. return expungeUIDs(c, set)
  225. })
  226. if err != nil {
  227. return nil, err
  228. }
  229. m.forgetLocalState(p, account.ID, folder, uids)
  230. return result, nil
  231. }
  232. // expungeUIDs permanently removes exactly the given messages when the server
  233. // supports UIDPLUS; otherwise EXPUNGE removes every \Deleted message.
  234. func expungeUIDs(c *imapclient.Client, set imap.UIDSet) error {
  235. if err := c.Store(set, &imap.StoreFlags{Op: imap.StoreFlagsAdd, Silent: true, Flags: []imap.Flag{imap.FlagDeleted}}, nil).Close(); err != nil {
  236. return err
  237. }
  238. if c.Caps().Has(imap.CapUIDPlus) || c.Caps().Has(imap.CapIMAP4rev2) {
  239. return c.UIDExpunge(set).Close()
  240. }
  241. return c.Expunge().Close()
  242. }
  243. // MarkAllRead marks every unread message of a folder as read.
  244. func (m *Manager) MarkAllRead(ctx context.Context, p Principal, accountID string, folder string) (*ActionResult, error) {
  245. account, err := m.account(p, accountID)
  246. if err != nil {
  247. return nil, err
  248. }
  249. result := &ActionResult{}
  250. err = m.withIMAP(ctx, p, account, func(c *imapclient.Client) error {
  251. if _, err := selectFolder(c, folder); err != nil {
  252. return err
  253. }
  254. data, err := c.UIDSearch(&imap.SearchCriteria{NotFlag: []imap.Flag{imap.FlagSeen}}, nil).Wait()
  255. if err != nil {
  256. return err
  257. }
  258. uids := data.AllUIDs()
  259. if len(uids) == 0 {
  260. return nil
  261. }
  262. result.Count = len(uids)
  263. return c.Store(imap.UIDSetNum(uids...), &imap.StoreFlags{Op: imap.StoreFlagsAdd, Silent: true, Flags: []imap.Flag{imap.FlagSeen}}, nil).Close()
  264. })
  265. if err != nil {
  266. return nil, err
  267. }
  268. return result, nil
  269. }
  270. // EmptyFolder permanently deletes every message of the Trash or Junk folder.
  271. func (m *Manager) EmptyFolder(ctx context.Context, p Principal, accountID string, folder string) (*ActionResult, error) {
  272. account, err := m.account(p, accountID)
  273. if err != nil {
  274. return nil, err
  275. }
  276. key := poolKey(p.Username, account.ID)
  277. result := &ActionResult{Permanent: true}
  278. err = m.withIMAP(ctx, p, account, func(c *imapclient.Client) error {
  279. folders, err := m.foldersQuick(c, key)
  280. if err != nil {
  281. return err
  282. }
  283. if role := roleOf(folders, folder); role != RoleTrash && role != RoleJunk {
  284. return errors.New("only the Trash and Junk folders can be emptied")
  285. }
  286. if _, err := selectFolder(c, folder); err != nil {
  287. return err
  288. }
  289. data, err := c.UIDSearch(&imap.SearchCriteria{}, nil).Wait()
  290. if err != nil {
  291. return err
  292. }
  293. uids := data.AllUIDs()
  294. result.Count = len(uids)
  295. if len(uids) == 0 {
  296. return nil
  297. }
  298. return expungeUIDs(c, imap.UIDSetNum(uids...))
  299. })
  300. if err != nil {
  301. return nil, err
  302. }
  303. return result, nil
  304. }
  305. // appendMessage stores a raw message in a folder and returns its UID when
  306. // the server reports it (UIDPLUS), otherwise looks it up by Message-ID.
  307. func appendMessage(c *imapclient.Client, folder string, raw []byte, flags []imap.Flag, date time.Time, messageID string) (uint32, error) {
  308. options := &imap.AppendOptions{Flags: flags}
  309. if !date.IsZero() {
  310. options.Time = date
  311. }
  312. command := c.Append(folder, int64(len(raw)), options)
  313. if _, err := command.Write(raw); err != nil {
  314. command.Close()
  315. return 0, err
  316. }
  317. if err := command.Close(); err != nil {
  318. return 0, err
  319. }
  320. data, err := command.Wait()
  321. if err != nil {
  322. return 0, err
  323. }
  324. if data != nil && data.UID != 0 {
  325. return uint32(data.UID), nil
  326. }
  327. if messageID == "" {
  328. return 0, nil
  329. }
  330. if _, err := selectFolder(c, folder); err != nil {
  331. return 0, nil
  332. }
  333. found, err := c.UIDSearch(&imap.SearchCriteria{Header: []imap.SearchCriteriaHeaderField{{Key: "Message-ID", Value: messageID}}}, nil).Wait()
  334. if err != nil {
  335. return 0, nil
  336. }
  337. uids := found.AllUIDs()
  338. if len(uids) == 0 {
  339. return 0, nil
  340. }
  341. return uint32(uids[len(uids)-1]), nil
  342. }
  343. // ImportMessage appends a raw RFC 822 message (an .eml file) to a folder.
  344. func (m *Manager) ImportMessage(ctx context.Context, p Principal, accountID string, folder string, raw []byte) (uint32, error) {
  345. if len(raw) == 0 {
  346. return 0, errors.New("the message is empty")
  347. }
  348. if len(raw) > maxRawMessage {
  349. return 0, ErrTooLarge
  350. }
  351. account, err := m.account(p, accountID)
  352. if err != nil {
  353. return 0, err
  354. }
  355. header := parseHeaderBytes(raw)
  356. date, _ := header.Date()
  357. messageID, _ := header.MessageID()
  358. var uid uint32
  359. err = m.withIMAP(ctx, p, account, func(c *imapclient.Client) error {
  360. var err error
  361. uid, err = appendMessage(c, folder, raw, []imap.Flag{imap.FlagSeen}, date, messageID)
  362. return err
  363. })
  364. return uid, err
  365. }