websocket.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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)
  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. func PushBackgroundTask(data map[string]interface{}) {
  133. BroadcastByType("main", "backgroundtask", 0, "", data)
  134. }
  135. type BlockStatResult struct {
  136. RuneCount int `json:"runeCount"`
  137. WordCount int `json:"wordCount"`
  138. LinkCount int `json:"linkCount"`
  139. ImageCount int `json:"imageCount"`
  140. RefCount int `json:"refCount"`
  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 PushClearAllMsg() {
  159. ClearPushProgress(100)
  160. PushClearMsg("")
  161. }
  162. func ClearPushProgress(total int) {
  163. PushProgress(PushProgressCodeEnd, total, total, "")
  164. }
  165. func PushEndlessProgress(msg string) {
  166. PushProgress(PushProgressCodeEndless, 1, 1, msg)
  167. }
  168. func PushProgress(code, current, total int, msg string) {
  169. BroadcastByType("main", "progress", code, msg, map[string]interface{}{
  170. "current": current,
  171. "total": total,
  172. })
  173. }
  174. // PushClearMsg 会清空指定消息。
  175. func PushClearMsg(msgId string) {
  176. BroadcastByType("main", "cmsg", 0, "", map[string]interface{}{"id": msgId})
  177. }
  178. // PushClearProgress 取消进度遮罩。
  179. func PushClearProgress() {
  180. BroadcastByType("main", "cprogress", 0, "", nil)
  181. }
  182. func PushDownloadProgress(id string, percent float32) {
  183. evt := NewCmdResult("downloadProgress", 0, PushModeBroadcast)
  184. evt.Data = map[string]interface{}{
  185. "id": id,
  186. "percent": percent,
  187. }
  188. PushEvent(evt)
  189. }
  190. func PushEvent(event *Result) {
  191. msg := event.Bytes()
  192. mode := event.PushMode
  193. switch mode {
  194. case PushModeBroadcast:
  195. Broadcast(msg)
  196. case PushModeSingleSelf:
  197. single(msg, event.AppId, event.SessionId)
  198. case PushModeBroadcastExcludeSelf:
  199. broadcastOthers(msg, event.SessionId)
  200. case PushModeBroadcastExcludeSelfApp:
  201. broadcastOtherApps(msg, event.AppId)
  202. case PushModeBroadcastApp:
  203. broadcastApp(msg, event.AppId)
  204. case PushModeBroadcastMainExcludeSelfApp:
  205. broadcastOtherAppMains(msg, event.AppId)
  206. }
  207. }
  208. func single(msg []byte, appId, sid string) {
  209. sessions.Range(func(key, value interface{}) bool {
  210. appSessions := value.(*sync.Map)
  211. if key != appId {
  212. return true
  213. }
  214. appSessions.Range(func(key, value interface{}) bool {
  215. session := value.(*melody.Session)
  216. if id, _ := session.Get("id"); id == sid {
  217. session.Write(msg)
  218. }
  219. return true
  220. })
  221. return true
  222. })
  223. }
  224. func Broadcast(msg []byte) {
  225. sessions.Range(func(key, value interface{}) bool {
  226. appSessions := value.(*sync.Map)
  227. appSessions.Range(func(key, value interface{}) bool {
  228. session := value.(*melody.Session)
  229. session.Write(msg)
  230. return true
  231. })
  232. return true
  233. })
  234. }
  235. func broadcastOtherApps(msg []byte, excludeApp string) {
  236. sessions.Range(func(key, value interface{}) bool {
  237. appSessions := value.(*sync.Map)
  238. appSessions.Range(func(key, value interface{}) bool {
  239. session := value.(*melody.Session)
  240. if app, _ := session.Get("app"); app == excludeApp {
  241. return true
  242. }
  243. session.Write(msg)
  244. return true
  245. })
  246. return true
  247. })
  248. }
  249. func broadcastOtherAppMains(msg []byte, excludeApp string) {
  250. sessions.Range(func(key, value interface{}) bool {
  251. appSessions := value.(*sync.Map)
  252. appSessions.Range(func(key, value interface{}) bool {
  253. session := value.(*melody.Session)
  254. if app, _ := session.Get("app"); app == excludeApp {
  255. return true
  256. }
  257. if t, ok := session.Get("type"); ok && "main" != t {
  258. return true
  259. }
  260. session.Write(msg)
  261. return true
  262. })
  263. return true
  264. })
  265. }
  266. func broadcastApp(msg []byte, app string) {
  267. sessions.Range(func(key, value interface{}) bool {
  268. appSessions := value.(*sync.Map)
  269. appSessions.Range(func(key, value interface{}) bool {
  270. session := value.(*melody.Session)
  271. if sessionApp, _ := session.Get("app"); sessionApp != app {
  272. return true
  273. }
  274. session.Write(msg)
  275. return true
  276. })
  277. return true
  278. })
  279. }
  280. func broadcastOthers(msg []byte, excludeSID string) {
  281. sessions.Range(func(key, value interface{}) bool {
  282. appSessions := value.(*sync.Map)
  283. appSessions.Range(func(key, value interface{}) bool {
  284. session := value.(*melody.Session)
  285. if id, _ := session.Get("id"); id == excludeSID {
  286. return true
  287. }
  288. session.Write(msg)
  289. return true
  290. })
  291. return true
  292. })
  293. }
  294. func CountSessions() (ret int) {
  295. sessions.Range(func(key, value interface{}) bool {
  296. ret++
  297. return true
  298. })
  299. return
  300. }