π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
[server] Schedule reminder for inactive accounts
Neeraj Guptafeb398f2234b
diff --git a/server/cmd/museum/main.go b/server/cmd/museum/main.goindex 7d8efb523f..68d1b5d161 100644--- a/server/cmd/museum/main.go+++ b/server/cmd/museum/main.go@@ -412,6 +412,12 @@ func main() {userCache,userCacheCtrl,)+ inactiveUserOrchestrator := user.NewInactiveUserOrchestrator(+ userRepo,+ notificationHistoryRepo,+ lockController,+ discordController,+ )fileLinkCtrl := &publicCtrl.FileLinkController{FileController: fileController,FileLinkRepo: fileLinkRepo,@@ -921,7 +927,7 @@ func main() {setupAndStartCrons(userAuthRepo, collectionLinkRepo, fileLinkRepo, twoFactorRepo, passkeysRepo, fileController, taskLockingRepo, emailNotificationCtrl,trashController, pushController, objectController, dataCleanupController, storageBonusCtrl, emergencyCtrl,- embeddingController, healthCheckHandler, castDb)+ embeddingController, healthCheckHandler, castDb, inactiveUserOrchestrator)// Create a new collector, the name will be used as a label on the metricscollector := sqlstats.NewStatsCollector("prod_db", db)@@ -1067,7 +1073,8 @@ func setupAndStartCrons(userAuthRepo *repo.UserAuthRepository, collectionLinkRepemergencyCtrl *emergency.Controller,embeddingCtrl *embeddingCtrl.Controller,healthCheckHandler *api.HealthCheckHandler,- castDb castRepo.Repository) {+ castDb castRepo.Repository,+ inactiveUserOrchestrator *user.InactiveUserOrchestrator) {shouldSkipCron := viper.GetBool("jobs.cron.skip")if shouldSkipCron {log.Info("Skipping cron jobs")@@ -1167,6 +1174,10 @@ func setupAndStartCrons(userAuthRepo *repo.UserAuthRepository, collectionLinkRep}})+ scheduleAndRun(c, "@every 24h", func() {+ inactiveUserOrchestrator.ProcessInactiveUsers()+ })+schedule(c, "@every 1m", func() {pushController.SendPushes()})diff --git a/server/mail-templates/ente_base.html b/server/mail-templates/ente_base.htmlnew file mode 100644index 0000000000..f5b333b075--- /dev/null+++ b/server/mail-templates/ente_base.html@@ -0,0 +1,142 @@+{{define "ente_base"}}+<!DOCTYPE html>+<html>+<meta content="text/html; charset=utf-8" />+<meta name="viewport" content="width=device-width, initial-scale=1,+ minimum-scale=1" />+<style>+ body {+ background-color: #f0f1f3;+ font-family: "Helvetica Neue", "Segoe UI", Helvetica, sans-serif;+ font-size: 16px;+ line-height: 27px;+ margin: 0;+ color: #444;+ }++ pre {+ background: #f4f4f4f4;+ padding: 2px;+ }++ table {+ width: 100%;+ border: 1px solid #ddd;+ }++ table td {+ border-color: #ddd;+ padding: 5px;+ }++ .wrap {+ background-color: #fff;+ padding: 30px;+ max-width: 525px;+ margin: 0 auto;+ border-radius: 5px;+ }++ .button {+ background: #0055d4;+ border-radius: 3px;+ text-decoration: none !important;+ color: #fff !important;+ font-weight: bold;+ padding: 10px 30px;+ display: inline-block;+ }++ .button:hover {+ background: #111;+ }++ .footer {+ text-align: center;+ font-size: 12px;+ color: #888;+ }++ .footer a {+ color: #888;+ margin-right: 5px;+ }++ .gutter {+ padding: 30px;+ }++ img {+ max-width: 100%;+ height: auto;+ }++ a {+ color: #0055d4;+ }++ a:hover {+ color: #111;+ }++ @media screen and (max-width: 600px) {+ .wrap {+ max-width: auto;+ }++ .gutter {+ padding: 10px;+ }+ }++ .footer-icons {+ padding: 4px !important;+ width: 24px !important;+ }+</style>++<body>+<div class="gutter" style="padding: 4px"> </div>+<div class="wrap" style=" background-color: rgb(255, 255, 255); padding: 2px+ 30px 30px 30px; max-width: 525px; margin: 0 auto; border-radius: 5px;+ font-size: 16px; " >+ <main>+ {{block "content" .}} Default Content {{end}}+ </main>+</div>+<br />+<div class="footer" style="text-align: center; font-size: 12px; color:+ rgb(136, 136, 136)" >+ <div>+ <a href="https://ente.io" target="_blank" ><img+ src="https://email-assets.ente.io/ente-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.io/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.io/twitter-icon.png" class="footer-icons"+ style="width: 24px; padding: 4px" title="Twitter" alt="Twitter" /></a>+ <a href="https://discord.ente.io" target="_blank" ><img+ src="https://email-assets.ente.io/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.io/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.io/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>+{{end}}diff --git a/server/mail-templates/inactive-user-deletion/confirm_12m.html b/server/mail-templates/inactive-user-deletion/confirm_12m.htmlnew file mode 100644index 0000000000..51e5c6797a--- /dev/null+++ b/server/mail-templates/inactive-user-deletion/confirm_12m.html@@ -0,0 +1,11 @@+{{template "ente_base" .}}++{{define "content"}}+<p>Hello,</p>++<p>Your Ente account has reached 12 months of inactivity.</p>+<p>This account has been marked for manual deletion review.</p>+<p>If you sign in again, the inactivity counter will reset.</p>++<p>Regards,<br/>Team Ente</p>+{{end}}diff --git a/server/mail-templates/inactive-user-deletion/warn_11m.html b/server/mail-templates/inactive-user-deletion/warn_11m.htmlnew file mode 100644index 0000000000..12ddbac3f5--- /dev/null+++ b/server/mail-templates/inactive-user-deletion/warn_11m.html@@ -0,0 +1,11 @@+{{template "ente_base" .}}++{{define "content"}}+<p>Hello,</p>++<p>Your Ente account has been inactive for about 11 months.</p>+<p>If you want to keep your account active, open any Ente app and sign in again.</p>+<p>If no activity is seen, we will continue to send inactivity reminders.</p>++<p>Regards,<br/>Team Ente</p>+{{end}}diff --git a/server/mail-templates/inactive-user-deletion/warn_12m_1d.html b/server/mail-templates/inactive-user-deletion/warn_12m_1d.htmlnew file mode 100644index 0000000000..f0288a4bdc--- /dev/null+++ b/server/mail-templates/inactive-user-deletion/warn_12m_1d.html@@ -0,0 +1,11 @@+{{template "ente_base" .}}++{{define "content"}}+<p>Hello,</p>++<p>Your Ente account is still inactive.</p>+<p>This is the final reminder before the 12-month inactivity milestone.</p>+<p>Open any Ente app and sign in to reset the inactivity counter.</p>++<p>Regards,<br/>Team Ente</p>+{{end}}diff --git a/server/mail-templates/inactive-user-deletion/warn_12m_7d.html b/server/mail-templates/inactive-user-deletion/warn_12m_7d.htmlnew file mode 100644index 0000000000..3fa8ffd54a--- /dev/null+++ b/server/mail-templates/inactive-user-deletion/warn_12m_7d.html@@ -0,0 +1,11 @@+{{template "ente_base" .}}++{{define "content"}}+<p>Hello,</p>++<p>Your Ente account is still inactive.</p>+<p>This is a reminder sent 7 days before the 12-month inactivity mark.</p>+<p>Open any Ente app and sign in to reset the inactivity counter.</p>++<p>Regards,<br/>Team Ente</p>+{{end}}diff --git a/server/pkg/controller/user/inactive_user_orchestrator.go b/server/pkg/controller/user/inactive_user_orchestrator.gonew file mode 100644index 0000000000..1b34ca8826--- /dev/null+++ b/server/pkg/controller/user/inactive_user_orchestrator.go@@ -0,0 +1,284 @@+package user++import (+ "errors"+ "fmt"+ "strings"++ "github.com/ente-io/museum/ente"+ "github.com/ente-io/museum/pkg/controller/discord"+ "github.com/ente-io/museum/pkg/controller/lock"+ "github.com/ente-io/museum/pkg/repo"+ emailUtil "github.com/ente-io/museum/pkg/utils/email"+ "github.com/ente-io/museum/pkg/utils/time"+ log "github.com/sirupsen/logrus"+)++const (+ InactiveUserDeletionJobLock = "inactive_user_deletion_mail_lock"++ inactiveUserDeletionBatchSize = 500+ inactiveUserDeletionFromName = "Ente"+ inactiveUserDeletionFromEmail = "[email protected]"+ inactiveUserDeletionBaseTemplate = "ente_base.html"++ InactiveUserDeletionWarn11mTemplateID = "inactive_user_deletion_warn_11m"+ InactiveUserDeletionWarn12m7dTemplateID = "inactive_user_deletion_warn_12m_7d"+ InactiveUserDeletionWarn12m1dTemplateID = "inactive_user_deletion_warn_12m_1d"+ InactiveUserDeletionFinalTemplateID = "inactive_user_deletion_confirm_12m"++ inactiveUserDeletionWarn11mTemplate = "inactive-user-deletion/warn_11m.html"+ inactiveUserDeletionWarn12m7dTemplate = "inactive-user-deletion/warn_12m_7d.html"+ inactiveUserDeletionWarn12m1dTemplate = "inactive-user-deletion/warn_12m_1d.html"+ inactiveUserDeletionFinalTemplate = "inactive-user-deletion/confirm_12m.html"++ inactiveUserDeletionWarn11mSubject = "Your Ente account has been inactive"+ inactiveUserDeletionWarn12m7dSubject = "Reminder: your Ente account is still inactive"+ inactiveUserDeletionWarn12m1dSubject = "Final reminder: your Ente account is inactive"+ inactiveUserDeletionFinalSubject = "Your Ente account is marked for manual deletion review"+)++const (+ inactiveUserOneDayInMicroSeconds = 24 * time.MicroSecondsInOneHour++ // 12 months is modeled as 365 days. The first stage (11 months) maps to+ // 30 days before 12 months to preserve the desired 23/6/1 day replay gaps.+ inactiveUserTwelveMonthsInMicroSeconds = 365 * inactiveUserOneDayInMicroSeconds+ inactiveUserWarn11MonthsInMicroSeconds = inactiveUserTwelveMonthsInMicroSeconds - (30 * inactiveUserOneDayInMicroSeconds)++ inactiveUserGap11mTo12mMinus7d = 23 * inactiveUserOneDayInMicroSeconds+ inactiveUserGap12mMinus7dTo1d = 6 * inactiveUserOneDayInMicroSeconds+ inactiveUserGap12mMinus1dTo12m = inactiveUserOneDayInMicroSeconds+)++var inactiveUserDeletionTemplateIDs = []string{+ InactiveUserDeletionWarn11mTemplateID,+ InactiveUserDeletionWarn12m7dTemplateID,+ InactiveUserDeletionWarn12m1dTemplateID,+ InactiveUserDeletionFinalTemplateID,+}++type inactivityEmailStage string++const (+ inactivityEmailStageNone inactivityEmailStage = ""+ inactivityEmailStageWarn11m inactivityEmailStage = "warn_11m"+ inactivityEmailStageWarn12m7d inactivityEmailStage = "warn_12m_7d"+ inactivityEmailStageWarn12m1d inactivityEmailStage = "warn_12m_1d"+ inactivityEmailStageFinal inactivityEmailStage = "confirm_12m"+)++type inactivityEmailStageConfig struct {+ TemplateID string+ TemplateName string+ Subject string+ IsFinal bool+}++// InactiveUserOrchestrator sends inactivity warning emails and final manual+// deletion reminders for users who stay inactive across all apps.+type InactiveUserOrchestrator struct {+ UserRepo *repo.UserRepository+ NotificationHistoryRepo *repo.NotificationHistoryRepository+ LockController *lock.LockController+ DiscordController *discord.DiscordController+}++func NewInactiveUserOrchestrator(+ userRepo *repo.UserRepository,+ notificationHistoryRepo *repo.NotificationHistoryRepository,+ lockController *lock.LockController,+ discordController *discord.DiscordController,+) *InactiveUserOrchestrator {+ return &InactiveUserOrchestrator{+ UserRepo: userRepo,+ NotificationHistoryRepo: notificationHistoryRepo,+ LockController: lockController,+ DiscordController: discordController,+ }+}++func (c *InactiveUserOrchestrator) ProcessInactiveUsers() {+ lockUntil := time.MicrosecondsAfterHours(24)+ if !c.LockController.TryLock(InactiveUserDeletionJobLock, lockUntil) {+ log.Info("Skipping inactive user processing because another instance is running")+ return+ }+ defer c.LockController.ReleaseLock(InactiveUserDeletionJobLock)++ now := time.Microseconds()+ beforeTime := now - inactiveUserWarn11MonthsInMicroSeconds+ var afterUserID int64+ processedUsers := 0+ sentEmails := 0++ for {+ candidates, err := c.UserRepo.GetActiveUsersByLastActivityBefore(beforeTime, afterUserID, inactiveUserDeletionBatchSize)+ if err != nil {+ log.WithError(err).Error("Failed to fetch inactive users")+ return+ }+ if len(candidates) == 0 {+ break+ }++ for _, candidate := range candidates {+ afterUserID = candidate.UserID+ processedUsers+++ sent, err := c.processCandidate(candidate, now)+ if err != nil {+ log.WithError(err).WithField("user_id", candidate.UserID).Error("Failed to process inactive user candidate")+ continue+ }+ if sent {+ sentEmails+++ }+ }+ }++ log.WithFields(log.Fields{+ "processed_users": processedUsers,+ "sent_emails": sentEmails,+ }).Info("Completed inactive user processing")+}++func (c *InactiveUserOrchestrator) processCandidate(candidate repo.UserInactivityCandidate, now int64) (bool, error) {+ user, err := c.UserRepo.Get(candidate.UserID)+ if err != nil {+ if errors.Is(err, ente.ErrUserDeleted) {+ return false, nil+ }+ return false, err+ }++ if !isEnteDomainRolloutUser(user.Email) {+ return false, nil+ }++ stage, err := c.resolveNextStage(user.ID, candidate.LastActivity, now)+ if err != nil {+ return false, err+ }+ if stage == inactivityEmailStageNone {+ return false, nil+ }++ config := inactivityStageConfig(stage)+ if config.TemplateID == "" {+ return false, nil+ }++ templateData := map[string]interface{}{+ "Email": user.Email,+ }+ if err := emailUtil.SendTemplatedEmailV2(+ []string{user.Email},+ inactiveUserDeletionFromName,+ inactiveUserDeletionFromEmail,+ config.Subject,+ inactiveUserDeletionBaseTemplate,+ config.TemplateName,+ templateData,+ nil,+ ); err != nil {+ return false, err+ }++ if err := c.NotificationHistoryRepo.SetLastNotificationTimeToNow(user.ID, config.TemplateID); err != nil {+ return false, err+ }++ log.WithFields(log.Fields{+ "user_id": user.ID,+ "template_id": config.TemplateID,+ }).Info("Sent inactive user email")++ if config.IsFinal {+ c.DiscordController.NotifyAdminAction(+ fmt.Sprintf("Inactive user %d (%s) reached 12 months inactivity and was sent final warning for manual deletion review",+ user.ID, user.Email))+ }++ return true, nil+}++func (c *InactiveUserOrchestrator) resolveNextStage(userID int64, lastActivity int64, now int64) (inactivityEmailStage, error) {+ history, err := c.NotificationHistoryRepo.GetLastNotificationTimes(userID, inactiveUserDeletionTemplateIDs)+ if err != nil {+ return inactivityEmailStageNone, err+ }+ return nextInactivityEmailStage(lastActivity, now, history), nil+}++func nextInactivityEmailStage(lastActivity int64, now int64, history map[string]int64) inactivityEmailStage {+ if now-lastActivity < inactiveUserWarn11MonthsInMicroSeconds {+ return inactivityEmailStageNone+ }++ sent11m := history[InactiveUserDeletionWarn11mTemplateID]+ if sent11m <= lastActivity {+ return inactivityEmailStageWarn11m+ }++ sentFinal := history[InactiveUserDeletionFinalTemplateID]+ if sentFinal > lastActivity {+ return inactivityEmailStageNone+ }++ sent12mMinus7d := history[InactiveUserDeletionWarn12m7dTemplateID]+ if sent12mMinus7d <= lastActivity {+ if now >= sent11m+inactiveUserGap11mTo12mMinus7d {+ return inactivityEmailStageWarn12m7d+ }+ return inactivityEmailStageNone+ }++ sent12mMinus1d := history[InactiveUserDeletionWarn12m1dTemplateID]+ if sent12mMinus1d <= lastActivity {+ if now >= sent12mMinus7d+inactiveUserGap12mMinus7dTo1d {+ return inactivityEmailStageWarn12m1d+ }+ return inactivityEmailStageNone+ }++ if now >= sent12mMinus1d+inactiveUserGap12mMinus1dTo12m {+ return inactivityEmailStageFinal+ }+ return inactivityEmailStageNone+}++func inactivityStageConfig(stage inactivityEmailStage) inactivityEmailStageConfig {+ switch stage {+ case inactivityEmailStageWarn11m:+ return inactivityEmailStageConfig{+ TemplateID: InactiveUserDeletionWarn11mTemplateID,+ TemplateName: inactiveUserDeletionWarn11mTemplate,+ Subject: inactiveUserDeletionWarn11mSubject,+ }+ case inactivityEmailStageWarn12m7d:+ return inactivityEmailStageConfig{+ TemplateID: InactiveUserDeletionWarn12m7dTemplateID,+ TemplateName: inactiveUserDeletionWarn12m7dTemplate,+ Subject: inactiveUserDeletionWarn12m7dSubject,+ }+ case inactivityEmailStageWarn12m1d:+ return inactivityEmailStageConfig{+ TemplateID: InactiveUserDeletionWarn12m1dTemplateID,+ TemplateName: inactiveUserDeletionWarn12m1dTemplate,+ Subject: inactiveUserDeletionWarn12m1dSubject,+ }+ case inactivityEmailStageFinal:+ return inactivityEmailStageConfig{+ TemplateID: InactiveUserDeletionFinalTemplateID,+ TemplateName: inactiveUserDeletionFinalTemplate,+ Subject: inactiveUserDeletionFinalSubject,+ IsFinal: true,+ }+ default:+ return inactivityEmailStageConfig{}+ }+}++func isEnteDomainRolloutUser(email string) bool {+ return strings.HasSuffix(strings.ToLower(strings.TrimSpace(email)), "@ente.io")+}diff --git a/server/pkg/controller/user/inactive_user_orchestrator_test.go b/server/pkg/controller/user/inactive_user_orchestrator_test.gonew file mode 100644index 0000000000..c33ee492d5--- /dev/null+++ b/server/pkg/controller/user/inactive_user_orchestrator_test.go@@ -0,0 +1,99 @@+package user++import "testing"++func TestNextInactivityEmailStage(t *testing.T) {+ day := int64(24 * 60 * 60 * 1000 * 1000)+ now := int64(500 * day)+ lastActivity := now - inactiveUserWarn11MonthsInMicroSeconds++ tests := []struct {+ name string+ lastActivity int64+ now int64+ history map[string]int64+ want inactivityEmailStage+ }{+ {+ name: "no stage before threshold",+ lastActivity: now - inactiveUserWarn11MonthsInMicroSeconds + day,+ now: now,+ history: map[string]int64{},+ want: inactivityEmailStageNone,+ },+ {+ name: "first stage at 11 months",+ lastActivity: lastActivity,+ now: now,+ history: map[string]int64{},+ want: inactivityEmailStageWarn11m,+ },+ {+ name: "second stage waits for replay gap",+ lastActivity: lastActivity,+ now: now + inactiveUserGap11mTo12mMinus7d - day,+ history: map[string]int64{+ InactiveUserDeletionWarn11mTemplateID: now,+ },+ want: inactivityEmailStageNone,+ },+ {+ name: "second stage after replay gap",+ lastActivity: lastActivity,+ now: now + inactiveUserGap11mTo12mMinus7d,+ history: map[string]int64{+ InactiveUserDeletionWarn11mTemplateID: now,+ },+ want: inactivityEmailStageWarn12m7d,+ },+ {+ name: "third stage after second stage gap",+ lastActivity: lastActivity,+ now: now + inactiveUserGap12mMinus7dTo1d,+ history: map[string]int64{+ InactiveUserDeletionWarn11mTemplateID: now - 100,+ InactiveUserDeletionWarn12m7dTemplateID: now,+ },+ want: inactivityEmailStageWarn12m1d,+ },+ {+ name: "final stage after third stage gap",+ lastActivity: lastActivity,+ now: now + inactiveUserGap12mMinus1dTo12m,+ history: map[string]int64{+ InactiveUserDeletionWarn11mTemplateID: now - 100,+ InactiveUserDeletionWarn12m7dTemplateID: now - 50,+ InactiveUserDeletionWarn12m1dTemplateID: now,+ },+ want: inactivityEmailStageFinal,+ },+ {+ name: "stop after final stage in same cycle",+ lastActivity: lastActivity,+ now: now + (10 * day),+ history: map[string]int64{+ InactiveUserDeletionWarn11mTemplateID: now - 1000,+ InactiveUserDeletionFinalTemplateID: now - 100,+ },+ want: inactivityEmailStageNone,+ },+ {+ name: "activity reset starts new cycle",+ lastActivity: now - inactiveUserWarn11MonthsInMicroSeconds,+ now: now,+ history: map[string]int64{+ InactiveUserDeletionWarn11mTemplateID: now - inactiveUserWarn11MonthsInMicroSeconds - day,+ },+ want: inactivityEmailStageWarn11m,+ },+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ got := nextInactivityEmailStage(tc.lastActivity, tc.now, tc.history)+ if got != tc.want {+ t.Fatalf("unexpected stage: got %q want %q", got, tc.want)+ }+ })+ }+}diff --git a/server/pkg/repo/notificationhistory.go b/server/pkg/repo/notificationhistory.goindex 3e1baece29..9129c64268 100644--- a/server/pkg/repo/notificationhistory.go+++ b/server/pkg/repo/notificationhistory.go@@ -3,6 +3,7 @@ package repoimport ("database/sql""github.com/ente-io/stacktrace"+ "github.com/lib/pq""github.com/ente-io/museum/pkg/utils/time")@@ -29,3 +30,36 @@ func (repo *NotificationHistoryRepository) SetLastNotificationTimeToNow(userID iuserID, templateID, time.Microseconds())return stacktrace.Propagate(err, "")}++// GetLastNotificationTimes returns the latest sent_time per templateID for the+// provided user.+func (repo *NotificationHistoryRepository) GetLastNotificationTimes(userID int64, templateIDs []string) (map[string]int64, error) {+ result := make(map[string]int64)+ if len(templateIDs) == 0 {+ return result, nil+ }++ rows, err := repo.DB.Query(+ `SELECT template_id, MAX(sent_time) FROM notification_history+ WHERE user_id = $1 AND template_id = ANY($2)+ GROUP BY template_id`,+ userID, pq.Array(templateIDs))+ if err != nil {+ return nil, stacktrace.Propagate(err, "failed to fetch notification history")+ }+ defer rows.Close()++ for rows.Next() {+ var templateID string+ var sentTime int64+ if err := rows.Scan(&templateID, &sentTime); err != nil {+ return nil, stacktrace.Propagate(err, "failed to scan notification history")+ }+ result[templateID] = sentTime+ }+ if err := rows.Err(); err != nil {+ return nil, stacktrace.Propagate(err, "failed to iterate notification history")+ }++ return result, nil+}diff --git a/server/pkg/repo/user.go b/server/pkg/repo/user.goindex bac3aaf2f1..1abc3659e6 100644--- a/server/pkg/repo/user.go+++ b/server/pkg/repo/user.go@@ -32,6 +32,13 @@ type UserRepository struct {PasskeysRepository *passkey.Repository}+// UserInactivityCandidate captures the latest known activity timestamp for an+// active (non-deleted) user account.+type UserInactivityCandidate struct {+ UserID int64+ LastActivity int64+}+// Get returns a user indicated by the userIDfunc (repo *UserRepository) Get(userID int64) (ente.User, error) {var user ente.User@@ -128,6 +135,47 @@ func (repo *UserRepository) GetAll(sinceTime int64, tillTime int64) ([]ente.Userreturn users, nil}+// GetActiveUsersByLastActivityBefore returns active users whose latest token+// activity is older than or equal to beforeTime. Only users having at least one+// token row are considered. Paging is done by user_id.+//+// TODO(inactive-user-deletion): Tokens are not a durable activity source.+// `RemoveDeletedTokens` prunes logged-out sessions after 30 days, which can make+// last_activity stale or missing for users who logged out from all devices.+// Move inactivity selection to a durable, app-wide last-activity signal.+func (repo *UserRepository) GetActiveUsersByLastActivityBefore(beforeTime int64, afterUserID int64, limit int) ([]UserInactivityCandidate, error) {+ rows, err := repo.DB.Query(`+ SELECT+ u.user_id,+ MAX(t.last_used_at) AS last_activity+ FROM users u+ INNER JOIN tokens t+ ON t.user_id = u.user_id+ WHERE u.encrypted_email IS NOT NULL+ AND u.user_id > $2+ GROUP BY u.user_id+ HAVING MAX(t.last_used_at) <= $1+ ORDER BY u.user_id+ LIMIT $3`, beforeTime, afterUserID, limit)+ if err != nil {+ return nil, stacktrace.Propagate(err, "failed to fetch inactive users")+ }+ defer rows.Close()++ result := make([]UserInactivityCandidate, 0)+ for rows.Next() {+ var candidate UserInactivityCandidate+ if err := rows.Scan(&candidate.UserID, &candidate.LastActivity); err != nil {+ return nil, stacktrace.Propagate(err, "failed to scan inactive user row")+ }+ result = append(result, candidate)+ }+ if err := rows.Err(); err != nil {+ return nil, stacktrace.Propagate(err, "failed to iterate inactive users")+ }+ return result, nil+}+// GetUserUsageWithSubData will return current storage usage & basic information about subscription for given list// of users. It's primarily used for fetching storage utilisation for a family/group of usersfunc (repo *UserRepository) GetUserUsageWithSubData(ctx context.Context, userIds []int64) ([]ente.UserUsageWithSubData, error) {