Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Add Space drip emails

Anand Baburajand8756d8706af
diff --git a/server/cmd/museum/main.go b/server/cmd/museum/main.go
index f24753b645..45cf2a7bd2 100644
--- a/server/cmd/museum/main.go
+++ b/server/cmd/museum/main.go
@@ -981,6 +981,7 @@ func main() {
spaceRepos := spacerepo.NewModule(db, s3Config)
userController.SpaceAccessResetter = spaceRepos
spaceModule := spacecontroller.NewModule(spaceRepos, userAuthRepo, &spacecontroller.SpaceEmailSender{UserRepo: userRepo})
+ spaceDripController := spacecontroller.NewSpaceDripController(spaceRepos, userRepo, notificationHistoryRepo, lockController)
spaceModule.UserTokens = userController
spaceHandlers := spaceapi.NewHandlers(spaceModule)
spacePrivateAPI := server.Group("/")
@@ -1067,7 +1068,7 @@ func main() {
setupAndStartCrons(
userAuthRepo, collectionLinkRepo, fileLinkRepo, pasteRepo, twoFactorRepo, passkeysRepo, fileController, taskLockingRepo, emailNotificationCtrl,
trashController, pushController, objectController, dataCleanupController, storageBonusCtrl, emergencyCtrl,
- embeddingController, healthCheckHandler, castDb, inactiveUserOrchestrator)
+ embeddingController, healthCheckHandler, castDb, inactiveUserOrchestrator, spaceDripController)
// Create new collectors, the names will be used as labels on the metrics
primaryDBCollector := sqlstats.NewStatsCollector("prod_db", db)
@@ -1255,7 +1256,8 @@ func setupAndStartCrons(userAuthRepo *repo.UserAuthRepository, collectionLinkRep
embeddingCtrl *embeddingCtrl.Controller,
healthCheckHandler *api.HealthCheckHandler,
castDb castRepo.Repository,
- inactiveUserOrchestrator *user.InactiveUserOrchestrator) {
+ inactiveUserOrchestrator *user.InactiveUserOrchestrator,
+ spaceDripController *spacecontroller.SpaceDripController) {
if viper.GetBool("jobs.cron.skip") {
log.Info("Skipping cron jobs")
return
@@ -1371,6 +1373,10 @@ func setupAndStartCrons(userAuthRepo *repo.UserAuthRepository, collectionLinkRep
emailNotificationCtrl.SendStorageWarningMails()
})
+ schedule(c, "@every 24h", func() {
+ spaceDripController.ProcessSpaceDrips()
+ })
+
schedule(c, "@every 1m", func() {
pushController.SendPushes()
})
diff --git a/server/mail-templates/space_drip.html b/server/mail-templates/space_drip.html
new file mode 100644
index 0000000000..5f5ce1210d
--- /dev/null
+++ b/server/mail-templates/space_drip.html
@@ -0,0 +1,102 @@
+<!DOCTYPE html>
+<html>
+<head>
+<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
+<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
+<title>Ente Space</title>
+<style>
+ @media screen and (max-width: 480px) {
+ .space-shell {
+ padding-left: 12px !important;
+ padding-right: 12px !important;
+ }
+
+ .space-card {
+ padding-left: 18px !important;
+ padding-right: 18px !important;
+ }
+ }
+
+ .footer-icons {
+ padding: 4px !important;
+ width: 24px !important;
+ }
+</style>
+</head>
+<body style="background-color: #f0f1f3; color: #232323; font-family: 'Helvetica Neue', Arial, Helvetica, sans-serif; margin: 0; padding: 0; -ms-text-size-adjust: 100%; -webkit-text-size-adjust: 100%;">
+<table role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#f0f1f3" style="background-color: #f0f1f3; border-collapse: collapse; margin: 0; width: 100%;">
+ <tr>
+ <td align="center" class="space-shell" style="padding: 40px 20px 0;">
+ <table role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0" style="border-collapse: separate; border-spacing: 0; max-width: 420px; width: 100%;">
+ <tr>
+ <td align="center" class="space-card" bgcolor="#ffffff" style="background-color: #ffffff; border-radius: 24px; color: #232323; font-family: 'Helvetica Neue', Arial, Helvetica, sans-serif; padding: 30px 28px 24px; text-align: center;">
+ <table role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0" style="border-collapse: collapse; width: 100%;">
+ {{if .IllustrationURL}}
+ <tr>
+ <td align="center" style="padding: 0 0 24px;">
+ <img src="{{ .IllustrationURL }}" width="{{ .IllustrationWidth }}" alt="" style="border: 0; display: block; height: auto; margin: 0 auto; max-width: 100%; outline: none; text-decoration: none; width: {{ .IllustrationWidth }}px;" />
+ </td>
+ </tr>
+ {{end}}
+ <tr>
+ <td align="left" style="color: #5f5f5f; font-family: 'Helvetica Neue', Arial, Helvetica, sans-serif; font-size: 15px; line-height: 22px; padding: 0 0 {{if .CTALabel}}22px{{else}}0{{end}}; text-align: left;">
+ {{range .BodyLines}}
+ <p style="margin: 0 0 12px;">{{.}}</p>
+ {{end}}
+ </td>
+ </tr>
+ {{if .CTALabel}}
+ <tr>
+ <td align="center">
+ <table role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0" style="border-collapse: separate; border-spacing: 0; width: 100%;">
+ <tr>
+ <td align="center" bgcolor="#08C225" style="background-color: #08C225; border-radius: 16px;">
+ <a href="{{ .CTAURL }}" target="_blank" style="background-color: #08C225; border-radius: 16px; color: #ffffff !important; display: block; font-family: 'Helvetica Neue', Arial, Helvetica, sans-serif; font-size: 14px; font-weight: 700; line-height: 20px; padding: 16px 28px; text-align: center; text-decoration: none !important;">{{ .CTALabel }}</a>
+ </td>
+ </tr>
+ </table>
+ </td>
+ </tr>
+ {{end}}
+ </table>
+ </td>
+ </tr>
+ </table>
+ </td>
+ </tr>
+</table>
+<br />
+<div class="footer" style="text-align: center; font-size: 12px; color:
+ rgb(136, 136, 136)" >
+ <div>
+ <a href="https://ente.com" target="_blank" ><img
+ src="https://email-assets.ente.com/ente-2026-green.png" style="width: 100px;
+ padding: 24px" title="Ente" alt="Ente" /></a>
+ </div>
+ <div>
+ <a href="https://fosstodon.org/@ente" target="_blank" ><img
+ src="https://email-assets.ente.com/mastodon-icon.png"
+ class="footer-icons" style="width: 24px; padding: 4px" title="Mastodon"
+ alt="Mastodon" /></a>
+ <a href="https://twitter.com/enteio" target="_blank" ><img
+ src="https://email-assets.ente.com/twitter-icon.png" class="footer-icons"
+ style="width: 24px; padding: 4px" title="Twitter" alt="Twitter" /></a>
+ <a href="https://ente.com/discord" target="_blank" ><img
+ src="https://email-assets.ente.com/discord-icon.png" class="footer-icons"
+ style="width: 24px; padding: 4px" title="Discord" alt="Discord" /></a>
+ <a href="https://github.com/ente-io" target="_blank" ><img
+ src="https://email-assets.ente.com/github-icon.png" class="footer-icons"
+ style="width: 24px; padding: 4px" title="GitHub" alt="GitHub" /></a>
+
+ <a href="https://www.youtube.com/@entestudio" target="_blank" ><img
+ src="https://email-assets.ente.com/youtube-icon.png" class="footer-icons"
+ style="width: 24px; padding: 4px" title="YouTube" alt="YouTube" /></a>
+ </div>
+ <p>
+ Ente Technologies, Inc.
+ <br /> 1111B S Governors Ave 6032 Dover, DE 19904
+ </p>
+ <br />
+</div>
+</body>
+</html>
diff --git a/server/pkg/utils/email/space_notification_template_test.go b/server/pkg/utils/email/space_notification_template_test.go
index 81bcc61a90..2d640fb012 100644
--- a/server/pkg/utils/email/space_notification_template_test.go
+++ b/server/pkg/utils/email/space_notification_template_test.go
@@ -29,3 +29,45 @@ func TestSpaceNotificationTemplateUsesEmailSafeLayout(t *testing.T) {
require.Contains(t, body, `padding: 24px" title="Ente"`)
require.Contains(t, body, `class="footer-icons" style="width: 24px; padding: 4px"`)
}
+
+func TestSpaceDripTemplateRendersCTAAndBody(t *testing.T) {
+ testutil.WithServerRoot(t)
+
+ body, err := getMailBody("space_drip.html", map[string]interface{}{
+ "BodyLines": []string{
+ "Hey,",
+ "Your Ente Space profile is still unfinished.",
+ },
+ "CTAURL": "https://ente.space/app",
+ "CTALabel": "Finish setup",
+ })
+ require.NoError(t, err)
+ require.Contains(t, body, `role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0" bgcolor="#f0f1f3"`)
+ require.Contains(t, body, `max-width: 420px; width: 100%;`)
+ require.Contains(t, body, `align="left" style="color: #5f5f5f;`)
+ require.Contains(t, body, "Your Ente Space profile is still unfinished.")
+ require.Contains(t, body, `style="border-collapse: separate; border-spacing: 0; width: 100%;"`)
+ require.Contains(t, body, `href="https://ente.space/app"`)
+ require.Contains(t, body, "Finish setup")
+ require.Contains(t, body, `https://email-assets.ente.com/ente-2026-green.png`)
+ require.Contains(t, body, `class="footer-icons" style="width: 24px; padding: 4px"`)
+ require.Contains(t, body, "Ente Technologies, Inc.")
+}
+
+func TestSpaceDripTemplateOmitsCTAWithoutLabel(t *testing.T) {
+ testutil.WithServerRoot(t)
+
+ body, err := getMailBody("space_drip.html", map[string]interface{}{
+ "BodyLines": []string{
+ "Hey,",
+ "Reply to this email or drop a message on our Discord!",
+ },
+ "CTAURL": "https://ente.space/app",
+ })
+ require.NoError(t, err)
+ require.Contains(t, body, "Reply to this email or drop a message on our Discord!")
+ require.Contains(t, body, `padding: 0 0 0; text-align: left;`)
+ require.NotContains(t, body, `href="https://ente.space/app"`)
+ require.NotContains(t, body, `Open Ente Space`)
+ require.Contains(t, body, `https://email-assets.ente.com/ente-2026-green.png`)
+}
diff --git a/server/space/controller/drips.go b/server/space/controller/drips.go
new file mode 100644
index 0000000000..b3c193892d
--- /dev/null
+++ b/server/space/controller/drips.go
@@ -0,0 +1,222 @@
+package controller
+
+import (
+ "context"
+ "fmt"
+ "strings"
+
+ lockctrl "github.com/ente-io/museum/pkg/controller/lock"
+ baserepo "github.com/ente-io/museum/pkg/repo"
+ emailutil "github.com/ente-io/museum/pkg/utils/email"
+ timeutil "github.com/ente-io/museum/pkg/utils/time"
+ spacerepo "github.com/ente-io/museum/space/repo"
+ log "github.com/sirupsen/logrus"
+)
+
+const (
+ SpaceDripProfileMissing24hTemplateID = "space_profile_missing_24h"
+ SpaceDripProfileMissing4dTemplateID = "space_profile_missing_4d"
+ SpaceDripInvitePeople24hTemplateID = "space_invite_people_24h"
+ SpaceDripInvitePeople4dTemplateID = "space_invite_people_4d"
+ SpaceDripFirstPost24hTemplateID = "space_first_post_24h"
+ SpaceDripFirstPost4dTemplateID = "space_first_post_4d"
+ SpaceDripFeedback7dTemplateID = "space_feedback_7d"
+
+ spaceDripTemplate = "space_drip.html"
+ spaceDripMailLock = "space_drip_mail_lock"
+ spaceDripDefaultBatchSize = 500
+)
+
+var sendSpaceDripEmail = emailutil.SendTemplatedEmail
+
+type SpaceDripController struct {
+ DripsRepo *spacerepo.DripsRepository
+ UserRepo *baserepo.UserRepository
+ NotificationHistoryRepo *baserepo.NotificationHistoryRepository
+ LockController *lockctrl.LockController
+ BatchSize int
+}
+
+type spaceDripStage struct {
+ TemplateID string
+ Subject string
+ BodyLines []string
+ CTALabel string
+ Candidates func(context.Context, int64, int) ([]spacerepo.SpaceDripCandidate, error)
+}
+
+type spaceDripRunStats struct {
+ SentByTemplate map[string]int
+}
+
+func NewSpaceDripController(repos *spacerepo.Module, userRepo *baserepo.UserRepository, notificationHistoryRepo *baserepo.NotificationHistoryRepository, lockController *lockctrl.LockController) *SpaceDripController {
+ return &SpaceDripController{
+ DripsRepo: repos.Drips,
+ UserRepo: userRepo,
+ NotificationHistoryRepo: notificationHistoryRepo,
+ LockController: lockController,
+ }
+}
+
+func (c *SpaceDripController) ProcessSpaceDrips() {
+ if c == nil || c.DripsRepo == nil || c.UserRepo == nil || c.NotificationHistoryRepo == nil {
+ log.Error("Skipping space drip emails because dependencies are missing")
+ return
+ }
+ if c.LockController != nil {
+ if !c.LockController.TryLock(spaceDripMailLock, timeutil.MicrosecondsAfterHours(24)) {
+ log.Info("Skipping space drip emails because another instance is running")
+ return
+ }
+ defer c.LockController.ReleaseLock(spaceDripMailLock)
+ }
+ stats, err := c.processSpaceDrips(context.Background(), timeutil.Microseconds())
+ if err != nil {
+ log.WithError(err).Error("Failed to process space drip emails")
+ return
+ }
+ log.WithField("sent_by_template", stats.SentByTemplate).Info("Processed space drip emails")
+}
+
+func (c *SpaceDripController) processSpaceDrips(ctx context.Context, now int64) (spaceDripRunStats, error) {
+ stats := spaceDripRunStats{SentByTemplate: map[string]int{}}
+ handledThisRun := map[int64]struct{}{}
+ batchSize := c.BatchSize
+ if batchSize <= 0 {
+ batchSize = spaceDripDefaultBatchSize
+ }
+ for _, stage := range c.spaceDripStages() {
+ sent, err := c.processSpaceDripStage(ctx, stage, now, batchSize, handledThisRun)
+ if err != nil {
+ return stats, err
+ }
+ if sent > 0 {
+ stats.SentByTemplate[stage.TemplateID] = sent
+ }
+ }
+ return stats, nil
+}
+
+func (c *SpaceDripController) spaceDripStages() []spaceDripStage {
+ day := int64(24) * timeutil.MicroSecondsInOneHour
+ return []spaceDripStage{
+ {
+ TemplateID: SpaceDripProfileMissing4dTemplateID,
+ Subject: "Your Space setup is incomplete",
+ BodyLines: []string{"Hey,", "Your Ente Space setup is still incomplete.", "Finish your profile to start sharing everyday photos privately with friends and family.", "If anything feels unclear, reply here and we'll help!"},
+ CTALabel: "Finish setup",
+ Candidates: func(ctx context.Context, now int64, limit int) ([]spacerepo.SpaceDripCandidate, error) {
+ return c.DripsRepo.ListProfileMissingCandidates(ctx, now, now-4*day, []string{SpaceDripProfileMissing4dTemplateID}, limit)
+ },
+ },
+ {
+ TemplateID: SpaceDripProfileMissing24hTemplateID,
+ Subject: "Finish setting up Ente Space",
+ BodyLines: []string{"Hey,", "You're almost done setting up Ente Space.", "Finish your profile to start sharing everyday photos with friends and family."},
+ CTALabel: "Finish setup",
+ Candidates: func(ctx context.Context, now int64, limit int) ([]spacerepo.SpaceDripCandidate, error) {
+ return c.DripsRepo.ListProfileMissingCandidates(ctx, now, now-day, []string{SpaceDripProfileMissing24hTemplateID, SpaceDripProfileMissing4dTemplateID}, limit)
+ },
+ },
+ {
+ TemplateID: SpaceDripInvitePeople4dTemplateID,
+ Subject: "Add close friends and family",
+ BodyLines: []string{"Hey,", "You haven't invited anyone to your Space yet.", "Start with close friends or family you'd like to share everyday photos with. You can add more people later.", "If anything feels unclear, reply here and we'll help!"},
+ CTALabel: "Open Ente Space",
+ Candidates: func(ctx context.Context, now int64, limit int) ([]spacerepo.SpaceDripCandidate, error) {
+ return c.DripsRepo.ListInvitePeopleCandidates(ctx, now-4*day, []string{SpaceDripInvitePeople4dTemplateID}, limit)
+ },
+ },
+ {
+ TemplateID: SpaceDripInvitePeople24hTemplateID,
+ Subject: "Invite friends and family",
+ BodyLines: []string{"Hey,", "Your space is ready!", "Invite friends and family to share everyday photos privately."},
+ CTALabel: "Open Ente Space",
+ Candidates: func(ctx context.Context, now int64, limit int) ([]spacerepo.SpaceDripCandidate, error) {
+ return c.DripsRepo.ListInvitePeopleCandidates(ctx, now-day, []string{SpaceDripInvitePeople24hTemplateID, SpaceDripInvitePeople4dTemplateID}, limit)
+ },
+ },
+ {
+ TemplateID: SpaceDripFirstPost4dTemplateID,
+ Subject: "Share a recent photo",
+ BodyLines: []string{"Hey,", "You haven't posted to your Space yet.", "Pick something recent and share it. It doesn't need to be perfect!", "If anything feels unclear, reply here and we'll help!"},
+ CTALabel: "Open Ente Space",
+ Candidates: func(ctx context.Context, now int64, limit int) ([]spacerepo.SpaceDripCandidate, error) {
+ return c.DripsRepo.ListFirstPostCandidates(ctx, now-4*day, []string{SpaceDripFirstPost4dTemplateID}, limit)
+ },
+ },
+ {
+ TemplateID: SpaceDripFirstPost24hTemplateID,
+ Subject: "Share your first photo",
+ BodyLines: []string{"Hey,", "You've got people in your Space now!", "Share something recent with them."},
+ CTALabel: "Open Ente Space",
+ Candidates: func(ctx context.Context, now int64, limit int) ([]spacerepo.SpaceDripCandidate, error) {
+ return c.DripsRepo.ListFirstPostCandidates(ctx, now-day, []string{SpaceDripFirstPost24hTemplateID, SpaceDripFirstPost4dTemplateID}, limit)
+ },
+ },
+ {
+ TemplateID: SpaceDripFeedback7dTemplateID,
+ Subject: "Thoughts on Ente Space?",
+ BodyLines: []string{"Hey,", "You've been using Ente Space for a few days.", "What do you love about it? What should we improve?", "Reply to this email or drop a message on our Discord!"},
+ Candidates: func(ctx context.Context, now int64, limit int) ([]spacerepo.SpaceDripCandidate, error) {
+ return c.DripsRepo.ListFeedbackCandidates(ctx, now-7*day, []string{SpaceDripFeedback7dTemplateID}, limit)
+ },
+ },
+ }
+}
+
+func (c *SpaceDripController) processSpaceDripStage(ctx context.Context, stage spaceDripStage, now int64, limit int, handledThisRun map[int64]struct{}) (int, error) {
+ candidates, err := stage.Candidates(ctx, now, limit)
+ if err != nil {
+ return 0, err
+ }
+ userIDs := make([]int64, 0, len(candidates))
+ for _, candidate := range candidates {
+ if _, handled := handledThisRun[candidate.UserID]; handled {
+ continue
+ }
+ userIDs = append(userIDs, candidate.UserID)
+ }
+ if len(userIDs) == 0 {
+ return 0, nil
+ }
+ users, err := c.UserRepo.GetActiveUsersForIds(userIDs)
+ if err != nil {
+ return 0, err
+ }
+ sent := 0
+ for _, candidate := range candidates {
+ if _, alreadyHandled := handledThisRun[candidate.UserID]; alreadyHandled {
+ continue
+ }
+ handledThisRun[candidate.UserID] = struct{}{}
+ user := users[candidate.UserID]
+ if user == nil || strings.TrimSpace(user.Email) == "" {
+ continue
+ }
+ if err := sendSpaceDripEmail(
+ []string{user.Email},
+ "Ente",
+ stage.Subject,
+ spaceDripTemplate,
+ map[string]interface{}{
+ "BodyLines": stage.BodyLines,
+ "CTAURL": spaceAppURL(),
+ "CTALabel": stage.CTALabel,
+ },
+ nil,
+ ); err != nil {
+ log.WithFields(log.Fields{
+ "user_id": candidate.UserID,
+ "template_id": stage.TemplateID,
+ }).WithError(err).Error("Error sending space drip email")
+ continue
+ }
+ sent++
+ if err := c.NotificationHistoryRepo.SetLastNotificationTimeToNow(candidate.UserID, stage.TemplateID); err != nil {
+ return sent, fmt.Errorf("failed to record space drip history for user %d template %s: %w", candidate.UserID, stage.TemplateID, err)
+ }
+ }
+ return sent, nil
+}
diff --git a/server/space/controller/drips_test.go b/server/space/controller/drips_test.go
new file mode 100644
index 0000000000..f38805d64d
--- /dev/null
+++ b/server/space/controller/drips_test.go
@@ -0,0 +1,118 @@
+package controller
+
+import (
+ "context"
+ "errors"
+ "testing"
+
+ "github.com/ente-io/museum/internal/testutil"
+ baserepo "github.com/ente-io/museum/pkg/repo"
+ timeutil "github.com/ente-io/museum/pkg/utils/time"
+ spacerepo "github.com/ente-io/museum/space/repo"
+ "github.com/stretchr/testify/require"
+)
+
+func TestSpaceDripsSendMatureProfileNudgeOnly(t *testing.T) {
+ testutil.WithServerRoot(t)
+ db := testutil.RequireTestDB(t)
+ testutil.ResetTables(t, db)
+ t.Cleanup(func() {
+ testutil.ResetTables(t, db)
+ })
+
+ ctx := context.Background()
+ repos := spacerepo.NewModule(db, nil)
+ now := timeutil.Microseconds()
+ userID := insertSpaceControllerUser(t, repos, "[email protected]", "profile-drip-public")
+ require.NoError(t, repos.Sessions.CreateBrowserSession(ctx, []byte("profile-drip-token-hash"), userID, "wrap-key", now+timeutil.MicroSecondsInOneHour))
+ _, err := repos.Sessions.DB.Exec(`
+ UPDATE space_browser_sessions
+ SET created_at = $1, updated_at = $1, last_used_at = $1
+ WHERE user_id = $2
+ `, now-5*24*timeutil.MicroSecondsInOneHour, userID)
+ require.NoError(t, err)
+
+ originalSend := sendSpaceDripEmail
+ t.Cleanup(func() {
+ sendSpaceDripEmail = originalSend
+ })
+ var subjects []string
+ sendSpaceDripEmail = func(_ []string, _ string, _ string, subject string, _ string, _ map[string]interface{}, _ []map[string]interface{}) error {
+ subjects = append(subjects, subject)
+ return nil
+ }
+
+ controller := &SpaceDripController{
+ DripsRepo: repos.Drips,
+ UserRepo: &baserepo.UserRepository{
+ DB: db,
+ SecretEncryptionKey: testutil.SecretEncryptionKey(),
+ HashingKey: testutil.HashingKey(),
+ },
+ NotificationHistoryRepo: &baserepo.NotificationHistoryRepository{DB: db},
+ BatchSize: 10,
+ }
+ stats, err := controller.processSpaceDrips(ctx, now)
+ require.NoError(t, err)
+ require.Equal(t, []string{"Your Space setup is incomplete"}, subjects)
+ require.Equal(t, 1, stats.SentByTemplate[SpaceDripProfileMissing4dTemplateID])
+
+ history, err := controller.NotificationHistoryRepo.GetLastNotificationTimes(userID, []string{
+ SpaceDripProfileMissing24hTemplateID,
+ SpaceDripProfileMissing4dTemplateID,
+ })
+ require.NoError(t, err)
+ require.Zero(t, history[SpaceDripProfileMissing24hTemplateID])
+ require.NotZero(t, history[SpaceDripProfileMissing4dTemplateID])
+
+ stats, err = controller.processSpaceDrips(ctx, now+timeutil.MicroSecondsInOneHour)
+ require.NoError(t, err)
+ require.Empty(t, stats.SentByTemplate)
+ require.Len(t, subjects, 1)
+}
+
+func TestSpaceDripsDoNotFallBackToEarlierStageAfterSendFailure(t *testing.T) {
+ testutil.WithServerRoot(t)
+ db := testutil.RequireTestDB(t)
+ testutil.ResetTables(t, db)
+ t.Cleanup(func() {
+ testutil.ResetTables(t, db)
+ })
+
+ ctx := context.Background()
+ repos := spacerepo.NewModule(db, nil)
+ now := timeutil.Microseconds()
+ userID := insertSpaceControllerUser(t, repos, "[email protected]", "profile-drip-failure-public")
+ require.NoError(t, repos.Sessions.CreateBrowserSession(ctx, []byte("profile-drip-failure-token-hash"), userID, "wrap-key", now+timeutil.MicroSecondsInOneHour))
+ _, err := repos.Sessions.DB.Exec(`
+ UPDATE space_browser_sessions
+ SET created_at = $1, updated_at = $1, last_used_at = $1
+ WHERE user_id = $2
+ `, now-5*24*timeutil.MicroSecondsInOneHour, userID)
+ require.NoError(t, err)
+
+ originalSend := sendSpaceDripEmail
+ t.Cleanup(func() {
+ sendSpaceDripEmail = originalSend
+ })
+ var subjects []string
+ sendSpaceDripEmail = func(_ []string, _ string, _ string, subject string, _ string, _ map[string]interface{}, _ []map[string]interface{}) error {
+ subjects = append(subjects, subject)
+ return errors.New("send failed")
+ }
+
+ controller := &SpaceDripController{
+ DripsRepo: repos.Drips,
+ UserRepo: &baserepo.UserRepository{
+ DB: db,
+ SecretEncryptionKey: testutil.SecretEncryptionKey(),
+ HashingKey: testutil.HashingKey(),
+ },
+ NotificationHistoryRepo: &baserepo.NotificationHistoryRepository{DB: db},
+ BatchSize: 10,
+ }
+ stats, err := controller.processSpaceDrips(ctx, now)
+ require.NoError(t, err)
+ require.Empty(t, stats.SentByTemplate)
+ require.Equal(t, []string{"Your Space setup is incomplete"}, subjects)
+}
diff --git a/server/space/repo/drips.go b/server/space/repo/drips.go
new file mode 100644
index 0000000000..3df2a4b0c6
--- /dev/null
+++ b/server/space/repo/drips.go
@@ -0,0 +1,178 @@
+package repo
+
+import (
+ "context"
+ "database/sql"
+
+ "github.com/ente-io/stacktrace"
+ "github.com/lib/pq"
+)
+
+const defaultSpaceDripCandidateLimit = 500
+
+type SpaceDripCandidate struct {
+ UserID int64
+}
+
+func spaceDripCandidateLimit(limit int) int {
+ if limit <= 0 {
+ return defaultSpaceDripCandidateLimit
+ }
+ if limit > defaultSpaceDripCandidateLimit {
+ return defaultSpaceDripCandidateLimit
+ }
+ return limit
+}
+
+func scanSpaceDripCandidates(rows *sql.Rows) ([]SpaceDripCandidate, error) {
+ defer rows.Close()
+ var out []SpaceDripCandidate
+ for rows.Next() {
+ var candidate SpaceDripCandidate
+ if err := rows.Scan(&candidate.UserID); err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ out = append(out, candidate)
+ }
+ return out, stacktrace.Propagate(rows.Err(), "")
+}
+
+func (r *DripsRepository) ListProfileMissingCandidates(ctx context.Context, now int64, threshold int64, excludeTemplateIDs []string, limit int) ([]SpaceDripCandidate, error) {
+ rows, err := r.DB.QueryContext(ctx, `
+ SELECT s.user_id
+ FROM space_browser_sessions s
+ JOIN users u ON u.user_id = s.user_id AND u.encrypted_email IS NOT NULL
+ WHERE s.created_at <= $1
+ AND s.expires_at > $2
+ AND NOT EXISTS (
+ SELECT 1
+ FROM spaces owned
+ WHERE owned.owner_id = s.user_id
+ )
+ AND NOT EXISTS (
+ SELECT 1
+ FROM notification_history nh
+ WHERE nh.user_id = s.user_id
+ AND nh.template_id = ANY($3)
+ )
+ GROUP BY s.user_id
+ ORDER BY MIN(s.created_at) ASC, s.user_id ASC
+ LIMIT $4
+ `, threshold, now, pq.Array(excludeTemplateIDs), spaceDripCandidateLimit(limit))
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ return scanSpaceDripCandidates(rows)
+}
+
+func (r *DripsRepository) ListInvitePeopleCandidates(ctx context.Context, threshold int64, excludeTemplateIDs []string, limit int) ([]SpaceDripCandidate, error) {
+ rows, err := r.DB.QueryContext(ctx, `
+ WITH candidate_users AS (
+ SELECT s.owner_id AS user_id, MIN(s.created_at) AS event_at
+ FROM spaces s
+ JOIN users u ON u.user_id = s.owner_id AND u.encrypted_email IS NOT NULL
+ GROUP BY s.owner_id
+ HAVING MIN(s.created_at) <= $1
+ )
+ SELECT c.user_id
+ FROM candidate_users c
+ WHERE NOT EXISTS (
+ SELECT 1
+ FROM notification_history nh
+ WHERE nh.user_id = c.user_id
+ AND nh.template_id = ANY($2)
+ )
+ AND NOT EXISTS (
+ SELECT 1
+ FROM spaces owned
+ JOIN space_friend_shares f ON f.space_id = owned.space_id
+ WHERE owned.owner_id = c.user_id
+ )
+ AND NOT EXISTS (
+ SELECT 1
+ FROM spaces owned
+ JOIN space_friend_requests fr
+ ON fr.requester_space_id = owned.space_id
+ OR fr.target_space_id = owned.space_id
+ WHERE owned.owner_id = c.user_id
+ )
+ ORDER BY c.event_at ASC, c.user_id ASC
+ LIMIT $3
+ `, threshold, pq.Array(excludeTemplateIDs), spaceDripCandidateLimit(limit))
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ return scanSpaceDripCandidates(rows)
+}
+
+func (r *DripsRepository) ListFirstPostCandidates(ctx context.Context, threshold int64, excludeTemplateIDs []string, limit int) ([]SpaceDripCandidate, error) {
+ rows, err := r.DB.QueryContext(ctx, `
+ WITH first_friend AS (
+ SELECT s.owner_id AS user_id, MIN(f.created_at) AS event_at
+ FROM spaces s
+ JOIN users u ON u.user_id = s.owner_id AND u.encrypted_email IS NOT NULL
+ JOIN space_friend_shares f ON f.space_id = s.space_id
+ GROUP BY s.owner_id
+ HAVING MIN(f.created_at) <= $1
+ )
+ SELECT ff.user_id
+ FROM first_friend ff
+ WHERE NOT EXISTS (
+ SELECT 1
+ FROM notification_history nh
+ WHERE nh.user_id = ff.user_id
+ AND nh.template_id = ANY($2)
+ )
+ AND NOT EXISTS (
+ SELECT 1
+ FROM spaces owned
+ JOIN space_posts p ON p.space_id = owned.space_id
+ WHERE owned.owner_id = ff.user_id
+ )
+ ORDER BY ff.event_at ASC, ff.user_id ASC
+ LIMIT $3
+ `, threshold, pq.Array(excludeTemplateIDs), spaceDripCandidateLimit(limit))
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ return scanSpaceDripCandidates(rows)
+}
+
+func (r *DripsRepository) ListFeedbackCandidates(ctx context.Context, threshold int64, excludeTemplateIDs []string, limit int) ([]SpaceDripCandidate, error) {
+ rows, err := r.DB.QueryContext(ctx, `
+ WITH activities AS (
+ SELECT s.owner_id AS user_id, p.created_at AS event_at
+ FROM spaces s
+ JOIN users u ON u.user_id = s.owner_id AND u.encrypted_email IS NOT NULL
+ JOIN space_posts p ON p.space_id = s.space_id
+
+ UNION ALL
+
+ SELECT s.owner_id AS user_id, m.created_at AS event_at
+ FROM spaces s
+ JOIN users u ON u.user_id = s.owner_id AND u.encrypted_email IS NOT NULL
+ JOIN space_messages m ON m.sender_space_id = s.space_id
+ WHERE m.kind = 'post_reply'
+ ),
+ first_activity AS (
+ SELECT user_id, MIN(event_at) AS event_at
+ FROM activities
+ GROUP BY user_id
+ HAVING MIN(event_at) <= $1
+ )
+ SELECT fa.user_id
+ FROM first_activity fa
+ WHERE NOT EXISTS (
+ SELECT 1
+ FROM notification_history nh
+ WHERE nh.user_id = fa.user_id
+ AND nh.template_id = ANY($2)
+ )
+ ORDER BY fa.event_at ASC, fa.user_id ASC
+ LIMIT $3
+ `, threshold, pq.Array(excludeTemplateIDs), spaceDripCandidateLimit(limit))
+ if err != nil {
+ return nil, stacktrace.Propagate(err, "")
+ }
+ return scanSpaceDripCandidates(rows)
+}
diff --git a/server/space/repo/drips_test.go b/server/space/repo/drips_test.go
new file mode 100644
index 0000000000..95b918e112
--- /dev/null
+++ b/server/space/repo/drips_test.go
@@ -0,0 +1,177 @@
+package repo
+
+import (
+ "context"
+ "crypto/sha256"
+ "database/sql"
+ "strconv"
+ "testing"
+
+ "github.com/ente-io/museum/internal/testutil"
+ timeutil "github.com/ente-io/museum/pkg/utils/time"
+ "github.com/stretchr/testify/require"
+)
+
+const (
+ testSpaceDripProfileMissing24h = "space_profile_missing_24h"
+ testSpaceDripProfileMissing4d = "space_profile_missing_4d"
+ testSpaceDripInvitePeople24h = "space_invite_people_24h"
+ testSpaceDripInvitePeople4d = "space_invite_people_4d"
+ testSpaceDripFirstPost24h = "space_first_post_24h"
+ testSpaceDripFirstPost4d = "space_first_post_4d"
+ testSpaceDripFeedback7d = "space_feedback_7d"
+)
+
+func TestProfileMissingDripCandidatesUseSpaceSessionsOnly(t *testing.T) {
+ ctx := context.Background()
+ module := newSpaceTestModule(t)
+ now := timeutil.Microseconds()
+
+ noSessionUserID := insertSpaceUser(t, module, "[email protected]", "no-session-public")
+ oldSessionUserID := insertSpaceUser(t, module, "[email protected]", "old-session-public")
+ recentSessionUserID := insertSpaceUser(t, module, "[email protected]", "recent-session-public")
+ completedProfileUserID := insertSpaceUser(t, module, "[email protected]", "completed-profile-public")
+
+ insertSpaceBrowserSession(t, module, oldSessionUserID, now-25*timeutil.MicroSecondsInOneHour, now+timeutil.MicroSecondsInOneHour)
+ insertSpaceBrowserSession(t, module, recentSessionUserID, now-2*timeutil.MicroSecondsInOneHour, now+timeutil.MicroSecondsInOneHour)
+ insertSpaceBrowserSession(t, module, completedProfileUserID, now-25*timeutil.MicroSecondsInOneHour, now+timeutil.MicroSecondsInOneHour)
+ _, err := testCreateSpace(ctx, module, completedProfileUserID, "completed_profile", "root", "public", "secret", "nonce", "profile")
+ require.NoError(t, err)
+
+ candidates, err := module.Drips.ListProfileMissingCandidates(ctx, now, now-24*timeutil.MicroSecondsInOneHour, []string{testSpaceDripProfileMissing24h, testSpaceDripProfileMissing4d}, 50)
+ require.NoError(t, err)
+ require.Equal(t, []int64{oldSessionUserID}, spaceDripCandidateUserIDs(candidates))
+ require.NotContains(t, spaceDripCandidateUserIDs(candidates), noSessionUserID)
+
+ testutil.InsertNotificationHistory(t, module.Drips.DB, testutil.NotificationHistoryFixture{
+ UserID: oldSessionUserID,
+ TemplateID: testSpaceDripProfileMissing4d,
+ SentTime: now,
+ })
+ candidates, err = module.Drips.ListProfileMissingCandidates(ctx, now, now-24*timeutil.MicroSecondsInOneHour, []string{testSpaceDripProfileMissing24h, testSpaceDripProfileMissing4d}, 50)
+ require.NoError(t, err)
+ require.Empty(t, candidates)
+}
+
+func TestInvitePeopleDripCandidatesRequireNoFriendsOrRequests(t *testing.T) {
+ ctx := context.Background()
+ module := newSpaceTestModule(t)
+ now := timeutil.Microseconds()
+ threshold := now - 24*timeutil.MicroSecondsInOneHour
+
+ readyUserID := insertSpaceUser(t, module, "[email protected]", "ready-public")
+ friendUserID := insertSpaceUser(t, module, "[email protected]", "friend-public")
+ pendingUserID := insertSpaceUser(t, module, "[email protected]", "pending-public")
+ otherUserID := insertSpaceUser(t, module, "[email protected]", "other-public")
+
+ readySpace := mustCreateOldSpace(t, ctx, module, readyUserID, "space_ready", now-2*24*timeutil.MicroSecondsInOneHour)
+ friendSpace := mustCreateOldSpace(t, ctx, module, friendUserID, "space_friend", now-2*24*timeutil.MicroSecondsInOneHour)
+ pendingSpace := mustCreateOldSpace(t, ctx, module, pendingUserID, "space_pending", now-2*24*timeutil.MicroSecondsInOneHour)
+ otherSpace := mustCreateOldSpace(t, ctx, module, otherUserID, "space_other", now-2*24*timeutil.MicroSecondsInOneHour)
+
+ require.NoError(t, testAddFriend(ctx, module, friendUserID, friendSpace.SpaceID, otherSpace.SpaceID, "other-share", otherSpace.CurrentVersion, "friend-share", friendSpace.CurrentVersion))
+ _, _, err := testCreateFriendRequest(ctx, module, pendingUserID, pendingSpace.SpaceID, otherSpace.SpaceID, "pending-share", pendingSpace.CurrentVersion)
+ require.NoError(t, err)
+
+ candidates, err := module.Drips.ListInvitePeopleCandidates(ctx, threshold, []string{testSpaceDripInvitePeople24h, testSpaceDripInvitePeople4d}, 50)
+ require.NoError(t, err)
+ require.Equal(t, []int64{readyUserID}, spaceDripCandidateUserIDs(candidates))
+ require.NotEmpty(t, readySpace.SpaceID)
+}
+
+func TestFirstPostAndFeedbackDripCandidates(t *testing.T) {
+ ctx := context.Background()
+ module := newSpaceTestModule(t)
+ now := timeutil.Microseconds()
+ old := now - 8*24*timeutil.MicroSecondsInOneHour
+
+ aliceID := insertSpaceUser(t, module, "[email protected]", "alice-public")
+ bobID := insertSpaceUser(t, module, "[email protected]", "bob-public")
+ charlieID := insertSpaceUser(t, module, "[email protected]", "charlie-public")
+ aliceSpace := mustCreateOldSpace(t, ctx, module, aliceID, "alice_drips", old)
+ bobSpace := mustCreateOldSpace(t, ctx, module, bobID, "bob_drips", old)
+ charlieSpace := mustCreateOldSpace(t, ctx, module, charlieID, "charlie_drips", old)
+
+ require.NoError(t, testAddFriend(ctx, module, aliceID, aliceSpace.SpaceID, bobSpace.SpaceID, "bob-share", bobSpace.CurrentVersion, "alice-share", aliceSpace.CurrentVersion))
+ setFriendshipCreatedAt(t, module, aliceSpace.SpaceID, bobSpace.SpaceID, old)
+ require.NoError(t, testAddFriend(ctx, module, charlieID, charlieSpace.SpaceID, bobSpace.SpaceID, "bob-charlie-share", bobSpace.CurrentVersion, "charlie-share", charlieSpace.CurrentVersion))
+ setFriendshipCreatedAt(t, module, charlieSpace.SpaceID, bobSpace.SpaceID, old)
+
+ postID, err := testCreatePost(ctx, module, aliceID, aliceSpace.SpaceID, "alice-post-key", nil, aliceSpace.CurrentVersion, nil)
+ require.NoError(t, err)
+ setPostCreatedAt(t, module, old, postID)
+ _, err = module.Messages.CreateMessage(ctx, CreateSpaceMessageRecord{
+ Kind: "post_reply",
+ SenderSpaceID: bobSpace.SpaceID,
+ RecipientSpaceID: aliceSpace.SpaceID,
+ MessageCipher: testSpaceBytes("reply-cipher"),
+ SenderEncryptedMessageKey: testSpaceBytes("reply-sender-key"),
+ RecipientEncryptedMessageKey: testSpaceBytes("reply-recipient-key"),
+ ReplyPostID: sql.NullInt64{Int64: postID, Valid: true},
+ })
+ require.NoError(t, err)
+ setPostRepliesCreatedAt(t, module, bobSpace.SpaceID, old)
+
+ firstPostCandidates, err := module.Drips.ListFirstPostCandidates(ctx, now-24*timeutil.MicroSecondsInOneHour, []string{testSpaceDripFirstPost24h, testSpaceDripFirstPost4d}, 50)
+ require.NoError(t, err)
+ require.ElementsMatch(t, []int64{bobID, charlieID}, spaceDripCandidateUserIDs(firstPostCandidates))
+
+ feedbackCandidates, err := module.Drips.ListFeedbackCandidates(ctx, now-7*24*timeutil.MicroSecondsInOneHour, []string{testSpaceDripFeedback7d}, 50)
+ require.NoError(t, err)
+ require.ElementsMatch(t, []int64{aliceID, bobID}, spaceDripCandidateUserIDs(feedbackCandidates))
+}
+
+func insertSpaceBrowserSession(t *testing.T, module *Module, userID int64, createdAt int64, expiresAt int64) {
+ t.Helper()
+ tokenHash := sha256.Sum256([]byte(strconv.FormatInt(userID, 10) + "-space-session"))
+ require.NoError(t, module.Sessions.CreateBrowserSession(context.Background(), tokenHash[:], userID, "wrap-key", expiresAt))
+ _, err := module.Sessions.DB.Exec(`
+ UPDATE space_browser_sessions
+ SET created_at = $1, updated_at = $1, last_used_at = $1, expires_at = $2
+ WHERE user_id = $3
+ `, createdAt, expiresAt, userID)
+ require.NoError(t, err)
+}
+
+func mustCreateOldSpace(t *testing.T, ctx context.Context, module *Module, userID int64, slug string, createdAt int64) *SpaceRecord {
+ t.Helper()
+ space, err := testCreateSpace(ctx, module, userID, slug, slug+"-root", slug+"-public", slug+"-secret", slug+"-nonce", slug+"-profile")
+ require.NoError(t, err)
+ _, err = module.Spaces.DB.Exec(`
+ UPDATE spaces
+ SET created_at = $1, updated_at = $1
+ WHERE space_id = $2
+ `, createdAt, space.SpaceID)
+ require.NoError(t, err)
+ space.CreatedAt = createdAt
+ return space
+}
+
+func setFriendshipCreatedAt(t *testing.T, module *Module, firstSpaceID string, secondSpaceID string, createdAt int64) {
+ t.Helper()
+ _, err := module.Friends.DB.Exec(`
+ UPDATE space_friend_shares
+ SET created_at = $1, updated_at = $1
+ WHERE (space_id = $2 AND friend_space_id = $3)
+ OR (space_id = $3 AND friend_space_id = $2)
+ `, createdAt, firstSpaceID, secondSpaceID)
+ require.NoError(t, err)
+}
+
+func setPostRepliesCreatedAt(t *testing.T, module *Module, senderSpaceID string, createdAt int64) {
+ t.Helper()
+ _, err := module.Messages.DB.Exec(`
+ UPDATE space_messages
+ SET created_at = $1, updated_at = $1
+ WHERE sender_space_id = $2 AND kind = 'post_reply'
+ `, createdAt, senderSpaceID)
+ require.NoError(t, err)
+}
+
+func spaceDripCandidateUserIDs(candidates []SpaceDripCandidate) []int64 {
+ userIDs := make([]int64, 0, len(candidates))
+ for _, candidate := range candidates {
+ userIDs = append(userIDs, candidate.UserID)
+ }
+ return userIDs
+}
diff --git a/server/space/repo/module.go b/server/space/repo/module.go
index 5abef97575..ba967216a9 100644
--- a/server/space/repo/module.go
+++ b/server/space/repo/module.go
@@ -14,6 +14,7 @@ type Module struct {
Assets *AssetsRepository
Read *ReadMarkersRepository
Sessions *SessionsRepository
+ Drips *DripsRepository
}
type SpacesRepository struct {
@@ -45,6 +46,10 @@ type SessionsRepository struct {
DB *sql.DB
}
+type DripsRepository struct {
+ DB *sql.DB
+}
+
type SpaceRecord struct {
SpaceID string
OwnerID int64
@@ -224,5 +229,6 @@ func NewModule(db *sql.DB, s3Config *s3config.S3Config) *Module {
Assets: &AssetsRepository{DB: db, S3Config: s3Config},
Read: &ReadMarkersRepository{DB: db},
Sessions: &SessionsRepository{DB: db},
+ Drips: &DripsRepository{DB: db},
}
}