-
Notifications
You must be signed in to change notification settings - Fork 3
/
webui.go
184 lines (157 loc) · 3.81 KB
/
webui.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
181
182
183
184
package main
import (
"context"
"encoding/json"
"errors"
"html/template"
"net/http"
"sync"
"github.com/gorilla/websocket"
"github.com/nymo-net/nymo"
)
type webui struct {
m http.ServeMux
u websocket.Upgrader
user *nymo.User
db *database
wsLock sync.RWMutex
wsHandler map[*websocket.Conn]chan<- baseClient
counter uint32
peer sync.Map
}
var (
web = webui{wsHandler: make(map[*websocket.Conn]chan<- baseClient)}
indexTpl = template.Must(template.New("index.gohtml").Funcs(template.FuncMap{
"convertAddr": nymo.ConvertAddrToStr,
}).ParseFiles("./view/index.gohtml"))
)
func init() {
web.registerRoutes()
}
func (w *webui) registerRoutes() {
w.m.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static"))))
w.m.HandleFunc("/", w.serveIndex)
}
func (w *webui) websocketHandle(conn *websocket.Conn, msgChan chan baseClient) {
w.wsLock.Lock()
w.wsHandler[conn] = msgChan
w.wsLock.Unlock()
defer func() {
w.wsLock.Lock()
delete(w.wsHandler, conn)
w.wsLock.Unlock()
close(msgChan)
}()
go func() {
defer conn.Close()
for msg := range msgChan {
if err := conn.WriteJSON(msg); err != nil {
if !websocket.IsCloseError(err, websocket.CloseGoingAway) {
log.Errorf("[webui] websocket: %s", err)
} else {
log.Debugf("[webui] websocket: %s", err)
}
return
}
}
}()
for {
var msg baseServer
if err := conn.ReadJSON(&msg); err != nil {
if !websocket.IsCloseError(err, websocket.CloseGoingAway) {
log.Errorf("[webui] websocket: %s", err)
} else {
log.Debugf("[webui] websocket: %s", err)
}
return
}
var action string
if err := json.Unmarshal(msg[0], &action); err != nil {
log.Errorf("[webui] websocket: %s", err)
return
}
var err error
switch action {
case "new_msg":
err = w.newMessage(msg[1])
case "alias":
err = w.setAlias(msg[1])
case "history":
var his *history
his, err = w.getHistory(msg[1])
if err == nil {
msgChan <- baseClient{"history", his}
}
case "meta":
m := metadata{
Version: nymo.Version(),
Address: w.user.Address().String(),
Servers: w.user.ListServers(),
}
w.peer.Range(func(_, value interface{}) bool {
m.Peers = append(m.Peers, value.(string))
return true
})
msgChan <- baseClient{"meta", m}
default:
err = errors.New("unknown op str")
}
if err != nil {
log.Warnf("[webui] websocket process: %s", err)
msgChan <- baseClient{"err", err.Error()}
}
}
}
type contact struct {
RowID uint
Address []byte
Alias *string
Message *string
Self *bool
}
type indexRender struct {
Contacts []contact
}
func renderIndex(ctx context.Context, db *database, cr *indexRender) error {
q, err := db.QueryContext(ctx, "WITH `lmsg` AS (SELECT MAX(ROWID) AS `msg_id` FROM `dec_msg` GROUP BY `target`),"+
"`lmsg_c` AS (SELECT * FROM `dec_msg` JOIN `lmsg` ON `dec_msg`.ROWID = `lmsg`.`msg_id`)"+
"SELECT `rowid`, `key`, `alias`, `self`, `content` "+
"FROM `user` LEFT JOIN `lmsg_c` ON `rowid`=`target` "+
"WHERE `rowid`>0 ORDER BY `msg_id` DESC")
if err != nil {
return err
}
for q.Next() {
var c contact
if err := q.Scan(&c.RowID, &c.Address, &c.Alias, &c.Self, &c.Message); err != nil {
return err
}
cr.Contacts = append(cr.Contacts, c)
}
return nil
}
func (w *webui) serveIndex(wr http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(wr, r)
return
}
if websocket.IsWebSocketUpgrade(r) {
conn, err := w.u.Upgrade(wr, r, nil)
if err != nil {
log.Warn(err)
} else {
go w.websocketHandle(conn, make(chan baseClient, 10))
}
return
}
var render indexRender
err := renderIndex(r.Context(), w.db, &render)
if err != nil {
http.Error(wr, err.Error(), http.StatusInternalServerError)
return
}
err = indexTpl.Execute(wr, &render)
if err != nil {
log.Error(err)
}
}