oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package notifications
2
3import (
4 "context"
5 "crypto/sha256"
6 "database/sql"
7 "encoding/json"
8 "fmt"
9 "time"
10
11 "amadan.net/oficina/equipo/internal/equipo/kernel"
12 "gorm.io/gorm"
13)
14
15func Topic(team, person, id string) string {
16 raw, _ := json.Marshal([]string{team, person, id})
17 return fmt.Sprintf("notifications/%x", sha256.Sum256(raw))
18}
19func (s *Store) AllowNotificationTopic(ctx context.Context, a kernel.Actor, key string) bool {
20 allowed := false
21 err := s.Read(ctx, func(tx *gorm.DB) error {
22 team, e := s.authorize(tx, ctx, a)
23 if e != nil {
24 return e
25 }
26 var subs []Subscription
27 if e = tx.Where("team_id=? AND person=? AND active=1", team, a.Address).Find(&subs).Error; e != nil {
28 return e
29 }
30 for _, sub := range subs {
31 if Topic(team, a.Address, sub.ID) == "notifications/"+key {
32 _, e = s.subscription(tx, ctx, a, team, sub.ID, true)
33 allowed = e == nil
34 return e
35 }
36 }
37 return nil
38 })
39 return err == nil && allowed
40}
41func InstallChanges(ctx context.Context, tx *sql.Tx) error {
42 for _, stmt := range []string{
43 `CREATE TEMP TABLE IF NOT EXISTS equipo_notification_changes(team TEXT,person TEXT,PRIMARY KEY(team,person))`,
44 `DELETE FROM equipo_notification_changes`,
45 `CREATE TEMP TRIGGER IF NOT EXISTS equipo_notification_insert AFTER INSERT ON main.notification_outbox BEGIN INSERT OR IGNORE INTO equipo_notification_changes VALUES(NEW.team_id,NEW.recipient); END`,
46 `CREATE TEMP TRIGGER IF NOT EXISTS equipo_notification_update AFTER UPDATE ON main.notification_outbox BEGIN INSERT OR IGNORE INTO equipo_notification_changes VALUES(NEW.team_id,NEW.recipient); END`,
47 `CREATE TEMP TRIGGER IF NOT EXISTS equipo_notification_subscription AFTER UPDATE ON main.notification_subscriptions BEGIN INSERT OR IGNORE INTO equipo_notification_changes VALUES(NEW.team_id,NEW.person); END`,
48 } {
49 if _, err := tx.ExecContext(ctx, stmt); err != nil {
50 return err
51 }
52 }
53 return nil
54}
55func Changes(ctx context.Context, tx *sql.Tx, deadlines map[string][]time.Time) ([]string, error) {
56 rows, err := tx.QueryContext(ctx, `SELECT s.team_id,s.person,s.id,s.expires_at FROM notification_subscriptions s JOIN equipo_notification_changes c ON c.team=s.team_id AND c.person=s.person`)
57 if err != nil {
58 return nil, err
59 }
60 defer rows.Close()
61 var topics []string
62 for rows.Next() {
63 var team, person, id string
64 var expires any
65 if err = rows.Scan(&team, &person, &id, &expires); err != nil {
66 return nil, err
67 }
68 topic := Topic(team, person, id)
69 topics = append(topics, topic)
70 deadlines[topic] = append(deadlines[topic], kernel.ReadTime(expires))
71 }
72 return topics, rows.Err()
73}
74