Files

144 lines
4.0 KiB
Go
Raw Permalink Normal View History

package api
import (
"context"
"encoding/json"
"io"
"log/slog"
"net/http"
"strings"
"time"
"github.com/SherClockHolmes/webpush-go"
"messenger/internal/realtime"
"messenger/internal/store"
)
type pushRequest struct {
Endpoint string `json:"endpoint"`
Keys struct {
P256dh string `json:"p256dh"`
Auth string `json:"auth"`
} `json:"keys"`
}
func (h *apiHandler) subscribePush(w http.ResponseWriter, r *http.Request) {
userID, _ := userIDFrom(r.Context())
var req pushRequest
if !decodeJSON(w, r, &req) {
return
}
if req.Endpoint == "" || req.Keys.P256dh == "" || req.Keys.Auth == "" {
writeError(w, http.StatusBadRequest, "endpoint, p256dh and auth are required")
return
}
_, err := h.store.CreatePushSubscription(r.Context(), store.PushSubscription{
UserID: userID,
Endpoint: req.Endpoint,
P256dh: req.Keys.P256dh,
Auth: req.Keys.Auth,
})
if err != nil {
writeError(w, http.StatusInternalServerError, "internal server error")
return
}
writeJSON(w, http.StatusCreated, map[string]string{"status": "ok"})
}
func (h *apiHandler) unsubscribePush(w http.ResponseWriter, r *http.Request) {
userID, _ := userIDFrom(r.Context())
var req pushRequest
if !decodeJSON(w, r, &req) {
return
}
if req.Endpoint == "" {
writeError(w, http.StatusBadRequest, "endpoint is required")
return
}
if err := h.store.DeletePushSubscription(r.Context(), userID, req.Endpoint); err != nil {
writeError(w, http.StatusInternalServerError, "internal server error")
return
}
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
}
type pushNotifier struct {
store *store.Store
hub *realtime.Hub
log *slog.Logger
public string
private string
subject string
}
func newPushNotifier(st *store.Store, hub *realtime.Hub, log *slog.Logger, public, private, subject string) *pushNotifier {
if public == "" || private == "" {
return nil
}
return &pushNotifier{store: st, hub: hub, log: log, public: public, private: private, subject: subject}
}
// notifyMembers pushes a message notification to offline members.
// Failed or stale endpoints are cleaned up asynchronously.
func (n *pushNotifier) notifyMembers(ctx context.Context, conversationID, senderID, messageID int64, senderName, body string) {
members, err := n.store.ListMembers(ctx, conversationID)
if err != nil {
return
}
title := senderName
text := strings.TrimSpace(body)
if text == "" {
text = "📎 Вложение"
}
if len(text) > 140 {
text = text[:140] + "…"
}
payload, _ := json.Marshal(map[string]any{
"title": title,
"body": text,
"conversation_id": conversationID,
"message_id": messageID,
})
for _, m := range members {
if m.User.ID == senderID || n.hub.IsOnline(m.User.ID) {
continue
}
subs, err := n.store.ListPushSubscriptionsForUser(ctx, m.User.ID)
if err != nil {
continue
}
for _, sub := range subs {
go n.send(m.User.ID, sub, payload)
}
}
}
// send delivers a single notification using a detached context, because the
// originating HTTP request context is canceled as soon as its handler returns.
func (n *pushNotifier) send(userID int64, sub store.PushSubscription, payload []byte) {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
wp := &webpush.Subscription{Endpoint: sub.Endpoint, Keys: webpush.Keys{P256dh: sub.P256dh, Auth: sub.Auth}}
resp, err := webpush.SendNotificationWithContext(ctx, payload, wp, &webpush.Options{
VAPIDPublicKey: n.public,
VAPIDPrivateKey: n.private,
Subscriber: n.subject,
TTL: 24 * 60 * 60,
})
if err != nil {
n.log.Warn("push send failed", "user_id", userID, "error", err)
return
}
defer resp.Body.Close()
switch {
case resp.StatusCode == http.StatusNotFound || resp.StatusCode == http.StatusGone:
_ = n.store.DeletePushSubscription(context.Background(), userID, sub.Endpoint)
case resp.StatusCode >= 300:
body, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
n.log.Warn("push rejected", "user_id", userID, "status", resp.StatusCode, "body", string(body))
}
}