8000 feat: add external mailbox integration and message actions by Abyxs · Pull Request #4 · xiaozhou26/icloud-hme · GitHub
[go: up one dir, main page]

Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 69 additions & 19 deletions internal/account/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,28 +20,37 @@ import (

// Account 描述一个 iCloud 账号。
type Account struct {
ID string `json:"id"`
Name string `json:"name"`
RealEmail string `json:"real_email"`
ICloudEmail string `json:"icloud_email"`
Cookies map[string]string `json:"cookies"`
Host string `json:"host"`
Proxy string `json:"proxy,omitempty"` // HTTP/SOCKS5 代理
AppPassword string `json:"app_password,omitempty"`
Status string `json:"status"` // active / error
AliasTotal int `json:"alias_total"`
AliasActive int `json:"alias_active"`
LastValidated string `json:"last_validated"`
LastError string `json:"last_error,omitempty"`
CreatedAt string `json:"created_at"`
ID string `json:"id"`
Name string `json:"name"`
RealEmail string `json:"real_email"`
ICloudEmail string `json:"icloud_email"`
Cookies map[string]string `json:"cookies"`
Host string `json:"host"`
Proxy string `json:"proxy,omitempty"` // HTTP/SOCKS5 代理
AppPassword string `json:"app_password,omitempty"`
Mailbox *MailboxConfig `json:"mailbox,omitempty"`
Status string `json:"status"` // active / error
AliasTotal int `json:"alias_total"`
AliasActive int `json:"alias_active"`
LastValidated string `json:"last_validated"`
LastError string `json:"last_error,omitempty"`
CreatedAt string `json:"created_at"`
}

type MailboxConfig struct {
Provider string `json:"provider"`
Email string `json:"email"`
IMAPHost string `json:"imap_host"`
IMAPPort int `json:"imap_port"`
Password string `json:"password,omitempty"`
}

// Manager 管理多个 iCloud 账号,线程安全。
type Manager struct {
mu sync.Mutex
accounts map[string]*Account
dataDir string
dataFile string
mu sync.Mutex
accounts map[string]*Account
dataDir string
dataFile string
}

// NewManager 创建管理器。dataDir 用于存放 accounts.json。
Expand Down Expand Up @@ -90,7 +99,7 @@ func (m *Manager) load() error {

func (m *Manager) save() error {
wrapper := struct {
Accounts map[string]*Account `json:"accounts"`
Accounts map[string]*Account `json:"accounts"`
UpdatedAt string `json:"updated_at"`
}{
Accounts: m.accounts,
Expand Down Expand Up @@ -248,6 +257,12 @@ func (m *Manager) ListAccounts() []*Account {
for _, acc := range m.accounts {
cp := *acc
cp.Cookies = nil
cp.AppPassword = ""
if acc.Mailbox != nil {
mailbox := *acc.Mailbox
mailbox.Password = ""
cp.Mailbox = &mailbox
}
out = append(out, &cp)
}
return out
Expand Down Expand Up @@ -313,6 +328,9 @@ func (m *Manager) MailClient(id string) (*mail.Client, error) {
if !ok {
return nil, fmt.Errorf("账号不存在: %s", id)
}
if acc.Mailbox != nil && acc.Mailbox.Email != "" && acc.Mailbox.Password != "" {
return mail.NewClientWithServer(acc.Mailbox.Email, acc.Mailbox.Password, acc.Mailbox.IMAPHost, acc.Mailbox.IMAPPort), nil
}
imapEmail := acc.ICloudEmail
if imapEmail == "" {
imapEmail = acc.RealEmail
Expand All @@ -326,6 +344,38 @@ func (m *Manager) MailClient(id string) (*mail.Client, error) {
return mail.NewClient(imapEmail, acc.AppPassword), nil
}

func (m *Manager) SetMailbox(id string, config MailboxConfig) error {
config.Provider = strings.TrimSpace(config.Provider)
config.Email = strings.TrimSpace(config.Email)
config.IMAPHost = strings.TrimSpace(config.IMAPHost)
if config.Email == "" || config.IMAPHost == "" || config.Password == "" {
return fmt.Errorf("收件邮箱、IMAP 服务器和授权码不能为空")
}
if strings.Contains(config.IMAPHost, "://") || config.IMAPPort < 1 || config.IMAPPort > 65535 {
return fmt.Errorf("IMAP 服务器或端口无效")
}
m.mu.Lock()
acc, ok := m.accounts[id]
m.mu.Unlock()
if !ok {
return fmt.Errorf("账号不存在: %s", id)
}
mc := mail.NewClientWithServer(config.Email, config.Password, config.IMAPHost, config.IMAPPort)
if err := mc.Connect(); err != nil {
return err
}
_, err := mc.InboxCount()
mc.Disconnect()
if err != nil {
return err
}
m.mu.Lock()
acc.Mailbox = &config
err = m.save()
m.mu.Unlock()
return err
}

// WebMailClient 为指定账号创建 Web 邮件客户端。
// 使用 Cookie 认证,无需 App Password。
func (m *Manager) WebMailClient(id string) (*mail.WebClient, error) {
Expand Down
59 changes: 39 additions & 20 deletions internal/mail/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"mime/quotedprintable"
"net/mail"
"regexp"
"sort"
"strings"
"time"

Expand Down Expand Up @@ -43,25 +44,32 @@ type FullMessage struct {

// Client 是 iCloud 邮件 IMAP 客户端。
type Client struct {
appleID string
appPassword string
cli *client.Client
username string
password string
server string
port int
cli *client.Client
}

// NewClient 创建 IMAP 客户端。需在调用其它方法前先 Connect。
func NewClient(appleID, appPassword string) *Client {
return &Client{appleID: appleID, appPassword: appPassword}
return NewClientWithServer(appleID, appPassword, IMAPServer, IMAPPort)
}

func NewClientWithServer(username, password, server string, port int) *Client {
return &Client{username: username, password: password, server: server, port: port}
}

// Connect 连接并登录 IMAP 服务器。
func (c *Client) Connect() error {
addr := fmt.Sprintf("%s:%d", IMAPServer, IMAPPort)
addr := fmt.Sprintf("%s:%d", c.server, c.port)
cli, err := client.DialTLS(addr, nil)
if err != nil {
return fmt.Errorf("IMAP 连接失败: %w", err)
}
if err := cli.Login(c.appleID, c.appPassword); err != nil {
return fmt.Errorf("IMAP 登录失败 — 请检查: 1) 应用专用密码是否正确 2) Apple ID: %s — %w", c.appleID, err)
if err := cli.Login(c.username, c.password); err != nil {
_ = cli.Logout()
return fmt.Errorf("IMAP 登录失败 — 请检查邮箱账号、授权码和服务器地址: %w", err)
}
c.cli = cli
return nil
Expand Down Expand Up @@ -137,7 +145,7 @@ func (c *Client) ListInbox(limit int, days int) ([]Message, error) {
m := toMessageWithBody(msg)
// days 过滤
if days > 0 {
if t, err := time.Parse(time.RFC1123Z, m.Date); err == nil {
if t, err := time.Parse(time.RFC3339, m.Date); err == nil {
if time.Since(t) > time.Duration(days)*24*time.Hour {
continue
}
Expand All @@ -148,6 +156,7 @@ func (c *Client) ListInbox(limit int, days int) ([]Message, error) {
if err := <-done; err != nil {
return nil, err
}
sort.SliceStable(out, func(i, j int) bool { return out[i].Date > out[j].Date })
return out, nil
}

Expand Down Expand Up @@ -226,6 +235,7 @@ func (c *Client) fetchByUIDs(uids []uint32, limit int) ([]Message, error) {
if err := <-done; err != nil {
return nil, err
}
sort.SliceStable(out, func(i, j int) bool { return out[i].Date > out[j].Date })
return out, nil
}

Expand All @@ -237,37 +247,46 @@ func (c *Client) GetFull(uid uint32) (*FullMessage, error) {
if _, err := c.cli.Select("INBOX", true); err != nil {
return nil, err
}

seqset := new(imap.SeqSet)
seqset.AddNum(uid)

items := []imap.FetchItem{imap.FetchUid, imap.FetchEnvelope, imap.FetchInternalDate, imap.FetchRFC822}
section := &imap.BodySectionName{}
messages := make(chan *imap.Message, 1)
done := make(chan error, 1)
go func() {
done <- c.cli.UidFetch(seqset, items, messages)
done <- c.cli.UidFetch(seqset, []imap.FetchItem{imap.FetchUid, imap.FetchEnvelope, imap.FetchInternalDate, section.FetchItem()}, messages)
}()

msg := <-messages
if err := <-done; err != nil {
return nil, err
}
if msg == nil {
return nil, fmt.Errorf("邮件不存在 (uid=%d)", uid)
}

full := &FullMessage{Message: toMessage(msg)}
// 解析正文
if r := msg.GetBody(&imap.BodySectionName{}); r != nil {
if em, err := mail.ReadMessage(r); err == nil {
body, _ := readBody(em)
full.Body = body
full.ContentType = em.Header.Get("Content-Type")
if reader := msg.GetBody(section); reader != nil {
if parsed, err := mail.ReadMessage(reader); err == nil {
full.Body, _ = readBody(parsed)
full.ContentType = parsed.Header.Get("Content-Type")
}
}
return full, nil
}

func (c *Client) Delete(uid uint32) error {
if c.cli == nil {
return fmt.Errorf("未连接")
}
if _, err := c.cli.Select("INBOX", false); err != nil {
return err
}
seqset := new(imap.SeqSet)
seqset.AddNum(uid)
if err := c.cli.UidStore(seqset, imap.FormatFlagsOp(imap.AddFlags, true), []interface{}{imap.DeletedFlag}, nil); err != nil {
return err
}
return c.cli.Expunge(nil)
}

// ---- 解析工具 ----

func toMessage(msg *imap.Message) Message {
Expand Down
90 changes: 86 additions & 4 deletions internal/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ func New(mgr *account.Manager, debug bool) *Server {
}
s := &Server{mgr: mgr}
s.r = gin.Default() // 自带 Logger + Recovery 中间件
s.registerUI()
s.register()
return s
}
Expand All @@ -51,6 +52,7 @@ func (s *Server) register() {
api.POST("/accounts", s.addAccount)
api.DELETE("/accounts/:id", s.removeAccount)
api.POST("/accounts/:id/password", s.setAppPassword)
api.PUT("/accounts/:id/mailbox", s.setMailbox)
api.PUT("/accounts/:id/cookies", s.updateCookies)
api.POST("/accounts/:id/login", s.loginAccount)

Expand All @@ -59,6 +61,8 @@ func (s *Server) register() {

// ===== 核心接口 2: 读取邮件 =====
api.GET("/inbox", s.listInbox)
api.GET("/inbox/:message_id", s.getMessage)
api.DELETE("/inbox/:message_id", s.deleteMessage)

// ===== 别名管理 =====
api.GET("/aliases", s.listAliases)
Expand Down Expand Up @@ -218,6 +222,55 @@ func (s *Server) listInbox(c *gin.Context) {
}
}

func (s *Server) getMessage(c *gin.Context) {
accountID := c.Query("account_id")
uid, err := strconv.ParseUint(c.Param("message_id"), 10, 32)
if accountID == "" || err != nil {
fail(c, http.StatusBadRequest, "account_id 或邮件 ID 无效")
return
}
mc, err := s.mgr.MailClient(accountID)
if err != nil {
fail(c, http.StatusBadRequest, err.Error())
return
}
if err = mc.Connect(); err != nil {
fail(c, http.StatusBadGateway, err.Error())
return
}
defer mc.Disconnect()
message, err := mc.GetFull(uint32(uid))
if err != nil {
fail(c, http.StatusBadGateway, "读取邮件详情失败: "+err.Error())
return
}
ok(c, message)
}

func (s *Server) deleteMessage(c *gin.Context) {
accountID := c.Query("account_id")
uid, err := strconv.ParseUint(c.Param("message_id"), 10, 10ACF 32)
if accountID == "" || err != nil {
fail(c, http.StatusBadRequest, "account_id 或邮件 ID 无效")
return
}
mc, err := s.mgr.MailClient(accountID)
if err != nil {
fail(c, http.StatusBadRequest, err.Error())
return
}
if err = mc.Connect(); err != nil {
fail(c, http.StatusBadGateway, err.Error())
return
}
defer mc.Disconnect()
if err = mc.Delete(uint32(uid)); err != nil {
fail(c, http.StatusBadGateway, err.Error())
return
}
ok(c, gin.H{"id": c.Param("message_id")})
}

// ====================================================================
// 辅助接口
// ====================================================================
Expand All @@ -227,10 +280,10 @@ func (s *Server) listAccounts(c *gin.Context) {
}

type addAccountReq struct {
Name string `json:"name" binding:"required"`
Cookies string `json:"cookies"` // 可选,后续可通过 /login 获取
Host string `json:"host"`
Proxy string `json:"proxy"` // HTTP/SOCKS5 代理
Name string `json:"name" binding:"required"`
Cookies string `json:"cookies"` // 可选,后续可通过 /login 获取
Host string `json:"host"`
Proxy string `json:"proxy"` // HTTP/SOCKS5 代理
}

func (s *Server) addAccount(c *gin.Context) {
Expand Down Expand Up @@ -277,6 +330,35 @@ func (s *Server) setAppPassword(c *gin.Context) {
ok(c, gin.H{"id": id, "icloud_email": req.ICloudEmail})
}

type mailboxReq struct {
Provider string `json:"provider"`
Email string `json:"email" binding:"required"`
IMAPHost string `json:"imap_host" binding:"required"`
IMAPPort int `json:"imap_port" binding:"required"`
AuthorizationCode string `json:"authorization_code" binding:"required"`
}

func (s *Server) setMailbox(c *gin.Context) {
id := c.Param("id")
var req mailboxReq
if err := c.ShouldBindJSON(&req); err != nil {
fail(c, http.StatusBadRequest, "参数错误: 邮箱、IMAP 服务器、端口和授权码必填 — "+err.Error())
return
}
config := account.MailboxConfig{
Provider: req.Provider,
Email: req.Email,
IMAPHost: req.IMAPHost,
IMAPPort: req.IMAPPort,
Password: req.AuthorizationCode,
}
if err := s.mgr.SetMailbox(id, config); err != nil {
fail(c, http.StatusBadRequest, "收件邮箱接入失败: "+err.Error())
return
}
ok(c, gin.H{"id": id, "email": req.Email, "imap_host": req.IMAPHost, "imap_port": req.IMAPPort})
}

type updateCookiesReq struct {
Cookies map[string]string `json:"cookies" binding:"required"`
}
Expand Down
Loading
0