Documentation
¶
Index ¶
- Constants
- Variables
- func ButtonAt(m *model.Message, blockID, actionID string) (model.BlockElement, bool)
- func IndexUser(ctx context.Context, idx UserIndexer, u *model.User)
- func IsMachineStateEmoji(emoji string) bool
- func IsNotifiable(k NotificationKind) bool
- func MayClick(e model.BlockElement, userID string) bool
- func NewMobilePushTaskHandler(ack NotificationAckStore, provider MobilePushSender) func(context.Context, *asynq.Task) error
- func PlainMentions(body string) string
- func PushMetricsSnapshot() map[string]int64
- func ReencodeThumbnail(ctx context.Context, objects ThumbnailObjects, key string, dryRun bool) (bool, error)
- func ReminderBotUserID() string
- func ResetPushMetricsForTests()
- func Slugify(name string) string
- func StableMediaURL(ctx context.Context, c MediaURLCache, ...) (string, error)
- func StableMediaURLs(ctx context.Context, c MediaURLCache, namespace string, reqs []MediaURLRequest) map[string]string
- func ValidateEmojiName(name string) error
- func WebhookBotUserID(webhookID string) string
- func WithClickID(ctx context.Context, clickID string) context.Context
- func WithClientNonce(ctx context.Context, nonce string) context.Context
- type ActResult
- type ActivityAdder
- type ActivityReadTracker
- type ActivityRecorder
- type ActivityService
- func (s *ActivityService) AddItem(ctx context.Context, userID string, item *model.ActivityItem)
- func (s *ActivityService) BadgeCount(ctx context.Context, userID string) (int, error)
- func (s *ActivityService) Feed(ctx context.Context, userID string) (model.ActivityFeed, error)
- func (s *ActivityService) MarkParentRead(ctx context.Context, userID, parentID, threadRootID string, position time.Time)
- func (s *ActivityService) MarkSeen(ctx context.Context, userID string) error
- func (s *ActivityService) MessageEdited(ctx context.Context, msg *model.Message, parentType string)
- func (s *ActivityService) MessagesDeleted(ctx context.Context, parentID, parentType string, messageIDs []string)
- func (s *ActivityService) ParentLeft(ctx context.Context, userIDs []string, parentID string)
- func (s *ActivityService) RecordChannelAdded(ctx context.Context, actorID, userID string, ch *model.Channel)
- func (s *ActivityService) RecordForRecipients(ctx context.Context, items map[string]*model.ActivityItem)
- func (s *ActivityService) RecordReaction(ctx context.Context, msg *model.Message, parentType, actorID, emoji string)
- func (s *ActivityService) RemoveItems(ctx context.Context, userID string, ids []string) error
- func (s *ActivityService) SetChannelResolver(c ChannelSlugResolver)
- func (s *ActivityService) SetDeactivatedAccounts(d DeactivatedAccounts)
- func (s *ActivityService) SetItemsRead(ctx context.Context, userID string, ids []string, read bool) error
- func (s *ActivityService) SetMemberLister(m ParentMemberLister)
- func (s *ActivityService) SetMentionResolver(r MentionResolver)
- func (s *ActivityService) Wired() error
- type ActivityStore
- type AgentDispatcher
- type AgentUploadParams
- type AppClickResult
- type AppClicker
- type AppInteractionState
- type AppResponse
- type AppSigner
- type AsynqPushScheduler
- func (s *AsynqPushScheduler) Close() error
- func (s *AsynqPushScheduler) EnqueueSharePoint(ctx context.Context, t SharePointTask) error
- func (s *AsynqPushScheduler) ScheduleNotifyCheck(ctx context.Context, msg *model.Message, parentType string) error
- func (s *AsynqPushScheduler) SchedulePush(ctx context.Context, recipientUserID string, n Notification, ...) error
- type AsynqPushWorker
- type AsynqPushWorkerConfig
- type AttachmentAccessChecker
- type AttachmentRefManager
- type AttachmentService
- func (s *AttachmentService) AddRef(ctx context.Context, attachmentID, messageID string) error
- func (s *AttachmentService) AttachmentOwner(ctx context.Context, id string) (createdBy string, messageIDs []string, err error)
- func (s *AttachmentService) CreateUploadURL(ctx context.Context, p CreateUploadParams) (*CreateUploadResult, error)
- func (s *AttachmentService) DeleteDraft(ctx context.Context, userID, attachmentID string) error
- func (s *AttachmentService) ForRunPost(ctx context.Context, id, runID, agentID string) (*model.Attachment, error)
- func (s *AttachmentService) Get(ctx context.Context, id string) (*model.Attachment, error)
- func (s *AttachmentService) GetForUser(ctx context.Context, userID, id, parentID, parentType, messageID string) (*model.Attachment, error)
- func (s *AttachmentService) GetMany(ctx context.Context, ids []string) ([]*model.Attachment, error)
- func (s *AttachmentService) GetManyForUser(ctx context.Context, userID string, ids []string, ...) ([]*model.Attachment, error)
- func (s *AttachmentService) LoadForPreview(ctx context.Context, ids []string) []*model.Attachment
- func (s *AttachmentService) LoadMany(ctx context.Context, ids []string) (map[string]*model.Attachment, error)
- func (s *AttachmentService) OpenByID(ctx context.Context, id string) (io.ReadCloser, *model.Attachment, error)
- func (s *AttachmentService) OpenForUser(ctx context.Context, userID, id, parentID, parentType, messageID string) (io.ReadCloser, *model.Attachment, error)
- func (s *AttachmentService) OpenMedia(ctx context.Context, token, grant, byteRange string) (*MediaObject, error)
- func (s *AttachmentService) ProcessUpload(ctx context.Context, userID, attachmentID string) (*model.Attachment, error)
- func (s *AttachmentService) ReadyForReader(ctx context.Context, a *model.Attachment, grant MediaGrant)
- func (s *AttachmentService) RemoveRef(ctx context.Context, attachmentID, messageID string) error
- func (s *AttachmentService) SetAccessChecker(c AttachmentAccessChecker)
- func (s *AttachmentService) SetMediaGrantKey(secret []byte)
- func (s *AttachmentService) SetMediaURLCache(c MediaURLCache)
- func (s *AttachmentService) SetUploadLimits(l uploadLimits)
- func (s *AttachmentService) SetVideoPoster(ctx context.Context, userID, attachmentID string, body io.Reader) (*model.Attachment, error)
- func (s *AttachmentService) SignUploadRequest(ctx context.Context, userID, attachmentID string, req UploadRequest) (*SignedUploadRequest, error)
- func (s *AttachmentService) UploadForAgent(ctx context.Context, p AgentUploadParams) (*model.Attachment, error)
- func (s *AttachmentService) ValidateForUse(ctx context.Context, attachmentID string) error
- func (s *AttachmentService) Wired() error
- type AttachmentSigner
- type AttachmentStore
- type AudienceCache
- type AudienceGenerations
- type AudienceInvalidator
- type AuthService
- func (s *AuthService) AcceptInvite(ctx context.Context, token, displayName, password string) (accessToken, refreshTokenRaw string, user *model.User, err error)
- func (s *AuthService) ConsumeDesktopAuthSession(ctx context.Context, code string) (*DesktopAuthSession, error)
- func (s *AuthService) CreateDesktopAuthSession(ctx context.Context, refreshToken string) (string, error)
- func (s *AuthService) CreateInvite(ctx context.Context, inviterID, inviteeEmail string, channelIDs []string) (*model.Invite, error)
- func (s *AuthService) CreatePasswordResetForUser(ctx context.Context, targetUserID string) (*PasswordResetTicket, error)
- func (s *AuthService) GuestLogin(ctx context.Context, email, password string) (accessToken, refreshTokenRaw string, user *model.User, err error)
- func (s *AuthService) HandleOIDCCallback(ctx context.Context, code, state, nonce string) (accessToken, refreshTokenRaw string, user *model.User, err error)
- func (s *AuthService) HandleOIDCLogin() (authURL, state, nonce string, err error)
- func (s *AuthService) Logout(ctx context.Context, refreshTokenRaw string) error
- func (s *AuthService) RefreshAccessToken(ctx context.Context, refreshTokenRaw string) (accessToken, newRefreshRaw string, err error)
- func (s *AuthService) RequestPasswordReset(ctx context.Context, rawEmail string) error
- func (s *AuthService) ResetPassword(ctx context.Context, token, password string) error
- func (s *AuthService) SetAllowedEmailDomains(domains []string)
- func (s *AuthService) SetBackgroundRunner(run func(fn func()))
- func (s *AuthService) SetChannelJoiner(j ChannelJoiner)
- func (s *AuthService) SetDelegatedTokens(t DelegatedTokenSaver)
- func (s *AuthService) SetDirectory(d DirectoryLookup)
- func (s *AuthService) SetGuestLoginAnyRole(v bool)
- func (s *AuthService) SetIndexer(i UserIndexer)
- func (s *AuthService) SetMailer(m email.Sender, baseURL string)
- func (s *AuthService) SetPasswordResetStore(st PasswordResetStore)
- func (s *AuthService) SetPublisher(p Publisher)
- func (s *AuthService) SetRunnerRevoker(r RunnerRevoker)
- func (s *AuthService) SetSessionMaxAge(d time.Duration)
- func (s *AuthService) Wired() error
- type AutomationStopper
- type AvatarObjects
- type AvatarSigner
- type BotAccountDirectory
- type BotActor
- type BotInput
- type BotService
- func (s *BotService) Authenticate(ctx context.Context, secret string) (*model.TokenClaims, error)
- func (s *BotService) Create(ctx context.Context, actor BotActor, in BotInput) (*model.User, error)
- func (s *BotService) CreateToken(ctx context.Context, actor BotActor, botID, description string) (*model.BotTokenIssued, error)
- func (s *BotService) Delete(ctx context.Context, actor BotActor, id string) error
- func (s *BotService) List(ctx context.Context, actor BotActor) ([]*model.User, error)
- func (s *BotService) ListTokens(ctx context.Context, actor BotActor, botID string) ([]*model.BotToken, error)
- func (s *BotService) RevokeToken(ctx context.Context, actor BotActor, botID, tokenID string) error
- func (s *BotService) SetEnabled(ctx context.Context, actor BotActor, id string, enabled bool) (*model.User, error)
- func (s *BotService) Update(ctx context.Context, actor BotActor, id string, in BotInput) (*model.User, error)
- type BotStore
- type Broker
- type Cache
- type CachedMemberships
- func (c *CachedMemberships) GetMembership(ctx context.Context, channelID, userID string) (*model.ChannelMembership, error)
- func (c *CachedMemberships) ListMembers(ctx context.Context, channelID string) ([]*model.ChannelMembership, error)
- func (c *CachedMemberships) SetUserChannelName(ctx context.Context, channelID, userID, name string) error
- type CategoryService
- func (s *CategoryService) Create(ctx context.Context, userID, name string) (*model.UserChannelCategory, error)
- func (s *CategoryService) Delete(ctx context.Context, userID, categoryID string) error
- func (s *CategoryService) List(ctx context.Context, userID string) ([]*model.UserChannelCategory, error)
- func (s *CategoryService) Move(ctx context.Context, userID, categoryID, afterID string) ([]*model.UserChannelCategory, error)
- func (s *CategoryService) Update(ctx context.Context, userID, categoryID string, name *string, position *int) (*model.UserChannelCategory, error)
- type CategoryStore
- type ChannelActivityRecorder
- type ChannelIndexer
- type ChannelJoiner
- type ChannelMemberCache
- type ChannelMembershipReader
- type ChannelReader
- type ChannelReminderSync
- type ChannelSearcher
- type ChannelService
- func (s *ChannelService) AddMember(ctx context.Context, actorID, channelID, userID string, role model.ChannelRole) error
- func (s *ChannelService) Archive(ctx context.Context, actorID, channelID string) error
- func (s *ChannelService) AutoJoinChannel(ctx context.Context, userID, channelID string, role model.ChannelRole) error
- func (s *ChannelService) BrowsePublic(ctx context.Context, userID string, limit int, cursor string) ([]*model.Channel, string, error)
- func (s *ChannelService) ConvertGroupConversation(ctx context.Context, actorID, convID, name string) (*model.Channel, error)
- func (s *ChannelService) Create(ctx context.Context, userID, name string, chanType model.ChannelType, ...) (*model.Channel, error)
- func (s *ChannelService) CreateWithID(ctx context.Context, userID, id, name string, chanType model.ChannelType, ...) (*model.Channel, error)
- func (s *ChannelService) GetByID(ctx context.Context, id string) (*model.Channel, error)
- func (s *ChannelService) GetBySlug(ctx context.Context, slug string) (*model.Channel, error)
- func (s *ChannelService) GetVisibleByID(ctx context.Context, actorID, id string) (*model.Channel, error)
- func (s *ChannelService) GetVisibleBySlug(ctx context.Context, actorID, slug string) (*model.Channel, error)
- func (s *ChannelService) IsMember(ctx context.Context, userID, channelID string) bool
- func (s *ChannelService) Join(ctx context.Context, userID, channelID string) error
- func (s *ChannelService) Leave(ctx context.Context, userID, channelID string) error
- func (s *ChannelService) ListMembers(ctx context.Context, actorID, channelID string) ([]*model.ChannelMembership, error)
- func (s *ChannelService) ListUserChannelIDs(ctx context.Context, userID string) ([]string, error)
- func (s *ChannelService) ListUserChannels(ctx context.Context, userID string) ([]*model.UserChannel, error)
- func (s *ChannelService) MakePrivate(ctx context.Context, actorID, channelID string) (*model.Channel, error)
- func (s *ChannelService) MarkChannelRead(ctx context.Context, userID, channelID string) error
- func (s *ChannelService) NameAvailable(ctx context.Context, name, exceptChannelID string) (bool, error)
- func (s *ChannelService) RemoveMember(ctx context.Context, actorID, channelID, targetID string) error
- func (s *ChannelService) SearchPublic(ctx context.Context, userID, q string, limit int) ([]*model.Channel, error)
- func (s *ChannelService) SetActivityRecorder(a ChannelActivityRecorder)
- func (s *ChannelService) SetAudienceInvalidator(a AudienceInvalidator)
- func (s *ChannelService) SetCategory(ctx context.Context, userID, channelID, categoryID string, ...) error
- func (s *ChannelService) SetConversationConverter(c ConversationConverter, drafts ConversationDraftMover)
- func (s *ChannelService) SetDeactivatedAccounts(d DeactivatedAccounts)
- func (s *ChannelService) SetFavorite(ctx context.Context, userID, channelID string, favorite bool) error
- func (s *ChannelService) SetIndexer(i ChannelIndexer)
- func (s *ChannelService) SetMute(ctx context.Context, userID, channelID string, muted bool) error
- func (s *ChannelService) SetNotificationPrefs(ctx context.Context, userID, channelID string, ...) error
- func (s *ChannelService) SetReminderSync(r ChannelReminderSync)
- func (s *ChannelService) SetSearcher(sr ChannelSearcher)
- func (s *ChannelService) SetSharePointSync(sp ChannelSharePointSync)
- func (s *ChannelService) SetThreadStateSync(t ChannelThreadStateSync)
- func (s *ChannelService) Unarchive(ctx context.Context, actorID, channelID string) error
- func (s *ChannelService) Update(ctx context.Context, actorID, channelID string, name, description *string) (*model.Channel, error)
- func (s *ChannelService) UpdateMemberRole(ctx context.Context, actorID, channelID, targetID string, ...) error
- func (s *ChannelService) Wired() error
- type ChannelSharePointSync
- type ChannelSlugResolver
- type ChannelStore
- type ChannelThreadStateSync
- type ClickLimiter
- type Command
- type CommandInfo
- type CommandRequest
- type CommandService
- type CommandUserError
- type ConversationActivator
- type ConversationConverter
- type ConversationDraftMover
- type ConversationService
- func (s *ConversationService) Activate(ctx context.Context, convID string) error
- func (s *ConversationService) ActivateLoaded(ctx context.Context, conv *model.Conversation) error
- func (s *ConversationService) CreateGroup(ctx context.Context, creatorID string, participantIDs []string, name string) (*model.Conversation, error)
- func (s *ConversationService) GetByID(ctx context.Context, userID, convID string) (*model.Conversation, error)
- func (s *ConversationService) GetOrCreateDM(ctx context.Context, userA, userB string) (*model.Conversation, error)
- func (s *ConversationService) GetOrCreateGroup(ctx context.Context, creatorID string, participantIDs []string, name string) (*model.Conversation, error)
- func (s *ConversationService) IsParticipant(ctx context.Context, userID, convID string) bool
- func (s *ConversationService) ListUserConversationIDs(ctx context.Context, userID string) ([]string, error)
- func (s *ConversationService) ListUserConversations(ctx context.Context, userID string) ([]*model.UserConversation, error)
- func (s *ConversationService) MarkConversationRead(ctx context.Context, userID, convID string) error
- func (s *ConversationService) SetActivityTracker(t ActivityReadTracker)
- func (s *ConversationService) SetCategory(ctx context.Context, userID, convID, categoryID string, sidebarPosition *int) error
- func (s *ConversationService) SetChannelMemberships(m ChannelMembershipReader)
- func (s *ConversationService) SetFavorite(ctx context.Context, userID, convID string, favorite bool) error
- func (s *ConversationService) SetMediaURLCache(c MediaURLCache)
- func (s *ConversationService) SetUserProfileResolver(r interface{ ... })
- func (s *ConversationService) Wired() error
- type ConversationStore
- type CreateUploadParams
- type CreateUploadResult
- type DeactivatedAccounts
- type DelegatedTokenSaver
- type DelegatedTokenStore
- type DelegatedTokens
- type DesktopAuthSession
- type DirectNotifier
- type DirectoryAccountLister
- type DirectoryLookup
- type DirectoryProfile
- type DirectoryStatusSetter
- type DirectorySyncLocker
- type DirectorySyncService
- func (s *DirectorySyncService) Run(ctx context.Context, interval time.Duration)
- func (s *DirectorySyncService) RunStatus(ctx context.Context, interval time.Duration)
- func (s *DirectorySyncService) SetStatusSync(accounts DirectoryAccountLister, st DirectoryStatusSetter)
- func (s *DirectorySyncService) Sweep(ctx context.Context, interval time.Duration)
- func (s *DirectorySyncService) SweepStatus(ctx context.Context, interval time.Duration)
- func (s *DirectorySyncService) Wired() error
- type DraftAttachmentReleaser
- type DraftConflictError
- type DraftService
- func (s *DraftService) Delete(ctx context.Context, userID, id, basisGen string) error
- func (s *DraftService) DeleteForScope(ctx context.Context, userID, parentID, parentType, parentMessageID string) error
- func (s *DraftService) List(ctx context.Context, userID string) ([]*model.MessageDraft, error)
- func (s *DraftService) MoveConversationDrafts(ctx context.Context, userIDs []string, conversationID string)
- func (s *DraftService) Upsert(ctx context.Context, ...) (*model.MessageDraft, error)
- type DraftStore
- type EmojiFrequencyStore
- type EmojiService
- func (s *EmojiService) Create(ctx context.Context, userID, name, imageKey string, gettingWorkDone bool) (*model.CustomEmoji, error)
- func (s *EmojiService) Delete(ctx context.Context, userID, name string) error
- func (s *EmojiService) FrequentEmojis(ctx context.Context, userID string, limit int) ([]string, error)
- func (s *EmojiService) List(ctx context.Context) ([]*model.CustomEmoji, error)
- func (s *EmojiService) RecordEmojiUse(ctx context.Context, userID, shortcode string) error
- func (s *EmojiService) SetCatalogCache(c Cache)
- func (s *EmojiService) SetFrequencyStore(f EmojiFrequencyStore)
- func (s *EmojiService) SetMediaURLCache(c MediaURLCache)
- func (s *EmojiService) SetSigner(signer EmojiURLSigner)
- func (s *EmojiService) Wired() error
- type EmojiStore
- type EmojiURLSigner
- type FileEntry
- type FileIndexEntry
- type FilePage
- type FileQuery
- type GraphDirectory
- type HastNode
- type IncomingWebhookPayload
- type IncomingWebhookService
- func (s *IncomingWebhookService) Create(ctx context.Context, actor WebhookActor, in *model.IncomingWebhook) (*model.IncomingWebhook, error)
- func (s *IncomingWebhookService) Delete(ctx context.Context, actor WebhookActor, id string) error
- func (s *IncomingWebhookService) DeleteTemplate(ctx context.Context, actor WebhookActor, id, key string) (*model.IncomingWebhook, error)
- func (s *IncomingWebhookService) Execute(ctx context.Context, id string, payload IncomingWebhookPayload) error
- func (s *IncomingWebhookService) ExecuteClassic(ctx context.Context, id string, payload IncomingWebhookPayload) (*model.Message, error)
- func (s *IncomingWebhookService) ExecuteMessage(ctx context.Context, id string, payload IncomingWebhookPayload) (*model.Message, error)
- func (s *IncomingWebhookService) ExecuteRich(ctx context.Context, id string, payload IncomingWebhookPayload) (*model.Message, error)
- func (s *IncomingWebhookService) List(ctx context.Context, actor WebhookActor) ([]*model.IncomingWebhook, error)
- func (s *IncomingWebhookService) PreviewMessage(ctx context.Context, actor WebhookActor, payload IncomingWebhookPayload) (*model.Message, error)
- func (s *IncomingWebhookService) SaveTemplate(ctx context.Context, actor WebhookActor, id, key string, ...) (*model.IncomingWebhook, error)
- func (s *IncomingWebhookService) SetBotProvisioner(b WebhookBotProvisioner)
- func (s *IncomingWebhookService) SetDMResolver(dms WebhookDMResolver)
- func (s *IncomingWebhookService) SetMembershipResolver(m WebhookMembershipResolver)
- func (s *IncomingWebhookService) SetPublisher(p Publisher)
- func (s *IncomingWebhookService) SetUserResolver(users WebhookUserResolver)
- func (s *IncomingWebhookService) TranslateMarkup(ctx context.Context, text string) string
- func (s *IncomingWebhookService) URL(wh *model.IncomingWebhook) string
- func (s *IncomingWebhookService) Update(ctx context.Context, actor WebhookActor, id string, in *model.IncomingWebhook) (*model.IncomingWebhook, error)
- func (s *IncomingWebhookService) Wired() error
- type IncomingWebhookStore
- type InteractionConfig
- type InteractionService
- func (s *InteractionService) AuthenticateApp(ctx context.Context, token string) (*model.IncomingWebhook, error)
- func (s *InteractionService) Click(ctx context.Context, msg *model.Message, parentType string, ...) (*AppClickResult, error)
- func (s *InteractionService) CloseView(ctx context.Context, userID, viewID string, all bool, ...) error
- func (s *InteractionService) Idempotent(ctx context.Context, wh *model.IncomingWebhook, method, key string, ...) ([]byte, error)
- func (s *InteractionService) OpenView(ctx context.Context, wh *model.IncomingWebhook, triggerID string, ...) (_ *model.View, err error)
- func (s *InteractionService) PreviewView(ctx context.Context, actor WebhookActor, in model.View) (*model.View, error)
- func (s *InteractionService) PushView(ctx context.Context, wh *model.IncomingWebhook, triggerID string, ...) (_ *model.View, err error)
- func (s *InteractionService) Respond(ctx context.Context, token string, resp AppResponse) error
- func (s *InteractionService) RotateBotToken(ctx context.Context, actor WebhookActor, id string, revokeNow bool) (string, *model.IncomingWebhook, error)
- func (s *InteractionService) RotateSigningSecret(ctx context.Context, actor WebhookActor, id string, revokeNow bool) (string, *model.IncomingWebhook, error)
- func (s *InteractionService) SendTest(ctx context.Context, actor WebhookActor, id string) (*TestResult, error)
- func (s *InteractionService) SetAdminPaused(ctx context.Context, actor WebhookActor, id string, paused bool) (*model.IncomingWebhook, error)
- func (s *InteractionService) SetEmailSharing(ctx context.Context, actor WebhookActor, id string, on bool) (*model.IncomingWebhook, error)
- func (s *InteractionService) SetRequestURL(ctx context.Context, actor WebhookActor, id, raw string) (*model.IncomingWebhook, error)
- func (s *InteractionService) Status(ctx context.Context, actor WebhookActor, id string) (*InteractionStatus, error)
- func (s *InteractionService) SubmitView(ctx context.Context, userID, viewID string, raw map[string]map[string]RawValue) (*ViewSubmitResult, error)
- func (s *InteractionService) UpdateMessage(ctx context.Context, wh *model.IncomingWebhook, in MessageUpdate) (_ *model.Message, err error)
- func (s *InteractionService) UpdateView(ctx context.Context, wh *model.IncomingWebhook, ...) (_ *model.View, err error)
- func (s *InteractionService) ViewAction(ctx context.Context, userID, viewID, blockID, actionID string, value RawValue, ...) (*ViewActionResult, error)
- type InteractionStatus
- type InviteStore
- type JWTProvider
- type MSDirectoryService
- type MarkdownRenderer
- type MarkupTranslator
- type MattermostChannels
- type MattermostDMs
- type MattermostMessages
- type MattermostService
- func (s *MattermostService) AddChannelMember(ctx context.Context, actorID, channelID, userID string) (*model.ChannelMembership, error)
- func (s *MattermostService) CreateChannel(ctx context.Context, actorID, name string, private bool, purpose string) (*model.Channel, error)
- func (s *MattermostService) CreatePost(ctx context.Context, actorID, channelID, message, rootID string) (*model.Message, error)
- func (s *MattermostService) DirectChannel(ctx context.Context, actorID string, userIDs []string) (*model.Conversation, error)
- type MediaGrant
- type MediaObject
- type MediaObjectStore
- type MediaURLBatchCache
- type MediaURLCache
- type MediaURLRequest
- type MeetingCreator
- type MeetingMessageSender
- type MeetingUserResolver
- type MembershipGetter
- type MembershipStore
- type MentionDirectory
- type MentionNames
- type MentionResolver
- type MentionUser
- type MessageActivityRecorder
- type MessageIndexer
- type MessageLinkService
- type MessageNotifier
- type MessageReminderSync
- type MessageService
- func (s *MessageService) Act(ctx context.Context, ...) (*ActResult, error)
- func (s *MessageService) ActWithValue(ctx context.Context, ...) (*ActResult, error)
- func (s *MessageService) CanAccessMessageAttachment(ctx context.Context, ...) error
- func (s *MessageService) CheckAccess(ctx context.Context, userID, parentID, parentType string) error
- func (s *MessageService) CheckWriteAccess(ctx context.Context, userID, parentID, parentType string) error
- func (s *MessageService) Delete(ctx context.Context, userID, parentID, parentType, msgID string) error
- func (s *MessageService) Edit(ctx context.Context, userID, parentID, parentType, msgID, newBody string, ...) (*model.Message, error)
- func (s *MessageService) List(ctx context.Context, userID, parentID, parentType, before string, limit int) ([]*model.Message, bool, error)
- func (s *MessageService) ListAfter(ctx context.Context, userID, parentID, parentType, after string, limit int) ([]*model.Message, bool, error)
- func (s *MessageService) ListAround(ctx context.Context, userID, parentID, parentType, msgID string, ...) ([]*model.Message, bool, bool, error)
- func (s *MessageService) ListFiles(ctx context.Context, userID, parentID, parentType string, q FileQuery) (*FilePage, error)
- func (s *MessageService) ListPinned(ctx context.Context, userID, parentID, parentType string) ([]*model.Message, error)
- func (s *MessageService) ListThreadMessages(ctx context.Context, userID, parentID, parentType, threadRootID string) ([]*model.Message, error)
- func (s *MessageService) ListThreadsPage(ctx context.Context, userID, cursor string, limit int) (*ThreadPage, error)
- func (s *MessageService) MarkUnread(ctx context.Context, userID, parentID, parentType, msgID string) (*model.MarkUnreadResult, error)
- func (s *MessageService) MessageAttachmentIDs(ctx context.Context, userID, parentID, parentType, messageID string) (map[string]bool, error)
- func (s *MessageService) NotificationsWired() error
- func (s *MessageService) ParentMemberIDs(ctx context.Context, parentID, parentType string) ([]string, error)
- func (s *MessageService) ResolveThreadRoot(ctx context.Context, userID, parentID, parentType, msgID string) (string, error)
- func (s *MessageService) RewriteAgentMessage(ctx context.Context, agentID, parentID, parentType, msgID, body string) (*model.Message, error)
- func (s *MessageService) Send(ctx context.Context, ...) (*model.Message, error)
- func (s *MessageService) SendAsAgent(ctx context.Context, ...) (*model.Message, error)
- func (s *MessageService) SendAsAgentRun(ctx context.Context, ...) (*model.Message, error)
- func (s *MessageService) SendNoIndex(ctx context.Context, ...) (*model.Message, error)
- func (s *MessageService) SendReminder(ctx context.Context, in WebhookMessageInput) (*model.Message, error)
- func (s *MessageService) SendScheduled(ctx context.Context, ...) (*model.Message, error)
- func (s *MessageService) SendWebhook(ctx context.Context, in WebhookMessageInput) (*model.Message, error)
- func (s *MessageService) SetActivator(a ConversationActivator)
- func (s *MessageService) SetActivityRecorder(r MessageActivityRecorder)
- func (s *MessageService) SetAgentDispatcher(d AgentDispatcher)
- func (s *MessageService) SetAppClicker(c AppClicker)
- func (s *MessageService) SetAttachmentManager(a AttachmentRefManager)
- func (s *MessageService) SetChannelReader(c ChannelReader)
- func (s *MessageService) SetChannelSeqStore(c UnreadSeqStore)
- func (s *MessageService) SetConversationSeqStore(c UnreadSeqStore)
- func (s *MessageService) SetDeactivatedAccounts(d DeactivatedAccounts)
- func (s *MessageService) SetDraftClearer(c SentDraftClearer)
- func (s *MessageService) SetIndexer(i MessageIndexer)
- func (s *MessageService) SetMachineReaction(ctx context.Context, ...) error
- func (s *MessageService) SetMarkdownRenderer(m *MarkdownRenderer)
- func (s *MessageService) SetMentionResolver(r MentionResolver)
- func (s *MessageService) SetNoUnfurl(ctx context.Context, userID, parentID, parentType, msgID string, noUnfurl bool) (*model.Message, error)
- func (s *MessageService) SetNotifier(n MessageNotifier)
- func (s *MessageService) SetNotifySafetyNet(n NotifySafetyNet)
- func (s *MessageService) SetParentIndex(p ParentPinFileIndexStore)
- func (s *MessageService) SetPinned(ctx context.Context, userID, parentID, parentType, msgID string, pinned bool) (*model.Message, error)
- func (s *MessageService) SetReminderSync(r MessageReminderSync)
- func (s *MessageService) SetRunLogPurger(p RunLogPurger)
- func (s *MessageService) SetRunSkillResolver(f func(ctx context.Context, runID string) []string)
- func (s *MessageService) SetSharePoint(sp MessageSharePoint)
- func (s *MessageService) SetThreadFollow(ctx context.Context, userID, parentID, parentType, threadRootID string, ...) error
- func (s *MessageService) SetThreadFollowStore(f ThreadFollowStore)
- func (s *MessageService) SetUserStateStore(userState UserStateStore)
- func (s *MessageService) ThreadFollowing(ctx context.Context, userID, parentID, parentType, threadRootID string) (bool, error)
- func (s *MessageService) ThreadWindowMessages(ctx context.Context, userID, parentID, parentType, threadRootID string, ...) ([]*model.Message, error)
- func (s *MessageService) ToggleReaction(ctx context.Context, userID, parentID, parentType, msgID, emoji string) (*model.Message, error)
- func (s *MessageService) ToggleReactionAsAgent(ctx context.Context, ...) (*model.Message, error)
- func (s *MessageService) WaitForNotifyFanOut()
- func (s *MessageService) Wired() error
- type MessageServiceDeps
- type MessageSharePoint
- type MessageStore
- type MessageUpdate
- type MobilePushScheduler
- type MobilePushSender
- type NameCache
- type Notification
- type NotificationAckStore
- type NotificationKind
- type NotificationService
- func (s *NotificationService) NotificationsWired() error
- func (s *NotificationService) NotifyCheckTaskHandler() func(context.Context, *asynq.Task) error
- func (s *NotificationService) NotifyDirect(ctx context.Context, userID string, notif Notification)
- func (s *NotificationService) NotifyForMessage(ctx context.Context, msg *model.Message, parentType string, ...)
- func (s *NotificationService) SetAckStore(store NotificationAckStore)
- func (s *NotificationService) SetActivityRecorder(a ActivityRecorder)
- func (s *NotificationService) SetAudienceCache(c *AudienceCache)
- func (s *NotificationService) SetMentionResolver(r MentionResolver)
- func (s *NotificationService) SetMobilePushScheduler(sched MobilePushScheduler)
- func (s *NotificationService) SetNameCache(c NameCache)
- func (s *NotificationService) SetNotifyMarker(m NotifyMarker)
- func (s *NotificationService) SetPresence(p PresenceLookup)
- func (s *NotificationService) SetThreadFollowStore(f ThreadFollowStore)
- func (s *NotificationService) SetUserStateService(userState *UserStateService)
- func (s *NotificationService) Wired() error
- type NotificationServiceDeps
- type NotifyMarker
- type NotifySafetyNet
- type OIDCProvider
- type OIDCUserInfo
- type OfficeUpload
- type OneSignalConfig
- type OneSignalPushSender
- type ParentMemberLister
- type ParentPinFileIndexStore
- type ParsedMentions
- type PasswordResetStore
- type PasswordResetTicket
- type PinIndexEntry
- type PresenceBatchLookup
- type PresenceLookup
- type PresenceService
- func (s *PresenceService) IsOnline(userID string) bool
- func (s *PresenceService) OnConnect(ctx context.Context, userID, connID string, topics ...string) bool
- func (s *PresenceService) OnDisconnect(ctx context.Context, userID, connID string, topics ...string) bool
- func (s *PresenceService) OnlineMany(userIDs []string) map[string]bool
- func (s *PresenceService) OnlineUserIDs() []string
- func (s *PresenceService) Refresh(ctx context.Context, userID, connID string)
- func (s *PresenceService) SetPresenceAudienceResolver(fn func(ctx context.Context, userID string) []string)
- func (s *PresenceService) Wired() error
- type PresenceStore
- type Publisher
- type RateLimitedError
- type RawValue
- type RedisAudienceGenerations
- type RedisNotifyMarker
- type ReminderAccessChecker
- type ReminderBotProvisioner
- type ReminderCanceller
- type ReminderDMOpener
- type ReminderInput
- type ReminderMessageStore
- type ReminderOwnerLookup
- type ReminderPoster
- type ReminderService
- func (s *ReminderService) Cancel(ctx context.Context, userID, id string) error
- func (s *ReminderService) CancelAllForUser(ctx context.Context, userID string) error
- func (s *ReminderService) ListPending(ctx context.Context, userID string) ([]*model.Reminder, error)
- func (s *ReminderService) MessageEdited(ctx context.Context, msg *model.Message, _ string)
- func (s *ReminderService) MessagesDeleted(ctx context.Context, parentID, _ string, messageIDs []string)
- func (s *ReminderService) ParentLeft(ctx context.Context, userIDs []string, parentID string)
- func (s *ReminderService) ProcessDue(ctx context.Context) (int, error)
- func (s *ReminderService) Schedule(ctx context.Context, userID string, in ReminderInput) (*model.Reminder, error)
- func (s *ReminderService) SetBot(poster ReminderPoster, bots ReminderBotProvisioner, dms ReminderDMOpener, ...)
- func (s *ReminderService) SetDelivery(activity ActivityAdder, notifier DirectNotifier)
- func (s *ReminderService) SetMentionResolver(r MentionResolver)
- func (s *ReminderService) SetOwnerLookup(o ReminderOwnerLookup)
- func (s *ReminderService) SetPublisher(p Publisher)
- func (s *ReminderService) Update(ctx context.Context, userID, id string, in ReminderUpdate) (*model.Reminder, error)
- func (s *ReminderService) Wired() error
- type ReminderStore
- type ReminderUpdate
- type RunLogPurger
- type RunnerRevoker
- type ScheduledMessageInput
- type ScheduledMessageSender
- type ScheduledMessageService
- func (s *ScheduledMessageService) Delete(ctx context.Context, userID, id string) error
- func (s *ScheduledMessageService) List(ctx context.Context, userID string) ([]*model.ScheduledMessage, error)
- func (s *ScheduledMessageService) ProcessDue(ctx context.Context) (int, error)
- func (s *ScheduledMessageService) Schedule(ctx context.Context, userID string, in ScheduledMessageInput) (*model.ScheduledMessage, error)
- func (s *ScheduledMessageService) SendNow(ctx context.Context, userID, id string) (*model.Message, error)
- func (s *ScheduledMessageService) SetDraftClearer(c SentDraftClearer)
- func (s *ScheduledMessageService) Update(ctx context.Context, userID, id string, upd ScheduledMessageUpdate) (*model.ScheduledMessage, error)
- func (s *ScheduledMessageService) Wired() error
- type ScheduledMessageUpdate
- type SentDraftClearer
- type SettingsService
- func (s *SettingsService) AllowsExtension(ctx context.Context, filename string) bool
- func (s *SettingsService) AllowsSize(ctx context.Context, size int64) bool
- func (s *SettingsService) Effective(ctx context.Context) *model.WorkspaceSettings
- func (s *SettingsService) SetPublisher(p Publisher)
- func (s *SettingsService) Update(ctx context.Context, ws *model.WorkspaceSettings) (*model.WorkspaceSettings, error)
- func (s *SettingsService) Wired() error
- type SettingsStore
- type SharePointAccess
- type SharePointChannels
- type SharePointConversations
- type SharePointDeps
- type SharePointFileEntry
- type SharePointGraph
- type SharePointLocker
- type SharePointMembers
- type SharePointMessages
- type SharePointQueue
- type SharePointRecords
- type SharePointService
- func (s *SharePointService) Files(ctx context.Context, parentID string) ([]SharePointFileEntry, error)
- func (s *SharePointService) Hosts() []string
- func (s *SharePointService) Link(ctx context.Context, viewerID, parentID, parentType, rawURL string) (*model.SharePointLink, error)
- func (s *SharePointService) MemberJoined(ctx context.Context, channelID, userID string)
- func (s *SharePointService) MessageEdited(ctx context.Context, before, after *model.Message, parentType string)
- func (s *SharePointService) MessageSent(ctx context.Context, msg *model.Message, parentType string)
- func (s *SharePointService) MessagesDeleted(ctx context.Context, parentID, parentType string, ids []string)
- func (s *SharePointService) ParentLeft(ctx context.Context, userIDs []string, parentID string)
- func (s *SharePointService) Preview(ctx context.Context, viewerID, parentID, parentType, fileID string) (string, error)
- func (s *SharePointService) RetryLink(ctx context.Context, userID, parentID, parentType, rawURL string) error
- func (s *SharePointService) SaveDelegatedToken(ctx context.Context, userID string, tok *oauth2.Token) error
- func (s *SharePointService) TaskHandler() func(context.Context, *asynq.Task) error
- func (s *SharePointService) UploadOfficeFile(ctx context.Context, userID, parentID, parentType, name string, body io.Reader, ...) (*OfficeUpload, error)
- type SharePointTask
- type SharePointTokens
- type SharePointUploadLimits
- type SharePointUsers
- type SidebarMove
- type SidebarOrderStore
- type SidebarService
- type SignedUploadRequest
- type TeamsMeetingCommand
- type TeamsMeetingDeps
- type TestResult
- type ThreadFollowStore
- type ThreadPage
- type ThreadSummary
- type ThumbnailObjects
- type TokenStore
- type UnfurlAttachment
- type UnfurlCache
- type UnfurlImageStore
- type UnfurlPreview
- type UnfurlService
- func (s *UnfurlService) ProxyImageURL(ctx context.Context, rawURL string) string
- func (s *UnfurlService) ProxyImageWithSize(ctx context.Context, rawURL string) (string, int, int)
- func (s *UnfurlService) SetImageStore(store UnfurlImageStore)
- func (s *UnfurlService) SetMediaURLCache(c MediaURLCache)
- func (s *UnfurlService) Unfurl(ctx context.Context, rawURL string) (*UnfurlPreview, error)
- func (s *UnfurlService) Wired() error
- type UnreadSeqStore
- type UploadRequest
- type UpsertOption
- type UserIndexer
- type UserSearcher
- type UserService
- func (s *UserService) BotAccounts(ctx context.Context) ([]*model.User, error)
- func (s *UserService) ClearExpiredStatuses(ctx context.Context, now time.Time) (int, error)
- func (s *UserService) DeactivatedAmong(ctx context.Context, userIDs []string) (map[string]bool, error)
- func (s *UserService) EnsureBotUser(ctx context.Context, botID, displayName string) (*model.User, error)
- func (s *UserService) GetBatch(ctx context.Context, ids []string) ([]*model.User, error)
- func (s *UserService) GetByEmail(ctx context.Context, email string) (*model.User, error)
- func (s *UserService) GetByID(ctx context.Context, id string) (*model.User, error)
- func (s *UserService) ListAll(ctx context.Context) ([]*model.User, error)
- func (s *UserService) PatchTimeZoneIfChanged(ctx context.Context, userID, timeZone string) (*model.User, error)
- func (s *UserService) RunExpiredStatusSweeper(ctx context.Context, interval time.Duration)
- func (s *UserService) Search(ctx context.Context, query string, limit int) ([]*model.User, error)
- func (s *UserService) SearchInvitable(ctx context.Context, query string, limit int) ([]*model.User, error)
- func (s *UserService) SetAudienceInvalidator(a AudienceInvalidator)
- func (s *UserService) SetAutomationStopper(a AutomationStopper)
- func (s *UserService) SetAvatarDecodeLimit(limit int64)
- func (s *UserService) SetAvatarObjects(o AvatarObjects)
- func (s *UserService) SetIndexer(i UserIndexer)
- func (s *UserService) SetMediaURLCache(c MediaURLCache)
- func (s *UserService) SetNotificationSettings(ctx context.Context, userID string, settings model.NotificationSettings) (*model.User, error)
- func (s *UserService) SetReminderCanceller(r ReminderCanceller)
- func (s *UserService) SetRunnerRevoker(r RunnerRevoker)
- func (s *UserService) SetSearcher(sr UserSearcher)
- func (s *UserService) SetStatus(ctx context.Context, targetID string, deactivated bool) (*model.User, error)
- func (s *UserService) SetStatusFromDirectory(ctx context.Context, targetID string, deactivated bool) error
- func (s *UserService) SetTokenStore(t TokenStore)
- func (s *UserService) SetUserStatusMessage(ctx context.Context, userID string, status *model.UserStatus, ...) (*model.User, error)
- func (s *UserService) ShrinkAvatar(ctx context.Context, userID string, dryRun bool) (bool, error)
- func (s *UserService) Update(ctx context.Context, userID string, ...) (*model.User, error)
- func (s *UserService) UpdateRole(ctx context.Context, _, targetID string, role model.SystemRole) (*model.User, error)
- func (s *UserService) UserAccess(ctx context.Context, id string) (string, model.SystemRole, error)
- func (s *UserService) Wired() error
- type UserStateService
- func (s *UserStateService) HiddenSkillSet(ctx context.Context, userID string) (map[string]bool, error)
- func (s *UserStateService) HideConversation(ctx context.Context, userID, convID string) error
- func (s *UserStateService) HideSkill(ctx context.Context, userID, skillID string) error
- func (s *UserStateService) List(ctx context.Context, userID string) (*model.UserState, error)
- func (s *UserStateService) MarkThreadNotificationUnread(ctx context.Context, userID, parentID, parentType, threadRootID string) error
- func (s *UserStateService) MarkThreadSeen(ctx context.Context, userID, parentID, parentType, threadRootID string) error
- func (s *UserStateService) ParentLeft(ctx context.Context, userIDs []string, parentID string)
- func (s *UserStateService) SetActivityTracker(t ActivityReadTracker)
- func (s *UserStateService) ThreadRead(ctx context.Context, userID, threadRootID string) (*model.ThreadReadState, error)
- func (s *UserStateService) UnhideConversation(ctx context.Context, userID, convID string) error
- func (s *UserStateService) UnhideSkill(ctx context.Context, userID, skillID string) error
- func (s *UserStateService) Wired() error
- type UserStateStore
- type UserStore
- type ViewActionResult
- type ViewApp
- type ViewEvent
- type ViewSubmitResult
- type ViewValue
- type WebhookActor
- type WebhookBotProvisioner
- type WebhookChannelResolver
- type WebhookDMResolver
- type WebhookImageProxy
- type WebhookMembershipResolver
- type WebhookMessageInput
- type WebhookUserResolver
Constants ¶
const ( MaxMessageBodyChars = limits.MaxMessageBodyChars MaxAttachmentsPerMessage = limits.MaxAttachmentsPerMessage MaxMessageListLimit = limits.MaxMessageListLimit MaxChannelNameLen = limits.MaxChannelNameLen MaxChannelDescriptionLen = limits.MaxChannelDescriptionLen MaxDistinctReactions = limits.MaxDistinctReactions )
The input ceilings and validators live in internal/limits so the history importer enforces exactly the same rules; these names keep the service API.
const ( ParentChannel = "channel" ParentConversation = "conversation" )
Parent type constants used by handlers to indicate whether the parent is a channel or a conversation.
const ( StateEmojiRead = "👀" // acknowledged StateEmojiWorking = "⚙️" // executing StateEmojiThinking = "🧠" // consulting/planning StateEmojiReviewing = "🔍" // reviewing StateEmojiDone = "✅" // completed StateEmojiBlocked = "⛔" // blocked / awaiting approval StateEmojiFailed = "❌" // failed StateEmojiQueued = "⏳" // queued until the invoker's runner is online StateEmojiStopped = "⏹️" // canceled by a human (StopThread) )
Machine state reactions (plan-v2 §9 / plan.md §9). Written exclusively by the orchestrator via SetMachineReaction; ToggleReaction rejects them from human callers so the state display is non-spoofable. Stored as the actual unicode emoji — that is what the SPA's reaction picker sends and what EmojiGlyph renders (a shortcode name would display as literal text).
const ( NotificationKindMessage = model.NotificationKindMessage NotificationKindMention = model.NotificationKindMention NotificationKindThreadReply = model.NotificationKindThreadReply NotificationKindReminder = model.NotificationKindReminder NotificationKindApproval = model.NotificationKindApproval NotificationKindCatchUp = model.NotificationKindCatchUp )
const ( )
SharePoint jobs have a queue and workers of their own: sharing with a large channel holds a worker for a while, and must never hold one the mobile pushes and notification checks need.
const ( SidebarSectionFavorites = "favorites" SidebarSectionCategory = "category" SidebarSectionChannels = "channels" )
Sidebar section kinds a move can target. The default DM section is absent on purpose: it is recency/alphabetically sorted, never position-ordered.
const ( DefaultThreadPageSize = 20 MaxThreadPageSize = 50 )
The /threads list comes a page at a time: first the threads with unread replies (their unread markers, the latest alert first), then every other thread the user follows, latest reply first (the follow rows' activity order). A cursor says which part a page continues: "u:<marker key>" or "r:<follow cursor>". No page reads more threads than it returns.
const ( MaxNotificationKeywords = 50 MaxNotificationKeywordLen = 100 )
MaxNotificationKeywords / MaxNotificationKeywordLen bound the global keyword list so a single user can't bloat their record (and the per-message keyword scan) without limit.
const ( ViewClose = "close" ViewErrors = "errors" ViewUpdate = "update" ViewPush = "push" ViewKeep = "keep" )
Submission outcomes.
const AttachmentURLTTL = 24 * time.Hour
AttachmentURLTTL is how long signed GET URLs remain valid. Frontend resolves URLs on demand via the API so this can be relatively short.
const EmojiURLTTL = 24 * time.Hour
EmojiURLTTL is how long re-signed emoji GET URLs remain valid. Short enough that a stale URL never lingers in caches forever, long enough to amortize the presign cost across a typical user session.
const MaxAttachmentBatchIDs = 50
const MaxAvatarBytes = 2 << 20
MaxAvatarBytes caps an uploaded avatar file.
const MaxAvatarSide = 1024
MaxAvatarSide is the longest side, in pixels, an avatar is kept at. Uploads are shrunk to fit. A camera photo kept at full size costs every browser that shows it ~50 MB of decoded pixels however small it is drawn, and a channel full of them is enough to run a phone out of memory.
const MaxEmojiImageBytes = 512 * 1024
const MaxEmojiShortcodeLen = 128
MaxEmojiShortcodeLen bounds a recorded shortcode so a malicious client can't store oversized members in the sorted set.
const MaxEmojiSide = 256
MaxEmojiSide is the longest side a re-encoded emoji is kept at: twice the largest size one is drawn at.
const MaxEmojiSourceSide = 2048
MaxEmojiSourceSide bounds an uploaded emoji's canvas. Nothing drawn at emoji size needs more, and the copied animated formats are decoded by every viewer's browser.
const MaxFrequentEmoji = 50
MaxFrequentEmoji caps how many frequently-used shortcodes the service will ever return, regardless of the requested limit.
const MaxUserDisplayNameLen = 80
const TaskTypeMobilePush = "push:mobile"
TaskTypeMobilePush is the asynq task type for a (possibly deferred) mobile push. One task = one recipient × one notification.
const TaskTypeNotifyCheck = "notify:check"
TaskTypeNotifyCheck is the asynq task type of the fan-out safety net. One task per message.
TaskTypeSharePointSync is the asynq task type of every SharePoint job.
const WebhookAuthorID = "webhook"
WebhookAuthorID is the sentinel author stamped on incoming-webhook posts. It is not a real user: it has no membership rows and no read state, so per-user bookkeeping (e.g. the author last-read mark) must skip it.
Variables ¶
var ( ErrInvalidCredentials = errors.New("auth: invalid credentials") // ErrSessionInvalid covers an unknown, expired, replayed or revoked // refresh token, and a session past its absolute lifetime. ErrSessionInvalid = errors.New("auth: session is no longer valid") // ErrAccountDeactivated refuses every sign-in path for a deactivated // account. ErrAccountDeactivated = errors.New("auth: this account is deactivated") // ErrIdentityMismatch refuses an SSO login whose verified identity // (issuer + subject, or the directory object id) differs from the one // the account is bound to. ErrIdentityMismatch = errors.New("auth: this sign-in does not match the account's identity") // ErrEmailUnverified refuses an SSO login whose provider explicitly // says the email address is not verified. ErrEmailUnverified = errors.New("auth: the identity provider has not verified this email address") // ErrEmailDomainNotAllowed refuses an SSO login outside // OIDC_ALLOWED_EMAIL_DOMAINS. ErrEmailDomainNotAllowed = errors.New("auth: this email domain may not sign in") // ErrInviteForbidden refuses an invite from anyone but a system admin. ErrInviteForbidden = fmt.Errorf("auth: only admins can invite: %w", ErrForbidden) // ErrInviteInvalid covers an unknown or expired invite. ErrInviteInvalid = errors.New("auth: this invite is invalid or has expired") // ErrInvalidDisplayName / ErrInvalidPassword are the invite form's // validation failures. ErrInvalidDisplayName = fmt.Errorf("auth: display name must be 1-%d characters", maxDisplayNameLen) ErrInvalidPassword = fmt.Errorf("auth: password must be at least %d characters", minGuestPasswordLen) // ErrAccountExists refuses an invite for an address that already has an // account. ErrAccountExists = errors.New("auth: an account with this email already exists") // ErrDesktopAuthInvalid refuses a desktop sign-in code that is missing, // unknown, expired or already redeemed. ErrDesktopAuthInvalid = errors.New("auth: desktop auth code expired or invalid") )
Errors the auth flows surface to their (often unauthenticated) callers. Each carries a fixed message; handlers map them to fixed responses and never echo an internal error's text.
var ( ErrAppUnavailable = errors.New("app unavailable") // ErrClickRateLimited: the clicker sent this app too many clicks. ErrClickRateLimited = errors.New("too many clicks") // ErrAppBusy: too many of the app's clicks are on their way already. ErrAppBusy = errors.New("app busy") // ErrBotTokenRequired: buttons that call the app need its bot token. ErrBotTokenRequired = errors.New("bot token required") // ErrInvalidBotToken: the bot token sent isn't this app's. ErrInvalidBotToken = errors.New("invalid bot token") // ErrNotRichWebhook: interactivity (buttons, forms, a bot token) is a // rich webhook's; a classic webhook only posts. ErrNotRichWebhook = errors.New("not a rich webhook") // ErrAppVersionConflict: the app's change was made on a version of the // message that is no longer current (if_version). ErrAppVersionConflict = errors.New("version conflict") // ErrResponseURLExpired / ErrResponseURLUsedUp: a response_url past its // 30 minutes, or its 5 uses. ErrResponseURLExpired = errors.New("response url expired") ErrResponseURLUsedUp = errors.New("response url used up") )
var ( ErrMessageTooLong = limits.ErrMessageTooLong ErrTooManyAttachments = limits.ErrTooManyAttachments ErrTooManyReactions = limits.ErrTooManyReactions ErrChannelNameInvalid = limits.ErrChannelNameInvalid ErrChannelNameTooLong = limits.ErrChannelNameTooLong ErrChannelDescriptionTooLong = limits.ErrChannelDescriptionTooLong ValidateMessageBody = limits.ValidateMessageBody ValidateAttachmentCount = limits.ValidateAttachmentCount ValidateChannelName = limits.ValidateChannelName ValidateChannelDescription = limits.ValidateChannelDescription )
var ( // ErrCardChanged: the button clicked is no longer on the message (the // app replaced the card meanwhile). The clicker sees the new card. ErrCardChanged = errors.New("card changed") // ErrAppNotSetUp: the button calls an app that isn't set up to receive // clicks. ErrAppNotSetUp = errors.New("app not set up for buttons") )
var ( // ErrPasswordResetUnsupported reports an account that cannot hold a local // password (an SSO/OIDC user). Surfaced to admins as a 409 so the UI can // explain WHY rather than silently doing nothing. ErrPasswordResetUnsupported = errors.New("auth: password reset is only available for guest accounts; SSO users sign in through the identity provider") // ErrPasswordResetInvalid reports an unknown, expired, or already-used // reset token. Deliberately indistinguishable between those cases. ErrPasswordResetInvalid = errors.New("auth: this password reset link is invalid or has expired") // store wired (no Redis), so the feature is off in this deployment. ErrPasswordResetUnavailable = errors.New("auth: password reset is not available") )
var ( // ErrInvalidAuth: no bot token, or one that is no app's. ErrInvalidAuth = errors.New("invalid auth") // ErrAppRateLimited: the app made too many calls this minute (see // RateLimitedError). ErrAppRateLimited = errors.New("ratelimited") // ErrTriggerExpired: a trigger_id older than 3 seconds, used, or // another app's. ErrTriggerExpired = errors.New("expired trigger id") // ErrViewNotFound: the form is closed, or isn't this app's (or person's). ErrViewNotFound = errors.New("view not found") // ErrDuplicateExternalID: another of the app's open forms has this // external_id; it must name one form, or updates by it go astray. ErrDuplicateExternalID = errors.New("duplicate external id") // ErrHashConflict: views.update named a hash the form has moved past. ErrHashConflict = errors.New("hash conflict") // ErrCantUpdateMessage: messages.update on a message another app (or a // person) posted. ErrCantUpdateMessage = errors.New("cant update message") // ErrIdempotencyInProgress: a call with this Idempotency-Key is still // running. ErrIdempotencyInProgress = errors.New("idempotency key in progress") // ErrPushNotAllowed: views.push without a form under it (a click on a // message opens with views.open), or past maxViewStack forms. ErrPushNotAllowed = errors.New("push not allowed") )
var ErrAlreadyExists = apperr.ErrAlreadyExists
ErrAlreadyExists marks a uniqueness conflict (duplicate name/slug/emoji). It is the store's sentinel too (both are apperr.ErrAlreadyExists): a storage-uniqueness conflict and a service-level one are the same kind, and handlers map it to 409 via errors.Is.
var ErrAttachmentUploaded = errors.New("attachment: already uploaded")
ErrAttachmentUploaded rejects upload requests for an attachment whose object is already final.
var ErrBotTokenInvalid = errors.New("bot: invalid or expired token")
ErrBotTokenInvalid refuses a request whose bot token is unknown, revoked, or belongs to a disabled bot.
var ErrBotUsernameTaken = apperr.Reject(ErrAlreadyExists, "that username is taken")
ErrBotUsernameTaken refuses a username another bot holds.
var ErrCategoryNameTaken = errors.New("category name already exists")
ErrCategoryNameTaken is returned when a user tries to create or rename a sidebar category to a name they already use.
var ErrChannelArchived = errors.New("channel: channel is archived")
ErrChannelArchived is returned for a write (post, reply, edit, delete, reaction, pin, rename, self-join, webhook post) into an archived channel. An archived channel keeps its members and history but is read-only until an owner unarchives it; members can still add people to it. Handlers map it to 409 Conflict.
var ErrConversationConverted = fmt.Errorf("message: this conversation is a channel now: %w", ErrForbidden)
ErrConversationConverted: the group message is a private channel now (the same ID). It is used as that channel; the conversation itself is no more.
var ErrForbidden = apperr.ErrForbidden
ErrForbidden marks a request for an existing resource that the caller is not allowed to access. Handlers use it to distinguish 403 from true 404.
var ErrInvalidBlocks = errors.New("invalid blocks")
ErrInvalidBlocks refuses a payload whose blocks break a rule; the message names the block. The HTTP layer answers 400 invalid_blocks.
var ErrInvalidPayload = errors.New("invalid payload")
ErrInvalidPayload: a rich webhook's blocks, template or data don't have the shape ex reads (a classic webhook never reads them).
var ErrInvalidThreadRoot = errors.New("message: invalid thread root")
ErrInvalidThreadRoot is returned when a webhook reply names a root it may not reply under: missing, itself a reply, or not posted by that webhook. The webhook handler maps it to 400.
var ErrInvalidView = errors.New("invalid view")
ErrInvalidView refuses a form that breaks a rule; the message names the block. Apps get it as invalid_view.
ErrMarkUnreadUnavailable is returned when the read-state stores mark-unread needs aren't wired.
var ErrMemberDeactivated = errors.New("channel: that account is deactivated")
ErrMemberDeactivated is returned for adding a deactivated account to a channel. Handlers map it to 409 Conflict.
var ErrMicrosoftSignInRequired = apperr.Conflict("sign in with Microsoft to keep Office files in OneDrive")
ErrMicrosoftSignInRequired: the uploader has no working Microsoft sign-in, so nothing can be put in their OneDrive.
var ErrNoDelegatedToken = errors.New("delegated token: none stored")
ErrNoDelegatedToken: no Microsoft token is stored for the user (they last signed in before SharePoint sharing was turned on, or never through SSO).
var ErrNotFound = apperr.ErrNotFound
ErrNotFound is the shared not-found kind (the store raises it).
var ErrPushUndeliverable = errors.New("push undeliverable (no device / rejected by provider)")
ErrPushUndeliverable marks a push failure that retrying cannot fix — a 4xx from the push provider, most commonly "no registered device for this user" (the user never installed/enabled the mobile app, or their device token lapsed). The async worker logs these LOUDLY (ERROR), because for an incident channel it means the offline fallback produced no alert at all and a human should know that recipient is unreachable on mobile. Transient failures (network blip / 5xx) that merely exhausted retries stay at WARN.
var ErrReminderTimeInvalid = errors.New("reminder: remind time must be in the future")
ErrReminderTimeInvalid is returned when a reminder's fire time is not strictly in the future, or is further out than reminderMaxHorizon.
var ErrReservedEmoji = errors.New("message: emoji reserved for agent state")
ErrReservedEmoji is returned when a human tries to react with a reserved machine-state emoji.
var ErrScheduledBusy = errors.New("scheduled message: already being sent")
ErrScheduledBusy is returned by SendNow when the message is being delivered at that very moment.
var ErrScheduledTimeInvalid = fmt.Errorf("%w: send time must be in the future", ErrValidation)
ErrScheduledTimeInvalid is returned when a send time isn't in the future, or is further out than scheduledMaxHorizon.
var ErrSidebarConflict = errors.New("sidebar: layout changed since it was read")
ErrSidebarConflict reports a move whose anchor no longer exists where the client saw it — the sidebar changed under them (another device moved or removed rows). Nothing was written; the client refetches the truth and the user drops again against current state.
var ErrSidebarInvalid = errors.New("invalid sidebar move")
ErrSidebarInvalid marks a malformed move request (unknown section/type, missing fields). Handlers map it to 400.
var ErrTemplateNotFound = apperr.Reject(apperr.ErrNotFound, "no template by that name on this webhook")
ErrTemplateNotFound: no template by that key on the webhook.
var ErrThreadDeleted = errors.New("message: thread has been deleted")
ErrThreadDeleted is returned when a reply is attempted on a thread whose root message has been soft-deleted. A deleted thread is closed for good — the cascade in MessageService.Delete tombstones every existing reply and this guard prevents new ones. Handlers map it to 409 Conflict.
var ErrUnknownCommand = errors.New("command: unknown command")
ErrUnknownCommand marks a slash-command invocation whose name isn't registered. Handlers map it to 404 so a stale client (offering a command a newer deploy removed) gets a clean error instead of a generic 500.
var ErrUnsupportedUploadType = errors.New("attachment: file type not allowed for agent uploads")
ErrUnsupportedUploadType rejects an agent upload outside agentUploadTypes.
var ErrUploadTooLarge = errors.New("attachment: file exceeds the agent upload limit")
ErrUploadTooLarge rejects an agent upload over model.UploadMaxBytes.
var ErrValidation = apperr.ErrValidation
ErrValidation marks caller input that fails a service-level bound (size, required field). Handlers map it to 400.
var ErrWebhookDMRejected = errors.New("webhook: direct-message target rejected")
ErrWebhookDMRejected marks an Execute payload whose direct-message target cannot be served (resolver not wired, or the webhook tried to DM its own creator). A sentinel rather than string matching: the handler maps it to a 400 with a FIXED user-facing message — the wrapped detail is for logs only, never for the unauthenticated caller.
ErrWebhookUnavailable marks an infrastructure failure rather than a bad request. The handler maps it to 503 so the caller retries.
var ErrWrongWebhookURL = errors.New("webhook: wrong URL for this webhook")
ErrWrongWebhookURL: each kind of webhook has its own URL — classic /hooks/{id}, rich /hooks/v2/{id} — and a payload sent to the other one is refused, so the classic URL only ever runs the classic path.
Functions ¶
func ButtonAt ¶ added in v0.0.116
ButtonAt finds the element named (blockID, actionID) — a button, or a picker the app gave the message — among its blocks and its cards'.
func IndexUser ¶ added in v0.0.97
func IndexUser(ctx context.Context, idx UserIndexer, u *model.User)
IndexUser is the nil-safe hook used by UserService (profile edits), AuthService (signup / invite acceptance) and the agents package (shared agent users).
func IsMachineStateEmoji ¶ added in v0.0.72
IsMachineStateEmoji reports whether the emoji name is reserved for backend-written run-state reactions.
func IsNotifiable ¶
func IsNotifiable(k NotificationKind) bool
IsNotifiable reports whether a kind should produce an actual user-facing notification (sound + browser popup). Exposed so callers can short-circuit payload assembly when nothing would be delivered.
func MayClick ¶ added in v0.0.116
func MayClick(e model.BlockElement, userID string) bool
MayClick reports whether userID may see and click e: anyone, unless the app named who may.
func NewMobilePushTaskHandler ¶ added in v0.0.64
func NewMobilePushTaskHandler(ack NotificationAckStore, provider MobilePushSender) func(context.Context, *asynq.Task) error
NewMobilePushTaskHandler builds the worker-side handler that runs when a scheduled push comes due. The ack check happens HERE, at delivery time — not at schedule time — so a desktop that acked any moment before the task runs still stands the push down, across instances (the ack marker is Redis-backed).
NO presence re-check here — deliberately (see the 2026-07-08 incident): every task carries its verdict from schedule time; the deferred path exists precisely for the "socket alive but user absent" case, and a delivery-time presence gate silently swallowed every alert for an idle-but-open desktop. Duplicates are the accepted failure direction.
func PlainMentions ¶ added in v0.0.97
PlainMentions rewrites "@[id|Name]" user mentions to plain "@Name", for text read by something that is not a renderer (an agent's task brief).
func PushMetricsSnapshot ¶ added in v0.0.66
PushMetricsSnapshot returns the current counter values for the admin endpoint. Key names are the wire contract — the frontend panel and any dashboards key off them.
func ReencodeThumbnail ¶ added in v0.0.88
func ReencodeThumbnail(ctx context.Context, objects ThumbnailObjects, key string, dryRun bool) (bool, error)
ReencodeThumbnail rewrites a lossless WebP thumbnail as lossy WebP under the same key. The picture is the same, so every URL to it stays valid; only the bytes shrink. A thumbnail that lossy would not make smaller (a few flat colours) and anything that is not a lossless WebP are left alone. With dryRun nothing is written, and a lossless thumbnail is reported without trying. Reports whether it was (or would be) rewritten.
Only the first bytes are read to find out whether there is anything to do, so a dry run, and a thumbnail that is already lossy, cost no download.
func ReminderBotUserID ¶ added in v0.0.114
func ReminderBotUserID() string
ReminderBotUserID is the reminder bot's account: it DMs a personal reminder to its owner. Derived like a webhook bot's, from its own separator, so it is the same account on every instance and never collides with one.
func ResetPushMetricsForTests ¶ added in v0.0.66
func ResetPushMetricsForTests()
ResetPushMetricsForTests zeroes all counters.
func StableMediaURL ¶ added in v0.0.19
func StableMediaURLs ¶ added in v0.0.59
func StableMediaURLs(ctx context.Context, c MediaURLCache, namespace string, reqs []MediaURLRequest) map[string]string
StableMediaURLs resolves many stable media URLs at once: one MGET for the existing records and one pipelined write for the misses' token+record rows — instead of the 1..3 Redis round trips PER item that made avatar resolution dominate /users/batch and /conversations. Falls back to the per-item path when the cache doesn't batch. Per-item failures drop that entry (same best-effort contract as StableMediaURL callers).
func ValidateEmojiName ¶
ValidateName returns an error if name is not a valid emoji shortcode.
func WebhookBotUserID ¶ added in v0.0.68
WebhookBotUserID derives a webhook's bot account ID.
DO NOT use the webhook ID directly. It is a bearer credential (POST /hooks/{id} has no other auth), while the bot ID is published to every recipient as the message authorID, in participantIDs, and by /api/v1/users/batch. The digest keeps derivation idempotent — same webhook, same bot, no stored mapping — without leaking the credential.
func WithClickID ¶ added in v0.0.116
WithClickID notes which browser tab a click came from.
Types ¶
type ActResult ¶ added in v0.0.116
type ActResult struct {
Message *model.Message `json:"message"`
Notice string `json:"notice,omitempty"`
// Failed: the click didn't go through; the notice says why.
Failed bool `json:"failed,omitempty"`
}
ActResult is a click's outcome: the message as it now is, and a notice for the clicker alone (an app's word, or why nothing happened).
type ActivityAdder ¶ added in v0.0.54
type ActivityAdder interface {
AddItem(ctx context.Context, userID string, item *model.ActivityItem)
}
ActivityAdder appends a fired reminder to the owner's activity stream.
type ActivityReadTracker ¶ added in v0.0.83
type ActivityReadTracker interface {
MarkParentRead(ctx context.Context, userID, parentID, threadRootID string, position time.Time)
}
ActivityReadTracker is told how far a user has read a channel, conversation or thread, so the activity items there follow it: reading a DM reads its items, and marking a message unread there makes its item unread again.
type ActivityRecorder ¶ added in v0.0.83
type ActivityRecorder interface {
RecordForRecipients(ctx context.Context, items map[string]*model.ActivityItem)
}
ActivityRecorder receives the Activity-tab entries the fan-out decides on (mentions, thread replies, DMs), one pre-built item per recipient. Implemented by ActivityService.
type ActivityService ¶ added in v0.0.54
type ActivityService struct {
// contains filtered or unexported fields
}
ActivityService owns the per-user activity stream (mentions, thread replies, DMs, reactions, channel adds and fired reminders) and notifies a user's own clients when it changes.
func NewActivityService ¶ added in v0.0.54
func NewActivityService(s ActivityStore, p Publisher) *ActivityService
NewActivityService builds an ActivityService.
func (*ActivityService) AddItem ¶ added in v0.0.54
func (s *ActivityService) AddItem(ctx context.Context, userID string, item *model.ActivityItem)
AddItem appends a pre-built activity item to a user's stream and nudges their clients. Used by the reminder service when a reminder fires.
func (*ActivityService) BadgeCount ¶ added in v0.0.116
BadgeCount is the user's Activity bell number: unread items, reactions left out (they never count towards the badge). The client's twin is badgeUnread in src/lib/activity-feed.ts; the two must agree, since the phone app's icon (set from each push) and every ex window show it.
func (*ActivityService) Feed ¶ added in v0.0.54
func (s *ActivityService) Feed(ctx context.Context, userID string) (model.ActivityFeed, error)
Feed returns the user's activity items plus the unread counts.
func (*ActivityService) MarkParentRead ¶ added in v0.0.83
func (s *ActivityService) MarkParentRead(ctx context.Context, userID, parentID, threadRootID string, position time.Time)
MarkParentRead records that the user has read a channel or conversation (or, with threadRootID, a thread) up to position, so the items there follow: mark-read passes now, mark-unread the instant before the message that became unread. Tells the user's clients when that can flip an item. Synchronous, so a quick read-then-unread can't land out of order; best-effort, because the read itself has already been saved.
func (*ActivityService) MarkSeen ¶ added in v0.0.54
func (s *ActivityService) MarkSeen(ctx context.Context, userID string) error
MarkSeen marks every item read, then tells the user's clients so every device clears its badge instead of waiting for the next activity.new (SPEC GAP-3 / I-4).
func (*ActivityService) MessageEdited ¶ added in v0.0.83
MessageEdited refreshes the preview on the items about an edited message in the streams of the parent's members.
func (*ActivityService) MessagesDeleted ¶ added in v0.0.83
func (s *ActivityService) MessagesDeleted(ctx context.Context, parentID, parentType string, messageIDs []string)
MessagesDeleted drops the items about deleted messages from the streams of the parent's members.
func (*ActivityService) ParentLeft ¶ added in v0.0.83
func (s *ActivityService) ParentLeft(ctx context.Context, userIDs []string, parentID string)
ParentLeft drops a channel's or conversation's items from the streams of users who can no longer read it (they left, were removed, or it was archived). One goroutine works through the users in turn, so archiving a large channel doesn't start one per member.
func (*ActivityService) RecordChannelAdded ¶ added in v0.0.83
func (s *ActivityService) RecordChannelAdded(ctx context.Context, actorID, userID string, ch *model.Channel)
RecordChannelAdded tells a user that someone else added them to a channel. No-op when the user added themselves or the channel is unknown. Being added to the same channel again replaces the earlier item.
func (*ActivityService) RecordForRecipients ¶ added in v0.0.83
func (s *ActivityService) RecordForRecipients(ctx context.Context, items map[string]*model.ActivityItem)
RecordForRecipients adds one pre-built item per recipient (userID → item) to their streams — the notification fan-out's hand-off for mentions, thread replies and DMs — written in one pipelined batch. Synchronous, unlike the other recorders: the fan-out that calls it then sets each mobile push's icon number from the recipient's bell count, so this message's own row must be readable before the push is scheduled (an offline recipient's push leaves at once). Nobody waits on it: the fan-out already runs detached from the send. A failed write stays best-effort inside addMany: logged, and the alert goes out regardless.
func (*ActivityService) RecordReaction ¶ added in v0.0.54
func (s *ActivityService) RecordReaction(ctx context.Context, msg *model.Message, parentType, actorID, emoji string)
RecordReaction adds a "someone reacted to your message" hint to the message author's activity stream. No-op when the reactor is the author themselves, the message was posted by a webhook or an agent (a machine has no stream to read), the author's account is deactivated, or there is no author. Best-effort: failures are logged, never propagated to the reaction write that triggered them. The account check, slug resolution and preview building run on a detached goroutine, off the reaction request path.
func (*ActivityService) RemoveItems ¶ added in v0.0.83
RemoveItems deletes specific items from the user's stream ("Remove from activity"), then tells the user's clients which items are gone. Ids not in the stream are ignored.
func (*ActivityService) SetChannelResolver ¶ added in v0.0.54
func (s *ActivityService) SetChannelResolver(c ChannelSlugResolver)
SetChannelResolver wires the channel-slug resolver used to snapshot the slug onto reaction activity items.
func (*ActivityService) SetDeactivatedAccounts ¶ added in v0.0.101
func (s *ActivityService) SetDeactivatedAccounts(d DeactivatedAccounts)
SetDeactivatedAccounts wires the check that keeps reaction hints out of a deactivated author's stream. Optional — without it every author gets them.
func (*ActivityService) SetItemsRead ¶ added in v0.0.83
func (s *ActivityService) SetItemsRead(ctx context.Context, userID string, ids []string, read bool) error
SetItemsRead marks specific items read or unread (the Activity tab's "Mark as read" / "Mark as unread"), then tells the user's clients which items flipped. Ids not in the stream are ignored.
func (*ActivityService) SetMemberLister ¶ added in v0.0.83
func (s *ActivityService) SetMemberLister(m ParentMemberLister)
SetMemberLister wires the parent-member lookup that message edits and deletes use to find the streams holding items about the message. Without it those items keep their original preview and outlive their message.
func (*ActivityService) SetMentionResolver ¶ added in v0.0.97
func (s *ActivityService) SetMentionResolver(r MentionResolver)
SetMentionResolver names mentioned users and channels in item previews by their current names. Optional — without it mentions read as typed.
func (*ActivityService) Wired ¶ added in v0.0.97
func (s *ActivityService) Wired() error
type ActivityStore ¶ added in v0.0.54
type ActivityStore interface {
AddActivityMany(ctx context.Context, adds []store.ActivityAdd) []store.ActivityAdded
// ListActivity returns the stream newest-first with each item's read state
// resolved.
ListActivity(ctx context.Context, userID string) ([]*model.ActivityFeedItem, error)
MarkActivitySeen(ctx context.Context, userID string) error
// SetActivityRead / RemoveActivity return the ids that were in the stream.
SetActivityRead(ctx context.Context, userID string, ids []string, read bool) ([]string, error)
RemoveActivity(ctx context.Context, userID string, ids []string) ([]string, error)
// RemoveActivityForMessages / UpdateActivityPreview return the touched ids
// per user.
RemoveActivityForMessages(ctx context.Context, userIDs, messageIDs []string) (map[string][]string, error)
UpdateActivityPreview(ctx context.Context, userIDs []string, messageID, preview string) (map[string][]string, error)
RemoveActivityForParent(ctx context.Context, userID, parentID string) ([]string, error)
MarkActivityParentRead(ctx context.Context, userID, parentKey string, position time.Time) (bool, error)
}
ActivityStore is the persistence the activity service needs.
type AgentDispatcher ¶ added in v0.0.72
type AgentDispatcher interface {
OnMessage(ctx context.Context, msg *model.Message, parentType string, conv *model.Conversation)
}
AgentDispatcher receives every persisted message so it can start runs for mentioned agents. Implemented by the orchestrator; wired via SetAgentDispatcher like the other optional seams. conv is the conversation the send already loaded for its access check (nil for a channel post), so the dispatcher never reads it again.
type AgentUploadParams ¶ added in v0.0.89
type AgentUploadParams struct {
RunID string
AgentID string // the agent user the run posts as (CreatedBy)
Filename string // untrusted; sanitised to a base name
Size int64 // declared; the bytes must match exactly
Body io.Reader
}
AgentUploadParams is one run-scoped upload.
type AppClickResult ¶ added in v0.0.116
AppClickResult is what a click on an app button came to: the message as it now is (nil when the app changed nothing) and a notice for the clicker. Failed marks a click that didn't go through, so its notice reads as an error.
type AppClicker ¶ added in v0.0.116
type AppClicker interface {
Click(ctx context.Context, msg *model.Message, parentType string, element model.BlockElement, blockID, userID string, value RawValue) (*AppClickResult, error)
}
AppClicker sends a click on an app button to the app (InteractionService).
type AppInteractionState ¶ added in v0.0.116
type AppInteractionState interface {
MintResponseURL(ctx context.Context, tokenHash string, rec model.ResponseURLRecord, uses int, ttl time.Duration) error
UseResponseURL(ctx context.Context, tokenHash string) (*model.ResponseURLRecord, int, error)
RecordInteraction(ctx context.Context, webhookID string, entry model.InteractionEntry) error
ListInteractions(ctx context.Context, webhookID string) ([]model.InteractionEntry, error)
NoteAppFailure(ctx context.Context, webhookID string, threshold int, pause time.Duration) (time.Duration, error)
NoteAppSuccess(ctx context.Context, webhookID string) error
AppPausedFor(ctx context.Context, webhookID string) (time.Duration, error)
MintTrigger(ctx context.Context, tokenHash string, rec model.TriggerRecord, ttl time.Duration) error
UseTrigger(ctx context.Context, tokenHash string) (*model.TriggerRecord, error)
SaveView(ctx context.Context, v *model.StoredView, ttl time.Duration) error
GetView(ctx context.Context, id string) (*model.StoredView, error)
ViewIDByExternalID(ctx context.Context, webhookID, externalID string) (string, error)
DeleteView(ctx context.Context, v *model.StoredView) error
// TakeView deletes v and reports whether this call was the one that did.
TakeView(ctx context.Context, v *model.StoredView) (bool, error)
DropViewExternalID(ctx context.Context, webhookID, externalID, viewID string) error
ClaimIdempotencyKey(ctx context.Context, scope, key string, ttl time.Duration) ([]byte, bool, error)
FinishIdempotencyKey(ctx context.Context, scope, key string, answer []byte, ttl time.Duration) error
}
AppInteractionState is interactivity's short-lived state (Redis).
type AppResponse ¶ added in v0.0.116
type AppResponse struct {
ReplaceOriginal bool `json:"replace_original"`
DeleteOriginal bool `json:"delete_original"`
Text string `json:"text"`
Blocks model.Blocks `json:"blocks"`
Attachments []model.MessageAttachment `json:"attachments"`
RootID string `json:"root_id"`
// IfVersion applies the change only to that version of the message.
IfVersion *int `json:"if_version"`
Notice string `json:"notice"`
}
AppResponse is an app's answer — in the body of its reply to a click, or posted to a response_url. It may replace or delete the message, post a new one, and leave the clicker a notice.
type AppSigner ¶ added in v0.0.116
type AppSigner struct {
// contains filtered or unexported fields
}
AppSigner signs what ex sends to apps. An app's signing secret is derived from the server's key, the webhook and a version — so it is never stored, and reading the database alone yields none. Rotating bumps the version.
func NewAppSigner ¶ added in v0.0.116
NewAppSigner returns a signer over the server key.
func (*AppSigner) Secret ¶ added in v0.0.116
Secret is a webhook's signing secret of the given version.
func (*AppSigner) SignatureHeader ¶ added in v0.0.116
func (s *AppSigner) SignatureHeader(wh *model.IncomingWebhook, timestamp int64, body []byte, now time.Time) string
SignatureHeader is the X-Ex-Signature value for a request body sent at timestamp: "v0=<hex HMAC-SHA256 of v0:<ts>:<body>>" with the current secret, followed — while a rotation's overlap lasts — by one with the previous secret, so an app still holding the old one verifies too.
type AsynqPushScheduler ¶ added in v0.0.64
type AsynqPushScheduler struct {
// contains filtered or unexported fields
}
AsynqPushScheduler is the production MobilePushScheduler: it enqueues Redis-backed asynq tasks, deferred via ProcessIn for the ack-fallback path.
func NewAsynqPushScheduler ¶ added in v0.0.64
func NewAsynqPushScheduler(rdb redis.UniversalClient) *AsynqPushScheduler
NewAsynqPushScheduler wraps an existing go-redis client (built through redisx.Options like every other Redis client in the app).
func (*AsynqPushScheduler) Close ¶ added in v0.0.64
func (s *AsynqPushScheduler) Close() error
Close releases the scheduler's asynq client. It does NOT touch the shared redis connection it was built on — the caller owns that.
func (*AsynqPushScheduler) EnqueueSharePoint ¶ added in v0.0.116
func (s *AsynqPushScheduler) EnqueueSharePoint(ctx context.Context, t SharePointTask) error
EnqueueSharePoint queues a SharePoint job on the app's one asynq producer.
func (*AsynqPushScheduler) ScheduleNotifyCheck ¶ added in v0.0.97
func (s *AsynqPushScheduler) ScheduleNotifyCheck(ctx context.Context, msg *model.Message, parentType string) error
ScheduleNotifyCheck arms the safety net for msg. The app's one asynq producer (AsynqPushScheduler) carries both the mobile pushes and these checks.
func (*AsynqPushScheduler) SchedulePush ¶ added in v0.0.64
func (s *AsynqPushScheduler) SchedulePush(ctx context.Context, recipientUserID string, n Notification, delay time.Duration) error
type AsynqPushWorker ¶ added in v0.0.64
type AsynqPushWorker struct {
// contains filtered or unexported fields
}
AsynqPushWorker runs the delivery side of the push pipeline. Where the old in-memory channel dropped queued jobs on Close, Shutdown here waits for in-flight tasks (up to ShutdownTimeout) and REQUEUES the rest in Redis for the next instance — a deploy can no longer lose a push.
func NewAsynqPushWorker ¶ added in v0.0.64
func NewAsynqPushWorker(rdb redis.UniversalClient, handler func(context.Context, *asynq.Task) error, cfg AsynqPushWorkerConfig) *AsynqPushWorker
func (*AsynqPushWorker) Handle ¶ added in v0.0.97
Handle registers another task type on the worker (before Start). The app runs one asynq worker for every durable task it schedules.
func (*AsynqPushWorker) Shutdown ¶ added in v0.0.64
func (w *AsynqPushWorker) Shutdown()
Shutdown drains in-flight tasks (bounded by ShutdownTimeout) and requeues everything else; scheduled tasks stay in Redis untouched.
func (*AsynqPushWorker) Start ¶ added in v0.0.64
func (w *AsynqPushWorker) Start() error
Start launches the worker's processing loops (non-blocking). A nil push handler (mobile push not configured) registers only the other task types.
type AsynqPushWorkerConfig ¶ added in v0.0.64
type AsynqPushWorkerConfig struct {
Concurrency int
DelayedTaskCheckInterval time.Duration
ShutdownTimeout time.Duration
// Queues are the queues this worker takes tasks from, by priority; nil
// is asynq's "default" queue, where pushes and notification checks go.
Queues map[string]int
}
AsynqPushWorkerConfig tunes the worker; zero values take asynq defaults (tests shrink DelayedTaskCheckInterval so deferred tasks come due fast).
type AttachmentAccessChecker ¶ added in v0.0.29
type AttachmentRefManager ¶
type AttachmentRefManager interface {
ValidateForUse(ctx context.Context, attachmentID string) error
// AttachmentOwner reports who uploaded the file and which messages carry
// it, for the send-time ownership rule (see validateAttachmentsForUse).
AttachmentOwner(ctx context.Context, attachmentID string) (createdBy string, messageIDs []string, err error)
AddRef(ctx context.Context, attachmentID, messageID string) error
RemoveRef(ctx context.Context, attachmentID, messageID string) error
// LoadMany and ReadyForReader serve the Files panel (ListFiles): one
// batched read, then thumbnails and media URLs for the reader.
LoadMany(ctx context.Context, ids []string) (map[string]*model.Attachment, error)
ReadyForReader(ctx context.Context, a *model.Attachment, grant MediaGrant)
}
AttachmentRefManager is the AttachmentService capability MessageService uses to bind/unbind attachments to messages. Defined as an interface so tests can stub it without dragging in storage.
type AttachmentService ¶
type AttachmentService struct {
// contains filtered or unexported fields
}
func NewAttachmentService ¶
func NewAttachmentService(attachments AttachmentStore, signer AttachmentSigner, publisher Publisher) *AttachmentService
NewAttachmentService constructs an AttachmentService.
func (*AttachmentService) AddRef ¶
func (s *AttachmentService) AddRef(ctx context.Context, attachmentID, messageID string) error
AddRef binds an attachment to a message. Called by MessageService.Send.
func (*AttachmentService) AttachmentOwner ¶ added in v0.0.89
func (s *AttachmentService) AttachmentOwner(ctx context.Context, id string) (createdBy string, messageIDs []string, err error)
AttachmentOwner reports who uploaded an attachment and which messages reference it — the message service's send-time ownership check.
func (*AttachmentService) CreateUploadURL ¶
func (s *AttachmentService) CreateUploadURL(ctx context.Context, p CreateUploadParams) (*CreateUploadResult, error)
CreateUploadURL either returns an existing attachment matching the SHA256 hash (with no upload URL) or creates a new attachment record + presigned PUT URL the client uploads to.
func (*AttachmentService) DeleteDraft ¶
func (s *AttachmentService) DeleteDraft(ctx context.Context, userID, attachmentID string) error
DeleteDraft removes an unattached (draft) attachment — invoked when the user removes the chip in the message composer before sending. Refuses to delete if any message references it (i.e. the same hash is in use elsewhere).
func (*AttachmentService) ForRunPost ¶ added in v0.0.89
func (s *AttachmentService) ForRunPost(ctx context.Context, id, runID, agentID string) (*model.Attachment, error)
ForRunPost returns the attachment if this run stored it (see model.Attachment.RunID) — the only files a run may put on its posts.
func (*AttachmentService) Get ¶
func (s *AttachmentService) Get(ctx context.Context, id string) (*model.Attachment, error)
Get returns an attachment with a signed GET URL. Used by clients to render an attachment. URLs are served from a per-S3-key cache so repeated lookups within the cache window hand out the SAME URL — the browser image cache hits on every subsequent render instead of re-downloading because the signature query string changed.
As a side effect, image attachments missing width/height (uploaded before the upload pipeline started recording dimensions) get a background backfill: we fetch ~256 KB from S3, decode the image header, and persist the dimensions. Subsequent reads return the stored values; this read may race ahead with zeros, which the frontend treats as "no width/height attribute" — same as today.
func (*AttachmentService) GetForUser ¶ added in v0.0.29
func (s *AttachmentService) GetForUser(ctx context.Context, userID, id, parentID, parentType, messageID string) (*model.Attachment, error)
func (*AttachmentService) GetMany ¶
func (s *AttachmentService) GetMany(ctx context.Context, ids []string) ([]*model.Attachment, error)
GetMany resolves a list of attachment IDs in parallel. Missing IDs are skipped silently — the caller can detect them by comparing returned IDs. Order matches the input.
func (*AttachmentService) GetManyForUser ¶ added in v0.0.29
func (s *AttachmentService) GetManyForUser(ctx context.Context, userID string, ids []string, parentID, parentType, messageID string) ([]*model.Attachment, error)
func (*AttachmentService) LoadForPreview ¶ added in v0.0.59
func (s *AttachmentService) LoadForPreview(ctx context.Context, ids []string) []*model.Attachment
LoadForPreview resolves many attachments with ONE batched row read (per-ID fallback) plus the usual read-side enrichment, in input order. Missing or failed IDs are skipped — previews are best-effort. Access gating is the CALLER's job (message-link unfurl checks message access before calling).
func (*AttachmentService) LoadMany ¶ added in v0.0.103
func (s *AttachmentService) LoadMany(ctx context.Context, ids []string) (map[string]*model.Attachment, error)
LoadMany reads attachments in one batched read (per-ID fallback), keyed by ID and without read-side enrichment. Missing IDs are left out; a failed read fails the call, so a caller never mistakes it for "no such files".
func (*AttachmentService) OpenByID ¶ added in v0.0.89
func (s *AttachmentService) OpenByID(ctx context.Context, id string) (io.ReadCloser, *model.Attachment, error)
OpenByID streams an attachment's bytes with NO access check — for callers that authorized the read themselves (a run fetching one of its project's reference screenshots). The caller closes the body.
func (*AttachmentService) OpenForUser ¶ added in v0.0.89
func (s *AttachmentService) OpenForUser(ctx context.Context, userID, id, parentID, parentType, messageID string) (io.ReadCloser, *model.Attachment, error)
OpenForUser streams an attachment's bytes under the same access rule as GetForUser — for an agent run reading a file from a message its invoker can see. The caller closes the body.
func (*AttachmentService) OpenMedia ¶ added in v0.0.19
func (s *AttachmentService) OpenMedia(ctx context.Context, token, grant, byteRange string) (*MediaObject, error)
OpenMedia opens the attachment behind a media token: all of it, or the one byte range in byteRange (an HTTP Range value).
func (*AttachmentService) ProcessUpload ¶ added in v0.0.43
func (s *AttachmentService) ProcessUpload(ctx context.Context, userID, attachmentID string) (*model.Attachment, error)
ProcessUpload validates the object that was uploaded via the presigned PUT URL, persists trusted image dimensions, and generates server-side thumbnails. The frontend calls this immediately after the direct upload completes, before allowing the attachment to be posted in a message. ValidateForUse runs the same path as a final guard in case a client skips this endpoint.
func (*AttachmentService) ReadyForReader ¶ added in v0.0.103
func (s *AttachmentService) ReadyForReader(ctx context.Context, a *model.Attachment, grant MediaGrant)
ReadyForReader applies the read-side enrichment to an attachment the caller has already authorized grant's user to read from grant's message.
func (*AttachmentService) RemoveRef ¶
func (s *AttachmentService) RemoveRef(ctx context.Context, attachmentID, messageID string) error
RemoveRef releases a message's claim on an attachment. When the last reference is removed the underlying S3 object and Attachment row are GC'd.
func (*AttachmentService) SetAccessChecker ¶ added in v0.0.29
func (s *AttachmentService) SetAccessChecker(c AttachmentAccessChecker)
func (*AttachmentService) SetMediaGrantKey ¶ added in v0.0.97
func (s *AttachmentService) SetMediaGrantKey(secret []byte)
SetMediaGrantKey derives the key media grants are signed with from a server secret. Every instance serving media must use the same one.
func (*AttachmentService) SetMediaURLCache ¶ added in v0.0.19
func (s *AttachmentService) SetMediaURLCache(c MediaURLCache)
SetMediaURLCache enables stable app-hosted media URLs for attachment rendering. Without it, Get falls back to direct presigned S3 URLs.
func (*AttachmentService) SetUploadLimits ¶ added in v0.0.2
func (s *AttachmentService) SetUploadLimits(l uploadLimits)
SetUploadLimits wires the settings-based limit checker. Optional — when unset, no extra validation runs (useful for unit tests of the other paths). Production wiring always passes the SettingsService.
func (*AttachmentService) SetVideoPoster ¶ added in v0.0.90
func (s *AttachmentService) SetVideoPoster(ctx context.Context, userID, attachmentID string, body io.Reader) (*model.Attachment, error)
SetVideoPoster keeps a frame of a video attachment, captured by the uploader's browser, as its thumbnails — the same lossy WebP pair an image gets — so the message list shows the video as a picture of a known size instead of a file card. Only the uploader may set one, only on an MP4, and only once: a poster can't be swapped for another picture after the video has been shared.
func (*AttachmentService) SignUploadRequest ¶ added in v0.0.82
func (s *AttachmentService) SignUploadRequest(ctx context.Context, userID, attachmentID string, req UploadRequest) (*SignedUploadRequest, error)
SignUploadRequest presigns one S3 request for uploading an attachment straight from the browser. Only the attachment's owner may upload, only to its own object key, only while the object is not yet final, and only the operations an upload needs.
func (*AttachmentService) UploadForAgent ¶ added in v0.0.89
func (s *AttachmentService) UploadForAgent(ctx context.Context, p AgentUploadParams) (*model.Attachment, error)
UploadForAgent stores and verifies one file for a run.
func (*AttachmentService) ValidateForUse ¶ added in v0.0.24
func (s *AttachmentService) ValidateForUse(ctx context.Context, attachmentID string) error
ValidateForUse proves that an attachment row points at an uploaded object whose immutable properties still match the metadata the row advertises. Message sends/edits call this before persisting attachment IDs supplied by the client, so a failed or tampered direct-to-S3 upload cannot become a message attachment.
func (*AttachmentService) Wired ¶ added in v0.0.97
func (s *AttachmentService) Wired() error
type AttachmentSigner ¶
type AttachmentSigner interface {
PresignedGetURL(ctx context.Context, key string, expires time.Duration) (string, error)
PresignedInlineURL(ctx context.Context, key, contentType, filename string, expires time.Duration) (string, error)
PresignedDownloadURL(ctx context.Context, key, filename string, expires time.Duration) (string, error)
PresignRequest(ctx context.Context, method, key string, query url.Values, headers map[string]string, expires time.Duration) (string, map[string]string, error)
DeleteObject(ctx context.Context, key string) error
GetObjectRange(ctx context.Context, key string, maxBytes int64) ([]byte, error)
GetObject(ctx context.Context, key string) (io.ReadCloser, string, int64, time.Time, error)
OpenObjectRange(ctx context.Context, key, byteRange string) (io.ReadCloser, string, int64, string, time.Time, error)
OpenObject(ctx context.Context, key string) (io.ReadCloser, string, int64, string, error)
StatObject(ctx context.Context, key string) (int64, string, string, string, error)
PutObject(ctx context.Context, key, contentType string, body []byte) error
}
AttachmentSigner generates time-limited URLs for attachment objects, signs the S3 requests browsers make to upload them directly, and reads/removes objects. GetObjectRange is used by the lazy dimension-backfill path; we read just enough of the image header to decode width/height without downloading the full payload.
type AttachmentStore ¶
type AttachmentStore interface {
Create(ctx context.Context, a *model.Attachment) error
GetByID(ctx context.Context, id string) (*model.Attachment, error)
GetByHash(ctx context.Context, sha256 string) (*model.Attachment, error)
AddRef(ctx context.Context, attachmentID, messageID string) error
RemoveRef(ctx context.Context, attachmentID, messageID string) (*model.Attachment, error)
Delete(ctx context.Context, id string) error
SetDimensions(ctx context.Context, id string, width, height int) error
SetThumbnailKeys(ctx context.Context, id, thumbnailKey, squareThumbnailKey string) error
SetMultipartUploadID(ctx context.Context, id, uploadID string) error
SetVerifiedETag(ctx context.Context, id, etag string) error
}
AttachmentStore is the persistence interface used by AttachmentService.
type AudienceCache ¶ added in v0.0.97
type AudienceCache struct {
// contains filtered or unexported fields
}
AudienceCache is the generation-checked, bounded, in-process audience cache. Safe for concurrent use.
func NewAudienceCache ¶ added in v0.0.97
func NewAudienceCache(gens AudienceGenerations) *AudienceCache
NewAudienceCache builds the cache over the shared generation store.
func (*AudienceCache) ChannelAudienceChanged ¶ added in v0.0.97
func (c *AudienceCache) ChannelAudienceChanged(ctx context.Context, channelID string)
ChannelAudienceChanged bumps the channel's generation (every instance reloads it on its next fan-out) and drops the local entry.
func (*AudienceCache) UserAudienceChanged ¶ added in v0.0.97
func (c *AudienceCache) UserAudienceChanged(ctx context.Context, userID string)
UserAudienceChanged bumps the user's generation and drops the local entry.
type AudienceGenerations ¶ added in v0.0.97
type AudienceGenerations interface {
// Generations returns the current value of every key, in order — one
// round trip in the steady state.
Generations(ctx context.Context, keys []string) ([]string, error)
// Bump moves every key to a new value.
Bump(ctx context.Context, keys ...string) error
}
AudienceGenerations holds one opaque generation per audience key. Values only ever need comparing for equality.
type AudienceInvalidator ¶ added in v0.0.97
type AudienceInvalidator interface {
ChannelAudienceChanged(ctx context.Context, channelID string)
UserAudienceChanged(ctx context.Context, userID string)
}
AudienceInvalidator is told, synchronously and after the write committed, whenever a notification audience changed: a channel's membership, a member's role, mute or per-channel preferences, or a user's account notification settings (levels, keywords, follow-all).
type AuthService ¶
type AuthService struct {
// contains filtered or unexported fields
}
AuthService handles authentication, token management, and invitations.
func NewAuthService ¶
func NewAuthService( users UserStore, tokens TokenStore, invites InviteStore, memberships MembershipStore, channelStore ChannelStore, jwt JWTProvider, oidc OIDCProvider, cache Cache, ) *AuthService
NewAuthService creates an AuthService with the given dependencies.
func (*AuthService) AcceptInvite ¶
func (s *AuthService) AcceptInvite(ctx context.Context, token, displayName, password string) (accessToken, refreshTokenRaw string, user *model.User, err error)
AcceptInvite validates the invite token, creates a guest user, adds the user to the specified channels, generates tokens, and deletes the invite.
func (*AuthService) ConsumeDesktopAuthSession ¶ added in v0.0.24
func (s *AuthService) ConsumeDesktopAuthSession(ctx context.Context, code string) (*DesktopAuthSession, error)
func (*AuthService) CreateDesktopAuthSession ¶ added in v0.0.24
func (s *AuthService) CreateDesktopAuthSession(ctx context.Context, refreshToken string) (string, error)
CreateDesktopAuthSession parks a refresh token behind a one-time code for a native/desktop shell to redeem at /auth/desktop/complete.
func (*AuthService) CreateInvite ¶
func (s *AuthService) CreateInvite(ctx context.Context, inviterID, inviteeEmail string, channelIDs []string) (*model.Invite, error)
CreateInvite generates an invitation token, stores the invite with a 72-hour expiry, and returns the invite model. The invite link is emailed to the invitee when SMTP is configured, and is also returned so the inviter can copy it directly — the invite must not depend on mail being up.
The parameter is inviteeEmail, not email: this file imports the email package, and a parameter named email would shadow it.
func (*AuthService) CreatePasswordResetForUser ¶ added in v0.0.66
func (s *AuthService) CreatePasswordResetForUser(ctx context.Context, targetUserID string) (*PasswordResetTicket, error)
CreatePasswordResetForUser mints a reset link for a guest account on an admin's behalf and emails it to the guest. The link is also returned so the admin can relay it directly — the reset must not depend on mail being up.
Callers are responsible for enforcing admin-only access.
func (*AuthService) GuestLogin ¶
func (s *AuthService) GuestLogin(ctx context.Context, email, password string) (accessToken, refreshTokenRaw string, user *model.User, err error)
GuestLogin authenticates a guest user via email and password (bcrypt).
func (*AuthService) HandleOIDCCallback ¶
func (s *AuthService) HandleOIDCCallback(ctx context.Context, code, state, nonce string) (accessToken, refreshTokenRaw string, user *model.User, err error)
HandleOIDCCallback exchanges the authorization code for tokens, upserts the user (creating with SystemRoleMember if new), generates an access/refresh token pair, and stores the refresh token.
The account is bound to the provider's verified identity, not just the email claim: the first login records issuer + subject, and a later login presenting a different identity for the same address is refused (as is one whose directory object id contradicts the pinned one). A guest (password) account at the address is converted to SSO — its password is cleared and every session and runner it had is revoked — so whoever claimed an employee's address through an invite loses it the moment the employee signs in.
func (*AuthService) HandleOIDCLogin ¶
func (s *AuthService) HandleOIDCLogin() (authURL, state, nonce string, err error)
HandleOIDCLogin generates a random state string and returns the OIDC provider's authorization URL. The caller is responsible for storing the state in an HTTP-only cookie.
func (*AuthService) Logout ¶
func (s *AuthService) Logout(ctx context.Context, refreshTokenRaw string) error
Logout ends the session the raw refresh token belongs to: every token of its family goes, so a rotated predecessor (kept for the lost-response grace) can't mint a new session afterwards. Other devices' sessions are other families and stay.
func (*AuthService) RefreshAccessToken ¶
func (s *AuthService) RefreshAccessToken(ctx context.Context, refreshTokenRaw string) (accessToken, newRefreshRaw string, err error)
RefreshAccessToken validates the raw refresh token, looks it up in the store, checks expiry and the session's absolute lifetime, loads the associated user (refusing a deactivated one), and returns a new access token plus the rotated refresh token.
func (*AuthService) RequestPasswordReset ¶ added in v0.0.66
func (s *AuthService) RequestPasswordReset(ctx context.Context, rawEmail string) error
RequestPasswordReset is the self-service "I forgot my password" entry point. It reports success for ANY input: a caller must not be able to learn whether an address is registered, whether it is a guest, or whether mail went out. Only the reset-store being unwired is surfaced, and that is a deployment fact, not a per-account one.
Everything per-account runs detached, after the response: a guest address used to answer only once its mail had been sent — a timing oracle that told guest accounts apart from everything else.
func (*AuthService) ResetPassword ¶ added in v0.0.66
func (s *AuthService) ResetPassword(ctx context.Context, token, password string) error
ResetPassword redeems a reset token and sets a new password. The token is single-use (GETDEL in the store), and every existing session is revoked: a reset means the old credential is no longer trusted, so sessions opened with it must not survive.
func (*AuthService) SetAllowedEmailDomains ¶ added in v0.0.97
func (s *AuthService) SetAllowedEmailDomains(domains []string)
SetAllowedEmailDomains restricts SSO sign-in to the given email domains (OIDC_ALLOWED_EMAIL_DOMAINS). Empty allows every domain the IdP vouches for.
func (*AuthService) SetBackgroundRunner ¶ added in v0.0.97
func (s *AuthService) SetBackgroundRunner(run func(fn func()))
SetBackgroundRunner replaces how detached work (the self-service reset mail) is started — safe.Go by default. A caller that must observe that work synchronously (tests, a CLI) passes a runner that calls fn inline.
func (*AuthService) SetChannelJoiner ¶
func (s *AuthService) SetChannelJoiner(j ChannelJoiner)
SetChannelJoiner wires the ChannelService for auto-join behavior so signup and invite-accept flows publish member.joined events and system messages. Called from the app wiring (internal/app) after ChannelService is constructed (avoids constructor cycle).
func (*AuthService) SetDelegatedTokens ¶ added in v0.0.116
func (s *AuthService) SetDelegatedTokens(t DelegatedTokenSaver)
SetDelegatedTokens wires keeping each SSO login's Microsoft token. Optional: only when SharePoint sharing is configured.
func (*AuthService) SetDirectory ¶ added in v0.0.65
func (s *AuthService) SetDirectory(d DirectoryLookup)
SetDirectory wires the employee-directory lookup (Microsoft Graph) used to enrich OIDC logins with phone + manager. Optional; nil disables enrichment.
func (*AuthService) SetGuestLoginAnyRole ¶ added in v0.0.72
func (s *AuthService) SetGuestLoginAnyRole(v bool)
SetGuestLoginAnyRole allows password login for non-guest roles. Intended ONLY for local dev (GUEST_LOGIN_ANY_ROLE=true in the compose overlay): production users authenticate via OIDC and carry no password hash, so even misconfigured this cannot log an SSO account in — but keep it off anyway.
func (*AuthService) SetIndexer ¶ added in v0.0.13
func (s *AuthService) SetIndexer(i UserIndexer)
func (*AuthService) SetMailer ¶ added in v0.0.66
func (s *AuthService) SetMailer(m email.Sender, baseURL string)
SetMailer wires transactional email and the public base URL used to build links inside it. Optional: with no mailer, invites and resets still mint their links (the admin copies them by hand) — they just aren't delivered.
func (*AuthService) SetPasswordResetStore ¶ added in v0.0.66
func (s *AuthService) SetPasswordResetStore(st PasswordResetStore)
SetPasswordResetStore wires the single-use reset-ticket store. Optional: without it, password reset reports ErrPasswordResetUnavailable instead of failing at the Redis call.
func (*AuthService) SetPublisher ¶ added in v0.0.65
func (s *AuthService) SetPublisher(p Publisher)
SetPublisher wires the event publisher used to broadcast user.updated when a directory sync changes a profile. Optional.
func (*AuthService) SetRunnerRevoker ¶ added in v0.0.89
func (s *AuthService) SetRunnerRevoker(r RunnerRevoker)
SetRunnerRevoker wires ex-runner revocation into password reset. Optional.
func (*AuthService) SetSessionMaxAge ¶ added in v0.0.97
func (s *AuthService) SetSessionMaxAge(d time.Duration)
SetSessionMaxAge sets the absolute session lifetime (SESSION_MAX_AGE).
func (*AuthService) Wired ¶ added in v0.0.97
func (s *AuthService) Wired() error
type AutomationStopper ¶ added in v0.0.97
AutomationStopper stops everything an account's agents do on its behalf — standing watch/schedule orders and live runs. Implemented by the Orchestrator (StopUserAutomations).
type AvatarObjects ¶ added in v0.0.88
type AvatarObjects interface {
GetObject(ctx context.Context, key string) (io.ReadCloser, string, int64, time.Time, error)
PutObject(ctx context.Context, key, contentType string, body []byte) error
DeleteObject(ctx context.Context, key string) error
}
AvatarObjects reads uploaded avatars from storage and writes the copies that are kept.
type AvatarSigner ¶
type AvatarSigner interface {
PresignedGetURL(ctx context.Context, key string, expires time.Duration) (string, error)
}
AvatarSigner generates time-limited GET URLs for avatar storage keys.
type BotAccountDirectory ¶ added in v0.0.112
type BotAccountDirectory interface {
BotAccounts(ctx context.Context) ([]*model.User, error)
SetStatus(ctx context.Context, targetID string, deactivated bool) (*model.User, error)
}
BotAccountDirectory lists the bot accounts and flips their status (UserService): disabling a bot is deactivating its account, with everything that comes with it.
type BotActor ¶ added in v0.0.112
type BotActor struct {
ID string
Role model.SystemRole
}
BotActor is the caller, with the stored role the auth middleware put in the claims. Only an admin manages bots.
type BotInput ¶ added in v0.0.112
type BotInput struct {
Username string `json:"username"`
DisplayName string `json:"displayName"`
Description string `json:"description"`
}
BotInput is what an admin writes about a bot.
type BotService ¶ added in v0.0.112
type BotService struct {
// contains filtered or unexported fields
}
BotService manages bot accounts and their tokens, and authenticates the requests made with them.
func NewBotService ¶ added in v0.0.112
func NewBotService(bots BotStore, users UserStore, accounts BotAccountDirectory, cache Cache, publisher Publisher) *BotService
NewBotService wires the bot service.
func (*BotService) Authenticate ¶ added in v0.0.112
func (s *BotService) Authenticate(ctx context.Context, secret string) (*model.TokenClaims, error)
Authenticate resolves a request's token to the bot it acts as. ErrBotTokenInvalid when the token is unknown or revoked, or its bot disabled; any other error is a failed lookup, not a verdict.
func (*BotService) Create ¶ added in v0.0.112
Create makes a bot account owned by the admin creating it.
func (*BotService) CreateToken ¶ added in v0.0.112
func (s *BotService) CreateToken(ctx context.Context, actor BotActor, botID, description string) (*model.BotTokenIssued, error)
CreateToken issues a bot a token and returns its secret, which is shown this once.
func (*BotService) Delete ¶ added in v0.0.115
Delete deletes a bot for good: its account is deactivated (as disabling it does), its tokens are revoked, its username is freed for another bot, and it leaves the bot list. Its row stays, so its messages keep their author. A delete that fails part way is safe to repeat.
func (*BotService) List ¶ added in v0.0.112
List returns the bot accounts, the migrated ones included.
func (*BotService) ListTokens ¶ added in v0.0.112
func (s *BotService) ListTokens(ctx context.Context, actor BotActor, botID string) ([]*model.BotToken, error)
ListTokens returns a bot's tokens, oldest first.
func (*BotService) RevokeToken ¶ added in v0.0.112
RevokeToken deletes one of a bot's tokens; requests made with it fail from then on.
type BotStore ¶ added in v0.0.112
type BotStore interface {
CreateBot(ctx context.Context, u *model.User) error
UpdateBot(ctx context.Context, u *model.User, previousUsername string) error
UsernameOwner(ctx context.Context, username string) (string, error)
PutBotToken(ctx context.Context, t *model.BotToken) error
GetBotToken(ctx context.Context, hash string) (*model.BotToken, error)
ListBotTokens(ctx context.Context, botID string) ([]*model.BotToken, error)
DeleteBotToken(ctx context.Context, hash string) error
DeleteBot(ctx context.Context, id, username string, at time.Time) error
}
BotStore is what only a bot has in storage: the claim on its username, and its tokens (store.BotStoreImpl).
type Cache ¶
type Cache interface {
Get(ctx context.Context, key string, dest interface{}) error
Set(ctx context.Context, key string, val interface{}, ttl time.Duration) error
GetUser(ctx context.Context, id string) (*model.User, error)
SetUser(ctx context.Context, user *model.User) error
Delete(ctx context.Context, key string) error
}
Cache defines cache operations used by the service layer.
type CachedMemberships ¶ added in v0.0.110
type CachedMemberships struct {
MembershipStore
// contains filtered or unexported fields
}
CachedMemberships serves channel member lists and membership checks — the access check behind nearly every request — from the shared copy, reading DynamoDB only to fill it. Everyone the copy doesn't hold is asked of the store, so a member whose join the copy missed is never locked out. Every other method is the store's own; writes move the channel's generation through the services (audienceWritten) and the importer.
func NewCachedMemberships ¶ added in v0.0.110
func NewCachedMemberships(store MembershipStore, cache ChannelMemberCache) *CachedMemberships
NewCachedMemberships wraps store with the shared copy.
func (*CachedMemberships) GetMembership ¶ added in v0.0.110
func (c *CachedMemberships) GetMembership(ctx context.Context, channelID, userID string) (*model.ChannelMembership, error)
GetMembership returns userID's membership of channelID: from the copy when it holds the row, else from a consistent store read that then joins the copy. ErrNotFound when they aren't a member.
func (*CachedMemberships) ListMembers ¶ added in v0.0.110
func (c *CachedMemberships) ListMembers(ctx context.Context, channelID string) ([]*model.ChannelMembership, error)
ListMembers returns channelID's members: from the copy when it is complete, else from a consistent store read that then becomes the copy.
func (*CachedMemberships) SetUserChannelName ¶ added in v0.0.110
func (c *CachedMemberships) SetUserChannelName(ctx context.Context, channelID, userID, name string) error
SetUserChannelName passes the channel service's sidebar-name rewrite on to the store when it has one.
type CategoryService ¶ added in v0.0.3
type CategoryService struct {
// contains filtered or unexported fields
}
CategoryService manages a user's sidebar categories. The categories are purely a UI grouping — they don't affect membership or visibility.
func NewCategoryService ¶ added in v0.0.3
func NewCategoryService(s CategoryStore, p Publisher) *CategoryService
NewCategoryService creates a CategoryService.
func (*CategoryService) Create ¶ added in v0.0.3
func (s *CategoryService) Create(ctx context.Context, userID, name string) (*model.UserChannelCategory, error)
Create adds a new category for the user with the given name. Position defaults to "end of list" — categories are always appended.
func (*CategoryService) Delete ¶ added in v0.0.3
func (s *CategoryService) Delete(ctx context.Context, userID, categoryID string) error
Delete removes a category. Channels assigned to it become uncategorised (the frontend renders them under the default "Other" section). Reassigning the channels server-side would require a scan; instead we rely on the frontend's lookup-by-ID falling through gracefully when the category is gone.
func (*CategoryService) List ¶ added in v0.0.3
func (s *CategoryService) List(ctx context.Context, userID string) ([]*model.UserChannelCategory, error)
List returns the user's categories, ordered by position.
func (*CategoryService) Move ¶ added in v0.0.59
func (s *CategoryService) Move(ctx context.Context, userID, categoryID, afterID string) ([]*model.UserChannelCategory, error)
Move places the category directly after afterID ("" = first) and renumbers the user's categories densely in one transaction. The client reports the drop EVENT; the server owns the resulting positions — a stale client can no longer write a position computed against a layout that has moved on. Returns the categories in their new canonical order.
func (*CategoryService) Update ¶ added in v0.0.3
func (s *CategoryService) Update(ctx context.Context, userID, categoryID string, name *string, position *int) (*model.UserChannelCategory, error)
Update applies a partial change: name and/or position. The caller passes the new desired values (zero values are kept; a non-zero position changes the row's position). The category must already belong to the user — store-side condition guards a stranger from flipping someone else's row.
type CategoryStore ¶ added in v0.0.3
type CategoryStore interface {
Create(ctx context.Context, c *model.UserChannelCategory) error
Get(ctx context.Context, userID, categoryID string) (*model.UserChannelCategory, error)
List(ctx context.Context, userID string) ([]*model.UserChannelCategory, error)
Update(ctx context.Context, c *model.UserChannelCategory) error
Delete(ctx context.Context, userID, categoryID string) error
// SetPositions commits server-computed positions for the user's
// categories in one transaction.
SetPositions(ctx context.Context, userID string, positions map[string]int) error
}
CategoryStore is the slice of store.CategoryStore CategoryService needs. Defined here as an interface so tests can stub it.
type ChannelActivityRecorder ¶ added in v0.0.83
type ChannelActivityRecorder interface {
RecordChannelAdded(ctx context.Context, actorID, userID string, ch *model.Channel)
ParentLeft(ctx context.Context, userIDs []string, parentID string)
ActivityReadTracker
}
ChannelActivityRecorder keeps the Activity tab in step with channel membership and reads: "X added you to ~channel", dropping a channel's items when the user leaves it, and reading them when the user reads the channel. Implemented by ActivityService.
type ChannelIndexer ¶ added in v0.0.13
type ChannelJoiner ¶
type ChannelJoiner interface {
AutoJoinChannel(ctx context.Context, userID, channelID string, role model.ChannelRole) error
}
ChannelJoiner is the subset of ChannelService that auth flows use to auto-join users to channels (e.g. #general on signup, channels listed on an invite). Defined as an interface so AuthService stays testable without pulling in the full ChannelService.
type ChannelMemberCache ¶ added in v0.0.110
type ChannelMemberCache interface {
// Member returns userID's row (nil when the copy doesn't hold one at the
// current generation) and the current generation to store a fill under.
Member(ctx context.Context, channelID, userID string) (*model.ChannelMembership, string, error)
// Members returns the member rows when the copy is complete at the
// current generation, and the current generation to store a fill under.
Members(ctx context.Context, channelID string) ([]*model.ChannelMembership, string, bool, error)
PutMember(ctx context.Context, channelID, gen string, row *model.ChannelMembership) error
PutMembers(ctx context.Context, channelID, gen string, rows []*model.ChannelMembership) error
}
ChannelMemberCache is the shared copy of channels' member rows (internal/cache.MemberLists), valid only at the channel's current audience generation — which every membership write moves.
type ChannelMembershipReader ¶ added in v0.0.97
type ChannelMembershipReader interface {
GetMembership(ctx context.Context, channelID, userID string) (*model.ChannelMembership, error)
}
ChannelMembershipReader is the channel-membership point read the conversation service needs for converted groups.
type ChannelReader ¶ added in v0.0.92
ChannelReader is the slice of the channel store the message service needs: whether a channel parent is archived, which makes it read-only.
type ChannelReminderSync ¶ added in v0.0.85
type ChannelReminderSync interface {
ParentLeft(ctx context.Context, userIDs []string, parentID string)
}
ChannelReminderSync is told when a user can no longer read a channel, so their pending reminders there (each a copy of a message's text) go too. Implemented by ReminderService.
type ChannelSearcher ¶ added in v0.0.13
type ChannelSearcher interface {
Channels(ctx context.Context, q string, limit int) ([]string, error)
}
ChannelSearcher returns matching channel IDs; SearchPublic hydrates and applies guest-visibility rules so the UI never has to see archived or out-of-scope hits.
type ChannelService ¶
type ChannelService struct {
// contains filtered or unexported fields
}
ChannelService manages channels and channel memberships.
func NewChannelService ¶
func NewChannelService(channels ChannelStore, memberships MembershipStore, users UserStore, messages MessageStore, cache Cache, broker Broker, publisher Publisher) *ChannelService
NewChannelService creates a ChannelService with the given dependencies. messages may be nil; when it is, system messages are not persisted.
func (*ChannelService) AddMember ¶
func (s *ChannelService) AddMember(ctx context.Context, actorID, channelID, userID string, role model.ChannelRole) error
AddMember adds a user to a channel with the specified role. The actor must be an admin or higher.
func (*ChannelService) Archive ¶
func (s *ChannelService) Archive(ctx context.Context, actorID, channelID string) error
Archive makes a channel read-only. Members keep their memberships and can still read its history, search it and leave it, but nobody can post, react, edit, rename it or add members until it is unarchived. Directory, browse and channel search stop listing it.
Only the owner or a system admin may archive. The well-known #general channel cannot be archived.
func (*ChannelService) AutoJoinChannel ¶
func (s *ChannelService) AutoJoinChannel(ctx context.Context, userID, channelID string, role model.ChannelRole) error
AutoJoinChannel adds a user to a channel without RBAC checks (used during signup/invite-accept flows where the caller has already authorized the action). Idempotent: a no-op (with no events) when the user is already a member.
func (*ChannelService) BrowsePublic ¶
func (s *ChannelService) BrowsePublic(ctx context.Context, userID string, limit int, cursor string) ([]*model.Channel, string, error)
BrowsePublic returns a paginated list of public channels visible to the caller. Members and admins see every public channel; guests are scoped to their joined channels (invite list + #general).
func (*ChannelService) ConvertGroupConversation ¶ added in v0.0.93
func (s *ChannelService) ConvertGroupConversation(ctx context.Context, actorID, convID, name string) (*model.Channel, error)
ConvertGroupConversation turns a group message into a private channel named name, as Slack does: everyone in it becomes a member (whoever converts it its owner), the whole history comes along, and the group is gone from everyone's list, the channel in its place. Each keeps where they had read up to, their unread badge and where the group sat in their sidebar. Any of its people may do it, except guests (who can't create channels).
func (*ChannelService) Create ¶
func (s *ChannelService) Create(ctx context.Context, userID, name string, chanType model.ChannelType, description string) (*model.Channel, error)
Create creates a new channel and adds the creator as the owner. Guests (invite-acceptance accounts) cannot create channels — they're scoped to the channels they're explicitly invited into plus #general.
func (*ChannelService) CreateWithID ¶ added in v0.0.72
func (s *ChannelService) CreateWithID(ctx context.Context, userID, id, name string, chanType model.ChannelType, description string) (*model.Channel, error)
CreateWithID is Create with a caller-chosen (derived) ID — for canonical channels that must have the same identity everywhere without coordination, e.g. a coding project's channel (DeriveID("codechan#"+projectPath)). The slug-uniqueness rules are unchanged.
func (*ChannelService) GetVisibleByID ¶ added in v0.0.19
func (s *ChannelService) GetVisibleByID(ctx context.Context, actorID, id string) (*model.Channel, error)
GetVisibleByID returns a channel only if the actor has access to its chat surface. Public discovery uses BrowsePublic; direct /channel/:id rendering is scoped to joined channels. An archived channel stays readable for its members (it is read-only, not hidden); a non-member cannot join it.
func (*ChannelService) GetVisibleBySlug ¶ added in v0.0.19
func (s *ChannelService) GetVisibleBySlug(ctx context.Context, actorID, slug string) (*model.Channel, error)
GetVisibleBySlug is the slug variant of GetVisibleByID.
func (*ChannelService) IsMember ¶ added in v0.0.3
func (s *ChannelService) IsMember(ctx context.Context, userID, channelID string) bool
IsMember reports whether the user has a membership row in the channel. Used by the WebSocket handler to gate inbound ephemeral events (typing indicator) — the same membership check that any persistent action has to pass on the write path.
func (*ChannelService) Join ¶
func (s *ChannelService) Join(ctx context.Context, userID, channelID string) error
Join adds a user to a public channel as a member. Guests are restricted to #general plus channels they were explicitly invited to — they cannot browse and self-join other public channels.
func (*ChannelService) Leave ¶
func (s *ChannelService) Leave(ctx context.Context, userID, channelID string) error
Leave removes a user from a channel. The channel owner cannot leave, and nobody can leave the well-known #general channel — every active workspace member must remain a participant.
func (*ChannelService) ListMembers ¶
func (s *ChannelService) ListMembers(ctx context.Context, actorID, channelID string) ([]*model.ChannelMembership, error)
ListMembers returns the memberships of a channel the actor can access, leaving out deactivated accounts: they keep their membership underneath (a reactivated account is back in its channels) but no longer count as members. A failed status read lists everyone rather than nobody.
func (*ChannelService) ListUserChannelIDs ¶ added in v0.0.59
ListUserChannelIDs returns just the channel IDs of the user's memberships: one membership Query, no META BatchGet, no unread math. The WebSocket connect path and the presence audience resolver only need topic names, and paying the full sidebar enrichment there doubled every connect's DynamoDB cost. Unlike ListUserChannels this does NOT filter archived channels — a subscription to an archived channel's topic is harmless (nothing posts there) and delivers the unarchive event live.
func (*ChannelService) ListUserChannels ¶
func (s *ChannelService) ListUserChannels(ctx context.Context, userID string) ([]*model.UserChannel, error)
ListUserChannels returns every channel a user belongs to, archived ones included (they are read-only, not hidden; the sidebar groups them apart). The archive flag isn't denormalized onto UserChannel, so the META rows are batch-read (one BatchGetItem) — this runs on the sidebar list — and the flag is stamped onto each row at read time.
func (*ChannelService) MakePrivate ¶ added in v0.0.101
func (s *ChannelService) MakePrivate(ctx context.Context, actorID, channelID string) (*model.Channel, error)
MakePrivate turns a public channel private: its members keep it, nobody else can find, join or read it any more — it leaves the directory, the channel browser and channel search. One way, as in Slack. The owner or a system admin may do it; #general stays public, and an archived channel is read-only. An already private channel is left as it is.
func (*ChannelService) MarkChannelRead ¶ added in v0.0.52
func (s *ChannelService) MarkChannelRead(ctx context.Context, userID, channelID string) error
MarkChannelRead catches the user up to the channel's current MessageSeq, so the sidebar unread badge clears and stays cleared across reloads. Publishes a user.channel.updated to the caller's own topic so other tabs/devices refetch and drop the badge too. Returns ErrNotFound when the caller isn't a member.
func (*ChannelService) NameAvailable ¶ added in v0.0.101
func (s *ChannelService) NameAvailable(ctx context.Context, name, exceptChannelID string) (bool, error)
NameAvailable reports whether a channel may be called name: a valid name no other channel holds. exceptChannelID is the channel being renamed — its own name counts as available to it.
func (*ChannelService) RemoveMember ¶
func (s *ChannelService) RemoveMember(ctx context.Context, actorID, channelID, targetID string) error
RemoveMember removes a user from a channel. The actor must be admin or higher. Owners can only be removed by a system admin. Members cannot be removed from the well-known #general channel — it must contain every active user.
func (*ChannelService) SearchPublic ¶ added in v0.0.13
func (s *ChannelService) SearchPublic(ctx context.Context, userID, q string, limit int) ([]*model.Channel, error)
SearchPublic returns matched public channels visible to the caller via OpenSearch. Returns (nil, nil) when no searcher is configured so the handler can fall back to BrowsePublic.
func (*ChannelService) SetActivityRecorder ¶ added in v0.0.83
func (s *ChannelService) SetActivityRecorder(a ChannelActivityRecorder)
SetActivityRecorder wires the Activity tab. Optional — without it adding a member works the same but nothing lands in their activity stream.
func (*ChannelService) SetAudienceInvalidator ¶ added in v0.0.97
func (s *ChannelService) SetAudienceInvalidator(a AudienceInvalidator)
SetAudienceInvalidator wires the notification audience cache's invalidation into every channel-audience write. Optional — unwired, nothing is cached against these writes to begin with.
func (*ChannelService) SetCategory ¶ added in v0.0.3
func (s *ChannelService) SetCategory(ctx context.Context, userID, channelID, categoryID string, sidebarPosition *int) error
SetCategory assigns a channel to one of the user's sidebar categories (or clears the assignment when categoryID is empty). Same per-user semantics as SetFavorite. Validation that the categoryID actually belongs to this user is the caller's responsibility — handlers do that check before invoking.
func (*ChannelService) SetConversationConverter ¶ added in v0.0.93
func (s *ChannelService) SetConversationConverter(c ConversationConverter, drafts ConversationDraftMover)
SetConversationConverter wires converting group messages into channels, and moving their drafts along (drafts may be nil).
func (*ChannelService) SetDeactivatedAccounts ¶ added in v0.0.109
func (s *ChannelService) SetDeactivatedAccounts(d DeactivatedAccounts)
SetDeactivatedAccounts wires the check that keeps deactivated accounts out of member lists (the user service answers it from the shared roster).
func (*ChannelService) SetFavorite ¶ added in v0.0.3
func (s *ChannelService) SetFavorite(ctx context.Context, userID, channelID string, favorite bool) error
SetFavorite pins or unpins a channel in the user's sidebar. Per-user. The user must already be a member — pinning a channel you can't see would create an orphan row in the user-side index.
func (*ChannelService) SetIndexer ¶ added in v0.0.13
func (s *ChannelService) SetIndexer(i ChannelIndexer)
func (*ChannelService) SetMute ¶
SetMute marks a channel as muted/unmuted for the calling user. Mute is a per-user preference: it suppresses notifications (sound + browser popup) but does not unsubscribe the user from real-time event delivery — they still see new messages, just without the alert.
func (*ChannelService) SetNotificationPrefs ¶ added in v0.0.50
func (s *ChannelService) SetNotificationPrefs(ctx context.Context, userID, channelID string, override model.ChannelNotificationOverride) error
SetNotificationPrefs persists the caller's per-channel notification overrides. Each field is "use my account default" when nil, or an explicit override otherwise. Like mute it's a per-user preference, so only the user's own clients are notified (via userchannel.updated) to keep tabs in sync.
func (*ChannelService) SetReminderSync ¶ added in v0.0.85
func (s *ChannelService) SetReminderSync(r ChannelReminderSync)
SetReminderSync wires reminder cleanup into losing access to a channel.
func (*ChannelService) SetSearcher ¶ added in v0.0.13
func (s *ChannelService) SetSearcher(sr ChannelSearcher)
func (*ChannelService) SetSharePointSync ¶ added in v0.0.116
func (s *ChannelService) SetSharePointSync(sp ChannelSharePointSync)
SetSharePointSync wires SharePoint access into joining and leaving a channel. Optional: only when SharePoint sharing is configured.
func (*ChannelService) SetThreadStateSync ¶ added in v0.0.107
func (s *ChannelService) SetThreadStateSync(t ChannelThreadStateSync)
SetThreadStateSync wires unread-thread marker cleanup into losing access to a channel.
func (*ChannelService) Unarchive ¶ added in v0.0.92
func (s *ChannelService) Unarchive(ctx context.Context, actorID, channelID string) error
Unarchive makes an archived channel writable again. Owner or system admin.
func (*ChannelService) Update ¶
func (s *ChannelService) Update(ctx context.Context, actorID, channelID string, name, description *string) (*model.Channel, error)
Update modifies optional channel fields. The actor must be an owner, admin, or system admin. A new name renames the channel: its slug — the URL key — follows the name, and must be free (ErrAlreadyExists otherwise). Both fields are validated before either is written, and each write touches only its own fields.
func (*ChannelService) UpdateMemberRole ¶
func (s *ChannelService) UpdateMemberRole(ctx context.Context, actorID, channelID, targetID string, newRole model.ChannelRole) error
UpdateMemberRole changes a member's role within a channel. Channel admins move members between member and admin; only an owner or a system admin makes someone an owner or changes an owner's role, so a system admin can hand a channel to a new owner.
func (*ChannelService) Wired ¶ added in v0.0.97
func (s *ChannelService) Wired() error
type ChannelSharePointSync ¶ added in v0.0.116
type ChannelSharePointSync interface {
}
ChannelSharePointSync keeps the access to SharePoint files shared in a channel in step with its members (SharePointService).
type ChannelSlugResolver ¶ added in v0.0.54
type ChannelSlugResolver interface {
GetByID(ctx context.Context, id string) (*model.Channel, error)
}
ChannelSlugResolver resolves a channel id to its slug so a reaction activity item can snapshot the slug server-side (matching the reminder/webhook paths) instead of the client re-deriving it — which breaks once the author leaves the channel. Optional; unset means the slug is left empty.
type ChannelStore ¶
type ChannelStore interface {
CreateChannel(ctx context.Context, ch *model.Channel) error
GetChannel(ctx context.Context, id string) (*model.Channel, error)
GetChannelBySlug(ctx context.Context, slug string) (*model.Channel, error)
// PatchChannel and RenameChannel are field-level: a whole-channel write
// would roll back the MessageSeq a message bumped meanwhile.
PatchChannel(ctx context.Context, id string, p store.ChannelPatch) error
RenameChannel(ctx context.Context, id, oldSlug, name, slug string, at time.Time) error
ListPublicChannels(ctx context.Context, limit int, cursor string) ([]*model.Channel, string, error)
}
ChannelStore defines persistence operations for channels.
type ChannelThreadStateSync ¶ added in v0.0.107
type ChannelThreadStateSync interface {
ParentLeft(ctx context.Context, userIDs []string, parentID string)
}
ChannelThreadStateSync is told when users can no longer read a channel, so the unread markers of its threads (which light the sidebar's Threads dot) go with it. Implemented by UserStateService.
type ClickLimiter ¶ added in v0.0.116
type ClickLimiter interface {
AllowClick(ctx context.Context, key string) (bool, error)
AllowAppCall(ctx context.Context, webhookID string) (ok bool, retryAfter time.Duration, err error)
}
ClickLimiter admits one more click under key's budget, and one more call an app makes to ex under its own.
type Command ¶ added in v0.0.65
type Command interface {
Info() CommandInfo
Run(ctx context.Context, req CommandRequest) (*model.Message, error)
}
Command is one executable slash command. Run returns the message the command posted into the chat (commands surface their result in-channel so every member sees it via the normal message.new fan-out).
type CommandInfo ¶ added in v0.0.65
CommandInfo describes a slash command to clients; the composer's "/" autocomplete renders exactly this.
type CommandRequest ¶ added in v0.0.65
type CommandRequest struct {
UserID string
ParentID string
ParentType string // ParentChannel or ParentConversation
}
CommandRequest carries the invocation context of a slash command: who ran it and in which chat (channel or conversation).
type CommandService ¶ added in v0.0.65
type CommandService struct {
// contains filtered or unexported fields
}
CommandService is the slash-command registry. Commands register at wiring time based on which integrations are configured; an empty registry is valid (clients see no commands and offer none).
func NewCommandService ¶ added in v0.0.65
func NewCommandService() *CommandService
NewCommandService creates an empty registry.
func (*CommandService) List ¶ added in v0.0.65
func (s *CommandService) List() []CommandInfo
List returns the registered commands in registration order. Always non-nil so the handler serializes an empty array, not null.
func (*CommandService) Register ¶ added in v0.0.65
func (s *CommandService) Register(cmd Command)
Register adds a command to the registry. Registration happens once at wiring time (no concurrent use).
func (*CommandService) Run ¶ added in v0.0.65
func (s *CommandService) Run(ctx context.Context, name string, req CommandRequest) (*model.Message, error)
Run executes a registered command. The command itself owns access control (each verifies the caller's membership in the target chat before acting).
func (*CommandService) SetDraftClearer ¶ added in v0.0.97
func (s *CommandService) SetDraftClearer(c SentDraftClearer)
SetDraftClearer folds the draft clear into a command run: the composer held "/mstmeetings" as a draft until it ran, so a successful run clears it like a message send. Optional — nil leaves drafts to the client.
func (*CommandService) Wired ¶ added in v0.0.97
func (s *CommandService) Wired() error
type CommandUserError ¶ added in v0.0.65
type CommandUserError struct {
Message string
}
CommandUserError is a command failure whose message is safe — and meant — to be shown verbatim to the invoking user (e.g. "guests can't start meetings"). Anything not wrapped in it stays a generic 500 so internal details never leak into the composer.
func (*CommandUserError) Error ¶ added in v0.0.65
func (e *CommandUserError) Error() string
type ConversationActivator ¶
type ConversationActivator interface {
ActivateLoaded(ctx context.Context, conv *model.Conversation) error
}
ConversationActivator is implemented by ConversationService and lets MessageService activate a conversation on first message send. It takes the conversation the send already loaded for its access check, so activation costs no second read (and none at all once the conversation is activated).
Test-double policy: stateful fakes (in-memory maps mimicking store semantics) stay hand-written in mocks_test.go; purely mechanical stubs — a programmable func + call recording, like this one — are generated with moq (`go generate ./internal/service/`).
type ConversationConverter ¶ added in v0.0.93
type ConversationConverter interface {
GetConversation(ctx context.Context, id string) (*model.Conversation, error)
GetUserConversations(ctx context.Context, convID string, userIDs []string) (map[string]*model.UserConversation, error)
ConvertGroupToChannel(ctx context.Context, ch *model.Channel, members []store.ConvertedMember, at time.Time) error
// MoveMembersToChannel finishes a conversion that stopped partway.
MoveMembersToChannel(ctx context.Context, channelID string, members []store.ConvertedMember) error
}
ConversationConverter is the conversation store's side of turning a group message into a private channel.
type ConversationDraftMover ¶ added in v0.0.93
type ConversationDraftMover interface {
MoveConversationDrafts(ctx context.Context, userIDs []string, conversationID string)
}
ConversationDraftMover moves what people were writing in a group message to the channel it became. Implemented by DraftService.
type ConversationService ¶
type ConversationService struct {
// contains filtered or unexported fields
}
ConversationService manages direct messages and group conversations.
func NewConversationService ¶
func NewConversationService(conversations ConversationStore, users UserStore, _ Cache, broker Broker, publisher Publisher) *ConversationService
NewConversationService creates a ConversationService with the given dependencies. The cache param is retained for call-site compatibility but is no longer used: unread is now persisted via the Conversation.MessageSeq seq counter (the same mechanism channels use), not a Redis flag.
func (*ConversationService) Activate ¶
func (s *ConversationService) Activate(ctx context.Context, convID string) error
Activate marks the conversation as activated and broadcasts EventConversationNew to all participants. Idempotent: subsequent calls return nil without republishing. Called by MessageService when the first message is sent.
func (*ConversationService) ActivateLoaded ¶ added in v0.0.97
func (s *ConversationService) ActivateLoaded(ctx context.Context, conv *model.Conversation) error
ActivateLoaded is Activate for a conversation the caller already read (the message send's access check) — no second read, and an already-activated conversation costs nothing at all.
func (*ConversationService) CreateGroup ¶
func (s *ConversationService) CreateGroup(ctx context.Context, creatorID string, participantIDs []string, name string) (*model.Conversation, error)
CreateGroup creates a new group conversation with the given participants. A group requires the creator plus at least one other unique participant.
func (*ConversationService) GetByID ¶
func (s *ConversationService) GetByID(ctx context.Context, userID, convID string) (*model.Conversation, error)
GetByID returns a conversation if the requesting user is a participant.
func (*ConversationService) GetOrCreateDM ¶
func (s *ConversationService) GetOrCreateDM(ctx context.Context, userA, userB string) (*model.Conversation, error)
GetOrCreateDM returns the existing DM conversation between two users, or creates one using a deterministic ID derived from the sorted user IDs. Self-DMs (userA == userB) are allowed — they act as a personal notepad.
func (*ConversationService) GetOrCreateGroup ¶ added in v0.0.4
func (s *ConversationService) GetOrCreateGroup(ctx context.Context, creatorID string, participantIDs []string, name string) (*model.Conversation, error)
GetOrCreateGroup returns an existing group whose participant set is the same constellation (creator + the supplied others), or creates a new one if none matches. Re-messaging the same set of people forwards into the prior group instead of spawning duplicates. Group name is ignored when matching — constellation is the identity.
The lookup is a single GetItem keyed by a deterministic group ID derived from the sorted participant set (groupConversationID), so the cost is constant regardless of how many groups the creator is in.
A group these people had that became a channel keeps its ID (the channel has it now), so their next group goes at the next ID along.
func (*ConversationService) IsParticipant ¶ added in v0.0.3
func (s *ConversationService) IsParticipant(ctx context.Context, userID, convID string) bool
IsParticipant reports whether the user appears in the conversation's participant list. Used by the WebSocket handler to gate inbound ephemeral events (typing indicator).
func (*ConversationService) ListUserConversationIDs ¶ added in v0.0.59
func (s *ConversationService) ListUserConversationIDs(ctx context.Context, userID string) ([]string, error)
ListUserConversationIDs returns the IDs of every conversation the user participates in, without the unread and DM profile enrichment — the WebSocket connect path and the presence audience resolver only need topic names. Unlike ListUserConversations it keeps conversations not yet activated: a socket that (re)connects between someone creating a DM with the user and sending its first message must already be on its topic, or that first message — and the ones after it — never arrive live.
func (*ConversationService) ListUserConversations ¶
func (s *ConversationService) ListUserConversations(ctx context.Context, userID string) ([]*model.UserConversation, error)
ListUserConversations returns all conversations the user participates in, hiding non-activated conversations from non-creator participants. A conversation becomes activated once its first message is sent.
func (*ConversationService) MarkConversationRead ¶ added in v0.0.52
func (s *ConversationService) MarkConversationRead(ctx context.Context, userID, convID string) error
MarkConversationRead catches the user up to the conversation's current MessageSeq so the sidebar badge clears and stays cleared across reloads, and notifies the caller's other tabs. Mirrors ChannelService.MarkChannelRead. Returns ErrNotFound when the caller isn't a participant.
func (*ConversationService) SetActivityTracker ¶ added in v0.0.83
func (s *ConversationService) SetActivityTracker(t ActivityReadTracker)
SetActivityTracker wires the Activity tab, so reading a conversation reads its activity items. Optional.
func (*ConversationService) SetCategory ¶ added in v0.0.3
func (s *ConversationService) SetCategory(ctx context.Context, userID, convID, categoryID string, sidebarPosition *int) error
SetCategory places the user's DM/group in one of their sidebar categories (empty: back to Direct Messages) and stores its sidebar position. The handler has checked the category is the user's.
func (*ConversationService) SetChannelMemberships ¶ added in v0.0.97
func (s *ConversationService) SetChannelMemberships(m ChannelMembershipReader)
SetChannelMemberships wires the channel-membership read that gates access to converted groups. Unwired, a converted group grants nobody.
func (*ConversationService) SetFavorite ¶ added in v0.0.3
func (s *ConversationService) SetFavorite(ctx context.Context, userID, convID string, favorite bool) error
SetFavorite pins the DM/group to the user's "Favorites" sidebar section. Caller must be a participant — pinning a conversation you can't see would create an orphan user-side row.
func (*ConversationService) SetMediaURLCache ¶ added in v0.0.39
func (s *ConversationService) SetMediaURLCache(c MediaURLCache)
SetMediaURLCache enables stable /api/v1/media URLs for transient DM avatar enrichments. The URL is still derived from the authoritative user AvatarKey.
func (*ConversationService) SetUserProfileResolver ¶ added in v0.0.39
func (s *ConversationService) SetUserProfileResolver(r interface { GetByID(context.Context, string) (*model.User, error) })
SetUserProfileResolver lets list responses use the same cached/profile- normalized user reads as the user API without changing conversation storage.
func (*ConversationService) Wired ¶ added in v0.0.97
func (s *ConversationService) Wired() error
type ConversationStore ¶
type ConversationStore interface {
CreateConversation(ctx context.Context, conv *model.Conversation, userConvs []*model.UserConversation) error
GetConversation(ctx context.Context, id string) (*model.Conversation, error)
ListUserConversations(ctx context.Context, userID string) ([]*model.UserConversation, error)
ActivateConversation(ctx context.Context, convID string, participantIDs []string) error
TouchConversation(ctx context.Context, convID string, participantIDs []string, at time.Time) error
IncrementMessageSeq(ctx context.Context, convID string) (int64, error)
SetConversationLastRead(ctx context.Context, convID, userID string, seq int64) error
SetFavorite(ctx context.Context, convID, userID string, favorite bool) error
SetCategory(ctx context.Context, convID, userID, categoryID string, sidebarPosition *int) error
}
ConversationStore defines persistence operations for conversations.
type CreateUploadParams ¶ added in v0.0.17
type CreateUploadParams struct {
UserID string
Filename string
ContentType string
SHA256 string
Size int64
Width int
Height int
}
CreateUploadParams bundles the upload-init request fields. Width and Height are optional — when the client measures them on its side (e.g. via the browser's <img> intrinsic dimensions) they're persisted at create time so the message-list renderer can reserve the layout box on first paint. Server-side backfill picks up missing dimensions on first read.
type CreateUploadResult ¶
type CreateUploadResult struct {
Attachment *model.Attachment
AlreadyExists bool
}
CreateUploadResult carries the result of an upload-init request. When AlreadyExists is true the caller should NOT upload — the attachment was dedupe-matched against a finished upload with the same SHA256 and they should just attach by ID. Otherwise the client uploads straight to S3 with requests signed by SignUploadRequest, resuming Attachment.MultipartUploadID when one is set.
type DeactivatedAccounts ¶ added in v0.0.101
type DeactivatedAccounts interface {
DeactivatedAmong(ctx context.Context, userIDs []string) (map[string]bool, error)
}
DeactivatedAccounts reports which of userIDs are deactivated accounts (the user store).
type DelegatedTokenSaver ¶ added in v0.0.116
type DelegatedTokenSaver interface {
SaveDelegatedToken(ctx context.Context, userID string, tok *oauth2.Token) error
}
DelegatedTokenSaver keeps the Microsoft token an SSO login returned (DelegatedTokens).
type DelegatedTokenStore ¶ added in v0.0.116
type DelegatedTokenStore interface {
GetDelegatedToken(ctx context.Context, userID string) ([]byte, error)
PutDelegatedToken(ctx context.Context, userID string, sealed []byte) error
}
DelegatedTokenStore persists each user's sealed Microsoft token.
type DelegatedTokens ¶ added in v0.0.116
type DelegatedTokens struct {
// contains filtered or unexported fields
}
DelegatedTokens keeps each SSO user's Microsoft (delegated Graph) token, the one their login returned, so the app can share SharePoint files as them later. Tokens are stored sealed with AES-256-GCM under a key only the app holds, bound to their user so a sealed token can't be replayed as someone else's. TokenSource renews an expired token with its refresh token and stores the renewed one.
func NewDelegatedTokens ¶ added in v0.0.116
func NewDelegatedTokens(st DelegatedTokenStore, key []byte, oauth *oauth2.Config) (*DelegatedTokens, error)
NewDelegatedTokens builds the vault. key must be 32 bytes; oauth is the SSO client, which renews the tokens.
func (*DelegatedTokens) SaveDelegatedToken ¶ added in v0.0.116
func (t *DelegatedTokens) SaveDelegatedToken(ctx context.Context, userID string, tok *oauth2.Token) error
SaveDelegatedToken stores the token a login returned. A token without a refresh token can't be renewed and is not worth keeping.
func (*DelegatedTokens) TokenSource ¶ added in v0.0.116
func (t *DelegatedTokens) TokenSource(ctx context.Context, userID string) (oauth2.TokenSource, error)
TokenSource returns the user's token, renewed when it has expired. Fails with ErrNoDelegatedToken when none is stored.
type DesktopAuthSession ¶ added in v0.0.24
type DesktopAuthSession struct {
RefreshToken string `json:"refreshToken"`
}
DesktopAuthSession is what a one-time desktop code redeems for: the refresh token /auth/desktop/complete sets as the first-party cookie. The access token is never carried — the app obtains one by refreshing.
type DirectNotifier ¶ added in v0.0.54
type DirectNotifier interface {
NotifyDirect(ctx context.Context, userID string, notif Notification)
}
DirectNotifier delivers a self-targeted alert (desktop + mobile fallback).
type DirectoryAccountLister ¶ added in v0.0.101
type DirectoryAccountLister interface {
ListAccounts(ctx context.Context) (map[string]bool, error)
}
DirectoryAccountLister reports every directory account's standing, keyed by AAD object id: true while it can sign in, false once disabled; an account deleted upstream is absent (MSDirectoryService.ListAccounts).
type DirectoryLookup ¶ added in v0.0.65
type DirectoryLookup interface {
LookupProfile(ctx context.Context, email, objectID string) (*DirectoryProfile, error)
}
DirectoryLookup resolves directory attributes (phone, manager) for a user. Implementations must treat "user not in the directory" as (nil, nil) — only transport/auth failures are errors. AuthService calls it fail-open: a directory outage degrades to an un-enriched login, never a failed one.
type DirectoryProfile ¶ added in v0.0.65
type DirectoryProfile struct {
// ObjectID is the directory's canonical id for the user (AAD object id).
ObjectID string
Phone string
Manager *model.UserManager
}
DirectoryProfile is the slice of the employee directory the app enriches user profiles with at SSO login.
type DirectoryStatusSetter ¶ added in v0.0.65
type DirectoryStatusSetter interface {
SetStatusFromDirectory(ctx context.Context, targetID string, deactivated bool) error
}
DirectoryStatusSetter flips an SSO account active/deactivated on the directory's authority (UserService.SetStatusFromDirectory): deactivation wipes refresh tokens and force-logs-out live sessions — SSO removal alone doesn't end an existing session.
type DirectorySyncLocker ¶ added in v0.0.65
type DirectorySyncLocker interface {
AcquireLock(ctx context.Context, key, token string, ttl time.Duration) (bool, error)
}
DirectorySyncLocker is the single-runner election capability (RedisCache). The winner holds the lock for the whole window, so N instances sweeping on the same interval sync the directory exactly once per window.
type DirectorySyncService ¶ added in v0.0.65
type DirectorySyncService struct {
// contains filtered or unexported fields
}
DirectorySyncService owns the sweep. It reuses the same DirectoryLookup as the login path, so both agree on what "synced" means.
func NewDirectorySyncService ¶ added in v0.0.65
func NewDirectorySyncService( directory DirectoryLookup, users UserStore, cache Cache, publisher Publisher, locker DirectorySyncLocker, newToken func() string, ) *DirectorySyncService
NewDirectorySyncService builds the sweep service. locker may be nil (tests); production wires the Redis cache so clustered instances elect one runner.
func (*DirectorySyncService) Run ¶ added in v0.0.65
func (s *DirectorySyncService) Run(ctx context.Context, interval time.Duration)
Run sweeps immediately (boot backfill) and then once per interval until the context is cancelled. Mirrors RunExpiredStatusSweeper's loop shape.
func (*DirectorySyncService) RunStatus ¶ added in v0.0.101
func (s *DirectorySyncService) RunStatus(ctx context.Context, interval time.Duration)
RunStatus checks account standing immediately and then once per interval until the context is cancelled.
func (*DirectorySyncService) SetStatusSync ¶ added in v0.0.101
func (s *DirectorySyncService) SetStatusSync(accounts DirectoryAccountLister, st DirectoryStatusSetter)
SetStatusSync wires offboarding: where account standing comes from and what applies it.
func (*DirectorySyncService) Sweep ¶ added in v0.0.65
func (s *DirectorySyncService) Sweep(ctx context.Context, interval time.Duration)
Sweep re-syncs every OIDC user's profile once, if this instance wins the window's election.
func (*DirectorySyncService) SweepStatus ¶ added in v0.0.101
func (s *DirectorySyncService) SweepStatus(ctx context.Context, interval time.Duration)
SweepStatus mirrors every SSO account's directory standing onto its Ex status, if this instance wins the window's election: disabled or deleted upstream → deactivated (sessions ended, behind the circuit breaker); able to sign in again → reactivated, unless an admin deactivated it.
Only accounts with a stored AAD object id are judged: matching by email can't tell a departed colleague from one whose mail != userPrincipalName. The profile sweep backfills the object id from the next lookup.
func (*DirectorySyncService) Wired ¶ added in v0.0.97
func (s *DirectorySyncService) Wired() error
type DraftAttachmentReleaser ¶ added in v0.0.81
type DraftAttachmentReleaser interface {
DeleteDraft(ctx context.Context, userID, attachmentID string) error
}
DraftAttachmentReleaser frees an attachment no message will use (a deleted scheduled message's files).
type DraftConflictError ¶ added in v0.0.59
type DraftConflictError struct {
Current *model.MessageDraft
}
DraftConflictError reports a write whose basis generation no longer matches the stored draft — the client acted on stale state. Current is the stored draft at decision time (nil when the scope has no draft), so callers can hand the client the truth to reconcile against. Nothing was written.
func (*DraftConflictError) Error ¶ added in v0.0.59
func (e *DraftConflictError) Error() string
type DraftService ¶ added in v0.0.23
type DraftService struct {
// contains filtered or unexported fields
}
DraftService manages server-side composer drafts.
func NewDraftService ¶ added in v0.0.23
func NewDraftService(drafts DraftStore, messages MessageStore, memberships MembershipStore, conversations ConversationStore, publisher Publisher) *DraftService
NewDraftService creates a DraftService.
func (*DraftService) Delete ¶ added in v0.0.23
func (s *DraftService) Delete(ctx context.Context, userID, id, basisGen string) error
Delete removes a draft by ID iff basisGen matches the stored generation — an explicit delete (Drafts page) still only applies to the state the user was looking at; a mismatch returns *DraftConflictError with the truth.
func (*DraftService) DeleteForScope ¶ added in v0.0.51
func (s *DraftService) DeleteForScope(ctx context.Context, userID, parentID, parentType, parentMessageID string) error
DeleteForScope removes the draft for a composer scope unconditionally. Used only by the message-send fold: sending is the authoritative user event for the scope, so it always wins — no generation check, no client clock. The id is derived from the scope, so the caller never needs the draft id.
func (*DraftService) List ¶ added in v0.0.23
func (s *DraftService) List(ctx context.Context, userID string) ([]*model.MessageDraft, error)
List returns all drafts for the user, newest first.
func (*DraftService) MoveConversationDrafts ¶ added in v0.0.93
func (s *DraftService) MoveConversationDrafts(ctx context.Context, userIDs []string, conversationID string)
MoveConversationDrafts moves these users' drafts in a group message that became a private channel (the same ID) to the channel, thread drafts included, so what they were writing is in the channel's composer. Their other tabs and devices hear of both drafts. Best-effort per draft: one that can't be moved stays where it was, still listed on the Drafts page.
func (*DraftService) Upsert ¶ added in v0.0.23
func (s *DraftService) Upsert(ctx context.Context, userID, parentID, parentType, parentMessageID, body string, attachmentIDs []string, basisGen string, opts ...UpsertOption) (*model.MessageDraft, error)
Upsert creates or replaces the draft for a single composer scope; empty content clears it (returning a nil draft). basisGen is the generation the client acted on ("" = it believes no draft exists): a mismatch means the client is stale, nothing is written, and a *DraftConflictError carrying the current state is returned — the server decides, the client reconciles.
type DraftStore ¶ added in v0.0.23
type DraftStore interface {
Upsert(ctx context.Context, draft *model.MessageDraft, basisGen string) (*store.DraftWriteResult, error)
Get(ctx context.Context, userID, id string) (*model.MessageDraft, error)
List(ctx context.Context, userID string) ([]*model.MessageDraft, error)
Delete(ctx context.Context, userID, id, basisGen string) (*store.DraftWriteResult, error)
// DeleteUnconditional removes the draft regardless of generation —
// reserved for the message-send fold, the authoritative event for a scope.
DeleteUnconditional(ctx context.Context, userID, id string) error
}
DraftStore defines persistence operations for server-side message drafts. Writes are server-owned compare-and-set: they apply only when basisGen matches the stored generation (empty = the scope must have no draft), and report the current row on rejection so callers can hand clients the truth.
type EmojiFrequencyStore ¶ added in v0.0.47
type EmojiFrequencyStore interface {
IncrementEmojiFrequency(ctx context.Context, userID, shortcode string) error
FrequentEmojis(ctx context.Context, userID string, limit int) ([]string, error)
}
EmojiFrequencyStore records and ranks a user's emoji usage. RedisCache implements it; when unset the feature is simply inert (best-effort).
type EmojiService ¶
type EmojiService struct {
// contains filtered or unexported fields
}
EmojiService manages workspace custom emojis.
func NewEmojiService ¶
func NewEmojiService(emojis EmojiStore, users UserStore, publisher Publisher) *EmojiService
NewEmojiService constructs an EmojiService.
func (*EmojiService) Create ¶
func (s *EmojiService) Create(ctx context.Context, userID, name, imageKey string, gettingWorkDone bool) (*model.CustomEmoji, error)
Create stores a new custom emoji and publishes a global event so connected clients can refresh their emoji catalog. The client supplies only the server-issued upload key; the URL is derived server-side so arbitrary or expired client URLs are never persisted.
func (*EmojiService) Delete ¶
func (s *EmojiService) Delete(ctx context.Context, userID, name string) error
Delete removes a custom emoji. Only admins or the creator may delete.
func (*EmojiService) FrequentEmojis ¶ added in v0.0.47
func (s *EmojiService) FrequentEmojis(ctx context.Context, userID string, limit int) ([]string, error)
FrequentEmojis returns up to limit of the user's most-used emoji shortcodes.
func (*EmojiService) List ¶
func (s *EmojiService) List(ctx context.Context) ([]*model.CustomEmoji, error)
List returns all custom emojis with freshly signed image URLs. Without re-signing, the stored URLs would expire after 7 days and every emoji on the workspace would silently break. Emojis missing ImageKey (created before the field existed) keep their stored URL — they'll need a one-time re-upload to self-heal.
func (*EmojiService) RecordEmojiUse ¶ added in v0.0.47
func (s *EmojiService) RecordEmojiUse(ctx context.Context, userID, shortcode string) error
RecordEmojiUse increments the usage count of a picked emoji shortcode for the given user. Best-effort: a nil store makes it a no-op.
func (*EmojiService) SetCatalogCache ¶ added in v0.0.109
func (s *EmojiService) SetCatalogCache(c Cache)
SetCatalogCache wires the shared catalog copy (emojiCatalogKey).
func (*EmojiService) SetFrequencyStore ¶ added in v0.0.47
func (s *EmojiService) SetFrequencyStore(f EmojiFrequencyStore)
SetFrequencyStore wires the per-user emoji-usage tracker. Optional — when unset, RecordEmojiUse is a no-op and FrequentEmojis returns an empty list.
func (*EmojiService) SetMediaURLCache ¶ added in v0.0.19
func (s *EmojiService) SetMediaURLCache(c MediaURLCache)
func (*EmojiService) SetSigner ¶ added in v0.0.8
func (s *EmojiService) SetSigner(signer EmojiURLSigner)
SetSigner wires the URL re-signer. Optional — when unset, List returns stored URLs as-is. Production wiring always passes the S3 client.
func (*EmojiService) Wired ¶ added in v0.0.97
func (s *EmojiService) Wired() error
type EmojiStore ¶
type EmojiStore interface {
Create(ctx context.Context, e *model.CustomEmoji) error
GetByName(ctx context.Context, name string) (*model.CustomEmoji, error)
List(ctx context.Context) ([]*model.CustomEmoji, error)
Delete(ctx context.Context, name string) error
}
EmojiStore defines the persistence operations the EmojiService depends on.
type EmojiURLSigner ¶ added in v0.0.8
type EmojiURLSigner interface {
PresignedGetURL(ctx context.Context, key string, expires time.Duration) (string, error)
GetObject(ctx context.Context, key string) (io.ReadCloser, string, int64, time.Time, error)
PutObject(ctx context.Context, key, contentType string, body []byte) error
DeleteObject(ctx context.Context, key string) error
}
EmojiURLSigner reads an uploaded emoji, writes the copy that is served, and re-signs short-lived GET URLs from a stored S3 key (storage.S3Client).
type FileEntry ¶ added in v0.0.8
type FileEntry struct {
AttachmentID string `json:"attachmentID"`
MessageID string `json:"messageID"`
AuthorID string `json:"authorID"`
CreatedAt time.Time `json:"createdAt"`
Attachment *model.Attachment `json:"attachment,omitempty"`
}
FileEntry is one file shared in the parent: the attachment, ready to show, or the SharePoint file a posted link shared, and the latest message that shared it, so the client can link back to it.
type FileIndexEntry ¶ added in v0.0.45
type FileIndexEntry struct {
AttachmentID string
MessageID string
AuthorID string
CreatedAt time.Time
// Filename is empty until a search in the parent has filled it in.
Filename string
// (AttachmentID is then "sp:" and the file's id).
SharePoint *model.SharePointFile
}
FileIndexEntry mirrors store.FileIndexRow at the service-interface boundary.
type FilePage ¶ added in v0.0.103
type FilePage struct {
Files []*FileEntry `json:"files"`
NextCursor string `json:"nextCursor,omitempty"`
}
FilePage is one page of ListFiles. NextCursor is empty on the last page.
type FileQuery ¶ added in v0.0.103
FileQuery selects one page of a parent's files. Query filters by file name (case-insensitive, anywhere in the name), Cursor continues after an earlier page, and Limit caps the page.
type GraphDirectory ¶ added in v0.0.65
type GraphDirectory interface {
GetUserProfile(ctx context.Context, key string) (*msgraph.UserProfile, error)
ResolveUserByEmail(ctx context.Context, email string) (*msgraph.UserProfile, error)
GetUserManager(ctx context.Context, key string) (*msgraph.UserProfile, error)
ListUserAccounts(ctx context.Context) ([]msgraph.UserAccount, error)
}
GraphDirectory is the slice of the Microsoft Graph client the directory service uses, as an interface so tests stub it without HTTP. ResolveUserByEmail covers tenants where mail != userPrincipalName (a plain /users/{email} lookup would 404 there).
type HastNode ¶ added in v0.0.45
HastNode is re-exported from the model package — the structure is shared with HTTP/WS wire formats. See model/hast.go for the full shape and the per-tag conventions.
type IncomingWebhookPayload ¶ added in v0.0.48
type IncomingWebhookPayload struct {
Text string `json:"text"`
Channel string `json:"channel"`
Username string `json:"username"`
IconURL string `json:"icon_url"`
IconEmoji string `json:"icon_emoji"`
Attachments []model.MessageAttachment `json:"attachments"`
// RootID posts the message as a reply in the thread of an earlier post
// by this webhook (the id ExecuteMessage returned for it).
RootID string `json:"root_id"`
// Blocks lay the message out (Block Kit); Text stays its fallback.
Blocks model.Blocks `json:"blocks"`
// BotToken is the app's bearer token from the request's Authorization
// header (never from the body): without it, buttons that call the app
// are refused.
BotToken string `json:"-"`
// Template names a layout saved on the (rich) webhook, filled from Data:
// the message is the template with its {{placeholders}} replaced.
Template string `json:"template"`
Data map[string]any `json:"data"`
// contains filtered or unexported fields
}
func (*IncomingWebhookPayload) UnmarshalJSON ¶ added in v0.0.116
func (p *IncomingWebhookPayload) UnmarshalJSON(data []byte) error
UnmarshalJSON reads a payload exactly as classic webhooks always have — text, channel, username, icons, attachments, root_id — and keeps the rich-only fields (blocks, attachments' blocks, template, data) raw. A classic webhook therefore accepts every payload it accepted before rich webhooks existed, whatever those fields hold: a stray "template": 5, or a Slack block ex doesn't model, used to be ignored and still is. Only a rich webhook reads them (readRich), and only its post can fail on them.
type IncomingWebhookService ¶ added in v0.0.48
type IncomingWebhookService struct {
// contains filtered or unexported fields
}
func NewIncomingWebhookService ¶ added in v0.0.48
func NewIncomingWebhookService(store IncomingWebhookStore, channels WebhookChannelResolver, messages *MessageService, images WebhookImageProxy, baseURL string) *IncomingWebhookService
func (*IncomingWebhookService) Create ¶ added in v0.0.48
func (s *IncomingWebhookService) Create(ctx context.Context, actor WebhookActor, in *model.IncomingWebhook) (*model.IncomingWebhook, error)
func (*IncomingWebhookService) Delete ¶ added in v0.0.48
func (s *IncomingWebhookService) Delete(ctx context.Context, actor WebhookActor, id string) error
func (*IncomingWebhookService) DeleteTemplate ¶ added in v0.0.116
func (s *IncomingWebhookService) DeleteTemplate(ctx context.Context, actor WebhookActor, id, key string) (*model.IncomingWebhook, error)
DeleteTemplate removes a rich webhook's template.
func (*IncomingWebhookService) Execute ¶ added in v0.0.48
func (s *IncomingWebhookService) Execute(ctx context.Context, id string, payload IncomingWebhookPayload) error
func (*IncomingWebhookService) ExecuteClassic ¶ added in v0.0.116
func (s *IncomingWebhookService) ExecuteClassic(ctx context.Context, id string, payload IncomingWebhookPayload) (*model.Message, error)
ExecuteClassic delivers a payload sent to the classic URL, /hooks/{id}.
func (*IncomingWebhookService) ExecuteMessage ¶ added in v0.0.80
func (s *IncomingWebhookService) ExecuteMessage(ctx context.Context, id string, payload IncomingWebhookPayload) (*model.Message, error)
ExecuteMessage delivers a webhook payload and returns the stored message, so callers can thread follow-ups under it via RootID.
func (*IncomingWebhookService) ExecuteRich ¶ added in v0.0.116
func (s *IncomingWebhookService) ExecuteRich(ctx context.Context, id string, payload IncomingWebhookPayload) (*model.Message, error)
ExecuteRich delivers a payload sent to the rich URL, /hooks/v2/{id}.
func (*IncomingWebhookService) List ¶ added in v0.0.48
func (s *IncomingWebhookService) List(ctx context.Context, actor WebhookActor) ([]*model.IncomingWebhook, error)
List returns every webhook to a system admin and the actor's own to anyone else.
func (*IncomingWebhookService) PreviewMessage ¶ added in v0.0.116
func (s *IncomingWebhookService) PreviewMessage(ctx context.Context, actor WebhookActor, payload IncomingWebhookPayload) (*model.Message, error)
PreviewMessage shows the actor what a payload would post — its text, blocks and cards, normalized and checked exactly as Execute does — without posting it. Images stay the payload's own URLs: nothing is fetched or stored for a preview.
func (*IncomingWebhookService) SaveTemplate ¶ added in v0.0.116
func (s *IncomingWebhookService) SaveTemplate(ctx context.Context, actor WebhookActor, id, key string, payload json.RawMessage) (*model.IncomingWebhook, error)
SaveTemplate adds or replaces a rich webhook's template. The payload must be a JSON object; placeholders are checked when the template is used, against the data the app sends.
func (*IncomingWebhookService) SetBotProvisioner ¶ added in v0.0.68
func (s *IncomingWebhookService) SetBotProvisioner(b WebhookBotProvisioner)
func (*IncomingWebhookService) SetDMResolver ¶ added in v0.0.48
func (s *IncomingWebhookService) SetDMResolver(dms WebhookDMResolver)
func (*IncomingWebhookService) SetMembershipResolver ¶ added in v0.0.48
func (s *IncomingWebhookService) SetMembershipResolver(m WebhookMembershipResolver)
func (*IncomingWebhookService) SetPublisher ¶ added in v0.0.48
func (s *IncomingWebhookService) SetPublisher(p Publisher)
func (*IncomingWebhookService) SetUserResolver ¶ added in v0.0.48
func (s *IncomingWebhookService) SetUserResolver(users WebhookUserResolver)
func (*IncomingWebhookService) TranslateMarkup ¶ added in v0.0.112
func (s *IncomingWebhookService) TranslateMarkup(ctx context.Context, text string) string
TranslateMarkup turns Mattermost (and Slack) message markup into ex's: ~channel and @user references into mentions, @channel and <!channel> into @all, <url|label> into a link. The Mattermost-compatible API posts with it. Mentions stay by name only, as for a classic webhook.
func (*IncomingWebhookService) URL ¶ added in v0.0.48
func (s *IncomingWebhookService) URL(wh *model.IncomingWebhook) string
func (*IncomingWebhookService) Update ¶ added in v0.0.48
func (s *IncomingWebhookService) Update(ctx context.Context, actor WebhookActor, id string, in *model.IncomingWebhook) (*model.IncomingWebhook, error)
Update edits an existing webhook's configurable fields. The ID, secret (the ID is the secret), creator, and creation time are preserved; the target channel is re-resolved so name/slug stay consistent.
func (*IncomingWebhookService) Wired ¶ added in v0.0.97
func (s *IncomingWebhookService) Wired() error
type IncomingWebhookStore ¶ added in v0.0.48
type IncomingWebhookStore interface {
Create(ctx context.Context, wh *model.IncomingWebhook) error
Get(ctx context.Context, id string) (*model.IncomingWebhook, error)
List(ctx context.Context) ([]*model.IncomingWebhook, error)
Update(ctx context.Context, wh *model.IncomingWebhook) error
Delete(ctx context.Context, id string) error
}
type InteractionConfig ¶ added in v0.0.116
type InteractionConfig struct {
SigningKey []byte
BaseURL string
AllowPrivate bool
InternalDomains []string
}
InteractionConfig is what NewInteractionService needs beyond its peers.
type InteractionService ¶ added in v0.0.116
type InteractionService struct {
// contains filtered or unexported fields
}
InteractionService connects apps to the buttons on their messages: it sends clicks, applies the apps' answers, and runs the setup the webhooks panel offers.
func NewInteractionService ¶ added in v0.0.116
func NewInteractionService(messages *MessageService, webhooks *IncomingWebhookService, state AppInteractionState, limiter ClickLimiter, publisher Publisher, cfg InteractionConfig) *InteractionService
NewInteractionService wires interactivity and registers it with the message service, which hands it every click on an app button.
func (*InteractionService) AuthenticateApp ¶ added in v0.0.116
func (s *InteractionService) AuthenticateApp(ctx context.Context, token string) (*model.IncomingWebhook, error)
AuthenticateApp finds the app a bot token belongs to and spends one of its calls this minute. The token is compared in constant time against each app's current and (during a rotation) previous token.
func (*InteractionService) Click ¶ added in v0.0.116
func (s *InteractionService) Click(ctx context.Context, msg *model.Message, parentType string, button model.BlockElement, blockID, userID string, value RawValue) (*AppClickResult, error)
Click sends userID's click on an app button to the app and applies its answer. A slow or failing app costs the clicker a notice, never an error: nothing else changes.
func (*InteractionService) CloseView ¶ added in v0.0.116
func (s *InteractionService) CloseView(ctx context.Context, userID, viewID string, all bool, raw map[string]map[string]RawValue) error
CloseView forgets a form its person closed — with all, its whole stack; otherwise just this one, and the form under it shows again. A form that asked (notify_on_close) tells its app, with what was entered so far. Closing one already gone is fine.
func (*InteractionService) Idempotent ¶ added in v0.0.116
func (s *InteractionService) Idempotent(ctx context.Context, wh *model.IncomingWebhook, method, key string, run func() (any, error)) ([]byte, error)
Idempotent runs an app's call once per Idempotency-Key: a retry with the same key (after a timeout, say) gets the first call's answer instead of doing it again. A call that fails releases the key. No key: just run.
func (*InteractionService) OpenView ¶ added in v0.0.116
func (s *InteractionService) OpenView(ctx context.Context, wh *model.IncomingWebhook, triggerID string, in model.View) (_ *model.View, err error)
OpenView opens a form for the person whose click (or submission) minted triggerID, in the tab they clicked from (views.open).
func (*InteractionService) PreviewView ¶ added in v0.0.116
func (s *InteractionService) PreviewView(ctx context.Context, actor WebhookActor, in model.View) (*model.View, error)
PreviewView shows the actor a form as ex would draw it — checked exactly as views.open checks it — without opening it. Images stay the form's own URLs: nothing is fetched for a preview.
func (*InteractionService) PushView ¶ added in v0.0.116
func (s *InteractionService) PushView(ctx context.Context, wh *model.IncomingWebhook, triggerID string, in model.View) (_ *model.View, err error)
PushView puts a form on top of the one the person is in (views.push). The trigger_id must come from that form — a change in it, a button in it, or its submission — so an app can only stack forms on its own forms, for the same person, in the same tab.
func (*InteractionService) Respond ¶ added in v0.0.116
func (s *InteractionService) Respond(ctx context.Context, token string, resp AppResponse) error
Respond carries out an answer posted to a response_url. The URL is the credential: it stands for one click on one message, for 30 minutes and 5 uses. A notice goes to the clicker alone.
func (*InteractionService) RotateBotToken ¶ added in v0.0.116
func (s *InteractionService) RotateBotToken(ctx context.Context, actor WebhookActor, id string, revokeNow bool) (string, *model.IncomingWebhook, error)
RotateBotToken issues a new bot token, shown once. The old one keeps working for a day unless revokeNow.
func (*InteractionService) RotateSigningSecret ¶ added in v0.0.116
func (s *InteractionService) RotateSigningSecret(ctx context.Context, actor WebhookActor, id string, revokeNow bool) (string, *model.IncomingWebhook, error)
RotateSigningSecret issues a new signing secret, shown once. ex signs with the old one too for a day unless revokeNow.
func (*InteractionService) SendTest ¶ added in v0.0.116
func (s *InteractionService) SendTest(ctx context.Context, actor WebhookActor, id string) (*TestResult, error)
SendTest sends the app a signed sample click ("test": true), so its setup can be checked before anyone clicks for real.
func (*InteractionService) SetAdminPaused ¶ added in v0.0.116
func (s *InteractionService) SetAdminPaused(ctx context.Context, actor WebhookActor, id string, paused bool) (*model.IncomingWebhook, error)
SetAdminPaused stops (or resumes) the app's buttons everywhere. Workspace admins only.
func (*InteractionService) SetEmailSharing ¶ added in v0.0.116
func (s *InteractionService) SetEmailSharing(ctx context.Context, actor WebhookActor, id string, on bool) (*model.IncomingWebhook, error)
SetEmailSharing lets the app see clickers' emails. Workspace admins only: any member can own a webhook, but not hand out others' addresses.
func (*InteractionService) SetRequestURL ¶ added in v0.0.116
func (s *InteractionService) SetRequestURL(ctx context.Context, actor WebhookActor, id, raw string) (*model.IncomingWebhook, error)
SetRequestURL sets where the app receives clicks; empty turns interactivity off (posted buttons stay, disabled).
func (*InteractionService) Status ¶ added in v0.0.116
func (s *InteractionService) Status(ctx context.Context, actor WebhookActor, id string) (*InteractionStatus, error)
Status shows the webhook's interactivity to someone who may manage it.
func (*InteractionService) SubmitView ¶ added in v0.0.116
func (s *InteractionService) SubmitView(ctx context.Context, userID, viewID string, raw map[string]map[string]RawValue) (*ViewSubmitResult, error)
SubmitView sends a person's form to the app, once ex has checked it against the stored form, and carries out the app's answer.
func (*InteractionService) UpdateMessage ¶ added in v0.0.116
func (s *InteractionService) UpdateMessage(ctx context.Context, wh *model.IncomingWebhook, in MessageUpdate) (_ *model.Message, err error)
UpdateMessage replaces one of the app's own messages at any time (messages.update) — as replace_original does, without a click: live for everyone, no "edited" label, nobody notified.
func (*InteractionService) UpdateView ¶ added in v0.0.116
func (s *InteractionService) UpdateView(ctx context.Context, wh *model.IncomingWebhook, viewID, externalID, hash string, in model.View) (_ *model.View, err error)
UpdateView replaces an open form — named by its ID or the app's external_id — while the person has it open (views.update). With a hash, only if nothing changed the form since the app last saw it.
func (*InteractionService) ViewAction ¶ added in v0.0.116
func (s *InteractionService) ViewAction(ctx context.Context, userID, viewID, blockID, actionID string, value RawValue, raw map[string]map[string]RawValue) (*ViewActionResult, error)
ViewAction sends a change in a person's form to the app (block_actions from a view): which element, its value — checked against the stored form — and the form as it stands, with a trigger_id to update or push forms.
type InteractionStatus ¶ added in v0.0.116
type InteractionStatus struct {
Webhook *model.IncomingWebhook `json:"webhook"`
PausedFor int64 `json:"pausedForSeconds,omitempty"`
Interactions []model.InteractionEntry `json:"interactions"`
}
InteractionStatus is an app's interactivity at a glance: its settings, whether it's paused for failing, and its recent interactions.
type InviteStore ¶
type InviteStore interface {
CreateInvite(ctx context.Context, inv *model.Invite) error
GetInvite(ctx context.Context, token string) (*model.Invite, error)
DeleteInvite(ctx context.Context, token string) error
}
InviteStore defines persistence operations for invitations.
type JWTProvider ¶
type JWTProvider interface {
GenerateAccessToken(user *model.User) (string, error)
GenerateRefreshToken() (raw string, hash string, err error)
RefreshTTL() time.Duration
}
JWTProvider generates and validates JWT tokens.
type MSDirectoryService ¶ added in v0.0.65
type MSDirectoryService struct {
// contains filtered or unexported fields
}
MSDirectoryService reads phone + manager from Microsoft Graph and resolves the manager to an Ex user (by email) so profiles can link to them.
func NewMSDirectoryService ¶ added in v0.0.65
func NewMSDirectoryService(graph GraphDirectory, users UserStore) *MSDirectoryService
NewMSDirectoryService builds the Graph-backed directory lookup.
func (*MSDirectoryService) ListAccounts ¶ added in v0.0.101
ListAccounts reports every directory account's standing, keyed by AAD object id: true while it can sign in, false once it is disabled. An account deleted upstream is absent.
func (*MSDirectoryService) LookupProfile ¶ added in v0.0.65
func (s *MSDirectoryService) LookupProfile(ctx context.Context, email, objectID string) (*DirectoryProfile, error)
LookupProfile fetches the user's directory profile keyed by AAD object id when known (robust against email != userPrincipalName), falling back to email. A user missing from the directory yields (nil, nil). A manager lookup failure degrades to a phone-only profile — half the enrichment beats failing the login sync entirely.
type MarkdownRenderer ¶ added in v0.0.45
type MarkdownRenderer struct {
// contains filtered or unexported fields
}
MarkdownRenderer wraps a goldmark parser configured with the extensions we use: GFM strikethrough only (we deliberately disable autolink-literal because the frontend wants to format bare URLs with the leading https:// stripped from the visible text — easier to reason about with a single bare-url renderer than two paths).
func NewMarkdownRenderer ¶ added in v0.0.45
func NewMarkdownRenderer() *MarkdownRenderer
func (*MarkdownRenderer) RenderToHast ¶ added in v0.0.45
func (r *MarkdownRenderer) RenderToHast(body string) *HastNode
RenderToHast parses `body` and returns a hast tree. The tree is always a `root` node; children are block-level elements.
The transform also walks every text leaf to extract our custom inline syntax (mentions, hashtags, emoji shortcodes, giphy refs, raw image syntax left as literal text, bare URLs) into `ex-*` element nodes. Doing this on the backend keeps the per-message parsing cost a single, server-side pass — no matter how many clients render it, no matter how many times a message re-renders on the frontend.
type MarkupTranslator ¶ added in v0.0.112
MarkupTranslator turns Mattermost message markup into ex's (IncomingWebhookService).
type MattermostChannels ¶ added in v0.0.112
type MattermostChannels interface {
Create(ctx context.Context, userID, name string, chanType model.ChannelType, description string) (*model.Channel, error)
GetByID(ctx context.Context, id string) (*model.Channel, error)
AddMember(ctx context.Context, actorID, channelID, userID string, role model.ChannelRole) error
}
MattermostChannels is the channel side (ChannelService).
type MattermostDMs ¶ added in v0.0.112
type MattermostDMs interface {
GetOrCreateDM(ctx context.Context, userA, userB string) (*model.Conversation, error)
}
MattermostDMs opens direct conversations (ConversationService).
type MattermostMessages ¶ added in v0.0.112
type MattermostMessages interface {
Send(ctx context.Context, userID, parentID, parentType, body, parentMessageID string, attachmentIDs ...string) (*model.Message, error)
}
MattermostMessages posts (MessageService).
type MattermostService ¶ added in v0.0.112
type MattermostService struct {
// contains filtered or unexported fields
}
MattermostService carries out the Mattermost API's calls.
func NewMattermostService ¶ added in v0.0.112
func NewMattermostService(channels MattermostChannels, memberships MembershipGetter, users UserStore, messages MattermostMessages, conversations MattermostDMs, markup MarkupTranslator) *MattermostService
NewMattermostService wires the Mattermost API's service.
func (*MattermostService) AddChannelMember ¶ added in v0.0.112
func (s *MattermostService) AddChannelMember(ctx context.Context, actorID, channelID, userID string) (*model.ChannelMembership, error)
AddChannelMember adds userID to a channel the actor is in, and returns the membership. Adding someone already there changes nothing and answers the same, as Mattermost does: an integration re-inviting whoever is relevant must not demote an admin or repeat the "was added" line.
func (*MattermostService) CreateChannel ¶ added in v0.0.112
func (s *MattermostService) CreateChannel(ctx context.Context, actorID, name string, private bool, purpose string) (*model.Channel, error)
CreateChannel creates a channel owned by the bot creating it. Its name is the Mattermost name (ex channels have no separate display name), its purpose the description.
func (*MattermostService) CreatePost ¶ added in v0.0.112
func (s *MattermostService) CreatePost(ctx context.Context, actorID, channelID, message, rootID string) (*model.Message, error)
CreatePost posts message to a channel or a direct conversation (Mattermost calls both channels), as a reply when rootID names a thread. Mattermost markup in the text becomes ex's.
func (*MattermostService) DirectChannel ¶ added in v0.0.112
func (s *MattermostService) DirectChannel(ctx context.Context, actorID string, userIDs []string) (*model.Conversation, error)
DirectChannel opens (or finds) the direct conversation between the actor and one other user. Mattermost takes the pair as two user IDs, the caller's among them.
type MediaGrant ¶ added in v0.0.97
type MediaGrant struct {
UserID string `json:"u"`
ParentID string `json:"p,omitempty"`
ParentType string `json:"t,omitempty"`
MessageID string `json:"m,omitempty"`
}
MediaGrant is who a scoped media URL was issued to and where their access to the file was proved.
type MediaObject ¶ added in v0.0.19
type MediaObject struct {
Body io.ReadCloser
ContentType string
Filename string
// Size is the length of Body: the whole object, or the range asked for.
Size int64
// ContentRange is set when Body is a range ("bytes 0-1023/52345").
ContentRange string
LastModified time.Time
}
func OpenStableMedia ¶ added in v0.0.19
func OpenStableMedia(ctx context.Context, c MediaURLCache, objects MediaObjectStore, token, byteRange string) (*MediaObject, error)
OpenStableMedia opens the object behind a media token — all of it, or the one byte range in byteRange (an HTTP Range value). A scoped token opens nothing here: only AttachmentService.OpenMedia can check its grant.
type MediaObjectStore ¶ added in v0.0.19
type MediaObjectStore interface {
OpenObjectRange(ctx context.Context, key, byteRange string) (io.ReadCloser, string, int64, string, time.Time, error)
}
MediaObjectStore opens an object, or the one byte range of it a player asked for (see storage.S3Client.OpenObjectRange).
type MediaURLBatchCache ¶ added in v0.0.59
type MediaURLBatchCache interface {
GetManyJSON(ctx context.Context, keys []string) ([][]byte, error)
SetManyJSON(ctx context.Context, keys []string, values []any, ttl time.Duration) error
}
MediaURLBatchCache is the optional batching capability of a MediaURLCache (implemented by the Redis cache). Callers type-assert it and fall back to per-item Get/Set when absent, mirroring the batchUserStore pattern.
type MediaURLCache ¶ added in v0.0.19
type MediaURLCache interface {
Get(ctx context.Context, key string, dest interface{}) error
Set(ctx context.Context, key string, val interface{}, ttl time.Duration) error
}
MediaURLCache is the Redis-shaped cache used to map stable browser media URLs to object storage keys. It is deliberately not durable application data: if it expires, the next metadata fetch issues a new stable URL.
type MediaURLRequest ¶ added in v0.0.59
type MediaURLRequest struct {
ID string
S3Key string
Filename string
ContentType string
Size int64
}
MediaURLRequest is one item for StableMediaURLs.
type MeetingCreator ¶ added in v0.0.65
type MeetingCreator interface {
CreateOnlineMeeting(ctx context.Context, organizerKey string, req msgraph.OnlineMeetingRequest) (*msgraph.OnlineMeeting, error)
ResolveUserByEmail(ctx context.Context, email string) (*msgraph.UserProfile, error)
}
MeetingCreator is the slice of the Graph client the command needs, as an interface so tests stub meeting creation without HTTP. ResolveUserByEmail recovers the organizer's AAD object id (tolerating mail != UPN tenants): the app-only onlineMeetings endpoint rejects UPN/email keys with a 400, so a user whose session predates oid capture must be resolved first.
type MeetingMessageSender ¶ added in v0.0.65
type MeetingMessageSender interface {
SendNoIndex(ctx context.Context, userID, parentID, parentType, body, parentMessageID string, attachmentIDs ...string) (*model.Message, error)
}
MeetingMessageSender posts the join-link message into the chat; satisfied by MessageService.SendNoIndex (message.new + the normal notification pipeline, but excluded from the search index — a stale join link surfacing in search results is noise, not content).
type MeetingUserResolver ¶ added in v0.0.65
type MeetingUserResolver interface {
GetByID(ctx context.Context, id string) (*model.User, error)
GetBatch(ctx context.Context, ids []string) ([]*model.User, error)
}
MeetingUserResolver resolves users for organizer/attendee data; satisfied by UserService (cache-first).
type MembershipGetter ¶ added in v0.0.112
type MembershipGetter interface {
GetMembership(ctx context.Context, channelID, userID string) (*model.ChannelMembership, error)
}
MembershipGetter reads one channel membership (the membership store).
type MembershipStore ¶
type MembershipStore interface {
AddMember(ctx context.Context, membership *model.ChannelMembership, userChannel *model.UserChannel) error
RemoveMember(ctx context.Context, channelID, userID string) error
GetMembership(ctx context.Context, channelID, userID string) (*model.ChannelMembership, error)
UpdateMemberRole(ctx context.Context, channelID, userID string, role model.ChannelRole) error
ListMembers(ctx context.Context, channelID string) ([]*model.ChannelMembership, error)
ListUserChannels(ctx context.Context, userID string) ([]*model.UserChannel, error)
// UserChannelNotifPrefs returns each user's per-channel notification
// override (muted + the five inherit-or-override fields), batched into a
// single fan-out instead of one query per user.
UserChannelNotifPrefs(ctx context.Context, channelID string, userIDs []string) (map[string]*model.UserChannel, error)
SetMute(ctx context.Context, channelID, userID string, muted bool) error
// SetChannelLastRead stamps the channel's current MessageSeq onto the
// user's row, marking everything up to it as read.
SetChannelLastRead(ctx context.Context, channelID, userID string, seq int64) error
SetFavorite(ctx context.Context, channelID, userID string, favorite bool) error
SetCategory(ctx context.Context, channelID, userID, categoryID string, sidebarPosition *int) error
// SetNotifPrefs persists a user's per-channel notification overrides;
// nil fields clear the override back to "inherit account default".
SetNotifPrefs(ctx context.Context, channelID, userID string, override model.ChannelNotificationOverride) error
}
MembershipStore defines persistence operations for channel memberships.
type MentionDirectory ¶ added in v0.0.97
type MentionDirectory struct {
// contains filtered or unexported fields
}
MentionDirectory resolves mention IDs: users through the cache-first batched user read, channels through one BatchGetItem of their META rows.
func NewMentionDirectory ¶ added in v0.0.97
func NewMentionDirectory(users mentionUserSource, channels batchChannelStore) *MentionDirectory
NewMentionDirectory builds the production MentionResolver.
func (*MentionDirectory) ResolveMentions ¶ added in v0.0.97
func (d *MentionDirectory) ResolveMentions(ctx context.Context, userIDs, channelIDs []string) (MentionNames, error)
ResolveMentions returns the current display name of every user and slug of every channel that exists. An ID that resolves to nothing (or to a blank name) is simply absent, so its mention renders as text.
type MentionNames ¶ added in v0.0.97
type MentionNames struct {
Users map[string]string // user ID → current display name
Channels map[string]string // channel ID → current slug
}
MentionNames maps mention IDs to what their pill shows.
type MentionResolver ¶ added in v0.0.97
type MentionResolver interface {
ResolveMentions(ctx context.Context, userIDs, channelIDs []string) (MentionNames, error)
}
MentionResolver looks up, in one batched call, every user and channel a batch of rendered messages mentions. Implemented by MentionDirectory.
type MentionUser ¶ added in v0.0.3
MentionUser is a single in-message mention of a specific user. The rendered text in the message is "@<DisplayName>" — the ID is the authoritative routing target for notifications.
type MessageActivityRecorder ¶ added in v0.0.83
type MessageActivityRecorder interface {
RecordReaction(ctx context.Context, msg *model.Message, parentType, actorID, emoji string)
MessagesDeleted(ctx context.Context, parentID, parentType string, messageIDs []string)
MessageEdited(ctx context.Context, msg *model.Message, parentType string)
ActivityReadTracker
}
MessageActivityRecorder keeps the Activity tab in step with messages: it records "someone reacted to your message" hints, drops the items about deleted messages, refreshes previews on edit, and follows mark-unread. Implemented by ActivityService; wired optionally so the message service degrades gracefully when activity is off.
type MessageIndexer ¶ added in v0.0.13
type MessageLinkService ¶ added in v0.0.49
type MessageLinkService struct {
// contains filtered or unexported fields
}
MessageLinkService turns a deep link to a message *inside this workspace* into a rich preview (author, channel, body, image) — the Slack / Mattermost "message link unfurl". It enforces the viewer's access: a link to a channel or DM the viewer can't see resolves to no preview rather than leaking the message, and never falls back to scraping our own host.
func NewMessageLinkService ¶ added in v0.0.49
func NewMessageLinkService( baseURL string, channels messageLinkChannels, memberships messageLinkMemberships, conversations messageLinkConversations, messages messageLinkMessages, users messageLinkUsers, attachments messageLinkAttachments, ) *MessageLinkService
NewMessageLinkService derives the workspace host from baseURL (BASE_URL) so only links to this deployment unfurl as message previews.
func (*MessageLinkService) Preview ¶ added in v0.0.49
func (s *MessageLinkService) Preview(ctx context.Context, viewerID, rawURL string) (*UnfurlPreview, bool)
Preview resolves rawURL. The bool reports whether rawURL is an internal message link at all; when true and the preview is nil, the link points somewhere the viewer can't see (the caller must NOT then web-fetch our own host). (nil, false) means rawURL isn't one of our message links.
type MessageNotifier ¶
type MessageNotifier interface {
NotifyForMessage(ctx context.Context, msg *model.Message, parentType string, threadRoot *model.Message)
}
MessageNotifier is the slice of NotificationService MessageService cares about. Defined as an interface so the dependency is explicit and tests can stub it without instantiating the real notifier. threadRoot is the authoritative root returned by IncrementReplyMetadata for a thread reply (nil otherwise, or when the bump failed) — the notifier derives the thread.updated fan-out from it alongside the notification decision, so the two audiences share one snapshot and can't drift.
type MessageReminderSync ¶ added in v0.0.85
type MessageReminderSync interface {
MessagesDeleted(ctx context.Context, parentID, parentType string, messageIDs []string)
MessageEdited(ctx context.Context, msg *model.Message, parentType string)
}
MessageReminderSync keeps pending reminders (each a copy of a message's text) in step with their message: a deleted message takes its reminders, an edit re-previews them. Implemented by ReminderService.
type MessageService ¶
type MessageService struct {
// contains filtered or unexported fields
}
MessageService handles sending, editing, deleting, and listing messages.
func NewMessageService ¶
func NewMessageService( messages MessageStore, memberships MembershipStore, conversations ConversationStore, publisher Publisher, broker Broker, ) *MessageService
NewMessageService creates a MessageService from the required core five — the test-oriented constructor; optional capabilities attach via Set*.
func NewMessageServiceFromDeps ¶ added in v0.0.64
func NewMessageServiceFromDeps(d MessageServiceDeps) *MessageService
NewMessageServiceFromDeps constructs a fully-wired MessageService.
func (*MessageService) Act ¶ added in v0.0.116
func (s *MessageService) Act(ctx context.Context, userID, parentID, parentType, msgID, blockID, actionID string) (*ActResult, error)
Act applies userID's click on the button (blockID, actionID) of a message. Everything that decides the outcome — which button, its action, who may click it — comes from the stored message, never from the request: the client names the button and nothing else. Built-in actions (ack, vote) are applied here; the result is broadcast like any change to the message, but marks it neither edited nor unread.
func (*MessageService) ActWithValue ¶ added in v0.0.116
func (s *MessageService) ActWithValue(ctx context.Context, userID, parentID, parentType, msgID, blockID, actionID string, value RawValue) (*ActResult, error)
ActWithValue is Act for an element that takes a value — a select, a picker, checkboxes: value is what the person picked, which the app gets only once it is checked against the stored element.
func (*MessageService) CanAccessMessageAttachment ¶ added in v0.0.29
func (s *MessageService) CanAccessMessageAttachment(ctx context.Context, userID, parentID, parentType, messageID, attachmentID string) error
func (*MessageService) CheckAccess ¶ added in v0.0.26
func (s *MessageService) CheckAccess(ctx context.Context, userID, parentID, parentType string) error
func (*MessageService) CheckWriteAccess ¶ added in v0.0.92
func (s *MessageService) CheckWriteAccess(ctx context.Context, userID, parentID, parentType string) error
CheckWriteAccess is CheckAccess for writes: the parent must also accept new content (an archived channel is read-only).
func (*MessageService) Delete ¶
func (s *MessageService) Delete(ctx context.Context, userID, parentID, parentType, msgID string) error
Delete soft-deletes a message: the row stays in the list (so replies referencing it can still resolve their thread root) but Body / AttachmentIDs / Reactions are cleared and the row is flagged Deleted=true so clients render a "(Message deleted)" placeholder. The author or a channel admin (for channel messages) may delete.
func (*MessageService) Edit ¶
func (s *MessageService) Edit(ctx context.Context, userID, parentID, parentType, msgID, newBody string, attachmentIDs []string) (*model.Message, error)
Edit updates the body and (optionally) the attachment list of an existing message. Only the original author may edit. If attachmentIDs is nil, the existing attachments are preserved; if non-nil (even an empty slice) the attachments are replaced wholesale and add/remove refs are reconciled.
func (*MessageService) List ¶
func (s *MessageService) List(ctx context.Context, userID, parentID, parentType, before string, limit int) ([]*model.Message, bool, error)
List returns top-level messages for a parent with cursor-based pagination. Thread replies live in the thread panel and are filtered out by listTopLevel.
func (*MessageService) ListAfter ¶ added in v0.0.13
func (s *MessageService) ListAfter(ctx context.Context, userID, parentID, parentType, after string, limit int) ([]*model.Message, bool, error)
ListAfter returns top-level messages strictly newer than `after`.
func (*MessageService) ListAround ¶ added in v0.0.13
func (s *MessageService) ListAround(ctx context.Context, userID, parentID, parentType, msgID string, before, after int) ([]*model.Message, bool, bool, error)
ListAround returns a top-level window centered on msgID so a deep- link can load only the messages near the target instead of paging back from the live tail. The three sub-fetches run concurrently — this is on the user-perceived "Jump to message" path so latency multiplies if they serialize.
func (*MessageService) ListFiles ¶ added in v0.0.8
func (s *MessageService) ListFiles(ctx context.Context, userID, parentID, parentType string, q FileQuery) (*FilePage, error)
ListFiles returns one page of the files shared in the parent, newest first.
Re-shares of the same physical file collapse to one row keyed on the AttachmentID — the AttachmentService dedupes uploads by SHA-256, so the same content always resolves to the same ID, and the user only sees the latest message that referenced it.
It reads the FILE# index, then one batch of messages and one batch of attachments per page, however many files the parent holds. (The panel used to fetch every attachment one request at a time, which on a busy channel ran into the per-user rate limit it shares with the images in the chat.)
func (*MessageService) ListPinned ¶ added in v0.0.2
func (s *MessageService) ListPinned(ctx context.Context, userID, parentID, parentType string) ([]*model.Message, error)
ListPinned returns all currently-pinned messages for a parent in reverse-chronological order (newest pin first by message ID). Membership is checked via the parent's access guard.
Backed by the dedicated PIN# index in the same DDB partition — the query returns only the pinned rows, then we batch-fetch the full messages by ID. Previously this scanned up to 1000 messages and filtered in-memory, which broke past that cap and burned RCUs on every sidebar click.
func (*MessageService) ListThreadMessages ¶
func (s *MessageService) ListThreadMessages(ctx context.Context, userID, parentID, parentType, threadRootID string) ([]*model.Message, error)
ListThreadMessages returns the root message followed by all reply messages for a thread, in chronological order (oldest first), from the thread's reply index alone: every reply is indexed as it is written (and older ones were backfilled), so the parent's history is never read for it.
func (*MessageService) ListThreadsPage ¶ added in v0.0.107
func (s *MessageService) ListThreadsPage(ctx context.Context, userID, cursor string, limit int) (*ThreadPage, error)
ListThreadsPage returns one page of userID's threads after cursor ("" for the first page), at most limit long.
func (*MessageService) MarkUnread ¶ added in v0.0.81
func (s *MessageService) MarkUnread(ctx context.Context, userID, parentID, parentType, msgID string) (*model.MarkUnreadResult, error)
MarkUnread makes msgID and everything after it unread again for userID.
Parent read state is a sequence watermark (unread = MessageSeq - LastReadSeq) and messages don't carry their seq, so a top-level message is mapped by counting the messages that bumped the counter from it onward — the same rule bumpUnreadSeq applies — and the watermark is set that far behind the current counter. A thread reply instead rewinds the thread's seen time to just before the reply and flags the thread, so it shows unread in Threads.
Publishes userchannel.updated to the caller's own topic so their other tabs and devices pick the change up.
func (*MessageService) MessageAttachmentIDs ¶ added in v0.0.59
func (s *MessageService) MessageAttachmentIDs(ctx context.Context, userID, parentID, parentType, messageID string) (map[string]bool, error)
MessageAttachmentIDs returns the attachment-ID set referenced by messageID after verifying the caller's access to the parent — the batch form of CanAccessMessageAttachment: one membership read + one message read cover a whole attachment batch instead of repeating both per attachment. An empty messageID is a definitive denial (attachment reads are always anchored to a message; the old un-anchored fallback scanned up to 1000 messages and was unreachable from any caller).
func (*MessageService) NotificationsWired ¶ added in v0.0.97
func (s *MessageService) NotificationsWired() error
NotificationsWired reports whether the alert pipeline is complete — a notifier, and the durable safety net behind it. Boot refuses to serve without it: a message service that silently alerts nobody is an incident.
func (*MessageService) ParentMemberIDs ¶ added in v0.0.83
func (s *MessageService) ParentMemberIDs(ctx context.Context, parentID, parentType string) ([]string, error)
ParentMemberIDs lists everyone who can read a channel or conversation.
func (*MessageService) ResolveThreadRoot ¶ added in v0.0.72
func (s *MessageService) ResolveThreadRoot(ctx context.Context, userID, parentID, parentType, msgID string) (string, error)
ResolveThreadRoot maps any message id to the root of its thread: a reply resolves to its ParentMessageID, a root (or unthreaded message) to itself. Permalinks point at arbitrary messages — this is what lets "read the thread this link is in" work no matter which message the link names. Access-checked like every other read; an unknown id passes through unchanged (the window read that follows renders what actually exists).
func (*MessageService) RewriteAgentMessage ¶ added in v0.0.72
func (s *MessageService) RewriteAgentMessage(ctx context.Context, agentID, parentID, parentType, msgID, body string) (*model.Message, error)
RewriteAgentMessage replaces the body of an AGENT-authored machine message (a task card marker, a lifecycle notice) in place — backend-only, no access check on purpose: the orchestrator/task service is the sole caller and the author is the shared agent user, not a channel member. Refuses to touch human-authored messages so it can never become an edit-anything primitive.
func (*MessageService) Send ¶
func (s *MessageService) Send(ctx context.Context, userID, parentID, parentType, body, parentMessageID string, attachmentIDs ...string) (*model.Message, error)
Send creates a new message in the given parent (channel or conversation). If parentMessageID is non-empty, the message is a thread reply: the root message's ReplyCount is incremented and a message.edited event is published for the root so the UI updates the count.
Attachments are bound by ID after the message row is persisted so dangling refs are impossible.
Send is the composer's send: once the message lands, the author's draft for that composer (the thread composer for a reply) is cleared, unconditionally and off the request path — sending is the authoritative event for the scope.
func (*MessageService) SendAsAgent ¶ added in v0.0.72
func (s *MessageService) SendAsAgent(ctx context.Context, agentID, invokerID, parentID, parentType, body, parentMessageID string) (*model.Message, error)
SendAsAgent posts a message authored by an agent instance while checking access against the INVOKING human (plan-v2 §3: an agent's permissions are always the invoker's — agents are not channel members and never gain reach their invoker lacks).
func (*MessageService) SendAsAgentRun ¶ added in v0.0.72
func (s *MessageService) SendAsAgentRun(ctx context.Context, agentID, invokerID, parentID, parentType, body, parentMessageID, runID string, attachmentIDs ...string) (*model.Message, error)
SendAsAgentRun is SendAsAgent carrying the producing run's ID, so the message links back to its run drawer ("Show activity").
func (*MessageService) SendNoIndex ¶ added in v0.0.65
func (s *MessageService) SendNoIndex(ctx context.Context, userID, parentID, parentType, body, parentMessageID string, attachmentIDs ...string) (*model.Message, error)
SendNoIndex is Send for machine-posted ephemera (e.g. the /mstmeetings join link): the message behaves normally everywhere except the search index, which never sees it — live indexing and the admin reindex both honor the persisted NoIndex flag.
func (*MessageService) SendReminder ¶ added in v0.0.114
func (s *MessageService) SendReminder(ctx context.Context, in WebhookMessageInput) (*model.Message, error)
SendReminder posts the reminder bot's message: a DM as the bot account, or a channel reply as the shared sentinel under the bot's name. Unlike a webhook (an unauthenticated URL, kept to its own threads) it is the server's own post, so it may reply in any live thread.
func (*MessageService) SendScheduled ¶ added in v0.0.97
func (s *MessageService) SendScheduled(ctx context.Context, userID, parentID, parentType, body, parentMessageID string, attachmentIDs ...string) (*model.Message, error)
SendScheduled posts a message composed earlier — a scheduled message at its time. Everything a send does except the draft clear: the composer was emptied when the message was scheduled, and whatever the author has drafted there since is theirs to keep.
func (*MessageService) SendWebhook ¶ added in v0.0.48
func (s *MessageService) SendWebhook(ctx context.Context, in WebhookMessageInput) (*model.Message, error)
func (*MessageService) SetActivator ¶
func (s *MessageService) SetActivator(a ConversationActivator)
SetActivator wires the conversation activator. Called from the app wiring after both services are constructed to avoid a constructor cycle.
func (*MessageService) SetActivityRecorder ¶ added in v0.0.83
func (s *MessageService) SetActivityRecorder(r MessageActivityRecorder)
SetActivityRecorder wires the Activity tab (see MessageActivityRecorder).
func (*MessageService) SetAgentDispatcher ¶ added in v0.0.72
func (s *MessageService) SetAgentDispatcher(d AgentDispatcher)
SetAgentDispatcher wires the agent run dispatcher. Optional — when nil, agent mentions are inert.
func (*MessageService) SetAppClicker ¶ added in v0.0.116
func (s *MessageService) SetAppClicker(c AppClicker)
SetAppClicker wires the service that sends app buttons' clicks.
func (*MessageService) SetAttachmentManager ¶
func (s *MessageService) SetAttachmentManager(a AttachmentRefManager)
SetAttachmentManager wires the attachment ref manager. Called from the app wiring after both services are constructed to avoid a constructor cycle.
func (*MessageService) SetChannelReader ¶ added in v0.0.92
func (s *MessageService) SetChannelReader(c ChannelReader)
SetChannelReader enables the archived-channel (read-only) check on writes.
func (*MessageService) SetChannelSeqStore ¶ added in v0.0.52
func (s *MessageService) SetChannelSeqStore(c UnreadSeqStore)
SetChannelSeqStore wires the channel message-counter used for server-side unread tracking. Optional — left unset, channel unread isn't persisted.
func (*MessageService) SetConversationSeqStore ¶ added in v0.0.52
func (s *MessageService) SetConversationSeqStore(c UnreadSeqStore)
SetConversationSeqStore wires the conversation message-counter (the same seq-based unread mechanism channels use). Optional — left unset, conversation unread isn't persisted.
func (*MessageService) SetDeactivatedAccounts ¶ added in v0.0.101
func (s *MessageService) SetDeactivatedAccounts(d DeactivatedAccounts)
SetDeactivatedAccounts wires the deactivated-account check.
func (*MessageService) SetDraftClearer ¶ added in v0.0.97
func (s *MessageService) SetDraftClearer(c SentDraftClearer)
SetDraftClearer folds the draft clear into the send: a successful Send clears the author's draft for that composer server-side, so the client makes no separate request.
func (*MessageService) SetIndexer ¶ added in v0.0.13
func (s *MessageService) SetIndexer(i MessageIndexer)
func (*MessageService) SetMachineReaction ¶ added in v0.0.72
func (s *MessageService) SetMachineReaction(ctx context.Context, actorID, watchedFor, parentID, parentType, msgID, state string) error
SetMachineReaction ADDS the actor's machine-state reaction to a message. States are cumulative, not exclusive — a message an agent read keeps 👀 when ⚙️ lands, and both stay when ✅ arrives, so the trail reads as a history: saw it → worked on it → done. Idempotent per (emoji, actor).
An empty state is refused: the "clear every machine emoji" branch this used to carry had no caller outside its own test, and a silent no-op is a worse answer than saying the argument is wrong.
watchedFor is the watcher's creator when a subscription (not a mention) started the run, "" otherwise. It is recorded in the same write as the reaction, so the trail never shows without its attribution.
Backend-only: no access check on purpose — the orchestrator is the sole caller and the agent actor is not a channel member. The human-facing path (ToggleReaction) rejects these emojis instead.
func (*MessageService) SetMarkdownRenderer ¶ added in v0.0.45
func (s *MessageService) SetMarkdownRenderer(m *MarkdownRenderer)
SetMarkdownRenderer wires the server-side markdown→hast renderer. When set, every Message returned by the service has its `Rendered` field populated so the frontend doesn't have to re-parse on each render. Optional — tests that don't care about rendered output leave it nil and the field stays empty (the frontend then falls back to its legacy client-side parser).
func (*MessageService) SetMentionResolver ¶ added in v0.0.97
func (s *MessageService) SetMentionResolver(r MentionResolver)
SetMentionResolver wires mention-pill resolution into every rendered message. Left unset (tests that don't care), pills keep the typed names.
func (*MessageService) SetNoUnfurl ¶ added in v0.0.11
func (s *MessageService) SetNoUnfurl(ctx context.Context, userID, parentID, parentType, msgID string, noUnfurl bool) (*model.Message, error)
SetNoUnfurl toggles the per-message link-preview suppression flag. Only the author may dismiss — the unfurl is content the author effectively chose to show, so they own the dismissal.
func (*MessageService) SetNotifier ¶
func (s *MessageService) SetNotifier(n MessageNotifier)
SetNotifier wires the notification dispatcher. Production must wire it — NotificationsWired fails the boot otherwise; narrow tests leave it nil, and then no alerts are produced.
func (*MessageService) SetNotifySafetyNet ¶ added in v0.0.97
func (s *MessageService) SetNotifySafetyNet(n NotifySafetyNet)
SetNotifySafetyNet wires the durable fan-out check.
func (*MessageService) SetParentIndex ¶ added in v0.0.45
func (s *MessageService) SetParentIndex(p ParentPinFileIndexStore)
SetParentIndex wires the per-parent pinned/file index. Required for ListPinned / ListFiles to return any data — those paths read exclusively from the index now. Production wiring (internal/app) and every test helper (setupMessageService, setupChannelHandlerFull, etc.) wire a real implementation. Pre-rollout data must be backfilled once with `cmd/migrate-parent-index --apply` (see README).
Write paths (Send / Edit / Delete / SetPinned) still guard with `if s.parentIndex != nil` so a misconfiguration logs a warning rather than panicking the request.
func (*MessageService) SetPinned ¶ added in v0.0.2
func (s *MessageService) SetPinned(ctx context.Context, userID, parentID, parentType, msgID string, pinned bool) (*model.Message, error)
SetPinned toggles the pinned state of a message. Any participant in the channel/conversation may pin or unpin — pin authorship is captured on the message itself and serves as the audit trail.
func (*MessageService) SetReminderSync ¶ added in v0.0.85
func (s *MessageService) SetReminderSync(r MessageReminderSync)
SetReminderSync wires reminder cleanup into message deletes and edits.
func (*MessageService) SetRunLogPurger ¶ added in v0.0.72
func (s *MessageService) SetRunLogPurger(p RunLogPurger)
SetRunLogPurger wires run-log cleanup into message deletion. Optional.
func (*MessageService) SetRunSkillResolver ¶ added in v0.0.72
func (s *MessageService) SetRunSkillResolver(f func(ctx context.Context, runID string) []string)
SetRunSkillResolver wires the orchestrator's RunSkillBadges: agent-run posts get the run's used-skill names stamped on the message (nil = none).
func (*MessageService) SetSharePoint ¶ added in v0.0.116
func (s *MessageService) SetSharePoint(sp MessageSharePoint)
SetSharePoint wires SharePoint link sharing. Optional: only when it is configured.
func (*MessageService) SetThreadFollow ¶ added in v0.0.24
func (s *MessageService) SetThreadFollow(ctx context.Context, userID, parentID, parentType, threadRootID string, following bool) error
SetThreadFollow records whether userID follows threadRootID. Following=true adds a thread to /threads without requiring the user to reply. Following=false suppresses implicit participation from authored roots/replies, and takes the thread off /threads at once (its unread alert goes with it). The user's other tabs and devices refresh their lists.
func (*MessageService) SetThreadFollowStore ¶ added in v0.0.24
func (s *MessageService) SetThreadFollowStore(f ThreadFollowStore)
func (*MessageService) SetUserStateStore ¶ added in v0.0.26
func (s *MessageService) SetUserStateStore(userState UserStateStore)
func (*MessageService) ThreadFollowing ¶ added in v0.0.107
func (s *MessageService) ThreadFollowing(ctx context.Context, userID, parentID, parentType, threadRootID string) (bool, error)
ThreadFollowing reports whether userID follows the thread — what the thread panel's Follow button shows. One row read: the user's follow row decides; without one, a DM's threads are followed and a channel's are not.
func (*MessageService) ThreadWindowMessages ¶ added in v0.0.72
func (s *MessageService) ThreadWindowMessages(ctx context.Context, userID, parentID, parentType, threadRootID string, limit int) ([]*model.Message, error)
ThreadWindowMessages returns at most `limit` of a thread's newest messages (root included), for the agent context bundle. Unlike ListThreadMessages it never drains the whole thread — the window is fixed, and a coding-task thread is not.
func (*MessageService) ToggleReaction ¶
func (s *MessageService) ToggleReaction(ctx context.Context, userID, parentID, parentType, msgID, emoji string) (*model.Message, error)
ToggleReaction adds the given emoji from the user to a message, or removes it if the user has already reacted with that emoji. The updated message is persisted and a message.edited event is published so all clients refresh.
func (*MessageService) ToggleReactionAsAgent ¶ added in v0.0.72
func (s *MessageService) ToggleReactionAsAgent(ctx context.Context, agentID, invokerID, parentID, parentType, msgID, emoji string) (*model.Message, error)
ToggleReactionAsAgent toggles a NORMAL (non machine-state) reaction authored by a shared agent, authorized by the INVOKER's access — the same author/accessor split as SendAsAgent. Machine-state emojis stay backend-only (SetMachineReaction).
func (*MessageService) WaitForNotifyFanOut ¶ added in v0.0.97
func (s *MessageService) WaitForNotifyFanOut()
WaitForNotifyFanOut blocks until every in-flight (or queued) notification fan-out finished. Graceful shutdown calls it, bounded, before exiting.
func (*MessageService) Wired ¶ added in v0.0.97
func (s *MessageService) Wired() error
Wired adds the rest of the message service's collaborators to the incident-critical alert pipeline check (NotificationsWired).
type MessageServiceDeps ¶ added in v0.0.64
type MessageServiceDeps struct {
// Required core.
Messages MessageStore
Memberships MembershipStore
Conversations ConversationStore
Publisher Publisher
Broker Broker
// Required in production, optional in tests.
ChannelSeq UnreadSeqStore
ConversationSeq UnreadSeqStore
ThreadFollows ThreadFollowStore
UserState UserStateStore
ParentIndex ParentPinFileIndexStore
Markdown *MarkdownRenderer
Activator ConversationActivator
Channels ChannelReader
// Optional capabilities (nil degrades gracefully). AttachmentManager is
// NOT here: attachments and messages reference each other, so that edge
// is late-bound via SetAttachmentManager after both exist.
Notifier MessageNotifier
Indexer MessageIndexer
Activity MessageActivityRecorder
}
MessageServiceDeps declares the full dependency surface of MessageService in one place, splitting hard requirements from optional capabilities. The production wiring (internal/app) constructs through this so a half-wired service can't escape into the router; tests use NewMessageService with just the core five and opt into extras via the Set* methods.
type MessageSharePoint ¶ added in v0.0.116
type MessageSharePoint interface {
}
MessageSharePoint shares the SharePoint links messages carry and lists the files they shared (SharePointService).
type MessageStore ¶
type MessageStore interface {
CreateMessage(ctx context.Context, msg *model.Message) error
GetMessage(ctx context.Context, parentID, msgID string) (*model.Message, error)
UpdateMessage(ctx context.Context, msg *model.Message) error
// UpdateMessageIfVersion writes msg only over the stored Version
// prevVersion; otherwise store.ErrVersionConflict.
UpdateMessageIfVersion(ctx context.Context, msg *model.Message, prevVersion int) error
DeleteMessage(ctx context.Context, parentID, msgID string) error
ListMessages(ctx context.Context, parentID string, before string, limit int) ([]*model.Message, bool, error)
// ListThreadReplies returns every reply to a thread root via the GSI1
// thread index (one Query, oldest-first) instead of a parent scan.
ListThreadReplies(ctx context.Context, threadRootID string) ([]*model.Message, error)
// ListThreadRepliesNewest is the bounded form: at most `limit` of the
// newest replies, oldest-first. The context bundle keeps a fixed window,
// so it must not read an entire hours-long task thread to slice the tail.
ListThreadRepliesNewest(ctx context.Context, threadRootID string, limit int) ([]*model.Message, error)
// ListMessagesAfter returns messages strictly newer than the given
// cursor, oldest-first within the page but with the same
// newest-first ordering as ListMessages overall.
ListMessagesAfter(ctx context.Context, parentID, after string, limit int) ([]*model.Message, bool, error)
// ListTopLevelMessages and ListTopLevelMessagesAfter page a parent's
// top-level messages (no thread replies) from the sparse top-level index,
// newest first: strictly older than `before` (or the live tail), or the
// ones nearest after `after`. hasMore reports more beyond the page.
ListTopLevelMessages(ctx context.Context, parentID, before string, limit int) ([]*model.Message, bool, error)
ListTopLevelMessagesAfter(ctx context.Context, parentID, after string, limit int) ([]*model.Message, bool, error)
// ListMessagesAround returns a window centered on msgID: up to
// `before` older + the target + up to `after` newer, newest-first.
ListMessagesAround(ctx context.Context, parentID, msgID string, before, after int) ([]*model.Message, bool, bool, error)
// IncrementReplyMetadata atomically bumps replyCount, sets
// lastReplyAt, and merges replyAuthorID into recentReplyAuthorIDs.
// Returns the updated message so callers can republish authoritative
// state. ErrNotFound if the parent doesn't exist.
IncrementReplyMetadata(ctx context.Context, parentID, msgID string, replyTime time.Time, replyAuthorID string) (*model.Message, error)
}
MessageStore defines persistence operations for messages.
type MessageUpdate ¶ added in v0.0.116
type MessageUpdate struct {
ChannelID string `json:"channel_id"`
MessageID string `json:"message_id"`
Text string `json:"text"`
Blocks model.Blocks `json:"blocks"`
Attachments []model.MessageAttachment `json:"attachments"`
IfVersion *int `json:"if_version"`
}
MessageUpdate is messages.update's input: which message, its new content, and optionally the version it must still be at.
type MobilePushScheduler ¶ added in v0.0.64
type MobilePushScheduler interface {
SchedulePush(ctx context.Context, recipientUserID string, n Notification, delay time.Duration) error
}
MobilePushScheduler durably schedules a mobile push for delivery after a delay (0 = as soon as a worker picks it up). The scheduled task must survive a process restart: the 30s ack-fallback window regularly spans a rolling deploy, and the previous in-memory time.Timer design silently dropped every pending fallback push on shutdown — an opted-in alert lost, which the notification contract forbids. asynq persists the task in Redis, so any instance's worker (including a freshly deployed one) delivers it.
type MobilePushSender ¶ added in v0.0.39
type MobilePushSender interface {
Send(ctx context.Context, recipientUserID string, n Notification) error
}
type NameCache ¶ added in v0.0.53
type NameCache interface {
GetName(ctx context.Context, key string) (string, bool)
SetName(ctx context.Context, key, val string)
}
NameCache caches the rarely-changing channel/author display names used in notification titles, so the per-message notify path doesn't do two uncached DynamoDB point reads (author profile + channel metadata) on every notifiable message. A short TTL keeps a renamed channel/user fresh within minutes.
type Notification ¶
type Notification = model.Notification
Notification is the notification.new payload (model.Notification).
type NotificationAckStore ¶ added in v0.0.51
type NotificationAckStore interface {
WasNotificationAcked(ctx context.Context, userID, messageID string) bool
}
NotificationAckStore records and reports desktop-delivery acknowledgements. When a client receives a `notification.new` it acks over its WebSocket; the deferred mobile-push fallback consults WasNotificationAcked to decide whether the desktop actually delivered the alert (ack present) or merely looked online (no ack → the socket was dead/reconnecting → push must fire). Redis-backed in production so an ack on one backend instance is visible to the deferred push running on another.
type NotificationKind ¶
type NotificationKind = model.NotificationKind
NotificationKind and its values live in internal/model with the Notification payload (so tygo mirrors them for the client); the service keeps its historical names as aliases.
type NotificationService ¶
type NotificationService struct {
// contains filtered or unexported fields
}
NotificationService dispatches notifications to interested users while honoring per-user mute preferences. It is intentionally tiny and parallel to the events package: events update *every* connected client; this fans out a separate "notification.new" event only to recipients who actually want an alert.
func NewNotificationService ¶
func NewNotificationService(p Publisher, m MembershipStore, c ConversationStore, ch ChannelStore, u UserStore, msgs MessageStore) *NotificationService
NewNotificationService builds a NotificationService from the required core — the test-oriented constructor; delivery capabilities attach via Set*. messages is used only for thread-reply scoping (looking up the root author + prior participants). Pass nil and the thread path will degrade gracefully to "no recipients beyond explicit @-mentions".
func NewNotificationServiceFromDeps ¶ added in v0.0.64
func NewNotificationServiceFromDeps(d NotificationServiceDeps) *NotificationService
NewNotificationServiceFromDeps constructs a fully-wired NotificationService. The push scheduler still attaches via SetMobilePushScheduler — it is built after the service because the asynq worker needs the service's ack store.
func (*NotificationService) NotificationsWired ¶ added in v0.0.97
func (s *NotificationService) NotificationsWired() error
NotificationsWired reports whether the notifier has everything the safety net needs. Boot refuses to serve without it.
func (*NotificationService) NotifyCheckTaskHandler ¶ added in v0.0.97
NotifyCheckTaskHandler is the worker side of the safety net. It needs the notifier's message store and marker (production wires both; boot refuses otherwise). Outcomes: marker present → done; message gone or deleted → done (nothing left to alert about); otherwise the fan-out runs now, and an audience that still can't be read is returned as an error so asynq retries.
func (*NotificationService) NotifyDirect ¶ added in v0.0.54
func (s *NotificationService) NotifyDirect(ctx context.Context, userID string, notif Notification)
NotifyDirect delivers a pre-built notification to a single user, bypassing all message-audience gating (mute/level/mention). It is for self-targeted alerts like fired reminders: publish the desktop `notification.new` and arm the same ack-gated mobile-push fallback messages use, so the alert reaches the user on desktop OR mobile exactly as a message notification would. No-op for an empty user id.
func (*NotificationService) NotifyForMessage ¶
func (s *NotificationService) NotifyForMessage(ctx context.Context, msg *model.Message, parentType string, threadRoot *model.Message)
NotifyForMessage emits a notification to every channel/conversation member except the author and any user who muted the parent. Errors loading recipients are swallowed (logged via the publisher path) — failure to notify must never block the underlying message send.
For a thread reply, threadRoot is the authoritative root returned by IncrementReplyMetadata (nil when that bump failed or for non-thread messages): it drives the thread.updated fan-out that live-patches each participant's /threads list. Computing that audience HERE — from the same member snapshot and thread reads the notification decision uses — keeps the two audiences from drifting; a previous parallel copy of the participation rules in MessageService silently missed follow-all-threads users and notification-pulled bystanders, and doubled the DynamoDB reads on every reply.
func (*NotificationService) SetAckStore ¶ added in v0.0.51
func (s *NotificationService) SetAckStore(store NotificationAckStore)
SetAckStore wires the desktop-delivery acknowledgement store that gates the deferred mobile-push fallback. Without it, an online recipient's push falls back to the old presence-only behaviour (skipped) — so wiring this is what closes the dead-socket delivery hole.
func (*NotificationService) SetActivityRecorder ¶ added in v0.0.83
func (s *NotificationService) SetActivityRecorder(a ActivityRecorder)
SetActivityRecorder wires the Activity tab. Optional — without it messages still notify but add nothing to anyone's activity stream.
func (*NotificationService) SetAudienceCache ¶ added in v0.0.97
func (s *NotificationService) SetAudienceCache(c *AudienceCache)
SetAudienceCache wires the generation-checked audience cache. Optional — without it every fan-out reads its audience from the stores.
func (*NotificationService) SetMentionResolver ¶ added in v0.0.97
func (s *NotificationService) SetMentionResolver(r MentionResolver)
SetMentionResolver makes alert text (popup, push, Activity row) name each mentioned user and channel by its current name, looked up by ID. Optional — without it mentions read as the poster typed them.
func (*NotificationService) SetMobilePushScheduler ¶ added in v0.0.64
func (s *NotificationService) SetMobilePushScheduler(sched MobilePushScheduler)
SetMobilePushScheduler wires the durable (Redis-backed) push scheduler. The service only ever *schedules* pushes — immediate for offline recipients, deferred by ackFallbackDelay for online ones; the ack check and the provider call happen in the worker at delivery time, so a pending push survives restarts and any instance can deliver it.
func (*NotificationService) SetNameCache ¶ added in v0.0.53
func (s *NotificationService) SetNameCache(c NameCache)
SetNameCache wires the display-name cache. Optional — without it the notifier reads names from the stores directly (the previous behaviour).
func (*NotificationService) SetNotifyMarker ¶ added in v0.0.97
func (s *NotificationService) SetNotifyMarker(m NotifyMarker)
SetNotifyMarker wires the completed-fan-out marker the safety net reads.
func (*NotificationService) SetPresence ¶ added in v0.0.3
func (s *NotificationService) SetPresence(p PresenceLookup)
SetPresence wires a presence lookup so the @here mention can target only currently-online members. Optional — when nil, @here falls through to "no recipients" (better than spamming the whole channel).
func (*NotificationService) SetThreadFollowStore ¶ added in v0.0.24
func (s *NotificationService) SetThreadFollowStore(f ThreadFollowStore)
func (*NotificationService) SetUserStateService ¶ added in v0.0.26
func (s *NotificationService) SetUserStateService(userState *UserStateService)
func (*NotificationService) Wired ¶ added in v0.0.97
func (s *NotificationService) Wired() error
Wired adds the rest of the notifier's collaborators to the safety-net check (NotificationsWired). The ack store gates the deferred mobile push and the presence lookup picks immediate vs deferred delivery, so both are required.
type NotificationServiceDeps ¶ added in v0.0.64
type NotificationServiceDeps struct {
// Required core.
Publisher Publisher
Memberships MembershipStore
Conversations ConversationStore
Channels ChannelStore
Users UserStore
// Messages is used only for thread-reply scoping (root author + prior
// participants). Nil degrades the thread path to "no recipients beyond
// explicit @-mentions".
Messages MessageStore
// Delivery-path capabilities (each nil-tolerant, but production wires
// all of them; see the Set* docs for per-field semantics).
Presence PresenceLookup
ThreadFollows ThreadFollowStore
UserState *UserStateService
AckStore NotificationAckStore
NameCache NameCache
}
NotificationServiceDeps declares the notifier's full dependency surface — the production constructor input. This pipeline is incident-critical (see CLAUDE.md): declaring presence/acks/push here makes it obvious at the wiring site when a delivery-path dependency is missing, instead of a forgotten Set* silently degrading the fallback.
type NotifyMarker ¶ added in v0.0.97
type NotifyMarker interface {
MarkNotified(ctx context.Context, messageID string) error
WasNotified(ctx context.Context, messageID string) (bool, error)
}
NotifyMarker records which messages' fan-outs completed.
type NotifySafetyNet ¶ added in v0.0.97
type NotifySafetyNet interface {
ScheduleNotifyCheck(ctx context.Context, msg *model.Message, parentType string) error
}
NotifySafetyNet durably schedules, at send time, a later check that the message's fan-out completed (see NotificationService.NotifyCheckTaskHandler): a deploy or crash between the commit and the in-process fan-out would otherwise lose the message's popup, Activity row and push.
type OIDCProvider ¶
type OIDCProvider interface {
AuthURL(state, nonce string) string
Exchange(ctx context.Context, code, nonce string) (*OIDCUserInfo, error)
}
OIDCProvider handles OpenID Connect authentication flows.
type OIDCUserInfo ¶
type OIDCUserInfo struct {
Email string
Name string
Picture string
// ObjectID is the Azure AD directory object id (`oid` claim); empty for
// non-AAD identity providers.
ObjectID string
// Issuer + Subject are the verified ID token's `iss` and `sub`: the
// identity the account is bound to (the email claim is mutable).
Issuer string
Subject string
// EmailVerified is the `email_verified` claim; nil when the provider
// omits it (Entra ID does), which is accepted. An explicit false is not.
EmailVerified *bool
// Token is the provider's token response; with SharePoint sharing on it
// carries the user's delegated Microsoft Graph tokens.
Token *oauth2.Token
}
OIDCUserInfo holds user profile data returned by the identity provider.
type OfficeUpload ¶ added in v0.0.116
type OfficeUpload struct {
Name string `json:"name"`
WebURL string `json:"webURL"`
Size int64 `json:"size"`
}
OfficeUpload is an Office file put into its uploader's OneDrive.
type OneSignalConfig ¶ added in v0.0.39
type OneSignalConfig struct {
AppID string
APIKey string
PublicURL string
APIURL string
HTTPClient *http.Client
// MaxRetries / RetryInterval override the transient-failure retry policy.
// Zero values fall back to the defaults; tests set RetryInterval tiny so the
// retry path runs instantly.
MaxRetries int
RetryInterval time.Duration
// BadgeCount answers a recipient's Activity unread count, the number the
// phone app's icon shows (iOS sets it from each push). Nil sends no
// badge.
BadgeCount func(ctx context.Context, userID string) (int, error)
}
type OneSignalPushSender ¶ added in v0.0.39
type OneSignalPushSender struct {
// contains filtered or unexported fields
}
func NewOneSignalPushSender ¶ added in v0.0.39
func NewOneSignalPushSender(cfg OneSignalConfig) (*OneSignalPushSender, error)
func (*OneSignalPushSender) Send ¶ added in v0.0.39
func (s *OneSignalPushSender) Send(ctx context.Context, recipientUserID string, n Notification) error
type ParentMemberLister ¶ added in v0.0.83
type ParentMemberLister interface {
ParentMemberIDs(ctx context.Context, parentID, parentType string) ([]string, error)
}
ParentMemberLister lists everyone who can read a channel or conversation — the users whose streams can hold items about its messages.
type ParentPinFileIndexStore ¶ added in v0.0.45
type ParentPinFileIndexStore interface {
SetPinIndex(ctx context.Context, parentID, msgID, pinnedBy string, pinnedAt time.Time) error
DeletePinIndex(ctx context.Context, parentID, msgID string) error
ListPinIndex(ctx context.Context, parentID string) ([]PinIndexEntry, error)
SetFileIndex(ctx context.Context, parentID, attachmentID, msgID, authorID string, createdAt time.Time) error
DeleteFileIndex(ctx context.Context, parentID, attachmentID string) error
ListFileIndex(ctx context.Context, parentID string) ([]FileIndexEntry, error)
// SetFileIndexName records the attachment's name on its existing row.
SetFileIndexName(ctx context.Context, parentID, attachmentID, filename string) error
}
ParentPinFileIndexStore is the per-parent index used by ListPinned and ListFiles. Without it, both code paths fall back to scanning recent messages — accurate up to 1000 items but unbounded in latency. With it, both queries become O(pinned) / O(files-shared) instead of O(messages).
type ParsedMentions ¶ added in v0.0.3
type ParsedMentions struct {
Users []MentionUser
All bool // @all → notify every channel/conversation member
Here bool // @here → notify online members only
}
ParsedMentions is the result of scanning a message body for @-mentions. Group flags are recorded as booleans rather than fake user IDs so the notification dispatcher can branch on them without a stringly-typed switch on a "userID" that isn't actually one.
func ParseMentions ¶ added in v0.0.3
func ParseMentions(body string) ParsedMentions
ParseMentions extracts all @-mentions from a message body.
Duplicate user mentions (the same userID mentioned twice in one message) are de-duplicated — notifying twice would be noise. The DisplayName from the first occurrence wins; subsequent occurrences are dropped.
func (ParsedMentions) Empty ¶ added in v0.0.3
func (m ParsedMentions) Empty() bool
Empty reports whether the message contained no @-mentions of any kind.
type PasswordResetStore ¶ added in v0.0.66
type PasswordResetStore interface {
MintPasswordResetTicket(ctx context.Context, tokenHash, userID string, ttl time.Duration) error
ConsumePasswordResetTicket(ctx context.Context, tokenHash string) (string, error)
}
PasswordResetStore persists single-use reset tickets keyed by the token's hash. Backed by Redis (cache.RedisCache) in production.
type PasswordResetTicket ¶ added in v0.0.66
type PasswordResetTicket struct {
URL string `json:"resetURL"`
ExpiresAt time.Time `json:"expiresAt"`
EmailSent bool `json:"emailSent"`
}
PasswordResetTicket is a freshly minted reset link. The URL is returned to an admin caller so the reset still works when mail is unconfigured or the relay is down — EmailSent tells the UI which of those two stories to tell.
type PinIndexEntry ¶ added in v0.0.45
PinIndexEntry mirrors store.PinIndexRow at the service-interface boundary so the service layer doesn't depend on the store package.
type PresenceBatchLookup ¶ added in v0.0.59
PresenceBatchLookup is the optional batched sibling of PresenceLookup (PresenceService implements it): one Redis round trip for a whole recipient set instead of a GET per recipient. Asserted where fan-outs need presence for many users; plain single-user lookups keep working via the fallback.
type PresenceLookup ¶ added in v0.0.3
PresenceLookup is the slice of PresenceService NotificationService cares about. Defined as an interface so the dependency is explicit and tests can stub it without instantiating the real presence tracker.
type PresenceService ¶
type PresenceService struct {
// contains filtered or unexported fields
}
PresenceService tracks online users and broadcasts presence changes to all connected clients via the global presence pub/sub channel. Connection counts allow a single user to have multiple sessions without flapping the online flag on each tab close.
func NewPresenceService ¶
func NewPresenceService(store PresenceStore, publisher Publisher) *PresenceService
NewPresenceService creates a presence service. The optional store shares presence counts across backend processes; the in-memory map remains the local fallback and prevents duplicate transitions within one process.
func (*PresenceService) IsOnline ¶
func (s *PresenceService) IsOnline(userID string) bool
IsOnline reports whether a user has any active connection.
func (*PresenceService) OnConnect ¶
func (s *PresenceService) OnConnect(ctx context.Context, userID, connID string, topics ...string) bool
OnConnect records a new connection (identified by its per-socket connID) for a user. Returns true if this made the user online (no other live connection anywhere in the fleet), so callers can publish a presence event exactly once per state transition. Every connection registers its own distributed entry — the store's live-member count is the transition authority; the local map only dedupes same-instance lookups. When the caller already knows the user's audience topics (the WS handler just built them for its broker subscription) it passes them in so the transition does not re-read the user's memberships through the audience resolver.
func (*PresenceService) OnDisconnect ¶
func (s *PresenceService) OnDisconnect(ctx context.Context, userID, connID string, topics ...string) bool
OnDisconnect removes a connection. Returns true if this transitioned the user from online to offline (no live connections remain fleet-wide), so we publish exactly once. Topics work as in OnConnect; disconnect callers usually omit them so the audience resolves fresh (memberships may have changed over the connection's lifetime).
func (*PresenceService) OnlineMany ¶ added in v0.0.59
func (s *PresenceService) OnlineMany(userIDs []string) map[string]bool
OnlineMany reports online status for many users at once: the local connection map answers for sessions on THIS instance, everyone else resolves through one batched Redis read instead of a GET per user — the notification fan-out calls this once per message rather than once per recipient. A store failure leaves the unresolved users offline, which is the fail-safe direction for the mobile-push fallback: an offline verdict pushes immediately, and a duplicate alert beats a silently lost one.
func (*PresenceService) OnlineUserIDs ¶
func (s *PresenceService) OnlineUserIDs() []string
OnlineUserIDs returns all currently online user IDs (sorted not guaranteed).
func (*PresenceService) Refresh ¶ added in v0.0.25
func (s *PresenceService) Refresh(ctx context.Context, userID, connID string)
Refresh re-scores the distributed presence entry for a locally connected user's connection. The plain ZADD underneath doubles as the self-heal: an entry lost to a Redis blip is recreated within one keep-alive interval.
func (*PresenceService) SetPresenceAudienceResolver ¶ added in v0.0.50
func (s *PresenceService) SetPresenceAudienceResolver(fn func(ctx context.Context, userID string) []string)
SetPresenceAudienceResolver wires the function that maps a user to the pub/sub topics their presence change should reach (shared channels + DM conversations). Without it, presence falls back to the single global broadcast topic.
func (*PresenceService) Wired ¶ added in v0.0.97
func (s *PresenceService) Wired() error
type PresenceStore ¶ added in v0.0.25
type PresenceStore interface {
IncrementPresence(ctx context.Context, userID, connID string) (bool, error)
DecrementPresence(ctx context.Context, userID, connID string) (bool, error)
RefreshPresence(ctx context.Context, userID, connID string) error
IsPresenceOnline(ctx context.Context, userID string) (bool, error)
OnlinePresenceUserIDs(ctx context.Context) ([]string, error)
}
PresenceStore is the distributed (Redis-backed) presence view. Connections are tracked INDIVIDUALLY by connID (a per-socket ULID): each one carries its own expiry, so a crashed instance's connections age out on their own, a disconnect of an unknown/lapsed connID is a no-op, and the keep-alive refresh recreates a blip-lost entry — the failure modes of the old per-instance counter (leaked increments, negative-count offline flaps, unhealable lost markers) are structurally gone.
type Publisher ¶
Publisher is an alias for events.Publisher; defined in the events package so that publish helpers can take a single canonical interface.
type RateLimitedError ¶ added in v0.0.116
RateLimitedError refuses an app's call over its budget, saying when the next one would be admitted (the Retry-After header).
func (*RateLimitedError) Error ¶ added in v0.0.116
func (e *RateLimitedError) Error() string
func (*RateLimitedError) Unwrap ¶ added in v0.0.116
func (e *RateLimitedError) Unwrap() error
type RawValue ¶ added in v0.0.116
type RawValue []string
RawValue is what a browser sends for one element: a string, or a list of strings for the elements that hold several (multi-selects, checkboxes). It is only ever a claim — readValue decides what it is worth.
func (*RawValue) UnmarshalJSON ¶ added in v0.0.116
UnmarshalJSON takes a string, a list of strings, or null.
type RedisAudienceGenerations ¶ added in v0.0.97
type RedisAudienceGenerations struct {
// contains filtered or unexported fields
}
RedisAudienceGenerations is the production AudienceGenerations. Keys are seeded with a random value and bumped by a random step, so a key lost to a Redis restart or eviction never comes back with a value an old cache entry still carries.
func NewRedisAudienceGenerations ¶ added in v0.0.97
func NewRedisAudienceGenerations(rdb redis.UniversalClient) *RedisAudienceGenerations
NewRedisAudienceGenerations wraps a Redis client built through redisx.Options like every other client in the app.
func (*RedisAudienceGenerations) Bump ¶ added in v0.0.97
func (g *RedisAudienceGenerations) Bump(ctx context.Context, keys ...string) error
func (*RedisAudienceGenerations) Generations ¶ added in v0.0.97
type RedisNotifyMarker ¶ added in v0.0.97
type RedisNotifyMarker struct {
// contains filtered or unexported fields
}
RedisNotifyMarker is the production NotifyMarker: one short-lived key per message, visible to every instance.
func NewRedisNotifyMarker ¶ added in v0.0.97
func NewRedisNotifyMarker(rdb redis.UniversalClient) *RedisNotifyMarker
NewRedisNotifyMarker wraps a Redis client built through redisx.Options.
func (*RedisNotifyMarker) MarkNotified ¶ added in v0.0.97
func (m *RedisNotifyMarker) MarkNotified(ctx context.Context, messageID string) error
func (*RedisNotifyMarker) WasNotified ¶ added in v0.0.97
type ReminderAccessChecker ¶ added in v0.0.54
type ReminderAccessChecker interface {
CheckAccess(ctx context.Context, userID, parentID, parentType string) error
}
ReminderAccessChecker gates scheduling to parents the user can actually see.
type ReminderBotProvisioner ¶ added in v0.0.114
type ReminderBotProvisioner interface {
EnsureBotUser(ctx context.Context, botID, displayName string) (*model.User, error)
}
ReminderBotProvisioner creates the reminder bot's account on first use.
type ReminderCanceller ¶ added in v0.0.85
ReminderCanceller stops a deactivated user's queued reminders. Implemented by ReminderService.
type ReminderDMOpener ¶ added in v0.0.114
type ReminderDMOpener interface {
GetOrCreateDM(ctx context.Context, userA, userB string) (*model.Conversation, error)
}
ReminderDMOpener opens the bot's DM with a reminder's owner.
type ReminderInput ¶ added in v0.0.54
type ReminderInput struct {
MessageID string `json:"messageID"`
ParentID string `json:"parentID"`
ParentType string `json:"parentType"`
ChannelSlug string `json:"channelSlug"`
RemindAt time.Time `json:"remindAt"`
// UserIDs are people to tag besides the owner when it comes due.
UserIDs []string `json:"userIDs"`
// Everyone reminds every member of the chat instead (UserIDs is then
// ignored), all but ExcludedUserIDs.
Everyone bool `json:"everyone"`
ExcludedUserIDs []string `json:"excludedUserIDs"`
// Note is optional context, shown with the reminder.
Note string `json:"note"`
}
ReminderInput is the client-supplied request to schedule a reminder.
type ReminderMessageStore ¶ added in v0.0.54
type ReminderMessageStore interface {
GetMessage(ctx context.Context, parentID, msgID string) (*model.Message, error)
}
ReminderMessageStore loads the source message so a reminder can carry a preview and be validated against an existing message.
type ReminderOwnerLookup ¶ added in v0.0.85
type ReminderOwnerLookup interface {
GetUsersByIDs(ctx context.Context, ids []string) ([]*model.User, error)
}
ReminderOwnerLookup resolves reminder owners, so a deactivated owner's reminders are dropped instead of fired. Implemented by the user store.
type ReminderPoster ¶ added in v0.0.114
type ReminderPoster interface {
SendReminder(ctx context.Context, in WebhookMessageInput) (*model.Message, error)
}
ReminderPoster posts the reminder bot's messages (MessageService).
type ReminderService ¶ added in v0.0.54
type ReminderService struct {
// contains filtered or unexported fields
}
ReminderService schedules per-message reminders and fires them at their due time into the owner's activity stream + a desktop/mobile alert.
func NewReminderService ¶ added in v0.0.54
func NewReminderService(s ReminderStore, messages ReminderMessageStore, access ReminderAccessChecker) *ReminderService
NewReminderService builds a ReminderService. activity and notifier are wired after construction (SetDelivery) to avoid a constructor cycle with the activity/notification services.
func (*ReminderService) Cancel ¶ added in v0.0.54
func (s *ReminderService) Cancel(ctx context.Context, userID, id string) error
Cancel removes a pending reminder. Returns store.ErrNotFound when there is no such pending reminder for the user.
func (*ReminderService) CancelAllForUser ¶ added in v0.0.85
func (s *ReminderService) CancelAllForUser(ctx context.Context, userID string) error
CancelAllForUser stops every reminder a user has queued — on deactivation, so nothing is left to come due for an account that can't sign in.
func (*ReminderService) ListPending ¶ added in v0.0.54
func (s *ReminderService) ListPending(ctx context.Context, userID string) ([]*model.Reminder, error)
ListPending returns the user's not-yet-fired reminders, minus any whose chat the user can no longer open. Leaving a channel cancels its reminders, but that cleanup is best-effort (see ParentLeft), so the list applies the same access rule the firing path does rather than trust it. A lookup failure keeps the reminder, like fire: never hide an alert over a blip.
func (*ReminderService) MessageEdited ¶ added in v0.0.85
MessageEdited gives every pending reminder about an edited message its new preview — text edited out must not live on in a reminder. The message is read again on the hook's own goroutine, so two quick edits whose hooks run out of order both write the latest text rather than the last hook winning. A message that is gone by then is left to the delete hook.
func (*ReminderService) MessagesDeleted ¶ added in v0.0.85
func (s *ReminderService) MessagesDeleted(ctx context.Context, parentID, _ string, messageIDs []string)
MessagesDeleted cancels every pending reminder about deleted messages, whoever set it.
func (*ReminderService) ParentLeft ¶ added in v0.0.85
func (s *ReminderService) ParentLeft(ctx context.Context, userIDs []string, parentID string)
ParentLeft cancels the pending reminders of users who can no longer read a channel or conversation (they left, were removed, or it was archived). One goroutine works through the users in turn, so archiving a large channel doesn't start one per member.
func (*ReminderService) ProcessDue ¶ added in v0.0.54
func (s *ReminderService) ProcessDue(ctx context.Context) (int, error)
ProcessDue claims and fires every reminder due at or before now. Returns the number claimed (a reminder its owner can no longer open, or whose owner was deactivated, is claimed but not delivered). Safe to call concurrently across instances — claiming is atomic.
Every owner whose reminder left the queue is told their pending list changed, whether it fired or was dropped — an open Activity panel would otherwise keep listing it as scheduled.
func (*ReminderService) Schedule ¶ added in v0.0.54
func (s *ReminderService) Schedule(ctx context.Context, userID string, in ReminderInput) (*model.Reminder, error)
Schedule validates and persists a reminder for userID.
func (*ReminderService) SetBot ¶ added in v0.0.114
func (s *ReminderService) SetBot(poster ReminderPoster, bots ReminderBotProvisioner, dms ReminderDMOpener, baseURL string)
SetBot wires the reminder bot: a reminder comes due as the bot's reply to the message tagging its people, or as the bot's DM to its owner. baseURL makes the DM's link to the message absolute, so it unfurls as a preview.
func (*ReminderService) SetDelivery ¶ added in v0.0.54
func (s *ReminderService) SetDelivery(activity ActivityAdder, notifier DirectNotifier)
SetDelivery wires the fired-reminder delivery channels.
func (*ReminderService) SetMentionResolver ¶ added in v0.0.97
func (s *ReminderService) SetMentionResolver(r MentionResolver)
SetMentionResolver names mentioned users and channels in reminder previews (the Activity row and the alert/push body) by their current names. Optional — without it mentions read as typed.
func (*ReminderService) SetOwnerLookup ¶ added in v0.0.85
func (s *ReminderService) SetOwnerLookup(o ReminderOwnerLookup)
SetOwnerLookup wires the owner check that drops a deactivated user's reminders when they come due — no alert, no mobile push job.
func (*ReminderService) SetPublisher ¶ added in v0.0.85
func (s *ReminderService) SetPublisher(p Publisher)
SetPublisher wires the reminders.changed event, so every tab and device keeps its pending list current.
func (*ReminderService) Update ¶ added in v0.0.114
func (s *ReminderService) Update(ctx context.Context, userID, id string, in ReminderUpdate) (*model.Reminder, error)
Update changes a pending reminder's time, people and note. Returns store.ErrNotFound when the user has no such pending reminder (it fired, was cancelled, or isn't theirs).
func (*ReminderService) Wired ¶ added in v0.0.97
func (s *ReminderService) Wired() error
type ReminderStore ¶ added in v0.0.54
type ReminderStore interface {
ScheduleReminder(ctx context.Context, r *model.Reminder) error
CancelReminder(ctx context.Context, userID, id string) (bool, error)
GetPendingReminder(ctx context.Context, userID, id string) (*model.Reminder, error)
RescheduleReminder(ctx context.Context, r *model.Reminder) error
ListPendingReminders(ctx context.Context, userID string) ([]*model.Reminder, error)
ClaimDueReminders(ctx context.Context, limit int) ([]*model.Reminder, error)
// CancelRemindersForParent returns how many it cancelled;
// CancelRemindersForMessages and UpdateReminderPreview return the owners
// whose reminders they touched.
CancelRemindersForParent(ctx context.Context, userID, parentID string) (int, error)
CancelRemindersForMessages(ctx context.Context, messageIDs []string) ([]string, error)
UpdateReminderPreview(ctx context.Context, messageID, preview string) ([]string, error)
// CancelAllRemindersForUser drops every reminder a user has queued, due or
// not, returning how many there were.
CancelAllRemindersForUser(ctx context.Context, userID string) (int, error)
}
ReminderStore is the persistence the reminder service needs.
type ReminderUpdate ¶ added in v0.0.114
type ReminderUpdate struct {
RemindAt time.Time `json:"remindAt"`
UserIDs []string `json:"userIDs"`
Everyone bool `json:"everyone"`
ExcludedUserIDs []string `json:"excludedUserIDs"`
Note string `json:"note"`
}
ReminderUpdate is an edit of a pending reminder: its new time, people and note.
type RunLogPurger ¶ added in v0.0.72
RunLogPurger deletes the agent-run activity logs tied to a message when it is deleted (implemented by the Orchestrator). Optional seam (SetRunLogPurger) — nil means deleting a chat leaves its run logs in place.
type RunnerRevoker ¶ added in v0.0.89
RunnerRevoker disconnects every ex-runner a user has paired. Account deactivation and password reset call it next to wiping refresh tokens: a runner is a machine credential of the same account. Implemented by the agents package's RunnerTokenService.
type ScheduledMessageInput ¶ added in v0.0.81
type ScheduledMessageInput struct {
ParentID string `json:"parentID"`
ParentType string `json:"parentType"`
ParentMessageID string `json:"parentMessageID"`
Body string `json:"body"`
AttachmentIDs []string `json:"attachmentIDs"`
SendAt time.Time `json:"sendAt"`
}
ScheduledMessageInput is a message to schedule.
type ScheduledMessageSender ¶ added in v0.0.81
type ScheduledMessageSender interface {
SendScheduled(ctx context.Context, userID, parentID, parentType, body, parentMessageID string, attachmentIDs ...string) (*model.Message, error)
// CheckWriteAccess: the author may post there now (member, and the
// channel is not archived).
CheckWriteAccess(ctx context.Context, userID, parentID, parentType string) error
}
ScheduledMessageSender posts a scheduled message as its author through the normal send path (access, validation, notifications) — without touching the composer's draft (MessageService.SendScheduled).
type ScheduledMessageService ¶ added in v0.0.81
type ScheduledMessageService struct {
// contains filtered or unexported fields
}
ScheduledMessageService lets a user compose a message now and have it posted at a chosen time.
func NewScheduledMessageService ¶ added in v0.0.81
func NewScheduledMessageService(st store.ScheduledMessageStore, sender ScheduledMessageSender, attachments DraftAttachmentReleaser, publisher Publisher) *ScheduledMessageService
NewScheduledMessageService builds a ScheduledMessageService. attachments and publisher may be nil.
func (*ScheduledMessageService) Delete ¶ added in v0.0.81
func (s *ScheduledMessageService) Delete(ctx context.Context, userID, id string) error
Delete drops a scheduled message and frees its files.
func (*ScheduledMessageService) List ¶ added in v0.0.81
func (s *ScheduledMessageService) List(ctx context.Context, userID string) ([]*model.ScheduledMessage, error)
List returns the user's scheduled messages, soonest first.
func (*ScheduledMessageService) ProcessDue ¶ added in v0.0.81
func (s *ScheduledMessageService) ProcessDue(ctx context.Context) (int, error)
ProcessDue sends every message whose time has come. Safe across instances: each message is claimed by exactly one of them. Returns how many were sent.
func (*ScheduledMessageService) Schedule ¶ added in v0.0.81
func (s *ScheduledMessageService) Schedule(ctx context.Context, userID string, in ScheduledMessageInput) (*model.ScheduledMessage, error)
Schedule validates and stores a message to be sent at in.SendAt.
func (*ScheduledMessageService) SendNow ¶ added in v0.0.81
func (s *ScheduledMessageService) SendNow(ctx context.Context, userID, id string) (*model.Message, error)
SendNow posts a scheduled message immediately — also how a failed one is retried.
func (*ScheduledMessageService) SetDraftClearer ¶ added in v0.0.97
func (s *ScheduledMessageService) SetDraftClearer(c SentDraftClearer)
SetDraftClearer folds the draft clear into scheduling: a scheduled message empties its composer's draft exactly like a send. Optional — nil leaves drafts to the client.
func (*ScheduledMessageService) Update ¶ added in v0.0.81
func (s *ScheduledMessageService) Update(ctx context.Context, userID, id string, upd ScheduledMessageUpdate) (*model.ScheduledMessage, error)
Update edits a scheduled message's text and/or time. Giving a failed message a new time schedules it again.
func (*ScheduledMessageService) Wired ¶ added in v0.0.97
func (s *ScheduledMessageService) Wired() error
type ScheduledMessageUpdate ¶ added in v0.0.81
ScheduledMessageUpdate edits a scheduled message's text and/or time.
type SentDraftClearer ¶ added in v0.0.97
type SentDraftClearer interface {
DeleteForScope(ctx context.Context, userID, parentID, parentType, parentMessageID string) error
}
SentDraftClearer removes a composer scope's draft once its content has been sent — DraftService.DeleteForScope. The clear presents no generation: sending is the authoritative user event for the scope (see the gen-token CAS in DraftService), so it always wins.
type SettingsService ¶ added in v0.0.2
type SettingsService struct {
// contains filtered or unexported fields
}
SettingsService exposes workspace-wide configuration. Reads are hot — every attachment upload looks up the limits — so the service caches the effective settings in memory. Writes invalidate the cache.
func NewSettingsService ¶ added in v0.0.2
func NewSettingsService(s SettingsStore) *SettingsService
NewSettingsService builds a SettingsService.
func (*SettingsService) AllowsExtension ¶ added in v0.0.2
func (s *SettingsService) AllowsExtension(ctx context.Context, filename string) bool
AllowsExtension reports whether the given filename's extension is permitted by the current settings. The check is case-insensitive.
func (*SettingsService) AllowsSize ¶ added in v0.0.2
func (s *SettingsService) AllowsSize(ctx context.Context, size int64) bool
AllowsSize reports whether `size` is at or below the configured ceiling.
func (*SettingsService) Effective ¶ added in v0.0.2
func (s *SettingsService) Effective(ctx context.Context) *model.WorkspaceSettings
Effective returns the current settings with any zero-valued fields filled from defaults. Always safe to call before the first PUT — a fresh workspace gets the built-in defaults.
func (*SettingsService) SetPublisher ¶ added in v0.0.89
func (s *SettingsService) SetPublisher(p Publisher)
SetPublisher makes Update tell every client the settings changed, so what they gate (the Runners tab) appears or goes away without a reload. Optional: nil publishes nothing.
func (*SettingsService) Update ¶ added in v0.0.2
func (s *SettingsService) Update(ctx context.Context, ws *model.WorkspaceSettings) (*model.WorkspaceSettings, error)
Update writes new settings and refreshes the cache. Empty inputs reset to defaults (the Effective() reader fills them back in).
func (*SettingsService) Wired ¶ added in v0.0.97
func (s *SettingsService) Wired() error
type SettingsStore ¶ added in v0.0.2
type SettingsStore interface {
GetSettings(ctx context.Context) (*model.WorkspaceSettings, error)
PutSettings(ctx context.Context, s *model.WorkspaceSettings) error
}
SettingsStore is the persistence interface SettingsService depends on.
type SharePointAccess ¶ added in v0.0.116
type SharePointAccess interface {
}
SharePointAccess checks a viewer may read a parent (MessageService).
type SharePointChannels ¶ added in v0.0.116
type SharePointChannels interface {
}
SharePointChannels reads the channel an Office file is uploaded in.
type SharePointConversations ¶ added in v0.0.116
type SharePointConversations interface {
}
SharePointConversations reads a conversation's participants.
type SharePointDeps ¶ added in v0.0.116
type SharePointDeps struct {
// "*.example.com" matches every subdomain of example.com.
Hosts []string
}
SharePointDeps are the service's collaborators.
type SharePointFileEntry ¶ added in v0.0.116
type SharePointFileEntry struct {
}
SharePointFileEntry is a file shared in a parent, for the Files panel.
type SharePointGraph ¶ added in v0.0.116
type SharePointGraph interface {
}
SharePointGraph is the delegated Microsoft Graph surface the jobs use.
type SharePointLocker ¶ added in v0.0.116
type SharePointLocker interface {
}
SharePointLocker serializes the jobs of one parent across instances.
type SharePointMembers ¶ added in v0.0.116
type SharePointMembers interface {
}
SharePointMembers lists a channel's members.
type SharePointMessages ¶ added in v0.0.116
type SharePointMessages interface {
}
SharePointMessages reads the messages that carry links.
type SharePointQueue ¶ added in v0.0.116
type SharePointQueue interface {
}
SharePointQueue durably enqueues SharePoint jobs.
type SharePointRecords ¶ added in v0.0.116
type SharePointRecords interface {
}
SharePointRecords persists links and shared files.
type SharePointService ¶ added in v0.0.116
type SharePointService struct {
// contains filtered or unexported fields
}
SharePointService shares posted SharePoint links with their parent's members and keeps that access in step with the membership.
func NewSharePointService ¶ added in v0.0.116
func NewSharePointService(d SharePointDeps) *SharePointService
func (*SharePointService) Files ¶ added in v0.0.116
func (s *SharePointService) Files(ctx context.Context, parentID string) ([]SharePointFileEntry, error)
Files lists the SharePoint files shared in a parent.
func (*SharePointService) Hosts ¶ added in v0.0.116
func (s *SharePointService) Hosts() []string
Hosts are the SharePoint host names whose links are shared.
func (*SharePointService) Link ¶ added in v0.0.116
func (s *SharePointService) Link(ctx context.Context, viewerID, parentID, parentType, rawURL string) (*model.SharePointLink, error)
Link returns a posted link as viewerID may see it, or nil when the link was never shared (it predates sharing, or was posted in ~general).
func (*SharePointService) MemberJoined ¶ added in v0.0.116
func (s *SharePointService) MemberJoined(ctx context.Context, channelID, userID string)
MemberJoined queues giving a new channel member access to its files.
func (*SharePointService) MessageEdited ¶ added in v0.0.116
func (s *SharePointService) MessageEdited(ctx context.Context, before, after *model.Message, parentType string)
MessageEdited queues bringing an edited message's links in line: links it gained are shared, links it lost are dropped.
func (*SharePointService) MessageSent ¶ added in v0.0.116
MessageSent queues the sharing of a new message's SharePoint links.
func (*SharePointService) MessagesDeleted ¶ added in v0.0.116
func (s *SharePointService) MessagesDeleted(ctx context.Context, parentID, parentType string, ids []string)
MessagesDeleted queues dropping the links the deleted messages carried.
func (*SharePointService) ParentLeft ¶ added in v0.0.116
func (s *SharePointService) ParentLeft(ctx context.Context, userIDs []string, parentID string)
ParentLeft queues taking back the access the app gave members who left a channel or were removed from it.
func (*SharePointService) Preview ¶ added in v0.0.116
func (s *SharePointService) Preview(ctx context.Context, viewerID, parentID, parentType, fileID string) (string, error)
Preview returns a short-lived address that shows a shared file as it is (Office for the web's viewer), for the viewer's lightbox. It is fetched with the viewer's own Microsoft token and carries their access, so it shows only what they may open themselves. ErrForbidden when ex holds no working sign-in of theirs; ErrNotFound when the file isn't theirs to see or has no preview.
func (*SharePointService) RetryLink ¶ added in v0.0.116
func (s *SharePointService) RetryLink(ctx context.Context, userID, parentID, parentType, rawURL string) error
RetryLink queues sharing a link that failed again, as the person who posted it (after they signed in again, say).
func (*SharePointService) SaveDelegatedToken ¶ added in v0.0.116
func (s *SharePointService) SaveDelegatedToken(ctx context.Context, userID string, tok *oauth2.Token) error
SaveDelegatedToken keeps an SSO login's Microsoft token, then queues finishing what the user's token couldn't do before: access it couldn't take back, members it couldn't share with.
func (*SharePointService) TaskHandler ¶ added in v0.0.116
TaskHandler runs SharePoint jobs, one parent at a time.
func (*SharePointService) UploadOfficeFile ¶ added in v0.0.116
func (s *SharePointService) UploadOfficeFile(ctx context.Context, userID, parentID, parentType, name string, body io.Reader, size int64) (*OfficeUpload, error)
UploadOfficeFile puts an Office file, posted by userID in a channel or a conversation they belong to, into their own OneDrive and returns its link. body holds exactly size bytes.
type SharePointTask ¶ added in v0.0.116
type SharePointTask struct {
}
SharePointTask is the job payload. Jobs carry coordinates, not state: the handler reads messages and links as they are when it runs, so jobs for the same parent can run in any order.
type SharePointTokens ¶ added in v0.0.116
type SharePointTokens interface {
DelegatedTokenSaver
}
SharePointTokens keeps and hands out each user's Microsoft token (DelegatedTokens).
type SharePointUploadLimits ¶ added in v0.0.116
type SharePointUploadLimits interface {
}
SharePointUploadLimits are the workspace's upload rules (SettingsService), which an Office file put in OneDrive keeps to like any attachment.
type SharePointUsers ¶ added in v0.0.116
type SharePointUsers interface {
}
SharePointUsers reads the members' accounts.
type SidebarMove ¶ added in v0.0.59
type SidebarMove struct {
ItemType string // store.SidebarItemChannel | store.SidebarItemConversation
ItemID string
Section string // SidebarSectionFavorites | SidebarSectionCategory | SidebarSectionChannels
// CategoryID qualifies Section == SidebarSectionCategory.
CategoryID string
// AfterType/AfterID anchor the drop: the item the moved row lands
// directly after, in the section's canonical order. Empty = first.
AfterType string
AfterID string
}
SidebarMove is the EVENT a client reports: "I dropped item X into section S right after item A" (empty anchor = at the top). The server decides what that means for stored positions — clients never compute or send position numbers.
type SidebarOrderStore ¶ added in v0.0.59
type SidebarOrderStore interface {
ApplyOrder(ctx context.Context, userID string, updates []store.SidebarRowUpdate) error
}
SidebarOrderStore applies server-computed ordering writes.
type SidebarService ¶ added in v0.0.59
type SidebarService struct {
// contains filtered or unexported fields
}
SidebarService owns sidebar ordering: it resolves client move events into canonical positions and persists them atomically.
func NewSidebarService ¶ added in v0.0.59
func NewSidebarService(memberships MembershipStore, conversations ConversationStore, categories CategoryStore, order SidebarOrderStore, publisher Publisher) *SidebarService
NewSidebarService creates a SidebarService.
func (*SidebarService) Move ¶ added in v0.0.59
func (s *SidebarService) Move(ctx context.Context, userID string, mv SidebarMove) ([]store.SidebarRowUpdate, error)
Move applies a client's drop event. It loads the target section in its canonical order, inserts the moved item after the anchor, computes the position server-side (midpoint into the gap, or a dense renumber of the whole section when the gap is exhausted or legacy unset positions are involved), and persists the result transactionally. Returns the applied row updates so the acting client can patch its cache with the exact truth.
type SignedUploadRequest ¶ added in v0.0.82
SignedUploadRequest is a presigned S3 URL plus the headers it was signed with, which the client must send verbatim.
type TeamsMeetingCommand ¶ added in v0.0.65
type TeamsMeetingCommand struct {
// contains filtered or unexported fields
}
TeamsMeetingCommand implements /mstmeetings: it creates a Microsoft Teams online meeting organized by the invoking user, invites everyone in the current chat (channel members or conversation participants), and posts the join link into the chat as the invoker. Because the workspace signs in through Microsoft 365 already, no account linking is required — the app creates the meeting via Graph application permissions.
func NewTeamsMeetingCommand ¶ added in v0.0.65
func NewTeamsMeetingCommand(deps TeamsMeetingDeps) *TeamsMeetingCommand
NewTeamsMeetingCommand builds the command from its dependency set.
func (*TeamsMeetingCommand) Info ¶ added in v0.0.65
func (t *TeamsMeetingCommand) Info() CommandInfo
Info describes the command to the composer autocomplete.
func (*TeamsMeetingCommand) Run ¶ added in v0.0.65
func (t *TeamsMeetingCommand) Run(ctx context.Context, req CommandRequest) (*model.Message, error)
Run executes the command. Membership doubles as the access check: the member list (channel) or participant list (conversation) is needed for the invite anyway, and the invoker must appear in it.
type TeamsMeetingDeps ¶ added in v0.0.65
type TeamsMeetingDeps struct {
Meetings MeetingCreator
Sender MeetingMessageSender
Users MeetingUserResolver
Memberships MembershipStore
Conversations ConversationStore
Channels ChannelStore
}
TeamsMeetingDeps declares the full dependency surface of the /mstmeetings command in one place (the MessageServiceDeps idiom).
type TestResult ¶ added in v0.0.116
type TestResult struct {
OK bool `json:"ok"`
Status int `json:"status,omitempty"`
LatencyMs int64 `json:"latencyMs"`
Error string `json:"error,omitempty"`
Reply string `json:"reply,omitempty"`
}
TestResult is how the app answered a test interaction.
type ThreadFollowStore ¶ added in v0.0.24
type ThreadFollowStore interface {
SetThreadFollow(ctx context.Context, follow *model.ThreadFollow) error
// SetThreadFollowMany writes a batch of follows in a single
// underlying call. Used by the auto-follow-on-mention path so a
// reply that mentions N people costs one round-trip instead of N.
SetThreadFollowMany(ctx context.Context, follows []*model.ThreadFollow) error
GetThreadFollow(ctx context.Context, userID, parentID, threadRootID string) (*model.ThreadFollow, error)
// GetUserThreadFollows reads userID's rows for the given threads; threads
// without one are left out.
GetUserThreadFollows(ctx context.Context, userID string, threads []model.ThreadRef) ([]*model.ThreadFollow, error)
ListUserThreadFollows(ctx context.Context, userID string) ([]*model.ThreadFollow, error)
// ListFollowedThreadsByActivity pages userID's followed threads, latest
// reply first; next is empty at the end.
ListFollowedThreadsByActivity(ctx context.Context, userID, cursor string, limit int) ([]*model.ThreadFollow, string, error)
ListThreadFollows(ctx context.Context, parentID, threadRootID string) ([]*model.ThreadFollow, error)
// TouchThreadActivity records a reply at `at` on the followers' rows.
TouchThreadActivity(ctx context.Context, userIDs []string, parentID, threadRootID string, at time.Time) error
}
ThreadFollowStore defines per-user follow/unfollow overrides for threads.
type ThreadPage ¶ added in v0.0.107
type ThreadPage struct {
Threads []*ThreadSummary `json:"threads"`
// NextCursor asks for the page after this one; empty at the end.
NextCursor string `json:"nextCursor,omitempty"`
}
ThreadPage is one page of the /threads list.
type ThreadSummary ¶ added in v0.0.2
type ThreadSummary struct {
ParentID string `json:"parentID"`
ParentType string `json:"parentType"`
ThreadRootID string `json:"threadRootID"`
RootAuthorID string `json:"rootAuthorID"`
RootBody string `json:"rootBody"`
RootCreatedAt time.Time `json:"rootCreatedAt"`
ReplyCount int `json:"replyCount"`
LatestActivityAt time.Time `json:"latestActivityAt"`
// False for a thread listed only because an alert pulled it in (a
// keyword, an @here) for someone who doesn't follow it.
Following bool `json:"following"`
// Unread: the thread has replies the user hasn't seen (its unread marker).
Unread bool `json:"unread,omitempty"`
}
ThreadSummary describes a thread the user has participated in. It carries the metadata the sidebar needs (where to navigate, what to show, when the last activity was) without forcing the client to make N follow-up queries.
type ThumbnailObjects ¶ added in v0.0.88
type ThumbnailObjects interface {
GetObjectRange(ctx context.Context, key string, maxBytes int64) ([]byte, error)
GetObject(ctx context.Context, key string) (io.ReadCloser, string, int64, time.Time, error)
PutObject(ctx context.Context, key, contentType string, body []byte) error
}
ThumbnailObjects reads and rewrites stored thumbnails.
type TokenStore ¶
type TokenStore interface {
StoreRefreshToken(ctx context.Context, rt *model.RefreshToken) error
GetRefreshToken(ctx context.Context, tokenHash string) (*model.RefreshToken, error)
DeleteRefreshToken(ctx context.Context, tokenHash string) error
// MarkRefreshTokenRotated stamps a token used-and-superseded (kept, not
// deleted — see AuthService.RefreshAccessToken's lost-response reuse rules).
MarkRefreshTokenRotated(ctx context.Context, tokenHash string, rotatedAt time.Time, supersededBy string) error
// DeleteRefreshTokenFamily revokes every token of one login session.
DeleteRefreshTokenFamily(ctx context.Context, userID, familyID string) error
DeleteAllRefreshTokensForUser(ctx context.Context, userID string) error
}
TokenStore defines persistence operations for refresh tokens.
type UnfurlAttachment ¶ added in v0.0.50
type UnfurlAttachment struct {
Filename string `json:"filename"`
ContentType string `json:"contentType,omitempty"`
}
UnfurlAttachment is the minimal file descriptor a message-link preview carries so the client can pick a file-type icon by content type / name.
type UnfurlCache ¶ added in v0.0.11
type UnfurlCache interface {
Get(ctx context.Context, key string, dest interface{}) error
Set(ctx context.Context, key string, val interface{}, ttl time.Duration) error
}
UnfurlCache is the slim slice of RedisCache UnfurlService uses; defined as an interface so tests can stub it without bringing up Redis.
type UnfurlImageStore ¶ added in v0.0.16
type UnfurlImageStore interface {
HeadObject(ctx context.Context, key string) (bool, error)
PutObject(ctx context.Context, key, contentType string, body []byte) error
PresignedGetURL(ctx context.Context, key string, expires time.Duration) (string, error)
GetObject(ctx context.Context, key string) (io.ReadCloser, string, int64, time.Time, error)
}
UnfurlImageStore is the slim S3 surface UnfurlService needs to proxy scraped preview images. Concrete impl: storage.S3Client. Defined as an interface so tests can stub it without bringing up real S3 / MinIO.
Lifecycle: keys live under the `unfurl/` prefix so an external S3 lifecycle rule (Terraform / IaC) can expire them on a schedule (e.g. 30 days). Nothing in this codebase manages that policy.
type UnfurlPreview ¶ added in v0.0.11
type UnfurlPreview struct {
URL string `json:"url"`
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
Image string `json:"image,omitempty"`
// Intrinsic pixel dimensions of Image (0 when unknown). For internal
// message-link previews this lets the client size a shared image exactly
// as the original message does, rather than expanding it to fill the card.
ImageWidth int `json:"imageWidth,omitempty"`
ImageHeight int `json:"imageHeight,omitempty"`
SiteName string `json:"siteName,omitempty"`
// Internal message-link preview (Slack/Mattermost-style). When Kind is
// "message" the client renders a rich author/body/channel card instead
// of the generic OpenGraph card. These fields are populated only by the
// MessageLinkService, never by web scraping.
Kind string `json:"kind,omitempty"` // "" (web) | "message"
AuthorName string `json:"authorName,omitempty"` // display name (or webhook username)
AuthorAvatarURL string `json:"authorAvatarURL,omitempty"` // signed avatar URL
ChannelLabel string `json:"channelLabel,omitempty"` // "~slug" / group name / "Direct message"
Body string `json:"body,omitempty"` // message body excerpt
CreatedAt string `json:"createdAt,omitempty"` // RFC3339
// Attachments lists the message's non-image uploaded file attachments so
// the client renders the same file-type icons it uses in the message
// list (instead of a paperclip emoji baked into the body). Image files
// are surfaced via Image above and omitted here.
Attachments []UnfurlAttachment `json:"attachments,omitempty"`
}
UnfurlPreview is the payload returned for a successfully unfurled URL. All fields are optional — the client renders whatever is available.
type UnfurlService ¶ added in v0.0.11
type UnfurlService struct {
// contains filtered or unexported fields
}
UnfurlService fetches HTML for a URL, scrapes OpenGraph / Twitter Card metadata, and caches the result. The HTTP client is hardened against SSRF (netguard): every dial — the first hop, each redirect, a name that resolves to a private address — must reach a public address, the proxy environment is ignored, and non-HTTP schemes are rejected; the response body is size-capped.
When an UnfurlImageStore is configured, the scraped Image URL is proxied through S3: the upstream image is fetched once, uploaded under `unfurl/<sha256>.<ext>`, and the public preview.Image is rewritten to a presigned GET on that key. Subsequent requests reuse the existing object via a HEAD check. If the upstream image fetch fails for any reason (timeout, non-image content-type, oversize, network), Image is cleared so the frontend can render a placeholder rather than a broken image icon.
func NewUnfurlService ¶ added in v0.0.11
func NewUnfurlService(cache UnfurlCache) *UnfurlService
NewUnfurlService builds an UnfurlService backed by the supplied cache.
func (*UnfurlService) ProxyImageURL ¶ added in v0.0.48
func (s *UnfurlService) ProxyImageURL(ctx context.Context, rawURL string) string
ProxyImageURL fetches and caches an arbitrary trusted-by-feature image URL through the same hardened image proxy used by unfurls.
func (*UnfurlService) ProxyImageWithSize ¶ added in v0.0.48
ProxyImageWithSize behaves like ProxyImageURL but also reports the intrinsic pixel dimensions of the cached image. Width/height are decoded from the upstream bytes the first time the image is cached and memoised in the cache keyed by the S3 object; an object stored without recorded dimensions (legacy objects) is read back once and decoded. Returns ("", 0, 0) on any failure.
When no image store is configured it degrades to the plain proxy and reports unknown dimensions.
func (*UnfurlService) SetImageStore ¶ added in v0.0.16
func (s *UnfurlService) SetImageStore(store UnfurlImageStore)
SetImageStore wires the S3-backed image proxy. When set, scraped preview.Image URLs are rewritten to presigned URLs on objects we own; when nil, the original upstream URL flows through unchanged (legacy behaviour).
func (*UnfurlService) SetMediaURLCache ¶ added in v0.0.19
func (s *UnfurlService) SetMediaURLCache(c MediaURLCache)
func (*UnfurlService) Unfurl ¶ added in v0.0.11
func (s *UnfurlService) Unfurl(ctx context.Context, rawURL string) (*UnfurlPreview, error)
Unfurl returns a preview for rawURL. Cache is hit first; on a miss the service fetches, scrapes, and caches the result. Errors are returned to the caller — callers typically swallow them and just skip the preview for that link.
func (*UnfurlService) Wired ¶ added in v0.0.97
func (s *UnfurlService) Wired() error
type UnreadSeqStore ¶ added in v0.0.52
type UnreadSeqStore interface {
IncrementMessageSeq(ctx context.Context, parentID string) (int64, error)
// CurrentMessageSeq reads the parent's counter without bumping it — the
// ceiling a mark-unread rewinds the caller's watermark from.
CurrentMessageSeq(ctx context.Context, parentID string) (int64, error)
SetLastRead(ctx context.Context, parentID, userID string, seq int64) error
}
UnreadSeqStore drives the per-parent unread counter shared by channels and conversations: a monotonic message seq on the parent, plus a per-user last-read stamp. unread = parent.MessageSeq - member.LastReadSeq. Adapters bind the underlying stores (for channels the two operations live on different stores; for conversations both live on the conversation store). Optional dependency — when unset (e.g. a narrow unit test) the bump is simply skipped.
type UploadRequest ¶ added in v0.0.82
UploadRequest is one S3 call the browser wants to make while uploading an attachment (Uppy's AWS S3 plugin asks for each one): a single PUT, or the create / part / list / complete / abort steps of a multipart upload.
type UpsertOption ¶ added in v0.0.50
type UpsertOption func(*upsertConfig)
UpsertOption configures Upsert behavior.
func WithSilent ¶ added in v0.0.50
func WithSilent(silent bool) UpsertOption
WithSilent suppresses the draft.updated broadcast for this upsert when silent is true. The draft is still persisted — only the cross-device "a draft is available" signal is withheld. Used for keystroke-by-keystroke saves while the user is still typing; the composer fires a non-silent upsert when it loses focus so the indicator surfaces only then.
type UserIndexer ¶ added in v0.0.13
type UserSearcher ¶ added in v0.0.13
UserSearcher returns matching user IDs; the service hydrates them against the user store so the response shape matches the legacy in-memory path (avatar URL, status, role, etc.).
type UserService ¶
type UserService struct {
// contains filtered or unexported fields
}
UserService provides user profile operations.
func NewUserService ¶
func NewUserService(users UserStore, cache Cache, avatars AvatarSigner, publisher Publisher) *UserService
NewUserService creates a UserService with the given dependencies. avatars may be nil; when set, AvatarKey is resolved into a presigned AvatarURL on each fetch. publisher may be nil to disable user.updated broadcasts.
func (*UserService) BotAccounts ¶ added in v0.0.112
BotAccounts returns the bot accounts admins manage, disabled ones included, oldest first. Bots are a handful of rows among the accounts, so they are filtered out of the paged user partition, and the result shared through the cache like the roster.
func (*UserService) ClearExpiredStatuses ¶ added in v0.0.22
ClearExpiredStatuses clears persisted statuses whose ClearAt has passed and publishes user.updated so every connected client removes the status without waiting for that user profile to be read again. It reads the shared roster: every instance sweeps each minute, and the clear itself is conditional on the ClearAt it saw, so a copy up to a minute old is safe.
func (*UserService) DeactivatedAmong ¶ added in v0.0.109
func (s *UserService) DeactivatedAmong(ctx context.Context, userIDs []string) (map[string]bool, error)
DeactivatedAmong reports which of userIDs are deactivated, from the shared roster: a large channel's member list no longer reads every member's row. Deactivation drops the roster (applyStatus), so it shows at once. IDs the roster doesn't list (bots, unknown IDs) are read from the store.
func (*UserService) EnsureBotUser ¶ added in v0.0.68
func (s *UserService) EnsureBotUser(ctx context.Context, botID, displayName string) (*model.User, error)
EnsureBotUser returns the machine account for botID, creating it on first use and renaming it when the webhook's username changes. Conversations created before a rename keep their label: UserConversation.DisplayName is snapshotted at creation.
func (*UserService) GetBatch ¶
GetBatch returns users by a list of IDs (input order, missing users skipped). Cache hits are served first; the misses are resolved in a SINGLE batched store read when the store supports it (instead of N serial GetItems on a cold cache), falling back to per-id reads otherwise.
func (*UserService) GetByEmail ¶
GetByEmail returns a user by email address.
func (*UserService) ListAll ¶ added in v0.0.109
ListAll returns every account except bots, with signed avatar URLs.
func (*UserService) PatchTimeZoneIfChanged ¶ added in v0.0.22
func (s *UserService) PatchTimeZoneIfChanged(ctx context.Context, userID, timeZone string) (*model.User, error)
PatchTimeZoneIfChanged records the browser's current local time zone when it differs from the stored profile value. It is intentionally quiet on no-op calls because /users/me is fetched often.
func (*UserService) RunExpiredStatusSweeper ¶ added in v0.0.22
func (s *UserService) RunExpiredStatusSweeper(ctx context.Context, interval time.Duration)
RunExpiredStatusSweeper periodically clears expired statuses from the persisted user profiles. Because the expiration timestamp lives in the user record, restarting the server only delays the next sweep; it does not lose scheduled clears.
func (*UserService) Search ¶
Search returns users whose display name or email matches the query. When an OpenSearch searcher is wired, the query is routed there and hits are hydrated from the user store so the response carries the full model (avatar, role, status). Otherwise it falls back to a substring scan over the first page of ListUsers — fine for small teams, and the same behaviour the app shipped with.
func (*UserService) SearchInvitable ¶ added in v0.0.112
func (s *UserService) SearchInvitable(ctx context.Context, query string, limit int) ([]*model.User, error)
SearchInvitable is Search plus the bots whose name or username matches: whoever can be added to a channel. A bot posts only where it is a member, so this is how one gets into a channel; everywhere else bots stay out of user search.
func (*UserService) SetAudienceInvalidator ¶ added in v0.0.97
func (s *UserService) SetAudienceInvalidator(a AudienceInvalidator)
SetAudienceInvalidator wires the notification audience cache's invalidation into account notification-settings writes.
func (*UserService) SetAutomationStopper ¶ added in v0.0.97
func (s *UserService) SetAutomationStopper(a AutomationStopper)
SetAutomationStopper wires agent-automation shutdown into deactivation, so a deactivated account's watchers, schedules and runs stop with it.
func (*UserService) SetAvatarDecodeLimit ¶ added in v0.0.89
func (s *UserService) SetAvatarDecodeLimit(limit int64)
SetAvatarDecodeLimit lets a process that shrinks one avatar at a time (the avatar-resize backfill) decode bigger pictures than the server accepts. The server's limit is its share of a budget every upload in flight draws from; this limit gets a budget of its own.
func (*UserService) SetAvatarObjects ¶ added in v0.0.88
func (s *UserService) SetAvatarObjects(o AvatarObjects)
SetAvatarObjects wires the storage uploaded avatars are read from and their shrunk copies written to. Without it a new avatar cannot be set.
func (*UserService) SetIndexer ¶ added in v0.0.13
func (s *UserService) SetIndexer(i UserIndexer)
func (*UserService) SetMediaURLCache ¶ added in v0.0.19
func (s *UserService) SetMediaURLCache(c MediaURLCache)
func (*UserService) SetNotificationSettings ¶ added in v0.0.50
func (s *UserService) SetNotificationSettings(ctx context.Context, userID string, settings model.NotificationSettings) (*model.User, error)
SetNotificationSettings persists the caller's account-level notification settings (levels, toggles, and the global keyword list) and notifies the user's own connected clients so every tab/device stays in sync.
func (*UserService) SetReminderCanceller ¶ added in v0.0.85
func (s *UserService) SetReminderCanceller(r ReminderCanceller)
SetReminderCanceller wires reminder cleanup into deactivation, so an account that can no longer sign in leaves no reminders queued to fire.
func (*UserService) SetRunnerRevoker ¶ added in v0.0.89
func (s *UserService) SetRunnerRevoker(r RunnerRevoker)
SetRunnerRevoker wires ex-runner revocation into account deactivation.
func (*UserService) SetSearcher ¶ added in v0.0.13
func (s *UserService) SetSearcher(sr UserSearcher)
func (*UserService) SetStatus ¶ added in v0.0.2
func (s *UserService) SetStatus(ctx context.Context, targetID string, deactivated bool) (*model.User, error)
SetStatus marks any account active or deactivated on an admin's behalf — SSO accounts included: the IdP can stop new logins, but only this ends the sessions and automations the account already has. The handler enforces actor admin rights (and refuses self-deactivation); this performs the mutation and emits a user.updated event so connected clients refresh.
func (*UserService) SetStatusFromDirectory ¶ added in v0.0.65
func (s *UserService) SetStatusFromDirectory(ctx context.Context, targetID string, deactivated bool) error
SetStatusFromDirectory flips an SSO-managed account's status on behalf of the employee directory (the periodic MS Graph sweep): an account deleted upstream is deactivated — ending its live sessions, since SSO removal alone doesn't invalidate refresh tokens — and reactivated if it reappears. The directory only ever undoes its OWN deactivation: an account an admin deactivated stays deactivated however present it is upstream.
func (*UserService) SetTokenStore ¶ added in v0.0.4
func (s *UserService) SetTokenStore(t TokenStore)
SetTokenStore wires a TokenStore so deactivating a user invalidates every outstanding refresh token they hold — kicking them out of any open session.
func (*UserService) SetUserStatusMessage ¶ added in v0.0.22
func (s *UserService) SetUserStatusMessage(ctx context.Context, userID string, status *model.UserStatus, clearAfter *time.Duration, timeZone string) (*model.User, error)
SetUserStatusMessage sets or clears the caller-visible status message. clearAfter is a duration from server time; clients must not supply an absolute persisted timestamp because their clock can be wrong.
func (*UserService) ShrinkAvatar ¶ added in v0.0.88
ShrinkAvatar replaces a user's avatar with a copy that fits MaxAvatarSide when it is bigger. Avatars kept before uploads were shrunk are full-size photos. The original object stays, since clients may still hold its URL until user.updated reaches them. With dryRun nothing is written. Reports whether the avatar was (or would be) replaced.
func (*UserService) Update ¶
func (s *UserService) Update(ctx context.Context, userID string, displayName, avatarKey, emojiSkinTone *string) (*model.User, error)
Update modifies optional user profile fields and invalidates the cache. avatarKey is the new S3 object key; pass nil to leave it unchanged.
func (*UserService) UpdateRole ¶
func (s *UserService) UpdateRole(ctx context.Context, _, targetID string, role model.SystemRole) (*model.User, error)
UpdateRole sets the system role on a user. The handler is responsible for enforcing that the actor is a system admin; this function performs the underlying mutation and invalidates the user cache.
Guest accounts (created via invite acceptance) cannot be promoted to member or admin — those roles are reserved for SSO-authenticated employees. A guest must re-onboard through SSO to gain a non-guest role. Demotions to "guest" remain allowed.
func (*UserService) UserAccess ¶ added in v0.0.97
func (s *UserService) UserAccess(ctx context.Context, id string) (string, model.SystemRole, error)
UserAccess returns just the account status and the STORED system role — the auth middleware's deactivation and role check runs on EVERY authenticated request and discards everything else, so this path deliberately skips the avatar-URL resolution GetByID performs (1-3 extra Redis round trips per request for a presigned URL nobody read). Cache-first with a store fill on miss, same as GetByID, so steady state is one Redis GET per request; every role/status writer evicts the cached copy.
func (*UserService) Wired ¶ added in v0.0.97
func (s *UserService) Wired() error
type UserStateService ¶ added in v0.0.26
type UserStateService struct {
// contains filtered or unexported fields
}
func NewUserStateService ¶ added in v0.0.26
func NewUserStateService(store UserStateStore, publisher Publisher) *UserStateService
func (*UserStateService) HiddenSkillSet ¶ added in v0.0.72
func (s *UserStateService) HiddenSkillSet(ctx context.Context, userID string) (map[string]bool, error)
HiddenSkillSet is the orchestrator's view: the set of skill ids userID has removed from their agents' discovery index.
func (*UserStateService) HideConversation ¶ added in v0.0.26
func (s *UserStateService) HideConversation(ctx context.Context, userID, convID string) error
func (*UserStateService) HideSkill ¶ added in v0.0.72
func (s *UserStateService) HideSkill(ctx context.Context, userID, skillID string) error
HideSkill removes one skill from the discovery index of this user's agent runs; UnhideSkill restores it. Hiding never blocks an explicit /skill pick.
func (*UserStateService) List ¶ added in v0.0.26
List returns userID's always-loaded state: unread-thread markers and hidden conversations and skills, one small query per kind. Thread seen rows are read one thread at a time (ThreadRead).
func (*UserStateService) MarkThreadNotificationUnread ¶ added in v0.0.26
func (s *UserStateService) MarkThreadNotificationUnread(ctx context.Context, userID, parentID, parentType, threadRootID string) error
func (*UserStateService) MarkThreadSeen ¶ added in v0.0.26
func (s *UserStateService) MarkThreadSeen(ctx context.Context, userID, parentID, parentType, threadRootID string) error
func (*UserStateService) ParentLeft ¶ added in v0.0.107
func (s *UserStateService) ParentLeft(ctx context.Context, userIDs []string, parentID string)
ParentLeft deletes the unread-thread markers userIDs hold in a channel they can no longer read: the threads can't be opened there any more, so a marker left behind would keep the sidebar's Threads dot lit.
func (*UserStateService) SetActivityTracker ¶ added in v0.0.83
func (s *UserStateService) SetActivityTracker(t ActivityReadTracker)
SetActivityTracker wires the Activity tab, so seeing a thread reads its activity items. Optional.
func (*UserStateService) ThreadRead ¶ added in v0.0.110
func (s *UserStateService) ThreadRead(ctx context.Context, userID, threadRootID string) (*model.ThreadReadState, error)
ThreadRead returns how far userID has read one thread. A thread they never opened has an empty state.
func (*UserStateService) UnhideConversation ¶ added in v0.0.26
func (s *UserStateService) UnhideConversation(ctx context.Context, userID, convID string) error
func (*UserStateService) UnhideSkill ¶ added in v0.0.72
func (s *UserStateService) UnhideSkill(ctx context.Context, userID, skillID string) error
func (*UserStateService) Wired ¶ added in v0.0.97
func (s *UserStateService) Wired() error
type UserStateStore ¶ added in v0.0.26
type UserStateStore interface {
SetUserState(ctx context.Context, item *model.UserStateItem) error
DeleteUserState(ctx context.Context, userID string, kind model.UserStateKind, targetID string) error
GetUserState(ctx context.Context, userID string, kind model.UserStateKind, targetID string) (*model.UserStateItem, error)
ListUserState(ctx context.Context, userID string, kind model.UserStateKind) ([]*model.UserStateItem, error)
}
type UserStore ¶
type UserStore interface {
CreateUser(ctx context.Context, user *model.User) error
GetUser(ctx context.Context, id string) (*model.User, error)
GetUserByEmail(ctx context.Context, email string) (*model.User, error)
UpdateUser(ctx context.Context, user *model.User) error
// PatchUser is the field-level update for writers that must not clobber
// concurrent changes to other fields (status, role, identity binding).
PatchUser(ctx context.Context, id string, p store.UserPatch) error
ListUsers(ctx context.Context, limit int, cursor string) ([]*model.User, string, error)
HasUsers(ctx context.Context) (bool, error)
// NotificationAccountsFor batch-loads account-level notification settings
// (and machine flags) for a set of users so the notifier can decide
// per-recipient without an N+1 fan-out. Missing users default to
// DefaultNotificationSettings.
NotificationAccountsFor(ctx context.Context, userIDs []string) (map[string]store.NotificationAccount, error)
// DeactivatedAmong reports which of userIDs are deactivated accounts.
DeactivatedAmong(ctx context.Context, userIDs []string) (map[string]bool, error)
}
UserStore defines persistence operations for users.
type ViewActionResult ¶ added in v0.0.116
type ViewActionResult struct {
Notice string `json:"notice,omitempty"`
Failed bool `json:"failed,omitempty"`
}
ViewActionResult is what a change in a form came to: the app answers by updating or pushing forms through the API; it may leave a notice.
type ViewApp ¶ added in v0.0.116
type ViewApp struct {
Name string `json:"name"`
AvatarURL string `json:"avatarURL,omitempty"`
IconEmoji string `json:"iconEmoji,omitempty"`
}
ViewApp is who a form is from, for its dialog's header.
type ViewEvent ¶ added in v0.0.116
type ViewEvent struct {
View model.View `json:"view"`
App ViewApp `json:"app"`
ClickID string `json:"clickID,omitempty"`
}
ViewEvent opens or updates a form in a person's client. ClickID names the tab that clicked: only it shows the form.
type ViewSubmitResult ¶ added in v0.0.116
type ViewSubmitResult struct {
Action string `json:"action"`
Errors map[string]string `json:"errors,omitempty"`
View *model.View `json:"view,omitempty"`
Cleared bool `json:"cleared,omitempty"`
Notice string `json:"notice,omitempty"`
Failed bool `json:"failed,omitempty"`
}
ViewSubmitResult is what a submission came to, for the form's dialog: close it (all of its stack when Cleared), show errors under fields, show the app's next form in its place (update) or on top of it (push), or keep it open (the app didn't answer). A notice is for the person alone.
type ViewValue ¶ added in v0.0.116
type ViewValue struct {
Type string `json:"type"`
Value *string `json:"value,omitempty"`
SelectedDate *string `json:"selected_date,omitempty"`
SelectedTime *string `json:"selected_time,omitempty"`
SelectedOption *model.SelectOption `json:"selected_option,omitempty"`
SelectedOptions []model.SelectOption `json:"selected_options,omitempty"`
SelectedUser *string `json:"selected_user,omitempty"`
SelectedUsers []string `json:"selected_users,omitempty"`
}
ViewValue is one element's value as the app receives it, in Slack's shape. Options come from the stored element, never the browser.
type WebhookActor ¶ added in v0.0.104
type WebhookActor struct {
ID string
Role model.SystemRole
}
WebhookActor is the person managing webhooks, with their stored system role (the auth middleware refreshes the role claim from the user store on every request). Anyone but a guest manages their own webhooks; a system admin manages everyone's.
type WebhookBotProvisioner ¶ added in v0.0.68
type WebhookBotProvisioner interface {
EnsureBotUser(ctx context.Context, botID, displayName string) (*model.User, error)
}
WebhookBotProvisioner creates (or returns) the machine account a webhook direct-messages from. Implemented by UserService.
type WebhookChannelResolver ¶ added in v0.0.48
type WebhookDMResolver ¶ added in v0.0.48
type WebhookImageProxy ¶ added in v0.0.48
type WebhookMembershipResolver ¶ added in v0.0.48
type WebhookMembershipResolver interface {
GetMembership(ctx context.Context, channelID, userID string) (*model.ChannelMembership, error)
}
WebhookMembershipResolver checks whether the webhook creator is a member of a channel — used to gate channel overrides into private channels.
type WebhookMessageInput ¶ added in v0.0.48
type WebhookMessageInput struct {
ChannelID string
ParentID string
ParentType string
AuthorID string
Body string
Username string
AvatarURL string
IconEmoji string
Attachments []model.MessageAttachment
// ParentMessageID makes the post a thread reply. The root must be a live
// top-level post by the same webhook (see checkWebhookThreadRoot).
ParentMessageID string
// WebhookID is the posting webhook, stamped on the message so its threads
// stay its own.
WebhookID string
// Blocks lay the message out; already normalized (blockNormalizer).
Blocks model.Blocks
// AppButtons: posted by the app with its bot token, so its app buttons
// reach it.
AppButtons bool
// NotifyExcept are members the post's notifications skip (a reminder for
// everyone but them).
NotifyExcept []string
// OwnerID is who set the webhook up, named by the post's integration card.
OwnerID string
}
type WebhookUserResolver ¶ added in v0.0.48
type WebhookUserResolver interface {
GetByID(ctx context.Context, id string) (*model.User, error)
GetByEmail(ctx context.Context, email string) (*model.User, error)
Search(ctx context.Context, query string, limit int) ([]*model.User, error)
}
WebhookUserResolver resolves a DM target or an @mention to a user: by exact email, by ID, or through the user search index (display names, email local-parts). Implemented by UserService. There is deliberately no directory walk: paging every user on an unauthenticated ingress, once per unknown name, cost O(directory) reads per payload.
Source Files
¶
- activity.go
- app_signing.go
- attachment.go
- attachment_agent.go
- attachment_heif.go
- attachment_poster.go
- attachment_sniff.go
- auth.go
- avatar.go
- blocks.go
- bots.go
- botuser.go
- cached_memberships.go
- category.go
- channel.go
- client_nonce.go
- command.go
- conversation.go
- conversation_convert.go
- delegated_tokens.go
- directory.go
- directory_sync.go
- draft.go
- draft_clear.go
- elements.go
- emoji.go
- emoji_shortcodes_generated.go
- errors.go
- form_values.go
- interactions.go
- interfaces.go
- layout_blocks.go
- limits.go
- markdown.go
- markdown_custom_syntax.go
- markdown_lazy.go
- mattermost.go
- media.go
- media_grant.go
- mention.go
- mention_render.go
- message.go
- message_actions.go
- message_agent.go
- message_files.go
- message_unread.go
- messagelink.go
- must.go
- notification.go
- notification_audience.go
- notification_durable.go
- notification_fanout.go
- notification_keywords.go
- notification_push.go
- notification_render.go
- notification_threads.go
- onesignal.go
- password_reset.go
- presence.go
- presigned_cache.go
- push_metrics.go
- push_scheduler.go
- reminder.go
- richtext.go
- scheduled_message.go
- settings.go
- sharepoint.go
- sharepoint_upload.go
- sidebar.go
- teamsmeeting.go
- thread_list.go
- thumbnail_webp.go
- unfurl.go
- user.go
- user_bots.go
- user_state.go
- view_blocks.go
- views.go
- webhook.go
- webhook_templates.go
- wired.go