整理前后端与测试构建目录并完善配置和安全引导
Security Checks / security (push) Waiting to run

统一 frontend、backend、test、test-log 和 out 目录,更新构建、部署及测试入口;纳入配置管理兼容与首次安全引导修复;排除本机配置、密钥和测试产物。
This commit is contained in:
xuans committed 2026-09-05 19:19:52 +08:00
1 parent 28cd9d3406
commit f60d3b0880
603 files changed
+2351 -660

No files matched your search

+513
View File
@@ -0,0 +1,513 @@
package list
import (
"fmt"
"math"
"strings"
"time"
"git.pcux.cn/xuans/Smail/db"
"git.pcux.cn/xuans/Smail/dto/response"
"git.pcux.cn/xuans/Smail/models"
"git.pcux.cn/xuans/Smail/utils/context"
"github.com/emersion/go-imap/v2"
"github.com/spf13/cast"
)
// IMAPSearchCriteria represents the search criteria for IMAP SEARCH command
type IMAPSearchCriteria struct {
// UID and sequence number sets
UIDs []imap.UIDSet
SeqNums []imap.SeqSet
// Date filters (only date is used, time and timezone are ignored)
Since time.Time // Internal date since
Before time.Time // Internal date before
SentSince time.Time // Sent date since
SentBefore time.Time // Sent date before
// Header field searches
Header []HeaderField // Key-Value pairs for header search
// Content search
Body []string // Search in body
Text []string // Search in headers + body
// Flag filters
Flag []imap.Flag // Messages with these flags
NotFlag []imap.Flag // Messages without these flags
// Size filters
Larger int64 // Messages larger than this (bytes)
Smaller int64 // Messages smaller than this (bytes)
// Logical combinations
Not []IMAPSearchCriteria
Or [][2]IMAPSearchCriteria
}
// HeaderField represents a header field search criterion
type HeaderField struct {
Key string
Value string
}
// IMAPSearchResult represents a search result item
type IMAPSearchResult struct {
UID int // user_email.id as UID
SeqNum int // sequence number
EmailID int // email.id
IsRead int8 // read status
SerialNumber int // serial number
}
// SearchEmails performs IMAP search based on criteria
func SearchEmails(ctx *context.Context, groupName string, criteria *imap.SearchCriteria) ([]*response.UserEmailUIDData, error) {
// First get the base list for the mailbox
baseList, err := GetUEListByUID(ctx, groupName, 0, 0, nil)
if err != nil {
return nil, err
}
if len(baseList) == 0 {
return baseList, nil
}
// If no criteria specified, return all
if criteria == nil || isEmptyCriteria(criteria) {
return baseList, nil
}
// Build UID to sequence number mapping
uidToSeq := make(map[int]int)
seqToUID := make(map[int]int)
for _, item := range baseList {
uidToSeq[item.ID] = item.SerialNumber
seqToUID[item.SerialNumber] = item.ID
}
// Filter by UID sets
if len(criteria.UID) > 0 {
baseList = filterByUIDSets(baseList, criteria.UID)
}
// Filter by sequence number sets
if len(criteria.SeqNum) > 0 {
baseList = filterBySeqNumSets(baseList, criteria.SeqNum)
}
// For more complex filters, we need to fetch email data
if needsEmailData(criteria) {
baseList, err = filterWithEmailData(ctx, baseList, criteria)
if err != nil {
return nil, fmt.Errorf("filter email data: %w", err)
}
}
// Filter by flags (is_read status in this implementation)
if len(criteria.Flag) > 0 || len(criteria.NotFlag) > 0 {
baseList = filterByFlags(baseList, criteria.Flag, criteria.NotFlag)
}
// Handle NOT criteria
if len(criteria.Not) > 0 {
for _, notCriteria := range criteria.Not {
baseList, err = applyNotCriteria(ctx, groupName, baseList, &notCriteria)
if err != nil {
return nil, fmt.Errorf("apply NOT criteria: %w", err)
}
}
}
// Handle OR criteria
if len(criteria.Or) > 0 {
baseList, err = applyOrCriteria(ctx, groupName, baseList, criteria.Or)
if err != nil {
return nil, fmt.Errorf("apply OR criteria: %w", err)
}
}
return baseList, nil
}
// isEmptyCriteria checks if the search criteria is empty
func isEmptyCriteria(criteria *imap.SearchCriteria) bool {
return len(criteria.UID) == 0 &&
len(criteria.SeqNum) == 0 &&
criteria.Since.IsZero() &&
criteria.Before.IsZero() &&
criteria.SentSince.IsZero() &&
criteria.SentBefore.IsZero() &&
len(criteria.Header) == 0 &&
len(criteria.Body) == 0 &&
len(criteria.Text) == 0 &&
len(criteria.Flag) == 0 &&
len(criteria.NotFlag) == 0 &&
criteria.Larger == 0 &&
criteria.Smaller == 0 &&
len(criteria.Not) == 0 &&
len(criteria.Or) == 0
}
// needsEmailData checks if we need to load email data for filtering
func needsEmailData(criteria *imap.SearchCriteria) bool {
return !criteria.Since.IsZero() ||
!criteria.Before.IsZero() ||
!criteria.SentSince.IsZero() ||
!criteria.SentBefore.IsZero() ||
len(criteria.Header) > 0 ||
len(criteria.Body) > 0 ||
len(criteria.Text) > 0 ||
criteria.Larger > 0 ||
criteria.Smaller > 0
}
func validIMAPNumber(value int) (uint32, bool) {
if value <= 0 || uint64(value) > math.MaxUint32 {
return 0, false
}
return cast.ToUint32(value), true
}
// filterByUIDSets filters the list by UID sets
func filterByUIDSets(list []*response.UserEmailUIDData, uidSets []imap.UIDSet) []*response.UserEmailUIDData {
var result []*response.UserEmailUIDData
for _, item := range list {
number, ok := validIMAPNumber(item.ID)
if !ok {
continue
}
uid := imap.UID(number)
for _, uidSet := range uidSets {
if uidSet.Contains(uid) {
result = append(result, item)
break
}
}
}
return result
}
// filterBySeqNumSets filters the list by sequence number sets
func filterBySeqNumSets(list []*response.UserEmailUIDData, seqSets []imap.SeqSet) []*response.UserEmailUIDData {
var result []*response.UserEmailUIDData
for _, item := range list {
number, ok := validIMAPNumber(item.SerialNumber)
if !ok {
continue
}
for _, seqSet := range seqSets {
if seqSet.Contains(number) {
result = append(result, item)
break
}
}
}
return result
}
// filterByFlags filters by message flags
func filterByFlags(list []*response.UserEmailUIDData, flags []imap.Flag, notFlags []imap.Flag) []*response.UserEmailUIDData {
var result []*response.UserEmailUIDData
for _, item := range list {
match := true
// Check required flags
for _, flag := range flags {
if !hasFlag(item, flag) {
match = false
break
}
}
// Check flags that should NOT be present
if match {
for _, flag := range notFlags {
if hasFlag(item, flag) {
match = false
break
}
}
}
if match {
result = append(result, item)
}
}
return result
}
// hasFlag checks if a message has a specific flag
func hasFlag(item *response.UserEmailUIDData, flag imap.Flag) bool {
switch flag {
case imap.FlagSeen:
return item.IsRead == 1
case imap.FlagDeleted:
return item.Status == 3
case imap.FlagDraft:
return item.Status == 4
case imap.FlagJunk:
return item.Status == 5
// For flags we don't track, return false
case imap.FlagAnswered, imap.FlagFlagged:
return false
default:
return false
}
}
// filterWithEmailData loads email data and applies filters that need it
func filterWithEmailData(ctx *context.Context, list []*response.UserEmailUIDData, criteria *imap.SearchCriteria) ([]*response.UserEmailUIDData, error) {
if len(list) == 0 {
return list, nil
}
// Get email IDs
var emailIDs []int
ueMap := make(map[int]*response.UserEmailUIDData) // emailID -> UserEmailUIDData
for _, item := range list {
emailIDs = append(emailIDs, item.EmailID)
ueMap[item.EmailID] = item
}
// Fetch emails from database
var emails []models.Email
err := db.Instance.Table("email").In("id", emailIDs).Find(&emails)
if err != nil {
return nil, fmt.Errorf("fetch emails for search: %w", err)
}
// Build email map
emailMap := make(map[int]*models.Email)
for i := range emails {
emailMap[emails[i].Id] = &emails[i]
}
// Filter
var result []*response.UserEmailUIDData
for _, item := range list {
email, ok := emailMap[item.EmailID]
if !ok {
continue
}
if matchesEmailCriteria(email, criteria) {
result = append(result, item)
}
}
return result, nil
}
// matchesEmailCriteria checks if an email matches the search criteria
func matchesEmailCriteria(email *models.Email, criteria *imap.SearchCriteria) bool {
// Date filters (internal date = CreateTime)
if !criteria.Since.IsZero() {
if email.CreateTime.Before(truncateToDate(criteria.Since)) {
return false
}
}
if !criteria.Before.IsZero() {
if !email.CreateTime.Before(truncateToDate(criteria.Before)) {
return false
}
}
// Sent date filters
if !criteria.SentSince.IsZero() {
if email.SendDate.Before(truncateToDate(criteria.SentSince)) {
return false
}
}
if !criteria.SentBefore.IsZero() {
if !email.SendDate.Before(truncateToDate(criteria.SentBefore)) {
return false
}
}
// Size filters
if criteria.Larger > 0 {
if int64(email.Size) <= criteria.Larger {
return false
}
}
if criteria.Smaller > 0 {
if int64(email.Size) >= criteria.Smaller {
return false
}
}
// Header field search
for _, hf := range criteria.Header {
if !matchesHeader(email, hf.Key, hf.Value) {
return false
}
}
// Body search
for _, pattern := range criteria.Body {
if !matchesBody(email, pattern) {
return false
}
}
// Text search (headers + body)
for _, pattern := range criteria.Text {
if !matchesText(email, pattern) {
return false
}
}
return true
}
// truncateToDate removes time component from a time.Time
func truncateToDate(t time.Time) time.Time {
return time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())
}
// matchesHeader checks if an email matches a header field search
func matchesHeader(email *models.Email, key, value string) bool {
key = strings.ToLower(key)
value = strings.ToLower(value)
switch key {
case "subject":
return strings.Contains(strings.ToLower(email.Subject), value)
case "from":
return strings.Contains(strings.ToLower(email.FromAddress), value) ||
strings.Contains(strings.ToLower(email.FromName), value)
case "to":
return strings.Contains(strings.ToLower(email.To), value)
case "cc":
return strings.Contains(strings.ToLower(email.Cc), value)
case "bcc":
return strings.Contains(strings.ToLower(email.Bcc), value)
case "reply-to":
return strings.Contains(strings.ToLower(email.ReplyTo), value)
case "sender":
return strings.Contains(strings.ToLower(email.Sender), value)
default:
// For unknown headers, we can't match
return false
}
}
// matchesBody checks if an email body matches the pattern
func matchesBody(email *models.Email, pattern string) bool {
pattern = strings.ToLower(pattern)
// Check text body
if email.Text.Valid && strings.Contains(strings.ToLower(email.Text.String), pattern) {
return true
}
// Check HTML body
if email.Html.Valid && strings.Contains(strings.ToLower(email.Html.String), pattern) {
return true
}
return false
}
// matchesText checks if an email (headers + body) matches the pattern
func matchesText(email *models.Email, pattern string) bool {
pattern = strings.ToLower(pattern)
// Check headers
if strings.Contains(strings.ToLower(email.Subject), pattern) {
return true
}
if strings.Contains(strings.ToLower(email.FromAddress), pattern) {
return true
}
if strings.Contains(strings.ToLower(email.FromName), pattern) {
return true
}
if strings.Contains(strings.ToLower(email.To), pattern) {
return true
}
if strings.Contains(strings.ToLower(email.Cc), pattern) {
return true
}
if strings.Contains(strings.ToLower(email.Bcc), pattern) {
return true
}
// Check body
return matchesBody(email, pattern)
}
// applyNotCriteria applies NOT criteria
func applyNotCriteria(ctx *context.Context, groupName string, list []*response.UserEmailUIDData, notCriteria *imap.SearchCriteria) ([]*response.UserEmailUIDData, error) {
// Get the list of items that match the NOT criteria
matchedList, err := SearchEmails(ctx, groupName, notCriteria)
if err != nil {
return nil, err
}
// Build a set of matched UIDs
matchedUIDs := make(map[int]bool)
for _, item := range matchedList {
matchedUIDs[item.ID] = true
}
// Return items that are NOT in the matched set
var result []*response.UserEmailUIDData
for _, item := range list {
if !matchedUIDs[item.ID] {
result = append(result, item)
}
}
return result, nil
}
// applyOrCriteria applies OR criteria
func applyOrCriteria(ctx *context.Context, groupName string, list []*response.UserEmailUIDData, orCriteria [][2]imap.SearchCriteria) ([]*response.UserEmailUIDData, error) {
if len(orCriteria) == 0 {
return list, nil
}
// Build a set of current UIDs for intersection
currentUIDs := make(map[int]bool)
for _, item := range list {
currentUIDs[item.ID] = true
}
// For each OR pair, find items matching either condition
resultUIDs := make(map[int]bool)
for _, pair := range orCriteria {
// Get matches for first condition
matches1, err := SearchEmails(ctx, groupName, &pair[0])
if err != nil {
return nil, err
}
for _, item := range matches1 {
if currentUIDs[item.ID] {
resultUIDs[item.ID] = true
}
}
// Get matches for second condition
matches2, err := SearchEmails(ctx, groupName, &pair[1])
if err != nil {
return nil, err
}
for _, item := range matches2 {
if currentUIDs[item.ID] {
resultUIDs[item.ID] = true
}
}
}
// Build result from original list preserving order
var result []*response.UserEmailUIDData
for _, item := range list {
if resultUIDs[item.ID] {
result = append(result, item)
}
}
return result, nil
}
+325
View File
@@ -0,0 +1,325 @@
package list
import (
"fmt"
"strings"
"git.pcux.cn/xuans/Smail/consts"
"git.pcux.cn/xuans/Smail/db"
"git.pcux.cn/xuans/Smail/dto"
"git.pcux.cn/xuans/Smail/dto/response"
"git.pcux.cn/xuans/Smail/models"
"git.pcux.cn/xuans/Smail/utils/context"
"git.pcux.cn/xuans/Smail/utils/query"
. "xorm.io/builder"
)
func GetEmailList(ctx *context.Context, tagInfo dto.SearchTag, keyword string, pop3List bool, offset, limit int) (emailList []*response.EmailResponseData, total int64, err error) {
return getList(ctx, tagInfo, keyword, pop3List, offset, limit)
}
func getList(ctx *context.Context, tagInfo dto.SearchTag, keyword string, pop3List bool, offset, limit int) (emailList []*response.EmailResponseData, total int64, err error) {
querySQL, queryParams := genSQL(ctx, false, tagInfo, keyword, pop3List, offset, limit)
if err := db.Instance.SQL(querySQL, queryParams...).Find(&emailList); err != nil {
return nil, 0, fmt.Errorf("query email list: %w", err)
}
totalSQL, totalParams := genSQL(ctx, true, tagInfo, keyword, pop3List, offset, limit)
if _, err := db.Instance.SQL(totalSQL, totalParams...).Get(&total); err != nil {
return nil, 0, fmt.Errorf("query email count: %w", err)
}
return emailList, total, nil
}
func genSQL(ctx *context.Context, count bool, tagInfo dto.SearchTag, keyword string, pop3List bool, offset, limit int) (string, []any) {
sqlParams := []any{ctx.UserID}
sql := "select "
if count {
sql += `count(1) from email e left join user_email ue on e.id=ue.email_id where ue.user_id = ? `
} else if pop3List {
sql += `e.id,e.size from email e left join user_email ue on e.id=ue.email_id where ue.user_id = ? `
} else {
sql += `e.*,ue.is_read from email e left join user_email ue on e.id=ue.email_id where ue.user_id = ? `
}
if tagInfo.Status != -1 {
switch tagInfo.Status {
case consts.EmailStatusDel:
sql += " and (ue.status =? or ue.group_id=?) "
sqlParams = append(sqlParams, tagInfo.Status, models.Deleted)
case consts.EmailStatusDrafts:
sql += " and (ue.status =? or ue.group_id=?) "
sqlParams = append(sqlParams, tagInfo.Status, models.Drafts)
case consts.EmailStatusJunk:
sql += " and (ue.status =? or ue.group_id=?) "
sqlParams = append(sqlParams, tagInfo.Status, models.Junk)
}
} else if tagInfo.Status == -1 {
if tagInfo.Type != 1 {
sql += " and ue.status = 0"
} else {
// 发件箱不展示已删除的邮件
sql += " and ue.status != 3"
}
}
if tagInfo.Type == consts.EmailTypeReceive {
sql += " and type =? "
sqlParams = append(sqlParams, tagInfo.Type)
} else if tagInfo.Type == consts.EmailTypeSend {
sql += " and (type =? or ue.group_id=?)"
sqlParams = append(sqlParams, tagInfo.Type, models.Sent)
}
if tagInfo.GroupId != -1 {
if tagInfo.GroupId > 0 {
sql += " and ue.group_id=? "
sqlParams = append(sqlParams, tagInfo.GroupId)
} else if tagInfo.GroupId == 0 && tagInfo.Status == -1 {
sql += " and (ue.group_id=? or ue.group_id=0)"
sqlParams = append(sqlParams, models.INBOX)
}
} else {
sql += " and (ue.group_id=0 or ue.group_id =?) "
sqlParams = append(sqlParams, models.INBOX)
}
if keyword != "" {
sql += " and (subject like ? or text like ? )"
sqlParams = append(sqlParams, "%"+keyword+"%", "%"+keyword+"%")
}
if limit == 0 {
limit = 10
}
sql += " order by e.id desc"
if limit < 10000 {
sql += fmt.Sprintf(" LIMIT %d OFFSET %d ", limit, offset)
}
return sql, sqlParams
}
type statRes struct {
Total int64
Size int64
}
// Stat 查询邮件总数和大小
func Stat(ctx *context.Context) (int64, int64, error) {
sql := `select count(1) as total,sum(size) as size from email e left join user_email ue on e.id=ue.email_id where ue.user_id = ? and e.type = 0 and ue.status != 3`
var ret statRes
if _, err := db.Instance.SQL(sql, ctx.UserID).Get(&ret); err != nil {
return 0, 0, fmt.Errorf("query mailbox statistics: %w", err)
}
return ret.Total, ret.Size, nil
}
type ImapListReq struct {
UidList []int
Star int
End int
}
func buildIMAPMailboxRelationQuery(ctx *context.Context, groupName string) (string, []any, error) {
if ctx == nil || ctx.UserID <= 0 {
return "", nil, fmt.Errorf("invalid mailbox user")
}
inner := "SELECT id,email_id,is_read,is_deleted,ROW_NUMBER() OVER (ORDER BY id) AS serial_number FROM user_email WHERE user_id = ?"
params := []any{ctx.UserID}
switch groupName {
case "INBOX":
inner += " and status = ? and group_id = 0"
params = append(params, 0)
case "Sent Messages":
inner += " and status = ? and group_id = 0"
params = append(params, 1)
case "Drafts":
inner += " and status = ? and group_id = 0"
params = append(params, 4)
case "Deleted Messages":
inner += " and status = ? and group_id = 0"
params = append(params, 3)
case "Junk":
inner += " and status = ? and group_id = 0"
params = append(params, 5)
default:
var mailbox models.Group
found, err := db.Instance.Table("group").Where("user_id=? and full_path=?", ctx.UserID, groupName).Get(&mailbox)
if err != nil {
return "", nil, fmt.Errorf("query mailbox: %w", err)
}
if !found || mailbox.ID == 0 {
return "", nil, fmt.Errorf("mailbox not found")
}
inner += " and group_id = ?"
params = append(params, mailbox.ID)
}
return inner, params, nil
}
func GetUEListByUID(ctx *context.Context, groupName string, star, end int, uidList []int) ([]*response.UserEmailUIDData, error) {
if star < 0 || end < 0 || (end > 0 && star > end) {
return nil, fmt.Errorf("invalid UID range")
}
inner, params, err := buildIMAPMailboxRelationQuery(ctx, groupName)
if err != nil {
return nil, err
}
filters := make([]string, 0, 3)
if len(uidList) > 0 {
placeholders, uidArgs, ok := query.IntList(uidList, 10000)
if !ok {
return nil, fmt.Errorf("invalid UID list")
}
filters = append(filters, fmt.Sprintf("id in (%s)", placeholders))
params = append(params, uidArgs...)
}
if star > 0 {
filters = append(filters, "id >= ?")
params = append(params, star)
}
if end > 0 {
filters = append(filters, "id <= ?")
params = append(params, end)
}
sql := "SELECT * FROM (" + inner + ") mailbox"
if len(filters) > 0 {
sql += " WHERE " + strings.Join(filters, " AND ")
}
sql += " ORDER BY id"
var relations []*response.UserEmailUIDData
if err := db.Instance.SQL(sql, params...).Find(&relations); err != nil {
return nil, fmt.Errorf("query mailbox UID relations: %w", err)
}
return relations, nil
}
func GetMaxUIDByMailbox(ctx *context.Context, groupName string) (int, error) {
inner, params, err := buildIMAPMailboxRelationQuery(ctx, groupName)
if err != nil {
return 0, err
}
var maxUID int
if _, err := db.Instance.SQL("SELECT COALESCE(MAX(id), 0) FROM ("+inner+") mailbox", params...).Get(&maxUID); err != nil {
return 0, fmt.Errorf("query mailbox maximum UID: %w", err)
}
return maxUID, nil
}
func getEmailListByUidList(ctx *context.Context, groupName string, req ImapListReq) ([]*response.EmailResponseData, error) {
if req.Star < 0 || req.End < 0 || (req.End > 0 && req.Star > req.End) {
return nil, fmt.Errorf("invalid UID range")
}
inner, params, err := buildIMAPMailboxRelationQuery(ctx, groupName)
if err != nil {
return nil, err
}
sql := "SELECT * FROM (" + inner + ") mailbox WHERE "
if req.Star > 0 {
sql += "id >= ?"
params = append(params, req.Star)
if req.End > 0 {
sql += " and id <= ?"
params = append(params, req.End)
}
} else {
placeholders, uidArgs, ok := query.IntList(req.UidList, 10000)
if !ok {
return nil, fmt.Errorf("invalid UID list")
}
sql += fmt.Sprintf("id in (%s)", placeholders)
params = append(params, uidArgs...)
}
sql += " ORDER BY id"
var relations []*response.UserEmailUIDData
if err := db.Instance.SQL(sql, params...).Find(&relations); err != nil {
return nil, fmt.Errorf("query mailbox UID list: %w", err)
}
return hydrateIMAPEmailResponses(relations)
}
func GetEmailListByGroup(ctx *context.Context, groupName string, req ImapListReq, uid bool) ([]*response.EmailResponseData, error) {
if len(req.UidList) == 0 && req.Star == 0 && req.End == 0 {
return nil, nil
}
if uid {
return getEmailListByUidList(ctx, groupName, req)
}
if req.Star < 0 || req.End < 0 || (req.End > 0 && req.Star > req.End) {
return nil, fmt.Errorf("invalid sequence range")
}
inner, params, err := buildIMAPMailboxRelationQuery(ctx, groupName)
if err != nil {
return nil, err
}
sql := "SELECT * FROM (" + inner + ") mailbox WHERE "
if req.Star > 0 {
sql += "serial_number >= ?"
params = append(params, req.Star)
if req.End > 0 {
sql += " and serial_number <= ?"
params = append(params, req.End)
}
} else {
placeholders, sequenceArgs, ok := query.IntList(req.UidList, 10000)
if !ok {
return nil, fmt.Errorf("invalid sequence list")
}
sql += fmt.Sprintf("serial_number in (%s)", placeholders)
params = append(params, sequenceArgs...)
}
sql += " ORDER BY serial_number"
var relations []*response.UserEmailUIDData
if err := db.Instance.SQL(sql, params...).Find(&relations); err != nil {
return nil, fmt.Errorf("query mailbox sequence list: %w", err)
}
return hydrateIMAPEmailResponses(relations)
}
func hydrateIMAPEmailResponses(relations []*response.UserEmailUIDData) ([]*response.EmailResponseData, error) {
result := make([]*response.EmailResponseData, 0, len(relations))
if len(relations) == 0 {
return result, nil
}
emailIDs := make([]int, 0, len(relations))
for _, relation := range relations {
if relation == nil || relation.EmailID <= 0 {
continue
}
emailIDs = append(emailIDs, relation.EmailID)
}
if len(emailIDs) == 0 {
return result, nil
}
var stored []*response.EmailResponseData
if err := db.Instance.Table("email").Select("*").Where(Eq{"id": emailIDs}).Find(&stored); err != nil {
return nil, fmt.Errorf("query mailbox messages: %w", err)
}
messageByID := make(map[int]*response.EmailResponseData, len(stored))
for _, message := range stored {
if message != nil {
messageByID[message.Id] = message
}
}
for _, relation := range relations {
message := messageByID[relation.EmailID]
if message == nil {
continue
}
message.IsRead = relation.IsRead
message.IsDeleted = relation.IsDeleted
message.SerialNumber = relation.SerialNumber
message.UeId = relation.ID
result = append(result, message)
}
return result, nil
}
+67
View File
@@ -0,0 +1,67 @@
package list
import (
"path/filepath"
"testing"
"git.pcux.cn/xuans/Smail/config"
"git.pcux.cn/xuans/Smail/db"
"git.pcux.cn/xuans/Smail/models"
"git.pcux.cn/xuans/Smail/utils/context"
)
func initListTestDB(t *testing.T) {
t.Helper()
config.Instance = &config.Config{DbType: config.DBTypeSQLite, DbDSN: filepath.Join(t.TempDir(), "list.db")}
if err := db.Init(""); err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
if db.Instance != nil {
_ = db.Instance.Close()
}
})
}
func TestGetUEListByUIDUsesFullPath(t *testing.T) {
initListTestDB(t)
first := models.Group{Name: "leaf", UserId: 1, FullPath: "first/leaf"}
second := models.Group{Name: "leaf", UserId: 1, FullPath: "second/leaf"}
if _, err := db.Instance.Insert(&first, &second); err != nil {
t.Fatal(err)
}
firstMail := models.UserEmail{UserID: 1, EmailID: 101, GroupId: first.ID}
secondMail := models.UserEmail{UserID: 1, EmailID: 102, GroupId: second.ID}
if _, err := db.Instance.Insert(&firstMail, &secondMail); err != nil {
t.Fatal(err)
}
result, err := GetUEListByUID(&context.Context{UserID: 1}, "first/leaf", 0, 0, nil)
if err != nil {
t.Fatal(err)
}
if len(result) != 1 || result[0].ID != firstMail.ID {
t.Fatalf("GetUEListByUID returned %#v, want relation %d", result, firstMail.ID)
}
}
func TestGetUEListByUIDDefaultMailboxExcludesGroupedMail(t *testing.T) {
initListTestDB(t)
group := models.Group{Name: "custom", UserId: 1, FullPath: "custom"}
if _, err := db.Instance.Insert(&group); err != nil {
t.Fatal(err)
}
inboxMail := models.UserEmail{UserID: 1, EmailID: 201, GroupId: 0, Status: 0}
groupedMail := models.UserEmail{UserID: 1, EmailID: 202, GroupId: group.ID, Status: 0}
if _, err := db.Instance.Insert(&inboxMail, &groupedMail); err != nil {
t.Fatal(err)
}
result, err := GetUEListByUID(&context.Context{UserID: 1}, "INBOX", 0, 0, nil)
if err != nil {
t.Fatal(err)
}
if len(result) != 1 || result[0].ID != inboxMail.ID {
t.Fatalf("GetUEListByUID returned %#v, want inbox relation %d", result, inboxMail.ID)
}
}