forked from skycoin/skywire
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chat.go
180 lines (150 loc) · 3.73 KB
/
chat.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
//go:generate esc -o static.go -prefix static static
/*
skychat app for skywire visor
*/
package main
import (
"encoding/json"
"flag"
"fmt"
"net"
"net/http"
"sync"
"time"
"github.com/SkycoinProject/dmsg/cipher"
"github.com/SkycoinProject/skycoin/src/util/logging"
"github.com/SkycoinProject/skywire-mainnet/internal/netutil"
"github.com/SkycoinProject/skywire-mainnet/pkg/app"
"github.com/SkycoinProject/skywire-mainnet/pkg/routing"
)
var addr = flag.String("addr", ":8000", "address to bind")
var r = netutil.NewRetrier(50*time.Millisecond, 5, 2)
var (
chatApp *app.App
clientCh chan string
chatConns map[cipher.PubKey]net.Conn
connsMu sync.Mutex
log *logging.MasterLogger
)
func main() {
appName := "skychat"
log = app.NewLogger(appName)
flag.Parse()
a, err := app.Setup(&app.Config{AppName: appName, AppVersion: "1.0", ProtocolVersion: "0.0.1"})
if err != nil {
log.Fatal("Setup failure: ", err)
}
defer func() {
if err := a.Close(); err != nil {
log.Println("Failed to close app:", err)
}
}()
chatApp = a
clientCh = make(chan string)
defer close(clientCh)
chatConns = make(map[cipher.PubKey]net.Conn)
go listenLoop()
http.Handle("/", http.FileServer(FS(false)))
http.HandleFunc("/message", messageHandler)
http.HandleFunc("/sse", sseHandler)
log.Println("Serving HTTP on", *addr)
log.Fatal(http.ListenAndServe(*addr, nil))
}
func listenLoop() {
for {
conn, err := chatApp.Accept()
if err != nil {
log.Println("failed to accept conn:", err)
return
}
raddr := conn.RemoteAddr().(routing.Addr)
connsMu.Lock()
chatConns[raddr.PubKey] = conn
connsMu.Unlock()
go handleConn(conn)
}
}
func handleConn(conn net.Conn) {
raddr := conn.RemoteAddr().(routing.Addr)
for {
buf := make([]byte, 32*1024)
n, err := conn.Read(buf)
if err != nil {
log.Println("failed to read packet:", err)
return
}
clientMsg, err := json.Marshal(map[string]string{"sender": raddr.PubKey.Hex(), "message": string(buf[:n])})
if err != nil {
log.Printf("Failed to marshal json: %v", err)
}
select {
case clientCh <- string(clientMsg):
log.Printf("received and sent to ui: %s\n", clientMsg)
default:
log.Printf("received and trashed: %s\n", clientMsg)
}
}
}
func messageHandler(w http.ResponseWriter, req *http.Request) {
data := map[string]string{}
if err := json.NewDecoder(req.Body).Decode(&data); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
pk := cipher.PubKey{}
if err := pk.UnmarshalText([]byte(data["recipient"])); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
addr := routing.Addr{PubKey: pk, Port: 1}
connsMu.Lock()
conn, ok := chatConns[pk]
connsMu.Unlock()
if !ok {
var err error
err = r.Do(func() error {
conn, err = chatApp.Dial(addr)
return err
})
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
connsMu.Lock()
chatConns[pk] = conn
connsMu.Unlock()
go handleConn(conn)
}
_, err := conn.Write([]byte(data["message"]))
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
connsMu.Lock()
delete(chatConns, pk)
connsMu.Unlock()
return
}
}
func sseHandler(w http.ResponseWriter, req *http.Request) {
f, ok := w.(http.Flusher)
if !ok {
http.Error(w, "Streaming unsupported!", http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
w.Header().Set("Transfer-Encoding", "chunked")
for {
select {
case msg, ok := <-clientCh:
if !ok {
return
}
_, _ = fmt.Fprintf(w, "data: %s\n\n", msg)
f.Flush()
case <-req.Context().Done():
log.Println("SSE connection were closed.")
return
}
}
}