summaryrefslogtreecommitdiff
path: root/xmpp/encoder_decoder.go
blob: c340b090e0c09b7b3f75cb36dede145d0f23eb4b (plain)
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
96
package xmpp

import (
	"encoding/xml"
	"errors"
	"io"
	"log"
	"os"
)

type encoderDecoder struct {
	session    *session
	ct         *xml.Encoder // client transport encoder
	cl         *xml.Encoder // client log encoder
	st         *xml.Decoder // server transport decoder
	sl         *xml.Encoder // server log encoder
	terminator chan bool
}

func newEncoderDecoder(s *session) encoderDecoder {
	ed := encoderDecoder{}

	ed.session = s

	ed.ct = xml.NewEncoder(s.transport)
	ed.ct.Indent("", "    ")

	ed.cl = xml.NewEncoder(os.Stdout)
	ed.cl.Indent("C: ", "    ")

	ed.st = xml.NewDecoder(s.transport)

	ed.sl = xml.NewEncoder(os.Stdout)
	ed.sl.Indent("S: ", "    ")

	return ed
}

func (ed *encoderDecoder) encodeToken(t xml.Token) error {
	var err error
	defer func() {
		if err != nil {
			log.Println(err)
		}
	}()

	err = ed.ct.EncodeToken(t)
	if err != nil {
		return err
	}
	err = ed.ct.Flush()
	if err != nil {
		return err
	}

	err = ed.cl.EncodeToken(t)
	if err != nil {
		return err
	}
	err = ed.cl.Flush()
	if err != nil {
		return err
	}

	return nil
}

func (ed *encoderDecoder) run() {
	for {
		select {
		case <-ed.terminator:
			return
		default:
			t, err := ed.st.Token()
			if t != nil && err == nil {
				err = ed.sl.EncodeToken(t)
				if err != nil {
					log.Println("Could not encode to server stream log")
				}
				err = ed.sl.Flush()
				if err != nil {
					log.Println("Could not flush server stream log")
				}
				c := xml.CopyToken(t)
				ed.session.rx <- c
			}
			if err != nil {
				if errors.Is(err, io.EOF) {
					return
				}
				log.Println(err) // FIXME terminate session on error
				return
			}
		}
	}
}