websocket.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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/88250/lute/html"
  22. "github.com/88250/melody"
  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. msg = html.EscapeHTMLStr(msg)
  113. BroadcastByType("main", "txerr", code, msg, data)
  114. }
  115. func PushUpdateMsg(msgId string, msg string, timeout int) {
  116. msg = html.EscapeHTMLStr(msg)
  117. BroadcastByType("main", "msg", 0, msg, map[string]interface{}{"id": msgId, "closeTimeout": timeout})
  118. return
  119. }
  120. func PushMsg(msg string, timeout int) (msgId string) {
  121. msgId = gulu.Rand.String(7)
  122. msg = html.EscapeHTMLStr(msg)
  123. BroadcastByType("main", "msg", 0, msg, map[string]interface{}{"id": msgId, "closeTimeout": timeout})
  124. return
  125. }
  126. func PushErrMsg(msg string, timeout int) (msgId string) {
  127. msgId = gulu.Rand.String(7)
  128. msg = html.EscapeHTMLStr(msg)
  129. BroadcastByType("main", "msg", -1, msg, map[string]interface{}{"id": msgId, "closeTimeout": timeout})
  130. return
  131. }
  132. func PushStatusBar(msg string) {
  133. msg += " (" + time.Now().Format("2006-01-02 15:04:05") + ")"
  134. msg = html.EscapeHTMLStr(msg)
  135. BroadcastByType("main", "statusbar", 0, msg, nil)
  136. }
  137. const (
  138. PushProgressCodeProgressed = 0 // 有进度
  139. PushProgressCodeEndless = 1 // 无进度
  140. PushProgressCodeEnd = 2 // 关闭进度
  141. )
  142. func ClearPushProgress(total int) {
  143. PushProgress(PushProgressCodeEnd, total, total, "")
  144. }
  145. func PushEndlessProgress(msg string) {
  146. PushProgress(PushProgressCodeEndless, 1, 1, msg)
  147. }
  148. func PushProgress(code, current, total int, msg string) {
  149. BroadcastByType("main", "progress", code, msg, map[string]interface{}{
  150. "current": current,
  151. "total": total,
  152. })
  153. }
  154. // PushClearMsg 会清空指定消息。
  155. func PushClearMsg(msgId string) {
  156. BroadcastByType("main", "cmsg", 0, "", map[string]interface{}{"id": msgId})
  157. }
  158. // PushClearProgress 取消进度遮罩。
  159. func PushClearProgress() {
  160. BroadcastByType("main", "cprogress", 0, "", nil)
  161. }
  162. func PushDownloadProgress(id string, percent float32) {
  163. evt := NewCmdResult("downloadProgress", 0, PushModeBroadcast, 0)
  164. evt.Data = map[string]interface{}{
  165. "id": id,
  166. "percent": percent,
  167. }
  168. PushEvent(evt)
  169. }
  170. func PushEvent(event *Result) {
  171. msg := event.Bytes()
  172. mode := event.PushMode
  173. if "reload" == event.Cmd {
  174. mode = event.ReloadPushMode
  175. }
  176. switch mode {
  177. case PushModeBroadcast:
  178. Broadcast(msg)
  179. case PushModeSingleSelf:
  180. single(msg, event.AppId, event.SessionId)
  181. case PushModeBroadcastExcludeSelf:
  182. broadcastOthers(msg, event.SessionId)
  183. case PushModeBroadcastExcludeSelfApp:
  184. broadcastOtherApps(msg, event.AppId)
  185. case PushModeNone:
  186. }
  187. }
  188. func single(msg []byte, appId, sid string) {
  189. sessions.Range(func(key, value interface{}) bool {
  190. appSessions := value.(*sync.Map)
  191. if key != appId {
  192. return true
  193. }
  194. appSessions.Range(func(key, value interface{}) bool {
  195. session := value.(*melody.Session)
  196. if id, _ := session.Get("id"); id == sid {
  197. session.Write(msg)
  198. }
  199. return true
  200. })
  201. return true
  202. })
  203. }
  204. func Broadcast(msg []byte) {
  205. sessions.Range(func(key, value interface{}) bool {
  206. appSessions := value.(*sync.Map)
  207. appSessions.Range(func(key, value interface{}) bool {
  208. session := value.(*melody.Session)
  209. session.Write(msg)
  210. return true
  211. })
  212. return true
  213. })
  214. }
  215. func broadcastOtherApps(msg []byte, excludeApp string) {
  216. sessions.Range(func(key, value interface{}) bool {
  217. appSessions := value.(*sync.Map)
  218. appSessions.Range(func(key, value interface{}) bool {
  219. session := value.(*melody.Session)
  220. if app, _ := session.Get("app"); app == excludeApp {
  221. return true
  222. }
  223. session.Write(msg)
  224. return true
  225. })
  226. return true
  227. })
  228. }
  229. func broadcastOthers(msg []byte, excludeSID string) {
  230. sessions.Range(func(key, value interface{}) bool {
  231. appSessions := value.(*sync.Map)
  232. appSessions.Range(func(key, value interface{}) bool {
  233. session := value.(*melody.Session)
  234. if id, _ := session.Get("id"); id == excludeSID {
  235. return true
  236. }
  237. session.Write(msg)
  238. return true
  239. })
  240. return true
  241. })
  242. }
  243. func CountSessions() (ret int) {
  244. sessions.Range(func(key, value interface{}) bool {
  245. ret++
  246. return true
  247. })
  248. return
  249. }