all repos — mx @ 4ae2f6e2c20f22ebb6b3d478313dce9a89c870e6

work in progress MUA

maildir/message.go (view raw)

 1package maildir
 2
 3import (
 4	"bufio"
 5	"fmt"
 6	"io"
 7	"mime"
 8	"net/mail"
 9
10	"github.com/emersion/go-maildir"
11)
12
13// A lot of this code was borrowed from aerc/worker/maildir/message.go
14
15type Message struct {
16	Dir maildir.Dir
17	Key string
18}
19
20func (m Message) NewReader() (io.Reader, error) {
21	f, err := m.Dir.Open(m.Key)
22	if err != nil {
23		return nil, err
24	}
25	return bufio.NewReader(f), nil
26}
27
28// Flags fetches the set of flags currently applied to the message.
29func (m Message) Flags() ([]maildir.Flag, error) {
30	return m.Dir.Flags(m.Key)
31}
32
33// SetFlags replaces the message's flags with a new set.
34func (m Message) SetFlags(flags []maildir.Flag) error {
35	return m.Dir.SetFlags(m.Key, flags)
36}
37
38// SetOneFlag enables or disables a single message flag on the message.
39func (m Message) SetOneFlag(flag maildir.Flag, enable bool) error {
40	flags, err := m.Flags()
41	if err != nil {
42		return fmt.Errorf("error: could not read previous flags: %v", err)
43	}
44	if enable {
45		flags = append(flags, flag)
46		return m.SetFlags(flags)
47	}
48	var newFlags []maildir.Flag
49	for _, oldFlag := range flags {
50		if oldFlag != flag {
51			newFlags = append(newFlags, oldFlag)
52		}
53	}
54	return m.SetFlags(newFlags)
55}
56
57// MarkReplied either adds or removes the maildir.FlagReplied flag from the
58// message.
59func (m Message) MarkReplied(answered bool) error {
60	return m.SetOneFlag(maildir.FlagReplied, answered)
61}
62
63// Remove deletes the email immediately.
64func (m Message) Remove() error {
65	return m.Dir.Remove(m.Key)
66}
67
68func decodeMime(str string) (string, error) {
69	dec := new(mime.WordDecoder)
70	return dec.DecodeHeader(str)
71}
72
73func (m Message) GetHeader(h string) (string, error) {
74	r, err := m.NewReader()
75	msg, err := mail.ReadMessage(r)
76	if err != nil {
77		return "", err
78	}
79
80	decodedHeader, err := decodeMime(msg.Header.Get(h))
81	return decodedHeader, err
82}
83
84var FlagMap = map[maildir.Flag]string{
85	maildir.FlagDraft:   "D",
86	maildir.FlagSeen:    "S",
87	maildir.FlagReplied: "R",
88	maildir.FlagTrashed: "T",
89}