|
| 1 | +package main |
| 2 | + |
| 3 | +// The most arcane part of the whole thing, because apparently, |
| 4 | +// to parse email with golang you need to actually know the IMAP standard |
| 5 | +// by heart, because none of this is properly documented. |
| 6 | +// |
| 7 | +// Oh well. |
| 8 | + |
| 9 | +import ( |
| 10 | + "bytes" |
| 11 | + "fmt" |
| 12 | + "io" |
| 13 | + "log" |
| 14 | + "strings" |
| 15 | + "time" |
| 16 | + |
| 17 | + "github.com/emersion/go-imap/v2" |
| 18 | + "github.com/emersion/go-imap/v2/imapclient" |
| 19 | + "github.com/emersion/go-message/mail" |
| 20 | + "golang.org/x/net/html/charset" |
| 21 | +) |
| 22 | + |
| 23 | +// Because the actual types are truly mindbending, we consolidate the interesting |
| 24 | +// parts of the email into a simpler structure before handing that over to the parsers. |
| 25 | +type NotificationEmail struct { |
| 26 | + From string |
| 27 | + Subj string |
| 28 | + Date time.Time |
| 29 | + Text string |
| 30 | + Html string |
| 31 | +} |
| 32 | + |
| 33 | +// The annoying part: taking the message apart into its html and txt bodies. |
| 34 | +// It is my intuition, (the documentation is exceedingly lacking) |
| 35 | +// that the BodySection[] map always contains exactly one element |
| 36 | +// when the message was downloaded with Collect() as above. |
| 37 | +// Whose key is a struct. |
| 38 | +// And bizarrely, it's not a nil struct. |
| 39 | +// So we have to curse to high heavens and loop through sections. |
| 40 | +func parseEmail(message *imapclient.FetchMessageBuffer) *NotificationEmail { |
| 41 | + |
| 42 | + notification := NotificationEmail{ |
| 43 | + From: message.Envelope.From[0].Addr(), |
| 44 | + Subj: message.Envelope.Subject, |
| 45 | + Date: message.Envelope.Date, |
| 46 | + } |
| 47 | + |
| 48 | + for _, bodyPart := range message.BodySection { |
| 49 | + |
| 50 | + mr, err := mail.CreateReader(bytes.NewReader(bodyPart)) |
| 51 | + if err != nil { |
| 52 | + // Looking at the createreader code, if there was |
| 53 | + // an error, it's probably a borked message anyway. |
| 54 | + return nil |
| 55 | + } |
| 56 | + |
| 57 | + partLoop: |
| 58 | + for { |
| 59 | + p, err := mr.NextPart() |
| 60 | + if err == io.EOF { |
| 61 | + break |
| 62 | + } else if err != nil { |
| 63 | + log.Printf("failed to read message part: %v", err) |
| 64 | + return nil |
| 65 | + } |
| 66 | + |
| 67 | + // We ignore attachments and stuff... |
| 68 | + switch h := p.Header.(type) { |
| 69 | + case *mail.InlineHeader: |
| 70 | + chunkBytes, _ := io.ReadAll(p.Body) |
| 71 | + contentType, contentTypeParams, err := h.ContentType() |
| 72 | + if err != nil { |
| 73 | + continue partLoop |
| 74 | + } |
| 75 | + |
| 76 | + // In case we got utf-8, that's where it ends. |
| 77 | + text := string(chunkBytes) |
| 78 | + |
| 79 | + // But encodings that are not utf-8 should be converted to utf-8. |
| 80 | + // We're assuming they didn't lie to us. (they can) |
| 81 | + cs := contentTypeParams["charset"] |
| 82 | + if strings.ToUpper(cs) != "UTF-8" { |
| 83 | + enc, _, certain := charset.DetermineEncoding(chunkBytes, h.Get("Content-Type")) |
| 84 | + if certain && enc != nil { |
| 85 | + decodedText, err := enc.NewDecoder().Bytes(chunkBytes) |
| 86 | + if err != nil { |
| 87 | + log.Printf("failed to decode message, skipping.") |
| 88 | + continue partLoop |
| 89 | + } |
| 90 | + text = string(decodedText) |
| 91 | + } |
| 92 | + } |
| 93 | + |
| 94 | + switch contentType { |
| 95 | + case "text/plain": |
| 96 | + notification.Text = text |
| 97 | + case "text/html": |
| 98 | + notification.Html = text |
| 99 | + } |
| 100 | + |
| 101 | + } |
| 102 | + } |
| 103 | + } |
| 104 | + return ¬ification |
| 105 | +} |
| 106 | + |
| 107 | +// Reach into the IMAP server and ask it for all unread emails matching a certain From address. |
| 108 | +func fetchMail(client *imapclient.Client, fromAddress string) []*NotificationEmail { |
| 109 | + |
| 110 | + searchResult, err := client.Search( |
| 111 | + &imap.SearchCriteria{ |
| 112 | + Header: []imap.SearchCriteriaHeaderField{ |
| 113 | + {Key: "From", Value: fromAddress}, |
| 114 | + }, |
| 115 | + NotFlag: []imap.Flag{ |
| 116 | + "\\Seen", |
| 117 | + }}, &imap.SearchOptions{}).Wait() |
| 118 | + if err != nil { |
| 119 | + log.Fatalf("search failed: %v", err) |
| 120 | + } |
| 121 | + |
| 122 | + fetchOptions := &imap.FetchOptions{ |
| 123 | + Flags: true, |
| 124 | + Envelope: true, |
| 125 | + BodyStructure: &imap.FetchItemBodyStructure{Extended: true}, |
| 126 | + BodySection: []*imap.FetchItemBodySection{{}}, |
| 127 | + } |
| 128 | + |
| 129 | + messages, err := client.Fetch(searchResult.All, fetchOptions).Collect() |
| 130 | + if err != nil { |
| 131 | + log.Fatalf("failed to fetch: %v", err) |
| 132 | + } |
| 133 | + |
| 134 | + log.Printf("unread messages from %s: %d", fromAddress, len(messages)) |
| 135 | + |
| 136 | + parsedMessages := make([]*NotificationEmail, 0, len(messages)) |
| 137 | + |
| 138 | + for _, message := range messages { |
| 139 | + result := parseEmail(message) |
| 140 | + if result != nil { |
| 141 | + parsedMessages = append(parsedMessages, result) |
| 142 | + } |
| 143 | + } |
| 144 | + return parsedMessages |
| 145 | +} |
| 146 | + |
| 147 | +// Log into the IMAP server, fetch all interesting emails, |
| 148 | +// and produce a slice of structures containing the important parts we're looking for. |
| 149 | +func acquireEmail(cfg NotifyRSSConfig) []*NotificationEmail { |
| 150 | + var err error |
| 151 | + |
| 152 | + dialTone := fmt.Sprintf("%s:%d", cfg.Mail.Host, cfg.Mail.Port) |
| 153 | + var client *imapclient.Client |
| 154 | + switch strings.ToLower(cfg.Mail.Connection) { |
| 155 | + case "ssl": |
| 156 | + client, err = imapclient.DialTLS(dialTone, nil) |
| 157 | + case "starttls": |
| 158 | + client, err = imapclient.DialStartTLS(dialTone, nil) |
| 159 | + case "plain": |
| 160 | + client, err = imapclient.DialInsecure(dialTone, nil) |
| 161 | + default: |
| 162 | + log.Fatalf("ssl parameter must be one of 'plain', 'ssl', 'starttls'") |
| 163 | + } |
| 164 | + if err != nil { |
| 165 | + log.Fatalf("connection failure: %v", err) |
| 166 | + } |
| 167 | + defer client.Close() |
| 168 | + |
| 169 | + if err := client.Login(cfg.Mail.User, cfg.Mail.Pass).Wait(); err != nil { |
| 170 | + log.Fatalf("failed to login: %v", err) |
| 171 | + } |
| 172 | + |
| 173 | + mailbox, err := client.Select(cfg.Mail.Folder, &imap.SelectOptions{ReadOnly: true}).Wait() |
| 174 | + if err != nil { |
| 175 | + log.Fatalf("failed to reach %s: %v", cfg.Mail.Folder, err) |
| 176 | + } |
| 177 | + |
| 178 | + log.Printf("%s contains %v messages", cfg.Mail.Folder, mailbox.NumMessages) |
| 179 | + |
| 180 | + var notifications []*NotificationEmail |
| 181 | + |
| 182 | + if mailbox.NumMessages > 0 { |
| 183 | + for _, notifier := range SupportedNotifiers { |
| 184 | + notifications = append(notifications, fetchMail(client, notifier.From)...) |
| 185 | + } |
| 186 | + } |
| 187 | + |
| 188 | + if err := client.Logout().Wait(); err != nil { |
| 189 | + log.Fatalf("failed to logout: %v", err) |
| 190 | + } |
| 191 | + |
| 192 | + return notifications |
| 193 | +} |
0 commit comments