-
Notifications
You must be signed in to change notification settings - Fork 0
/
outbound.go
83 lines (68 loc) · 1.88 KB
/
outbound.go
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
package main
import (
"bytes"
"fmt"
"io"
"os"
)
func handle(message []byte) ([]byte, error) {
cmd := bytes.ToUpper(bytes.TrimSpace(bytes.Split(message, []byte(" "))[0]))
args := bytes.TrimSpace(bytes.TrimPrefix(message, cmd))
switch string(cmd) {
case "SEND":
return send(args)
}
return message, nil
}
func send(args []byte) ([]byte, error) {
if args[0] != '#' {
return []byte(""), fmt.Errorf("->> ERR: Recipient must be a channel ('#name')")
}
recipient := bytes.Split(args, []byte(" "))[0]
if len(recipient) == 1 {
return []byte(""), fmt.Errorf("->> ERR: Recipient must have a name ('#name')")
}
args = bytes.TrimSpace(bytes.TrimPrefix(args, recipient))
filename := bytes.Split(args, []byte(" "))[0]
if len(filename) == 1 {
return []byte(""), fmt.Errorf("->> ERR: File must be saved with a name")
}
filepath := string(bytes.TrimSpace(bytes.TrimPrefix(args, filename)))
filepathStat, err := os.Stat(filepath)
if err != nil {
return []byte(""), err
}
if !filepathStat.Mode().IsRegular() {
return []byte(""), fmt.Errorf("->> ERR: %s is not a regular file", filepath)
}
buffer := make([]byte, 8)
var body []byte
file, err := os.Open(filepath)
if err != nil {
return []byte(""), err
}
for {
n, err := file.Read(buffer)
if err != nil && err != io.EOF {
return []byte(""), err
}
if n == 0 {
break
}
body = append(body, buffer[:n]...)
}
formattedBody := replaceReturns(body)
command := []byte("SEND ")
command = append(command, recipient...)
command = append(command, []byte(" ")...)
command = append(command, filename...)
command = append(command, []byte(" >> ")...)
command = append(command, formattedBody...)
return command, nil
}
func replaceReturns(body []byte) []byte {
splittedBody := bytes.Split(body, []byte("\n"))
joinedBody := bytes.Join(splittedBody, []byte("//"))
joinedBody = append(joinedBody, '\n')
return joinedBody
}