streaming.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. package mastodon
  2. import (
  3. "bufio"
  4. "context"
  5. "encoding/json"
  6. "io"
  7. "net/http"
  8. "net/url"
  9. "path"
  10. "strings"
  11. )
  12. // UpdateEvent is struct for passing status event to app.
  13. type UpdateEvent struct {
  14. Status *Status `json:"status"`
  15. }
  16. func (e *UpdateEvent) event() {}
  17. // NotificationEvent is struct for passing notification event to app.
  18. type NotificationEvent struct {
  19. Notification *Notification `json:"notification"`
  20. }
  21. func (e *NotificationEvent) event() {}
  22. // DeleteEvent is struct for passing deletion event to app.
  23. type DeleteEvent struct{ ID string }
  24. func (e *DeleteEvent) event() {}
  25. // ErrorEvent is struct for passing errors to app.
  26. type ErrorEvent struct{ err error }
  27. func (e *ErrorEvent) event() {}
  28. func (e *ErrorEvent) Error() string { return e.err.Error() }
  29. // Event is interface passing events to app.
  30. type Event interface {
  31. event()
  32. }
  33. func handleReader(q chan Event, r io.Reader) error {
  34. var name string
  35. s := bufio.NewScanner(r)
  36. for s.Scan() {
  37. line := s.Text()
  38. token := strings.SplitN(line, ":", 2)
  39. if len(token) != 2 {
  40. continue
  41. }
  42. switch strings.TrimSpace(token[0]) {
  43. case "event":
  44. name = strings.TrimSpace(token[1])
  45. case "data":
  46. var err error
  47. switch name {
  48. case "update":
  49. var status Status
  50. err = json.Unmarshal([]byte(token[1]), &status)
  51. if err == nil {
  52. q <- &UpdateEvent{&status}
  53. }
  54. case "notification":
  55. var notification Notification
  56. err = json.Unmarshal([]byte(token[1]), &notification)
  57. if err == nil {
  58. q <- &NotificationEvent{&notification}
  59. }
  60. case "delete":
  61. q <- &DeleteEvent{ID: string(strings.TrimSpace(token[1]))}
  62. }
  63. if err != nil {
  64. q <- &ErrorEvent{err}
  65. }
  66. }
  67. }
  68. return s.Err()
  69. }
  70. func (c *Client) streaming(ctx context.Context, p string, params url.Values) (chan Event, error) {
  71. u, err := url.Parse(c.config.Server)
  72. if err != nil {
  73. return nil, err
  74. }
  75. u.Path = path.Join(u.Path, "/api/v1/streaming", p)
  76. u.RawQuery = params.Encode()
  77. req, err := http.NewRequest(http.MethodGet, u.String(), nil)
  78. if err != nil {
  79. return nil, err
  80. }
  81. req = req.WithContext(ctx)
  82. req.Header.Set("Authorization", "Bearer "+c.config.AccessToken)
  83. q := make(chan Event)
  84. go func() {
  85. defer close(q)
  86. for {
  87. select {
  88. case <-ctx.Done():
  89. return
  90. default:
  91. }
  92. c.doStreaming(req, q)
  93. }
  94. }()
  95. return q, nil
  96. }
  97. func (c *Client) doStreaming(req *http.Request, q chan Event) {
  98. resp, err := c.Do(req)
  99. if err != nil {
  100. q <- &ErrorEvent{err}
  101. return
  102. }
  103. defer resp.Body.Close()
  104. if resp.StatusCode != http.StatusOK {
  105. q <- &ErrorEvent{parseAPIError("bad request", resp)}
  106. return
  107. }
  108. err = handleReader(q, resp.Body)
  109. if err != nil {
  110. q <- &ErrorEvent{err}
  111. }
  112. }
  113. // StreamingUser return channel to read events on home.
  114. func (c *Client) StreamingUser(ctx context.Context) (chan Event, error) {
  115. return c.streaming(ctx, "user", nil)
  116. }
  117. // StreamingPublic return channel to read events on public.
  118. func (c *Client) StreamingPublic(ctx context.Context, isLocal bool) (chan Event, error) {
  119. p := "public"
  120. if isLocal {
  121. p = path.Join(p, "local")
  122. }
  123. return c.streaming(ctx, p, nil)
  124. }
  125. // StreamingHashtag return channel to read events on tagged timeline.
  126. func (c *Client) StreamingHashtag(ctx context.Context, tag string, isLocal bool) (chan Event, error) {
  127. params := url.Values{}
  128. params.Set("tag", tag)
  129. p := "hashtag"
  130. if isLocal {
  131. p = path.Join(p, "local")
  132. }
  133. return c.streaming(ctx, p, params)
  134. }
  135. // StreamingList return channel to read events on a list.
  136. func (c *Client) StreamingList(ctx context.Context, id string) (chan Event, error) {
  137. params := url.Values{}
  138. params.Set("list", string(id))
  139. return c.streaming(ctx, "list", params)
  140. }