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

Skip to content
Merged
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
8000
Diff view
71 changes: 71 additions & 0 deletions internal/account/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ type Account struct {
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"`
Expand All @@ -37,6 +38,15 @@ type Account struct {
CreatedAt string `json:"created_at"`
}

// MailboxConfig describes an external mailbox used to receive forwarded mail.
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.RWMutex
Expand Down Expand Up @@ -399,6 +409,12 @@ func (m *Manager) ListAccounts() []*Account {
for _, acc := range m.accounts {
cp := copyAccount(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 @@ -516,6 +532,9 @@ func (m *Manager) MailClient(id string) (*mail.Client, error) {
if !ok {
return nil, fmt.Errorf("账号不存在: %s", id)
}
if snap.Mailbox != nil && snap.Mailbox.Email != "" && snap.Mailbox.Password != "" {
return mail.NewClientWithServer(snap.Mailbox.Email, snap.Mailbox.Password, snap.Mailbox.IMAPHost, snap.Mailbox.IMAPPort), nil
}
imapEmail := snap.ICloudEmail
if imapEmail == "" {
imapEmail = snap.RealEmail
Expand All @@ -532,6 +551,22 @@ func (m *Manager) MailClient(id string) (*mail.Client, error) {
// WithMailClient 使用连接池中的长连接执行 fn(串行/账号级)。
// fn 返回后连接保留在池中, 不会 Logout。
func (m *Manager) WithMailClient(id string, fn func(*mail.Client) error) error {
m.mu.RLock()
acc, ok := m.accounts[id]
var mailbox *MailboxConfig
if ok && acc.Mailbox != nil {
copy := *acc.Mailbox
mailbox = &copy
}
m.mu.RUnlock()
if mailbox != nil && mailbox.Email != "" && mailbox.Password != "" {
mc := mail.NewClientWithServer(mailbox.Email, mailbox.Password, mailbox.IMAPHost, mailbox.IMAPPort)
if err := mc.Connect(); err != nil {
return err
}
defer mc.Disconnect()
return fn(mc)
}
imapEmail, appPassword, err := m.imapCreds(id)
if err != nil {
return err
Expand Down Expand Up @@ -566,6 +601,42 @@ func (m *Manager) imapCreds(id string) (imapEmail, appPassword string, err error
return imapEmail, snap.AppPassword, nil
}

// SetMailbox validates and stores an external IMAP mailbox after testing it.
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.RLock()
_, ok := m.accounts[id]
m.mu.RUnlock()
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()
defer m.mu.Unlock()
acc, ok := m.accounts[id]
if !ok {
return fmt.Errorf("账号不存在: %s", id)
}
acc.Mailbox = &config
return m.save()
}

// WebMailClient 为指定账号创建 Web 邮件客户端。
// 使用 Cookie 认证,无需 App Password。
func (m *Manager) WebMailClient(id string) (*mail.WebClient, error) {
Expand Down
39 changes: 25 additions & 14 deletions internal/account/public.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,20 +13,21 @@ import (

// Summary 是账号的安全公开表示,不含任何秘密字段。
type Summary struct {
ID string `json:"id"`
Name string `json:"name"`
RealEmail string `json:"real_email"`
ICloudEmail string `json:"icloud_email"`
Host string `json:"host"`
Status string `json:"status"`
AliasTotal int `json:"alias_total"`
AliasActive int `json:"alias_active"`
HasCookies bool `json:"has_cookies"`
HasAppPassword bool `json:"has_app_password"`
HasProxy bool `json:"has_proxy"`
LastValidated string `json:"last_validated"`
StatusMessage string `json:"status_message,omitempty"`
CreatedAt string `json:"created_at"`
ID string `json:"id"`
Name string `json:"name"`
RealEmail string `json:"real_email"`
ICloudEmail string `json:"icloud_email"`
Host string `json:"host"`
Status string `json:"status"`
AliasTotal int `json:"alias_total"`
AliasActive int `json:"alias_active"`
HasCookies bool `json:"has_cookies"`
HasAppPassword bool `json:"has_app_password"`
HasProxy bool `json:"has_proxy"`
Mailbox *MailboxSummary `json:"mailbox,omitempty"`
LastValidated string `json:"last_validated"`
StatusMessage string `json:"status_message,omitempty"`
CreatedAt string `json:"created_at"`
}

// Summary 返回账号的安全快照,忽略内部 LastError。
Expand All @@ -46,6 +47,9 @@ func (a *Account) Summary() Summary {
LastValidated: a.LastValidated,
CreatedAt: a.CreatedAt,
}
if a.Mailbox != nil {
s.Mailbox = &MailboxSummary{Provider: a.Mailbox.Provider, Email: a.Mailbox.Email, IMAPHost: a.Mailbox.IMAPHost, IMAPPort: a.Mailbox.IMAPPort}
}
switch a.Status {
case "pending":
s.StatusMessage = "等待配置或验证凭据"
Expand All @@ -55,6 +59,13 @@ func (a *Account) Summary() Summary {
return s
}

type MailboxSummary struct {
Provider string `json:"provider"`
Email string `json:"email"`
IMAPHost string `json:"imap_host"`
IMAPPort int `json:"imap_port"`
}

// AddAccountInput 是添加账号的输入。
type AddAccountInput struct {
Name string
Expand Down
23 changes: 16 additions & 7 deletions internal/mail/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"mime"
"mime/quotedprintable"
"net/mail"
"sort"
"strings"
"time"

Expand Down Expand Up @@ -42,14 +43,21 @@ 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)
}

// NewClientWithServer creates an IMAP client for a custom server.
func NewClientWithServer(username, password, server string, port int) *Client {
return &Client{username: username, password: password, server: server, port: port}
}

// Connect 连接并登录 IMAP 服务器。已连接且存活时直接复用。
Expand All @@ -60,14 +68,14 @@ func (c *Client) Connect() error {
}
c.forceClose()
}
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 {
if err := cli.Login(c.username, c.password); err != nil {
_ = cli.Logout()
return fmt.Errorf("IMAP 登录失败 — 请检查: 1) 应用专用密码是否正确 2) Apple ID: %s — %w", c.appleID, err)
return fmt.Errorf("IMAP 登录失败 — 请检查邮箱账号、授权码和服务器地址: %w", err)
}
c.cli = cli
return nil
Expand Down Expand Up @@ -170,6 +178,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
24 changes: 24 additions & 0 deletions internal/server/account_handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,30 @@ func (s *Server) setAppPasswordHandler(c *gin.Context) {
ok(c, sum)
}

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

func (s *Server) setMailboxHandler(c *gin.Context) {
var req setMailboxReq
if err := c.ShouldBindJSON(&req); err != nil || req.Email == "" || req.IMAPHost == "" || req.IMAPPort < 1 || req.AuthorizationCode == "" {
failCode(c, http.StatusBadRequest, "VALIDATION_ERROR", "参数错误: 收件邮箱、IMAP 服务器、端口和授权码必填")
return
}
sum, err := s.be.SetMailbox(c.Param("id"), account.MailboxConfig{
Provider: req.Provider, Email: req.Email, IMAPHost: req.IMAPHost, IMAPPort: req.IMAPPort, Password: req.AuthorizationCode,
})
if err != nil {
backendFail(c, err)
return
}
ok(c, sum)
}

// loginAccountReq 是 POST /api/accounts/:id/login 请求体。
type loginAccountReq struct {
Password string `json:"password"`
Expand Down
49 changes: 49 additions & 0 deletions internal/server/backend.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,13 +48,16 @@ type Backend interface {
UpdateProxy(string, string) (account.Summary, error)
UpdateCookies(string, string) (account.Summary, error)
SetAppPassword(string, string, string) (account.Summary, error)
SetMailbox(string, account.MailboxConfig) (account.Summary, error)
LoginAccount(string, string, string) (account.Summary, error)
RemoveAccount(string) bool
CreateAlias(string, string) (*hme.CreateResult, error)
ListAliases(string) ([]hme.Alias, error)
SetAliasActive(string, string, bool) (bool, error)
DeleteAlias(string, string) error
ListInbox(InboxQuery) (InboxResult, error)
GetMessage(string, uint32) (*mail.FullMessage, error)
DeleteMessage(string, uint32) error
Reload() error
}

Expand Down Expand Up @@ -131,6 +134,21 @@ func (b *managerBackend) SetAppPassword(id, icloudEmail, appPassword string) (ac
return sum.Summary(), nil
}

// SetMailbox configures and verifies an external IMAP mailbox.
func (b *managerBackend) SetMailbox(id string, config account.MailboxConfig) (account.Summary, error) {
if err := b.mgr.SetMailbox(id, config); err != nil {
if strings.Contains(err.Error(), "账号不存在") {
return account.Summary{}, &BackendError{Status: http.StatusNotFound, Code: "ACCOUNT_NOT_FOUND", Message: "账号不存在"}
}
return account.Summary{}, &BackendError{Status: http.StatusBadGateway, Code: "UPSTREAM_FAILURE", Message: "收件邮箱验证失败,请检查邮箱、授权码和 IMAP 配置"}
}
sum, ok := b.mgr.GetAccount(id)
if !ok {
return account.Summary{}, &BackendError{Status: http.StatusNotFound, Code: "ACCOUNT_NOT_FOUND", Message: "账号不存在"}
}
return sum.Summary(), nil
}

// LoginAccount 使用 iCloud 密码登录账号,成功只返回 Summary,绝不返回 Cookies。
func (b *managerBackend) LoginAccount(id, password, otpCode string) (account.Summary, error) {
var otpProvider hme.OTPProvider
Expand Down Expand Up @@ -285,6 +303,37 @@ func (b *managerBackend) ListInbox(q InboxQuery) (InboxResult, error) {
return InboxResult{AccountID: q.AccountID, Count: len(messages), Messages: messages, Method: "web_api"}, nil
}

func (b *managerBackend) GetMessage(accountID string, uid uint32) (*mail.FullMessage, error) {
mc, err := b.mgr.MailClient(accountID)
if err != nil {
return nil, mapAccountErr(err)
}
if err := mc.Connect(); err != nil {
return nil, &BackendError{Status: http.StatusBadGateway, Code: "UPSTREAM_FAILURE", Message: "读取邮件失败"}
}
defer mc.Disconnect()
message, err := mc.GetFull(uid)
if err != nil {
return nil, &BackendError{Status: http.StatusBadGateway, Code: "UPSTREAM_FAILURE", Message: "读取邮件详情失败"}
}
return message, nil
}

func (b *managerBackend) DeleteMessage(accountID string, uid uint32) error {
mc, err := b.mgr.MailClient(accountID)
if err != nil {
return mapAccountErr(err)
}
if err := mc.Connect(); err != nil {
return &BackendError{Status: http.StatusBadGateway, Code: "UPSTREAM_FAILURE", Message: "删除邮件失败"}
}
defer mc.Disconnect()
if err := mc.Delete(uid); err != nil {
return &BackendError{Status: http.StatusBadGateway, Code: "UPSTREAM_FAILURE", Message: "删除邮件失败"}
}
return nil
}

// Reload 重新加载配置。
func (b *managerBackend) Reload() error {
if err := b.mgr.Reload(); err != nil {
Expand Down
14 changes: 14 additions & 0 deletions internal/server/backend_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (

"icloud-hme/internal/account"
"icloud-hme/internal/hme"
"icloud-hme/internal/mail"
)

// fakeBackend 是测试用内存 Backend,记录调用,不访问网络。
Expand Down Expand Up @@ -83,6 +84,13 @@ func (f *fakeBackend) SetAppPassword(id, email, appPassword string) (account.Sum
return f.accounts[0], nil
}

func (f *fakeBackend) SetMailbox(id string, config account.MailboxConfig) (account.Summary, error) {
if len(f.accounts) == 0 {
return account.Summary{}, fmt.Errorf("fake: 收件邮箱设置失败")
}
return f.accounts[0], nil
}

func (f *fakeBackend) LoginAccount(id, password, otp string) (account.Summary, error) {
f.loginID = id
if f.loginErr != nil {
Expand Down Expand Up @@ -122,6 +130,12 @@ func (f *fakeBackend) ListInbox(q InboxQuery) (InboxResult, error) {
return f.inbox, nil
}

func (f *fakeBackend) GetMessage(accountID string, uid uint32) (*mail.FullMessage, error) {
return &mail.FullMessage{Message: mail.Message{ID: fmt.Sprint(uid)}}, nil
}

func (f *fakeBackend) DeleteMessage(accountID string, uid uint32) error { return nil }

func (f *fakeBackend) Reload() error {
f.reloadCount++
return nil
Expand Down
Loading
0