broadcast.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package dao
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "net/http"
  8. "net/url"
  9. "go-common/library/log"
  10. "go-common/library/net/metadata"
  11. )
  12. const (
  13. _goimChatURI = "/x/internal/chat/push/room"
  14. _broadcastURI = "/x/internal/broadcast/push/room"
  15. _broadcastDmOperation = 1000
  16. _broadcastDmRoomFmt = "video://%d/%d" //video://{aid}/{cid}
  17. )
  18. func (d *Dao) goimChatURI() string {
  19. return d.conf.Host.API + _goimChatURI
  20. }
  21. func (d *Dao) broadcastURI() string {
  22. return d.conf.Host.API + _broadcastURI
  23. }
  24. // BroadcastInGoim send dm msg in realtime.
  25. func (d *Dao) BroadcastInGoim(c context.Context, cid, aid int64, info json.RawMessage) (err error) {
  26. var (
  27. res struct {
  28. Code int64 `json:"code"`
  29. }
  30. data = map[string]interface{}{
  31. "cmd": "DM",
  32. "info": info,
  33. }
  34. )
  35. v, err := json.Marshal(data)
  36. if err != nil {
  37. log.Error("json.Marshal(%s) error(%v)", info, err)
  38. return
  39. }
  40. url := fmt.Sprintf("%s?cids=%d&aid=%d", d.goimChatURI(), cid, aid)
  41. req, err := http.NewRequest("POST", url, bytes.NewReader(v))
  42. if err != nil {
  43. log.Error("broadcast http.NewRequest() error(%v)", err)
  44. return
  45. }
  46. if err = d.httpCli.Do(c, req, &res); err != nil {
  47. log.Error("httpCli.Do(%s) error(%v)", url, err)
  48. return
  49. }
  50. if res.Code != 0 {
  51. err = fmt.Errorf("broadcast api failed(%d)", res.Code)
  52. log.Error("broadcast(%s) res code(%d)", url, res.Code)
  53. }
  54. return
  55. }
  56. // Broadcast send dm msg in realtime.
  57. func (d *Dao) Broadcast(c context.Context, cid, aid int64, msg string) (err error) {
  58. var (
  59. res struct {
  60. Code int64 `json:"code"`
  61. }
  62. )
  63. params := url.Values{}
  64. params.Set("operation", fmt.Sprint(_broadcastDmOperation))
  65. params.Set("room", fmt.Sprintf(_broadcastDmRoomFmt, aid, cid))
  66. params.Set("message", msg)
  67. if err = d.httpCli.Post(c, d.broadcastURI(), metadata.String(c, metadata.RemoteIP), params, &res); err != nil {
  68. log.Error("httpCli.Do(%s) error(%v)", d.broadcastURI(), err)
  69. return
  70. }
  71. if res.Code != 0 {
  72. err = fmt.Errorf("broadcast api failed(%d)", res.Code)
  73. log.Error("broadcast(%s) res code(%d)", d.broadcastURI(), res.Code)
  74. }
  75. return
  76. }