-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
websocket.go
278 lines (243 loc) · 6.81 KB
/
websocket.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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
// SiYuan - Build Your Eternal Digital Garden
// Copyright (c) 2020-present, b3log.org
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package util
import (
"sync"
"time"
"github.com/88250/gulu"
"github.com/olahol/melody"
)
var (
WebSocketServer = melody.New()
// map[string]map[string]*melody.Session{}
sessions = sync.Map{} // {appId, {sessionId, session}}
)
// BroadcastByType 广播所有实例上 typ 类型的会话。
func BroadcastByType(typ, cmd string, code int, msg string, data interface{}) {
typeSessions := SessionsByType(typ)
for _, sess := range typeSessions {
event := NewResult()
event.Cmd = cmd
event.Code = code
event.Msg = msg
event.Data = data
sess.Write(event.Bytes())
}
}
func SessionsByType(typ string) (ret []*melody.Session) {
ret = []*melody.Session{}
sessions.Range(func(key, value interface{}) bool {
appSessions := value.(*sync.Map)
appSessions.Range(func(key, value interface{}) bool {
session := value.(*melody.Session)
if t, ok := session.Get("type"); ok && typ == t {
ret = append(ret, session)
}
return true
})
return true
})
return
}
func AddPushChan(session *melody.Session) {
appID := session.Request.URL.Query().Get("app")
session.Set("app", appID)
id := session.Request.URL.Query().Get("id")
session.Set("id", id)
typ := session.Request.URL.Query().Get("type")
session.Set("type", typ)
if appSessions, ok := sessions.Load(appID); !ok {
appSess := &sync.Map{}
appSess.Store(id, session)
sessions.Store(appID, appSess)
} else {
(appSessions.(*sync.Map)).Store(id, session)
}
}
func RemovePushChan(session *melody.Session) {
app, _ := session.Get("app")
id, _ := session.Get("id")
if nil == app || nil == id {
return
}
appSess, _ := sessions.Load(app)
if nil != appSess {
appSessions := appSess.(*sync.Map)
appSessions.Delete(id)
if 1 > lenOfSyncMap(appSessions) {
sessions.Delete(app)
}
}
}
func lenOfSyncMap(m *sync.Map) (ret int) {
m.Range(func(key, value interface{}) bool {
ret++
return true
})
return
}
func ClosePushChan(id string) {
sessions.Range(func(key, value interface{}) bool {
appSessions := value.(*sync.Map)
appSessions.Range(func(key, value interface{}) bool {
session := value.(*melody.Session)
if sid, _ := session.Get("id"); sid == id {
session.CloseWithMsg([]byte(" close websocket"))
RemovePushChan(session)
}
return true
})
return true
})
}
func ReloadUI() {
evt := NewCmdResult("reloadui", 0, PushModeBroadcast, 0)
PushEvent(evt)
}
func PushTxErr(msg string, code int, data interface{}) {
BroadcastByType("main", "txerr", code, msg, data)
}
func PushUpdateMsg(msgId string, msg string, timeout int) {
BroadcastByType("main", "msg", 0, msg, map[string]interface{}{"id": msgId, "closeTimeout": timeout})
return
}
func PushMsg(msg string, timeout int) (msgId string) {
msgId = gulu.Rand.String(7)
BroadcastByType("main", "msg", 0, msg, map[string]interface{}{"id": msgId, "closeTimeout": timeout})
return
}
func PushErrMsg(msg string, timeout int) (msgId string) {
msgId = gulu.Rand.String(7)
BroadcastByType("main", "msg", -1, msg, map[string]interface{}{"id": msgId, "closeTimeout": timeout})
return
}
func PushStatusBar(msg string) {
msg += " (" + time.Now().Format("2006-01-02 15:04:05") + ")"
BroadcastByType("main", "statusbar", 0, msg, nil)
}
const (
PushProgressCodeProgressed = 0 // 有进度
PushProgressCodeEndless = 1 // 无进度
PushProgressCodeEnd = 2 // 关闭进度
)
func ClearPushProgress(total int) {
PushProgress(PushProgressCodeEnd, total, total, "")
}
func PushEndlessProgress(msg string) {
PushProgress(PushProgressCodeEndless, 1, 1, msg)
}
func PushProgress(code, current, total int, msg string) {
BroadcastByType("main", "progress", code, msg, map[string]interface{}{
"current": current,
"total": total,
})
}
// PushClearMsg 会清空指定消息。
func PushClearMsg(msgId string) {
BroadcastByType("main", "cmsg", 0, "", map[string]interface{}{"id": msgId})
}
// PushClearProgress 取消进度遮罩。
func PushClearProgress() {
BroadcastByType("main", "cprogress", 0, "", nil)
}
func PushDownloadProgress(id string, percent float32) {
evt := NewCmdResult("downloadProgress", 0, PushModeBroadcast, 0)
evt.Data = map[string]interface{}{
"id": id,
"percent": percent,
}
PushEvent(evt)
}
func PushEvent(event *Result) {
msg := event.Bytes()
mode := event.PushMode
if "reload" == event.Cmd {
mode = event.ReloadPushMode
}
switch mode {
case PushModeBroadcast:
Broadcast(msg)
case PushModeSingleSelf:
single(msg, event.AppId, event.SessionId)
case PushModeBroadcastExcludeSelf:
broadcastOthers(msg, event.SessionId)
case PushModeBroadcastExcludeSelfApp:
broadcastOtherApps(msg, event.AppId)
case PushModeNone:
}
}
func single(msg []byte, appId, sid string) {
sessions.Range(func(key, value interface{}) bool {
appSessions := value.(*sync.Map)
if key != appId {
return true
}
appSessions.Range(func(key, value interface{}) bool {
session := value.(*melody.Session)
if id, _ := session.Get("id"); id == sid {
session.Write(msg)
}
return true
})
return true
})
}
func Broadcast(msg []byte) {
sessions.Range(func(key, value interface{}) bool {
appSessions := value.(*sync.Map)
appSessions.Range(func(key, value interface{}) bool {
session := value.(*melody.Session)
session.Write(msg)
return true
})
return true
})
}
func broadcastOtherApps(msg []byte, excludeApp string) {
sessions.Range(func(key, value interface{}) bool {
appSessions := value.(*sync.Map)
appSessions.Range(func(key, value interface{}) bool {
session := value.(*melody.Session)
if app, _ := session.Get("app"); app == excludeApp {
return true
}
session.Write(msg)
return true
})
return true
})
}
func broadcastOthers(msg []byte, excludeSID string) {
sessions.Range(func(key, value interface{}) bool {
appSessions := value.(*sync.Map)
appSessions.Range(func(key, value interface{}) bool {
session := value.(*melody.Session)
if id, _ := session.Get("id"); id == excludeSID {
return true
}
session.Write(msg)
return true
})
return true
})
}
func CountSessions() (ret int) {
sessions.Range(func(key, value interface{}) bool {
ret++
return true
})
return
}