Browse Source

Able to send note

Piotr Czajkowski 3 years ago
parent
commit
c9877d44f7
3 changed files with 106 additions and 0 deletions
  1. 60 0
      bullet.go
  2. 17 0
      error.go
  3. 29 0
      push.go

+ 60 - 0
bullet.go

@@ -0,0 +1,60 @@
+package bullet
+
+import (
+	"encoding/json"
+	"io"
+	"net/http"
+)
+
+const (
+	shortTimeFormat = "2006-01-02 15:04"
+)
+
+type Bullet struct {
+	Token string
+}
+
+func (b Bullet) newRequest(body io.Reader) (*http.Request, error) {
+	request, err := http.NewRequest(http.MethodPost, "https://api.pushbullet.com/v2/pushes", body)
+	if err != nil {
+		return nil, err
+	}
+
+	request.Header.Add("Access-Token", b.Token)
+	request.Header.Add("Content-Type", "application/json")
+	return request, nil
+}
+
+//Send push note with given title and text
+func (b Bullet) SendNote(title, text string) error {
+	note := NewNotePush(title, text)
+	reader, errReader := note.GetReader()
+	if errReader != nil {
+		return errReader
+	}
+
+	request, errRequest := b.newRequest(reader)
+	if errRequest != nil {
+		return errRequest
+	}
+
+	client := http.Client{}
+	response, errResponse := client.Do(request)
+	if errResponse != nil {
+		return errResponse
+	}
+	defer response.Body.Close()
+
+	if response.StatusCode != http.StatusOK {
+		var errBullet BulletError
+		decoder := json.NewDecoder(response.Body)
+		errJSON := decoder.Decode(&errBullet)
+		if errJSON != nil {
+			return errJSON
+		}
+
+		return errBullet.GetError()
+	}
+
+	return nil
+}

+ 17 - 0
error.go

@@ -0,0 +1,17 @@
+package bullet
+
+import (
+	"fmt"
+)
+
+type BulletError struct {
+	Error struct {
+		Cat     string `json:"cat"`
+		Message string `json:"message"`
+		Type    string `json:"type"`
+	} `json:"error"`
+}
+
+func (be BulletError) GetError() error {
+	return fmt.Errorf("%s: %s", be.Error.Type, be.Error.Message)
+}

+ 29 - 0
push.go

@@ -0,0 +1,29 @@
+package bullet
+
+import (
+	"bytes"
+	"encoding/json"
+)
+
+type Push struct {
+	Type  string `json:"type"`
+	Title string `json:"title"`
+	Body  string `json:"body"`
+}
+
+//GetReader
+func (p Push) GetReader() (*bytes.Buffer, error) {
+	jsonBytes, err := json.Marshal(p)
+	if err != nil {
+		return nil, err
+	}
+
+	buffer := bytes.NewBuffer(jsonBytes)
+	return buffer, err
+}
+
+//NewNotePush
+func NewNotePush(title, text string) Push {
+	push := Push{Type: "note", Title: title, Body: text}
+	return push
+}