feat: new-music notices come from the scanner; request notices and the original specs go
release / web (push) Failing after 1m29s
release / go (push) Successful in 1m55s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 4m22s
release / android (push) Successful in 4m57s
release / Attach APK to the Release (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
release / Build signed APK (push) Canceled after 4m23s
release / web (push) Failing after 1m29s
release / go (push) Successful in 1m55s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 4m22s
release / android (push) Successful in 4m57s
release / Attach APK to the Release (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
release / Build signed APK (push) Canceled after 4m23s
Request notifications (approved, declined, completed, pending) are removed
along with the request flow that produced them. A new_music kind takes the
"new music arrived" slot: when a scan or a watcher batch finishes, the
scanner claims every album not yet announced (albums.announced_at) and tells
every user about the ones that are new: an album with a track on disk and
no track older than itself. The first import into an empty library, and an
album formed only by retagging tracks already held, announce nothing. One
notice per scan, carrying up to 50 albums and the total; it is never
coalesced, so a notice already emailed can't quietly absorb later arrivals.
It feeds the daily summary email, grouped by artist. Defaults: inbox and
email on, phone off.
Migration 0103 deletes request-kind notification rows and prefs, swaps the
kind CHECKs to new_music, and adds albums.announced_at with every album
held marked announced, so the first scan after it announces nothing old.
Web and Android: labels, the Android "Requests" settings section becomes
"New music", the shade channel your_requests becomes new_music (the old one
is deleted at startup), and "/" opens Home in the app. TrackLabel moves to
the notifications package. docs/smart-music-{server,client}-spec.md are
deleted per the operator; an Android comment loses the word "exchanges".
Grimoire #7666, #7671.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -32,14 +32,14 @@ func digestWith(pool *pgxpool.Pool) (*notifications.Digest, *mailer.FakeSender)
|
||||
func TestDigest_BatchGoesOutOnceAWindowAfterTheFirstItem(t *testing.T) {
|
||||
pool := testPool(t)
|
||||
ctx := context.Background()
|
||||
alice := emailUser(t, pool, "alice", false)
|
||||
alice := emailUser(t, pool, "alice", true)
|
||||
n := notifications.New(pool, nil, nil)
|
||||
d, fake := digestWith(pool)
|
||||
start := time.Now()
|
||||
|
||||
require.NoError(t, n.Notify(ctx, notifications.KindRequestApproved, notifications.ToUser(alice),
|
||||
require.NoError(t, n.Notify(ctx, notifications.KindQuarantineFlagged, notifications.ToUser(alice),
|
||||
notifications.Payload{Name: "Moe Shop – WWW"}.Map()))
|
||||
require.NoError(t, n.Notify(ctx, notifications.KindRequestRejected, notifications.ToUser(alice),
|
||||
require.NoError(t, n.Notify(ctx, notifications.KindQuarantineFlagged, notifications.ToUser(alice),
|
||||
notifications.Payload{Name: "Tycho – Awake", Reason: "already have it"}.Map()))
|
||||
|
||||
d.Tick(ctx, start.Add(30*time.Minute))
|
||||
@@ -49,8 +49,8 @@ func TestDigest_BatchGoesOutOnceAWindowAfterTheFirstItem(t *testing.T) {
|
||||
require.Len(t, fake.Sent, 1, "both items, one email")
|
||||
require.Equal(t, "alice@example.com", fake.Sent[0].To)
|
||||
require.Equal(t, "Minstrel: 2 updates", fake.Sent[0].Subject)
|
||||
require.Contains(t, fake.Sent[0].TextBody, "Moe Shop – WWW is on its way.")
|
||||
require.Contains(t, fake.Sent[0].TextBody, "Tycho – Awake was declined: already have it")
|
||||
require.Contains(t, fake.Sent[0].TextBody, "Someone flagged Moe Shop – WWW.")
|
||||
require.Contains(t, fake.Sent[0].TextBody, "Someone flagged Tycho – Awake: already have it")
|
||||
|
||||
d.Tick(ctx, start.Add(3*time.Hour))
|
||||
require.Len(t, fake.Sent, 1, "never sent twice")
|
||||
@@ -60,12 +60,12 @@ func TestDigest_ReadBeforeTheEmailIsNotEmailed(t *testing.T) {
|
||||
pool := testPool(t)
|
||||
ctx := context.Background()
|
||||
q := dbq.New(pool)
|
||||
alice := emailUser(t, pool, "alice", false)
|
||||
alice := emailUser(t, pool, "alice", true)
|
||||
n := notifications.New(pool, nil, nil)
|
||||
d, fake := digestWith(pool)
|
||||
start := time.Now()
|
||||
|
||||
require.NoError(t, n.Notify(ctx, notifications.KindRequestApproved, notifications.ToUser(alice), nil))
|
||||
require.NoError(t, n.Notify(ctx, notifications.KindQuarantineFlagged, notifications.ToUser(alice), nil))
|
||||
_, err := q.MarkAllNotificationsRead(ctx, dbq.MarkAllNotificationsReadParams{UserID: alice})
|
||||
require.NoError(t, err)
|
||||
|
||||
@@ -77,20 +77,20 @@ func TestDigest_EmailOffAtNotifyTimeIsNeverSent(t *testing.T) {
|
||||
pool := testPool(t)
|
||||
ctx := context.Background()
|
||||
q := dbq.New(pool)
|
||||
alice := emailUser(t, pool, "alice", false)
|
||||
alice := emailUser(t, pool, "alice", true)
|
||||
off := false
|
||||
_, err := notifications.SaveSettings(ctx, q, alice, false, []notifications.SettingChange{
|
||||
{Kind: notifications.KindRequestApproved, Email: &off},
|
||||
_, err := notifications.SaveSettings(ctx, q, alice, true, []notifications.SettingChange{
|
||||
{Kind: notifications.KindQuarantineFlagged, Email: &off},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
n := notifications.New(pool, nil, nil)
|
||||
d, fake := digestWith(pool)
|
||||
start := time.Now()
|
||||
|
||||
require.NoError(t, n.Notify(ctx, notifications.KindRequestApproved, notifications.ToUser(alice), nil))
|
||||
require.NoError(t, n.Notify(ctx, notifications.KindQuarantineFlagged, notifications.ToUser(alice), nil))
|
||||
on := true
|
||||
_, err = notifications.SaveSettings(ctx, q, alice, false, []notifications.SettingChange{
|
||||
{Kind: notifications.KindRequestApproved, Email: &on},
|
||||
_, err = notifications.SaveSettings(ctx, q, alice, true, []notifications.SettingChange{
|
||||
{Kind: notifications.KindQuarantineFlagged, Email: &on},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
@@ -101,11 +101,11 @@ func TestDigest_EmailOffAtNotifyTimeIsNeverSent(t *testing.T) {
|
||||
func TestDigest_NoAddressNoEmail(t *testing.T) {
|
||||
pool := testPool(t)
|
||||
ctx := context.Background()
|
||||
bob := mkUser(t, dbq.New(pool), "bob", false)
|
||||
bob := mkUser(t, dbq.New(pool), "bob", true)
|
||||
n := notifications.New(pool, nil, nil)
|
||||
d, fake := digestWith(pool)
|
||||
|
||||
require.NoError(t, n.Notify(ctx, notifications.KindRequestApproved, notifications.ToUser(bob), nil))
|
||||
require.NoError(t, n.Notify(ctx, notifications.KindQuarantineFlagged, notifications.ToUser(bob), nil))
|
||||
d.Tick(ctx, time.Now().Add(2*time.Hour))
|
||||
require.Empty(t, fake.Sent)
|
||||
}
|
||||
@@ -136,12 +136,12 @@ func TestDigest_CoalescedItemAppearsOnceWithItsLatestCount(t *testing.T) {
|
||||
func TestDigest_MailerFailureRetriesWithBackoffAndSendsOnce(t *testing.T) {
|
||||
pool := testPool(t)
|
||||
ctx := context.Background()
|
||||
alice := emailUser(t, pool, "alice", false)
|
||||
alice := emailUser(t, pool, "alice", true)
|
||||
n := notifications.New(pool, nil, nil)
|
||||
d, fake := digestWith(pool)
|
||||
start := time.Now()
|
||||
|
||||
require.NoError(t, n.Notify(ctx, notifications.KindRequestApproved, notifications.ToUser(alice), nil))
|
||||
require.NoError(t, n.Notify(ctx, notifications.KindQuarantineFlagged, notifications.ToUser(alice), nil))
|
||||
|
||||
fake.FailNext = errors.New("smtp: 421 try later")
|
||||
d.Tick(ctx, start.Add(61*time.Minute))
|
||||
@@ -160,7 +160,7 @@ func TestDigest_MailerFailureRetriesWithBackoffAndSendsOnce(t *testing.T) {
|
||||
func TestDigest_NewMusicWaitsForTheSummaryHour(t *testing.T) {
|
||||
pool := testPool(t)
|
||||
ctx := context.Background()
|
||||
alice := emailUser(t, pool, "alice", false) // timezone defaults to UTC
|
||||
alice := emailUser(t, pool, "alice", true) // timezone defaults to UTC
|
||||
n := notifications.New(pool, nil, nil)
|
||||
d, fake := digestWith(pool)
|
||||
|
||||
@@ -170,11 +170,12 @@ func TestDigest_NewMusicWaitsForTheSummaryHour(t *testing.T) {
|
||||
slot = slot.AddDate(0, 0, 1)
|
||||
}
|
||||
|
||||
for _, p := range []notifications.Payload{
|
||||
{Name: "Moe Shop – WWW", Artist: "Moe Shop", Title: "WWW"},
|
||||
{Name: "Moe Shop – Pure", Artist: "Moe Shop", Title: "Pure"},
|
||||
for _, a := range []notifications.Arrival{
|
||||
{Artist: "Moe Shop", Title: "WWW"},
|
||||
{Artist: "Moe Shop", Title: "Pure"},
|
||||
} {
|
||||
require.NoError(t, n.Notify(ctx, notifications.KindRequestCompleted, notifications.ToUser(alice), p.Map()))
|
||||
p := notifications.Payload{Count: 1, Albums: []notifications.Arrival{a}}
|
||||
require.NoError(t, n.Notify(ctx, notifications.KindNewMusic, notifications.ToUser(alice), p.Map()))
|
||||
}
|
||||
|
||||
d.Tick(ctx, slot.Add(-time.Minute))
|
||||
@@ -210,14 +211,14 @@ func TestEmailSettings_DefaultsMatchTheMigrationAndRoundTrip(t *testing.T) {
|
||||
func TestDigest_UsesTheConfiguredBatchWindow(t *testing.T) {
|
||||
pool := testPool(t)
|
||||
ctx := context.Background()
|
||||
alice := emailUser(t, pool, "alice", false)
|
||||
alice := emailUser(t, pool, "alice", true)
|
||||
_, err := notifications.SaveEmailSettings(ctx, dbq.New(pool), notifications.EmailSettings{SummaryHour: 9, BatchWindowMinutes: 15})
|
||||
require.NoError(t, err)
|
||||
n := notifications.New(pool, nil, nil)
|
||||
d, fake := digestWith(pool)
|
||||
start := time.Now()
|
||||
|
||||
require.NoError(t, n.Notify(ctx, notifications.KindRequestApproved, notifications.ToUser(alice), nil))
|
||||
require.NoError(t, n.Notify(ctx, notifications.KindQuarantineFlagged, notifications.ToUser(alice), nil))
|
||||
d.Tick(ctx, start.Add(16*time.Minute))
|
||||
require.Len(t, fake.Sent, 1)
|
||||
}
|
||||
|
||||
@@ -77,36 +77,33 @@ func renderDigest(group EmailGroup, name string, items []pendingItem, base strin
|
||||
}
|
||||
|
||||
// summaryArtists groups new-music arrivals by artist, in the order each
|
||||
// artist first arrived, with each artist's albums and tracks under them. An
|
||||
// artist request has no title of its own; the artist links to its page.
|
||||
// artist first arrived, with each artist's albums under them.
|
||||
func summaryArtists(items []pendingItem, base string) []digestArtist {
|
||||
var out []digestArtist
|
||||
index := map[string]int{}
|
||||
for _, it := range items {
|
||||
var p Payload
|
||||
_ = json.Unmarshal(it.Payload, &p)
|
||||
artist, title := p.Artist, p.Title
|
||||
if artist == "" {
|
||||
// Rows from before Artist was recorded carry only "Artist – Title".
|
||||
artist, title, _ = strings.Cut(p.Name, " – ")
|
||||
}
|
||||
if artist == "" {
|
||||
artist = "Something you asked for"
|
||||
}
|
||||
i, ok := index[artist]
|
||||
if !ok {
|
||||
i = len(out)
|
||||
index[artist] = i
|
||||
out = append(out, digestArtist{Name: artist})
|
||||
}
|
||||
link := Render(it.Kind, it.Payload).Link
|
||||
if title == "" {
|
||||
if p.ArtistID != "" {
|
||||
out[i].URL = joinURL(base, link)
|
||||
for _, a := range p.Albums {
|
||||
artist := a.Artist
|
||||
if artist == "" {
|
||||
artist = "Unknown artist"
|
||||
}
|
||||
continue
|
||||
i, ok := index[artist]
|
||||
if !ok {
|
||||
i = len(out)
|
||||
index[artist] = i
|
||||
out = append(out, digestArtist{Name: artist})
|
||||
if a.ArtistID != "" {
|
||||
out[i].URL = joinURL(base, "/artists/"+a.ArtistID)
|
||||
}
|
||||
}
|
||||
link := "/"
|
||||
if a.AlbumID != "" {
|
||||
link = "/albums/" + a.AlbumID
|
||||
}
|
||||
out[i].Titles = append(out[i].Titles, digestLine{Title: a.Title, URL: joinURL(base, link)})
|
||||
}
|
||||
out[i].Titles = append(out[i].Titles, digestLine{Title: title, URL: joinURL(base, link)})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -28,8 +28,8 @@ func allEmail() map[Kind]bool {
|
||||
}
|
||||
|
||||
func TestPlanUser_BatchWindow(t *testing.T) {
|
||||
first := item(KindRequestApproved, t0)
|
||||
later := item(KindRequestRejected, t0.Add(40*time.Minute))
|
||||
first := item(KindQuarantineFlagged, t0)
|
||||
later := item(KindTracksMissing, t0.Add(40*time.Minute))
|
||||
cases := []struct {
|
||||
name string
|
||||
now time.Time
|
||||
@@ -63,7 +63,7 @@ func TestPlanUser_QuietBatchSendsNothing(t *testing.T) {
|
||||
func TestPlanUser_SummaryHourInUserTimezone(t *testing.T) {
|
||||
ny, err := time.LoadLocation("America/New_York")
|
||||
require.NoError(t, err)
|
||||
arrived := []pendingItem{item(KindRequestCompleted, time.Date(2026, 7, 1, 3, 0, 0, 0, time.UTC))}
|
||||
arrived := []pendingItem{item(KindNewMusic, time.Date(2026, 7, 1, 3, 0, 0, 0, time.UTC))}
|
||||
// 09:00 in New York in July is 13:00 UTC (EDT, UTC-4).
|
||||
cases := []struct {
|
||||
name string
|
||||
@@ -90,7 +90,7 @@ func TestPlanUser_SummaryHourInUserTimezone(t *testing.T) {
|
||||
func TestPlanUser_SummaryAcrossDST(t *testing.T) {
|
||||
ny, err := time.LoadLocation("America/New_York")
|
||||
require.NoError(t, err)
|
||||
arrived := []pendingItem{item(KindRequestCompleted, time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC))}
|
||||
arrived := []pendingItem{item(KindNewMusic, time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC))}
|
||||
// Clocks go back on 1 November 2026: 09:00 the day before is 13:00 UTC
|
||||
// (EDT), and 09:00 that day is 14:00 UTC (EST).
|
||||
before := groupState{LastSentAt: time.Date(2026, 10, 31, 13, 0, 0, 0, time.UTC)}
|
||||
@@ -102,7 +102,7 @@ func TestPlanUser_SummaryAcrossDST(t *testing.T) {
|
||||
// Spring forward, 8 March 2026: 02:00 does not exist. A summary hour of
|
||||
// 2 still goes out that day, once.
|
||||
gap := EmailSettings{SummaryHour: 2, BatchWindowMinutes: 60}
|
||||
spring := []pendingItem{item(KindRequestCompleted, time.Date(2026, 3, 8, 0, 0, 0, 0, time.UTC))}
|
||||
spring := []pendingItem{item(KindNewMusic, time.Date(2026, 3, 8, 0, 0, 0, 0, time.UTC))}
|
||||
at := time.Date(2026, 3, 8, 9, 0, 0, 0, time.UTC) // 05:00 EDT
|
||||
p = planUser(at, gap, ny, spring, allEmail(), groupState{}, groupState{LastSentAt: time.Date(2026, 3, 7, 7, 0, 0, 0, time.UTC)})
|
||||
require.True(t, p.SummaryDue)
|
||||
@@ -112,10 +112,10 @@ func TestPlanUser_SummaryAcrossDST(t *testing.T) {
|
||||
|
||||
func TestPlanUser_EmailOffAndStaleItemsAreSkippedNotSent(t *testing.T) {
|
||||
off := allEmail()
|
||||
off[KindRequestRejected] = false
|
||||
off[KindTracksMissing] = false
|
||||
items := []pendingItem{
|
||||
item(KindRequestRejected, t0),
|
||||
item(KindRequestApproved, t0.Add(-8*24*time.Hour)),
|
||||
item(KindTracksMissing, t0),
|
||||
item(KindQuarantineFlagged, t0.Add(-8*24*time.Hour)),
|
||||
}
|
||||
p := planUser(t0.Add(2*time.Hour), digestCfg, time.UTC, items, off, groupState{}, groupState{})
|
||||
require.Len(t, p.Skip, 2)
|
||||
@@ -132,15 +132,14 @@ func TestRetryDelay_DoublesToACap(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestRenderDigest_SummaryGroupsByArtist(t *testing.T) {
|
||||
arrival := func(p Payload) pendingItem {
|
||||
b, _ := json.Marshal(p.Map())
|
||||
return pendingItem{Kind: KindRequestCompleted, Payload: b}
|
||||
scan := func(albums ...Arrival) pendingItem {
|
||||
b, _ := json.Marshal(Payload{Count: int64(len(albums)), Albums: albums}.Map())
|
||||
return pendingItem{Kind: KindNewMusic, Payload: b}
|
||||
}
|
||||
items := []pendingItem{
|
||||
arrival(Payload{Name: "Moe Shop – WWW", Artist: "Moe Shop", Title: "WWW", AlbumID: "al-1"}),
|
||||
arrival(Payload{Name: "Boards of Canada", Artist: "Boards of Canada", ArtistID: "ar-2"}),
|
||||
arrival(Payload{Name: "Moe Shop – Pure", Artist: "Moe Shop", Title: "Pure", AlbumID: "al-3"}),
|
||||
arrival(Payload{Name: "Tycho – Awake"}), // stored before Artist was recorded
|
||||
scan(Arrival{Artist: "Moe Shop", Title: "WWW", ArtistID: "ar-1", AlbumID: "al-1"},
|
||||
Arrival{Artist: "Boards of Canada", Title: "Geogaddi", AlbumID: "al-2"}),
|
||||
scan(Arrival{Artist: "Moe Shop", Title: "Pure", ArtistID: "ar-1", AlbumID: "al-3"}),
|
||||
}
|
||||
e, err := renderDigest(EmailSummary, "alice", items, "https://music.example/")
|
||||
require.NoError(t, err)
|
||||
@@ -148,12 +147,12 @@ func TestRenderDigest_SummaryGroupsByArtist(t *testing.T) {
|
||||
|
||||
moe := strings.Index(e.Text, "Moe Shop")
|
||||
require.GreaterOrEqual(t, moe, 0)
|
||||
require.Equal(t, moe, strings.LastIndex(e.Text, "Moe Shop\n"), "one heading per artist")
|
||||
require.Equal(t, moe, strings.LastIndex(e.Text, "Moe Shop\n"), "one heading per artist, across scans")
|
||||
require.Less(t, moe, strings.Index(e.Text, "Boards of Canada"), "artists in the order they arrived")
|
||||
require.Contains(t, e.Text, "Moe Shop\n https://music.example/artists/ar-1")
|
||||
require.Contains(t, e.Text, " - WWW\n https://music.example/albums/al-1")
|
||||
require.Contains(t, e.Text, " - Pure\n https://music.example/albums/al-3")
|
||||
require.Contains(t, e.Text, "Boards of Canada\n https://music.example/artists/ar-2")
|
||||
require.Contains(t, e.Text, "Tycho\n - Awake")
|
||||
require.Contains(t, e.Text, " - Geogaddi\n https://music.example/albums/al-2")
|
||||
require.Contains(t, e.Text, "https://music.example/settings/notifications")
|
||||
require.Contains(t, e.HTML, `<a href="https://music.example/albums/al-1"`)
|
||||
}
|
||||
@@ -161,18 +160,18 @@ func TestRenderDigest_SummaryGroupsByArtist(t *testing.T) {
|
||||
func TestRenderDigest_BatchListsEachItemAndEscapesHTML(t *testing.T) {
|
||||
b, _ := json.Marshal(Payload{Name: "<script>x</script>", Reason: "dup"}.Map())
|
||||
items := []pendingItem{
|
||||
{Kind: KindRequestApproved, Payload: []byte(`{"name":"WWW"}`)},
|
||||
{Kind: KindRequestRejected, Payload: b},
|
||||
{Kind: KindQuarantineFlagged, Payload: []byte(`{"name":"WWW","actor":"Ann"}`)},
|
||||
{Kind: KindQuarantineFlagged, Payload: b},
|
||||
}
|
||||
e, err := renderDigest(EmailBatch, "alice", items, "")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "Minstrel: 2 updates", e.Subject)
|
||||
require.Contains(t, e.Text, "- Request approved\n WWW is on its way.")
|
||||
require.Contains(t, e.Text, "- Track flagged\n Ann flagged WWW.")
|
||||
require.NotContains(t, e.Text, "http", "no public address: no links")
|
||||
require.Contains(t, e.Text, "Settings → Notifications")
|
||||
require.NotContains(t, e.HTML, "<script>")
|
||||
|
||||
one, err := renderDigest(EmailBatch, "alice", items[:1], "")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "Minstrel: Request approved", one.Subject)
|
||||
require.Equal(t, "Minstrel: Track flagged", one.Subject)
|
||||
}
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
// inbox. Producers across the server call Notifier.Notify; nothing else
|
||||
// inserts into user_notifications.
|
||||
//
|
||||
// The event bus is fire-and-forget: a client that is not connected when a
|
||||
// request completes, or when tracks go missing, never hears of it. A row here
|
||||
// The event bus is fire-and-forget: a client that is not connected when new
|
||||
// music arrives, or when tracks go missing, never hears of it. A row here
|
||||
// is the durable record. The bus only nudges open clients to come and read
|
||||
// it.
|
||||
package notifications
|
||||
@@ -14,10 +14,9 @@ package notifications
|
||||
type Kind string
|
||||
|
||||
const (
|
||||
KindRequestApproved Kind = "request_approved"
|
||||
KindRequestRejected Kind = "request_rejected"
|
||||
KindRequestCompleted Kind = "request_completed"
|
||||
KindRequestPending Kind = "request_pending"
|
||||
// KindNewMusic: albums new to the library, one notice per scan that
|
||||
// brought them in, for every user.
|
||||
KindNewMusic Kind = "new_music"
|
||||
KindQuarantineFlagged Kind = "quarantine_flagged"
|
||||
KindScanFailed Kind = "scan_failed"
|
||||
KindTracksMissing Kind = "tracks_missing"
|
||||
@@ -33,7 +32,7 @@ const (
|
||||
type Audience int
|
||||
|
||||
const (
|
||||
AudienceRequester Audience = iota
|
||||
AudienceEveryone Audience = iota
|
||||
AudienceAdmin
|
||||
)
|
||||
|
||||
@@ -80,13 +79,12 @@ var (
|
||||
// inboxOnly: news an admin may want to read but never needs to be
|
||||
// interrupted for.
|
||||
inboxOnly = Channels{Inbox: true}
|
||||
// readLater: news worth a daily email but not a buzz in the pocket.
|
||||
readLater = Channels{Inbox: true, Email: true}
|
||||
)
|
||||
|
||||
var specs = map[Kind]spec{
|
||||
KindRequestApproved: {audience: AudienceRequester, group: EmailBatch, defaults: allOn},
|
||||
KindRequestRejected: {audience: AudienceRequester, group: EmailBatch, defaults: allOn},
|
||||
KindRequestCompleted: {audience: AudienceRequester, group: EmailSummary, defaults: allOn},
|
||||
KindRequestPending: {audience: AudienceAdmin, group: EmailBatch, defaults: allOn},
|
||||
KindNewMusic: {audience: AudienceEveryone, group: EmailSummary, defaults: readLater},
|
||||
KindQuarantineFlagged: {audience: AudienceAdmin, group: EmailBatch, defaults: allOn},
|
||||
KindScanFailed: {audience: AudienceAdmin, coalesce: true, group: EmailBatch, defaults: healthAlert},
|
||||
KindTracksMissing: {audience: AudienceAdmin, coalesce: true, group: EmailBatch, defaults: healthAlert},
|
||||
@@ -95,13 +93,10 @@ var specs = map[Kind]spec{
|
||||
KindPlaybackErrors: {audience: AudienceAdmin, coalesce: true, group: EmailBatch, defaults: healthAlert},
|
||||
}
|
||||
|
||||
// order is the display order for settings screens: the requester's own kinds
|
||||
// order is the display order for settings screens: the kind every user gets
|
||||
// first, then the admin ones.
|
||||
var order = []Kind{
|
||||
KindRequestApproved,
|
||||
KindRequestRejected,
|
||||
KindRequestCompleted,
|
||||
KindRequestPending,
|
||||
KindNewMusic,
|
||||
KindQuarantineFlagged,
|
||||
KindScanFailed,
|
||||
KindTracksMissing,
|
||||
|
||||
@@ -33,26 +33,29 @@ func TestKinds_OrderAndSpecsAgree(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestKinds_AdminKindsDefaultEmailOffExceptRequestQueue(t *testing.T) {
|
||||
// The burst-prone health kinds stay out of email unless an admin opts
|
||||
// in; the request queue and quarantine flags are things an admin acts on.
|
||||
func TestKinds_HealthKindsStayOutOfEmailAndCoalesce(t *testing.T) {
|
||||
// The burst-prone health kinds stay out of email unless an admin opts in.
|
||||
for _, k := range []Kind{KindScanFailed, KindTracksMissing, KindDuplicatesFound, KindDuplicatesResolved, KindPlaybackErrors} {
|
||||
require.True(t, k.AdminOnly(), k)
|
||||
require.False(t, k.Defaults().Email, k)
|
||||
require.NotEmpty(t, k.coalesceKey(), "%s should coalesce", k)
|
||||
}
|
||||
for _, k := range []Kind{KindRequestApproved, KindRequestRejected, KindRequestCompleted} {
|
||||
require.False(t, k.AdminOnly(), k)
|
||||
require.Equal(t, Channels{true, true, true}, k.Defaults(), k)
|
||||
require.Empty(t, k.coalesceKey(), "%s must never coalesce: each request is its own news", k)
|
||||
}
|
||||
require.Equal(t, EmailSummary, KindRequestCompleted.EmailGroup())
|
||||
require.Equal(t, EmailBatch, KindRequestApproved.EmailGroup())
|
||||
}
|
||||
|
||||
// New music reaches everyone, goes out in the daily summary, and never buzzes
|
||||
// a phone unless the user asks. Each scan's notice is its own row, so a
|
||||
// notice that was already emailed never silently absorbs later arrivals.
|
||||
func TestKinds_NewMusicIsForEveryoneAndDailyByEmail(t *testing.T) {
|
||||
require.False(t, KindNewMusic.AdminOnly())
|
||||
require.Equal(t, EmailSummary, KindNewMusic.EmailGroup())
|
||||
require.Equal(t, Channels{Inbox: true, Email: true}, KindNewMusic.Defaults())
|
||||
require.Empty(t, KindNewMusic.coalesceKey())
|
||||
require.Equal(t, EmailBatch, KindQuarantineFlagged.EmailGroup())
|
||||
}
|
||||
|
||||
func TestNotify_NilNotifierIsANoOp(t *testing.T) {
|
||||
var n *Notifier
|
||||
require.NoError(t, n.Notify(context.Background(), KindRequestApproved, Recipients{}, nil))
|
||||
require.NoError(t, n.Notify(context.Background(), KindNewMusic, Recipients{}, nil))
|
||||
}
|
||||
|
||||
func TestNotify_UnknownKindIsRefusedBeforeTouchingTheDB(t *testing.T) {
|
||||
|
||||
@@ -25,14 +25,19 @@ type Recipients struct {
|
||||
Users []pgtype.UUID
|
||||
// Admins adds every admin.
|
||||
Admins bool
|
||||
// Except is never notified, even when it is in Users or is an admin. The
|
||||
// admin who filed a request needs no notice that it is pending.
|
||||
// Everyone adds every user.
|
||||
Everyone bool
|
||||
// Except is never notified, even when it is in Users or is an admin: the
|
||||
// person who caused an event needs no notice of it.
|
||||
Except pgtype.UUID
|
||||
}
|
||||
|
||||
// ToUser addresses one user.
|
||||
func ToUser(id pgtype.UUID) Recipients { return Recipients{Users: []pgtype.UUID{id}} }
|
||||
|
||||
// ToEveryone addresses every user.
|
||||
func ToEveryone() Recipients { return Recipients{Everyone: true} }
|
||||
|
||||
// ToAdmins addresses every admin except one (pass the zero UUID for none).
|
||||
func ToAdmins(except pgtype.UUID) Recipients { return Recipients{Admins: true, Except: except} }
|
||||
|
||||
@@ -131,6 +136,13 @@ func (n *Notifier) resolve(ctx context.Context, q *dbq.Queries, kind Kind, to Re
|
||||
if to.Admins {
|
||||
candidates = append(candidates, admins...)
|
||||
}
|
||||
if to.Everyone {
|
||||
all, err := q.ListUserIDs(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("notifications: list users: %w", err)
|
||||
}
|
||||
candidates = append(candidates, all...)
|
||||
}
|
||||
|
||||
seen := make(map[pgtype.UUID]bool, len(candidates))
|
||||
out := make([]pgtype.UUID, 0, len(candidates))
|
||||
|
||||
@@ -82,14 +82,14 @@ func TestNotify_WritesARowAndNudgesOnlyThatUser(t *testing.T) {
|
||||
defer unsub()
|
||||
|
||||
n := notifications.New(pool, bus, nil)
|
||||
require.NoError(t, n.Notify(ctx, notifications.KindRequestApproved,
|
||||
notifications.ToUser(alice), map[string]any{"request_id": "r1", "title": "WWW"}))
|
||||
require.NoError(t, n.Notify(ctx, notifications.KindNewMusic,
|
||||
notifications.ToUser(alice), map[string]any{"count": 1, "name": "WWW"}))
|
||||
|
||||
rows := rowsFor(t, q, alice)
|
||||
require.Len(t, rows, 1)
|
||||
require.Equal(t, "request_approved", rows[0].Kind)
|
||||
require.Equal(t, "new_music", rows[0].Kind)
|
||||
require.False(t, rows[0].ReadAt.Valid)
|
||||
require.JSONEq(t, `{"request_id":"r1","title":"WWW"}`, string(rows[0].Payload))
|
||||
require.JSONEq(t, `{"count":1,"name":"WWW"}`, string(rows[0].Payload))
|
||||
require.Empty(t, rowsFor(t, q, bob))
|
||||
|
||||
select {
|
||||
@@ -106,17 +106,17 @@ func TestNotify_AdminKindReachesAdminsOnly_AndNeverTheExcepted(t *testing.T) {
|
||||
pool := testPool(t)
|
||||
q := dbq.New(pool)
|
||||
ctx := context.Background()
|
||||
requester := mkUser(t, q, "admin-requester", true)
|
||||
flagger := mkUser(t, q, "admin-flagger", true)
|
||||
other := mkUser(t, q, "admin-other", true)
|
||||
plain := mkUser(t, q, "plain", false)
|
||||
|
||||
n := notifications.New(pool, nil, nil)
|
||||
// A plain user named directly must still get nothing: the kind is admin-only.
|
||||
to := notifications.ToAdmins(requester)
|
||||
to := notifications.ToAdmins(flagger)
|
||||
to.Users = []pgtype.UUID{plain}
|
||||
require.NoError(t, n.Notify(ctx, notifications.KindRequestPending, to, nil))
|
||||
require.NoError(t, n.Notify(ctx, notifications.KindQuarantineFlagged, to, nil))
|
||||
|
||||
require.Empty(t, rowsFor(t, q, requester), "the admin who filed it needs no notice")
|
||||
require.Empty(t, rowsFor(t, q, flagger), "the admin who flagged it needs no notice")
|
||||
require.Len(t, rowsFor(t, q, other), 1)
|
||||
require.Empty(t, rowsFor(t, q, plain))
|
||||
}
|
||||
@@ -183,18 +183,37 @@ func TestNotify_ACoalescedUpdateMergesNamesAndKeepsItsArrival(t *testing.T) {
|
||||
require.True(t, emailed.Valid, "an emailed notice is not emailed again because it grew")
|
||||
}
|
||||
|
||||
func TestNotify_RequestKindsNeverCoalesce(t *testing.T) {
|
||||
// Each scan's new music is its own notice: one already emailed in the daily
|
||||
// summary must not quietly take in albums that arrive after it.
|
||||
func TestNotify_NewMusicNeverCoalesces(t *testing.T) {
|
||||
pool := testPool(t)
|
||||
q := dbq.New(pool)
|
||||
ctx := context.Background()
|
||||
alice := mkUser(t, q, "alice", false)
|
||||
n := notifications.New(pool, nil, nil)
|
||||
for _, id := range []string{"r1", "r2"} {
|
||||
require.NoError(t, n.Notify(ctx, notifications.KindRequestCompleted, notifications.ToUser(alice), map[string]any{"request_id": id}))
|
||||
for range 2 {
|
||||
require.NoError(t, n.Notify(ctx, notifications.KindNewMusic, notifications.ToUser(alice), map[string]any{"count": 1}))
|
||||
}
|
||||
require.Len(t, rowsFor(t, q, alice), 2)
|
||||
}
|
||||
|
||||
func TestNotify_EveryoneReachesEveryUser(t *testing.T) {
|
||||
pool := testPool(t)
|
||||
q := dbq.New(pool)
|
||||
ctx := context.Background()
|
||||
admin := mkUser(t, q, "admin", true)
|
||||
plain := mkUser(t, q, "plain", false)
|
||||
n := notifications.New(pool, nil, nil)
|
||||
require.NoError(t, n.Notify(ctx, notifications.KindNewMusic, notifications.ToEveryone(), map[string]any{"count": 1}))
|
||||
require.Len(t, rowsFor(t, q, admin), 1)
|
||||
require.Len(t, rowsFor(t, q, plain), 1)
|
||||
|
||||
// An admin kind addressed to everyone still reaches admins only.
|
||||
require.NoError(t, n.Notify(ctx, notifications.KindScanFailed, notifications.ToEveryone(), map[string]any{"count": 1}))
|
||||
require.Len(t, rowsFor(t, q, admin), 2)
|
||||
require.Len(t, rowsFor(t, q, plain), 1)
|
||||
}
|
||||
|
||||
func TestNotify_InboxOffStoresNothing_AndDefaultsApplyWithoutAPref(t *testing.T) {
|
||||
pool := testPool(t)
|
||||
q := dbq.New(pool)
|
||||
@@ -202,12 +221,12 @@ func TestNotify_InboxOffStoresNothing_AndDefaultsApplyWithoutAPref(t *testing.T)
|
||||
muted := mkUser(t, q, "muted", false)
|
||||
fresh := mkUser(t, q, "fresh", false)
|
||||
require.NoError(t, q.UpsertNotificationPref(ctx, dbq.UpsertNotificationPrefParams{
|
||||
UserID: muted, Kind: "request_rejected", Inbox: false, Phone: true, Email: true,
|
||||
UserID: muted, Kind: "new_music", Inbox: false, Phone: true, Email: true,
|
||||
}))
|
||||
|
||||
n := notifications.New(pool, nil, nil)
|
||||
to := notifications.Recipients{Users: []pgtype.UUID{muted, fresh}}
|
||||
require.NoError(t, n.Notify(ctx, notifications.KindRequestRejected, to, nil))
|
||||
require.NoError(t, n.Notify(ctx, notifications.KindNewMusic, to, nil))
|
||||
|
||||
require.Empty(t, rowsFor(t, q, muted), "inbox off is off, whatever phone and email say")
|
||||
require.Len(t, rowsFor(t, q, fresh), 1)
|
||||
@@ -220,7 +239,7 @@ func TestMarkRead_ScopedToTheOwner_AndIdempotent(t *testing.T) {
|
||||
alice := mkUser(t, q, "alice", false)
|
||||
mallory := mkUser(t, q, "mallory", false)
|
||||
n := notifications.New(pool, nil, nil)
|
||||
require.NoError(t, n.Notify(ctx, notifications.KindRequestApproved, notifications.ToUser(alice), nil))
|
||||
require.NoError(t, n.Notify(ctx, notifications.KindNewMusic, notifications.ToUser(alice), nil))
|
||||
id := rowsFor(t, q, alice)[0].ID
|
||||
|
||||
got, err := q.MarkNotificationRead(ctx, dbq.MarkNotificationReadParams{ID: id, UserID: mallory})
|
||||
@@ -271,7 +290,7 @@ func TestRetention_TrimsOldReadRowsAndAncientUnreadOnes(t *testing.T) {
|
||||
readAt = *read
|
||||
}
|
||||
_, err := pool.Exec(ctx,
|
||||
`INSERT INTO user_notifications (user_id, kind, created_at, read_at) VALUES ($1, 'request_approved', $2, $3)`,
|
||||
`INSERT INTO user_notifications (user_id, kind, created_at, read_at) VALUES ($1, 'new_music', $2, $3)`,
|
||||
user, created, readAt)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
@@ -23,19 +23,11 @@ type Rendered struct {
|
||||
// Payload is what producers put in a notification. Every field is optional;
|
||||
// each kind documents the ones it uses in Render.
|
||||
type Payload struct {
|
||||
RequestID string `json:"request_id,omitempty"`
|
||||
RequestKind string `json:"request_kind,omitempty"` // artist | album | track
|
||||
// Name is what was requested or flagged, as the user would say it:
|
||||
// "WWW", "Moe Shop", "Moe Shop – WWW".
|
||||
// Name is what was flagged, as the user would say it: "Moe Shop – WWW".
|
||||
Name string `json:"name,omitempty"`
|
||||
// Artist and Title are Name's parts, for request_completed: the new-music
|
||||
// summary email groups arrivals by artist. Title is empty for an artist
|
||||
// request.
|
||||
Artist string `json:"artist,omitempty"`
|
||||
Title string `json:"title,omitempty"`
|
||||
ArtistID string `json:"artist_id,omitempty"`
|
||||
AlbumID string `json:"album_id,omitempty"`
|
||||
// Actor is the other person involved: who asked, who flagged.
|
||||
// Albums are new_music's arrivals, the first AlbumsKept of Count.
|
||||
Albums []Arrival `json:"albums,omitempty"`
|
||||
// Actor is the other person involved: who flagged.
|
||||
Actor string `json:"actor,omitempty"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
// Count is the coalesced kinds' running total since the notice was last
|
||||
@@ -50,6 +42,18 @@ type Payload struct {
|
||||
Detail string `json:"detail,omitempty"`
|
||||
}
|
||||
|
||||
// Arrival is one album new to the library.
|
||||
type Arrival struct {
|
||||
Artist string `json:"artist"`
|
||||
Title string `json:"title"`
|
||||
ArtistID string `json:"artist_id,omitempty"`
|
||||
AlbumID string `json:"album_id,omitempty"`
|
||||
}
|
||||
|
||||
// AlbumsKept is how many arrivals a new_music notice carries. The count says
|
||||
// how many there were in all.
|
||||
const AlbumsKept = 50
|
||||
|
||||
// Map turns a Payload into the map Notify takes, dropping empty fields.
|
||||
func (p Payload) Map() map[string]any {
|
||||
b, _ := json.Marshal(p)
|
||||
@@ -65,33 +69,12 @@ func Render(kind Kind, payload []byte) Rendered {
|
||||
_ = json.Unmarshal(payload, &p)
|
||||
name := p.Name
|
||||
if name == "" {
|
||||
name = "Your request"
|
||||
name = "A track"
|
||||
}
|
||||
|
||||
switch kind {
|
||||
case KindRequestApproved:
|
||||
return Rendered{Title: "Request approved", Body: name + " is on its way.", Link: "/requests"}
|
||||
case KindRequestRejected:
|
||||
body := name + " was declined."
|
||||
if p.Reason != "" {
|
||||
body = name + " was declined: " + p.Reason
|
||||
}
|
||||
return Rendered{Title: "Request declined", Body: body, Link: "/requests"}
|
||||
case KindRequestCompleted:
|
||||
link := "/requests"
|
||||
switch {
|
||||
case p.AlbumID != "":
|
||||
link = "/albums/" + p.AlbumID
|
||||
case p.ArtistID != "":
|
||||
link = "/artists/" + p.ArtistID
|
||||
}
|
||||
return Rendered{Title: "Now in your library", Body: name + " has arrived.", Link: link}
|
||||
case KindRequestPending:
|
||||
who := p.Actor
|
||||
if who == "" {
|
||||
who = "Someone"
|
||||
}
|
||||
return Rendered{Title: "Request to review", Body: who + " asked for " + name + ".", Link: "/admin/requests"}
|
||||
case KindNewMusic:
|
||||
return renderNewMusic(p)
|
||||
case KindQuarantineFlagged:
|
||||
who := p.Actor
|
||||
if who == "" {
|
||||
@@ -160,6 +143,38 @@ func Render(kind Kind, payload []byte) Rendered {
|
||||
}
|
||||
}
|
||||
|
||||
// renderNewMusic: a single album opens itself; several open Home, whose
|
||||
// Recently added row starts with them.
|
||||
func renderNewMusic(p Payload) Rendered {
|
||||
total := max(p.Count, int64(len(p.Albums)))
|
||||
if total == 1 && len(p.Albums) == 1 {
|
||||
a := p.Albums[0]
|
||||
link := "/"
|
||||
if a.AlbumID != "" {
|
||||
link = "/albums/" + a.AlbumID
|
||||
}
|
||||
return Rendered{Title: "New album", Body: TrackLabel(a.Artist, a.Title) + " is in the library.", Link: link}
|
||||
}
|
||||
labels := make([]string, 0, min(len(p.Albums), namesShown))
|
||||
for _, a := range p.Albums[:min(len(p.Albums), namesShown)] {
|
||||
labels = append(labels, TrackLabel(a.Artist, a.Title))
|
||||
}
|
||||
body := "New albums are in the library."
|
||||
if names := nameList(labels, total); names != "" {
|
||||
body = "Now in the library: " + names + "."
|
||||
}
|
||||
return Rendered{Title: plural(total, "new album", "new albums"), Body: body, Link: "/"}
|
||||
}
|
||||
|
||||
// TrackLabel names a track or album as a notice does: "Artist – Title", or
|
||||
// the title alone when the artist is unknown.
|
||||
func TrackLabel(artist, title string) string {
|
||||
if artist == "" {
|
||||
return title
|
||||
}
|
||||
return artist + " – " + title
|
||||
}
|
||||
|
||||
// namesShown is how many of a notice's items its body names.
|
||||
const namesShown = 3
|
||||
|
||||
|
||||
@@ -25,16 +25,25 @@ func TestRender_EveryKindHasATitleAndALink(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRender_RequestCompletedLinksToWhatArrived(t *testing.T) {
|
||||
require.Equal(t, "/albums/al-1", render(KindRequestCompleted, Payload{Name: "WWW", AlbumID: "al-1", ArtistID: "ar-1"}).Link)
|
||||
require.Equal(t, "/artists/ar-1", render(KindRequestCompleted, Payload{Name: "Moe Shop", ArtistID: "ar-1"}).Link)
|
||||
require.Equal(t, "/requests", render(KindRequestCompleted, Payload{Name: "WWW"}).Link)
|
||||
require.Equal(t, "WWW has arrived.", render(KindRequestCompleted, Payload{Name: "WWW"}).Body)
|
||||
func TestRender_NewMusicOpensWhatArrived(t *testing.T) {
|
||||
one := render(KindNewMusic, Payload{Count: 1, Albums: []Arrival{{Artist: "Moe Shop", Title: "WWW", AlbumID: "al-1"}}})
|
||||
require.Equal(t, "New album", one.Title)
|
||||
require.Equal(t, "Moe Shop – WWW is in the library.", one.Body)
|
||||
require.Equal(t, "/albums/al-1", one.Link)
|
||||
|
||||
// Several open Home, whose Recently added row starts with them; the
|
||||
// count, not only the albums carried, is what "more" counts.
|
||||
many := render(KindNewMusic, Payload{Count: 60, Albums: []Arrival{
|
||||
{Artist: "A", Title: "1"}, {Artist: "B", Title: "2"}, {Artist: "C", Title: "3"}, {Artist: "D", Title: "4"},
|
||||
}})
|
||||
require.Equal(t, "60 new albums", many.Title)
|
||||
require.Equal(t, "Now in the library: A – 1, B – 2, C – 3 and 57 more.", many.Body)
|
||||
require.Equal(t, "/", many.Link)
|
||||
}
|
||||
|
||||
func TestRender_RejectionCarriesTheReasonWhenThereIsOne(t *testing.T) {
|
||||
require.Equal(t, "WWW was declined.", render(KindRequestRejected, Payload{Name: "WWW"}).Body)
|
||||
require.Equal(t, "WWW was declined: already owned", render(KindRequestRejected, Payload{Name: "WWW", Reason: "already owned"}).Body)
|
||||
func TestRender_FlagCarriesTheReasonWhenThereIsOne(t *testing.T) {
|
||||
require.Equal(t, "Ann flagged WWW.", render(KindQuarantineFlagged, Payload{Name: "WWW", Actor: "Ann"}).Body)
|
||||
require.Equal(t, "Ann flagged WWW: bad rip", render(KindQuarantineFlagged, Payload{Name: "WWW", Actor: "Ann", Reason: "bad rip"}).Body)
|
||||
}
|
||||
|
||||
func TestRender_CoalescedCountsReadNaturally(t *testing.T) {
|
||||
@@ -76,9 +85,9 @@ func TestRender_AScanFailureSaysWhatStopped(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestRender_AnUnreadablePayloadStillRenders(t *testing.T) {
|
||||
r := Render(KindRequestApproved, []byte(`not json`))
|
||||
require.Equal(t, "Request approved", r.Title)
|
||||
require.Equal(t, "Your request is on its way.", r.Body)
|
||||
r := Render(KindQuarantineFlagged, []byte(`not json`))
|
||||
require.Equal(t, "Track flagged", r.Title)
|
||||
require.Equal(t, "Someone flagged A track.", r.Body)
|
||||
}
|
||||
|
||||
func TestPayloadMap_DropsEmptyFields(t *testing.T) {
|
||||
|
||||
Reference in New Issue
Block a user