1/*2Maddy Mail Server - Composable all-in-one email server.3Copyright © 2019-2020 Max Mazurov <fox.cpp@disroot.org>, Maddy Mail Server contributors45This program is free software: you can redistribute it and/or modify6it under the terms of the GNU General Public License as published by7the Free Software Foundation, either version 3 of the License, or8(at your option) any later version.910This program is distributed in the hope that it will be useful,11but WITHOUT ANY WARRANTY; without even the implied warranty of12MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the13GNU General Public License for more details.1415You should have received a copy of the GNU General Public License16along with this program. If not, see <https://www.gnu.org/licenses/>.17*/1819package updatepipe2021import (22 "encoding/json"23 "errors"24 "fmt"25 "strconv"26 "strings"2728 mess "github.com/foxcpp/go-imap-mess"29)3031func unescapeName(s string) string {32 return strings.ReplaceAll(s, "\x10", ";")33}3435func escapeName(s string) string {36 return strings.ReplaceAll(s, ";", "\x10")37}3839func 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 }4445 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 }5253 if val, ok := upd.Key.(json.Number); ok {54 upd.Key, _ = strconv.ParseUint(val.String(), 10, 64)55 }5657 return parts[0], upd, nil58}5960func 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", nil69}