maddy

Fork https://github.com/foxcpp/maddy

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

 1/*
 2Maddy Mail Server - Composable all-in-one email server.
 3Copyright © 2019-2020 Max Mazurov <fox.cpp@disroot.org>, Maddy Mail Server contributors
 4
 5This program is free software: you can redistribute it and/or modify
 6it under the terms of the GNU General Public License as published by
 7the Free Software Foundation, either version 3 of the License, or
 8(at your option) any later version.
 9
10This program is distributed in the hope that it will be useful,
11but WITHOUT ANY WARRANTY; without even the implied warranty of
12MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13GNU General Public License for more details.
14
15You should have received a copy of the GNU General Public License
16along with this program.  If not, see <https://www.gnu.org/licenses/>.
17*/
18
19package updatepipe
20
21import (
22	"encoding/json"
23	"errors"
24	"fmt"
25	"strconv"
26	"strings"
27
28	mess "github.com/foxcpp/go-imap-mess"
29)
30
31func unescapeName(s string) string {
32	return strings.ReplaceAll(s, "\x10", ";")
33}
34
35func escapeName(s string) string {
36	return strings.ReplaceAll(s, ";", "\x10")
37}
38
39func parseUpdate(s string) (id string, upd *mess.Update, err error) {
40	parts := strings.SplitN(s, ";", 2)
41	if len(parts) != 2 {
42		return "", nil, errors.New("updatepipe: mismatched parts count")
43	}
44
45	upd = &mess.Update{}
46	dec := json.NewDecoder(strings.NewReader(unescapeName(parts[1])))
47	dec.UseNumber()
48	err = dec.Decode(upd)
49	if err != nil {
50		return "", nil, fmt.Errorf("parseUpdate: %w", err)
51	}
52
53	if val, ok := upd.Key.(json.Number); ok {
54		upd.Key, _ = strconv.ParseUint(val.String(), 10, 64)
55	}
56
57	return parts[0], upd, nil
58}
59
60func formatUpdate(myID string, upd mess.Update) (string, error) {
61	updBlob, err := json.Marshal(upd)
62	if err != nil {
63		return "", fmt.Errorf("formatUpdate: %w", err)
64	}
65	return strings.Join([]string{
66		myID,
67		escapeName(string(updBlob)),
68	}, ";") + "\n", nil
69}