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		return m, nil
180
181	case tui.SendEmailMsg:
182		m.cachedComposer = nil // Clear cache on successful send
183		m.current = tui.NewStatus("Sending email...")
184		return m, tea.Batch(m.current.Init(), sendEmail(m.config, msg))
185
186	case tui.EmailResultMsg:
187		m.current = tui.NewChoice(m.cachedComposer != nil)
188		return m, m.current.Init()
189
190	case tui.DeleteEmailMsg:
191		m.previousModel = m.current
192		m.current = tui.NewStatus("Deleting email...")
193		return m, tea.Batch(m.current.Init(), deleteEmailCmd(m.config, msg.UID))
194
195	case tui.ArchiveEmailMsg:
196		m.previousModel = m.current
197		m.current = tui.NewStatus("Archiving email...")
198		return m, tea.Batch(m.current.Init(), archiveEmailCmd(m.config, msg.UID))
199
200	case tui.EmailActionDoneMsg:
201		if msg.Err != nil {
202			log.Printf("Action failed: %v", msg.Err)
203			m.current = m.inbox
204			return m, nil
205		}
206		var updatedEmails []fetcher.Email
207		for _, email := range m.emails {
208			if email.UID != msg.UID {
209				updatedEmails = append(updatedEmails, email)
210			}
211		}
212		m.emails = updatedEmails
213		m.inbox = tui.NewInbox(m.emails)
214		m.current = m.inbox
215		m.current, _ = m.current.Update(tea.WindowSizeMsg{Width: m.width, Height: m.height})
216		return m, m.current.Init()
217
218	case tui.DownloadAttachmentMsg:
219		m.previousModel = m.current
220		m.current = tui.NewStatus(fmt.Sprintf("Downloading %s...", msg.Filename))
221		return m, tea.Batch(m.current.Init(), downloadAttachmentCmd(msg))
222
223	case tui.AttachmentDownloadedMsg:
224		var statusMsg string
225		if msg.Err != nil {
226			statusMsg = fmt.Sprintf("Error downloading: %v", msg.Err)
227		} else {
228			statusMsg = fmt.Sprintf("Saved to %s", msg.Path)
229		}
230		m.current = tui.NewStatus(statusMsg)
231		return m, tea.Tick(2*time.Second, func(t time.Time) tea.Msg {
232			return tui.RestoreViewMsg{}
233		})
234
235	case tui.RestoreViewMsg:
236		if m.previousModel != nil {
237			m.current = m.previousModel
238			m.previousModel = nil
239		}
240		return m, nil
241	}
242
243	return m, tea.Batch(cmds...)
244}
245
246func (m *mainModel) View() string {
247	return m.current.View()
248}
249
250func markdownToHTML(md []byte) []byte {
251	var buf bytes.Buffer
252	p := goldmark.New(goldmark.WithRendererOptions(html.WithUnsafe()))
253	if err := p.Convert(md, &buf); err != nil {
254		return md
255	}
256	return buf.Bytes()
257}
258
259func sendEmail(cfg *config.Config, msg tui.SendEmailMsg) tea.Cmd {
260	return func() tea.Msg {
261		recipients := []string{msg.To}
262		body := msg.Body
263		images := make(map[string][]byte)
264		attachments := make(map[string][]byte)
265
266		re := regexp.MustCompile(`!\[.*?\]\((.*?)\)`)
267		matches := re.FindAllStringSubmatch(body, -1)
268
269		for _, match := range matches {
270			imgPath := match[1]
271			imgData, err := os.ReadFile(imgPath)
272			if err != nil {
273				log.Printf("Could not read image file %s: %v", imgPath, err)
274				continue
275			}
276			cid := fmt.Sprintf("%s%s@%s", uuid.NewString(), filepath.Ext(imgPath), "email-cli")
277			images[cid] = []byte(base64.StdEncoding.EncodeToString(imgData))
278			body = strings.Replace(body, imgPath, "cid:"+cid, 1)
279		}
280
281		htmlBody := markdownToHTML([]byte(body))
282
283		if msg.AttachmentPath != "" {
284			fileData, err := os.ReadFile(msg.AttachmentPath)
285			if err != nil {
286				log.Printf("Could not read attachment file %s: %v", msg.AttachmentPath, err)
287			} else {
288				_, filename := filepath.Split(msg.AttachmentPath)
289				attachments[filename] = fileData
290			}
291		}
292
293		err := sender.SendEmail(cfg, recipients, msg.Subject, msg.Body, string(htmlBody), images, attachments, msg.InReplyTo, msg.References)
294		if err != nil {
295			log.Printf("Failed to send email: %v", err)
296			return tui.EmailResultMsg{Err: err}
297		}
298		return tui.EmailResultMsg{}
299	}
300}
301
302func fetchEmails(cfg *config.Config, limit, offset uint32) tea.Cmd {
303	return func() tea.Msg {
304		emails, err := fetcher.FetchEmails(cfg, limit, offset)
305		if err != nil {
306			return tui.FetchErr(err)
307		}
308		if offset == 0 {
309			return tui.EmailsFetchedMsg{Emails: emails}
310		}
311		return tui.EmailsAppendedMsg{Emails: emails}
312	}
313}
314
315func deleteEmailCmd(cfg *config.Config, uid uint32) tea.Cmd {
316	return func() tea.Msg {
317		err := fetcher.DeleteEmail(cfg, uid)
318		return tui.EmailActionDoneMsg{UID: uid, Err: err}
319	}
320}
321
322func archiveEmailCmd(cfg *config.Config, uid uint32) tea.Cmd {
323	return func() tea.Msg {
324		err := fetcher.ArchiveEmail(cfg, uid)
325		return tui.EmailActionDoneMsg{UID: uid, Err: err}
326	}
327}
328
329func downloadAttachmentCmd(msg tui.DownloadAttachmentMsg) tea.Cmd {
330	return func() tea.Msg {
331		homeDir, err := os.UserHomeDir()
332		if err != nil {
333			return tui.AttachmentDownloadedMsg{Err: err}
334		}
335		downloadsPath := filepath.Join(homeDir, "Downloads")
336		if _, err := os.Stat(downloadsPath); os.IsNotExist(err) {
337			if mkErr := os.MkdirAll(downloadsPath, 0755); mkErr != nil {
338				return tui.AttachmentDownloadedMsg{Err: mkErr}
339			}
340		}
341		filePath := filepath.Join(downloadsPath, msg.Filename)
342		err = os.WriteFile(filePath, msg.Data, 0644)
343		return tui.AttachmentDownloadedMsg{Path: filePath, Err: err}
344	}
345}
346
347func main() {
348	cfg, err := config.LoadConfig()
349	var initialModel *mainModel
350	if err != nil {
351		initialModel = newInitialModel(nil)
352	} else {
353		initialModel = newInitialModel(cfg)
354	}
355
356	p := tea.NewProgram(initialModel, tea.WithAltScreen())
357
358	if _, err := p.Run(); err != nil {
359		fmt.Printf("Alas, there's been an error: %v", err)
360		os.Exit(1)
361	}
362}