-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Signed-off-by: Ales Verbic <verbotenj@gmail.com>
- Loading branch information
Showing
13 changed files
with
713 additions
and
77 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,99 @@ | ||
package fcm | ||
|
||
import ( | ||
"bytes" | ||
"encoding/json" | ||
"errors" | ||
"fmt" | ||
"io" | ||
"net/http" | ||
|
||
"github.com/blinklabs-io/snek/internal/logging" | ||
) | ||
|
||
type Message struct { | ||
MessageContent `json:"message"` | ||
} | ||
|
||
type MessageContent struct { | ||
Token string `json:"token"` | ||
Notification *NotificationContent `json:"notification,omitempty"` | ||
Data map[string]interface{} `json:"data,omitempty"` | ||
} | ||
|
||
type NotificationContent struct { | ||
Title string `json:"title"` | ||
Body string `json:"body"` | ||
} | ||
|
||
type MessageOption func(*MessageContent) | ||
|
||
func WithData(data map[string]interface{}) MessageOption { | ||
return func(m *MessageContent) { | ||
m.Data = data | ||
} | ||
} | ||
|
||
func WithNotification(title string, body string) MessageOption { | ||
return func(m *MessageContent) { | ||
m.Notification = &NotificationContent{ | ||
Title: title, | ||
Body: body, | ||
} | ||
} | ||
} | ||
|
||
func NewMessage(token string, opts ...MessageOption) *Message { | ||
if token == "" { | ||
logging.GetLogger().Fatalf("Token is mandatory for FCM message") | ||
} | ||
|
||
msg := &Message{ | ||
MessageContent: MessageContent{ | ||
Token: token, | ||
}, | ||
} | ||
for _, opt := range opts { | ||
opt(&msg.MessageContent) | ||
} | ||
return msg | ||
} | ||
|
||
func Send(accessToken string, projectId string, msg *Message) error { | ||
|
||
fcmEndpoint := fmt.Sprintf("https://fcm.googleapis.com/v1/projects/%s/messages:send", projectId) | ||
|
||
// Convert the message to JSON | ||
payload, err := json.Marshal(msg) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
fmt.Println(string(payload)) | ||
|
||
// Create a new HTTP request | ||
req, err := http.NewRequest("POST", fcmEndpoint, bytes.NewBuffer(payload)) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
// Set headers | ||
req.Header.Set("Authorization", "Bearer "+accessToken) | ||
req.Header.Set("Content-Type", "application/json") | ||
|
||
// Execute the request | ||
client := &http.Client{} | ||
resp, err := client.Do(req) | ||
if err != nil { | ||
return err | ||
} | ||
defer resp.Body.Close() | ||
|
||
// Check for errors in the response | ||
if resp.StatusCode != http.StatusOK { | ||
body, _ := io.ReadAll(resp.Body) | ||
return errors.New(string(body)) | ||
} | ||
|
||
return nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
// Copyright 2023 Blink Labs, LLC. | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
|
||
package push | ||
|
||
import ( | ||
"github.com/blinklabs-io/snek/api" | ||
) | ||
|
||
func (p *PushOutput) RegisterRoutes() { | ||
apiInstance := api.GetInstance() | ||
|
||
apiInstance.AddRoute("POST", "/fcm", storeFCMToken) | ||
apiInstance.AddRoute("POST", "/fcm/", storeFCMToken) | ||
|
||
apiInstance.AddRoute("GET", "/fcm/:token", readFCMToken) | ||
apiInstance.AddRoute("GET", "/fcm/:token/", readFCMToken) | ||
|
||
apiInstance.AddRoute("DELETE", "/fcm/:token", deleteFCMToken) | ||
apiInstance.AddRoute("DELETE", "/fcm/:token/", deleteFCMToken) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,130 @@ | ||
package push_test | ||
|
||
import ( | ||
"net/http" | ||
"net/http/httptest" | ||
"strings" | ||
"testing" | ||
|
||
"github.com/blinklabs-io/snek/api" | ||
"github.com/blinklabs-io/snek/output/push" | ||
"github.com/gin-gonic/gin" | ||
"github.com/stretchr/testify/assert" | ||
) | ||
|
||
func setupRouter() *gin.Engine { | ||
apiInstance := api.New(false) | ||
p := &push.PushOutput{} | ||
p.RegisterRoutes() // This will internally get the API instance and register the routes for push | ||
return apiInstance.Engine() | ||
} | ||
|
||
func TestStoreFCMToken(t *testing.T) { | ||
router := setupRouter() | ||
|
||
t.Run("Valid JSON input", func(t *testing.T) { | ||
jsonStr := `{"FCMToken": "abcd1234"}` | ||
req, _ := http.NewRequest("POST", "/fcm", strings.NewReader(jsonStr)) | ||
req.Header.Set("Content-Type", "application/json") | ||
w := httptest.NewRecorder() | ||
router.ServeHTTP(w, req) | ||
|
||
assert.Equal(t, http.StatusCreated, w.Code) | ||
|
||
tokens := push.GetFcmTokens() | ||
assert.Contains(t, tokens, "abcd1234") | ||
}) | ||
|
||
t.Run("Store 2 tokens JSON input", func(t *testing.T) { | ||
jsonStr := `{"FCMToken": "abcd1234"}` | ||
req, _ := http.NewRequest("POST", "/fcm", strings.NewReader(jsonStr)) | ||
req.Header.Set("Content-Type", "application/json") | ||
w := httptest.NewRecorder() | ||
router.ServeHTTP(w, req) | ||
|
||
assert.Equal(t, http.StatusCreated, w.Code) | ||
|
||
tokens := push.GetFcmTokens() | ||
assert.Contains(t, tokens, "abcd1234") | ||
|
||
jsonStr = `{"FCMToken": "abcd0000"}` | ||
req, _ = http.NewRequest("POST", "/fcm", strings.NewReader(jsonStr)) | ||
req.Header.Set("Content-Type", "application/json") | ||
w = httptest.NewRecorder() | ||
router.ServeHTTP(w, req) | ||
|
||
assert.Equal(t, http.StatusCreated, w.Code) | ||
|
||
tokens = push.GetFcmTokens() | ||
assert.Contains(t, tokens, "abcd0000") | ||
}) | ||
|
||
t.Run("Invalid JSON input", func(t *testing.T) { | ||
jsonStr := `{"invalid_field": "abcd1234"}` | ||
req, _ := http.NewRequest("POST", "/fcm", strings.NewReader(jsonStr)) | ||
req.Header.Set("Content-Type", "application/json") | ||
w := httptest.NewRecorder() | ||
router.ServeHTTP(w, req) | ||
|
||
assert.Equal(t, http.StatusBadRequest, w.Code) | ||
}) | ||
} | ||
|
||
func TestReadFCMToken(t *testing.T) { | ||
router := setupRouter() | ||
|
||
// Prepopulate the FCMTokens map for the read test | ||
push.GetFcmTokens()["abcd1234"] = "abcd1234" | ||
|
||
t.Run("Token exists", func(t *testing.T) { | ||
req, _ := http.NewRequest("GET", "/fcm/abcd1234", nil) | ||
w := httptest.NewRecorder() | ||
router.ServeHTTP(w, req) | ||
|
||
assert.Equal(t, http.StatusOK, w.Code) | ||
assert.Contains(t, w.Body.String(), "abcd1234") | ||
}) | ||
|
||
t.Run("Token does not exist", func(t *testing.T) { | ||
req, _ := http.NewRequest("GET", "/fcm/nonexistenttoken", nil) | ||
w := httptest.NewRecorder() | ||
router.ServeHTTP(w, req) | ||
|
||
assert.Equal(t, http.StatusNotFound, w.Code) | ||
}) | ||
} | ||
|
||
func TestDeleteFCMToken(t *testing.T) { | ||
router := setupRouter() | ||
|
||
// Prepopulate the FCMTokens map for the delete test | ||
push.GetFcmTokens()["abcd1234"] = "abcd1234" | ||
|
||
t.Run("Token exists and is deleted", func(t *testing.T) { | ||
req, _ := http.NewRequest("DELETE", "/fcm/abcd1234", nil) | ||
w := httptest.NewRecorder() | ||
router.ServeHTTP(w, req) | ||
|
||
assert.Equal(t, http.StatusNoContent, w.Code) | ||
|
||
tokens := push.GetFcmTokens() | ||
_, exists := tokens["abcd1234"] | ||
assert.False(t, exists, "Token should be deleted") | ||
}) | ||
|
||
t.Run("Token does not exist", func(t *testing.T) { | ||
req, _ := http.NewRequest("DELETE", "/fcm/nonexistenttoken", nil) | ||
w := httptest.NewRecorder() | ||
router.ServeHTTP(w, req) | ||
|
||
assert.Equal(t, http.StatusNotFound, w.Code) | ||
}) | ||
|
||
t.Run("Deleting already deleted token", func(t *testing.T) { | ||
req, _ := http.NewRequest("DELETE", "/fcm/abcd1234", nil) | ||
w := httptest.NewRecorder() | ||
router.ServeHTTP(w, req) | ||
|
||
assert.Equal(t, http.StatusNotFound, w.Code) | ||
}) | ||
} |
Oops, something went wrong.