package models import ( "time" "gorm.io/gorm" "gorm.io/gorm/clause" ) // MutedUser table, for users to mute one another's Site Gallery photos and similar. type MutedUser struct { ID uint64 `gorm:"primaryKey"` SourceUserID uint64 `gorm:"uniqueIndex:idx_muted_user"` TargetUserID uint64 `gorm:"uniqueIndex:idx_muted_user"` Context MutedUserContext `gorm:"uniqueIndex:idx_muted_user"` CreatedAt time.Time UpdatedAt time.Time } type MutedUserContext string // Context options for MutedUser to specify what is being muted. const ( MutedUserContextSiteGallery MutedUserContext = "site_gallery" // hide a user's photos from the Site Gallery. ) // IsValidMuteUserContext validates acceptable options for muting users. func IsValidMuteUserContext(ctx MutedUserContext) bool { return ctx == MutedUserContextSiteGallery } // AddMutedUser is sourceUserId adding targetUserId to their mute list under the given context. func AddMutedUser(sourceUserID, targetUserID uint64, ctx MutedUserContext) error { m := &MutedUser{ SourceUserID: sourceUserID, TargetUserID: targetUserID, Context: ctx, } // Upsert the mute. res := DB.Model(&MutedUser{}).Clauses( clause.OnConflict{ Columns: []clause.Column{ {Name: "source_user_id"}, {Name: "target_user_id"}, {Name: "context"}, }, DoNothing: true, }, ).Create(m) return res.Error } // MutedUserIDs returns all user IDs Muted by the user. func MutedUserIDs(user *User, context MutedUserContext) []uint64 { var ( ms = []*MutedUser{} userIDs = []uint64{} ) DB.Where("source_user_id = ? AND context = ?", user.ID, context).Find(&ms) for _, row := range ms { userIDs = append(userIDs, row.TargetUserID) } return userIDs } // PaginateMuteList views a user's mute lists. func PaginateMuteList(user *User, pager *Pagination) ([]*User, error) { // We paginate over the MutedUser table. var ( ms = []*MutedUser{} userIDs = []uint64{} query *gorm.DB ) query = DB.Where( "source_user_id = ?", user.ID, ) query = query.Order(pager.Sort) query.Model(&MutedUser{}).Count(&pager.Total) result := query.Offset(pager.GetOffset()).Limit(pager.PerPage).Find(&ms) if result.Error != nil { return nil, result.Error } // Now of these users get their User objects. for _, b := range ms { userIDs = append(userIDs, b.TargetUserID) } return GetUsers(user, userIDs) } // RemoveMutedUser clears the muted user row. func RemoveMutedUser(sourceUserID, targetUserID uint64, ctx MutedUserContext) error { result := DB.Where( "source_user_id = ? AND target_user_id = ? AND context = ?", sourceUserID, targetUserID, ctx, ).Delete(&MutedUser{}) return result.Error }