cmd.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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 cmd
  17. import (
  18. "github.com/olahol/melody"
  19. "github.com/siyuan-note/logging"
  20. "github.com/siyuan-note/siyuan/kernel/util"
  21. )
  22. type Cmd interface {
  23. Name() string
  24. IsRead() bool // 非读即写
  25. Id() float64
  26. Exec()
  27. }
  28. type BaseCmd struct {
  29. id float64
  30. param map[string]interface{}
  31. session *melody.Session
  32. PushPayload *util.Result
  33. }
  34. func (cmd *BaseCmd) Id() float64 {
  35. return cmd.id
  36. }
  37. func (cmd *BaseCmd) Push() {
  38. cmd.PushPayload.Callback = cmd.param["callback"]
  39. appId, _ := cmd.session.Get("app")
  40. cmd.PushPayload.AppId = appId.(string)
  41. sid, _ := cmd.session.Get("id")
  42. cmd.PushPayload.SessionId = sid.(string)
  43. util.PushEvent(cmd.PushPayload)
  44. }
  45. func NewCommand(cmdStr string, cmdId float64, param map[string]interface{}, session *melody.Session) (ret Cmd) {
  46. baseCmd := &BaseCmd{id: cmdId, param: param, session: session}
  47. switch cmdStr {
  48. case "closews":
  49. ret = &closews{baseCmd}
  50. case "ping":
  51. ret = &ping{baseCmd}
  52. }
  53. if nil == ret {
  54. return
  55. }
  56. pushMode := util.PushModeSingleSelf
  57. if pushModeParam := param["pushMode"]; nil != pushModeParam {
  58. pushMode = util.PushMode(pushModeParam.(float64))
  59. }
  60. baseCmd.PushPayload = util.NewCmdResult(ret.Name(), cmdId, pushMode)
  61. appId, _ := baseCmd.session.Get("app")
  62. baseCmd.PushPayload.AppId = appId.(string)
  63. sid, _ := baseCmd.session.Get("id")
  64. baseCmd.PushPayload.SessionId = sid.(string)
  65. return
  66. }
  67. func Exec(cmd Cmd) {
  68. go func() {
  69. defer logging.Recover()
  70. cmd.Exec()
  71. }()
  72. }