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