2026-04-05 20:42:32 +00:00
|
|
|
package service
|
|
|
|
|
|
|
|
|
|
import (
|
2026-04-06 09:00:47 +00:00
|
|
|
"context"
|
2026-04-05 20:42:32 +00:00
|
|
|
"fmt"
|
|
|
|
|
"log/slog"
|
|
|
|
|
"time"
|
|
|
|
|
|
2026-08-28 06:54:32 +02:00
|
|
|
"github.com/J3vb/OwnCord/Server/auth"
|
|
|
|
|
"github.com/J3vb/OwnCord/Server/db"
|
|
|
|
|
"github.com/J3vb/OwnCord/Server/permissions"
|
|
|
|
|
"github.com/J3vb/OwnCord/Server/telemetry"
|
2026-04-05 20:42:32 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// ChannelService handles channel-related business logic including
|
|
|
|
|
// listing, permission-filtered access, typing, presence, and read state.
|
|
|
|
|
type ChannelService struct {
|
2026-07-19 16:33:58 +00:00
|
|
|
st Store
|
2026-04-05 20:42:32 +00:00
|
|
|
perms *PermissionService
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// NewChannelService creates a ChannelService.
|
2026-07-19 16:33:58 +00:00
|
|
|
func NewChannelService(st Store, perms *PermissionService) *ChannelService {
|
2026-04-05 20:42:32 +00:00
|
|
|
return &ChannelService{
|
2026-04-05 21:01:29 +00:00
|
|
|
st: st,
|
2026-04-05 20:42:32 +00:00
|
|
|
perms: perms,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ListVisibleChannels returns channels the user has ReadMessages permission for.
|
|
|
|
|
// DM channels are excluded (they are accessed via DMService).
|
2026-04-07 09:10:14 +02:00
|
|
|
func (s *ChannelService) ListVisibleChannels(ctx context.Context, userID int64) ([]db.Channel, error) {
|
2026-04-06 09:00:47 +00:00
|
|
|
// Phase B Step 8 — span the public service entrypoint.
|
2026-04-07 09:10:14 +02:00
|
|
|
ctx, span := telemetry.GlobalTracer("service/channel").Start(ctx,
|
2026-04-06 09:00:47 +00:00
|
|
|
"ChannelService.ListVisibleChannels",
|
|
|
|
|
telemetry.Int64("user_id", userID),
|
|
|
|
|
)
|
|
|
|
|
start := time.Now()
|
|
|
|
|
defer func() {
|
2026-04-06 13:48:41 +00:00
|
|
|
telemetry.TimeSince(ctx, telemetry.NewAppMetrics().ServiceCallDurationSec, start,
|
2026-04-06 09:00:47 +00:00
|
|
|
telemetry.String("method", "ListVisibleChannels"))
|
|
|
|
|
span.End()
|
|
|
|
|
}()
|
2026-07-23 17:03:52 +02:00
|
|
|
all, err := s.st.ListChannels(ctx)
|
2026-04-05 20:42:32 +00:00
|
|
|
if err != nil {
|
|
|
|
|
slog.Error("ChannelService.ListVisibleChannels", "err", err)
|
|
|
|
|
return nil, fmt.Errorf("%w: failed to list channels", ErrInternal)
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-23 17:03:52 +02:00
|
|
|
role, err := s.perms.GetRoleForUser(ctx, userID)
|
2026-04-05 20:42:32 +00:00
|
|
|
if err != nil || role == nil {
|
|
|
|
|
slog.Error("ChannelService.ListVisibleChannels GetRoleForUser", "err", err, "user_id", userID)
|
|
|
|
|
return nil, fmt.Errorf("%w: failed to get role", ErrInternal)
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-20 11:28:03 +02:00
|
|
|
// Admins skip the override fetch (they bypass all channel checks anyway).
|
2026-08-01 22:06:14 +02:00
|
|
|
// Non-admins get both layers — role and per-user — in one batched fetch.
|
2026-07-20 11:28:03 +02:00
|
|
|
var overrides map[int64]db.ChannelOverride
|
|
|
|
|
if !permissions.HasAdmin(role.Permissions) {
|
2026-08-01 22:06:14 +02:00
|
|
|
overrides, err = s.st.GetChannelOverridesFor(ctx, role.ID, userID)
|
2026-07-20 11:28:03 +02:00
|
|
|
if err != nil {
|
2026-07-23 14:45:34 +02:00
|
|
|
// Fail closed — an empty map would return every denied channel.
|
2026-08-01 22:06:14 +02:00
|
|
|
slog.Error("ChannelService.ListVisibleChannels GetChannelOverridesFor", "err", err, "user_id", userID, "role_id", role.ID)
|
2026-07-23 14:45:34 +02:00
|
|
|
return nil, fmt.Errorf("%w: failed to fetch channel overrides", ErrInternal)
|
2026-04-05 20:42:32 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-20 11:28:03 +02:00
|
|
|
// Single visibility predicate shared with the ws ready payload and reconnect
|
|
|
|
|
// replay filtering, so REST and WS can never disagree on what a role sees.
|
|
|
|
|
visibleIDs := s.perms.Checker().VisibleChannelIDs(role.Permissions, channelRefs(all), permOverrides(overrides))
|
|
|
|
|
visible := make([]db.Channel, 0, len(visibleIDs))
|
2026-04-07 10:10:38 +02:00
|
|
|
for i := range all {
|
2026-07-20 11:28:03 +02:00
|
|
|
if visibleIDs[all[i].ID] {
|
2026-04-07 10:10:38 +02:00
|
|
|
visible = append(visible, all[i])
|
2026-04-05 20:42:32 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return visible, nil
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-20 11:28:03 +02:00
|
|
|
// channelRefs maps db channels to the checker's db-agnostic ChannelRef.
|
|
|
|
|
func channelRefs(channels []db.Channel) []permissions.ChannelRef {
|
|
|
|
|
refs := make([]permissions.ChannelRef, len(channels))
|
|
|
|
|
for i := range channels {
|
2026-08-01 22:06:14 +02:00
|
|
|
refs[i] = permissions.ChannelRef{ID: channels[i].ID, Type: channels[i].Type, Archived: channels[i].Archived}
|
2026-07-20 11:28:03 +02:00
|
|
|
}
|
|
|
|
|
return refs
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-01 22:06:14 +02:00
|
|
|
// permOverrides maps a db override map to the checker's override map, carrying
|
|
|
|
|
// BOTH layers — the role override and the per-user override — so the checker
|
|
|
|
|
// resolves the full order (base -> role -> user) rather than half of it.
|
2026-07-20 11:28:03 +02:00
|
|
|
func permOverrides(overrides map[int64]db.ChannelOverride) map[int64]permissions.ChannelOverride {
|
|
|
|
|
out := make(map[int64]permissions.ChannelOverride, len(overrides))
|
|
|
|
|
for id, o := range overrides {
|
2026-08-01 22:06:14 +02:00
|
|
|
out[id] = permissions.ChannelOverride{
|
|
|
|
|
Allow: o.Allow,
|
|
|
|
|
Deny: o.Deny,
|
|
|
|
|
UserAllow: o.UserAllow,
|
|
|
|
|
UserDeny: o.UserDeny,
|
|
|
|
|
}
|
2026-07-20 11:28:03 +02:00
|
|
|
}
|
|
|
|
|
return out
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-05 20:42:32 +00:00
|
|
|
// HandleTyping processes a typing start event for a channel.
|
|
|
|
|
// Returns the channel so callers can build broadcast events.
|
|
|
|
|
// Silent errors are returned as nil (typing indicators are best-effort).
|
2026-07-23 17:03:52 +02:00
|
|
|
func (s *ChannelService) HandleTyping(ctx context.Context, userID, channelID int64, limiter interface {
|
2026-04-05 20:42:32 +00:00
|
|
|
Allow(key string, limit int, window time.Duration) bool
|
2026-04-06 22:48:59 +02:00
|
|
|
},
|
|
|
|
|
) (*db.Channel, error) {
|
2026-04-05 20:42:32 +00:00
|
|
|
if channelID <= 0 {
|
|
|
|
|
return nil, nil
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-23 17:03:52 +02:00
|
|
|
ch, err := s.st.GetChannel(ctx, channelID)
|
2026-04-05 20:42:32 +00:00
|
|
|
if err != nil || ch == nil {
|
2026-04-07 10:10:38 +02:00
|
|
|
return nil, nil //nolint:nilerr // typing indicators are best-effort; errors silently dropped
|
2026-04-05 20:42:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if ch.Type == "dm" {
|
2026-07-23 17:03:52 +02:00
|
|
|
ok, dmErr := s.st.IsDMParticipant(ctx, userID, channelID)
|
2026-04-07 10:10:38 +02:00
|
|
|
if dmErr != nil || !ok {
|
|
|
|
|
return nil, nil //nolint:nilerr // typing indicators are best-effort; errors silently dropped
|
2026-04-05 20:42:32 +00:00
|
|
|
}
|
2026-07-29 12:48:47 +02:00
|
|
|
// A blocked user must not be able to keep poking the blocker with
|
|
|
|
|
// typing indicators. Same gate as the other DM sinks; silently dropped
|
|
|
|
|
// here because typing is best-effort.
|
|
|
|
|
if blkErr := requireDMNotBlocked(ctx, s.st, userID, channelID); blkErr != nil {
|
|
|
|
|
return nil, nil //nolint:nilerr // best-effort: a blocked or unreadable DM emits nothing
|
|
|
|
|
}
|
2026-07-23 17:03:52 +02:00
|
|
|
} else if !s.perms.HasChannelPerm(ctx, userID, channelID, permissions.ReadMessages) {
|
2026-04-05 20:42:32 +00:00
|
|
|
return nil, nil // silent drop
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-15 16:30:05 +02:00
|
|
|
// Per-user-per-channel rate limit. Built only now that the channel is
|
|
|
|
|
// known to exist and the caller is authorized to read it (OC-0202): doing
|
|
|
|
|
// this before resolution let any caller-supplied channel id — including
|
|
|
|
|
// ids that don't exist or aren't readable — pin a new entry in the
|
|
|
|
|
// shared, process-wide RateLimiter. RateLimiter.Cleanup only evicts a key
|
|
|
|
|
// once every timestamp on it is stale, so a stream of forged channel ids
|
|
|
|
|
// could retain an unbounded number of dead map entries for hours.
|
|
|
|
|
ratKey := auth.Key(auth.Key("typing", userID), channelID)
|
|
|
|
|
if limiter != nil && !limiter.Allow(ratKey, 1, 3*time.Second) {
|
|
|
|
|
return nil, nil
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-05 20:42:32 +00:00
|
|
|
return ch, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// GetDMParticipantIDs returns the participant IDs for a DM channel.
|
|
|
|
|
// Convenience method for handlers building DM events.
|
2026-07-23 17:03:52 +02:00
|
|
|
func (s *ChannelService) GetDMParticipantIDs(ctx context.Context, channelID int64) ([]int64, error) {
|
|
|
|
|
return s.st.GetDMParticipantIDs(ctx, channelID)
|
2026-04-05 20:42:32 +00:00
|
|
|
}
|
|
|
|
|
|
2026-08-01 22:06:14 +02:00
|
|
|
// HandlePresenceUpdate validates and persists a presence status change, and
|
|
|
|
|
// (when customStatus is non-nil) the custom status line that came with it.
|
|
|
|
|
//
|
|
|
|
|
// The status is stored as chosen, invisible included; collapsing invisible to
|
|
|
|
|
// offline is a broadcast-time concern (db.BroadcastStatus), not a storage one —
|
|
|
|
|
// the server has to be able to tell "chose to look offline" from "is gone" on
|
|
|
|
|
// the next connect. Returns the sanitized custom status the caller should put
|
|
|
|
|
// on the wire, so the broadcast and the row can never disagree.
|
|
|
|
|
func (s *ChannelService) HandlePresenceUpdate(ctx context.Context, userID int64, status string, customStatus *string, limiter interface {
|
2026-04-05 20:42:32 +00:00
|
|
|
Allow(key string, limit int, window time.Duration) bool
|
2026-04-06 22:48:59 +02:00
|
|
|
},
|
2026-08-01 22:06:14 +02:00
|
|
|
) (*string, error) {
|
2026-04-05 20:42:32 +00:00
|
|
|
// Rate limit.
|
2026-07-31 15:41:57 +02:00
|
|
|
ratKey := auth.Key("presence", userID)
|
2026-04-05 20:42:32 +00:00
|
|
|
if limiter != nil && !limiter.Allow(ratKey, 1, 10*time.Second) {
|
2026-08-01 22:06:14 +02:00
|
|
|
return nil, ErrRateLimited
|
2026-04-05 20:42:32 +00:00
|
|
|
}
|
|
|
|
|
|
2026-08-01 22:06:14 +02:00
|
|
|
if !db.ValidStatuses[status] {
|
|
|
|
|
return nil, fmt.Errorf("%w: invalid status", ErrBadRequest)
|
2026-04-05 20:42:32 +00:00
|
|
|
}
|
2026-08-01 22:06:14 +02:00
|
|
|
|
|
|
|
|
var cleaned *string
|
|
|
|
|
if customStatus != nil {
|
2026-08-20 20:45:30 +02:00
|
|
|
// OC-0195: bound the raw bytes before cleanText (sanitizeToFixpoint)
|
|
|
|
|
// runs — see cleanTextBounded's doc comment (user.go). This path is
|
|
|
|
|
// reachable over the WS presence_update frame, whose read limit is
|
|
|
|
|
// config.MaxMessageBytes (1 MiB), far larger than any REST body that
|
|
|
|
|
// reaches the equivalent guard on SetCustomStatus/UpdateProfile.
|
|
|
|
|
text, err := cleanTextBounded(*customStatus, MaxCustomStatusLen, "custom_status")
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
2026-08-01 22:06:14 +02:00
|
|
|
}
|
|
|
|
|
cleaned = nullable(text)
|
2026-04-05 20:42:32 +00:00
|
|
|
}
|
|
|
|
|
|
2026-08-07 21:20:48 +02:00
|
|
|
// Read the stored custom status BEFORE either write, unconditionally.
|
|
|
|
|
// custom_status is *string with no omitempty on the wire (see
|
|
|
|
|
// presencePayload), so a nil on the broadcast is wire-identical to "the
|
|
|
|
|
// user cleared it" — returning nil for a value we merely failed to read
|
|
|
|
|
// wipes the text on every connected client while the row still holds it.
|
|
|
|
|
// The stored value is needed twice:
|
|
|
|
|
// - when the command carries no custom_status field, it is what rides
|
|
|
|
|
// along on the broadcast (a plain online -> idle flip must not blank
|
|
|
|
|
// everyone else's copy of the text);
|
|
|
|
|
// - when it does carry one and the second write below fails after the
|
|
|
|
|
// status write has already committed, it is the true DB state the
|
|
|
|
|
// broadcast has to report.
|
|
|
|
|
// Doing it first means a read failure aborts before anything commits,
|
|
|
|
|
// instead of leaving a committed status with nothing truthful to say.
|
|
|
|
|
current, readErr := s.st.GetUserByID(ctx, userID)
|
|
|
|
|
if readErr != nil || current == nil {
|
|
|
|
|
slog.Error("ChannelService.HandlePresenceUpdate: could not read stored custom status",
|
|
|
|
|
"err", readErr, "user_id", userID)
|
|
|
|
|
return nil, fmt.Errorf("%w: failed to read current custom status", ErrInternal)
|
|
|
|
|
}
|
|
|
|
|
storedCustomStatus := current.CustomStatus
|
|
|
|
|
|
2026-07-23 17:03:52 +02:00
|
|
|
if err := s.st.UpdateUserStatus(ctx, userID, status); err != nil {
|
2026-04-05 20:42:32 +00:00
|
|
|
slog.Error("ChannelService.HandlePresenceUpdate", "err", err, "user_id", userID)
|
2026-08-01 22:06:14 +02:00
|
|
|
return nil, fmt.Errorf("%w: failed to update status", ErrInternal)
|
|
|
|
|
}
|
2026-08-07 21:20:48 +02:00
|
|
|
|
|
|
|
|
if customStatus == nil {
|
|
|
|
|
return storedCustomStatus, nil
|
2026-04-05 20:42:32 +00:00
|
|
|
}
|
|
|
|
|
|
2026-08-07 21:20:48 +02:00
|
|
|
if err := s.st.UpdateUserCustomStatus(ctx, userID, cleaned); err != nil {
|
|
|
|
|
// The status row is already committed at this point (two independent
|
|
|
|
|
// writes, no transaction), so failing the whole update here would
|
|
|
|
|
// report total failure — and broadcast nothing — for a presence
|
|
|
|
|
// change that in fact partly succeeded, leaving every client
|
|
|
|
|
// (sender included) stuck on the old status while the DB has the
|
|
|
|
|
// new one. Swallow the write failure and broadcast the value that is
|
|
|
|
|
// actually stored, not the unpersisted "cleaned" text.
|
|
|
|
|
slog.Error("ChannelService.HandlePresenceUpdate custom status", "err", err, "user_id", userID)
|
|
|
|
|
return storedCustomStatus, nil //nolint:nilerr // status committed; broadcast the true stored custom status
|
2026-08-01 22:06:14 +02:00
|
|
|
}
|
2026-08-07 21:20:48 +02:00
|
|
|
return cleaned, nil
|
2026-04-05 20:42:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// HandleChannelFocus processes a channel focus event and updates read state.
|
|
|
|
|
// Returns the channel for callers to set client state.
|
2026-07-23 17:03:52 +02:00
|
|
|
func (s *ChannelService) HandleChannelFocus(ctx context.Context, userID, channelID int64) (*db.Channel, error) {
|
2026-04-05 20:42:32 +00:00
|
|
|
if channelID <= 0 {
|
|
|
|
|
return nil, fmt.Errorf("%w: channel_id must be positive", ErrBadRequest)
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-23 17:03:52 +02:00
|
|
|
ch, err := s.st.GetChannel(ctx, channelID)
|
2026-04-05 20:42:32 +00:00
|
|
|
if err != nil || ch == nil {
|
2026-04-06 22:48:59 +02:00
|
|
|
return nil, fmt.Errorf("%w: channel not found", ErrNotFound)
|
2026-04-05 20:42:32 +00:00
|
|
|
}
|
|
|
|
|
|
2026-08-14 18:48:10 +02:00
|
|
|
switch {
|
|
|
|
|
case ch.Type == "dm":
|
2026-07-23 17:03:52 +02:00
|
|
|
ok, err := s.st.IsDMParticipant(ctx, userID, channelID)
|
2026-04-05 20:42:32 +00:00
|
|
|
if err != nil || !ok {
|
|
|
|
|
return nil, fmt.Errorf("%w: access denied", ErrForbidden)
|
|
|
|
|
}
|
2026-08-14 18:48:10 +02:00
|
|
|
case !s.perms.HasChannelPerm(ctx, userID, channelID, permissions.ReadMessages):
|
2026-04-07 10:10:38 +02:00
|
|
|
return nil, fmt.Errorf("%w: access denied", ErrForbidden)
|
2026-08-14 18:48:10 +02:00
|
|
|
case ch.Archived:
|
|
|
|
|
// Archived channels are hidden from every other client surface
|
|
|
|
|
// (ListVisibleChannels, ready payload, reconnect replay, voice join —
|
|
|
|
|
// see permissions.Checker.VisibleChannelIDs and ws/voice_join.go).
|
|
|
|
|
// HasChannelPerm alone doesn't know about the archive flag, so without
|
|
|
|
|
// this a socket that still held the id could resubscribe to the live
|
|
|
|
|
// topic and advance its own read state on a channel reconnect replay
|
|
|
|
|
// then filters back out. channel_focus and mark_read share this one
|
|
|
|
|
// service call, so the guard closes both at once (OC-0070).
|
|
|
|
|
return nil, fmt.Errorf("%w: channel is archived", ErrForbidden)
|
2026-04-05 20:42:32 +00:00
|
|
|
}
|
|
|
|
|
|
2026-08-07 21:20:48 +02:00
|
|
|
// Mark channel as read. latestID == 0 (no undeleted messages) still
|
|
|
|
|
// writes: the upsert is what zeroes mention_count, and a last_read of 0 is
|
|
|
|
|
// correct then — any future message id is larger, so unread counts hold.
|
2026-08-15 20:50:47 +02:00
|
|
|
//
|
|
|
|
|
// Skip the UPSERT when the stored row already says exactly this (same
|
|
|
|
|
// last_message_id, no mentions to clear): channel_focus/mark_read fire on
|
|
|
|
|
// every refocus at up to 10/s/user, and even a no-op write occupies the
|
|
|
|
|
// single writer connection and opens a transaction. The extra read runs on
|
|
|
|
|
// the reader pool, which doesn't serialize. Same problem-shape as the
|
|
|
|
|
// session-touch throttle (api/middleware.go). A read failure falls through
|
|
|
|
|
// to the write — the write is the load-bearing half.
|
2026-07-23 17:03:52 +02:00
|
|
|
latestID, err := s.st.GetLatestMessageID(ctx, channelID)
|
2026-08-07 21:20:48 +02:00
|
|
|
if err == nil {
|
2026-08-15 20:50:47 +02:00
|
|
|
lastRead, mentions, found, rsErr := s.st.GetReadState(ctx, userID, channelID)
|
|
|
|
|
if rsErr == nil && found && lastRead == latestID && mentions == 0 {
|
|
|
|
|
slog.Debug("channel_focus: read state already current, skipping write",
|
|
|
|
|
"user_id", userID, "channel_id", channelID)
|
|
|
|
|
return ch, nil
|
|
|
|
|
}
|
2026-08-20 03:49:13 +02:00
|
|
|
if wErr := s.st.UpdateReadState(ctx, userID, channelID, latestID); wErr != nil {
|
|
|
|
|
// Self-heals on the next focus, but a persistently failing write
|
|
|
|
|
// means unread badges never clear — it must not be invisible.
|
|
|
|
|
slog.Warn("channel_focus: read-state write failed",
|
|
|
|
|
"user_id", userID, "channel_id", channelID, "err", wErr)
|
|
|
|
|
}
|
2026-04-05 20:42:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
slog.Debug("channel_focus", "user_id", userID, "channel_id", channelID)
|
|
|
|
|
return ch, nil
|
|
|
|
|
}
|