main.go

  1package main
  2
  3import (
  4	"bytes"
  5	"encoding/base64"
  6	"fmt"
  7	"log"
  8	"os"
  9	"path/filepath"
 10	"regexp"
 11	"strings"
 12	"time"
 13
 14	"github.com/andrinoff/email-cli/config"
 15	"github.com/andrinoff/email-cli/fetcher"
 16	"github.com/andrinoff/email-cli/sender"
 17	"github.com/andrinoff/email-cli/tui"
 18	tea "github.com/charmbracelet/bubbletea"
 19	"github.com/google/uuid"
 20	"github.com/yuin/goldmark"
 21	"github.com/yuin/goldmark/renderer/html"
 22)
 23
 24const (
 25	initialEmailLimit = 20
 26	paginationLimit   = 20
 27)
 28
 29type mainModel struct {
 30	current        tea.Model
 31	previousModel  tea.Model
 32	cachedComposer *tui.Composer // To cache a discarded draft
 33	config         *config.Config
 34	emails         []fetcher.Email
 35	inbox          *tui.Inbox
 36	width          int
 37	height         int
 38	err            error
 39}
 40
 41func newInitialModel(cfg *config.Config) *mainModel {
 42	// Determine if there is a cached composer to pass to the initial choice view
 43	hasCache := false
 44	initialModel := &mainModel{}
 45	if cfg == nil {
 46		initialModel.current = tui.NewLogin()
 47	} else {
 48		initialModel.current = tui.NewChoice(hasCache)
 49		initialModel.config = cfg
 50	}
 51	return initialModel
 52}
 53
 54func (m *mainModel) Init() tea.Cmd {
 55	return m.current.Init()
 56}
 57
 58func (m *mainModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
 59	var cmd tea.Cmd
 60	var cmds []tea.Cmd
 61
 62	m.current, cmd = m.current.Update(msg)
 63	cmds = append(cmds, cmd)
 64
 65	switch msg := msg.(type) {
 66	case tea.WindowSizeMsg:
 67		m.width = msg.Width
 68		m.height = msg.Height
 69		return m, nil
 70
 71	case tea.KeyMsg:
 72		if msg.String() == "ctrl+c" {
 73			return m, tea.Quit
 74		}
 75		if msg.String() == "esc" {
 76			switch m.current.(type) {
 77			case *tui.FilePicker:
 78				return m, func() tea.Msg { return tui.CancelFilePickerMsg{} }
 79			case *tui.Inbox, *tui.Login:
 80				m.current = tui.NewChoice(m.cachedComposer != nil)
 81				return m, m.current.Init()
 82			}
 83		}
 84
 85	case tui.BackToInboxMsg:
 86		if m.inbox != nil {
 87			m.current = m.inbox
 88		} else {
 89			m.current = tui.NewChoice(m.cachedComposer != nil)
 90		}
 91		return m, nil
 92
 93	case tui.DiscardDraftMsg:
 94		m.cachedComposer = msg.ComposerState
 95		m.current = tui.NewChoice(true) // Now there is a cached draft
 96		return m, m.current.Init()
 97
 98	case tui.RestoreDraftMsg:
 99		if m.cachedComposer != nil {
100			m.current = m.cachedComposer
101			m.cachedComposer.ResetConfirmation()
102			m.cachedComposer = nil // Clear cache after restoring
103			return m, m.current.Init()
104		}
105
106	case tui.Credentials:
107		cfg := &config.Config{
108			ServiceProvider: msg.Provider,
109			Name:            msg.Name,
110			Email:           msg.Email,
111			Password:        msg.Password,
112		}
113		if err := config.SaveConfig(cfg); err != nil {
114			log.Printf("could not save config: %v", err)
115			return m, tea.Quit
116		}
117		m.config = cfg
118		m.current = tui.NewChoice(m.cachedComposer != nil)
119		return m, m.current.Init()
120
121	case tui.GoToInboxMsg:
122		m.current = tui.NewStatus("Fetching emails...")
123		return m, tea.Batch(m.current.Init(), fetchEmails(m.config, initialEmailLimit, 0))
124
125	case tui.EmailsFetchedMsg:
126		m.emails = msg.Emails
127		m.inbox = tui.NewInbox(m.emails)
128		m.current = m.inbox
129		m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
130		return m, m.current.Init()
131
132	case tui.FetchMoreEmailsMsg:
133		return m, tea.Batch(
134			func() tea.Msg { return tui.FetchingMoreEmailsMsg{} },
135			fetchEmails(m.config, paginationLimit, msg.Offset),
136		)
137
138	case tui.EmailsAppendedMsg:
139		m.emails = append(m.emails, msg.Emails...)
140		return m, nil
141
142	case tui.GoToSendMsg:
143		// When composing a new email, we discard any previously cached draft.
144		m.cachedComposer = nil
145		m.current = tui.NewComposer(m.config.Email, msg.To, msg.Subject, msg.Body)
146		m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
147		return m, m.current.Init()
148
149	case tui.GoToSettingsMsg:
150		m.current = tui.NewLogin()
151		m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
152		return m, m.current.Init()
153
154	case tui.ViewEmailMsg:
155		emailView := tui.NewEmailView(m.emails[msg.Index], m.width, m.height)
156		m.current = emailView
157		return m, m.current.Init()
158
159	case tui.ReplyToEmailMsg:
160		to := msg.Email.From
161		subject := "Re: " + msg.Email.Subject
162		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> "))
163		m.current = tui.NewComposer(m.config.Email, to, subject, body)
164		m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
165		return m, m.current.Init()
166
167	case tui.GoToFilePickerMsg:
168		m.previousModel = m.current
169		wd, _ := os.Getwd()
170		m.current = tui.NewFilePicker(wd)
171		m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
172		return m, m.current.Init()
173
174	case tui.FileSelectedMsg, tui.CancelFilePickerMsg:
175		if m.previousModel != nil {
176			m.current = m.previousModel
177			m.previousModel = nil
178		}
179		m.current, cmd = m.current.Update(msg)
180		cmds = append(cmds, cmd)
181
182	case tui.SendEmailMsg:
183		m.cachedComposer = nil // Clear cache on successful send
184		m.current = tui.NewStatus("Sending email...")
185		return m, tea.Batch(m.current.Init(), sendEmail(m.config, msg))
186
187	case tui.EmailResultMsg:
188		m.current = tui.NewChoice(m.cachedComposer != nil)
189		return m, m.current.Init()
190
191	case tui.DeleteEmailMsg:
192		m.previousModel = m.current
193		m.current = tui.NewStatus("Deleting email...")
194		return m, tea.Batch(m.current.Init(), deleteEmailCmd(m.config, msg.UID))
195
196	case tui.ArchiveEmailMsg:
197		m.previousModel = m.current
198		m.current = tui.NewStatus("Archiving email...")
199		return m, tea.Batch(m.current.Init(), archiveEmailCmd(m.config, msg.UID))
200
201	case tui.EmailActionDoneMsg:
202		if msg.Err != nil {
203			log.Printf("Action failed: %v", msg.Err)
204			m.current = m.inbox
205			return m, nil
206		}
207		var updatedEmails []fetcher.Email
208		for _, email := range m.emails {
209			if email.UID != msg.UID {
210				updatedEmails = append(updatedEmails, email)
211			}
212		}
213		m.emails = updatedEmails
214		m.inbox = tui.NewInbox(m.emails)
215		m.current = m.inbox
216		m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
217		return m, m.current.Init()
218
219	case tui.DownloadAttachmentMsg:
220		m.previousModel = m.current
221		m.current = tui.NewStatus(fmt.Sprintf("Downloading %s...", msg.Filename))
222		return m, tea.Batch(m.current.Init(), downloadAttachmentCmd(msg))
223
224	case tui.AttachmentDownloadedMsg:
225		var statusMsg string
226		if msg.Err != nil {
227			statusMsg = fmt.Sprintf("Error downloading: %v", msg.Err)
228		} else {
229			statusMsg = fmt.Sprintf("Saved to %s", msg.Path)
230		}
231		m.current = tui.NewStatus(statusMsg)
232		return m, tea.Tick(2*time.Second, func(t time.Time) tea.Msg {
233			return tui.RestoreViewMsg{}
234		})
235
236	case tui.RestoreViewMsg:
237		if m.previousModel != nil {
238			m.current = m.previousModel
239			m.previousModel = nil
240		}
241		return m, nil
242	}
243
244	return m, tea.Batch(cmds...)
245}
246
247func (m *mainModel) View() string {
248	return m.current.View()
249}
250
251func markdownToHTML(md []byte) []byte {
252	var buf bytes.Buffer
253	p := goldmark.New(goldmark.WithRendererOptions(html.WithUnsafe()))
254	if err := p.Convert(md, &buf); err != nil {
255		return md
256	}
257	return buf.Bytes()
258}
259
260func sendEmail(cfg *config.Config, msg tui.SendEmailMsg) tea.Cmd {
261	return func() tea.Msg {
262		recipients := []string{msg.To}
263		body := msg.Body
264		images := make(map[string][]byte)
265		attachments := make(map[string][]byte)
266
267		re := regexp.MustCompile(`!\[.*?\]\((.*?)\)`)
268		matches := re.FindAllStringSubmatch(body, -1)
269
270		for _, match := range matches {
271			imgPath := match[1]
272			imgData, err := os.ReadFile(imgPath)
273			if err != nil {
274				log.Printf("Could not read image file %s: %v", imgPath, err)
275				continue
276			}
277			cid := fmt.Sprintf("%s%s@%s", uuid.NewString(), filepath.Ext(imgPath), "email-cli")
278			images[cid] = []byte(base64.StdEncoding.EncodeToString(imgData))
279			body = strings.Replace(body, imgPath, "cid:"+cid, 1)
280		}
281
282		htmlBody := markdownToHTML([]byte(body))
283
284		if msg.AttachmentPath != "" {
285			fileData, err := os.ReadFile(msg.AttachmentPath)
286			if err != nil {
287				log.Printf("Could not read attachment file %s: %v", msg.AttachmentPath, err)
288			} else {
289				_, filename := filepath.Split(msg.AttachmentPath)
290				attachments[filename] = fileData
291			}
292		}
293
294		err := sender.SendEmail(cfg, recipients, msg.Subject, msg.Body, string(htmlBody), images, attachments, msg.InReplyTo, msg.References)
295		if err != nil {
296			log.Printf("Failed to send email: %v", err)
297			return tui.EmailResultMsg{Err: err}
298		}
299		return tui.EmailResultMsg{}
300	}
301}
302
303func fetchEmails(cfg *config.Config, limit, offset uint32) tea.Cmd {
304	return func() tea.Msg {
305		emails, err := fetcher.FetchEmails(cfg, limit, offset)
306		if err != nil {
307			return tui.FetchErr(err)
308		}
309		if offset == 0 {
310			return tui.EmailsFetchedMsg{Emails: emails}
311		}
312		return tui.EmailsAppendedMsg{Emails: emails}
313	}
314}
315
316func deleteEmailCmd(cfg *config.Config, uid uint32) tea.Cmd {
317	return func() tea.Msg {
318		err := fetcher.DeleteEmail(cfg, uid)
319		return tui.EmailActionDoneMsg{UID: uid, Err: err}
320	}
321}
322
323func archiveEmailCmd(cfg *config.Config, uid uint32) tea.Cmd {
324	return func() tea.Msg {
325		err := fetcher.ArchiveEmail(cfg, uid)
326		return tui.EmailActionDoneMsg{UID: uid, Err: err}
327	}
328}
329
330func downloadAttachmentCmd(msg tui.DownloadAttachmentMsg) tea.Cmd {
331	return func() tea.Msg {
332		homeDir, err := os.UserHomeDir()
333		if err != nil {
334			return tui.AttachmentDownloadedMsg{Err: err}
335		}
336		downloadsPath := filepath.Join(homeDir, "Downloads")
337		if _, err := os.Stat(downloadsPath); os.IsNotExist(err) {
338			if mkErr := os.MkdirAll(downloadsPath, 0755); mkErr != nil {
339				return tui.AttachmentDownloadedMsg{Err: mkErr}
340			}
341		}
342		filePath := filepath.Join(downloadsPath, msg.Filename)
343		err = os.WriteFile(filePath, msg.Data, 0644)
344		return tui.AttachmentDownloadedMsg{Path: filePath, Err: err}
345	}
346}
347
348func main() {
349	cfg, err := config.LoadConfig()
350	var initialModel *mainModel
351	if err != nil {
352		initialModel = newInitialModel(nil)
353	} else {
354		initialModel = newInitialModel(cfg)
355	}
356
357	p := tea.NewProgram(initialModel, tea.WithAltScreen())
358
359	if _, err := p.Run(); err != nil {
360		fmt.Printf("Alas, there's been an error: %v", err)
361		os.Exit(1)
362	}
363}