summaryrefslogtreecommitdiff
path: root/pkg/model/marshaller.go
blob: 59f990a91b886bb96e2c4bf2002498ba5da1d987 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
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
}