Skip to content

Commit

Permalink
Merge pull request #54 from pusher/pyjac-master
Browse files Browse the repository at this point in the history
Fixes #43 (originally by pyjac)
  • Loading branch information
kn100 committed May 31, 2019
2 parents 06f6d13 + 89524d6 commit 03a5e1a
Show file tree
Hide file tree
Showing 5 changed files with 45 additions and 79 deletions.
62 changes: 29 additions & 33 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (
"errors"
"fmt"
"net/http"
u "net/url"
"net/url"
"os"
"regexp"
"strings"
Expand Down Expand Up @@ -56,8 +56,8 @@ Clients can be instantiated from a specially-crafted Pusher URL. For example:
client := pusher.ClientFromURL("http://key:[email protected]/apps/app_id")
*/
func ClientFromURL(url string) (*Client, error) {
url2, err := u.Parse(url)
func ClientFromURL(serverURL string) (*Client, error) {
url2, err := url.Parse(serverURL)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -129,7 +129,7 @@ be marshallable into JSON.
client.Trigger("greeting_channel", "say_hello", data)
*/
func (c *Client) Trigger(channel string, eventName string, data interface{}) (*BufferedEvents, error) {
func (c *Client) Trigger(channel string, eventName string, data interface{}) error {
return c.trigger([]string{channel}, eventName, data, nil)
}

Expand All @@ -138,7 +138,7 @@ The same as `client.Trigger`, except one passes in a slice of `channels` as the
The maximum length of channels is 100.
client.TriggerMulti([]string{"a_channel", "another_channel"}, "event", data)
*/
func (c *Client) TriggerMulti(channels []string, eventName string, data interface{}) (*BufferedEvents, error) {
func (c *Client) TriggerMulti(channels []string, eventName string, data interface{}) error {
return c.trigger(channels, eventName, data, nil)
}

Expand All @@ -149,7 +149,7 @@ This method allow you to exclude a recipient whose connection has that
client.TriggerExclusive("a_channel", "event", data, "123.12")
*/
func (c *Client) TriggerExclusive(channel string, eventName string, data interface{}, socketID string) (*BufferedEvents, error) {
func (c *Client) TriggerExclusive(channel string, eventName string, data interface{}, socketID string) error {
return c.trigger([]string{channel}, eventName, data, &socketID)
}

Expand All @@ -159,47 +159,46 @@ Excluding a recipient on a trigger to multiple channels.
client.TriggerMultiExclusive([]string{"a_channel", "another_channel"}, "event", data, "123.12")
*/
func (c *Client) TriggerMultiExclusive(channels []string, eventName string, data interface{}, socketID string) (*BufferedEvents, error) {
func (c *Client) TriggerMultiExclusive(channels []string, eventName string, data interface{}, socketID string) error {
return c.trigger(channels, eventName, data, &socketID)
}

func (c *Client) trigger(channels []string, eventName string, data interface{}, socketID *string) (*BufferedEvents, error) {
func (c *Client) trigger(channels []string, eventName string, data interface{}, socketID *string) error {
hasEncryptedChannel := false
for _, channel := range channels {
if isEncryptedChannel(channel) {
hasEncryptedChannel = true
}
}
if len(channels) > maxTriggerableChannels {
return nil, fmt.Errorf("You cannot trigger on more than %d channels at once", maxTriggerableChannels)
return fmt.Errorf("You cannot trigger on more than %d channels at once", maxTriggerableChannels)
}
if hasEncryptedChannel && len(channels) > 1 {
// For rationale, see limitations of end-to-end encryption in the README
return nil, errors.New("You cannot trigger to multiple channels when using encrypted channels")
return errors.New("You cannot trigger to multiple channels when using encrypted channels")

}
if !channelsAreValid(channels) {
return nil, errors.New("At least one of your channels' names are invalid")
return errors.New("At least one of your channels' names are invalid")
}
if hasEncryptedChannel && !validEncryptionKey(c.EncryptionMasterKey) {
return nil, errors.New("Your encryptionMasterKey is not of the correct format")
return errors.New("Your encryptionMasterKey is not of the correct format")
}
if err := validateSocketID(socketID); err != nil {
return nil, err
return err
}
payload, err := encodeTriggerBody(channels, eventName, data, socketID, c.EncryptionMasterKey)
if err != nil {
return nil, err
return err
}
path := fmt.Sprintf("/apps/%s/events", c.AppId)
u, err := createRequestURL("POST", c.Host, path, c.Key, c.Secret, authTimestamp(), c.Secure, payload, nil, c.Cluster)
triggerURL, err := createRequestURL("POST", c.Host, path, c.Key, c.Secret, authTimestamp(), c.Secure, payload, nil, c.Cluster)
if err != nil {
return nil, err
}
response, err := c.request("POST", u, payload)
if err != nil {
return nil, err
return err
}
return unmarshalledBufferedEvents(response)
_, err = c.request("POST", triggerURL, payload)

return err
}

type Event struct {
Expand All @@ -215,15 +214,15 @@ type Event struct {
{ Channel: "private-encrypted-secretdonut", Name: "ev2", Data: "pippo2" },
})
*/
func (c *Client) TriggerBatch(batch []Event) (*BufferedEvents, error) {
func (c *Client) TriggerBatch(batch []Event) error {
hasEncryptedChannel := false
// validate every channel name and every sockedID (if present) in batch
for _, event := range batch {
if !validChannel(event.Channel) {
return nil, fmt.Errorf("The channel named %s has a non-valid name", event.Channel)
return fmt.Errorf("The channel named %s has a non-valid name", event.Channel)
}
if err := validateSocketID(event.SocketId); err != nil {
return nil, err
return err
}
if isEncryptedChannel(event.Channel) {
hasEncryptedChannel = true
Expand All @@ -232,23 +231,20 @@ func (c *Client) TriggerBatch(batch []Event) (*BufferedEvents, error) {
if hasEncryptedChannel {
// validate EncryptionMasterKey
if !validEncryptionKey(c.EncryptionMasterKey) {
return nil, errors.New("Your encryptionMasterKey is not of the correct format")
return errors.New("Your encryptionMasterKey is not of the correct format")
}
}
payload, err := encodeTriggerBatchBody(batch, c.EncryptionMasterKey)
if err != nil {
return nil, err
return err
}
path := fmt.Sprintf("/apps/%s/batch_events", c.AppId)
u, err := createRequestURL("POST", c.Host, path, c.Key, c.Secret, authTimestamp(), c.Secure, payload, nil, c.Cluster)
if err != nil {
return nil, err
}
response, err := c.request("POST", u, payload)
triggerURL, err := createRequestURL("POST", c.Host, path, c.Key, c.Secret, authTimestamp(), c.Secure, payload, nil, c.Cluster)
if err != nil {
return nil, err
return err
}
return unmarshalledBufferedEvents(response)
_, err = c.request("POST", triggerURL, payload)
return err
}

/*
Expand Down
32 changes: 15 additions & 17 deletions client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,7 @@ func TestTriggerSuccessCase(t *testing.T) {

u, _ := url.Parse(server.URL)
client := Client{AppId: "id", Key: "key", Secret: "secret", Host: u.Host}
_, err := client.Trigger("test_channel", "test", "yolo")

err := client.Trigger("test_channel", "test", "yolo")
assert.NoError(t, err)
}

Expand Down Expand Up @@ -123,7 +122,7 @@ func TestTriggerWithSocketId(t *testing.T) {

func TestTriggerSocketIdValidation(t *testing.T) {
client := Client{AppId: "id", Key: "key", Secret: "secret"}
_, err := client.TriggerExclusive("test_channel", "test", "yolo", "1234.12:lalala")
err := client.TriggerExclusive("test_channel", "test", "yolo", "1234.12:lalala")
assert.Error(t, err)
}

Expand All @@ -144,7 +143,7 @@ func TestTriggerBatchSuccess(t *testing.T) {

u, _ := url.Parse(server.URL)
client := Client{AppId: "appid", Key: "key", Secret: "secret", Host: u.Host}
_, err := client.TriggerBatch([]Event{
err := client.TriggerBatch([]Event{
{"test_channel", "test", "yolo1", nil},
{"test_channel", "test", "yolo2", nil},
})
Expand All @@ -166,10 +165,9 @@ func TestTriggerBatchWithEncryptionMasterKeyNoEncryptedChanSuccess(t *testing.T)
assert.NoError(t, err)
}))
defer server.Close()

u, _ := url.Parse(server.URL)
client := Client{AppId: "appid", Key: "key", Secret: "secret", EncryptionMasterKey: "eHPVWHg7nFGYVBsKjOFDXWRribIR2b0b", Host: u.Host}
_, err := client.TriggerBatch([]Event{
err := client.TriggerBatch([]Event{
{"test_channel", "test", "yolo1", nil},
{"test_channel", "test", "yolo2", nil},
})
Expand All @@ -194,7 +192,7 @@ func TestTriggerBatchNoEncryptionMasterKeyWithEncryptedChanFailure(t *testing.T)

u, _ := url.Parse(server.URL)
client := Client{AppId: "appid", Key: "key", Secret: "secret", Host: u.Host}
_, err := client.TriggerBatch([]Event{
err := client.TriggerBatch([]Event{
{"test_channel", "test", "yolo1", nil},
{"private-encrypted-test_channel", "test", "yolo2", nil},
})
Expand All @@ -218,7 +216,7 @@ func TestTriggerBatchWithEncryptedChanSuccess(t *testing.T) {

u, _ := url.Parse(server.URL)
client := Client{AppId: "appid", Key: "key", Secret: "secret", EncryptionMasterKey: "eHPVWHg7nFGYVBsKjOFDXWRribIR2b0b", Host: u.Host}
_, err := client.TriggerBatch([]Event{
err := client.TriggerBatch([]Event{
{"test_channel", "test", "yolo1", nil},
{"private-encrypted-test_channel", "test", "yolo2", nil},
})
Expand Down Expand Up @@ -253,7 +251,8 @@ func TestRequestTimeouts(t *testing.T) {

u, _ := url.Parse(server.URL)
client := Client{AppId: "id", Key: "key", Secret: "secret", Host: u.Host, HttpClient: &http.Client{Timeout: time.Millisecond * 100}}
_, err := client.Trigger("test_channel", "test", "yolo")

err := client.Trigger("test_channel", "test", "yolo")

assert.Error(t, err)
}
Expand All @@ -273,10 +272,9 @@ func TestChannelLengthValidation(t *testing.T) {
}

client := Client{AppId: "id", Key: "key", Secret: "secret"}
res, err := client.TriggerMulti(channels, "yolo", "woot")
err := client.TriggerMulti(channels, "yolo", "woot")

assert.EqualError(t, err, "You cannot trigger on more than 100 channels at once")
assert.Nil(t, res)
}

func TestChannelFormatValidation(t *testing.T) {
Expand All @@ -286,13 +284,13 @@ func TestChannelFormatValidation(t *testing.T) {
channel2 += "a"
}
client := Client{AppId: "id", Key: "key", Secret: "secret"}
res1, err1 := client.Trigger(channel1, "yolo", "w00t")
res2, err2 := client.Trigger(channel2, "yolo", "not 19 forever")
err1 := client.Trigger(channel1, "yolo", "w00t")

err2 := client.Trigger(channel2, "yolo", "not 19 forever")

assert.EqualError(t, err1, "At least one of your channels' names are invalid")
assert.Nil(t, res1)

assert.EqualError(t, err2, "At least one of your channels' names are invalid")
assert.Nil(t, res2)

}

Expand All @@ -302,9 +300,9 @@ func TestDataSizeValidation(t *testing.T) {
for i := 0; i <= 10242; i++ {
data += "a"
}
res, err := client.Trigger("channel", "event", data)
err := client.Trigger("channel", "event", data)

assert.EqualError(t, err, "Data must be smaller than 10kb")
assert.Nil(t, res)

}

Expand Down
6 changes: 1 addition & 5 deletions encoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,6 @@ type eventPayload struct {
SocketId *string `json:"socket_id,omitempty"`
}

type BufferedEvents struct {
EventIds map[string]string `json:"event_ids,omitempty"`
}

func encodeTriggerBody(channels []string, event string, data interface{}, socketID *string, encryptionKey string) ([]byte, error) {
dataBytes, err := encodeEventData(data)
if err != nil {
Expand All @@ -53,7 +49,7 @@ func encodeTriggerBody(channels []string, event string, data interface{}, socket
}

func encodeTriggerBatchBody(batch []Event, encryptionKey string) ([]byte, error) {
batchEvents := make([]batchEvent, len(batch))
batchEvents := make([]batchEvent, len(batch))
for idx, e := range batch {
var stringifyedDataBytes string
dataBytes, err := encodeEventData(e.Data)
Expand Down
11 changes: 0 additions & 11 deletions response_parsing.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,14 +72,3 @@ func unmarshalledChannelUsers(response []byte) (*Users, error) {

return users, nil
}

func unmarshalledBufferedEvents(response []byte) (*BufferedEvents, error) {
bufferedEvents := &BufferedEvents{}
err := json.Unmarshal(response, &bufferedEvents)

if err != nil {
return nil, err
}

return bufferedEvents, nil
}
13 changes: 0 additions & 13 deletions response_parsing_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,19 +46,6 @@ func TestParsingChannelUsers(t *testing.T) {

}

func TestParsingTriggerResult(t *testing.T) {
testJSON := []byte("{\"event_ids\":{\"test_channel\":\"eudhq17zrhfc4f\",\"another_channel\":\"eudhq17zrhfc74\"}}")
expected := &BufferedEvents{
EventIds: map[string]string{
"test_channel": "eudhq17zrhfc4f",
"another_channel": "eudhq17zrhfc74",
},
}
result, err := unmarshalledBufferedEvents(testJSON)
assert.Equal(t, expected, result)
assert.NoError(t, err)
}

func TestParserError(t *testing.T) {
testJSON := []byte("[];;[[p{{}}{{{}[][][]@£$@")
_, err := unmarshalledChannelsList(testJSON)
Expand Down

0 comments on commit 03a5e1a

Please sign in to comment.