mlisting

Mailing list service

git clone git://git.lin.moe/go/mlisting.git

 1package storage
 2
 3import (
 4	"bytes"
 5	"io"
 6	"strings"
 7
 8	gomsg "github.com/emersion/go-message"
 9	"github.com/k3a/html2text"
10)
11
12func MailToText(entity *gomsg.Entity) string {
13	var (
14		ori_body *bytes.Buffer
15		text     = ""
16	)
17
18	switch v := entity.Body.(type) {
19	case *bytes.Buffer:
20		ori_body = bytes.NewBuffer(v.Bytes())
21	default:
22		ori_body = bytes.NewBuffer(nil)
23		if _, err := io.Copy(ori_body, entity.Body); err != nil {
24			return ""
25		}
26		entity.Body = bytes.NewReader(ori_body.Bytes())
27	}
28	entity.Walk(func(path []int, entity *gomsg.Entity, err error) error {
29		ct, _, _ := entity.Header.ContentType()
30		if ct == "text/plain" {
31			b, err := io.ReadAll(entity.Body)
32			if err != nil {
33				return nil
34			}
35			text = string(b)
36			return io.EOF
37		} else if ct == "text/html" {
38			b, err := io.ReadAll(entity.Body)
39			if err != nil {
40				return nil
41			}
42			text = html2text.HTML2Text(string(b))
43		}
44		return nil
45	})
46	entity.Body = ori_body
47	return text
48}
49
50func PermString(perm uint8) string {
51	perms := []string{}
52	if perm&PERM_BROWSE != 0 {
53		perms = append(perms, "browse")
54	}
55	if perm&PERM_REPLY != 0 {
56		perms = append(perms, "reply")
57	}
58	if perm&PERM_POST != 0 {
59		perms = append(perms, "post")
60	}
61	return strings.Join(perms, ",")
62}