Debian Codegraph @

server/messages.go

raw
1 package server
2
3 import (
4 "encoding/base64"
5 "encoding/json"
6 "fmt"
7 "mime"
8 "net/http"
9 "net/mail"
10 "strconv"
11 "time"
12
13 "github.com/ProtonMail/gluon/rfc822"
14 "github.com/ProtonMail/gopenpgp/v2/crypto"
15 "github.com/gin-gonic/gin"
16 "github.com/henrybear327/go-proton-api"
17 "golang.org/x/exp/slices"
18 )
19
20 const (
21 defaultPage = 0
22 defaultPageSize = 100
23 )
24
25 func (s *Server) handleGetMailMessages() gin.HandlerFunc {
26 return func(c *gin.Context) {
27 s.getMailMessages(
28 c,
29 mustParseInt(c.DefaultQuery("Page", strconv.Itoa(defaultPage))),
30 mustParseInt(c.DefaultQuery("PageSize", strconv.Itoa(defaultPageSize))),
31 proton.MessageFilter{ID: c.QueryArray("ID")},
32 )
33 }
34 }
35
36 func (s *Server) getMailMessages(c *gin.Context, page, pageSize int, filter proton.MessageFilter) {
37 // Set default page.
38 if page <= 0 {
39 page = defaultPage
40 }
41
42 // Set default page size.
43 if pageSize <= 0 {
44 pageSize = defaultPageSize
45 }
46
47 messages, err := s.b.GetMessages(c.GetString("UserID"), page, pageSize, filter)
48 if err != nil {
49 _ = c.AbortWithError(http.StatusInternalServerError, err)
50 return
51 }
52
53 total, err := s.b.CountMessages(c.GetString("UserID"))
54 if err != nil {
55 _ = c.AbortWithError(http.StatusInternalServerError, err)
56 return
57 }
58
59 c.JSON(http.StatusOK, gin.H{
60 "Messages": messages,
61 "Total": total,
62 "Stale": proton.APIFalse,
63 })
64 }
65
66 func (s *Server) handlePostMailMessages() gin.HandlerFunc {
67 return func(c *gin.Context) {
68 switch c.GetHeader("X-HTTP-Method-Override") {
69 case "GET":
70 var req struct {
71 proton.MessageFilter
72
73 Page int
74 PageSize int
75 }
76
77 if err := c.BindJSON(&req); err != nil {
78 c.AbortWithStatus(http.StatusBadRequest)
79 return
80 }
81
82 s.getMailMessages(c, req.Page, req.PageSize, req.MessageFilter)
83
84 default:
85 s.postMailMessages(c)
86 }
87 }
88 }
89
90 func (s *Server) postMailMessages(c *gin.Context) {
91 var req proton.CreateDraftReq
92
93 if err := c.BindJSON(&req); err != nil {
94 c.AbortWithStatus(http.StatusBadRequest)
95 return
96 }
97
98 addrID, err := s.b.GetAddressID(req.Message.Sender.Address)
99 if err != nil {
100 c.AbortWithStatus(http.StatusUnprocessableEntity)
101 return
102 }
103
104 message, err := s.b.CreateDraft(c.GetString("UserID"), addrID, req.Message, req.ParentID)
105 if err != nil {
106 c.AbortWithStatus(http.StatusUnprocessableEntity)
107 return
108 }
109
110 c.JSON(http.StatusOK, gin.H{
111 "Message": message,
112 })
113 }
114
115 func (s *Server) handleGetMailMessageIDs() gin.HandlerFunc {
116 return func(c *gin.Context) {
117 limit, err := strconv.Atoi(c.Query("Limit"))
118 if err != nil {
119 c.AbortWithStatus(http.StatusBadRequest)
120 return
121 }
122
123 messageIDs, err := s.b.GetMessageIDs(c.GetString("UserID"), c.Query("AfterID"), limit)
124 if err != nil {
125 c.AbortWithStatus(http.StatusUnprocessableEntity)
126 return
127 }
128
129 c.JSON(http.StatusOK, gin.H{
130 "IDs": messageIDs,
131 })
132 }
133 }
134
135 func (s *Server) handleGetMailMessage() gin.HandlerFunc {
136 return func(c *gin.Context) {
137 message, err := s.b.GetMessage(c.GetString("UserID"), c.Param("messageID"))
138 if err != nil {
139 c.AbortWithStatusJSON(http.StatusUnprocessableEntity, proton.APIError{
140 Code: proton.InvalidValue,
141 Message: fmt.Sprintf("Message %s not found", c.Param("messageID")),
142 })
143
144 return
145 }
146
147 c.JSON(http.StatusOK, gin.H{
148 "Message": message,
149 })
150 }
151 }
152
153 func (s *Server) handlePostMailMessage() gin.HandlerFunc {
154 return func(c *gin.Context) {
155 var req proton.SendDraftReq
156
157 if err := c.BindJSON(&req); err != nil {
158 c.AbortWithStatus(http.StatusBadRequest)
159 return
160 }
161
162 message, err := s.b.SendMessage(c.GetString("UserID"), c.Param("messageID"), req.Packages)
163 if err != nil {
164 c.AbortWithStatus(http.StatusUnprocessableEntity)
165 return
166 }
167
168 c.JSON(http.StatusOK, gin.H{
169 "Sent": message,
170 })
171 }
172 }
173
174 func (s *Server) handlePutMailMessage() gin.HandlerFunc {
175 return func(c *gin.Context) {
176 var req proton.UpdateDraftReq
177
178 if err := c.BindJSON(&req); err != nil {
179 c.AbortWithStatus(http.StatusBadRequest)
180 return
181 }
182
183 message, err := s.b.UpdateDraft(c.GetString("UserID"), c.Param("messageID"), req.Message)
184 if err != nil {
185 c.AbortWithStatus(http.StatusUnprocessableEntity)
186 return
187 }
188
189 c.JSON(http.StatusOK, gin.H{
190 "Message": message,
191 })
192 }
193 }
194
195 func (s *Server) handlePutMailMessagesRead() gin.HandlerFunc {
196 return func(c *gin.Context) {
197 var req proton.MessageActionReq
198
199 if err := c.BindJSON(&req); err != nil {
200 c.AbortWithStatus(http.StatusBadRequest)
201 return
202 }
203
204 if err := s.b.SetMessagesRead(c.GetString("UserID"), true, req.IDs...); err != nil {
205 c.AbortWithStatus(http.StatusUnprocessableEntity)
206 return
207 }
208 }
209 }
210
211 func (s *Server) handlePutMailMessagesUnread() gin.HandlerFunc {
212 return func(c *gin.Context) {
213 var req proton.MessageActionReq
214
215 if err := c.BindJSON(&req); err != nil {
216 c.AbortWithStatus(http.StatusBadRequest)
217 return
218 }
219
220 if err := s.b.SetMessagesRead(c.GetString("UserID"), false, req.IDs...); err != nil {
221 c.AbortWithStatus(http.StatusUnprocessableEntity)
222 return
223 }
224 }
225 }
226
227 func (s *Server) handlePutMailMessagesLabel() gin.HandlerFunc {
228 return func(c *gin.Context) {
229 var req proton.LabelMessagesReq
230
231 if err := c.BindJSON(&req); err != nil {
232 c.AbortWithStatus(http.StatusBadRequest)
233 return
234 }
235
236 if err := s.b.LabelMessages(c.GetString("UserID"), req.LabelID, req.IDs...); err != nil {
237 c.AbortWithStatus(http.StatusUnprocessableEntity)
238 return
239 }
240 }
241 }
242
243 func (s *Server) handlePutMailMessagesUnlabel() gin.HandlerFunc {
244 return func(c *gin.Context) {
245 var req proton.LabelMessagesReq
246
247 if err := c.BindJSON(&req); err != nil {
248 c.AbortWithStatus(http.StatusBadRequest)
249 return
250 }
251
252 if err := s.b.UnlabelMessages(c.GetString("UserID"), req.LabelID, req.IDs...); err != nil {
253 c.AbortWithStatus(http.StatusUnprocessableEntity)
254 return
255 }
256 }
257 }
258
259 func (s *Server) handlePutMailMessagesImport() gin.HandlerFunc {
260 return func(c *gin.Context) {
261 form, err := c.MultipartForm()
262 if err != nil {
263 c.AbortWithStatus(http.StatusBadRequest)
264 return
265 }
266
267 var metadata map[string]proton.ImportMetadata
268
269 if err := json.Unmarshal([]byte(form.Value["Metadata"][0]), &metadata); err != nil {
270 c.AbortWithStatus(http.StatusBadRequest)
271 return
272 }
273
274 files := make(map[string][]byte)
275
276 for name, file := range form.File {
277 files[name] = mustReadFileHeader(file[0])
278 }
279
280 type response struct {
281 Name string
282 Response proton.ImportRes
283 }
284
285 var responses []response
286
287 for name, literal := range files {
288 res := response{Name: name}
289
290 messageID, err := s.importMessage(
291 c.GetString("UserID"),
292 metadata[name].AddressID,
293 metadata[name].LabelIDs,
294 literal,
295 metadata[name].Flags,
296 bool(metadata[name].Unread),
297 )
298 if err != nil {
299 res.Response = proton.ImportRes{
300 APIError: proton.APIError{
301 Code: proton.InvalidValue,
302 Message: fmt.Sprintf("failed to import: %v", err),
303 },
304 }
305 } else {
306 res.Response = proton.ImportRes{
307 APIError: proton.APIError{Code: proton.SuccessCode},
308 MessageID: messageID,
309 }
310 }
311
312 responses = append(responses, res)
313 }
314
315 c.JSON(http.StatusOK, gin.H{
316 "Code": proton.MultiCode,
317 "Responses": responses,
318 })
319 }
320 }
321
322 func (s *Server) handleDeleteMailMessages() gin.HandlerFunc {
323 return func(c *gin.Context) {
324 var req proton.MessageActionReq
325
326 if err := c.BindJSON(&req); err != nil {
327 c.AbortWithStatus(http.StatusBadRequest)
328 return
329 }
330
331 for _, messageID := range req.IDs {
332 if err := s.b.DeleteMessage(c.GetString("UserID"), messageID); err != nil {
333 c.AbortWithStatus(http.StatusUnprocessableEntity)
334 return
335 }
336 }
337 }
338 }
339
340 func (s *Server) handleMessageGroupCount() gin.HandlerFunc {
341 return func(c *gin.Context) {
342 count, err := s.b.GetMessageGroupCount(c.GetString("UserID"))
343 if err != nil {
344 c.AbortWithStatusJSON(http.StatusUnprocessableEntity, proton.APIError{
345 Code: proton.InvalidValue,
346 Message: fmt.Sprintf("Message %s not found", c.Param("messageID")),
347 })
348
349 return
350 }
351
352 c.JSON(http.StatusOK, gin.H{
353 "Counts": count,
354 })
355 }
356 }
357
358 func (s *Server) importMessage(
359 userID, addrID string,
360 labelIDs []string,
361 literal []byte,
362 flags proton.MessageFlag,
363 unread bool,
364 ) (string, error) {
365 var exclusive int
366
367 for _, labelID := range labelIDs {
368 switch labelID {
369 case proton.AllDraftsLabel, proton.AllSentLabel, proton.AllMailLabel, proton.OutboxLabel:
370 return "", fmt.Errorf("invalid label ID: %s", labelID)
371 }
372
373 label, err := s.b.GetLabel(userID, labelID)
374 if err != nil {
375 return "", fmt.Errorf("invalid label ID: %s", labelID)
376 }
377
378 if label.Type != proton.LabelTypeLabel {
379 exclusive++
380 }
381 }
382
383 if exclusive > 1 {
384 return "", fmt.Errorf("too many exclusive labels")
385 }
386
387 header, body, atts, mimeType, err := s.parseMessage(literal)
388 if err != nil {
389 return "", fmt.Errorf("failed to parse message: %w", err)
390 }
391
392 messageID, err := s.importBody(userID, addrID, header, body, mimeType, flags, unread, slices.Contains(labelIDs, proton.StarredLabel))
393 if err != nil {
394 return "", fmt.Errorf("failed to import message: %w", err)
395 }
396
397 for _, att := range atts {
398 if _, err := s.importAttachment(userID, messageID, att); err != nil {
399 return "", fmt.Errorf("failed to import attachment: %w", err)
400 }
401 }
402
403 for _, labelID := range labelIDs {
404 if err := s.b.LabelMessagesNoEvents(userID, labelID, messageID); err != nil {
405 return "", fmt.Errorf("failed to label message: %w", err)
406 }
407 }
408
409 return messageID, nil
410 }
411
412 func (s *Server) parseMessage(literal []byte) (*rfc822.Header, []string, []*rfc822.Section, rfc822.MIMEType, error) {
413 root := rfc822.Parse(literal)
414
415 header, err := root.ParseHeader()
416 if err != nil {
417 return nil, nil, nil, "", fmt.Errorf("failed to parse header: %w", err)
418 }
419
420 body, atts, err := collect(root)
421 if err != nil {
422 return nil, nil, nil, "", fmt.Errorf("failed to collect body and attachments: %w", err)
423 }
424
425 mimeType, _, err := root.ContentType()
426 if err != nil {
427 return nil, nil, nil, "", fmt.Errorf("failed to parse content type: %w", err)
428 }
429
430 // Force all multipart types to be multipart/mixed.
431 if mimeType.Type() == "multipart" {
432 mimeType = "multipart/mixed"
433 }
434
435 return header, body, atts, mimeType, nil
436 }
437
438 func collect(section *rfc822.Section) ([]string, []*rfc822.Section, error) {
439 mimeType, _, err := section.ContentType()
440 if err != nil {
441 return nil, nil, fmt.Errorf("failed to parse content type: %w", err)
442 }
443
444 switch mimeType.Type() {
445 case "text":
446 return []string{string(section.Body())}, nil, nil
447
448 case "multipart":
449 children, err := section.Children()
450 if err != nil {
451 return nil, nil, fmt.Errorf("failed to parse children: %w", err)
452 }
453
454 switch mimeType.SubType() {
455 case "encrypted":
456 if len(children) != 2 {
457 return nil, nil, fmt.Errorf("expected two children for multipart/encrypted, got %d", len(children))
458 }
459
460 return []string{string(children[1].Body())}, nil, nil
461
462 default:
463 var (
464 multiBody []string
465 multiAtts []*rfc822.Section
466 )
467
468 for _, child := range children {
469 body, atts, err := collect(child)
470 if err != nil {
471 return nil, nil, fmt.Errorf("failed to collect child: %w", err)
472 }
473
474 multiBody = append(multiBody, body...)
475 multiAtts = append(multiAtts, atts...)
476 }
477
478 return multiBody, multiAtts, nil
479 }
480
481 default:
482 return nil, []*rfc822.Section{section}, nil
483 }
484 }
485
486 func (s *Server) importBody(
487 userID, addrID string,
488 header *rfc822.Header,
489 body []string,
490 mimeType rfc822.MIMEType,
491 flags proton.MessageFlag,
492 unread, starred bool,
493 ) (string, error) {
494 subject := header.Get("Subject")
495 sender := tryParseAddress(header.Get("From"))
496 toList := tryParseAddressList(header.Get("To"))
497 ccList := tryParseAddressList(header.Get("Cc"))
498 bccList := tryParseAddressList(header.Get("Bcc"))
499 replytos := tryParseAddressList(header.Get("Reply-To"))
500 date := time.Date(1970, 1, 1, 0, 0, 0, 0, time.UTC)
501
502 headerDate := header.Get("Date")
503 if len(headerDate) != 0 {
504 d, err := mail.ParseDate(headerDate)
505 if err != nil {
506 return "", err
507 }
508
509 date = d
510 }
511
512 // NOTE: Importing without sender adds empty sender on API side
513 if sender == nil {
514 sender = &mail.Address{}
515 }
516
517 // NOTE: Importing without sender adds empty reply to on API side
518 if len(replytos) == 0 {
519 replytos = []*mail.Address{{}}
520 }
521
522 // NOTE: Importing just the first body part matches API behaviour but sucks!
523 return s.b.CreateMessage(
524 userID, addrID,
525 subject,
526 sender,
527 toList, ccList, bccList, replytos,
528 string(body[0]),
529 rfc822.MIMEType(mimeType),
530 flags,
531 date,
532 unread, starred,
533 )
534 }
535
536 func (s *Server) importAttachment(userID, messageID string, att *rfc822.Section) (proton.Attachment, error) {
537 header, err := att.ParseHeader()
538 if err != nil {
539 return proton.Attachment{}, fmt.Errorf("failed to parse attachment header: %w", err)
540 }
541
542 mimeType, _, err := att.ContentType()
543 if err != nil {
544 return proton.Attachment{}, fmt.Errorf("failed to parse attachment content type: %w", err)
545 }
546
547 var disposition, filename string
548
549 if !header.Has("Content-Disposition") {
550 disposition = "attachment"
551 filename = "attachment.bin"
552 } else if dispType, dispParams, err := mime.ParseMediaType(header.Get("Content-Disposition")); err == nil {
553 disposition = dispType
554 filename = dispParams["filename"]
555 } else {
556 disposition = "attachment"
557 filename = "attachment.bin"
558 }
559
560 var body *crypto.PGPSplitMessage
561
562 if header.Get("Content-Transfer-Encoding") == "base64" {
563 b := make([]byte, base64.StdEncoding.DecodedLen(len(att.Body())))
564
565 n, err := base64.StdEncoding.Decode(b, att.Body())
566 if err != nil {
567 return proton.Attachment{}, fmt.Errorf("failed to decode attachment body: %w", err)
568 }
569
570 split, err := crypto.NewPGPMessage(b[:n]).SplitMessage()
571 if err != nil {
572 return proton.Attachment{}, fmt.Errorf("failed to split attachment body: %w", err)
573 }
574
575 body = split
576 } else {
577 msg, err := crypto.NewPGPMessageFromArmored(string(att.Body()))
578 if err != nil {
579 return proton.Attachment{}, fmt.Errorf("failed to parse attachment body: %w", err)
580 }
581
582 split, err := msg.SplitMessage()
583 if err != nil {
584 return proton.Attachment{}, fmt.Errorf("failed to split attachment body: %w", err)
585 }
586
587 body = split
588 }
589
590 // TODO: What about the signature?
591 return s.b.CreateAttachment(
592 userID, messageID,
593 filename,
594 mimeType,
595 proton.Disposition(disposition),
596 header.Get("Content-Id"),
597 body.GetBinaryKeyPacket(),
598 body.GetBinaryDataPacket(),
599 "",
600 )
601 }
602
603 func tryParseAddress(s string) *mail.Address {
604 if s == "" {
605 return nil
606 }
607
608 addr, err := mail.ParseAddress(s)
609 if err != nil {
610 return &mail.Address{
611 Name: s,
612 }
613 }
614
615 return addr
616 }
617
618 func tryParseAddressList(s string) []*mail.Address {
619 if s == "" {
620 return nil
621 }
622
623 addrs, err := mail.ParseAddressList(s)
624 if err != nil {
625 return []*mail.Address{{
626 Name: s,
627 }}
628 }
629
630 return addrs
631 }
632
633 func mustParseInt(num string) int {
634 val, err := strconv.Atoi(num)
635 if err != nil {
636 panic(err)
637 }
638
639 return val
640 }