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 "amadan.net/oficina/equipo/internal/equipo/conversation"
5 "amadan.net/oficina/equipo/internal/equipo/kernel"
6 "amadan.net/oficina/equipo/internal/equipo/team"
7 "context"
8 "database/sql"
9 "sort"
10 "time"
11)
12
13type Notifier interface {
14 Notify(...string)
15 NotifyAt(time.Time, ...string)
16}
17
18func ObserveWrite(ctx context.Context, tx *sql.Tx, n Notifier) (team.CommitObserver, error) {
19 if n == nil {
20 return nil, nil
21 }
22 if err := InstallChanges(ctx, tx); err != nil {
23 return nil, err
24 }
25 if err := conversation.InstallConversationChanges(ctx, tx); err != nil {
26 return nil, err
27 }
28 if err := conversation.InstallPersonalChanges(ctx, tx); err != nil {
29 return nil, err
30 }
31 if err := conversation.InstallJobChanges(ctx, tx); err != nil {
32 return nil, err
33 }
34 return func(ctx context.Context, tx *sql.Tx) (func(), error) {
35 rows, err := tx.QueryContext(ctx, `SELECT c.team,c.job FROM equipo_live_changes c JOIN teams t ON t.id=c.team WHERE c.job=0 OR EXISTS(SELECT 1 FROM jobs j WHERE j.id=c.job AND j.account=c.team)`)
36 if err != nil {
37 return nil, err
38 }
39 touched := map[string][]team.JobID{}
40 topics := map[string]bool{}
41 for rows.Next() {
42 var teamID string
43 var job team.JobID
44 if err = rows.Scan(&teamID, &job); err != nil {
45 break
46 }
47 touched[teamID] = append(touched[teamID], job)
48 topics[kernel.JobTopic(teamID, int64(job))] = true
49 topics[kernel.JobTopic(teamID, 0)] = true
50 }
51 if err == nil {
52 err = rows.Err()
53 }
54 rows.Close()
55 if err != nil {
56 return nil, err
57 }
58 deadlines := map[string][]time.Time{}
59 if err := conversation.ConversationDeadlines(ctx, tx, deadlines); err != nil {
60 return nil, err
61 }
62 for teamID, ids := range touched {
63 if err := conversation.JobDeadlines(ctx, tx, deadlines, teamID, ids); err != nil {
64 return nil, err
65 }
66 }
67 private, err := conversation.PersonalChanges(ctx, tx)
68 if err != nil {
69 return nil, err
70 }
71 conversations, err := conversation.ConversationChanges(ctx, tx)
72 if err != nil {
73 return nil, err
74 }
75 notificationTopics, err := Changes(ctx, tx, deadlines)
76 if err != nil {
77 return nil, err
78 }
79 private = append(private, notificationTopics...)
80 private = append(private, conversations...)
81 for _, topic := range private {
82 topics[topic] = true
83 }
84 keys := make([]string, 0, len(topics))
85 for topic := range topics {
86 keys = append(keys, topic)
87 }
88 sort.Strings(keys)
89 return func() {
90 if len(keys) > 0 {
91 n.Notify(keys...)
92 }
93 Schedule(n, deadlines)
94 }, nil
95 }, nil
96}
97func Schedule(n Notifier, deadlines map[string][]time.Time) {
98 for topic, dates := range deadlines {
99 for _, at := range dates {
100 if at.After(time.Now()) {
101 n.NotifyAt(at, topic)
102 }
103 }
104 }
105}
106