websocket.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. // SiYuan - Refactor your thinking
  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. func BroadcastByTypeAndApp(typ, app, cmd string, code int, msg string, data interface{}) {
  30. appSessions, ok := sessions.Load(app)
  31. if !ok {
  32. return
  33. }
  34. appSessions.(*sync.Map).Range(func(key, value interface{}) bool {
  35. session := value.(*melody.Session)
  36. if t, ok := session.Get("type"); ok && typ == t {
  37. event := NewResult()
  38. event.Cmd = cmd
  39. event.Code = code
  40. event.Msg = msg
  41. event.Data = data
  42. session.Write(event.Bytes())
  43. }
  44. return true
  45. })
  46. }
  47. // BroadcastByType 广播所有实例上 typ 类型的会话。
  48. func BroadcastByType(typ, cmd string, code int, msg string, data interface{}) {
  49. typeSessions := SessionsByType(typ)
  50. for _, sess := range typeSessions {
  51. event := NewResult()
  52. event.Cmd = cmd
  53. event.Code = code
  54. event.Msg = msg
  55. event.Data = data
  56. sess.Write(event.Bytes())
  57. }
  58. }
  59. func SessionsByType(typ string) (ret []*melody.Session) {
  60. ret = []*melody.Session{}
  61. sessions.Range(func(key, value interface{}) bool {
  62. appSessions := value.(*sync.Map)
  63. appSessions.Range(func(key, value interface{}) bool {
  64. session := value.(*melody.Session)
  65. if t, ok := session.Get("type"); ok && typ == t {
  66. ret = append(ret, session)
  67. }
  68. return true
  69. })
  70. return true
  71. })
  72. return
  73. }
  74. func AddPushChan(session *melody.Session) {
  75. appID := session.Request.URL.Query().Get("app")
  76. session.Set("app", appID)
  77. id := session.Request.URL.Query().Get("id")
  78. session.Set("id", id)
  79. typ := session.Request.URL.Query().Get("type")
  80. session.Set("type", typ)
  81. if appSessions, ok := sessions.Load(appID); !ok {
  82. appSess := &sync.Map{}
  83. appSess.Store(id, session)
  84. sessions.Store(appID, appSess)
  85. } else {
  86. (appSessions.(*sync.Map)).Store(id, session)
  87. }
  88. }
  89. func RemovePushChan(session *melody.Session) {
  90. app, _ := session.Get("app")
  91. id, _ := session.Get("id")
  92. if nil == app || nil == id {
  93. return
  94. }
  95. appSess, _ := sessions.Load(app)
  96. if nil != appSess {
  97. appSessions := appSess.(*sync.Map)
  98. appSessions.Delete(id)
  99. if 1 > lenOfSyncMap(appSessions) {
  100. sessions.Delete(app)
  101. }
  102. }
  103. }
  104. func lenOfSyncMap(m *sync.Map) (ret int) {
  105. m.Range(func(key, value interface{}) bool {
  106. ret++
  107. return true
  108. })
  109. return
  110. }
  111. func ClosePushChan(id string) {
  112. sessions.Range(func(key, value interface{}) bool {
  113. appSessions := value.(*sync.Map)
  114. appSessions.Range(func(key, value interface{}) bool {
  115. session := value.(*melody.Session)
  116. if sid, _ := session.Get("id"); sid == id {
  117. session.CloseWithMsg([]byte(" close websocket"))
  118. RemovePushChan(session)
  119. }
  120. return true
  121. })
  122. return true
  123. })
  124. }
  125. func ReloadUIResetScroll() {
  126. BroadcastByType("main", "reloadui", 0, "", map[string]interface{}{"resetScroll": true})
  127. }
  128. func ReloadUI() {
  129. BroadcastByType("main", "reloadui", 0, "", nil)
  130. }
  131. func PushTxErr(msg string, code int, data interface{}) {
  132. BroadcastByType("main", "txerr", code, msg, data)
  133. }
  134. func PushUpdateMsg(msgId string, msg string, timeout int) {
  135. BroadcastByType("main", "msg", 0, msg, map[string]interface{}{"id": msgId, "closeTimeout": timeout})
  136. return
  137. }
  138. func PushMsg(msg string, timeout int) (msgId string) {
  139. msgId = gulu.Rand.String(7)
  140. BroadcastByType("main", "msg", 0, msg, map[string]interface{}{"id": msgId, "closeTimeout": timeout})
  141. return
  142. }
  143. func PushErrMsg(msg string, timeout int) (msgId string) {
  144. msgId = gulu.Rand.String(7)
  145. BroadcastByType("main", "msg", -1, msg, map[string]interface{}{"id": msgId, "closeTimeout": timeout})
  146. return
  147. }
  148. func PushStatusBar(msg string) {
  149. msg += " (" + time.Now().Format("2006-01-02 15:04:05") + ")"
  150. BroadcastByType("main", "statusbar", 0, msg, nil)
  151. }
  152. func PushBackgroundTask(data map[string]interface{}) {
  153. BroadcastByType("main", "backgroundtask", 0, "", data)
  154. }
  155. func PushReloadFiletree() {
  156. BroadcastByType("filetree", "reloadFiletree", 0, "", nil)
  157. }
  158. type BlockStatResult struct {
  159. RuneCount int `json:"runeCount"`
  160. WordCount int `json:"wordCount"`
  161. LinkCount int `json:"linkCount"`
  162. ImageCount int `json:"imageCount"`
  163. RefCount int `json:"refCount"`
  164. }
  165. func ContextPushMsg(context map[string]interface{}, msg string) {
  166. switch context[eventbus.CtxPushMsg].(int) {
  167. case eventbus.CtxPushMsgToNone:
  168. break
  169. case eventbus.CtxPushMsgToProgress:
  170. PushEndlessProgress(msg)
  171. case eventbus.CtxPushMsgToStatusBar:
  172. PushStatusBar(msg)
  173. case eventbus.CtxPushMsgToStatusBarAndProgress:
  174. PushStatusBar(msg)
  175. PushEndlessProgress(msg)
  176. }
  177. }
  178. const (
  179. PushProgressCodeProgressed = 0 // 有进度
  180. PushProgressCodeEndless = 1 // 无进度
  181. PushProgressCodeEnd = 2 // 关闭进度
  182. )
  183. func PushClearAllMsg() {
  184. ClearPushProgress(100)
  185. PushClearMsg("")
  186. }
  187. func ClearPushProgress(total int) {
  188. PushProgress(PushProgressCodeEnd, total, total, "")
  189. }
  190. func PushEndlessProgress(msg string) {
  191. PushProgress(PushProgressCodeEndless, 1, 1, msg)
  192. }
  193. func PushProgress(code, current, total int, msg string) {
  194. BroadcastByType("main", "progress", code, msg, map[string]interface{}{
  195. "current": current,
  196. "total": total,
  197. })
  198. }
  199. // PushClearMsg 会清空指定消息。
  200. func PushClearMsg(msgId string) {
  201. BroadcastByType("main", "cmsg", 0, "", map[string]interface{}{"id": msgId})
  202. }
  203. // PushClearProgress 取消进度遮罩。
  204. func PushClearProgress() {
  205. BroadcastByType("main", "cprogress", 0, "", nil)
  206. }
  207. func PushReloadAttrView(avID string) {
  208. BroadcastByType("protyle", "refreshAttributeView", 0, "", map[string]interface{}{"id": avID})
  209. }
  210. func PushReloadDoc(rootID string) {
  211. BroadcastByType("main", "reloaddoc", 0, "", rootID)
  212. }
  213. func PushSaveDoc(rootID, typ string, sources interface{}) {
  214. evt := NewCmdResult("savedoc", 0, PushModeBroadcast)
  215. evt.Data = map[string]interface{}{
  216. "rootID": rootID,
  217. "type": typ,
  218. "sources": sources,
  219. }
  220. PushEvent(evt)
  221. }
  222. func PushProtyleReload(rootID string) {
  223. BroadcastByType("protyle", "reload", 0, "", rootID)
  224. }
  225. func PushProtyleLoading(rootID, msg string) {
  226. BroadcastByType("protyle", "addLoading", 0, msg, rootID)
  227. }
  228. func PushReloadEmojiConf() {
  229. BroadcastByType("main", "reloadEmojiConf", 0, "", nil)
  230. }
  231. func PushDownloadProgress(id string, percent float32) {
  232. evt := NewCmdResult("downloadProgress", 0, PushModeBroadcast)
  233. evt.Data = map[string]interface{}{
  234. "id": id,
  235. "percent": percent,
  236. }
  237. PushEvent(evt)
  238. }
  239. func PushEvent(event *Result) {
  240. msg := event.Bytes()
  241. mode := event.PushMode
  242. switch mode {
  243. case PushModeBroadcast:
  244. Broadcast(msg)
  245. case PushModeSingleSelf:
  246. single(msg, event.AppId, event.SessionId)
  247. case PushModeBroadcastExcludeSelf:
  248. broadcastOthers(msg, event.SessionId)
  249. case PushModeBroadcastExcludeSelfApp:
  250. broadcastOtherApps(msg, event.AppId)
  251. case PushModeBroadcastApp:
  252. broadcastApp(msg, event.AppId)
  253. case PushModeBroadcastMainExcludeSelfApp:
  254. broadcastOtherAppMains(msg, event.AppId)
  255. }
  256. }
  257. func single(msg []byte, appId, sid string) {
  258. sessions.Range(func(key, value interface{}) bool {
  259. appSessions := value.(*sync.Map)
  260. if key != appId {
  261. return true
  262. }
  263. appSessions.Range(func(key, value interface{}) bool {
  264. session := value.(*melody.Session)
  265. if id, _ := session.Get("id"); id == sid {
  266. session.Write(msg)
  267. }
  268. return true
  269. })
  270. return true
  271. })
  272. }
  273. func Broadcast(msg []byte) {
  274. sessions.Range(func(key, value interface{}) bool {
  275. appSessions := value.(*sync.Map)
  276. appSessions.Range(func(key, value interface{}) bool {
  277. session := value.(*melody.Session)
  278. session.Write(msg)
  279. return true
  280. })
  281. return true
  282. })
  283. }
  284. func broadcastOtherApps(msg []byte, excludeApp string) {
  285. sessions.Range(func(key, value interface{}) bool {
  286. appSessions := value.(*sync.Map)
  287. appSessions.Range(func(key, value interface{}) bool {
  288. session := value.(*melody.Session)
  289. if app, _ := session.Get("app"); app == excludeApp {
  290. return true
  291. }
  292. session.Write(msg)
  293. return true
  294. })
  295. return true
  296. })
  297. }
  298. func broadcastOtherAppMains(msg []byte, excludeApp string) {
  299. sessions.Range(func(key, value interface{}) bool {
  300. appSessions := value.(*sync.Map)
  301. appSessions.Range(func(key, value interface{}) bool {
  302. session := value.(*melody.Session)
  303. if app, _ := session.Get("app"); app == excludeApp {
  304. return true
  305. }
  306. if t, ok := session.Get("type"); ok && "main" != t {
  307. return true
  308. }
  309. session.Write(msg)
  310. return true
  311. })
  312. return true
  313. })
  314. }
  315. func broadcastApp(msg []byte, app string) {
  316. sessions.Range(func(key, value interface{}) bool {
  317. appSessions := value.(*sync.Map)
  318. appSessions.Range(func(key, value interface{}) bool {
  319. session := value.(*melody.Session)
  320. if sessionApp, _ := session.Get("app"); sessionApp != app {
  321. return true
  322. }
  323. session.Write(msg)
  324. return true
  325. })
  326. return true
  327. })
  328. }
  329. func broadcastOthers(msg []byte, excludeSID string) {
  330. sessions.Range(func(key, value interface{}) bool {
  331. appSessions := value.(*sync.Map)
  332. appSessions.Range(func(key, value interface{}) bool {
  333. session := value.(*melody.Session)
  334. if id, _ := session.Get("id"); id == excludeSID {
  335. return true
  336. }
  337. session.Write(msg)
  338. return true
  339. })
  340. return true
  341. })
  342. }
  343. func CountSessions() (ret int) {
  344. sessions.Range(func(key, value interface{}) bool {
  345. ret++
  346. return true
  347. })
  348. return
  349. }