add gotify transport
This commit is contained in:
parent
fc7784ba12
commit
4b312e28ae
6 changed files with 142 additions and 3 deletions
|
|
@ -93,6 +93,9 @@ func (s *Server) Router() *gin.Engine {
|
|||
a.POST("/push/subscribe", s.subscribe)
|
||||
a.POST("/push/unsubscribe", s.unsubscribe)
|
||||
a.POST("/push/test", s.testPush)
|
||||
a.GET("/push/gotify", s.getGotify)
|
||||
a.PUT("/push/gotify", s.setGotify)
|
||||
a.DELETE("/push/gotify", s.deleteGotify)
|
||||
a.GET("/passkeys", s.listPasskeys)
|
||||
a.POST("/passkeys/register/begin", s.passkeyRegisterBegin)
|
||||
a.POST("/passkeys/register/finish", s.passkeyRegisterFinish)
|
||||
|
|
|
|||
|
|
@ -1,6 +1,8 @@
|
|||
package api
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/sirupsen/logrus"
|
||||
"jonasled.dev/jonasled/go-libs/log"
|
||||
|
|
@ -85,13 +87,66 @@ func (s *Server) unsubscribe(c *gin.Context) {
|
|||
// @Failure 409 {object} ErrorResponse
|
||||
// @Router /push/test [post]
|
||||
func (s *Server) testPush(c *gin.Context) {
|
||||
var n int64
|
||||
var n, g int64
|
||||
s.db.Model(&models.PushSub{}).Where("user_id = ?", me(c).ID).Count(&n)
|
||||
if n == 0 {
|
||||
s.db.Model(&models.GotifySub{}).Where("user_id = ?", me(c).ID).Count(&g)
|
||||
if n+g == 0 {
|
||||
fail(c, 409, "no device subscribed, enable notifications first")
|
||||
return
|
||||
}
|
||||
log.Log.WithFields(logrus.Fields{"user_id": me(c).ID, "devices": n}).Info("push: test notification requested")
|
||||
log.Log.WithFields(logrus.Fields{"user_id": me(c).ID, "devices": n, "gotify": g}).Info("push: test notification requested")
|
||||
s.push.Notify(me(c).TenantID, []uint{me(c).ID}, push.TestMsg())
|
||||
c.Status(204)
|
||||
}
|
||||
|
||||
type GotifyReq struct {
|
||||
URL string `json:"url"`
|
||||
Token string `json:"token"`
|
||||
}
|
||||
|
||||
// getGotify godoc
|
||||
//
|
||||
// @Summary Gotify server of the caller (token is never returned)
|
||||
// @Tags push
|
||||
// @Produce json
|
||||
// @Success 200 {object} GotifyReq
|
||||
// @Router /push/gotify [get]
|
||||
func (s *Server) getGotify(c *gin.Context) {
|
||||
var g models.GotifySub
|
||||
s.db.Where("user_id = ?", me(c).ID).Limit(1).Find(&g)
|
||||
c.JSON(200, GotifyReq{URL: g.URL})
|
||||
}
|
||||
|
||||
// setGotify godoc
|
||||
//
|
||||
// @Summary Use Gotify as notification transport
|
||||
// @Tags push
|
||||
// @Accept json
|
||||
// @Param body body GotifyReq true "Gotify base URL and application token"
|
||||
// @Success 204
|
||||
// @Router /push/gotify [put]
|
||||
func (s *Server) setGotify(c *gin.Context) {
|
||||
var in GotifyReq
|
||||
if c.BindJSON(&in) != nil || !strings.HasPrefix(in.URL, "http") || in.Token == "" {
|
||||
fail(c, 400, "url (http/https) and token required")
|
||||
return
|
||||
}
|
||||
u := me(c)
|
||||
s.db.Where("user_id = ?", u.ID).Delete(&models.GotifySub{})
|
||||
if err := s.db.Create(&models.GotifySub{UserID: u.ID, TenantID: u.TenantID, URL: in.URL, Token: in.Token}).Error; err != nil {
|
||||
fail(c, 500, "could not save gotify settings")
|
||||
return
|
||||
}
|
||||
c.Status(204)
|
||||
}
|
||||
|
||||
// deleteGotify godoc
|
||||
//
|
||||
// @Summary Stop using Gotify
|
||||
// @Tags push
|
||||
// @Success 204
|
||||
// @Router /push/gotify [delete]
|
||||
func (s *Server) deleteGotify(c *gin.Context) {
|
||||
s.db.Where("user_id = ?", me(c).ID).Delete(&models.GotifySub{})
|
||||
c.Status(204)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -117,5 +117,9 @@ func migrate(db *gorm.DB) error {
|
|||
tx.Migrator().DropColumn(&models.Tenant{}, "Slug")
|
||||
return tx.Migrator().DropTable("oidc_configs")
|
||||
},
|
||||
}, {
|
||||
ID: "202611170001_gotify",
|
||||
Migrate: func(tx *gorm.DB) error { return tx.AutoMigrate(&models.GotifySub{}) },
|
||||
Rollback: func(tx *gorm.DB) error { return tx.Migrator().DropTable("gotify_subs") },
|
||||
}}).Migrate()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -63,6 +63,15 @@ type PushSub struct {
|
|||
Auth string `gorm:"size:255"`
|
||||
}
|
||||
|
||||
// GotifySub is a user's Gotify server + application token, an alternative to Web Push.
|
||||
type GotifySub struct {
|
||||
ID uint `gorm:"primaryKey"`
|
||||
UserID uint `gorm:"uniqueIndex"`
|
||||
TenantID uint `gorm:"index"`
|
||||
URL string `gorm:"size:500"`
|
||||
Token string `gorm:"size:255"`
|
||||
}
|
||||
|
||||
type Setting struct {
|
||||
Key string `gorm:"primaryKey;size:64"`
|
||||
Value string `gorm:"type:text"`
|
||||
|
|
|
|||
|
|
@ -2,9 +2,13 @@
|
|||
package push
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
webpush "github.com/SherClockHolmes/webpush-go"
|
||||
"github.com/sirupsen/logrus"
|
||||
|
|
@ -71,12 +75,49 @@ func TestMsg() []byte {
|
|||
}
|
||||
|
||||
// Notify sends to the given users, or the whole tenant when users is nil. Runs async.
|
||||
// sendGotify posts to a Gotify server using message extras: markdown body, click-through URL, priority.
|
||||
// https://gotify.net/docs/msgextras
|
||||
func sendGotify(g models.GotifySub, payload []byte) error {
|
||||
var p struct {
|
||||
Title, Body, URL string
|
||||
Urgent bool
|
||||
}
|
||||
json.Unmarshal(payload, &p)
|
||||
prio := 5
|
||||
if p.Urgent {
|
||||
prio = 8
|
||||
}
|
||||
extras := map[string]any{"client::display": map[string]string{"contentType": "text/markdown"}}
|
||||
msg := p.Body
|
||||
if base := strings.TrimRight(config.Env("PUBLIC_URL", ""), "/"); base != "" && p.URL != "" {
|
||||
extras["client::notification"] = map[string]any{"click": map[string]string{"url": base + p.URL}}
|
||||
msg += "\n\n[Open in Pager](" + base + p.URL + ")"
|
||||
}
|
||||
b, _ := json.Marshal(map[string]any{"title": p.Title, "message": msg, "priority": prio, "extras": extras})
|
||||
resp, err := (&http.Client{Timeout: 10 * time.Second}).Post(strings.TrimRight(g.URL, "/")+"/message?token="+url.QueryEscape(g.Token), "application/json", bytes.NewReader(b))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode >= 400 {
|
||||
return fmt.Errorf("status %d", resp.StatusCode)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) Notify(tid uint, users []uint, payload []byte) {
|
||||
go func() {
|
||||
q := s.db.Where("tenant_id = ?", tid)
|
||||
if users != nil {
|
||||
q = q.Where("user_id IN ?", users)
|
||||
}
|
||||
var gs []models.GotifySub
|
||||
q.Find(&gs)
|
||||
for _, g := range gs {
|
||||
if err := sendGotify(g, payload); err != nil {
|
||||
log.Log.WithFields(logrus.Fields{"user_id": g.UserID, "err": err}).Warn("gotify: send failed")
|
||||
}
|
||||
}
|
||||
var subs []models.PushSub
|
||||
q.Find(&subs)
|
||||
log.Log.WithFields(logrus.Fields{"tenant_id": tid, "subscriptions": len(subs)}).Debug("push: sending notification")
|
||||
|
|
|
|||
|
|
@ -26,6 +26,32 @@ function PushToggle() {
|
|||
)
|
||||
}
|
||||
|
||||
function GotifyToggle() {
|
||||
const [url, setUrl] = useState(null) // null = loading, '' = not configured
|
||||
const [open, setOpen] = useState(false)
|
||||
const [form, setForm] = useState({ url: '', token: '' })
|
||||
const [err, setErr] = useState('')
|
||||
useEffect(() => { api('/push/gotify').then((g) => setUrl(g.url), () => setUrl('')) }, [])
|
||||
if (url === null) return null
|
||||
const run = (p, done) => p.then(() => { setErr(''); done() }, (e) => setErr(e.message))
|
||||
const save = () => run(api('/push/gotify', 'PUT', form), () => { setUrl(form.url); setOpen(false); setForm({ ...form, token: '' }) })
|
||||
const remove = () => run(api('/push/gotify', 'DELETE'), () => { setUrl(''); setOpen(false) })
|
||||
return (
|
||||
<>
|
||||
{url && <button className="btn" onClick={() => run(api('/push/test', 'POST'), () => {})}>Test Gotify</button>}
|
||||
<button className="btn" onClick={() => setOpen(!open)} title={err}>{err ? '⚠ ' + err : url ? '📨 Gotify on' : '📨 Gotify'}</button>
|
||||
{open && (
|
||||
<span>
|
||||
<input placeholder="https://gotify.example.com" value={form.url} onChange={(e) => setForm({ ...form, url: e.target.value })} />
|
||||
<input placeholder="App token" type="password" value={form.token} onChange={(e) => setForm({ ...form, token: e.target.value })} />
|
||||
<button className="btn primary" onClick={save}>Save</button>
|
||||
{url && <button className="btn" onClick={remove}>Remove</button>}
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
// /sso/<slug> is a short link that starts the SSO sign-in of that organisation.
|
||||
function SsoRedirect() {
|
||||
const { slug } = useParams()
|
||||
|
|
@ -67,6 +93,7 @@ export default function App() {
|
|||
</nav>
|
||||
<span className="grow" />
|
||||
<PushToggle />
|
||||
<GotifyToggle />
|
||||
<span className="muted who">{user.name} · {user.role}</span>
|
||||
<button className="btn" onClick={logout}>Sign out</button>
|
||||
</header>
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue