1package main
2
3import (
4 "archive/tar"
5 "bytes"
6 "compress/gzip"
7 "encoding/base64"
8 "encoding/json"
9 "fmt"
10 "io"
11 "log"
12 "net/http"
13 "os"
14 "os/exec"
15 "path/filepath"
16 "regexp"
17 "runtime"
18 "strings"
19 "sync"
20 "time"
21
22 tea "github.com/charmbracelet/bubbletea"
23 "github.com/floatpane/matcha/config"
24 "github.com/floatpane/matcha/fetcher"
25 "github.com/floatpane/matcha/sender"
26 "github.com/floatpane/matcha/tui"
27 "github.com/google/uuid"
28 "github.com/yuin/goldmark"
29 "github.com/yuin/goldmark/renderer/html"
30)
31
32const (
33 initialEmailLimit = 20
34 paginationLimit = 20
35)
36
37// Version variables are injected by the build (GoReleaser ldflags).
38// They default to "dev" when not set by the build system.
39var (
40 version = "dev"
41 commit = ""
42 date = ""
43)
44
45// UpdateAvailableMsg is sent into the TUI when a newer release is detected.
46type UpdateAvailableMsg struct {
47 Latest string
48 Current string
49}
50
51// internal struct for parsing GitHub release JSON.
52type githubRelease struct {
53 TagName string `json:"tag_name"`
54 Assets []struct {
55 Name string `json:"name"`
56 BrowserDownloadURL string `json:"browser_download_url"`
57 } `json:"assets"`
58}
59
60type mainModel struct {
61 current tea.Model
62 previousModel tea.Model
63 config *config.Config
64 emails []fetcher.Email
65 emailsByAcct map[string][]fetcher.Email
66 sentEmails []fetcher.Email
67 sentByAcct map[string][]fetcher.Email
68 trashEmails []fetcher.Email
69 trashByAcct map[string][]fetcher.Email
70 archiveEmails []fetcher.Email
71 archiveByAcct map[string][]fetcher.Email
72 inbox *tui.Inbox
73 sentInbox *tui.Inbox
74 trashArchive *tui.TrashArchive
75 width int
76 height int
77 err error
78}
79
80func newInitialModel(cfg *config.Config) *mainModel {
81 initialModel := &mainModel{
82 emailsByAcct: make(map[string][]fetcher.Email),
83 sentByAcct: make(map[string][]fetcher.Email),
84 trashByAcct: make(map[string][]fetcher.Email),
85 archiveByAcct: make(map[string][]fetcher.Email),
86 }
87
88 if cfg == nil || !cfg.HasAccounts() {
89 initialModel.current = tui.NewLogin()
90 } else {
91 initialModel.current = tui.NewChoice()
92 initialModel.config = cfg
93 }
94 return initialModel
95}
96
97func (m *mainModel) Init() tea.Cmd {
98 return tea.Batch(m.current.Init(), checkForUpdatesCmd())
99}
100
101func (m *mainModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
102 var cmd tea.Cmd
103 var cmds []tea.Cmd
104
105 m.current, cmd = m.current.Update(msg)
106 cmds = append(cmds, cmd)
107
108 switch msg := msg.(type) {
109 case tea.WindowSizeMsg:
110 m.width = msg.Width
111 m.height = msg.Height
112 return m, nil
113
114 case tea.KeyMsg:
115 if msg.String() == "ctrl+c" {
116 return m, tea.Quit
117 }
118 if msg.String() == "esc" {
119 switch m.current.(type) {
120 case *tui.FilePicker:
121 return m, func() tea.Msg { return tui.CancelFilePickerMsg{} }
122 case *tui.Inbox, *tui.Login, *tui.TrashArchive:
123 m.current = tui.NewChoice()
124 return m, m.current.Init()
125 }
126 }
127
128 case tui.BackToInboxMsg:
129 if m.inbox != nil {
130 m.current = m.inbox
131 } else {
132 m.current = tui.NewChoice()
133 }
134 return m, nil
135
136 case tui.BackToMailboxMsg:
137 switch msg.Mailbox {
138 case tui.MailboxSent:
139 if m.sentInbox != nil {
140 m.current = m.sentInbox
141 return m, nil
142 }
143 case tui.MailboxInbox:
144 if m.inbox != nil {
145 m.current = m.inbox
146 return m, nil
147 }
148 case tui.MailboxTrash, tui.MailboxArchive:
149 if m.trashArchive != nil {
150 m.current = m.trashArchive
151 return m, nil
152 }
153 }
154 m.current = tui.NewChoice()
155 return m, nil
156
157 case tui.DiscardDraftMsg:
158 // Save draft to disk
159 if msg.ComposerState != nil {
160 draft := msg.ComposerState.ToDraft()
161 go func() {
162 if err := config.SaveDraft(draft); err != nil {
163 log.Printf("Error saving draft: %v", err)
164 }
165 }()
166 }
167 m.current = tui.NewChoice()
168 return m, m.current.Init()
169
170 case tui.Credentials:
171 // Add new account or update existing
172 account := config.Account{
173 ID: uuid.New().String(),
174 Name: msg.Name,
175 Email: msg.Host, // login/email used for authentication comes from Host field in the form
176 Password: msg.Password,
177 ServiceProvider: msg.Provider,
178 FetchEmail: msg.FetchEmail,
179 }
180
181 if msg.Provider == "custom" {
182 account.IMAPServer = msg.IMAPServer
183 account.IMAPPort = msg.IMAPPort
184 account.SMTPServer = msg.SMTPServer
185 account.SMTPPort = msg.SMTPPort
186 }
187
188 // Ensure FetchEmail defaults to the login Email (Host) if not explicitly set
189 if account.FetchEmail == "" && account.Email != "" {
190 account.FetchEmail = account.Email
191 }
192
193 if m.config == nil {
194 m.config = &config.Config{}
195 }
196
197 // Check if we're editing an existing account
198 if login, ok := m.current.(*tui.Login); ok && login.IsEditMode() {
199 // Find and update the existing account
200 existingID := login.GetAccountID()
201 for i, acc := range m.config.Accounts {
202 if acc.ID == existingID {
203 account.ID = existingID
204 m.config.Accounts[i] = account
205 break
206 }
207 }
208 } else {
209 m.config.AddAccount(account)
210 }
211
212 if err := config.SaveConfig(m.config); err != nil {
213 log.Printf("could not save config: %v", err)
214 return m, tea.Quit
215 }
216
217 m.current = tui.NewChoice()
218 return m, m.current.Init()
219
220 case tui.GoToInboxMsg:
221 if m.config == nil || !m.config.HasAccounts() {
222 m.current = tui.NewLogin()
223 return m, m.current.Init()
224 }
225 // Try to load from cache first for instant display
226 if config.HasEmailCache() {
227 return m, loadCachedEmails()
228 }
229 // No cache, fetch normally
230 m.current = tui.NewStatus("Fetching emails from all accounts...")
231 return m, tea.Batch(m.current.Init(), fetchAllAccountsEmails(m.config, tui.MailboxInbox))
232
233 case tui.GoToSentInboxMsg:
234 if m.config == nil || !m.config.HasAccounts() {
235 m.current = tui.NewLogin()
236 return m, m.current.Init()
237 }
238 m.current = tui.NewStatus("Fetching sent emails from all accounts...")
239 return m, tea.Batch(m.current.Init(), fetchAllAccountsEmails(m.config, tui.MailboxSent))
240
241 case tui.GoToTrashArchiveMsg:
242 if m.config == nil || !m.config.HasAccounts() {
243 m.current = tui.NewLogin()
244 return m, m.current.Init()
245 }
246 m.current = tui.NewStatus("Fetching trash and archive emails...")
247 return m, tea.Batch(
248 m.current.Init(),
249 fetchAllAccountsEmails(m.config, tui.MailboxTrash),
250 fetchAllAccountsEmails(m.config, tui.MailboxArchive),
251 )
252
253 case tui.CachedEmailsLoadedMsg:
254 if msg.Cache == nil {
255 // Cache load failed, fetch normally
256 m.current = tui.NewStatus("Fetching emails from all accounts...")
257 return m, tea.Batch(m.current.Init(), fetchAllAccountsEmails(m.config, tui.MailboxInbox))
258 }
259
260 // Convert cached emails to fetcher.Email
261 var cachedEmails []fetcher.Email
262 emailsByAcct := make(map[string][]fetcher.Email)
263 for _, cached := range msg.Cache.Emails {
264 email := fetcher.Email{
265 UID: cached.UID,
266 From: cached.From,
267 To: cached.To,
268 Subject: cached.Subject,
269 Date: cached.Date,
270 MessageID: cached.MessageID,
271 AccountID: cached.AccountID,
272 }
273 cachedEmails = append(cachedEmails, email)
274 emailsByAcct[cached.AccountID] = append(emailsByAcct[cached.AccountID], email)
275 }
276
277 m.emails = cachedEmails
278 m.emailsByAcct = emailsByAcct
279 m.inbox = tui.NewInbox(m.emails, m.config.Accounts)
280 m.current = m.inbox
281 m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
282
283 // Start background refresh
284 return m, tea.Batch(
285 m.current.Init(),
286 func() tea.Msg { return tui.RefreshingEmailsMsg{Mailbox: tui.MailboxInbox} },
287 refreshEmails(m.config, tui.MailboxInbox),
288 )
289
290 case tui.RequestRefreshMsg:
291 return m, tea.Batch(
292 func() tea.Msg { return tui.RefreshingEmailsMsg{Mailbox: msg.Mailbox} },
293 refreshEmails(m.config, msg.Mailbox),
294 )
295
296 case tui.EmailsRefreshedMsg:
297 if msg.Mailbox == tui.MailboxSent {
298 m.sentByAcct = msg.EmailsByAccount
299 m.sentEmails = flattenAndSort(msg.EmailsByAccount)
300 if m.sentInbox != nil {
301 m.sentInbox.SetEmails(m.sentEmails, m.config.Accounts)
302 m.current, _ = m.current.Update(msg)
303 }
304 return m, nil
305 }
306
307 m.emailsByAcct = msg.EmailsByAccount
308 m.emails = flattenAndSort(msg.EmailsByAccount)
309
310 // Save to cache (inbox only)
311 go saveEmailsToCache(m.emails)
312
313 // Update inbox if it exists
314 if m.inbox != nil {
315 m.inbox.SetEmails(m.emails, m.config.Accounts)
316 // Forward the message to inbox to clear refreshing state
317 m.current, _ = m.current.Update(msg)
318 }
319 return m, nil
320
321 case tui.AllEmailsFetchedMsg:
322 if msg.Mailbox == tui.MailboxSent {
323 m.sentByAcct = msg.EmailsByAccount
324 m.sentEmails = flattenAndSort(msg.EmailsByAccount)
325
326 m.sentInbox = tui.NewSentInbox(m.sentEmails, m.config.Accounts)
327 m.current = m.sentInbox
328 m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
329 return m, m.current.Init()
330 }
331
332 if msg.Mailbox == tui.MailboxTrash {
333 m.trashByAcct = msg.EmailsByAccount
334 m.trashEmails = flattenAndSort(msg.EmailsByAccount)
335
336 // Create or update trash/archive view
337 if m.trashArchive == nil {
338 m.trashArchive = tui.NewTrashArchive(m.trashEmails, m.archiveEmails, m.config.Accounts)
339 } else {
340 m.trashArchive.SetTrashEmails(m.trashEmails, m.config.Accounts)
341 }
342 m.current = m.trashArchive
343 m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
344 return m, m.current.Init()
345 }
346
347 if msg.Mailbox == tui.MailboxArchive {
348 m.archiveByAcct = msg.EmailsByAccount
349 m.archiveEmails = flattenAndSort(msg.EmailsByAccount)
350
351 // Create or update trash/archive view
352 if m.trashArchive == nil {
353 m.trashArchive = tui.NewTrashArchive(m.trashEmails, m.archiveEmails, m.config.Accounts)
354 } else {
355 m.trashArchive.SetArchiveEmails(m.archiveEmails, m.config.Accounts)
356 }
357 m.current = m.trashArchive
358 m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
359 return m, m.current.Init()
360 }
361
362 m.emailsByAcct = msg.EmailsByAccount
363 m.emails = flattenAndSort(msg.EmailsByAccount)
364
365 // Save to cache
366 go saveEmailsToCache(m.emails)
367
368 m.inbox = tui.NewInbox(m.emails, m.config.Accounts)
369 m.current = m.inbox
370 m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
371 return m, m.current.Init()
372
373 case tui.EmailsFetchedMsg:
374 if msg.Mailbox == tui.MailboxSent {
375 if m.sentByAcct == nil {
376 m.sentByAcct = make(map[string][]fetcher.Email)
377 }
378 m.sentByAcct[msg.AccountID] = msg.Emails
379 m.sentEmails = flattenAndSort(m.sentByAcct)
380 if m.sentInbox == nil {
381 m.sentInbox = tui.NewSentInbox(m.sentEmails, m.config.Accounts)
382 } else {
383 m.sentInbox.SetEmails(m.sentEmails, m.config.Accounts)
384 }
385 m.current = m.sentInbox
386 m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
387 return m, m.current.Init()
388 }
389
390 // Inbox path
391 if m.emailsByAcct == nil {
392 m.emailsByAcct = make(map[string][]fetcher.Email)
393 }
394 m.emailsByAcct[msg.AccountID] = msg.Emails
395 m.emails = flattenAndSort(m.emailsByAcct)
396 if m.inbox == nil {
397 m.inbox = tui.NewInbox(m.emails, m.config.Accounts)
398 } else {
399 m.inbox.SetEmails(m.emails, m.config.Accounts)
400 }
401 m.current = m.inbox
402 m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
403 return m, m.current.Init()
404
405 case tui.FetchMoreEmailsMsg:
406 if msg.AccountID == "" {
407 return m, nil // Don't fetch more for "ALL" view
408 }
409 account := m.config.GetAccountByID(msg.AccountID)
410 if account == nil {
411 return m, nil
412 }
413 limit := uint32(paginationLimit)
414 if msg.Limit > 0 {
415 limit = msg.Limit
416 }
417 return m, tea.Batch(
418 func() tea.Msg { return tui.FetchingMoreEmailsMsg{} },
419 fetchEmailsForMailbox(account, limit, msg.Offset, msg.Mailbox),
420 )
421
422 case tui.EmailsAppendedMsg:
423 if msg.Mailbox == tui.MailboxSent {
424 if m.sentByAcct == nil {
425 m.sentByAcct = make(map[string][]fetcher.Email)
426 }
427 m.sentByAcct[msg.AccountID] = append(m.sentByAcct[msg.AccountID], msg.Emails...)
428 m.sentEmails = append(m.sentEmails, msg.Emails...)
429 return m, nil
430 }
431 if msg.Mailbox == tui.MailboxTrash {
432 if m.trashByAcct == nil {
433 m.trashByAcct = make(map[string][]fetcher.Email)
434 }
435 m.trashByAcct[msg.AccountID] = append(m.trashByAcct[msg.AccountID], msg.Emails...)
436 m.trashEmails = append(m.trashEmails, msg.Emails...)
437 return m, nil
438 }
439 if msg.Mailbox == tui.MailboxArchive {
440 if m.archiveByAcct == nil {
441 m.archiveByAcct = make(map[string][]fetcher.Email)
442 }
443 m.archiveByAcct[msg.AccountID] = append(m.archiveByAcct[msg.AccountID], msg.Emails...)
444 m.archiveEmails = append(m.archiveEmails, msg.Emails...)
445 return m, nil
446 }
447 // Inbox
448 if m.emailsByAcct == nil {
449 m.emailsByAcct = make(map[string][]fetcher.Email)
450 }
451 m.emailsByAcct[msg.AccountID] = append(m.emailsByAcct[msg.AccountID], msg.Emails...)
452 m.emails = append(m.emails, msg.Emails...)
453 return m, nil
454
455 case tui.GoToSendMsg:
456 if m.config != nil && len(m.config.Accounts) > 0 {
457 firstAccount := m.config.GetFirstAccount()
458 composer := tui.NewComposerWithAccounts(m.config.Accounts, firstAccount.ID, msg.To, msg.Subject, msg.Body)
459 m.current = composer
460 } else {
461 m.current = tui.NewComposer("", msg.To, msg.Subject, msg.Body)
462 }
463 m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
464 return m, m.current.Init()
465
466 case tui.GoToDraftsMsg:
467 drafts := config.GetAllDrafts()
468 m.current = tui.NewDrafts(drafts)
469 m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
470 return m, m.current.Init()
471
472 case tui.OpenDraftMsg:
473 var accounts []config.Account
474 if m.config != nil {
475 accounts = m.config.Accounts
476 }
477 composer := tui.NewComposerFromDraft(msg.Draft, accounts)
478 m.current = composer
479 m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
480 return m, m.current.Init()
481
482 case tui.DeleteSavedDraftMsg:
483 go func() {
484 if err := config.DeleteDraft(msg.DraftID); err != nil {
485 log.Printf("Error deleting draft: %v", err)
486 }
487 }()
488 // Send message back to drafts view
489 m.current, cmd = m.current.Update(tui.DraftDeletedMsg{DraftID: msg.DraftID})
490 return m, cmd
491
492 case tui.GoToSettingsMsg:
493 m.current = tui.NewSettings(m.config)
494 m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
495 return m, m.current.Init()
496
497 case tui.GoToAddAccountMsg:
498 m.current = tui.NewLogin()
499 m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
500 return m, m.current.Init()
501
502 case tui.GoToSignatureEditorMsg:
503 m.current = tui.NewSignatureEditor()
504 m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
505 return m, m.current.Init()
506
507 case tui.GoToChoiceMenuMsg:
508 m.current = tui.NewChoice()
509 return m, m.current.Init()
510
511 case tui.DeleteAccountMsg:
512 if m.config != nil {
513 m.config.RemoveAccount(msg.AccountID)
514 if err := config.SaveConfig(m.config); err != nil {
515 log.Printf("could not save config: %v", err)
516 }
517 // Remove emails for this account
518 delete(m.emailsByAcct, msg.AccountID)
519
520 // Rebuild all emails
521 var allEmails []fetcher.Email
522 for _, emails := range m.emailsByAcct {
523 allEmails = append(allEmails, emails...)
524 }
525 m.emails = allEmails
526
527 // Go back to settings
528 m.current = tui.NewSettings(m.config)
529 m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
530 }
531 return m, m.current.Init()
532
533 case tui.ViewEmailMsg:
534 email := m.getEmailByUIDAndAccount(msg.UID, msg.AccountID, msg.Mailbox)
535 if email == nil {
536 return m, nil
537 }
538 m.current = tui.NewStatus("Fetching email content...")
539 return m, tea.Batch(m.current.Init(), fetchEmailBodyCmd(m.config, *email, msg.UID, msg.AccountID, msg.Mailbox))
540
541 case tui.EmailBodyFetchedMsg:
542 if msg.Err != nil {
543 log.Printf("could not fetch email body: %v", msg.Err)
544 if msg.Mailbox == tui.MailboxSent && m.sentInbox != nil {
545 m.current = m.sentInbox
546 } else {
547 m.current = m.inbox
548 }
549 return m, nil
550 }
551
552 // Update the email in our stores
553 m.updateEmailBodyByUID(msg.UID, msg.AccountID, msg.Mailbox, msg.Body, msg.Attachments)
554
555 email := m.getEmailByUIDAndAccount(msg.UID, msg.AccountID, msg.Mailbox)
556 if email == nil {
557 if msg.Mailbox == tui.MailboxSent && m.sentInbox != nil {
558 m.current = m.sentInbox
559 } else {
560 m.current = m.inbox
561 }
562 return m, nil
563 }
564
565 // Find the index for the email view (used for display purposes)
566 emailIndex := m.getEmailIndex(msg.UID, msg.AccountID, msg.Mailbox)
567 emailView := tui.NewEmailView(*email, emailIndex, m.width, m.height, msg.Mailbox, m.config.DisableImages)
568 m.current = emailView
569 return m, m.current.Init()
570
571 case tui.ReplyToEmailMsg:
572 to := msg.Email.From
573 subject := msg.Email.Subject
574 normalizedSubject := strings.ToLower(strings.TrimSpace(subject))
575 if !strings.HasPrefix(normalizedSubject, "re:") {
576 subject = "Re: " + subject
577 }
578 quotedText := fmt.Sprintf("\n\nOn %s, %s wrote:\n> %s", msg.Email.Date.Format("Jan 2, 2006 at 3:04 PM"), msg.Email.From, strings.ReplaceAll(msg.Email.Body, "\n", "\n> "))
579
580 var composer *tui.Composer
581 if m.config != nil && len(m.config.Accounts) > 0 {
582 // Use the account that received the email
583 accountID := msg.Email.AccountID
584 if accountID == "" {
585 accountID = m.config.GetFirstAccount().ID
586 }
587 composer = tui.NewComposerWithAccounts(m.config.Accounts, accountID, to, subject, "")
588 } else {
589 composer = tui.NewComposer("", to, subject, "")
590 }
591 composer.SetQuotedText(quotedText)
592
593 // Set reply headers
594 inReplyTo := msg.Email.MessageID
595 references := append(msg.Email.References, msg.Email.MessageID)
596 composer.SetReplyContext(inReplyTo, references)
597
598 m.current = composer
599 m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
600 return m, m.current.Init()
601
602 case tui.ForwardEmailMsg:
603 subject := msg.Email.Subject
604 if !strings.HasPrefix(strings.ToLower(subject), "fwd:") {
605 subject = "Fwd: " + subject
606 }
607
608 forwardHeader := fmt.Sprintf("\n\n---------- Forwarded message ----------\nFrom: %s\nDate: %s\nSubject: %s\nTo: %s\n\n",
609 msg.Email.From,
610 msg.Email.Date.Format("Mon, Jan 2, 2006 at 3:04 PM"),
611 msg.Email.Subject,
612 msg.Email.To,
613 )
614
615 body := forwardHeader + msg.Email.Body
616
617 var composer *tui.Composer
618 if m.config != nil && len(m.config.Accounts) > 0 {
619 // Use the account that received the email
620 accountID := msg.Email.AccountID
621 if accountID == "" {
622 accountID = m.config.GetFirstAccount().ID
623 }
624 composer = tui.NewComposerWithAccounts(m.config.Accounts, accountID, "", subject, body)
625 } else {
626 composer = tui.NewComposer("", "", subject, body)
627 }
628
629 m.current = composer
630 m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
631 return m, m.current.Init()
632
633 case tui.GoToFilePickerMsg:
634 m.previousModel = m.current
635 wd, _ := os.Getwd()
636 m.current = tui.NewFilePicker(wd)
637 m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
638 return m, m.current.Init()
639
640 case tui.FileSelectedMsg, tui.CancelFilePickerMsg:
641 if m.previousModel != nil {
642 m.current = m.previousModel
643 m.previousModel = nil
644 }
645 m.current, cmd = m.current.Update(msg)
646 cmds = append(cmds, cmd)
647
648 case tui.SendEmailMsg:
649 // Get draft ID before clearing composer (if it's a composer)
650 var draftID string
651 if composer, ok := m.current.(*tui.Composer); ok {
652 draftID = composer.GetDraftID()
653 }
654 m.current = tui.NewStatus("Sending email...")
655
656 // Get the account to send from
657 var account *config.Account
658 if msg.AccountID != "" && m.config != nil {
659 account = m.config.GetAccountByID(msg.AccountID)
660 }
661 if account == nil && m.config != nil {
662 account = m.config.GetFirstAccount()
663 }
664
665 // Save contact and delete draft in background
666 go func() {
667 // Save the recipient as a contact
668 if msg.To != "" {
669 // Parse "Name <email>" format
670 name, email := parseEmailAddress(msg.To)
671 if err := config.AddContact(name, email); err != nil {
672 log.Printf("Error saving contact: %v", err)
673 }
674 }
675 // Delete the draft since email is being sent
676 if draftID != "" {
677 if err := config.DeleteDraft(draftID); err != nil {
678 log.Printf("Error deleting draft after send: %v", err)
679 }
680 }
681 }()
682
683 return m, tea.Batch(m.current.Init(), sendEmail(account, msg))
684
685 case tui.EmailResultMsg:
686 if msg.Err != nil {
687 log.Printf("Failed to send email: %v", msg.Err)
688 m.previousModel = tui.NewChoice()
689 m.current = tui.NewStatus(fmt.Sprintf("Error: %v", msg.Err))
690 return m, tea.Tick(2*time.Second, func(t time.Time) tea.Msg {
691 return tui.RestoreViewMsg{}
692 })
693 }
694 m.current = tui.NewChoice()
695 return m, m.current.Init()
696
697 case tui.DeleteEmailMsg:
698 m.previousModel = m.current
699 m.current = tui.NewStatus("Deleting email...")
700
701 account := m.config.GetAccountByID(msg.AccountID)
702 if account == nil {
703 if msg.Mailbox == tui.MailboxSent && m.sentInbox != nil {
704 m.current = m.sentInbox
705 } else {
706 m.current = m.inbox
707 }
708 return m, nil
709 }
710
711 return m, tea.Batch(m.current.Init(), deleteEmailCmd(account, msg.UID, msg.AccountID, msg.Mailbox))
712
713 case tui.ArchiveEmailMsg:
714 m.previousModel = m.current
715 m.current = tui.NewStatus("Archiving email...")
716
717 account := m.config.GetAccountByID(msg.AccountID)
718 if account == nil {
719 if msg.Mailbox == tui.MailboxSent && m.sentInbox != nil {
720 m.current = m.sentInbox
721 } else {
722 m.current = m.inbox
723 }
724 return m, nil
725 }
726
727 return m, tea.Batch(m.current.Init(), archiveEmailCmd(account, msg.UID, msg.AccountID, msg.Mailbox))
728
729 case tui.EmailActionDoneMsg:
730 if msg.Err != nil {
731 log.Printf("Action failed: %v", msg.Err)
732 m.previousModel = m.current
733 switch msg.Mailbox {
734 case tui.MailboxSent:
735 if m.sentInbox != nil {
736 m.previousModel = m.sentInbox
737 }
738 case tui.MailboxTrash, tui.MailboxArchive:
739 if m.trashArchive != nil {
740 m.previousModel = m.trashArchive
741 }
742 default:
743 if m.inbox != nil {
744 m.previousModel = m.inbox
745 }
746 }
747 m.current = tui.NewStatus(fmt.Sprintf("Error: %v", msg.Err))
748 return m, tea.Tick(2*time.Second, func(t time.Time) tea.Msg {
749 return tui.RestoreViewMsg{}
750 })
751 }
752
753 // Remove email from stores
754 m.removeEmailByMailbox(msg.UID, msg.AccountID, msg.Mailbox)
755
756 if msg.Mailbox == tui.MailboxSent {
757 if m.sentInbox != nil {
758 m.sentInbox.RemoveEmail(msg.UID, msg.AccountID)
759 m.current = m.sentInbox
760 m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
761 return m, m.current.Init()
762 }
763 m.current = tui.NewChoice()
764 return m, m.current.Init()
765 }
766
767 if msg.Mailbox == tui.MailboxTrash || msg.Mailbox == tui.MailboxArchive {
768 if m.trashArchive != nil {
769 m.trashArchive.RemoveEmail(msg.UID, msg.AccountID, msg.Mailbox)
770 m.current = m.trashArchive
771 m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
772 return m, m.current.Init()
773 }
774 m.current = tui.NewChoice()
775 return m, m.current.Init()
776 }
777
778 if m.inbox != nil {
779 m.inbox.RemoveEmail(msg.UID, msg.AccountID)
780 m.current = m.inbox
781 m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
782 return m, m.current.Init()
783 }
784 m.current = tui.NewChoice()
785 return m, m.current.Init()
786
787 case tui.DownloadAttachmentMsg:
788 m.previousModel = m.current
789 m.current = tui.NewStatus(fmt.Sprintf("Downloading %s...", msg.Filename))
790
791 account := m.config.GetAccountByID(msg.AccountID)
792 if account == nil {
793 m.current = m.previousModel
794 return m, nil
795 }
796
797 email := m.getEmailByIndex(msg.Index, msg.Mailbox)
798 if email == nil {
799 m.current = m.previousModel
800 return m, nil
801 }
802
803 // Find the correct attachment to get encoding
804 var encoding string
805 for _, att := range email.Attachments {
806 if att.PartID == msg.PartID {
807 encoding = att.Encoding
808 break
809 }
810 }
811 newMsg := tui.DownloadAttachmentMsg{
812 Index: msg.Index,
813 Filename: msg.Filename,
814 PartID: msg.PartID,
815 Data: msg.Data,
816 AccountID: msg.AccountID,
817 Encoding: encoding,
818 Mailbox: msg.Mailbox,
819 }
820 return m, tea.Batch(m.current.Init(), downloadAttachmentCmd(account, email.UID, newMsg))
821
822 case tui.AttachmentDownloadedMsg:
823 var statusMsg string
824 if msg.Err != nil {
825 statusMsg = fmt.Sprintf("Error downloading: %v", msg.Err)
826 } else {
827 statusMsg = fmt.Sprintf("Saved to %s", msg.Path)
828 }
829 m.current = tui.NewStatus(statusMsg)
830 return m, tea.Tick(2*time.Second, func(t time.Time) tea.Msg {
831 return tui.RestoreViewMsg{}
832 })
833
834 case tui.RestoreViewMsg:
835 if m.previousModel != nil {
836 m.current = m.previousModel
837 m.previousModel = nil
838 }
839 return m, nil
840 }
841
842 return m, tea.Batch(cmds...)
843}
844
845func (m *mainModel) View() string {
846 return m.current.View()
847}
848
849func (m *mainModel) getEmailByIndex(index int, mailbox tui.MailboxKind) *fetcher.Email {
850 switch mailbox {
851 case tui.MailboxSent:
852 if index >= 0 && index < len(m.sentEmails) {
853 return &m.sentEmails[index]
854 }
855 case tui.MailboxTrash:
856 if index >= 0 && index < len(m.trashEmails) {
857 return &m.trashEmails[index]
858 }
859 case tui.MailboxArchive:
860 if index >= 0 && index < len(m.archiveEmails) {
861 return &m.archiveEmails[index]
862 }
863 default:
864 if index >= 0 && index < len(m.emails) {
865 return &m.emails[index]
866 }
867 }
868 return nil
869}
870
871func (m *mainModel) getEmailByUIDAndAccount(uid uint32, accountID string, mailbox tui.MailboxKind) *fetcher.Email {
872 switch mailbox {
873 case tui.MailboxSent:
874 for i := range m.sentEmails {
875 if m.sentEmails[i].UID == uid && m.sentEmails[i].AccountID == accountID {
876 return &m.sentEmails[i]
877 }
878 }
879 case tui.MailboxTrash:
880 for i := range m.trashEmails {
881 if m.trashEmails[i].UID == uid && m.trashEmails[i].AccountID == accountID {
882 return &m.trashEmails[i]
883 }
884 }
885 case tui.MailboxArchive:
886 for i := range m.archiveEmails {
887 if m.archiveEmails[i].UID == uid && m.archiveEmails[i].AccountID == accountID {
888 return &m.archiveEmails[i]
889 }
890 }
891 default:
892 for i := range m.emails {
893 if m.emails[i].UID == uid && m.emails[i].AccountID == accountID {
894 return &m.emails[i]
895 }
896 }
897 }
898 return nil
899}
900
901func (m *mainModel) getEmailIndex(uid uint32, accountID string, mailbox tui.MailboxKind) int {
902 switch mailbox {
903 case tui.MailboxSent:
904 for i := range m.sentEmails {
905 if m.sentEmails[i].UID == uid && m.sentEmails[i].AccountID == accountID {
906 return i
907 }
908 }
909 case tui.MailboxTrash:
910 for i := range m.trashEmails {
911 if m.trashEmails[i].UID == uid && m.trashEmails[i].AccountID == accountID {
912 return i
913 }
914 }
915 case tui.MailboxArchive:
916 for i := range m.archiveEmails {
917 if m.archiveEmails[i].UID == uid && m.archiveEmails[i].AccountID == accountID {
918 return i
919 }
920 }
921 default:
922 for i := range m.emails {
923 if m.emails[i].UID == uid && m.emails[i].AccountID == accountID {
924 return i
925 }
926 }
927 }
928 return -1
929}
930
931func (m *mainModel) updateEmailBodyByUID(uid uint32, accountID string, mailbox tui.MailboxKind, body string, attachments []fetcher.Attachment) {
932 switch mailbox {
933 case tui.MailboxSent:
934 for i := range m.sentEmails {
935 if m.sentEmails[i].UID == uid && m.sentEmails[i].AccountID == accountID {
936 m.sentEmails[i].Body = body
937 m.sentEmails[i].Attachments = attachments
938 break
939 }
940 }
941 if emails, ok := m.sentByAcct[accountID]; ok {
942 for i := range emails {
943 if emails[i].UID == uid {
944 emails[i].Body = body
945 emails[i].Attachments = attachments
946 break
947 }
948 }
949 }
950 case tui.MailboxTrash:
951 for i := range m.trashEmails {
952 if m.trashEmails[i].UID == uid && m.trashEmails[i].AccountID == accountID {
953 m.trashEmails[i].Body = body
954 m.trashEmails[i].Attachments = attachments
955 break
956 }
957 }
958 if emails, ok := m.trashByAcct[accountID]; ok {
959 for i := range emails {
960 if emails[i].UID == uid {
961 emails[i].Body = body
962 emails[i].Attachments = attachments
963 break
964 }
965 }
966 }
967 case tui.MailboxArchive:
968 for i := range m.archiveEmails {
969 if m.archiveEmails[i].UID == uid && m.archiveEmails[i].AccountID == accountID {
970 m.archiveEmails[i].Body = body
971 m.archiveEmails[i].Attachments = attachments
972 break
973 }
974 }
975 if emails, ok := m.archiveByAcct[accountID]; ok {
976 for i := range emails {
977 if emails[i].UID == uid {
978 emails[i].Body = body
979 emails[i].Attachments = attachments
980 break
981 }
982 }
983 }
984 default:
985 for i := range m.emails {
986 if m.emails[i].UID == uid && m.emails[i].AccountID == accountID {
987 m.emails[i].Body = body
988 m.emails[i].Attachments = attachments
989 break
990 }
991 }
992 if emails, ok := m.emailsByAcct[accountID]; ok {
993 for i := range emails {
994 if emails[i].UID == uid {
995 emails[i].Body = body
996 emails[i].Attachments = attachments
997 break
998 }
999 }
1000 }
1001 }
1002}
1003
1004func (m *mainModel) removeEmailByMailbox(uid uint32, accountID string, mailbox tui.MailboxKind) {
1005 switch mailbox {
1006 case tui.MailboxSent:
1007 var filtered []fetcher.Email
1008 for _, e := range m.sentEmails {
1009 if !(e.UID == uid && e.AccountID == accountID) {
1010 filtered = append(filtered, e)
1011 }
1012 }
1013 m.sentEmails = filtered
1014 if emails, ok := m.sentByAcct[accountID]; ok {
1015 var filteredAcct []fetcher.Email
1016 for _, e := range emails {
1017 if e.UID != uid {
1018 filteredAcct = append(filteredAcct, e)
1019 }
1020 }
1021 m.sentByAcct[accountID] = filteredAcct
1022 }
1023 case tui.MailboxTrash:
1024 var filtered []fetcher.Email
1025 for _, e := range m.trashEmails {
1026 if !(e.UID == uid && e.AccountID == accountID) {
1027 filtered = append(filtered, e)
1028 }
1029 }
1030 m.trashEmails = filtered
1031 if emails, ok := m.trashByAcct[accountID]; ok {
1032 var filteredAcct []fetcher.Email
1033 for _, e := range emails {
1034 if e.UID != uid {
1035 filteredAcct = append(filteredAcct, e)
1036 }
1037 }
1038 m.trashByAcct[accountID] = filteredAcct
1039 }
1040 case tui.MailboxArchive:
1041 var filtered []fetcher.Email
1042 for _, e := range m.archiveEmails {
1043 if !(e.UID == uid && e.AccountID == accountID) {
1044 filtered = append(filtered, e)
1045 }
1046 }
1047 m.archiveEmails = filtered
1048 if emails, ok := m.archiveByAcct[accountID]; ok {
1049 var filteredAcct []fetcher.Email
1050 for _, e := range emails {
1051 if e.UID != uid {
1052 filteredAcct = append(filteredAcct, e)
1053 }
1054 }
1055 m.archiveByAcct[accountID] = filteredAcct
1056 }
1057 default:
1058 var filtered []fetcher.Email
1059 for _, e := range m.emails {
1060 if !(e.UID == uid && e.AccountID == accountID) {
1061 filtered = append(filtered, e)
1062 }
1063 }
1064 m.emails = filtered
1065 if emails, ok := m.emailsByAcct[accountID]; ok {
1066 var filteredAcct []fetcher.Email
1067 for _, e := range emails {
1068 if e.UID != uid {
1069 filteredAcct = append(filteredAcct, e)
1070 }
1071 }
1072 m.emailsByAcct[accountID] = filteredAcct
1073 }
1074 }
1075}
1076
1077func flattenAndSort(emailsByAccount map[string][]fetcher.Email) []fetcher.Email {
1078 var allEmails []fetcher.Email
1079 for _, emails := range emailsByAccount {
1080 allEmails = append(allEmails, emails...)
1081 }
1082 for i := 0; i < len(allEmails); i++ {
1083 for j := i + 1; j < len(allEmails); j++ {
1084 if allEmails[j].Date.After(allEmails[i].Date) {
1085 allEmails[i], allEmails[j] = allEmails[j], allEmails[i]
1086 }
1087 }
1088 }
1089 return allEmails
1090}
1091
1092func fetchAllAccountsEmails(cfg *config.Config, mailbox tui.MailboxKind) tea.Cmd {
1093 return func() tea.Msg {
1094 emailsByAccount := make(map[string][]fetcher.Email)
1095 var mu sync.Mutex
1096 var wg sync.WaitGroup
1097
1098 for _, account := range cfg.Accounts {
1099 wg.Add(1)
1100 go func(acc config.Account) {
1101 defer wg.Done()
1102 var emails []fetcher.Email
1103 var err error
1104 switch mailbox {
1105 case tui.MailboxSent:
1106 emails, err = fetcher.FetchSentEmails(&acc, initialEmailLimit, 0)
1107 case tui.MailboxTrash:
1108 emails, err = fetcher.FetchTrashEmails(&acc, initialEmailLimit, 0)
1109 case tui.MailboxArchive:
1110 emails, err = fetcher.FetchArchiveEmails(&acc, initialEmailLimit, 0)
1111 default:
1112 emails, err = fetcher.FetchEmails(&acc, initialEmailLimit, 0)
1113 }
1114 if err != nil {
1115 log.Printf("Error fetching from %s: %v", acc.Email, err)
1116 return
1117 }
1118 mu.Lock()
1119 emailsByAccount[acc.ID] = emails
1120 mu.Unlock()
1121 }(account)
1122 }
1123
1124 wg.Wait()
1125 return tui.AllEmailsFetchedMsg{EmailsByAccount: emailsByAccount, Mailbox: mailbox}
1126 }
1127}
1128
1129func fetchEmails(account *config.Account, limit, offset uint32, mailbox tui.MailboxKind) tea.Cmd {
1130 return func() tea.Msg {
1131 var emails []fetcher.Email
1132 var err error
1133 if mailbox == tui.MailboxSent {
1134 emails, err = fetcher.FetchSentEmails(account, limit, offset)
1135 } else {
1136 emails, err = fetcher.FetchEmails(account, limit, offset)
1137 }
1138 if err != nil {
1139 return tui.FetchErr(err)
1140 }
1141 if offset == 0 {
1142 return tui.EmailsFetchedMsg{Emails: emails, AccountID: account.ID, Mailbox: mailbox}
1143 }
1144 return tui.EmailsAppendedMsg{Emails: emails, AccountID: account.ID, Mailbox: mailbox}
1145 }
1146}
1147
1148func fetchEmailsForMailbox(account *config.Account, limit, offset uint32, mailbox tui.MailboxKind) tea.Cmd {
1149 return func() tea.Msg {
1150 var emails []fetcher.Email
1151 var err error
1152 switch mailbox {
1153 case tui.MailboxSent:
1154 emails, err = fetcher.FetchSentEmails(account, limit, offset)
1155 case tui.MailboxTrash:
1156 emails, err = fetcher.FetchTrashEmails(account, limit, offset)
1157 case tui.MailboxArchive:
1158 emails, err = fetcher.FetchArchiveEmails(account, limit, offset)
1159 default:
1160 emails, err = fetcher.FetchEmails(account, limit, offset)
1161 }
1162 if err != nil {
1163 return tui.FetchErr(err)
1164 }
1165 if offset == 0 {
1166 return tui.EmailsFetchedMsg{Emails: emails, AccountID: account.ID, Mailbox: mailbox}
1167 }
1168 return tui.EmailsAppendedMsg{Emails: emails, AccountID: account.ID, Mailbox: mailbox}
1169 }
1170}
1171
1172func loadCachedEmails() tea.Cmd {
1173 return func() tea.Msg {
1174 cache, err := config.LoadEmailCache()
1175 if err != nil {
1176 return tui.CachedEmailsLoadedMsg{Cache: nil}
1177 }
1178 return tui.CachedEmailsLoadedMsg{Cache: cache}
1179 }
1180}
1181
1182func refreshEmails(cfg *config.Config, mailbox tui.MailboxKind) tea.Cmd {
1183 return func() tea.Msg {
1184 emailsByAccount := make(map[string][]fetcher.Email)
1185 var mu sync.Mutex
1186 var wg sync.WaitGroup
1187
1188 for _, account := range cfg.Accounts {
1189 wg.Add(1)
1190 go func(acc config.Account) {
1191 defer wg.Done()
1192 var emails []fetcher.Email
1193 var err error
1194 if mailbox == tui.MailboxSent {
1195 emails, err = fetcher.FetchSentEmails(&acc, initialEmailLimit, 0)
1196 } else {
1197 emails, err = fetcher.FetchEmails(&acc, initialEmailLimit, 0)
1198 }
1199 if err != nil {
1200 log.Printf("Error fetching from %s: %v", acc.Email, err)
1201 return
1202 }
1203 mu.Lock()
1204 emailsByAccount[acc.ID] = emails
1205 mu.Unlock()
1206 }(account)
1207 }
1208
1209 wg.Wait()
1210 return tui.EmailsRefreshedMsg{EmailsByAccount: emailsByAccount, Mailbox: mailbox}
1211 }
1212}
1213
1214func saveEmailsToCache(emails []fetcher.Email) {
1215 var cachedEmails []config.CachedEmail
1216 for _, email := range emails {
1217 cachedEmails = append(cachedEmails, config.CachedEmail{
1218 UID: email.UID,
1219 From: email.From,
1220 To: email.To,
1221 Subject: email.Subject,
1222 Date: email.Date,
1223 MessageID: email.MessageID,
1224 AccountID: email.AccountID,
1225 })
1226
1227 // Save sender as a contact
1228 if email.From != "" {
1229 name, emailAddr := parseEmailAddress(email.From)
1230 if err := config.AddContact(name, emailAddr); err != nil {
1231 log.Printf("Error saving contact from email: %v", err)
1232 }
1233 }
1234 }
1235 cache := &config.EmailCache{Emails: cachedEmails}
1236 if err := config.SaveEmailCache(cache); err != nil {
1237 log.Printf("Error saving email cache: %v", err)
1238 }
1239}
1240
1241// parseEmailAddress parses "Name <email>" or just "email" format
1242func parseEmailAddress(addr string) (name, email string) {
1243 addr = strings.TrimSpace(addr)
1244 if idx := strings.Index(addr, "<"); idx != -1 {
1245 name = strings.TrimSpace(addr[:idx])
1246 endIdx := strings.Index(addr, ">")
1247 if endIdx > idx {
1248 email = strings.TrimSpace(addr[idx+1 : endIdx])
1249 } else {
1250 email = strings.TrimSpace(addr[idx+1:])
1251 }
1252 } else {
1253 email = addr
1254 }
1255 return name, email
1256}
1257
1258func fetchEmailBodyCmd(cfg *config.Config, email fetcher.Email, uid uint32, accountID string, mailbox tui.MailboxKind) tea.Cmd {
1259 return func() tea.Msg {
1260 account := cfg.GetAccountByID(accountID)
1261 if account == nil {
1262 return tui.EmailBodyFetchedMsg{UID: uid, AccountID: accountID, Mailbox: mailbox, Err: fmt.Errorf("account not found")}
1263 }
1264
1265 var (
1266 body string
1267 attachments []fetcher.Attachment
1268 err error
1269 )
1270 switch mailbox {
1271 case tui.MailboxSent:
1272 body, attachments, err = fetcher.FetchSentEmailBody(account, uid)
1273 case tui.MailboxTrash:
1274 body, attachments, err = fetcher.FetchTrashEmailBody(account, uid)
1275 case tui.MailboxArchive:
1276 body, attachments, err = fetcher.FetchArchiveEmailBody(account, uid)
1277 default:
1278 body, attachments, err = fetcher.FetchEmailBody(account, uid)
1279 }
1280 if err != nil {
1281 return tui.EmailBodyFetchedMsg{UID: uid, AccountID: accountID, Mailbox: mailbox, Err: err}
1282 }
1283
1284 return tui.EmailBodyFetchedMsg{
1285 UID: uid,
1286 Body: body,
1287 Attachments: attachments,
1288 AccountID: accountID,
1289 Mailbox: mailbox,
1290 }
1291 }
1292}
1293
1294func markdownToHTML(md []byte) []byte {
1295 var buf bytes.Buffer
1296 p := goldmark.New(goldmark.WithRendererOptions(html.WithUnsafe()))
1297 if err := p.Convert(md, &buf); err != nil {
1298 return md
1299 }
1300 return buf.Bytes()
1301}
1302
1303func splitEmails(s string) []string {
1304 if s == "" {
1305 return nil
1306 }
1307 parts := strings.Split(s, ",")
1308 var res []string
1309 for _, p := range parts {
1310 if trimmed := strings.TrimSpace(p); trimmed != "" {
1311 res = append(res, trimmed)
1312 }
1313 }
1314 return res
1315}
1316
1317func sendEmail(account *config.Account, msg tui.SendEmailMsg) tea.Cmd {
1318 return func() tea.Msg {
1319 if account == nil {
1320 return tui.EmailResultMsg{Err: fmt.Errorf("no account configured")}
1321 }
1322
1323 recipients := splitEmails(msg.To)
1324 cc := splitEmails(msg.Cc)
1325 bcc := splitEmails(msg.Bcc)
1326 body := msg.Body
1327 // Append signature if present
1328 if msg.Signature != "" {
1329 body = body + "\n\n" + msg.Signature
1330 }
1331 // Append quoted text if present (for replies)
1332 if msg.QuotedText != "" {
1333 body = body + msg.QuotedText
1334 }
1335 images := make(map[string][]byte)
1336 attachments := make(map[string][]byte)
1337
1338 re := regexp.MustCompile(`!\[.*?\]\((.*?)\)`)
1339 matches := re.FindAllStringSubmatch(body, -1)
1340
1341 for _, match := range matches {
1342 imgPath := match[1]
1343 imgData, err := os.ReadFile(imgPath)
1344 if err != nil {
1345 log.Printf("Could not read image file %s: %v", imgPath, err)
1346 continue
1347 }
1348 cid := fmt.Sprintf("%s%s@%s", uuid.NewString(), filepath.Ext(imgPath), "matcha")
1349 images[cid] = []byte(base64.StdEncoding.EncodeToString(imgData))
1350 body = strings.Replace(body, imgPath, "cid:"+cid, 1)
1351 }
1352
1353 htmlBody := markdownToHTML([]byte(body))
1354
1355 if msg.AttachmentPath != "" {
1356 fileData, err := os.ReadFile(msg.AttachmentPath)
1357 if err != nil {
1358 log.Printf("Could not read attachment file %s: %v", msg.AttachmentPath, err)
1359 } else {
1360 _, filename := filepath.Split(msg.AttachmentPath)
1361 attachments[filename] = fileData
1362 }
1363 }
1364
1365 err := sender.SendEmail(account, recipients, cc, bcc, msg.Subject, body, string(htmlBody), images, attachments, msg.InReplyTo, msg.References)
1366 if err != nil {
1367 log.Printf("Failed to send email: %v", err)
1368 return tui.EmailResultMsg{Err: err}
1369 }
1370 return tui.EmailResultMsg{}
1371 }
1372}
1373
1374func deleteEmailCmd(account *config.Account, uid uint32, accountID string, mailbox tui.MailboxKind) tea.Cmd {
1375 return func() tea.Msg {
1376 var err error
1377 switch mailbox {
1378 case tui.MailboxSent:
1379 err = fetcher.DeleteSentEmail(account, uid)
1380 case tui.MailboxTrash:
1381 err = fetcher.DeleteTrashEmail(account, uid)
1382 case tui.MailboxArchive:
1383 err = fetcher.DeleteArchiveEmail(account, uid)
1384 default:
1385 err = fetcher.DeleteEmail(account, uid)
1386 }
1387 return tui.EmailActionDoneMsg{UID: uid, AccountID: accountID, Mailbox: mailbox, Err: err}
1388 }
1389}
1390
1391func archiveEmailCmd(account *config.Account, uid uint32, accountID string, mailbox tui.MailboxKind) tea.Cmd {
1392 return func() tea.Msg {
1393 var err error
1394 if mailbox == tui.MailboxSent {
1395 err = fetcher.ArchiveSentEmail(account, uid)
1396 } else {
1397 err = fetcher.ArchiveEmail(account, uid)
1398 }
1399 return tui.EmailActionDoneMsg{UID: uid, AccountID: accountID, Mailbox: mailbox, Err: err}
1400 }
1401}
1402
1403func downloadAttachmentCmd(account *config.Account, uid uint32, msg tui.DownloadAttachmentMsg) tea.Cmd {
1404 return func() tea.Msg {
1405 // Download and decode the attachment using encoding provided in msg.Encoding.
1406 var data []byte
1407 var err error
1408 switch msg.Mailbox {
1409 case tui.MailboxSent:
1410 data, err = fetcher.FetchSentAttachment(account, uid, msg.PartID, msg.Encoding)
1411 case tui.MailboxTrash:
1412 data, err = fetcher.FetchTrashAttachment(account, uid, msg.PartID, msg.Encoding)
1413 case tui.MailboxArchive:
1414 data, err = fetcher.FetchArchiveAttachment(account, uid, msg.PartID, msg.Encoding)
1415 default:
1416 data, err = fetcher.FetchAttachment(account, uid, msg.PartID, msg.Encoding)
1417 }
1418 if err != nil {
1419 return tui.AttachmentDownloadedMsg{Err: err}
1420 }
1421
1422 homeDir, err := os.UserHomeDir()
1423 if err != nil {
1424 return tui.AttachmentDownloadedMsg{Err: err}
1425 }
1426 downloadsPath := filepath.Join(homeDir, "Downloads")
1427 if _, err := os.Stat(downloadsPath); os.IsNotExist(err) {
1428 if mkErr := os.MkdirAll(downloadsPath, 0755); mkErr != nil {
1429 return tui.AttachmentDownloadedMsg{Err: mkErr}
1430 }
1431 }
1432
1433 // Save the attachment using an exclusive create so we never overwrite an existing file.
1434 // If the filename already exists, append \" (n)\" before the extension.
1435 origName := msg.Filename
1436 ext := filepath.Ext(origName)
1437 base := strings.TrimSuffix(origName, ext)
1438 candidate := origName
1439 i := 1
1440 var filePath string
1441
1442 for {
1443 filePath = filepath.Join(downloadsPath, candidate)
1444
1445 // Try to create file exclusively. If it already exists, os.OpenFile will return an error
1446 // that satisfies os.IsExist(err), so we can increment the candidate.
1447 f, err := os.OpenFile(filePath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644)
1448 if err != nil {
1449 if os.IsExist(err) {
1450 // file exists, try next candidate
1451 candidate = fmt.Sprintf("%s (%d)%s", base, i, ext)
1452 i++
1453 continue
1454 }
1455 // Some other error while attempting to create file
1456 log.Printf("error creating file %s: %v", filePath, err)
1457 return tui.AttachmentDownloadedMsg{Err: err}
1458 }
1459
1460 // Successfully created the file descriptor; write and close.
1461 if _, writeErr := f.Write(data); writeErr != nil {
1462 _ = f.Close()
1463 log.Printf("error writing to file %s: %v", filePath, writeErr)
1464 return tui.AttachmentDownloadedMsg{Err: writeErr}
1465 }
1466 if closeErr := f.Close(); closeErr != nil {
1467 log.Printf("warning: error closing file %s: %v", filePath, closeErr)
1468 }
1469
1470 // file saved successfully
1471 break
1472 }
1473
1474 log.Printf("attachment saved to %s", filePath)
1475
1476 // Try to open the file using a platform-specific opener asynchronously and log the outcome.
1477 go func(p string) {
1478 var cmd *exec.Cmd
1479 switch runtime.GOOS {
1480 case "darwin":
1481 cmd = exec.Command("open", p)
1482 case "linux":
1483 cmd = exec.Command("xdg-open", p)
1484 case "windows":
1485 // 'start' is a cmd builtin; provide an empty title argument to avoid interpreting the path as the title.
1486 cmd = exec.Command("cmd", "/c", "start", "", p)
1487 default:
1488 // Unsupported OS: nothing to do.
1489 return
1490 }
1491 if err := cmd.Start(); err != nil {
1492 log.Printf("failed to open file %s: %v", p, err)
1493 }
1494 }(filePath)
1495
1496 return tui.AttachmentDownloadedMsg{Path: filePath, Err: nil}
1497 }
1498}
1499
1500/*
1501detectInstalledVersion returns a best-effort installed version string.
1502Priority:
1503 1. If the build-in `version` variable is set to something other than "dev", return it.
1504 2. If Homebrew is present and reports a version for `matcha`, return that.
1505 3. If snap is present and lists `matcha`, return that.
1506 4. Fallback to the build `version` (likely "dev").
1507*/
1508func detectInstalledVersion() string {
1509 v := strings.TrimSpace(version)
1510 if v != "dev" && v != "" {
1511 return v
1512 }
1513
1514 // Try Homebrew (macOS)
1515 if runtime.GOOS == "darwin" {
1516 if _, err := exec.LookPath("brew"); err == nil {
1517 // `brew list --versions matcha` prints: matcha 1.2.3
1518 if out, err := exec.Command("brew", "list", "--versions", "matcha").Output(); err == nil {
1519 parts := strings.Fields(string(out))
1520 if len(parts) >= 2 {
1521 return parts[1]
1522 }
1523 }
1524 }
1525 }
1526
1527 // Try snap (Linux)
1528 if runtime.GOOS == "linux" {
1529 if _, err := exec.LookPath("snap"); err == nil {
1530 if out, err := exec.Command("snap", "list", "matcha").Output(); err == nil {
1531 lines := strings.Split(strings.TrimSpace(string(out)), "\n")
1532 if len(lines) >= 2 {
1533 fields := strings.Fields(lines[1])
1534 if len(fields) >= 2 {
1535 return fields[1]
1536 }
1537 }
1538 }
1539 }
1540 }
1541
1542 return v
1543}
1544
1545/*
1546checkForUpdatesCmd queries GitHub for the latest release tag and returns a
1547tea.Msg (UpdateAvailableMsg) if the latest version differs from the current
1548installed version. This runs in the background when the TUI initializes.
1549*/
1550func checkForUpdatesCmd() tea.Cmd {
1551 return func() tea.Msg {
1552 // Non-fatal: if anything goes wrong we just don't show the update message.
1553 const api = "https://api.github.com/repos/floatpane/matcha/releases/latest"
1554 resp, err := http.Get(api)
1555 if err != nil {
1556 return nil
1557 }
1558 defer resp.Body.Close()
1559
1560 var rel githubRelease
1561 if err := json.NewDecoder(resp.Body).Decode(&rel); err != nil {
1562 return nil
1563 }
1564
1565 latest := strings.TrimPrefix(rel.TagName, "v")
1566 installed := strings.TrimPrefix(detectInstalledVersion(), "v")
1567 if latest != "" && installed != "" && latest != installed {
1568 return UpdateAvailableMsg{Latest: latest, Current: installed}
1569 }
1570 return nil
1571 }
1572}
1573
1574// runUpdateCLI implements the CLI entrypoint for `matcha update`.
1575// It detects the likely installation method and attempts the appropriate
1576// update path (Homebrew, Snap, or GitHub release binary extract).
1577func runUpdateCLI() error {
1578 const api = "https://api.github.com/repos/floatpane/matcha/releases/latest"
1579 resp, err := http.Get(api)
1580 if err != nil {
1581 return fmt.Errorf("could not query releases: %w", err)
1582 }
1583 defer resp.Body.Close()
1584
1585 var rel githubRelease
1586 if err := json.NewDecoder(resp.Body).Decode(&rel); err != nil {
1587 return fmt.Errorf("could not parse release info: %w", err)
1588 }
1589
1590 latestTag := rel.TagName
1591 if strings.HasPrefix(latestTag, "v") {
1592 latestTag = latestTag[1:]
1593 }
1594
1595 fmt.Printf("Current version: %s\n", version)
1596 fmt.Printf("Latest version: %s\n", latestTag)
1597
1598 // Quick check: if already up-to-date, exit
1599 cur := version
1600 if strings.HasPrefix(cur, "v") {
1601 cur = cur[1:]
1602 }
1603 if latestTag == "" || cur == latestTag {
1604 fmt.Println("Already up to date.")
1605 return nil
1606 }
1607
1608 // Detect Homebrew
1609 if _, err := exec.LookPath("brew"); err == nil {
1610 fmt.Println("Detected Homebrew — updating taps and attempting to upgrade via brew.")
1611
1612 updateCmd := exec.Command("brew", "update")
1613 updateCmd.Stdout = os.Stdout
1614 updateCmd.Stderr = os.Stderr
1615 if err := updateCmd.Run(); err != nil {
1616 fmt.Printf("Homebrew update failed: %v\n", err)
1617 // continue to attempt upgrade even if update failed
1618 }
1619
1620 upgradeCmd := exec.Command("brew", "upgrade", "floatpane/matcha/matcha")
1621 upgradeCmd.Stdout = os.Stdout
1622 upgradeCmd.Stderr = os.Stderr
1623 if err := upgradeCmd.Run(); err == nil {
1624 fmt.Println("Successfully upgraded via Homebrew.")
1625 return nil
1626 }
1627 fmt.Printf("Homebrew upgrade failed: %v\n", err)
1628 // fallthrough to other methods
1629 }
1630
1631 // Detect snap
1632 if _, err := exec.LookPath("snap"); err == nil {
1633 // Check if matcha is installed as a snap
1634 cmdCheck := exec.Command("snap", "list", "matcha")
1635 if err := cmdCheck.Run(); err == nil {
1636 fmt.Println("Detected Snap package — attempting to refresh.")
1637 cmd := exec.Command("snap", "refresh", "matcha")
1638 cmd.Stdout = os.Stdout
1639 cmd.Stderr = os.Stderr
1640 if err := cmd.Run(); err == nil {
1641 fmt.Println("Successfully refreshed snap.")
1642 return nil
1643 }
1644 fmt.Printf("Snap refresh failed: %v\n", err)
1645 // fallthrough
1646 }
1647 }
1648
1649 // Otherwise attempt to download the proper release asset and replace the binary.
1650 osName := runtime.GOOS
1651 arch := runtime.GOARCH
1652
1653 // Try to find a matching asset
1654 var assetURL, assetName string
1655 for _, a := range rel.Assets {
1656 n := strings.ToLower(a.Name)
1657 if strings.Contains(n, osName) && strings.Contains(n, arch) && (strings.HasSuffix(n, ".tar.gz") || strings.HasSuffix(n, ".tgz") || strings.HasSuffix(n, ".zip")) {
1658 assetURL = a.BrowserDownloadURL
1659 assetName = a.Name
1660 break
1661 }
1662 }
1663 if assetURL == "" {
1664 // Try any asset that contains 'matcha' and os/arch as a fallback
1665 for _, a := range rel.Assets {
1666 n := strings.ToLower(a.Name)
1667 if strings.Contains(n, "matcha") && (strings.Contains(n, osName) || strings.Contains(n, arch)) {
1668 assetURL = a.BrowserDownloadURL
1669 assetName = a.Name
1670 break
1671 }
1672 }
1673 }
1674
1675 if assetURL == "" {
1676 return fmt.Errorf("no suitable release artifact found for %s/%s", osName, arch)
1677 }
1678
1679 fmt.Printf("Found release asset: %s\n", assetName)
1680 fmt.Println("Downloading...")
1681
1682 // Download asset
1683 respAsset, err := http.Get(assetURL)
1684 if err != nil {
1685 return fmt.Errorf("download failed: %w", err)
1686 }
1687 defer respAsset.Body.Close()
1688
1689 // Create a temp file for the download
1690 tmpDir, err := os.MkdirTemp("", "matcha-update-*")
1691 if err != nil {
1692 return fmt.Errorf("could not create temp dir: %w", err)
1693 }
1694 defer os.RemoveAll(tmpDir)
1695
1696 assetPath := filepath.Join(tmpDir, assetName)
1697 outFile, err := os.Create(assetPath)
1698 if err != nil {
1699 return fmt.Errorf("could not create temp file: %w", err)
1700 }
1701 _, err = io.Copy(outFile, respAsset.Body)
1702 outFile.Close()
1703 if err != nil {
1704 return fmt.Errorf("could not write asset to disk: %w", err)
1705 }
1706
1707 // If it's a tar.gz, extract and find the `matcha` binary
1708 var binPath string
1709 if strings.HasSuffix(assetName, ".tar.gz") || strings.HasSuffix(assetName, ".tgz") {
1710 f, err := os.Open(assetPath)
1711 if err != nil {
1712 return fmt.Errorf("could not open archive: %w", err)
1713 }
1714 defer f.Close()
1715 gzr, err := gzip.NewReader(f)
1716 if err != nil {
1717 return fmt.Errorf("could not create gzip reader: %w", err)
1718 }
1719 tr := tar.NewReader(gzr)
1720 for {
1721 hdr, err := tr.Next()
1722 if err == io.EOF {
1723 break
1724 }
1725 if err != nil {
1726 return fmt.Errorf("error reading tar: %w", err)
1727 }
1728 name := filepath.Base(hdr.Name)
1729 if name == "matcha" || strings.Contains(strings.ToLower(name), "matcha") && (hdr.Typeflag == tar.TypeReg) {
1730 // write out the file
1731 binPath = filepath.Join(tmpDir, "matcha")
1732 out, err := os.Create(binPath)
1733 if err != nil {
1734 return fmt.Errorf("could not create binary file: %w", err)
1735 }
1736 if _, err := io.Copy(out, tr); err != nil {
1737 out.Close()
1738 return fmt.Errorf("could not extract binary: %w", err)
1739 }
1740 out.Close()
1741 if err := os.Chmod(binPath, 0755); err != nil {
1742 return fmt.Errorf("could not make binary executable: %w", err)
1743 }
1744 break
1745 }
1746 }
1747 } else {
1748 // For non-archive assets, assume the asset is the binary itself.
1749 binPath = assetPath
1750 if err := os.Chmod(binPath, 0755); err != nil {
1751 // ignore chmod errors but warn
1752 fmt.Printf("warning: could not chmod downloaded binary: %v\n", err)
1753 }
1754 }
1755
1756 if binPath == "" {
1757 return fmt.Errorf("could not locate matcha binary inside the release artifact")
1758 }
1759
1760 // Replace the running executable with the new binary
1761 execPath, err := os.Executable()
1762 if err != nil {
1763 return fmt.Errorf("could not determine executable path: %w", err)
1764 }
1765
1766 // Write the new binary to a temp file in same dir, then rename for atomic replacement.
1767 execDir := filepath.Dir(execPath)
1768 tmpNew := filepath.Join(execDir, fmt.Sprintf("matcha.new.%d", time.Now().Unix()))
1769 in, err := os.Open(binPath)
1770 if err != nil {
1771 return fmt.Errorf("could not open new binary: %w", err)
1772 }
1773 out, err := os.OpenFile(tmpNew, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0755)
1774 if err != nil {
1775 in.Close()
1776 return fmt.Errorf("could not create temp binary in target dir: %w", err)
1777 }
1778 if _, err := io.Copy(out, in); err != nil {
1779 in.Close()
1780 out.Close()
1781 return fmt.Errorf("could not write new binary to disk: %w", err)
1782 }
1783 in.Close()
1784 out.Close()
1785
1786 // Attempt to atomically replace
1787 if err := os.Rename(tmpNew, execPath); err != nil {
1788 return fmt.Errorf("could not replace executable: %w", err)
1789 }
1790
1791 fmt.Println("Successfully updated matcha to", latestTag)
1792 return nil
1793}
1794
1795func main() {
1796 // If invoked as CLI update command, run updater and exit.
1797 if len(os.Args) > 1 && os.Args[1] == "update" {
1798 if err := runUpdateCLI(); err != nil {
1799 fmt.Fprintf(os.Stderr, "update failed: %v\n", err)
1800 os.Exit(1)
1801 }
1802 os.Exit(0)
1803 }
1804
1805 cfg, err := config.LoadConfig()
1806 var initialModel *mainModel
1807 if err != nil {
1808 initialModel = newInitialModel(nil)
1809 } else {
1810 initialModel = newInitialModel(cfg)
1811 }
1812
1813 p := tea.NewProgram(initialModel, tea.WithAltScreen())
1814
1815 if _, err := p.Run(); err != nil {
1816 fmt.Printf("Alas, there's been an error: %v", err)
1817 os.Exit(1)
1818 }
1819}