idecnode/pkg/model/marshaller.go

96 lines
1.9 KiB
Go
Raw Permalink Normal View History

2024-10-20 03:39:07 +03:00
package model
import (
"errors"
"fmt"
"strconv"
"strings"
"time"
)
var ErrInvalidMessage = errors.New("invalid message")
func MessageFromBundleLine(bundle string) (*Message, error) {
var uid, text string
if _, err := fmt.Sscanf(bundle, "%s:%s", &uid, &text); err != nil {
return nil, err
}
return MessageFromBundle(uid, text)
}
func MessageFromBundle(uid, text string) (*Message, error) {
lines := strings.SplitN(text, "\n", 9)
if len(lines) < 9 {
return nil, ErrInvalidMessage
}
repto := ""
tag := lines[0]
tags := strings.SplitN(tag, "/", 4)
if len(tags) == 4 {
if tags[2] == "repto" {
repto = tags[3]
}
}
timestamp, err := strconv.Atoi(lines[2])
if err != nil {
return nil, err
}
date := time.Unix(int64(timestamp), 0)
return &Message{
ID: uid,
RepTo: repto,
EchoArea: lines[1],
Date: date,
From: lines[3],
Addr: lines[4],
MsgTo: lines[5],
Subject: lines[6],
Message: lines[8],
}, nil
}
func MessageFromPointMessage(node string, point string, pointMessage string) (*Message, error) {
lines := strings.SplitN(pointMessage, "\n", 5)
if len(lines) < 4 {
return nil, ErrInvalidMessage
}
repto := ""
message := lines[4]
if strings.HasPrefix(message, "@repto:") {
strings.TrimPrefix(message, "@repto:")
messageParts := strings.SplitN(message, "\n", 2)
repto, message = messageParts[0], messageParts[1]
}
return &Message{
ID: UIDFromText(pointMessage),
RepTo: repto,
EchoArea: lines[0],
Date: time.Now(),
From: point,
Addr: node,
MsgTo: lines[1],
Subject: lines[2],
Message: message,
}, nil
}
func EchoFromText(text string) *Echo {
e := new(Echo)
lines := strings.Split(text, "\n")
e.Name = lines[0]
e.Messages = make([]string, 0, len(lines))
for _, line := range lines[1:] {
if len(line) == 20 {
e.Messages = append(e.Messages, line)
}
}
return e
}