feat: add bark encrypt message
This commit is contained in:
+56
-2
@@ -2,6 +2,9 @@ package message
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -22,10 +25,11 @@ type Bark struct {
|
||||
Icon string
|
||||
Level string
|
||||
URL string
|
||||
Key string
|
||||
IV string
|
||||
}
|
||||
|
||||
func (b *Bark) Request(title, content string) ([]byte, error) {
|
||||
url := b.getURL()
|
||||
data := map[string]interface{}{
|
||||
"title": title,
|
||||
"body": content,
|
||||
@@ -49,7 +53,34 @@ func (b *Bark) Request(title, content string) ([]byte, error) {
|
||||
data["url"] = b.URL
|
||||
}
|
||||
|
||||
jsonData, err := json.Marshal(data)
|
||||
var postData interface{}
|
||||
url := b.getURL()
|
||||
|
||||
if b.Key != "" && b.IV != "" {
|
||||
// Use encryption
|
||||
jsonData, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ciphertext, err := b.encryptPayload(string(jsonData))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("encryption failed: %v", err)
|
||||
}
|
||||
postData = map[string]interface{}{
|
||||
"ciphertext": ciphertext,
|
||||
"device_key": b.PushKey,
|
||||
"sound": b.Sound,
|
||||
}
|
||||
// When using encryption, use the push endpoint if PushKey is just a key
|
||||
if !strings.HasPrefix(b.PushKey, "http") {
|
||||
url = "https://api.day.app/push"
|
||||
}
|
||||
} else {
|
||||
// Normal request
|
||||
postData = data
|
||||
}
|
||||
|
||||
jsonData, err := json.Marshal(postData)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -84,3 +115,26 @@ func (b *Bark) getURL() string {
|
||||
}
|
||||
return fmt.Sprintf("https://api.day.app/%s", pushKey)
|
||||
}
|
||||
|
||||
func (b *Bark) encryptPayload(payload string) (string, error) {
|
||||
key := []byte(b.Key)
|
||||
iv := []byte(b.IV)
|
||||
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
paddedPayload := b.pkcs7Pad([]byte(payload), aes.BlockSize)
|
||||
mode := cipher.NewCBCEncrypter(block, iv)
|
||||
ciphertext := make([]byte, len(paddedPayload))
|
||||
mode.CryptBlocks(ciphertext, paddedPayload)
|
||||
|
||||
return base64.StdEncoding.EncodeToString(ciphertext), nil
|
||||
}
|
||||
|
||||
func (b *Bark) pkcs7Pad(data []byte, blockSize int) []byte {
|
||||
padding := blockSize - len(data)%blockSize
|
||||
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
|
||||
return append(data, padtext...)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user