Files
Sebastian UnterschützandClaude Opus 5.5 d58e3e2653
ci / lint (pull_request) Successful in 6m32s
ci / image (pull_request) Successful in 6m29s
ci / build (pull_request) Successful in 11m31s
ci / test (pull_request) Successful in 12m59s
chore(lint): re-enable staticcheck and unused
golangci-lint v2.15.0 ships a honnef.co/go/tools that analyzes the Go 1.27
standard library without panicking. Fix what they found: dead helpers, an
unused constant, error strings starting with a product name, the usage
error, and two negations simplified by De Morgan.

Closes #43

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-23 07:12:20 +01:00

414 lines
20 KiB
Go

package notify
import (
"context"
"crypto/hmac"
"crypto/sha1" //nolint:gosec // Alibaba Cloud's API signature is HMAC-SHA1
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"sort"
"strings"
"time"
"github.com/google/uuid"
)
// SMS gateways and phone calls. Messages are cut to what several SMS
// parts hold.
func (m Message) sms() string { return truncate(m.text(), 600) }
// ascii drops characters GSM gateways without Unicode support reject.
func ascii(s string) string {
return strings.Map(func(r rune) rune {
if r > 127 {
return -1
}
return r
}, s)
}
func senderField(required bool) Field { return text("sender", required) }
var smsProviders = []Provider{
{Type: "elks46", Group: "sms", Fields: []Field{text("username", true), secret("auth_token", true), senderField(true), text("phone_number", true)},
send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
_, err := c.form(ctx, "https://api.46elks.com/a1/sms", basic(cfg["username"], cfg["auth_token"]),
url.Values{"from": {cfg["sender"]}, "to": {cfg["phone_number"]}, "message": {m.sms()}})
return err
}},
{Type: "aliyunsms", Group: "sms", Fields: []Field{
text("access_key_id", true), secret("access_key_secret", true), text("sign_name", true), text("template_code", true), text("phone_number", true),
}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
// The template receives name, time, status and msg.
param, _ := json.Marshal(map[string]string{
"name": m.Monitor, "time": time.Now().UTC().Format(time.DateTime), "status": strings.ToUpper(m.status()), "msg": truncate(m.Body, 100),
})
v := url.Values{
"PhoneNumbers": {cfg["phone_number"]}, "TemplateCode": {cfg["template_code"]}, "SignName": {cfg["sign_name"]},
"TemplateParam": {string(param)}, "AccessKeyId": {cfg["access_key_id"]}, "Format": {"JSON"},
"SignatureMethod": {"HMAC-SHA1"}, "SignatureVersion": {"1.0"}, "SignatureNonce": {uuid.NewString()},
"Timestamp": {time.Now().UTC().Format("2006-01-02T15:04:05Z")}, "Action": {"SendSms"}, "Version": {"2017-05-25"},
}
v.Set("Signature", aliyunSign(v, cfg["access_key_secret"]))
reply, err := c.form(ctx, "https://dysmsapi.aliyuncs.com/", nil, v)
return replyCheck(reply, err, func(r map[string]any) string {
if str(r["Code"]) != "OK" {
return "Alibaba Cloud SMS: " + str(r["Message"])
}
return ""
})
}},
{Type: "amootsms", Group: "sms", Fields: []Field{secret("api_token", true), text("line_number", true), text("phone_numbers", true)},
send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
reply, err := c.form(ctx, "https://portal.amootsms.com/rest/SendSimple", http.Header{"Authorization": {cfg["api_token"]}}, url.Values{
"SendDateTime": {time.Now().In(tehran()).Format(time.DateTime)}, "SMSMessageText": {m.sms()},
"LineNumber": {cfg["line_number"]}, "Mobiles": {strings.Join(list(cfg["phone_numbers"]), ",")},
})
return replyCheck(reply, err, func(v map[string]any) string {
if s := str(v["Status"]); s != "" && s != "Success" {
return "Amoot SMS: " + s + " " + str(v["ErrorMessage"])
}
return ""
})
}},
{Type: "bearsms", Group: "sms", Fields: []Field{text("username", true), secret("hash_key", true), text("phone_number", true), senderField(false)},
send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
msg := m.sms()
q := url.Values{"app": {"ws"}, "u": {cfg["username"]}, "h": {cfg["hash_key"]}, "op": {"pv"}, "to": {cfg["phone_number"]}, "msg": {msg}}
if cfg["sender"] != "" {
q.Set("from", cfg["sender"])
}
if ascii(msg) != msg {
q.Set("unicode", "1")
}
reply, err := c.get(ctx, "https://app.bearsms.com/index.php", nil, q)
return replyCheck(reply, err, func(v map[string]any) string {
if str(v["status"]) == "ERR" || str(v["error_string"]) != "" {
return "BearSMS: " + or(str(v["error_string"]), "failed")
}
return ""
})
}},
{Type: "cellsynt", Group: "sms", Fields: []Field{
text("username", true), secret("password", true), text("phone_number", true),
{Name: "originator_type", Kind: "select", Options: []string{"alpha", "numeric"}, Default: "alpha"}, senderField(true),
}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
q := url.Values{
"username": {cfg["username"]}, "password": {cfg["password"]}, "destination": {cfg["phone_number"]},
"text": {ascii(m.sms())}, "originatortype": {or(cfg["originator_type"], "alpha")}, "originator": {cfg["sender"]}, "allowconcat": {"6"},
}
reply, err := c.call(ctx, http.MethodPost, "https://se-1.cellsynt.net/sms.php?"+q.Encode(), nil, nil)
if err == nil && strings.Contains(string(reply), "Error:") {
return errors.New("Cellsynt: " + strings.TrimSpace(strings.ReplaceAll(string(reply), "Error:", "")))
}
return err
}},
{Type: "clicksend", Group: "sms", Fields: []Field{text("username", true), secret("api_key", true), text("phone_number", true), senderField(false)},
send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
reply, err := c.callJSON(ctx, http.MethodPost, "https://rest.clicksend.com/v3/sms/send", basic(cfg["username"], cfg["api_key"]), map[string]any{
"messages": []map[string]any{{"body": ascii(m.sms()), "to": cfg["phone_number"], "source": "uptimesebi", "from": cfg["sender"]}},
})
return replyCheck(reply, err, func(v map[string]any) string {
data, _ := v["data"].(map[string]any)
msgs, _ := data["messages"].([]any)
if len(msgs) > 0 {
if st := str(msgs[0].(map[string]any)["status"]); st != "SUCCESS" {
return "ClickSend: " + st
}
}
return ""
})
}},
{Type: "egosms", Group: "sms", Fields: []Field{text("username", true), secret("password", true), text("phone_number", true), senderField(false)},
send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
_, err := c.get(ctx, "https://www.egosms.co/api/v1/plain/", nil, url.Values{
"number": {cfg["phone_number"]}, "message": {m.sms()}, "username": {cfg["username"]},
"password": {cfg["password"]}, "sender": {or(cfg["sender"], "EGOSMS")}, "priority": {"0"},
})
return err
}},
{Type: "freemobile", Group: "sms", Fields: []Field{text("username", true), secret("password", true)},
send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
// Free Mobile texts the account's own number.
return c.json(ctx, http.MethodPost, "https://smsapi.free-mobile.fr/sendmsg?msg="+url.QueryEscape(m.sms()), nil,
map[string]any{"user": cfg["username"], "pass": cfg["password"]})
}},
{Type: "gtxmessaging", Group: "sms", Fields: []Field{secret("api_key", true), senderField(true), text("phone_number", true)},
send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
_, err := c.form(ctx, "https://rest.gtx-messaging.net/smsc/sendsms/"+url.PathEscape(cfg["api_key"])+"/json", nil,
url.Values{"from": {cfg["sender"]}, "to": {cfg["phone_number"]}, "text": {m.sms()}})
return err
}},
{Type: "octopush", Group: "sms", Fields: []Field{
text("username", true), secret("api_key", true), text("phone_number", true),
{Name: "sms_type", Kind: "select", Options: []string{"sms_premium", "sms_low_cost"}, Default: "sms_premium"}, senderField(false),
}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
h := http.Header{"api-key": {cfg["api_key"]}, "api-login": {cfg["username"]}}
return c.json(ctx, http.MethodPost, "https://api.octopush.com/v1/public/sms-campaign/send", h, map[string]any{
"recipients": []map[string]any{{"phone_number": cfg["phone_number"]}}, "text": ascii(m.sms()),
"type": or(cfg["sms_type"], "sms_premium"), "purpose": "alert", "sender": cfg["sender"],
})
}},
{Type: "ooredoo", Group: "sms", Fields: []Field{
text("username", true), secret("access_key", true), secret("api_token", true), text("phone_numbers", true),
urlField("api_url", false, "https://o-papi1-lb01.ooredoo.mv/bulk_sms/v2"),
}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
numbers := list(strings.ReplaceAll(cfg["phone_numbers"], " ", ","))
for i := 0; i < len(numbers); i += 20 {
reply, err := c.form(ctx, or(cfg["api_url"], "https://o-papi1-lb01.ooredoo.mv/bulk_sms/v2"), bearer(cfg["api_token"]), url.Values{
"username": {cfg["username"]}, "access_key": {base64.StdEncoding.EncodeToString([]byte(cfg["access_key"]))},
"message": {m.sms()}, "batch": {strings.Join(numbers[i:min(i+20, len(numbers))], " ")},
})
if err := replyCheck(reply, err, func(v map[string]any) string {
if str(v["response_code"]) != "0" {
return "Ooredoo: " + or(str(v["response_message"]), "rejected")
}
return ""
}); err != nil {
return err
}
}
return nil
}},
{Type: "plivo", Group: "sms", Fields: []Field{
text("auth_id", true), secret("auth_token", true), senderField(true), text("phone_number", true),
{Name: "message_type", Kind: "select", Options: []string{"sms", "call"}, Default: "sms"}, urlField("answer_url", false, ""),
}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
base := "https://api.plivo.com/v1/Account/" + url.PathEscape(cfg["auth_id"])
h := basic(cfg["auth_id"], cfg["auth_token"])
if cfg["message_type"] == "call" {
// The answer URL returns Plivo XML that reads the message out.
answer, err := url.Parse(cfg["answer_url"])
if err != nil || cfg["answer_url"] == "" {
return errors.New("calls need an answer URL")
}
q := answer.Query()
q.Set("message", m.Title)
answer.RawQuery = q.Encode()
return c.json(ctx, http.MethodPost, base+"/Call/", h, map[string]any{
"from": cfg["sender"], "to": cfg["phone_number"], "answer_url": answer.String(), "answer_method": "GET",
})
}
return c.json(ctx, http.MethodPost, base+"/Message/", h, map[string]any{"src": cfg["sender"], "dst": cfg["phone_number"], "text": m.sms()})
}},
{Type: "promosms", Group: "sms", Fields: []Field{
text("username", true), secret("password", true), text("phone_number", true),
{Name: "sms_type", Kind: "select", Options: []string{"1", "3", "4", "0"}, Default: "1"}, senderField(false),
}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
typ := 1
_, _ = fmt.Sscan(cfg["sms_type"], &typ)
reply, err := c.callJSON(ctx, http.MethodPost, "https://promosms.com/api/rest/v3_2/sms", basic(cfg["username"], cfg["password"]), map[string]any{
"recipients": []string{cfg["phone_number"]}, "text": truncate(ascii(m.sms()), 639), "long-sms": true, "type": typ, "sender": cfg["sender"],
})
return replyCheck(reply, err, func(v map[string]any) string {
resp, _ := v["response"].(map[string]any)
if st := str(resp["status"]); st != "0" {
return "PromoSMS: status " + st
}
return ""
})
}},
{Type: "serwersms", Group: "sms", Fields: []Field{text("username", true), secret("password", true), text("phone_number", true), senderField(false)},
send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
reply, err := c.callJSON(ctx, http.MethodPost, "https://api2.serwersms.pl/messages/send_sms", nil, map[string]any{
"username": cfg["username"], "password": cfg["password"], "text": ascii(m.sms()), "sender": cfg["sender"], "phone": cfg["phone_number"],
})
return replyCheck(reply, err, func(v map[string]any) string {
if v["success"] != true {
e, _ := v["error"].(map[string]any)
return "SerwerSMS: " + or(str(e["message"]), "failed")
}
return ""
})
}},
{Type: "sevenio", Group: "sms", Fields: []Field{secret("api_key", true), text("phone_number", true), senderField(false)},
send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
return c.json(ctx, http.MethodPost, "https://gateway.seven.io/api/sms", http.Header{"X-API-Key": {cfg["api_key"]}},
map[string]any{"to": cfg["phone_number"], "from": or(cfg["sender"], "UptimeSebi"), "text": m.sms()})
}},
{Type: "smsgateway", Group: "sms", Fields: []Field{urlField("api_url", true, ""), secret("api_key", true), text("phone_numbers", true)},
send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
// SMS Gateway for Android.
for _, to := range list(cfg["phone_numbers"]) {
reply, err := c.callJSON(ctx, http.MethodPost, trimURL(cfg["api_url"])+"/api/v1/sms/send", http.Header{"X-API-Key": {cfg["api_key"]}},
map[string]any{"to": to, "body": m.sms()})
if err := replyCheck(reply, err, func(v map[string]any) string {
if str(v["status"]) == "failed" {
return to + ": " + or(str(v["message"]), "failed")
}
return ""
}); err != nil {
return err
}
}
return nil
}},
{Type: "smsplanet", Group: "sms", Fields: []Field{secret("api_token", true), senderField(true), text("phone_numbers", true)},
send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
reply, err := c.form(ctx, "https://api2.smsplanet.pl/sms", bearer(cfg["api_token"]),
url.Values{"from": {cfg["sender"]}, "to": {cfg["phone_numbers"]}, "msg": {m.sms()}})
return replyCheck(reply, err, func(v map[string]any) string {
if str(v["messageId"]) == "" {
return "SMSPlanet: " + or(str(v["errorMsg"]), "no message ID")
}
return ""
})
}},
{Type: "smsc", Group: "sms", Fields: []Field{text("username", true), secret("password", true), text("phone_number", true), senderField(false)},
send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
q := url.Values{"fmt": {"3"}, "translit": {"0"}, "login": {cfg["username"]}, "psw": {cfg["password"]},
"phones": {cfg["phone_number"]}, "mes": {ascii(m.sms())}}
if cfg["sender"] != "" {
q.Set("sender", cfg["sender"])
}
reply, err := c.get(ctx, "https://smsc.kz/sys/send.php", nil, q)
return replyCheck(reply, err, func(v map[string]any) string {
if v["id"] == nil {
return fmt.Sprintf("SMSC: %s (%s)", str(v["error"]), str(v["error_code"]))
}
return ""
})
}},
{Type: "smseagle", Group: "sms", Fields: []Field{
urlField("api_url", true, ""), secret("access_token", true), text("phone_numbers", true),
{Name: "api_version", Kind: "select", Options: []string{"2", "1"}, Default: "2"},
}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
base := trimURL(cfg["api_url"])
if cfg["api_version"] == "1" {
reply, err := c.get(ctx, base+"/http_api/send_sms", nil, url.Values{
"access_token": {cfg["access_token"]}, "to": {strings.Join(list(cfg["phone_numbers"]), ",")}, "message": {m.sms()}, "unicode": {"1"},
})
if err == nil && !strings.Contains(string(reply), "OK") {
return errors.New("SMSEagle: " + truncate(string(reply), 200))
}
return err
}
return c.json(ctx, http.MethodPost, base+"/api/v2/messages/sms", http.Header{"access-token": {cfg["access_token"]}},
map[string]any{"to": list(cfg["phone_numbers"]), "text": m.sms(), "encoding": "unicode"})
}},
{Type: "smsir", Group: "sms", Fields: []Field{secret("api_key", true), text("template_id", true), text("phone_numbers", true)},
send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
// sms.ir verify templates take one parameter, uptkumaalert, of
// at most 20 characters.
var template int
_, _ = fmt.Sscan(cfg["template_id"], &template)
msg := truncate(strings.ReplaceAll(m.Monitor+" "+m.status(), " ", ""), 20)
for _, mobile := range list(cfg["phone_numbers"]) {
if len(mobile) == 11 && strings.HasPrefix(mobile, "09") {
mobile = mobile[1:]
}
if err := c.json(ctx, http.MethodPost, "https://api.sms.ir/v1/send/verify", http.Header{"X-API-Key": {cfg["api_key"]}}, map[string]any{
"mobile": mobile, "templateId": template, "parameters": []map[string]any{{"name": "uptkumaalert", "value": msg}},
}); err != nil {
return err
}
}
return nil
}},
{Type: "smsmanager", Group: "sms", Fields: []Field{
secret("api_key", true), text("phone_numbers", true),
{Name: "gateway", Kind: "select", Options: []string{"high", "economy"}, Default: "high"},
}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
_, err := c.get(ctx, "https://http-api.smsmanager.cz/Send", nil, url.Values{
"apikey": {cfg["api_key"]}, "message": {ascii(m.sms())}, "number": {cfg["phone_numbers"]}, "gateway": {or(cfg["gateway"], "high")},
})
return err
}},
{Type: "smspartner", Group: "sms", Fields: []Field{secret("api_key", true), text("phone_numbers", true), senderField(true)},
send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
reply, err := c.callJSON(ctx, http.MethodPost, "https://api.smspartner.fr/v1/send", nil, map[string]any{
"apiKey": cfg["api_key"], "sender": truncate(cfg["sender"], 11), "phoneNumbers": cfg["phone_numbers"], "message": truncate(ascii(m.sms()), 639),
})
return replyCheck(reply, err, func(v map[string]any) string {
if v["success"] != true {
return "SMSPartner: " + str(v["message"])
}
return ""
})
}},
{Type: "telnyx", Group: "sms", Fields: []Field{secret("api_key", true), senderField(true), text("phone_number", true), text("messaging_profile_id", false)},
send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
body := map[string]any{"from": cfg["sender"], "to": cfg["phone_number"], "text": m.sms()}
if cfg["messaging_profile_id"] != "" {
body["messaging_profile_id"] = cfg["messaging_profile_id"]
}
return c.json(ctx, http.MethodPost, "https://api.telnyx.com/v2/messages", bearer(cfg["api_key"]), body)
}},
{Type: "teltonika", Group: "sms", Fields: []Field{
urlField("server_url", true, ""), text("username", true), secret("password", true), text("modem", true), text("phone_number", true),
}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
// Teltonika routers (RutOS): sign in, then send through a modem.
u, err := url.Parse(cfg["server_url"])
if err != nil {
return err
}
base := u.Scheme + "://" + u.Host
reply, err := c.callJSON(ctx, http.MethodPost, base+"/api/login", nil, map[string]any{"username": cfg["username"], "password": cfg["password"]})
var login struct {
Success bool `json:"success"`
Data struct {
Token string `json:"token"`
} `json:"data"`
}
if err != nil || json.Unmarshal(reply, &login) != nil || !login.Success {
return errors.Join(errors.New("sign-in to Teltonika failed"), err)
}
reply, err = c.callJSON(ctx, http.MethodPost, base+"/api/messages/actions/send", bearer(login.Data.Token), map[string]any{
"data": map[string]any{"modem": cfg["modem"], "number": cfg["phone_number"], "message": truncate(m.sms(), 159)},
})
return replyCheck(reply, err, func(v map[string]any) string {
if v["success"] != true {
return "Teltonika: " + str(v["errors"])
}
return ""
})
}},
{Type: "twilio", Group: "sms", Fields: []Field{
text("account_sid", true), secret("auth_token", true), text("api_key", false), senderField(false), text("phone_number", true),
text("messaging_service_sid", false),
}, send: func(ctx context.Context, c *client, cfg map[string]string, m Message) error {
// With an API key, the token is that key's secret.
v := url.Values{"To": {cfg["phone_number"]}, "Body": {m.sms()}}
if cfg["sender"] != "" {
v.Set("From", cfg["sender"])
}
if cfg["messaging_service_sid"] != "" {
v.Set("MessagingServiceSid", cfg["messaging_service_sid"])
}
_, err := c.form(ctx, "https://api.twilio.com/2010-04-01/Accounts/"+url.PathEscape(cfg["account_sid"])+"/Messages.json",
basic(or(cfg["api_key"], cfg["account_sid"]), cfg["auth_token"]), v)
return err
}},
}
// aliyunSign signs Alibaba Cloud RPC parameters (signature version 1.0).
func aliyunSign(v url.Values, secret string) string {
keys := make([]string, 0, len(v))
for k := range v {
keys = append(keys, k)
}
sort.Strings(keys)
enc := func(s string) string {
return strings.NewReplacer("+", "%20", "*", "%2A", "%7E", "~").Replace(url.QueryEscape(s))
}
pairs := make([]string, len(keys))
for i, k := range keys {
pairs[i] = enc(k) + "=" + enc(v.Get(k))
}
mac := hmac.New(sha1.New, []byte(secret+"&"))
mac.Write([]byte("POST&" + enc("/") + "&" + enc(strings.Join(pairs, "&"))))
return base64.StdEncoding.EncodeToString(mac.Sum(nil))
}
func tehran() *time.Location {
if l, err := time.LoadLocation("Asia/Tehran"); err == nil {
return l
}
return time.FixedZone("IRST", 3*3600+1800)
}