Better list messages encoding

This commit is contained in:
Melon 2023-09-11 11:55:52 +01:00
parent 31186402f7
commit dfc74925cd
Signed by: melon
GPG Key ID: 6C9D970C50D26A25
3 changed files with 43 additions and 1 deletions

1
.gitignore vendored
View File

@ -1,3 +1,4 @@
*.sqlite
*.local
.data
.idea/

View File

@ -3,7 +3,9 @@ package api
import (
"encoding/json"
"github.com/1f349/lotus/imap"
json2 "github.com/1f349/lotus/imap/json"
"github.com/julienschmidt/httprouter"
"log"
"net/http"
"time"
)
@ -37,7 +39,10 @@ func SetupApiServer(listen string, auth func(callback AuthCallback) httprouter.H
rw.WriteHeader(http.StatusForbidden)
return
}
_ = json.NewEncoder(rw).Encode(messages)
err = json.NewEncoder(rw).Encode(json2.ListMessagesJson(messages))
if err != nil {
log.Println("list-messages json encode error:", err)
}
})))
r.GET("/search-messages", auth(imapClient(recv, func(rw http.ResponseWriter, req *http.Request, params httprouter.Params, cli *imap.Client, t statusJson) {
status, err := cli.Status(t.Folder)

View File

@ -0,0 +1,36 @@
package json
import (
"encoding/json"
"github.com/emersion/go-imap"
)
type ListMessagesJson []*imap.Message
func (l ListMessagesJson) MarshalJSON() ([]byte, error) {
a := make([]encodeImapMessage, len(l))
for i := range a {
a[i] = encodeImapMessage(*l[i])
}
return json.Marshal(a)
}
type encodeImapMessage imap.Message
func (e encodeImapMessage) MarshalJSON() ([]byte, error) {
body := make(map[string]imap.Literal, len(e.Body))
for k, v := range e.Body {
body[string(k.FetchItem())] = v
}
return json.Marshal(map[string]any{
"SeqNum": e.SeqNum,
"Items": e.Items,
"Envelope": e.Envelope,
"BodyStructure": e.BodyStructure,
"Flags": e.Flags,
"InternalDate": e.InternalDate,
"Size": e.Size,
"Uid": e.Uid,
"$Body": body,
})
}