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