author | Mikael Berthe <mikael@lilotux.net> |
Sat, 29 Apr 2017 17:30:58 +0200 | |
changeset 157 | 6e9d927d5e32 |
parent 140 | 7665451f74cc |
child 159 | 408aa794d9bb |
permissions | -rw-r--r-- |
130 | 1 |
/* |
2 |
Copyright 2017 Mikael Berthe |
|
3 |
||
4 |
Licensed under the MIT license. Please see the LICENSE file is this directory. |
|
5 |
*/ |
|
6 |
||
138
23d3a518d0ad
Update package name in source files
Mikael Berthe <mikael@lilotux.net>
parents:
130
diff
changeset
|
7 |
package madon |
117 | 8 |
|
9 |
import ( |
|
10 |
"encoding/json" |
|
11 |
"errors" |
|
12 |
"fmt" |
|
140 | 13 |
"net/url" |
117 | 14 |
"strings" |
15 |
||
140 | 16 |
"github.com/gorilla/websocket" |
117 | 17 |
) |
18 |
||
19 |
// StreamEvent contains a single event from the streaming API |
|
20 |
type StreamEvent struct { |
|
21 |
Event string // Name of the event (error, update, notification or delete) |
|
22 |
Data interface{} // Status, Notification or status ID |
|
23 |
Error error // Error message from the StreamListener |
|
24 |
} |
|
25 |
||
26 |
// openStream opens a stream URL and returns an http.Response |
|
27 |
// Note that the caller should close the connection when it's done reading |
|
28 |
// the stream. |
|
140 | 29 |
// The stream name can be "user", "local", "public" or "hashtag". |
30 |
// When it is "hashtag", the hashTag argument cannot be empty. |
|
31 |
func (mc *Client) openStream(streamName, hashTag string) (*websocket.Conn, error) { |
|
32 |
var tag string |
|
117 | 33 |
|
34 |
switch streamName { |
|
140 | 35 |
case "user", "public", "public:local": |
117 | 36 |
case "hashtag": |
37 |
if hashTag == "" { |
|
38 |
return nil, ErrInvalidParameter |
|
39 |
} |
|
140 | 40 |
tag = hashTag |
117 | 41 |
default: |
42 |
return nil, ErrInvalidParameter |
|
43 |
} |
|
44 |
||
140 | 45 |
if !strings.HasPrefix(mc.APIBase, "http") { |
46 |
return nil, errors.New("cannot create Websocket URL: unexpected API base URL") |
|
128
a5a00fad7a32
Add checks for client initialization
Mikael Berthe <mikael@lilotux.net>
parents:
122
diff
changeset
|
47 |
} |
a5a00fad7a32
Add checks for client initialization
Mikael Berthe <mikael@lilotux.net>
parents:
122
diff
changeset
|
48 |
|
140 | 49 |
// Build streaming websocket URL |
50 |
u, err := url.Parse("ws" + mc.APIBase[4:] + "/streaming/") |
|
117 | 51 |
if err != nil { |
140 | 52 |
return nil, errors.New("cannot create Websocket URL: " + err.Error()) |
117 | 53 |
} |
120 | 54 |
|
140 | 55 |
urlParams := url.Values{} |
56 |
urlParams.Add("stream", streamName) |
|
57 |
urlParams.Add("access_token", mc.UserToken.AccessToken) |
|
58 |
if tag != "" { |
|
59 |
urlParams.Add("tag", tag) |
|
117 | 60 |
} |
140 | 61 |
u.RawQuery = urlParams.Encode() |
62 |
||
63 |
c, _, err := websocket.DefaultDialer.Dial(u.String(), nil) |
|
64 |
return c, err |
|
117 | 65 |
} |
66 |
||
67 |
// readStream reads from the http.Response and sends events to the events channel |
|
122
50c7733ee886
Change StreamListener prototype
Mikael Berthe <mikael@lilotux.net>
parents:
120
diff
changeset
|
68 |
// It stops when the connection is closed or when the stopCh channel is closed. |
50c7733ee886
Change StreamListener prototype
Mikael Berthe <mikael@lilotux.net>
parents:
120
diff
changeset
|
69 |
// The foroutine will close the doneCh channel when it terminates. |
140 | 70 |
func (mc *Client) readStream(events chan<- StreamEvent, stopCh <-chan bool, doneCh chan bool, c *websocket.Conn) { |
71 |
defer c.Close() |
|
72 |
defer close(doneCh) |
|
117 | 73 |
|
140 | 74 |
go func() { |
117 | 75 |
select { |
76 |
case <-stopCh: |
|
140 | 77 |
// Close connection |
78 |
c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, "")) |
|
79 |
case <-doneCh: |
|
80 |
// Leave |
|
117 | 81 |
} |
140 | 82 |
}() |
117 | 83 |
|
140 | 84 |
for { |
85 |
var msg struct { |
|
86 |
Event string |
|
87 |
Payload interface{} |
|
117 | 88 |
} |
89 |
||
140 | 90 |
err := c.ReadJSON(&msg) |
91 |
if err != nil { |
|
92 |
if strings.Contains(err.Error(), "close 1000 (normal)") { |
|
93 |
break // Connection properly closed |
|
94 |
} |
|
95 |
e := fmt.Errorf("read error: %v", err) |
|
117 | 96 |
events <- StreamEvent{Event: "error", Error: e} |
140 | 97 |
break |
117 | 98 |
} |
99 |
||
100 |
var obj interface{} |
|
101 |
||
102 |
// Decode API object |
|
140 | 103 |
switch msg.Event { |
117 | 104 |
case "update": |
140 | 105 |
strPayload, ok := msg.Payload.(string) |
106 |
if !ok { |
|
107 |
e := fmt.Errorf("could not decode status: payload isn't a string") |
|
108 |
events <- StreamEvent{Event: "error", Error: e} |
|
109 |
continue |
|
110 |
} |
|
117 | 111 |
var s Status |
140 | 112 |
if err := json.Unmarshal([]byte(strPayload), &s); err != nil { |
113 |
e := fmt.Errorf("could not decode status: %v", err) |
|
117 | 114 |
events <- StreamEvent{Event: "error", Error: e} |
115 |
continue |
|
116 |
} |
|
117 |
obj = s |
|
118 |
case "notification": |
|
140 | 119 |
strPayload, ok := msg.Payload.(string) |
120 |
if !ok { |
|
121 |
e := fmt.Errorf("could not decode notification: payload isn't a string") |
|
122 |
events <- StreamEvent{Event: "error", Error: e} |
|
123 |
continue |
|
124 |
} |
|
117 | 125 |
var notif Notification |
140 | 126 |
if err := json.Unmarshal([]byte(strPayload), ¬if); err != nil { |
127 |
e := fmt.Errorf("could not decode notification: %v", err) |
|
117 | 128 |
events <- StreamEvent{Event: "error", Error: e} |
129 |
continue |
|
130 |
} |
|
131 |
obj = notif |
|
132 |
case "delete": |
|
140 | 133 |
floatPayload, ok := msg.Payload.(float64) |
134 |
if !ok { |
|
135 |
e := fmt.Errorf("could not decode deletion: payload isn't a number") |
|
117 | 136 |
events <- StreamEvent{Event: "error", Error: e} |
137 |
continue |
|
138 |
} |
|
140 | 139 |
obj = int(floatPayload) // statusID |
117 | 140 |
default: |
140 | 141 |
e := fmt.Errorf("unhandled event '%s'", msg.Event) |
117 | 142 |
events <- StreamEvent{Event: "error", Error: e} |
143 |
continue |
|
144 |
} |
|
145 |
||
146 |
// Send event to the channel |
|
140 | 147 |
events <- StreamEvent{Event: msg.Event, Data: obj} |
117 | 148 |
} |
149 |
} |
|
150 |
||
151 |
// StreamListener listens to a stream from the Mastodon server |
|
140 | 152 |
// The stream 'name' can be "user", "local", "public" or "hashtag". |
117 | 153 |
// For 'hashtag', the hashTag argument cannot be empty. |
154 |
// The events are sent to the events channel (the errors as well). |
|
122
50c7733ee886
Change StreamListener prototype
Mikael Berthe <mikael@lilotux.net>
parents:
120
diff
changeset
|
155 |
// The streaming is terminated if the 'stopCh' channel is closed. |
50c7733ee886
Change StreamListener prototype
Mikael Berthe <mikael@lilotux.net>
parents:
120
diff
changeset
|
156 |
// The 'doneCh' channel is closed if the connection is closed by the server. |
117 | 157 |
// Please note that this method launches a goroutine to listen to the events. |
140 | 158 |
func (mc *Client) StreamListener(name, hashTag string, events chan<- StreamEvent, stopCh <-chan bool, doneCh chan bool) error { |
138
23d3a518d0ad
Update package name in source files
Mikael Berthe <mikael@lilotux.net>
parents:
130
diff
changeset
|
159 |
if mc == nil { |
23d3a518d0ad
Update package name in source files
Mikael Berthe <mikael@lilotux.net>
parents:
130
diff
changeset
|
160 |
return ErrUninitializedClient |
128
a5a00fad7a32
Add checks for client initialization
Mikael Berthe <mikael@lilotux.net>
parents:
122
diff
changeset
|
161 |
} |
a5a00fad7a32
Add checks for client initialization
Mikael Berthe <mikael@lilotux.net>
parents:
122
diff
changeset
|
162 |
|
140 | 163 |
conn, err := mc.openStream(name, hashTag) |
117 | 164 |
if err != nil { |
165 |
return err |
|
166 |
} |
|
140 | 167 |
go mc.readStream(events, stopCh, doneCh, conn) |
117 | 168 |
return nil |
169 |
} |