websocket.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. // SiYuan - Build Your Eternal Digital Garden
  2. // Copyright (c) 2020-present, b3log.org
  3. //
  4. // This program is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. package util
  17. import (
  18. "sync"
  19. "time"
  20. "github.com/88250/gulu"
  21. "github.com/olahol/melody"
  22. "github.com/siyuan-note/eventbus"
  23. )
  24. var (
  25. WebSocketServer = melody.New()
  26. // map[string]map[string]*melody.Session{}
  27. sessions = sync.Map{} // {appId, {sessionId, session}}
  28. )
  29. // BroadcastByType 广播所有实例上 typ 类型的会话。
  30. func BroadcastByType(typ, cmd string, code int, msg string, data interface{}) {
  31. typeSessions := SessionsByType(typ)
  32. for _, sess := range typeSessions {
  33. event := NewResult()
  34. event.Cmd = cmd
  35. event.Code = code
  36. event.Msg = msg
  37. event.Data = data
  38. sess.Write(event.Bytes())
  39. }
  40. }
  41. func SessionsByType(typ string) (ret []*melody.Session) {
  42. ret = []*melody.Session{}
  43. sessions.Range(func(key, value interface{}) bool {
  44. appSessions := value.(*sync.Map)
  45. appSessions.Range(func(key, value interface{}) bool {
  46. session := value.(*melody.Session)
  47. if t, ok := session.Get("type"); ok && typ == t {
  48. ret = append(ret, session)
  49. }
  50. return true
  51. })
  52. return true
  53. })
  54. return
  55. }
  56. func AddPushChan(session *melody.Session) {
  57. appID := session.Request.URL.Query().Get("app")
  58. session.Set("app", appID)
  59. id := session.Request.URL.Query().Get("id")
  60. session.Set("id", id)
  61. typ := session.Request.URL.Query().Get("type")
  62. session.Set("type", typ)
  63. if appSessions, ok := sessions.Load(appID); !ok {
  64. appSess := &sync.Map{}
  65. appSess.Store(id, session)
  66. sessions.Store(appID, appSess)
  67. } else {
  68. (appSessions.(*sync.Map)).Store(id, session)
  69. }
  70. }
  71. func RemovePushChan(session *melody.Session) {
  72. app, _ := session.Get("app")
  73. id, _ := session.Get("id")
  74. if nil == app || nil == id {
  75. return
  76. }
  77. appSess, _ := sessions.Load(app)
  78. if nil != appSess {
  79. appSessions := appSess.(*sync.Map)
  80. appSessions.Delete(id)
  81. if 1 > lenOfSyncMap(appSessions) {
  82. sessions.Delete(app)
  83. }
  84. }
  85. }
  86. func lenOfSyncMap(m *sync.Map) (ret int) {
  87. m.Range(func(key, value interface{}) bool {
  88. ret++
  89. return true
  90. })
  91. return
  92. }
  93. func ClosePushChan(id string) {
  94. sessions.Range(func(key, value interface{}) bool {
  95. appSessions := value.(*sync.Map)
  96. appSessions.Range(func(key, value interface{}) bool {
  97. session := value.(*melody.Session)
  98. if sid, _ := session.Get("id"); sid == id {
  99. session.CloseWithMsg([]byte(" close websocket"))
  100. RemovePushChan(session)
  101. }
  102. return true
  103. })
  104. return true
  105. })
  106. }
  107. func ReloadUI() {
  108. evt := NewCmdResult("reloadui", 0, PushModeBroadcast, 0)
  109. PushEvent(evt)
  110. }
  111. func PushTxErr(msg string, code int, data interface{}) {
  112. BroadcastByType("main", "txerr", code, msg, data)
  113. }
  114. func PushUpdateMsg(msgId string, msg string, timeout int) {
  115. BroadcastByType("main", "msg", 0, msg, map[string]interface{}{"id": msgId, "closeTimeout": timeout})
  116. return
  117. }
  118. func PushMsg(msg string, timeout int) (msgId string) {
  119. msgId = gulu.Rand.String(7)
  120. BroadcastByType("main", "msg", 0, msg, map[string]interface{}{"id": msgId, "closeTimeout": timeout})
  121. return
  122. }
  123. func PushErrMsg(msg string, timeout int) (msgId string) {
  124. msgId = gulu.Rand.String(7)
  125. BroadcastByType("main", "msg", -1, msg, map[string]interface{}{"id": msgId, "closeTimeout": timeout})
  126. return
  127. }
  128. func PushStatusBar(msg string) {
  129. msg += " (" + time.Now().Format("2006-01-02 15:04:05") + ")"
  130. BroadcastByType("main", "statusbar", 0, msg, nil)
  131. }
  132. type BlockStatResult struct {
  133. RuneCount int `json:"runeCount"`
  134. WordCount int `json:"wordCount"`
  135. LinkCount int `json:"linkCount"`
  136. ImageCount int `json:"imageCount"`
  137. RefCount int `json:"refCount"`
  138. }
  139. func PushStatusBarCounter(stat *BlockStatResult) {
  140. BroadcastByType("main", "statusbarCounter", 0, "", stat)
  141. }
  142. func ContextPushMsg(context map[string]interface{}, msg string) {
  143. switch context[eventbus.CtxPushMsg].(int) {
  144. case eventbus.CtxPushMsgToProgress:
  145. PushEndlessProgress(msg)
  146. case eventbus.CtxPushMsgToStatusBar:
  147. PushStatusBar(msg)
  148. case eventbus.CtxPushMsgToStatusBarAndProgress:
  149. PushStatusBar(msg)
  150. PushEndlessProgress(msg)
  151. }
  152. }
  153. const (
  154. PushProgressCodeProgressed = 0 // 有进度
  155. PushProgressCodeEndless = 1 // 无进度
  156. PushProgressCodeEnd = 2 // 关闭进度
  157. )
  158. func ClearPushProgress(total int) {
  159. PushProgress(PushProgressCodeEnd, total, total, "")
  160. }
  161. func PushEndlessProgress(msg string) {
  162. PushProgress(PushProgressCodeEndless, 1, 1, msg)
  163. }
  164. func PushProgress(code, current, total int, msg string) {
  165. BroadcastByType("main", "progress", code, msg, map[string]interface{}{
  166. "current": current,
  167. "total": total,
  168. })
  169. }
  170. // PushClearMsg 会清空指定消息。
  171. func PushClearMsg(msgId string) {
  172. BroadcastByType("main", "cmsg", 0, "", map[string]interface{}{"id": msgId})
  173. }
  174. // PushClearProgress 取消进度遮罩。
  175. func PushClearProgress() {
  176. BroadcastByType("main", "cprogress", 0, "", nil)
  177. }
  178. func PushDownloadProgress(id string, percent float32) {
  179. evt := NewCmdResult("downloadProgress", 0, PushModeBroadcast, 0)
  180. evt.Data = map[string]interface{}{
  181. "id": id,
  182. "percent": percent,
  183. }
  184. PushEvent(evt)
  185. }
  186. func PushEvent(event *Result) {
  187. msg := event.Bytes()
  188. mode := event.PushMode
  189. if "reload" == event.Cmd {
  190. mode = event.ReloadPushMode
  191. }
  192. switch mode {
  193. case PushModeBroadcast:
  194. Broadcast(msg)
  195. case PushModeSingleSelf:
  196. single(msg, event.AppId, event.SessionId)
  197. case PushModeBroadcastExcludeSelf:
  198. broadcastOthers(msg, event.SessionId)
  199. case PushModeBroadcastExcludeSelfApp:
  200. broadcastOtherApps(msg, event.AppId)
  201. case PushModeNone:
  202. }
  203. }
  204. func single(msg []byte, appId, sid string) {
  205. sessions.Range(func(key, value interface{}) bool {
  206. appSessions := value.(*sync.Map)
  207. if key != appId {
  208. return true
  209. }
  210. appSessions.Range(func(key, value interface{}) bool {
  211. session := value.(*melody.Session)
  212. if id, _ := session.Get("id"); id == sid {
  213. session.Write(msg)
  214. }
  215. return true
  216. })
  217. return true
  218. })
  219. }
  220. func Broadcast(msg []byte) {
  221. sessions.Range(func(key, value interface{}) bool {
  222. appSessions := value.(*sync.Map)
  223. appSessions.Range(func(key, value interface{}) bool {
  224. session := value.(*melody.Session)
  225. session.Write(msg)
  226. return true
  227. })
  228. return true
  229. })
  230. }
  231. func broadcastOtherApps(msg []byte, excludeApp string) {
  232. sessions.Range(func(key, value interface{}) bool {
  233. appSessions := value.(*sync.Map)
  234. appSessions.Range(func(key, value interface{}) bool {
  235. session := value.(*melody.Session)
  236. if app, _ := session.Get("app"); app == excludeApp {
  237. return true
  238. }
  239. session.Write(msg)
  240. return true
  241. })
  242. return true
  243. })
  244. }
  245. func broadcastOthers(msg []byte, excludeSID string) {
  246. sessions.Range(func(key, value interface{}) bool {
  247. appSessions := value.(*sync.Map)
  248. appSessions.Range(func(key, value interface{}) bool {
  249. session := value.(*melody.Session)
  250. if id, _ := session.Get("id"); id == excludeSID {
  251. return true
  252. }
  253. session.Write(msg)
  254. return true
  255. })
  256. return true
  257. })
  258. }
  259. func CountSessions() (ret int) {
  260. sessions.Range(func(key, value interface{}) bool {
  261. ret++
  262. return true
  263. })
  264. return
  265. }