websocket.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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 ContextPushMsg(context map[string]interface{}, msg string) {
  140. switch context[eventbus.CtxPushMsg].(int) {
  141. case eventbus.CtxPushMsgToProgress:
  142. PushEndlessProgress(msg)
  143. case eventbus.CtxPushMsgToStatusBar:
  144. PushStatusBar(msg)
  145. case eventbus.CtxPushMsgToStatusBarAndProgress:
  146. PushStatusBar(msg)
  147. PushEndlessProgress(msg)
  148. }
  149. }
  150. const (
  151. PushProgressCodeProgressed = 0 // 有进度
  152. PushProgressCodeEndless = 1 // 无进度
  153. PushProgressCodeEnd = 2 // 关闭进度
  154. )
  155. func ClearPushProgress(total int) {
  156. PushProgress(PushProgressCodeEnd, total, total, "")
  157. }
  158. func PushEndlessProgress(msg string) {
  159. PushProgress(PushProgressCodeEndless, 1, 1, msg)
  160. }
  161. func PushProgress(code, current, total int, msg string) {
  162. BroadcastByType("main", "progress", code, msg, map[string]interface{}{
  163. "current": current,
  164. "total": total,
  165. })
  166. }
  167. // PushClearMsg 会清空指定消息。
  168. func PushClearMsg(msgId string) {
  169. BroadcastByType("main", "cmsg", 0, "", map[string]interface{}{"id": msgId})
  170. }
  171. // PushClearProgress 取消进度遮罩。
  172. func PushClearProgress() {
  173. BroadcastByType("main", "cprogress", 0, "", nil)
  174. }
  175. func PushDownloadProgress(id string, percent float32) {
  176. evt := NewCmdResult("downloadProgress", 0, PushModeBroadcast, 0)
  177. evt.Data = map[string]interface{}{
  178. "id": id,
  179. "percent": percent,
  180. }
  181. PushEvent(evt)
  182. }
  183. func PushEvent(event *Result) {
  184. msg := event.Bytes()
  185. mode := event.PushMode
  186. if "reload" == event.Cmd {
  187. mode = event.ReloadPushMode
  188. }
  189. switch mode {
  190. case PushModeBroadcast:
  191. Broadcast(msg)
  192. case PushModeSingleSelf:
  193. single(msg, event.AppId, event.SessionId)
  194. case PushModeBroadcastExcludeSelf:
  195. broadcastOthers(msg, event.SessionId)
  196. case PushModeBroadcastExcludeSelfApp:
  197. broadcastOtherApps(msg, event.AppId)
  198. case PushModeNone:
  199. }
  200. }
  201. func single(msg []byte, appId, sid string) {
  202. sessions.Range(func(key, value interface{}) bool {
  203. appSessions := value.(*sync.Map)
  204. if key != appId {
  205. return true
  206. }
  207. appSessions.Range(func(key, value interface{}) bool {
  208. session := value.(*melody.Session)
  209. if id, _ := session.Get("id"); id == sid {
  210. session.Write(msg)
  211. }
  212. return true
  213. })
  214. return true
  215. })
  216. }
  217. func Broadcast(msg []byte) {
  218. sessions.Range(func(key, value interface{}) bool {
  219. appSessions := value.(*sync.Map)
  220. appSessions.Range(func(key, value interface{}) bool {
  221. session := value.(*melody.Session)
  222. session.Write(msg)
  223. return true
  224. })
  225. return true
  226. })
  227. }
  228. func broadcastOtherApps(msg []byte, excludeApp string) {
  229. sessions.Range(func(key, value interface{}) bool {
  230. appSessions := value.(*sync.Map)
  231. appSessions.Range(func(key, value interface{}) bool {
  232. session := value.(*melody.Session)
  233. if app, _ := session.Get("app"); app == excludeApp {
  234. return true
  235. }
  236. session.Write(msg)
  237. return true
  238. })
  239. return true
  240. })
  241. }
  242. func broadcastOthers(msg []byte, excludeSID string) {
  243. sessions.Range(func(key, value interface{}) bool {
  244. appSessions := value.(*sync.Map)
  245. appSessions.Range(func(key, value interface{}) bool {
  246. session := value.(*melody.Session)
  247. if id, _ := session.Get("id"); id == excludeSID {
  248. return true
  249. }
  250. session.Write(msg)
  251. return true
  252. })
  253. return true
  254. })
  255. }
  256. func CountSessions() (ret int) {
  257. sessions.Range(func(key, value interface{}) bool {
  258. ret++
  259. return true
  260. })
  261. return
  262. }