Skip to content

Commit

Permalink
Merge pull request #1 from nyaruka/housekeeping
Browse files Browse the repository at this point in the history
Move utility methods and add tests
  • Loading branch information
nicpottier authored May 10, 2017
2 parents be753b0 + 0e50fcd commit f74d45e
Show file tree
Hide file tree
Showing 8 changed files with 93 additions and 59 deletions.
46 changes: 2 additions & 44 deletions handlers/base.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package handlers

import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
Expand All @@ -10,10 +9,10 @@ import (
"net/http"
"regexp"
"strings"
"unicode/utf8"

"github.com/gorilla/schema"
"github.com/nyaruka/courier"
"github.com/nyaruka/courier/utils"
validator "gopkg.in/go-playground/validator.v9"
)

Expand Down Expand Up @@ -58,28 +57,6 @@ func init() {
decoder.SetAliasTag("name")
}

func mapAsJSON(m map[string]string) []byte {
bytes, err := json.Marshal(m)
if err != nil {
panic(err)
}
return bytes
}

// JoinNonEmpty takes a vararg of strings and return the join of all the non-empty strings with a space between them
func JoinNonEmpty(delim string, strings ...string) string {
var buf bytes.Buffer
for _, s := range strings {
if s != "" {
if buf.Len() > 0 {
buf.WriteString(delim)
}
buf.WriteString(s)
}
}
return buf.String()
}

func NameFromFirstLastUsername(first string, last string, username string) string {
if first != "" && last != "" {
return fmt.Sprintf("%s %s", first, last)
Expand Down Expand Up @@ -174,7 +151,7 @@ func DecodePossibleBase64(original string) string {
return original
}

decoded := decodeUTF8(decodedBytes)
decoded := utils.DecodeUTF8(decodedBytes)
numASCIIChars := 0
for _, c := range decoded {
if c <= 127 {
Expand All @@ -188,22 +165,3 @@ func DecodePossibleBase64(original string) string {

return decoded
}

// decodeUTF8 is equivalent to .decode('utf-8', 'ignore') in Python
func decodeUTF8(bytes []byte) string {
s := string(bytes)
if !utf8.ValidString(s) {
v := make([]rune, 0, len(s))
for i, r := range s {
if r == utf8.RuneError {
_, size := utf8.DecodeRuneInString(s[i:])
if size == 1 {
continue
}
}
v = append(v, r)
}
s = string(v)
}
return s
}
7 changes: 4 additions & 3 deletions handlers/telegram/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"github.com/go-errors/errors"
"github.com/nyaruka/courier"
"github.com/nyaruka/courier/handlers"
"github.com/nyaruka/courier/utils"
)

func init() {
Expand Down Expand Up @@ -81,7 +82,7 @@ func (h *telegramHandler) ReceiveMessage(channel courier.Channel, w http.Respons
} else if te.Message.Document != nil {
mediaURL, err = resolveFileID(channel, te.Message.Document.FileID)
} else if te.Message.Venue != nil {
text = handlers.JoinNonEmpty(", ", te.Message.Venue.Title, te.Message.Venue.Address)
text = utils.JoinNonEmpty(", ", te.Message.Venue.Title, te.Message.Venue.Address)
mediaURL = fmt.Sprintf("geo:%f,%f", te.Message.Location.Latitude, te.Message.Location.Longitude)
} else if te.Message.Location != nil {
text = fmt.Sprintf("%f,%f", te.Message.Location.Latitude, te.Message.Location.Longitude)
Expand All @@ -91,7 +92,7 @@ func (h *telegramHandler) ReceiveMessage(channel courier.Channel, w http.Respons
if te.Message.Contact.PhoneNumber != "" {
phone = fmt.Sprintf("(%s)", te.Message.Contact.PhoneNumber)
}
text = handlers.JoinNonEmpty(" ", te.Message.Contact.FirstName, te.Message.Contact.LastName, phone)
text = utils.JoinNonEmpty(" ", te.Message.Contact.FirstName, te.Message.Contact.LastName, phone)
}

// we had an error downloading media
Expand Down Expand Up @@ -132,7 +133,7 @@ func resolveFileID(channel courier.Channel, fileID string) (string, error) {
return "", err
}

_, body, err := courier.MakeHTTPRequest(req)
_, body, err := utils.MakeHTTPRequest(req)
if err != nil {
return "", err
}
Expand Down
3 changes: 2 additions & 1 deletion msg.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
"net/http"
"net/url"

"github.com/nyaruka/courier/utils"
uuid "github.com/satori/go.uuid"
"gopkg.in/h2non/filetype.v1"
)
Expand Down Expand Up @@ -295,7 +296,7 @@ func downloadMediaToS3(s *server, msgUUID MsgUUID, mediaURL string) (string, err
if err != nil {
return "", err
}
resp, body, err := MakeHTTPRequest(req)
resp, body, err := utils.MakeHTTPRequest(req)
if err != nil {
return "", err
}
Expand Down
3 changes: 2 additions & 1 deletion server.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import (
"github.com/gorilla/mux"
"github.com/jmoiron/sqlx"
"github.com/nyaruka/courier/config"
"github.com/nyaruka/courier/utils"
)

type Server interface {
Expand Down Expand Up @@ -227,7 +228,7 @@ func (s *server) initializeChannelHandlers() {
// initialize handlers which are included/not-excluded in the config
for _, handler := range registeredHandlers {
channelType := string(handler.ChannelType())
if (includes == nil || stringArrayContains(includes, channelType)) && (excludes == nil || !stringArrayContains(excludes, channelType)) {
if (includes == nil || utils.StringArrayContains(includes, channelType)) && (excludes == nil || !utils.StringArrayContains(excludes, channelType)) {
err := handler.Initialize(s)
if err != nil {
log.Fatal(err)
Expand Down
9 changes: 0 additions & 9 deletions util.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,12 +60,3 @@ func WriteReceiveSuccess(w http.ResponseWriter, msg Msg) error {
func WriteStatusSuccess(w http.ResponseWriter, status MsgStatusUpdate) error {
return writeData(w, http.StatusOK, "Status Update Accepted", &statusData{status.Status()})
}

func stringArrayContains(s []string, e string) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
2 changes: 1 addition & 1 deletion http.go → utils/http.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package courier
package utils

import (
"fmt"
Expand Down
59 changes: 59 additions & 0 deletions utils/misc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package utils

import (
"bytes"
"encoding/json"
"unicode/utf8"
)

// MapAsJSON serializes the given map as a JSON string
func MapAsJSON(m map[string]string) []byte {
bytes, err := json.Marshal(m)
if err != nil {
panic(err)
}
return bytes
}

// JoinNonEmpty takes a vararg of strings and return the join of all the non-empty strings with a delimiter between them
func JoinNonEmpty(delim string, strings ...string) string {
var buf bytes.Buffer
for _, s := range strings {
if s != "" {
if buf.Len() > 0 {
buf.WriteString(delim)
}
buf.WriteString(s)
}
}
return buf.String()
}

// DecodeUTF8 is equivalent to .decode('utf-8', 'ignore') in Python
func DecodeUTF8(bytes []byte) string {
s := string(bytes)
if !utf8.ValidString(s) {
v := make([]rune, 0, len(s))
for i, r := range s {
if r == utf8.RuneError {
_, size := utf8.DecodeRuneInString(s[i:])
if size == 1 {
continue
}
}
v = append(v, r)
}
s = string(v)
}
return s
}

// StringArrayContains returns whether a given string array contains the given element
func StringArrayContains(s []string, e string) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
23 changes: 23 additions & 0 deletions utils/misc_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package utils

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestMapAsJSON(t *testing.T) {
assert.Equal(t, "{}", string(MapAsJSON(map[string]string{})))
assert.Equal(t, "{\"foo\":\"bar\"}", string(MapAsJSON(map[string]string{"foo": "bar"})))
}

func TestJoinNonEmpty(t *testing.T) {
assert.Equal(t, "", JoinNonEmpty(" "))
assert.Equal(t, "hello world", JoinNonEmpty(" ", "", "hello", "", "world"))
}

func TestStringArrayContains(t *testing.T) {
assert.False(t, StringArrayContains([]string{}, "x"))
assert.False(t, StringArrayContains([]string{"a", "b"}, "x"))
assert.True(t, StringArrayContains([]string{"a", "b", "x", "y"}, "x"))
}

0 comments on commit f74d45e

Please sign in to comment.