Files
ds-galo/backend/internal/members/service.go
T
iu e82f45647c feat(realtime): доставлять клиентам события жизненного цикла альбома и изменения состава фото
Публиковать album.created/updated/deleted и изменения состава фото в личный поток
SSE, а также photo.created при загрузке, чтобы списки альбомов, счётчики и открытые
страницы альбома обновлялись без перезагрузки.

- members.Repository получил Audience (владелец + участники) для дешёвого веера
- albums.Service рассылает события в личные потоки получателей, перечитывая альбом
  через GetByID и attachCover, чтобы payload совпадал с GET /api/albums
- members.Service публикует при принятии инвайта, смене роли и исключении
- photos.Service публикует photo.created при загрузке и album.updated при
  добавлении/копировании/перемещении/восстановлении/корзине/окончательном удалении
- photos_count теперь считает фото вне корзины
- web-клиент подписывается на /api/sse/me один раз на уровне layout'а (app) и
  применяет события к стору альбомов; страница альбома уходит при потере доступа
2026-10-15 23:25:07 +03:00

258 lines
7.8 KiB
Go

package members
import (
"context"
"errors"
"time"
"galo/internal/auth"
"galo/internal/httpx"
"galo/internal/models"
"galo/internal/roles"
"galo/internal/sse"
)
// AlbumAccess is what the members domain needs from the albums service: the
// owner of an album for authorization, and the ability to publish an album
// lifecycle event to specific users' personal streams. It is satisfied by
// albums.Service.
type AlbumAccess interface {
OwnerID(ctx context.Context, albumID string) (string, error)
PublishAlbumTo(ctx context.Context, albumID, eventType string, userIDs []string)
}
type Notifier interface {
Create(ctx context.Context, userID, typ string, payload map[string]any) error
}
type Service struct {
store Repository
albums AlbumAccess
hub *sse.Hub
notify Notifier
}
func NewService(store Repository, albums AlbumAccess, hub *sse.Hub, notify Notifier) *Service {
return &Service{store: store, albums: albums, hub: hub, notify: notify}
}
// Event names published to personal streams on membership changes. They match
// the album lifecycle contract published by albums.Service.
const (
eventAlbumCreated = "album.created"
eventAlbumUpdated = "album.updated"
eventAlbumDeleted = "album.deleted"
)
// audience returns the users an album is visible to (owner + members), or nil
// when the lookup fails. A missed fan-out is recovered by the client's
// reconnect sync, so it must not fail the membership mutation.
func (s *Service) audience(ctx context.Context, albumID string) []string {
if s.albums == nil {
return nil
}
ids, err := s.store.Audience(ctx, albumID)
if err != nil {
return nil
}
return ids
}
// audienceExcept is audience without the given user, used when one recipient
// must get a different event (the invitee, the removed member).
func (s *Service) audienceExcept(ctx context.Context, albumID, exclude string) []string {
ids := s.audience(ctx, albumID)
if exclude == "" {
return ids
}
out := make([]string, 0, len(ids))
for _, id := range ids {
if id != exclude {
out = append(out, id)
}
}
return out
}
func (s *Service) Role(ctx context.Context, albumID, userID string) (string, error) {
return s.store.Role(ctx, albumID, userID)
}
func (s *Service) actorRole(ctx context.Context, albumID, actorID string) (string, error) {
ownerID, err := s.albums.OwnerID(ctx, albumID)
if err != nil {
return "", err
}
if ownerID == actorID {
return roles.Owner, nil
}
role, err := s.store.Role(ctx, albumID, actorID)
if err != nil {
return "", err
}
if role == "" {
return "", httpx.NotFound("album_not_found", "album not found")
}
return role, nil
}
type CreateInviteInput struct {
Role string
TTL time.Duration
MaxUses int
}
func (s *Service) CreateInvite(ctx context.Context, albumID, actorID string, in CreateInviteInput) (*models.Invite, error) {
role, err := s.actorRole(ctx, albumID, actorID)
if err != nil {
return nil, err
}
if !roles.CanInvite(role, in.Role) {
return nil, httpx.Forbidden("forbidden", "you cannot invite with this role")
}
if in.TTL <= 0 {
in.TTL = 7 * 24 * time.Hour
}
if in.MaxUses <= 0 {
in.MaxUses = 1
}
token, err := randomToken()
if err != nil {
return nil, err
}
inv := &models.Invite{
ID: auth.NewID(),
AlbumID: albumID,
Token: token,
Role: in.Role,
CreatedBy: actorID,
ExpiresAt: time.Now().Add(in.TTL),
MaxUses: in.MaxUses,
}
if err := s.store.CreateInvite(ctx, inv); err != nil {
return nil, err
}
return inv, nil
}
func (s *Service) Accept(ctx context.Context, token, userID string) (*models.Invite, error) {
inv, err := s.store.GetInviteByToken(ctx, token)
if err != nil {
if errors.Is(err, ErrNotFound) {
return nil, httpx.NotFound("invite_not_found", "invite not found")
}
return nil, err
}
if time.Now().After(inv.ExpiresAt) {
return nil, httpx.BadRequest("invite_expired", "invite has expired")
}
if inv.Uses >= inv.MaxUses {
return nil, httpx.BadRequest("invite_exhausted", "invite has no remaining uses")
}
if err := s.store.Add(ctx, inv.AlbumID, userID, inv.Role, &inv.CreatedBy); err != nil {
return nil, err
}
if err := s.store.IncrementUses(ctx, inv.ID); err != nil {
return nil, err
}
s.hub.Publish(inv.AlbumID, "member.joined", map[string]string{"album_id": inv.AlbumID, "user_id": userID, "role": inv.Role})
// The invitee gains the album and gets its object; everyone already in the
// album sees the updated member count.
s.albums.PublishAlbumTo(ctx, inv.AlbumID, eventAlbumCreated, []string{userID})
s.albums.PublishAlbumTo(ctx, inv.AlbumID, eventAlbumUpdated, s.audienceExcept(ctx, inv.AlbumID, userID))
if s.notify != nil {
ownerID, err := s.albums.OwnerID(ctx, inv.AlbumID)
if err == nil && ownerID != userID {
_ = s.notify.Create(ctx, ownerID, "member.joined", map[string]any{"album_id": inv.AlbumID, "user_id": userID, "role": inv.Role})
}
}
return inv, nil
}
func (s *Service) List(ctx context.Context, albumID, actorID string) ([]models.AlbumMember, error) {
if _, err := s.actorRole(ctx, albumID, actorID); err != nil {
return nil, err
}
return s.store.List(ctx, albumID)
}
func (s *Service) InviteInfo(ctx context.Context, token string) (*models.Invite, error) {
inv, err := s.store.GetInviteByToken(ctx, token)
if err != nil {
if errors.Is(err, ErrNotFound) {
return nil, httpx.NotFound("invite_not_found", "invite not found")
}
return nil, err
}
if time.Now().After(inv.ExpiresAt) || inv.Uses >= inv.MaxUses {
return nil, httpx.BadRequest("invite_inactive", "invite is expired or exhausted")
}
return inv, nil
}
func (s *Service) ChangeRole(ctx context.Context, albumID, actorID, targetID, newRole string) error {
actor, err := s.actorRole(ctx, albumID, actorID)
if err != nil {
return err
}
current, err := s.store.Role(ctx, albumID, targetID)
if err != nil {
return err
}
if current == "" {
if ownerID, oerr := s.albums.OwnerID(ctx, albumID); oerr == nil && ownerID == targetID {
return httpx.Forbidden("forbidden", "cannot change the owner's role")
}
return httpx.NotFound("member_not_found", "member not found")
}
if !roles.CanChangeRole(actor, current, newRole) {
return httpx.Forbidden("forbidden", "you cannot assign this role")
}
if err := s.store.UpdateRole(ctx, albumID, targetID, newRole); err != nil {
if errors.Is(err, ErrNotFound) {
return httpx.NotFound("member_not_found", "member not found")
}
return err
}
s.hub.Publish(albumID, "member.updated", map[string]string{"album_id": albumID, "user_id": targetID, "role": newRole})
s.albums.PublishAlbumTo(ctx, albumID, eventAlbumUpdated, s.audience(ctx, albumID))
return nil
}
func (s *Service) Remove(ctx context.Context, albumID, actorID, targetID string) error {
actor, err := s.actorRole(ctx, albumID, actorID)
if err != nil {
return err
}
targetRole, err := s.store.Role(ctx, albumID, targetID)
if err != nil {
return err
}
if targetRole == "" {
if ownerID, oerr := s.albums.OwnerID(ctx, albumID); oerr == nil && ownerID == targetID {
return httpx.Forbidden("forbidden", "cannot remove the album owner")
}
return httpx.NotFound("member_not_found", "member not found")
}
if !roles.CanRemoveMember(actor, targetRole) {
return httpx.Forbidden("forbidden", "you cannot remove this member")
}
if err := s.store.Remove(ctx, albumID, targetID); err != nil {
if errors.Is(err, ErrNotFound) {
return httpx.NotFound("member_not_found", "member not found")
}
return err
}
s.hub.Publish(albumID, "member.left", map[string]string{"album_id": albumID, "user_id": targetID})
// Those who remain see the updated member count; the removed member only
// learns that the album is gone (album.deleted carries just its id).
s.albums.PublishAlbumTo(ctx, albumID, eventAlbumUpdated, s.audience(ctx, albumID))
s.albums.PublishAlbumTo(ctx, albumID, eventAlbumDeleted, []string{targetID})
return nil
}
func randomToken() (string, error) {
raw, _, err := auth.NewRefreshToken()
return raw, err
}