Documentation
¶
Overview ¶
Package app holds the services, their permission checks and the audit events they write. It never imports net/http or templ.
Index ¶
- Constants
- func AvatarPath(userID uint64, key string) string
- func CleanClientName(kind SessionKind, name string) (string, error)
- func IsCallRefusal(tag string) bool
- func NormalizeCode(s string) string
- func OthersText(others int) string
- func ParseTags(s string) []string
- func SSHCodeHash(typed string) string
- func ThreadTitle(body string) string
- type Accounts
- func (a *Accounts) APISessionActor(ctx context.Context, token string) (Session, error)
- func (a *Accounts) CancelPendingLogin(ctx context.Context, token string) error
- func (a *Accounts) ChangePassword(ctx context.Context, actor Actor, sessionID uint64, in PasswordChange) error
- func (a *Accounts) CompleteLogin(ctx context.Context, pendingToken, code, clientIP, userAgent string) (LoginResult, error)
- func (a *Accounts) CreateInvitation(ctx context.Context, actor Actor, role store.Role) (IssuedInvitation, error)
- func (a *Accounts) CreateResetLink(ctx context.Context, actor Actor, userID uint64) (IssuedResetLink, error)
- func (a *Accounts) CreateSystemInvitation(ctx context.Context, role store.Role) (IssuedInvitation, error)
- func (a *Accounts) CreateSystemResetLink(ctx context.Context, username string) (IssuedResetLink, error)
- func (a *Accounts) EndSession(ctx context.Context, actor Actor, sessionID uint64) error
- func (a *Accounts) InvitationDetails(ctx context.Context, token string) (InvitationInfo, error)
- func (a *Accounts) InvitationValid(ctx context.Context, token string) error
- func (a *Accounts) Login(ctx context.Context, username, password, clientIP string) (LoginResult, error)
- func (a *Accounts) LoginClient(ctx context.Context, in ClientLogin) (LoginResult, error)
- func (a *Accounts) Logout(ctx context.Context, token string) error
- func (a *Accounts) OpenAvatar(ctx context.Context, actor Actor, userID uint64) (*os.File, string, error)
- func (a *Accounts) PendingLoginInfo(ctx context.Context, token string) (PendingLogin, error)
- func (a *Accounts) RemoveAvatar(ctx context.Context, actor Actor) (User, error)
- func (a *Accounts) ResetLinkValid(ctx context.Context, token string) error
- func (a *Accounts) ResetPassword(ctx context.Context, in ResetInput) (LoginResult, error)
- func (a *Accounts) SearchUsers(ctx context.Context, actor Actor, prefix string) ([]User, error)
- func (a *Accounts) SessionActor(ctx context.Context, token string) (Session, error)
- func (a *Accounts) Sessions(ctx context.Context, actor Actor, currentID uint64) ([]SessionInfo, error)
- func (a *Accounts) SetAvatar(ctx context.Context, actor Actor, r io.Reader) (User, error)
- func (a *Accounts) SetDisabled(ctx context.Context, actor Actor, userID uint64, disabled bool) error
- func (a *Accounts) SetRole(ctx context.Context, actor Actor, userID uint64, role store.Role) error
- func (a *Accounts) Settings(ctx context.Context, actor Actor) (Settings, error)
- func (a *Accounts) SignUp(ctx context.Context, token, username, displayName, password string, ...) (User, error)
- func (a *Accounts) UpdateProfile(ctx context.Context, actor Actor, displayName string) (User, error)
- func (a *Accounts) UpdateSettings(ctx context.Context, actor Actor, update SettingsUpdate) (Settings, error)
- func (a *Accounts) Users(ctx context.Context, actor Actor) ([]User, error)
- type AccountsConfig
- type Actor
- type AttachmentView
- type Audit
- type AuditAction
- type AuditFilter
- type AuditPage
- type AuditView
- type Board
- func (b *Board) AddColumn(ctx context.Context, actor Actor, roomID uint64, name string) (ColumnView, error)
- func (b *Board) Board(ctx context.Context, actor Actor, roomID uint64) (BoardView, error)
- func (b *Board) Column(ctx context.Context, actor Actor, columnID uint64) (ColumnView, error)
- func (b *Board) DeleteColumn(ctx context.Context, actor Actor, columnID uint64) error
- func (b *Board) MoveColumn(ctx context.Context, actor Actor, columnID uint64, position int) error
- func (b *Board) MoveTask(ctx context.Context, actor Actor, taskID, columnID uint64, position int) error
- func (b *Board) RenameColumn(ctx context.Context, actor Actor, columnID uint64, name string) error
- func (b *Board) Task(ctx context.Context, actor Actor, taskID uint64) (TaskCard, error)
- func (b *Board) UpdateTask(ctx context.Context, actor Actor, taskID uint64, patch TaskPatch) error
- type BoardView
- type Call
- type CallEndReason
- type CallEntry
- type CallInvitation
- type CallOutcome
- type CallState
- type CallStatus
- type Calls
- func (c *Calls) Answer(ctx context.Context, actor Actor, callID uint64, video bool) (Call, error)
- func (c *Calls) Cancel(ctx context.Context, actor Actor, callID uint64) (Call, error)
- func (c *Calls) Current(ctx context.Context, actor Actor, convID uint64) (Call, bool, error)
- func (c *Calls) Decline(ctx context.Context, actor Actor, callID uint64) (Call, error)
- func (c *Calls) Enabled() bool
- func (c *Calls) EndOpen(ctx context.Context, home string) (int, error)
- func (c *Calls) EndOrphans(ctx context.Context) (int, error)
- func (c *Calls) Expire(ctx context.Context) (int, error)
- func (c *Calls) Fail(ctx context.Context, callID uint64) error
- func (c *Calls) Get(ctx context.Context, actor Actor, callID uint64) (Call, error)
- func (c *Calls) HangUp(ctx context.Context, actor Actor, callID uint64) (Call, error)
- func (c *Calls) Invitation(ctx context.Context, actor Actor, callID uint64) (CallInvitation, bool, error)
- func (c *Calls) IsOpen(ctx context.Context, callID uint64) (bool, error)
- func (c *Calls) Join(ctx context.Context, actor Actor, convID uint64) (Call, error)
- func (c *Calls) Leave(ctx context.Context, actor Actor, callID uint64) error
- func (c *Calls) Open(ctx context.Context, actor Actor, convID uint64) (Call, error)
- func (c *Calls) Ringing(ctx context.Context, actor Actor) (CallInvitation, bool, error)
- func (c *Calls) SetMedia(ctx context.Context, actor Actor, callID uint64, microphone, camera bool) error
- func (c *Calls) Start(ctx context.Context, actor Actor, convID uint64, video bool) (Call, error)
- func (c *Calls) Status(ctx context.Context, callID uint64) (CallStatus, error)
- type CallsConfig
- type ClientLogin
- type ColumnView
- type Comment
- type Connections
- type ConversationHeader
- type ConversationKind
- type ConversationMemberView
- type ConversationSummary
- type EntityType
- type EventKind
- type FailureCounter
- type FeedPage
- type Format
- type Health
- type HistoryPage
- type InvitationInfo
- type IssuedInvitation
- type IssuedResetLink
- type IssuedSSHCode
- type LastMessage
- type LoginLimiter
- func (l *LoginLimiter) Allow(ctx context.Context, username, ip string) bool
- func (l *LoginLimiter) AllowAddr(ctx context.Context, ip string) bool
- func (l *LoginLimiter) Fail(ctx context.Context, username, ip string)
- func (l *LoginLimiter) FailAddr(ctx context.Context, ip string)
- func (l *LoginLimiter) Reset(ctx context.Context, username string)
- type LoginResult
- type MarkUnread
- type Member
- type Message
- type MessageInput
- type MessageKind
- type MessageQuote
- type MessageSearchPage
- type MessageSearchResult
- type Messages
- func (m *Messages) AddMembers(ctx context.Context, actor Actor, convID uint64, userIDs []uint64) error
- func (m *Messages) Attachment(ctx context.Context, actor Actor, attachmentID uint64) (AttachmentView, io.ReadSeekCloser, error)
- func (m *Messages) Conversation(ctx context.Context, actor Actor, convID uint64) (ConversationHeader, error)
- func (m *Messages) Conversations(ctx context.Context, actor Actor) ([]ConversationSummary, error)
- func (m *Messages) Delete(ctx context.Context, actor Actor, msgID uint64) error
- func (m *Messages) DiscardUploads(ctx context.Context, actor Actor, uploads []Upload)
- func (m *Messages) Edit(ctx context.Context, actor Actor, msgID uint64, body string) (Message, error)
- func (m *Messages) ForgetStaged(ctx context.Context, actor Actor, uploads []Upload)
- func (m *Messages) GroupMentionCount(ctx context.Context, actor Actor, convID uint64, body string) (int, error)
- func (m *Messages) History(ctx context.Context, actor Actor, convID, before uint64, limit int) (HistoryPage, error)
- func (m *Messages) Leave(ctx context.Context, actor Actor, convID uint64) error
- func (m *Messages) MarkRead(ctx context.Context, actor Actor, convID, upToID uint64) error
- func (m *Messages) Message(ctx context.Context, actor Actor, msgID uint64) (Message, error)
- func (m *Messages) OpenDirect(ctx context.Context, actor Actor, userID uint64) (uint64, bool, error)
- func (m *Messages) React(ctx context.Context, actor Actor, msgID uint64, emoji string) (Reactions, error)
- func (m *Messages) Rename(ctx context.Context, actor Actor, convID uint64, name string) error
- func (m *Messages) ResolveUsernames(ctx context.Context, actor Actor, usernames []string) ([]uint64, error)
- func (m *Messages) Search(ctx context.Context, actor Actor, query string, before uint64) (MessageSearchPage, error)
- func (m *Messages) Send(ctx context.Context, actor Actor, convID uint64, in MessageInput) (Message, error)
- func (m *Messages) SetReaction(ctx context.Context, actor Actor, msgID uint64, emoji string, present bool) (Reactions, error)
- func (m *Messages) StagedUploads(ctx context.Context, actor Actor, ids []string) ([]Upload, error)
- func (m *Messages) StartDirect(ctx context.Context, actor Actor, userID uint64) (uint64, error)
- func (m *Messages) StartGroup(ctx context.Context, actor Actor, userIDs []uint64, name string) (uint64, error)
- func (m *Messages) Summary(ctx context.Context, actor Actor, convID uint64) (ConversationSummary, error)
- func (m *Messages) UnreadCount(ctx context.Context, actor Actor) (int, error)
- func (m *Messages) Upload(ctx context.Context, actor Actor, name string, r io.Reader) (Upload, error)
- type MessagesConfig
- type Notice
- type Notification
- type NotificationKind
- type NotificationPage
- type Notifications
- type NotifyLevel
- type PasswordChange
- type PendingLogin
- type PlaceKind
- type PlaceNotify
- type PlacePrefs
- type PlaceRef
- type PlaceSound
- type PlaceUpdate
- type Post
- type PostInput
- type Posts
- func (p *Posts) Attachment(ctx context.Context, actor Actor, id uint64) (AttachmentView, io.ReadSeekCloser, error)
- func (p *Posts) Create(ctx context.Context, actor Actor, roomID uint64, in PostInput) (Post, error)
- func (p *Posts) Delete(ctx context.Context, actor Actor, postID uint64) error
- func (p *Posts) DiscardUploads(ctx context.Context, actor Actor, uploads []Upload)
- func (p *Posts) Edit(ctx context.Context, actor Actor, postID uint64, in PostInput) (Post, error)
- func (p *Posts) Feed(ctx context.Context, actor Actor, roomID, beforeID uint64, limit int) (FeedPage, error)
- func (p *Posts) Follow(ctx context.Context, actor Actor, postID uint64) error
- func (p *Posts) ForgetStaged(ctx context.Context, actor Actor, uploads []Upload)
- func (p *Posts) Get(ctx context.Context, actor Actor, postID uint64) (Post, error)
- func (p *Posts) GroupMentionCount(ctx context.Context, actor Actor, roomID uint64, format Format, body string) (int, error)
- func (p *Posts) Preview(_ context.Context, actor Actor, format Format, body string) (template.HTML, error)
- func (p *Posts) Reply(ctx context.Context, actor Actor, parentID uint64, in PostInput) (Post, error)
- func (p *Posts) SetReaction(ctx context.Context, actor Actor, postID uint64, emoji string, present bool) (Reactions, error)
- func (p *Posts) StagedFileLimit() int
- func (p *Posts) StagedLimit() int64
- func (p *Posts) StagedUploads(ctx context.Context, actor Actor, ids []string) ([]Upload, error)
- func (p *Posts) SuggestTags(ctx context.Context, actor Actor, prefix string) ([]string, error)
- func (p *Posts) SweepStaged(ctx context.Context, maxAge time.Duration) (int, error)
- func (p *Posts) Thread(ctx context.Context, actor Actor, postID uint64) (Thread, error)
- func (p *Posts) ToggleReaction(ctx context.Context, actor Actor, postID uint64, emoji string) (Reactions, error)
- func (p *Posts) Unfollow(ctx context.Context, actor Actor, postID uint64) error
- func (p *Posts) Upload(ctx context.Context, actor Actor, name string, r io.Reader) (Upload, error)
- func (p *Posts) UploadStaged(ctx context.Context, actor Actor, name string, r io.Reader) (StagedUpload, error)
- type PostsConfig
- type Prefs
- func (p *Prefs) Notice(ctx context.Context, actor Actor, ev live.Event) (Notice, bool, error)
- func (p *Prefs) Place(ctx context.Context, actor Actor, ref PlaceRef) (PlacePrefs, error)
- func (p *Prefs) Places(ctx context.Context, actor Actor) ([]PlacePrefs, error)
- func (p *Prefs) UpdatePlace(ctx context.Context, actor Actor, ref PlaceRef, update PlaceUpdate) (PlacePrefs, error)
- type Presence
- type ProcessDirectory
- type Publisher
- type Query
- type ReactionCount
- type Reactions
- type RepliesMode
- type ResetInput
- type Ring
- type Role
- type Room
- type RoomInput
- type RoomPatch
- type RoomUnread
- type Rooms
- func (r *Rooms) AddMember(ctx context.Context, actor Actor, roomID, userID uint64) error
- func (r *Rooms) AdminMembers(ctx context.Context, actor Actor, roomID uint64) ([]Member, error)
- func (r *Rooms) AllRooms(ctx context.Context, actor Actor) ([]Room, error)
- func (r *Rooms) Available(ctx context.Context, actor Actor) ([]Room, error)
- func (r *Rooms) Candidates(ctx context.Context, actor Actor, roomID uint64) ([]User, error)
- func (r *Rooms) Create(ctx context.Context, actor Actor, in RoomInput) (Room, error)
- func (r *Rooms) Delete(ctx context.Context, actor Actor, roomID uint64) error
- func (r *Rooms) Get(ctx context.Context, actor Actor, roomID uint64) (Room, error)
- func (r *Rooms) Join(ctx context.Context, actor Actor, roomID uint64) error
- func (r *Rooms) Leave(ctx context.Context, actor Actor, roomID uint64) error
- func (r *Rooms) MarkRead(ctx context.Context, actor Actor, roomID, upToID uint64) error
- func (r *Rooms) Members(ctx context.Context, actor Actor, roomID uint64) ([]Member, error)
- func (r *Rooms) Mine(ctx context.Context, actor Actor) ([]Room, error)
- func (r *Rooms) MineOne(ctx context.Context, actor Actor, roomID uint64) (Room, bool, error)
- func (r *Rooms) Patch(ctx context.Context, actor Actor, roomID uint64, patch RoomPatch) (Room, error)
- func (r *Rooms) RemoveMember(ctx context.Context, actor Actor, roomID, userID uint64) error
- func (r *Rooms) SearchCandidates(ctx context.Context, actor Actor, roomID uint64, prefix string) ([]User, error)
- func (r *Rooms) Unread(ctx context.Context, actor Actor, roomID uint64) (RoomUnread, bool, error)
- func (r *Rooms) Update(ctx context.Context, actor Actor, roomID uint64, in RoomInput) error
- func (r *Rooms) Visible(ctx context.Context, actor Actor) ([]Room, error)
- func (r *Rooms) Visit(ctx context.Context, actor Actor, roomID uint64) (uint64, error)
- type SSHKey
- type SSHKeys
- func (k *SSHKeys) Add(ctx context.Context, actor Actor, name, line, password, clientIP string) (SSHKey, error)
- func (k *SSHKeys) DisableSSHCode(ctx context.Context, actor Actor, currentPassword, clientIP string) error
- func (k *SSHKeys) EnableSSHCode(ctx context.Context, actor Actor, currentPassword, clientIP string) error
- func (k *SSHKeys) List(ctx context.Context, actor Actor) ([]SSHKey, error)
- func (k *SSHKeys) Remove(ctx context.Context, actor Actor, keyID uint64, password, clientIP string) error
- func (k *SSHKeys) RemoveSSHCode(ctx context.Context, actor Actor, userID uint64) error
- func (k *SSHKeys) Server(username string) SSHServer
- type SSHServer
- type SSHServerInfo
- type Search
- type SearchPage
- type SearchResult
- type Session
- type SessionInfo
- type SessionKind
- type Settings
- type SettingsUpdate
- type SignIn
- type SignInOption
- type SignUpOption
- type SnippetSegment
- type SoundName
- type StagedUpload
- type TaskCard
- type TaskInput
- type TaskPatch
- type Term
- type Theme
- type Thread
- type Upload
- type User
- type UserRef
- type Visibility
Constants ¶
const ( // FieldUsername names the username of a sign-up or a login. FieldUsername = "username" // FieldDisplayName names the display name of a sign-up. FieldDisplayName = "displayName" // FieldPassword names the password of a sign-up. FieldPassword = "password" // FieldRole names the role of an invitation or a role change. FieldRole = "role" // FieldUser names the user an admin acts on. FieldUser = "user" // FieldClientName names the client name of an API login. FieldClientName = "clientName" // FieldForm names a problem of a whole form, not of one field: a login // with the wrong username or password. FieldForm = "form" )
The names of the fields in the metadata "fields" of a TagInvalidInput error.
const ( // TagNotFound is the tag of something that does not exist, or that the // actor may not know exists (a private room, an invitation that is used, // expired or unknown). The handlers answer 404. The metadata "op" or // "reason" says why, for the log; it is never shown. TagNotFound = store.TagNotFound // TagConflict is the tag of a change that clashes with the current state // (the last admin cannot lose the role, a unique value is taken). The // handlers answer 409. TagConflict = store.TagConflict // TagForbidden is the tag of an action that the actor's role does not // allow. The handlers answer 403. TagForbidden = "Forbidden" // TagInvalidInput is the tag of input that breaks a rule. The metadata // "fields" is a map[string]string from the name of each wrong field to a // short message for people. The handlers answer 422 and show the messages // next to the fields. TagInvalidInput = "InvalidInput" // TagUnauthenticated is the tag of a request that needs a login and has // none. The handlers redirect to the login page. TagUnauthenticated = "Unauthenticated" // TagRateLimited is the tag of a login attempt refused because the // username or the client address failed too many times lately (SPEC // §7.1). The handlers answer 429. TagRateLimited = "RateLimited" )
The tags of the errors that the services return and the handlers turn into answers (SPEC §9.1). TagNotFound and TagConflict are the store's own tags, the very same strings: an error of the store travels up through a service untouched and still matches them. Any other error is a 500.
const ( // EntityRoom is a room. EntityRoom = store.EntityRoom // EntityPost is a post. EntityPost = store.EntityPost // EntityComment is a comment: a post with a parent. EntityComment = store.EntityComment // EntityTask is a task. EntityTask = store.EntityTask // EntityColumn is a board column. EntityColumn = store.EntityColumn // EntityMember is a room membership. EntityMember = store.EntityMember // EntityUser is a user's account; its events belong to no room. EntityUser = store.EntityUser )
The kinds of entity of SPEC §7.10.
const ( // ActionPostCreated is a new post or comment. ActionPostCreated = store.ActionPostCreated // ActionPostEdited is an edit of a post or comment. ActionPostEdited = store.ActionPostEdited // ActionPostDeleted is the deletion of a post or comment. ActionPostDeleted = store.ActionPostDeleted // ActionTaskCreated is a new task. ActionTaskCreated = store.ActionTaskCreated // ActionTaskEdited is a change of the title, assignees or due date of a task. ActionTaskEdited = store.ActionTaskEdited // ActionTaskMoved is a task moved to another column or position. ActionTaskMoved = store.ActionTaskMoved // ActionTaskDeleted is the deletion of a task. ActionTaskDeleted = store.ActionTaskDeleted // ActionColumnCreated is a new board column. ActionColumnCreated = store.ActionColumnCreated // ActionColumnRenamed is a renamed board column. ActionColumnRenamed = store.ActionColumnRenamed // ActionColumnMoved is a board column moved to another position. ActionColumnMoved = store.ActionColumnMoved // ActionColumnDeleted is the deletion of a board column. ActionColumnDeleted = store.ActionColumnDeleted // ActionMemberJoined is a user who joined a visible room. ActionMemberJoined = store.ActionMemberJoined // ActionMemberAdded is a user added to a room by another member. ActionMemberAdded = store.ActionMemberAdded // ActionMemberLeft is a member who left a room. ActionMemberLeft = store.ActionMemberLeft // ActionMemberRemoved is a member removed from a room by an admin. ActionMemberRemoved = store.ActionMemberRemoved // ActionRoomCreated is a new room. ActionRoomCreated = store.ActionRoomCreated // ActionRoomRenamed is a change of the name or description of a room. ActionRoomRenamed = store.ActionRoomRenamed // ActionRoomDeleted is the deletion of a room. ActionRoomDeleted = store.ActionRoomDeleted // ActionUserPasswordChanged is a user who changed their own password. ActionUserPasswordChanged = store.ActionUserPasswordChanged // ActionUserResetLinkCreated is a password reset link made for a user. ActionUserResetLinkCreated = store.ActionUserResetLinkCreated // ActionUserPasswordReset is a user who set a new password with a reset // link. ActionUserPasswordReset = store.ActionUserPasswordReset // ActionUserSSHKeyAdded is a user who registered an SSH key. ActionUserSSHKeyAdded = store.ActionUserSSHKeyAdded // ActionUserSSHKeyRemoved is a user who removed an SSH key. ActionUserSSHKeyRemoved = store.ActionUserSSHKeyRemoved // ActionUserSSHCodeEnabled is a user who turned on the SSH code at login. ActionUserSSHCodeEnabled = store.ActionUserSSHCodeEnabled // ActionUserSSHCodeDisabled is a user who turned off the SSH code at // login. ActionUserSSHCodeDisabled = store.ActionUserSSHCodeDisabled // ActionUserSSHCodeRemoved is an admin who turned off the SSH code of // another user. ActionUserSSHCodeRemoved = store.ActionUserSSHCodeRemoved )
The actions of SPEC §7.10.
const ( // AvatarMaxBytes is the largest file that SetAvatar takes. AvatarMaxBytes = 2 << 20 // AvatarMaxPixels is the largest width and height of the file that // SetAvatar takes. AvatarMaxPixels = 4096 // AvatarSize is the width and the height of the stored avatar. AvatarSize = 256 )
The limits of an avatar (SPEC §7.14).
const ( // TagCallGroup is the tag of a call in a conversation of more than two // people. TagCallGroup = "CallGroup" // TagCallsOff is the tag of a call on a server whose media server is off // (no -media-addr). TagCallsOff = "CallsOff" // TagCallCalleeDisabled is the tag of a call to a disabled user. TagCallCalleeDisabled = "CallCalleeDisabled" // TagCallCallerBusy is the tag of a call by a user who is in another call. TagCallCallerBusy = "CallCallerBusy" // TagCallCalleeBusy is the tag of a call to a user who is in another call. TagCallCalleeBusy = "CallCalleeBusy" // TagCallServerFull is the tag of a call refused because the process // holds as many calls as -max-calls allows. TagCallServerFull = "CallServerFull" // TagCallWrongState is the tag of a change that the call's state does not // allow (answering a call that is active, hanging up one that rings). TagCallWrongState = "CallWrongState" // TagCallNone is the tag of a change to the call of a conversation that // has none in progress. TagCallNone = "CallNone" )
The tags of the refusals of the calls (SPEC §7.18). The handlers answer 409 for each of them, with the message of the metadata "fields" under FieldForm, which says why in words for people.
const ( // CounterUser is the namespace of the failures per username. CounterUser = "user" // CounterIP is the namespace of the failures per client address. CounterIP = "ip" )
The namespaces of the keys that LoginLimiter gives a FailureCounter: the failures of a username and the failures of a client address are counted apart.
const ( // GroupMentionRoom mentions every member of the place. GroupMentionRoom = "room" // GroupMentionAll is the same as GroupMentionRoom. GroupMentionAll = "all" // GroupMentionHere mentions the members who are online now. GroupMentionHere = "here" )
The names of the group mentions (SPEC §7.15). They are reserved: nobody signs up with one of them as a username.
const ( // FieldUsers names the people chosen for a group. FieldUsers = "users" // FieldReplyTo names the message that a message replies to. FieldReplyTo = "replyTo" // FieldMessage names the message that MarkRead was given. FieldMessage = "message" )
The names of the fields of the private messages in the metadata "fields" of a TagInvalidInput error (FieldUser, FieldName, FieldBody, FieldEmoji and FieldAttachments are named elsewhere).
const ( // FieldBody names the body of a post. FieldBody = "body" // FieldFormat names the format of a post. FieldFormat = "format" // FieldTags names the tags of a post. FieldTags = "tags" )
The names of the fields of a post in the metadata "fields" of a TagInvalidInput error.
const ( // PlaceNotifyDefault follows the global setting. PlaceNotifyDefault = store.PlaceNotifyDefault // PlaceNotifyAll notifies about every new post or message. PlaceNotifyAll = store.PlaceNotifyAll // PlaceNotifyMentions notifies only about mentions. PlaceNotifyMentions = store.PlaceNotifyMentions // PlaceNotifyNothing notifies about nothing. PlaceNotifyNothing = store.PlaceNotifyNothing )
The four choices of "Notify me about" in a place.
const ( // PlaceSoundDefault follows the global sound setting. PlaceSoundDefault = store.PlaceSoundDefault // PlaceSoundOn plays the sound in the place. PlaceSoundOn = store.PlaceSoundOn // PlaceSoundOff plays no sound in the place. PlaceSoundOff = store.PlaceSoundOff )
The three choices of the sound in a place.
const ( // MarkUnreadAll counts every new post; the default. MarkUnreadAll = store.MarkUnreadAll // MarkUnreadMentions counts only the mentions. MarkUnreadMentions = store.MarkUnreadMentions )
The two choices of "Mark as unread".
const ( // FieldPlaceNotify names the "Notify me about" of a place. FieldPlaceNotify = "notify" // FieldPlaceSound names the sound of a place. FieldPlaceSound = "sound" // FieldIgnoreGroupMentions names "Ignore @room, @all and @here". FieldIgnoreGroupMentions = "ignoreGroupMentions" // FieldMarkUnread names "Mark as unread". FieldMarkUnread = "markUnread" // FieldMuted names the mute. FieldMuted = "muted" )
The names of the fields of the preferences of a place in the metadata "fields" of a TagInvalidInput error.
const ( // ThemeSystem follows the setting of the user's device; it is the default. ThemeSystem = store.ThemeSystem // ThemeLight is the light look. ThemeLight = store.ThemeLight // ThemeDark is the dark look. ThemeDark = store.ThemeDark )
The three themes.
const ( // NotifyAll notifies about every new post and message. NotifyAll = store.NotifyAll // NotifyMentions notifies about mentions, replies, assignments, additions // and every message of a direct or group conversation; it is the default. NotifyMentions = store.NotifyMentions // NotifyNothing notifies about nothing. NotifyNothing = store.NotifyNothing )
The three global choices of "Notify me about".
const ( // SoundPurr is the default: a low, warm rumble. SoundPurr = store.SoundPurr // SoundChirp is two quick rising notes. SoundChirp = store.SoundChirp // SoundBell is one soft bell. SoundBell = store.SoundBell // SoundMeow is a sweep up and down. SoundMeow = store.SoundMeow )
The four sounds.
const ( // RepliesFollowing notifies about every comment under a followed post; it // is the default. RepliesFollowing = store.RepliesFollowing // RepliesDirect notifies only about a comment under the user's own post // or comment. RepliesDirect = store.RepliesDirect )
The two choices for replies.
const ( // FieldCurrentPassword names the current password of a password change. FieldCurrentPassword = "currentPassword" // FieldNewPassword names the new password of a password change. FieldNewPassword = "newPassword" // FieldNewPasswordConfirm names the repetition of the new password; the // handlers check it, since the service takes the password once. FieldNewPasswordConfirm = "newPasswordConfirm" // FieldTheme names the theme of the settings. FieldTheme = "theme" // FieldNotify names the global "Notify me about" of the settings. FieldNotify = "notify" // FieldSoundName names the sound of the settings. FieldSoundName = "soundName" // FieldReplies names the replies choice of the settings. FieldReplies = "replies" // FieldKeywords names the mention keywords of the settings. FieldKeywords = "keywords" )
The names of the fields of the account forms in the metadata "fields" of a TagInvalidInput error.
const ( // FieldName names the name of a room. FieldName = "name" // FieldDescription names the description of a room. FieldDescription = "description" // FieldVisibility names the visibility of a room. FieldVisibility = "visibility" )
The names of the fields of a room in the metadata "fields" of a TagInvalidInput error. The field "user" of AddMember is FieldUser.
const ( // SSHCodeLifetime is how long a code works. SSHCodeLifetime = 60 * time.Second // SSHCodeLimit is the most codes a user gets within SSHCodeLimitWindow. SSHCodeLimit = 10 // SSHCodeLimitWindow is the window of SSHCodeLimit. SSHCodeLimitWindow = 15 * time.Minute )
The rules of the sign-in codes of SPEC §7.16.
const ( // TagSSHKeyTypeRefused is the tag of a public key whose type is not on // the list of SPEC §7.16, ssh-dss included. The handlers answer 422; the // metadata "fields" has the message for the field "publicKey". TagSSHKeyTypeRefused = "SSHKeyTypeRefused" // TagSSHKeyTooShort is the tag of an RSA public key of less than 3,072 // bits. The handlers answer 422; the metadata "fields" has the message // for the field "publicKey". TagSSHKeyTooShort = "SSHKeyTooShort" )
const ( // MessageSignInExpired is shown when a pending login is gone: it expired, // had five wrong codes, or its user was disabled or changed the password. MessageSignInExpired = "This sign-in has expired. Log in again." // MessageSSHCodeWrong is the message under the field of the code. MessageSSHCodeWrong = "That code is not right." // MessageSSHCodeNotTried is the answer to turning the SSH code on before a // key has fetched a code. MessageSSHCodeNotTried = "Fetch a code with one of your keys first." // MessageSSHServerOff is the answer to turning the SSH code on when this // Clowder runs no SSH server. MessageSSHServerOff = "The SSH server is not running on this Clowder." // MessageSSHCodeNeedsKey is the answer to removing the last key while the // SSH code is on. MessageSSHCodeNeedsKey = "Turn off the SSH code before you remove your last key." )
Messages of the SSH code at login. They are fixed text, shown to people.
const ( // TagSSHServerOff is the tag of turning on the SSH code when this Clowder // runs no SSH server (SPEC §7.16). The handlers answer 409. TagSSHServerOff = "SSHServerOff" // TagSSHCodeNotTried is the tag of turning on the SSH code before one of // the keys of the user has fetched a code. The handlers answer 409. TagSSHCodeNotTried = "SSHCodeNotTried" // TagSSHCodeNeedsKey is the tag of removing the last SSH key of a user // whose SSH code is on. The handlers answer 409. TagSSHCodeNeedsKey = "SSHCodeNeedsKey" // TagSSHCodeRequired is the tag of an API login whose password was right // and whose user turned on the SSH code, without a code. The API answers // 401 with the code ssh_code_required. TagSSHCodeRequired = "SSHCodeRequired" // TagSSHCodeWrong is the tag of a wrong code in the second form of the // login. The pages show the message of the metadata "fields" next to the // code field. TagSSHCodeWrong = "SSHCodeWrong" )
const ( // FieldTasks names the tasks of a post. FieldTasks = "tasks" // FieldTitle names the title of a task. FieldTitle = "title" // FieldAssignees names the assignees of a task. FieldAssignees = "assignees" // FieldDueDate names the due date of a task. FieldDueDate = "dueDate" )
The names of the fields of a task in the metadata "fields" of a TagInvalidInput error. The tasks of a post are one field, FieldTasks, whose message names the row of the first wrong task ("Task 2: ..."); the fields of TaskPatch are the other three.
const ConnectionsRetryAfterSeconds = 30
ConnectionsRetryAfterSeconds is the Retry-After of the 429 that refuses a stream or a WebSocket past the limit.
const FieldAttachments = "attachments"
FieldAttachments names the attachments of a post in the metadata "fields" of a TagInvalidInput error.
const FieldAvatar = "avatar"
FieldAvatar names the avatar in the metadata "fields" of a TagInvalidInput error.
const FieldEmoji = "emoji"
FieldEmoji names the emoji of a reaction in the metadata "fields" of a TagInvalidInput error.
const FieldPostID = "post_id"
FieldPostID names the post or comment ID of Rooms.MarkRead in the metadata "fields" of a TagInvalidInput error.
const FieldPublicKey = "publicKey"
FieldPublicKey names the public key line of a new SSH key in the metadata "fields" of an error (the name of the key is FieldName).
const ( // FieldQuery names the search box in the metadata "fields" of a // TagInvalidInput error. FieldQuery = "q" )
The limits of search (SPEC §7.8).
const FieldSSHCode = "sshCode"
FieldSSHCode names the code of the second form of the login in the metadata "fields" of an error; the API calls it ssh_code.
const FieldUserIDs = "user_ids"
FieldUserIDs names the list of users that Presence.Online was given in the metadata "fields" of a TagInvalidInput error.
const GroupMentionConfirmAbove = groupMentionConfirmAbove
GroupMentionConfirmAbove is the number of people above which a page asks "This will notify N people. Send anyway?" before it sends a group mention.
const LoginWindow = loginWindow
LoginWindow is the window of the login limiter: failures older than this are forgotten. The API sends it as the Retry-After of a refused login, an upper bound of the wait, because the limiter does not know the remaining time.
const MaxClientNameRunes = store.MaxClientNameRunes
MaxClientNameRunes is the longest name of a client that a session keeps, in characters.
const MaxConnectionsPerUser = 30
MaxConnectionsPerUser is how many live connections one user may hold in one process, event streams of the pages and WebSockets together (SPEC D62).
const MessageDeletedPreview = "message deleted"
MessageDeletedPreview is the text shown instead of a deleted message, in a preview or a quote.
const ( // PendingLoginLifetime is how long a login waits for its code. PendingLoginLifetime = 5 * time.Minute )
The rules of the SSH code at login (SPEC §7.16, D53).
const PresenceMaxUsers = 100
PresenceMaxUsers is the most users one call of Presence.Online may ask about.
const ResetLinkLifetime = 24 * time.Hour
ResetLinkLifetime is how long a password reset link stays valid (SPEC §7.1, D51). It is a constant, not a setting.
const (
// SSHKeyMaxPerUser is the most keys a user has.
SSHKeyMaxPerUser = 10
)
The rules of the SSH keys of SPEC §7.16.
const StagedFilesFactor = 10
StagedFilesFactor is how many times the number of attachments of a post a user may have staged at once (step 24.1): the count of files, whatever their size. A user who stages thousands of tiny files would otherwise stay far under the byte limit, fill the disk with files and notes, and make every upload (which reads every note) slower.
const StagedLifetime = 24 * time.Hour
StagedLifetime is how long an upload may wait for a post: SweepStaged removes the ones older (SPEC §7.12).
const StagedLimitFactor = 10
StagedLimitFactor is how many times the attachment limit a user may have staged at once (SPEC D62): uploaded and not yet posted, in bytes.
const TagConnectionsLimited = "ConnectionsLimited"
TagConnectionsLimited is the tag of a stream or a WebSocket refused because the user already holds MaxConnectionsPerUser of them in this process. The handlers answer 429 with Retry-After (ConnectionsRetryAfterSeconds); the metadata "limit" is the limit.
const ( // TagSSHCodeLimit is the tag of a user who asked for more than 10 sign-in // codes within 15 minutes (SPEC §7.16). TagSSHCodeLimit = "SSHCodeLimit" )
const TagStagedFull = "StagedUploadsFull"
TagStagedFull is the tag of an upload refused because the user's staged uploads would go past StagedLimit. The handlers answer 413 (too_large in the API) with a message that says to post the staged files first; the metadata holds the "limit" and the bytes "staged" before the upload, and the "fileLimit" and the number of "files" staged before it. It is the tag of a user past the byte limit and of one past the limit of the number of files.
const TagSweepCanceled = "StagedSweepCanceled"
TagSweepCanceled is the tag of a sweep of the staged uploads that ctx ended; the metadata "removed" is how many it had removed.
const TagTooLarge = files.TagTooLarge
TagTooLarge is the tag of an upload larger than the limit (SPEC §7.5). It is the tag of the files package, the very same string: the error travels up from Posts.Upload untouched. The metadata "limit" is the limit in bytes. The handlers answer 413.
const UnreadPostsCap = store.UnreadPostsCap
UnreadPostsCap is the largest number of unread posts that a room counts: 100 means 100 or more (the pages show "99+" above 99). Counting stops there, so that a room nobody read for a long time costs no more than a read one.
Variables ¶
This section is empty.
Functions ¶
func AvatarPath ¶ added in v1.2.0
AvatarPath returns the address of the avatar of the user, with the key in the query so that a new avatar has a new address (SPEC §7.14), or "" when the key is empty, which is a user without an avatar.
func CleanClientName ¶ added in v1.1.0
func CleanClientName(kind SessionKind, name string) (string, error)
CleanClientName returns the client name a session of the kind keeps, or fails. For SessionAPI the name is trimmed and must have 1 to 80 characters and no control character, else it fails with TagInvalidInput (field "clientName"). For SessionBrowser, the user agent, it is cleaned of control characters and bytes that are not UTF-8, trimmed and cut to 80 characters; it never fails, and may come back empty. Any other kind fails with TagInvalidInput (field "form").
func IsCallRefusal ¶ added in v1.2.0
IsCallRefusal reports whether tag is one of the refusals of the calls, which the handlers answer with 409 and a message for people.
func NormalizeCode ¶ added in v1.2.0
NormalizeCode returns the code as it is stored and compared: without dashes and spaces, in upper case, with Crockford's I and L read as 1 and O as 0. The login with the SSH code uses it on what a person types.
func OthersText ¶ added in v1.2.0
OthersText is the text that follows the name of the actor of a reply notification that took in others more people (SPEC §7.15): " and 2 others", " and 1 other", or nothing for none.
func ParseTags ¶
ParseTags splits the tags field of the editor on spaces and commas. It returns the pieces as typed, without empty ones; PostInput.Tags takes them and the service normalizes them.
func SSHCodeHash ¶ added in v1.2.0
SSHCodeHash returns the hash that is stored for a code the person typed: the SHA-256 of the normalised code. The login with the SSH code uses it.
func ThreadTitle ¶ added in v1.2.0
ThreadTitle makes the name of a thread out of the body of its first post: the start of the first line that has text, without the marks of markdown that open a line (#, >, -, *), up to 40 characters, with an ellipsis when it was longer. A body with no text gives the empty string.
Types ¶
type Accounts ¶
type Accounts struct {
// contains filtered or unexported fields
}
Accounts is the service of invitations, sign-up, login, sessions and user management (SPEC §7.1). Make it with NewAccounts. It is safe for concurrent use.
func NewAccounts ¶
func NewAccounts(st *store.Store, clk clock.Clock, hasher auth.Hasher, cfg AccountsConfig) *Accounts
NewAccounts makes the service. Time is counted on clk; a nil clk is the real clock.
func (*Accounts) APISessionActor ¶ added in v1.1.0
APISessionActor is SessionActor for the token of the Authorization header of the API: it accepts only a session of kind SessionAPI, so that the session cookie of a browser is never a bearer token.
func (*Accounts) CancelPendingLogin ¶ added in v1.2.0
CancelPendingLogin deletes the pending login of the token ("Start again"). An unknown token is not an error.
func (*Accounts) ChangePassword ¶ added in v1.2.0
func (a *Accounts) ChangePassword(ctx context.Context, actor Actor, sessionID uint64, in PasswordChange) error
ChangePassword sets a new password for the actor. The current password is checked through the hashing gate; a wrong one counts as a failed login of the username in the login limiter, and a username or address that the limiter blocks gets TagRateLimited before the password is looked at. In one transaction it stores the new hash, deletes every session of the user but sessionID (browsers and clients alike) and every pending login that waits for an SSH code, ends the call the user is in when a session was deleted (SPEC §7.18), and writes the audit event user.password_changed; after the commit it publishes live.KindUserChanged, which closes the sockets and streams of the other sessions.
A new password that is shorter than 12 characters or longer than 1024 bytes fails with TagInvalidInput (field "newPassword"), as does one equal to the current password; a wrong current password fails with TagInvalidInput (field "currentPassword"). A disabled or missing account fails with TagUnauthenticated.
func (*Accounts) CompleteLogin ¶ added in v1.2.0
func (a *Accounts) CompleteLogin(ctx context.Context, pendingToken, code, clientIP, userAgent string) (LoginResult, error)
CompleteLogin finishes a login that waits for the SSH code (SPEC §7.16, D53): pendingToken is the token of the cookie clowder_pending and code what the person typed (a dash, spaces and the case do not matter). On a right code of any key of the user it starts a browser session named by userAgent, uses the code up and deletes the pending login, in one transaction, and returns the session like a login does, with the path to go to in Next.
An unknown or expired token, a user who was disabled, and a pending login that is gone fail with TagUnauthenticated (message MessageSignInExpired). A username or address that the limiter blocks fails with TagRateLimited before the code is looked at. A wrong, used, expired, replaced or foreign code counts as a failed login of the username and of clientIP, counts one wrong try of the pending login and fails with TagSSHCodeWrong (field "sshCode"); the fifth wrong code deletes the pending login, and that attempt and the ones after it fail as an expired one.
func (*Accounts) CreateInvitation ¶
func (a *Accounts) CreateInvitation(ctx context.Context, actor Actor, role store.Role) (IssuedInvitation, error)
CreateInvitation makes an invitation for a new user with the given role. Only admins may. It fails with TagForbidden for anyone else and with TagInvalidInput (field "role") for a role that does not exist.
func (*Accounts) CreateResetLink ¶ added in v1.2.0
func (a *Accounts) CreateResetLink(ctx context.Context, actor Actor, userID uint64) (IssuedResetLink, error)
CreateResetLink makes a one-time password reset link for the user userID (SPEC §7.1, D51). Only admins may, for any user who is not disabled, themselves included. In one transaction it deletes the unused links of the user, stores the new one (the SHA-256 of its token; the token is returned once and never stored) and writes the audit event user.reset_link_created.
It fails with TagForbidden for anyone but an admin (also for an actor whose role was taken away since the actor was built), with TagUnauthenticated when the actor's account is disabled or gone, with TagNotFound for an unknown user and with TagConflict for a user who is disabled.
func (*Accounts) CreateSystemInvitation ¶
func (a *Accounts) CreateSystemInvitation(ctx context.Context, role store.Role) (IssuedInvitation, error)
CreateSystemInvitation makes an invitation that no user made: the one of "clowder invite" on the command line, which has no actor. Nothing in the web layer calls it. It fails with TagInvalidInput (field "role") for a role that does not exist.
func (*Accounts) CreateSystemResetLink ¶ added in v1.2.0
func (a *Accounts) CreateSystemResetLink(ctx context.Context, username string) (IssuedResetLink, error)
CreateSystemResetLink makes a password reset link that no admin made: the one of "clowder reset-password" on the command line, which has no actor. It is for the user with the username (lower-cased and trimmed); like CreateResetLink it replaces the unused links of the user and writes the audit event user.reset_link_created. Nothing in the web layer calls it.
The audit event needs an actor that is a user (the table of events has a foreign key to the users), and the command line has none, so the event names the user of the link as its actor and says in its summary and in its details ("via": "command line") that it was made there.
It fails with TagNotFound for an unknown username and with TagConflict for a user who is disabled.
func (*Accounts) EndSession ¶ added in v1.1.0
EndSession deletes the session sessionID of the actor, which logs that browser or client out. It fails with TagNotFound for a session that does not exist or belongs to someone else, and does not tell the two apart. Like a logout it publishes live.KindUserChanged on the topic of the user, so that the open streams of that session read it again and end (SPEC D37). The call the user is in, if any, ends in the same transaction (session_ended, SPEC §7.18): a call is not tied to a session in the database, so it ends whichever session was ended.
func (*Accounts) InvitationDetails ¶ added in v1.1.0
InvitationDetails returns the role and the expiry of the invitation of token. For a used, expired or unknown one it fails with TagNotFound, like InvitationValid, without saying which.
func (*Accounts) InvitationValid ¶
InvitationValid returns nil when token is the token of an invitation that is not used and not expired. For a used, expired or unknown one it returns TagNotFound, and does not tell the caller which; the metadata "reason" does, for the log.
func (*Accounts) Login ¶
func (a *Accounts) Login(ctx context.Context, username, password, clientIP string) (LoginResult, error)
Login is LoginClient for a browser that sends no name: a SessionBrowser session with an empty client name. It returns the result of LoginClient: a session, or, for a user who has to type an SSH code, a pending login.
func (*Accounts) LoginClient ¶ added in v1.1.0
func (a *Accounts) LoginClient(ctx context.Context, in ClientLogin) (LoginResult, error)
LoginClient checks the username and the password of a person at the client address and starts a session of the kind and the client name given. It returns the session token, which goes into the cookie or the Authorization header and is never stored (only its SHA-256 is), the user and when the session ends.
An unknown kind, and for SessionAPI a client name that breaks its rules (see CleanClientName), fail with TagInvalidInput before the limiter and the password are looked at. The username is lower-cased and trimmed. A wrong password, an unknown username and a disabled user all fail the same way, with TagInvalidInput and the message under the field "form" (FieldForm), and cost the same time. After 5 failed attempts for the username or the address within 15 minutes it fails with TagRateLimited, before it looks at the password, until the window has passed. A successful login clears the failures of the username.
A user who turned on the SSH code is asked for it when this process runs the SSH server (AccountsConfig.SSHServer), and only after the right password (SPEC §7.16, D53). A SessionBrowser login then makes a pending login and no session: the result has Pending set, and CompleteLogin finishes it. A SessionAPI login takes the code in in.SSHCode: without one it fails with TagSSHCodeRequired, with a wrong, used, expired or foreign one with TagUnauthenticated and a failure in the limiter, and with a right one it uses the code up and starts the session in one transaction. Nothing but the right password and the right code logs anyone in.
func (*Accounts) Logout ¶
Logout deletes the session of the cookie token. An unknown token is not an error. The call the user is in, if any, ends (session_ended, SPEC §7.18).
func (*Accounts) OpenAvatar ¶ added in v1.2.0
func (a *Accounts) OpenAvatar(ctx context.Context, actor Actor, userID uint64) (*os.File, string, error)
OpenAvatar opens the avatar file of the user userID for reading, with its key. Any user who is logged in may read any avatar. A user without an avatar, an unknown user and a store without avatars fail with TagNotFound, without telling which; a disabled or missing actor fails with TagUnauthenticated. The caller closes the file.
func (*Accounts) PendingLoginInfo ¶ added in v1.2.0
PendingLoginInfo returns the pending login of the token of the cookie clowder_pending, without the token: what the second form of the login shows. A token that is empty, unknown or expired, and one of a user who is disabled, fails with TagUnauthenticated (message MessageSignInExpired): the pending login is deleted when it is found expired or its user disabled.
func (*Accounts) RemoveAvatar ¶ added in v1.2.0
RemoveAvatar removes the avatar of the actor, which brings back the initials. A user without an avatar is not an error. The file is removed after the commit, and live.KindUserUpdated is published when there was one. A disabled or missing account fails with TagUnauthenticated.
func (*Accounts) ResetLinkValid ¶ added in v1.2.0
ResetLinkValid returns nil when token is the token of a reset link that is not used, not expired and belongs to a user who is not disabled. For any other token it returns TagNotFound and does not tell the caller which reason; the metadata "reason" does, for the log.
func (*Accounts) ResetPassword ¶ added in v1.2.0
func (a *Accounts) ResetPassword(ctx context.Context, in ResetInput) (LoginResult, error)
ResetPassword sets a new password with a reset link (SPEC §7.1, D51). In one transaction it checks the link again, stores the new hash, deletes every session of the user (browsers and API clients alike) and every pending login that waits for an SSH code, starts a new browser session, marks the link used and writes the audit event user.password_reset (the actor is the user). After the commit it clears the failed logins of the username and publishes live.KindUserChanged, which closes the sockets and streams of the sessions that ended. It returns the new session like a login does.
An unknown, used or expired link, and a link of a user who was disabled since it was made, fail with TagNotFound without telling which. A password that breaks the rule of SPEC §7.1 fails with TagInvalidInput (field "password"). The link is not asked for a password check: holding it is the proof, so the failed logins of the limiter do not apply.
func (*Accounts) SearchUsers ¶ added in v1.1.0
SearchUsers returns the users who are not disabled and whose username or display name starts with prefix (case-insensitive, after trimming), ordered by username, at most 20. An empty prefix returns the first 20. It is for picking people: any logged-in user may call it. An actor whose account is disabled gets TagUnauthenticated.
func (*Accounts) SessionActor ¶
SessionActor finds the browser session of the cookie token and returns who it belongs to. For an empty, unknown or expired token, for a session of another kind (an API token, SPEC D43) and for a disabled user, it fails with TagUnauthenticated. A session lasts the configured lifetime from its last use: when the last use is more than a minute old, the use and the expiry are written again and Refreshed is true. A session that is found expired is deleted; if that fails, the store's error is returned as it is.
func (*Accounts) Sessions ¶ added in v1.1.0
func (a *Accounts) Sessions(ctx context.Context, actor Actor, currentID uint64) ([]SessionInfo, error)
Sessions returns the live sessions of the actor, browsers and API clients, the newest first, never anyone else's. currentID is the ID of the session of the request (Session.SessionID), marked as current; 0 marks none. A session that has expired is not listed.
func (*Accounts) SetAvatar ¶ added in v1.2.0
SetAvatar makes the picture that r gives the avatar of the actor: a PNG, JPEG or GIF (its first frame) of at most 2 MiB and 4096 by 4096 pixels, checked from its header before it is decoded, cut to the centre square, scaled to 256 by 256 pixels and stored as a PNG under a new random key. The old file is removed after the commit. It returns the user with the new key and publishes live.KindUserUpdated. A picture that breaks a rule fails with TagInvalidInput (field "avatar"); an Accounts made without a store for avatars fails with the tag AvatarsUnavailable; a disabled or missing account fails with TagUnauthenticated.
func (*Accounts) SetDisabled ¶
func (a *Accounts) SetDisabled(ctx context.Context, actor Actor, userID uint64, disabled bool) error
SetDisabled disables or enables a user. Disabling also deletes the sessions and the pending logins of the user, and ends the call the user is in (SPEC §7.18), in the same transaction. Only admins may; anyone else gets TagForbidden. It fails with TagInvalidInput (field "user") when an admin disables themselves, with TagNotFound for an unknown user, and with TagConflict when the user is the last active admin.
func (*Accounts) SetRole ¶
SetRole gives a user a role. Only admins may; anyone else gets TagForbidden. It fails with TagInvalidInput (field "role") for a role that does not exist, with TagNotFound for an unknown user, and with TagConflict when the user is the last active admin and the role is not admin.
func (*Accounts) Settings ¶ added in v1.2.0
Settings returns the settings of the actor: the defaults (the theme System, the sound on and Purr, the browser notifications off, notify about mentions, replies in followed threads) while none are saved. A disabled or missing account fails with TagUnauthenticated.
func (*Accounts) SignUp ¶
func (a *Accounts) SignUp(ctx context.Context, token, username, displayName, password string, opts ...SignUpOption) (User, error)
SignUp makes a user from an invitation and uses the invitation up. The username is lower-cased and trimmed, the display name trimmed (SPEC §7.1). It fails with TagNotFound for a used, expired or unknown invitation, and with TagInvalidInput for input that breaks a rule, with all the problems in the metadata "fields" (a username that is taken is one of them). The new user has the role of the invitation.
With FromAddress the sign-up is limited like a login (SPEC D62): an address that already failed the maximum number of logins or sign-ups within the window fails with TagRateLimited before the invitation is looked at, and a sign-up whose invitation is used, expired or unknown (TagNotFound) counts as one failed login of the address, the same count that a wrong password adds to, so the limit holds across processes when the limiter is in Redis. A valid invitation never counts, whatever else is wrong with the form.
func (*Accounts) UpdateProfile ¶ added in v1.2.0
func (a *Accounts) UpdateProfile(ctx context.Context, actor Actor, displayName string) (User, error)
UpdateProfile sets the display name of the actor, which follows the rules of sign-up: trimmed, 1 to 64 characters. It returns the user as it is now and publishes live.KindUserUpdated when the name changed. A name that breaks the rule fails with TagInvalidInput (field "displayName"); an account that is disabled or gone fails with TagUnauthenticated.
func (*Accounts) UpdateSettings ¶ added in v1.2.0
func (a *Accounts) UpdateSettings(ctx context.Context, actor Actor, update SettingsUpdate) (Settings, error)
UpdateSettings changes the settings of the actor; a nil field of update keeps its value. It returns the settings as they are now and publishes live.KindSettingsChanged when something changed. An unknown theme fails with TagInvalidInput (field "theme", "notify", "soundName" or "replies"); a disabled or missing account fails with TagUnauthenticated.
type AccountsConfig ¶
type AccountsConfig struct {
// InvitationLifetime is how long an invitation made now stays valid.
InvitationLifetime time.Duration
// SessionLifetime is how long a session lasts from its last use.
SessionLifetime time.Duration
// Limiter limits the failed logins. Nil makes the default one of SPEC
// §7.1 (5 failures in 15 minutes), on the clock of the service.
Limiter *LoginLimiter
// Publisher receives the live events of the account changes: a user who
// is disabled, gets another role or logs out (live.KindUserChanged), so
// that the open streams of that user notice at once. Nil publishes
// nothing.
Publisher Publisher
// MaxConcurrentHashes bounds how many passwords are hashed or checked at
// the same time, each costing 64 MiB; the other requests wait. 0 means
// twice the number of CPUs, at least 2 and at most 8.
MaxConcurrentHashes int
// Avatars stores the avatars (SPEC §7.14), in its own directory. Nil
// turns the avatars off: SetAvatar then fails with the tag
// AvatarsUnavailable and nobody has one.
Avatars *files.Store
// Logger receives what could not be cleaned up, such as the file of an
// avatar that was replaced. Nil discards it.
Logger *slog.Logger
// SSHServer is true when this process runs the SSH server (-ssh-addr is
// set). A login asks for the SSH code of a user who turned it on only
// then; with the server off the password alone logs in. Every process of
// a cluster has the same setting (SPEC §7.16).
SSHServer bool
// Logins counts the logins by result (metrics.Set.Logins, SPEC D60): the
// counter vec has the one label "result". Nil counts nothing.
Logins *metrics.CounterVec
// SignUpsRefused counts the sign-ups the limiter refused (the metric
// "signup" of clowder_limits_refused_total, SPEC D62). Nil counts nothing.
SignUpsRefused *metrics.Counter
}
AccountsConfig holds the settings and the injected parts of Accounts.
type Actor ¶
type Actor struct {
// UserID is the ID of the user.
UserID uint64
// Username is the username of the user.
Username string
// Role is the role of the user.
Role store.Role
}
Actor is the user on whose behalf a service method runs. The web layer builds it from the session; the method trusts its Role and checks the permission itself. Services take it by value, as the second parameter after ctx. Methods for people who are not logged in take no Actor.
type AttachmentView ¶
type AttachmentView struct {
// ID is the ID of the attachment.
ID uint64
// FileName is the name the file had when it was uploaded.
FileName string
// ContentType is the type found by sniffing the content.
ContentType string
// Size is the size in bytes.
Size int64
// IsImage is true for the types shown inline: PNG, JPEG, GIF and WebP.
IsImage bool
// Width and Height are the size in pixels of an image; 0 for any other
// file.
Width, Height int
// CreatedAt is when the file was attached. The download answers it as the
// time the file was last modified.
CreatedAt time.Time
}
AttachmentView is an attachment as the services show it.
type Audit ¶
type Audit struct {
// contains filtered or unexported fields
}
Audit is the service that reads the audit log (SPEC §7.10). Events are written by the other services, in their transactions, and nothing edits or deletes them. Make it with NewAudit. It is safe for concurrent use.
func (*Audit) Events ¶
func (a *Audit) Events(ctx context.Context, actor Actor, filter AuditFilter, page int) (AuditPage, error)
Events returns a page of the audit log: the events that match filter, newest first, 50 a page. The first page is 1; a page below 1 is page 1, and a page past the last one is empty. Only admins may; anyone else gets TagForbidden. The log covers private rooms and rooms that are gone.
type AuditAction ¶
type AuditAction = store.AuditAction
AuditAction is what an audit event records. It is the store's type, so the web layer can name the actions without importing the store.
type AuditFilter ¶
type AuditFilter = store.AuditFilter
AuditFilter narrows Audit.Events (SPEC §7.10). A zero field does not filter; the filters that are set all have to match.
type AuditPage ¶
type AuditPage struct {
// Events are the events of the page, newest first, at most 50.
Events []AuditView
// Page is the number of the page, starting at 1.
Page int
// HasNext is true when an older page exists.
HasNext bool
}
AuditPage is one page of the audit log.
type AuditView ¶
type AuditView struct {
// ID orders the log: newer events have larger IDs.
ID uint64
// CreatedAt is when the change was made.
CreatedAt time.Time
// ActorID is the user who made the change.
ActorID uint64
// ActorUsername is the username of the actor.
ActorUsername string
// ActorDisplayName is the display name of the actor.
ActorDisplayName string
// Action is what happened.
Action AuditAction
// RoomID is the room of the change. The room may be gone.
RoomID uint64
// EntityType is the kind of the entity that changed.
EntityType EntityType
// EntityID is the ID of the entity that changed. The entity may be gone.
EntityID uint64
// Summary reads on its own after the entity is gone.
Summary string
// Details is the decoded JSON of the event: the changed fields with their
// old and new values. Numbers are float64.
Details map[string]any
}
AuditView is an audit event as the admin pages show it.
type Board ¶
type Board struct {
// contains filtered or unexported fields
}
Board is the service of the Kanban boards of the rooms (SPEC §7.6). Make it with NewBoard. It is safe for concurrent use.
func NewBoard ¶
NewBoard makes the service. The clock decides what is overdue; pub receives the live events of the changes, after they are committed; nil publishes nothing.
func (*Board) AddColumn ¶
func (b *Board) AddColumn(ctx context.Context, actor Actor, roomID uint64, name string) (ColumnView, error)
AddColumn appends a column to the right of the board of the room and writes column.created. The name is trimmed, 1 to 40 characters, and unique in the room without regard to case; otherwise it fails with TagInvalidInput and the message under FieldName. Any member may (D25): a room that the actor may not read fails with TagNotFound, a visible room that the actor has not joined with TagForbidden. It publishes board.changed.
func (*Board) Board ¶
Board returns the board of a room that the actor may read: the columns in order with their cards in order. For a room that the actor may not read it fails with TagNotFound.
func (*Board) Column ¶ added in v1.1.0
Column returns one column of a board with its cards, for a client that changes a column and needs it back. For a column of a room that the actor may not read, and a missing column, it fails with TagNotFound. Any reader may.
func (*Board) DeleteColumn ¶
DeleteColumn deletes a column and writes column.deleted. A column that still has cards (message "Move its cards first.") and the last column of a board (message "A board needs at least one column.") are refused with TagConflict; the last column is checked first. The positions of the columns stay 0..n-1. The permissions and errors are those of RenameColumn. It publishes board.changed.
func (*Board) MoveColumn ¶
MoveColumn puts a column at the position (from 0, the left), clamped to 0..the number of columns minus one, and writes column.moved with the position from and to. The positions of the columns stay 0..n-1. A move to where the column is already writes and publishes nothing. The permissions and errors are those of RenameColumn. It publishes board.changed.
func (*Board) MoveTask ¶
func (b *Board) MoveTask(ctx context.Context, actor Actor, taskID, columnID uint64, position int) error
MoveTask puts the task in the column at the position (from 0, the top). The position counts in the target column without the task, and is clamped to 0..the number of cards there. The positions of the cards stay 0..n-1 in both columns. It writes task.moved with the column and the position from and to, and publishes board.changed and post.updated (comment.updated for a comment). A move to where the card is already writes and publishes nothing. Only members may: a task of a room that the actor may not read, a missing task and a column that is missing or of another room fail with TagNotFound, a visible room that the actor has not joined with TagForbidden.
func (*Board) RenameColumn ¶
RenameColumn changes the name of a column and writes column.renamed with the old and the new name. The name rules are those of AddColumn; renaming a column to its own name, or to another case of it, is allowed, and to the exact name it has already does nothing. Any member may (D25): a column of a room that the actor may not read and a missing column fail with TagNotFound, a visible room that the actor has not joined with TagForbidden. It publishes board.changed.
func (*Board) Task ¶ added in v1.1.0
Task returns one task as the board shows it, with its place in its column: for a client that changes a card and needs the card back. For a task of a room that the actor may not read, and a missing task, it fails with TagNotFound. Any reader may (the board of a visible room is readable by non-members).
func (*Board) UpdateTask ¶
UpdateTask changes the title, the assignees or the due date of a task on the board, and writes task.edited with only what changed (the title, the usernames of the assignees, the due date, old and new). It publishes board.changed and post.updated (comment.updated for a comment). A patch that changes nothing writes and publishes nothing. Only members may: a task of a room that the actor may not read and a missing task fail with TagNotFound, a visible room that the actor has not joined with TagForbidden. It fails with TagInvalidInput, with the problems in the metadata "fields", for a title, assignees or due date that break a rule. The users newly assigned are notified (assigned), not the actor and not those who stay on the task.
type BoardView ¶
type BoardView struct {
// Room is the room of the board.
Room Room
// Columns are the columns from left to right.
Columns []ColumnView
// CanEdit is true when the actor is a member of the room, who may move
// cards, change them and change the columns.
CanEdit bool
}
BoardView is the board of a room as one actor sees it.
type Call ¶ added in v1.2.0
type Call struct {
// ID is the ID of the call.
ID uint64
// ConversationID is the direct conversation of the call.
ConversationID uint64
// Caller started the call and Callee was called.
Caller UserRef
Callee UserRef
// Video is true when the caller started the call with video.
Video bool
// State is ringing, active or ended.
State CallState
// CreatedAt is when the call started to ring.
CreatedAt time.Time
// AnsweredAt is when the callee answered; nil if never.
AnsweredAt *time.Time
// EndedAt is when the call ended; nil while it is open.
EndedAt *time.Time
// EndReason is how the call ended; empty while it is open.
EndReason CallEndReason
// EndedBy is the ID of the user who ended the call; 0 when it was not a
// user (a timeout, a failure, a disabled account).
EndedBy uint64
// Home is the ID of the process that holds the media of the call.
Home string
// Incoming is true when the asking actor is the callee.
Incoming bool
// Elapsed is how long an active call has been answered, by the clock of
// the service when the call was read; zero for a call that is not active.
Elapsed time.Duration
}
Call is a call as the services show it to one participant.
type CallEndReason ¶ added in v1.2.0
type CallEndReason = store.CallEndReason
CallEndReason says how a call ended. It is the store's type.
const ( // CallEndHangup is a call that one side ended while it was active. CallEndHangup CallEndReason = store.CallHangup // CallEndCancelled is a call that the caller ended while it rang. CallEndCancelled CallEndReason = store.CallCancelled // CallEndDeclined is a call that the callee refused. CallEndDeclined CallEndReason = store.CallDeclined // CallEndMissed is a call that nobody answered in time. CallEndMissed CallEndReason = store.CallMissed // CallEndBusy is a call to someone who was in another call. CallEndBusy CallEndReason = store.CallBusy // CallEndFailed is a call whose media connection failed or was lost. CallEndFailed CallEndReason = store.CallFailed // CallEndDisabled is a call that ended because a participant was disabled. CallEndDisabled CallEndReason = store.CallDisabled // CallEndSessionEnded is a call that ended because a session of a // participant ended. CallEndSessionEnded CallEndReason = store.CallSessionEnded // CallEndServerStopped is a call that ended because the process holding // its media stopped. CallEndServerStopped CallEndReason = store.CallServerStopped )
The reasons a call ends (SPEC §7.18).
type CallEntry ¶ added in v1.2.0
type CallEntry struct {
// CallID is the ID of the call.
CallID uint64
// Video is true for a call that began with video.
Video bool
// Outcome says what became of the call.
Outcome CallOutcome
// DurationSeconds is how long an answered call lasted; 0 for the others.
DurationSeconds int
// Text is the line the conversation shows to the asking user: "Video call
// · 12 min", "Declined video call", "Missed video call" (the callee), "No
// answer", "Cancelled video call" or "Video call · busy" (the caller).
Text string
// Missed is true for the callee of a call that nobody answered while it
// rang: missed, cancelled by the caller, or made while the callee was in
// another call. The pages show such an entry in the colour of a warning.
Missed bool
}
CallEntry is a finished call as the conversation shows it: the content of a message of kind call.
type CallInvitation ¶ added in v1.2.0
type CallInvitation struct {
// Call is the call, as the callee reads it.
Call Call
// Ring is true when the invitation plays the ringtone: the conversation is
// not muted and its preferences do not say "Nothing". The ringtone plays
// whatever the user's notification sound says.
Ring bool
// Browser is true when the browser notification is wanted: the invitation
// rings and the user turned the browser notifications on.
Browser bool
// Text is the text of the browser notification, "Bob is calling you".
Text string
}
CallInvitation is the ringing call that a user is asked to answer, with how the invitation rings for them (SPEC §7.15, §7.18).
type CallOutcome ¶ added in v1.2.0
type CallOutcome string
CallOutcome says what became of a call, for its entry in the conversation.
const ( // CallCompleted is a call that was answered; it has a duration. CallCompleted CallOutcome = "completed" // CallDeclinedOutcome is a call that the callee declined. CallDeclinedOutcome CallOutcome = "declined" // CallCancelledOutcome is a call that the caller cancelled while it rang. CallCancelledOutcome CallOutcome = "cancelled" // CallMissedOutcome is a call nobody answered. CallMissedOutcome CallOutcome = "missed" // CallBusyOutcome is a call to someone who was in another call. CallBusyOutcome CallOutcome = "busy" )
The outcomes of a call (SPEC §7.18).
type CallState ¶ added in v1.2.0
CallState says where a call is. It is the store's type, so the web layer can name the values without importing the store.
const ( // CallRinging is a call that the callee has not answered yet. CallRinging CallState = store.CallRinging // CallActive is a call that the callee answered and that is not over. CallActive CallState = store.CallActive // CallEnded is a call that is over. CallEnded CallState = store.CallEnded )
The three states of a call (SPEC §7.18).
type CallStatus ¶ added in v1.2.0
type CallStatus struct {
// Open is true while the call is ringing or active.
Open bool
// Active is true while the call is open and has been answered.
Active bool
// Reason is how the call ended; empty while it is open.
Reason CallEndReason
}
CallStatus is the state of a call as the media server asks for it: it needs no user.
type Calls ¶ added in v1.2.0
type Calls struct {
// contains filtered or unexported fields
}
Calls is the service of one-to-one calls in direct conversations (SPEC §7.18, D63, D64). The media of a call is forwarded by the media server of package calls; this service holds the rules: who may call whom, the states of a call, the entry a finished call leaves in the conversation and the live events. Make it with NewCalls. It is safe for concurrent use. Only the two members of the direct conversation use it: anyone else, admins included, gets TagNotFound.
func NewCalls ¶ added in v1.2.0
NewCalls makes the service. pub receives the live events of the changes, after they are committed; nil publishes nothing.
func (*Calls) Answer ¶ added in v1.2.0
Answer answers the ringing call as the callee. video says whether the callee answers with video: the pages use it to decide what to send, and the media server needs nothing of it, because every call has an audio and a video transceiver; it is not stored. Only the callee may (the caller gets TagForbidden); a call that does not exist or is not the actor's fails with TagNotFound; one that is not ringing with TagCallWrongState. Both users hear call.started.
func (*Calls) Cancel ¶ added in v1.2.0
Cancel ends the ringing call as the caller: it ends as cancelled and leaves its entry. Only the caller may (the callee gets TagForbidden); a call that does not exist or is not the actor's fails with TagNotFound; one that is not ringing with TagCallWrongState.
func (*Calls) Current ¶ added in v1.2.0
Current returns the call in progress (ringing or active) of the direct conversation, and false when there is none. A conversation that does not exist or that the actor is no member of fails with TagNotFound, a group conversation with TagCallGroup.
func (*Calls) Decline ¶ added in v1.2.0
Decline refuses the ringing call as the callee: the call ends as declined and leaves its entry. The permissions and the refusals are those of Answer.
func (*Calls) Enabled ¶ added in v1.2.0
Enabled reports whether this process runs the media server, so that a call can be started. The pages show the call buttons only then.
func (*Calls) EndOpen ¶ added in v1.2.0
EndOpen ends the open calls as server_stopped and returns how many it ended: those of the process home, or every open call when home is empty. serve calls it at start without Redis, when no call can be live, and at a graceful shutdown for its own calls.
func (*Calls) EndOrphans ¶ added in v1.2.0
EndOrphans ends, as server_stopped, every open call whose home process has had no live key at every check for at least CallsConfig.OrphanGrace (20 seconds), and returns how many it ended (SPEC D65). The grace is longer than the refresh of the keys, so that a Redis that restarted and lost them does not end live calls: the first check that finds a home missing only notes the time, a check that finds the key again forgets it, and a home with no open call left is forgotten. It does nothing without a ProcessDirectory (a process that runs alone ends the calls of an earlier run at start, EndOpen). The calls of this process are left alone. When the directory cannot say whether a process is alive (Redis is down) its calls are left alone too, and the first such error is returned after the rest were handled. Each call is ended in a transaction of its own that only changes a call that is still open, so several processes may run it at the same time: a call is ended, and written to the conversation, once. serve calls it every second.
func (*Calls) Expire ¶ added in v1.2.0
Expire ends every call that has rung for 45 seconds or more, by the clock of the service, as missed, and returns how many it ended. Each call is ended in a transaction of its own, so that one that fails does not hold back the others; the first failure is returned after all were tried. serve calls it every second.
func (*Calls) Fail ¶ added in v1.2.0
Fail ends the call as failed, because its media connection did not come up or was lost (SPEC D64); the media server calls it. A call that has ended already is left alone.
func (*Calls) Get ¶ added in v1.2.0
Get returns the call, in any state, to one of its two participants. A call that does not exist or is not the actor's fails with TagNotFound.
func (*Calls) HangUp ¶ added in v1.2.0
HangUp ends the active call as either side: it ends as hangup and leaves its entry. A call that does not exist or is not the actor's fails with TagNotFound; one that is not active (still ringing, or over) with TagCallWrongState.
func (*Calls) Invitation ¶ added in v1.2.0
func (c *Calls) Invitation(ctx context.Context, actor Actor, callID uint64) (CallInvitation, bool, error)
Invitation returns the invitation of the call callID for the actor, and false when there is nothing to answer any more: the call does not exist, is not the actor's, is not ringing or was started by the actor. A disabled or missing account fails with TagUnauthenticated.
func (*Calls) IsOpen ¶ added in v1.2.0
IsOpen reports whether the call is ringing or active. A call that does not exist is not open.
func (*Calls) Join ¶ added in v1.2.0
Join returns the call of the conversation that the actor may open the signalling socket of now: the caller while the call rings or is active, the callee once they have answered it. It fails with TagCallsOff when calls are off, with TagCallWrongState for the callee of a call that still rings, and as Open does.
func (*Calls) Leave ¶ added in v1.2.0
Leave is a participant ending the call from the signalling socket: the caller cancels a ringing call, and either side hangs up an active one. It fails as Cancel and HangUp do; the callee of a ringing call has Decline.
func (*Calls) Open ¶ added in v1.2.0
Open is Current for the routes that act on "the call of this conversation" (answer, decline, cancel, hang up): it returns the call in progress, and fails with TagCallNone when there is none. The other failures are those of Current.
func (*Calls) Ringing ¶ added in v1.2.0
Ringing returns the invitation of the call that rings for the actor now, and false when none does. The pages call it when they are made, so that a page opened while a call rings shows the dialog at once. A disabled or missing account fails with TagUnauthenticated.
func (*Calls) SetMedia ¶ added in v1.2.0
func (c *Calls) SetMedia(ctx context.Context, actor Actor, callID uint64, microphone, camera bool) error
SetMedia tells the other side that the actor turned the microphone or the camera on or off (microphone and camera are true when on): both users hear call.updated. Only a participant of the active call may; a call that does not exist or is not the actor's fails with TagNotFound, one that is not active with TagCallWrongState.
func (*Calls) Start ¶ added in v1.2.0
Start starts a call from the actor to the other member of the direct conversation, with video or audio only, and rings the other member. The call is written in the transaction with the check that neither user is in another call: on PostgreSQL the rows of both users are locked first, so two calls started at the same time cannot both ring.
A conversation that does not exist or that the actor is no member of fails with TagNotFound; a group conversation with TagCallGroup; calls that are off with TagCallsOff; a disabled callee with TagCallCalleeDisabled; a caller who is in a call with TagCallCallerBusy; a process that holds -max-calls calls with TagCallServerFull. A callee who is in another call fails with TagCallCalleeBusy ("Bob is in another call") after the call was written as ended and busy, with its entry, so that the callee has a missed call. The callee hears call.ringing, both users call.started.
type CallsConfig ¶ added in v1.2.0
type CallsConfig struct {
// ProcessID is the ID of this process, recorded as the home of the calls
// it starts (SPEC D65): 16 hexadecimal characters, made at start. Empty
// is only for tests that do not care.
ProcessID string
// Enabled is true when this process runs the media server (-media-addr is
// set). Without it a call cannot be started.
Enabled bool
// MaxCalls is the most calls, ringing or active, that a process holds
// (-max-calls). Zero or less means no limit.
MaxCalls int
// RingTimeout is how long a call rings before Expire ends it as missed;
// zero means 45 seconds.
RingTimeout time.Duration
// Processes tells which processes are alive when several share the
// database (SPEC D65); nil when this one runs alone. With it, EndOrphans
// ends the calls whose home process is gone.
Processes ProcessDirectory
// OrphanGrace is how long a home process must have been missing, at every
// check of EndOrphans, before its calls are ended; zero means 20 seconds,
// which is longer than the 5-second refresh of the key of a process, so
// that a Redis that restarted and lost its keys does not end live calls
// (SPEC D65). Tests make it short.
OrphanGrace time.Duration
// Logger receives the failures that the service handles itself; nil logs
// nothing.
Logger *slog.Logger
}
CallsConfig holds the settings of the calls service.
type ClientLogin ¶ added in v1.1.0
type ClientLogin struct {
// Username is the username as typed; it is lower-cased and trimmed.
Username string
// Password is the password as typed.
Password string
// ClientIP is the address of the client, for the login limiter.
ClientIP string
// Kind is the kind of the session to make: SessionBrowser for the pages,
// SessionAPI for the API.
Kind SessionKind
// ClientName names the client. For SessionAPI it is required: 1 to 80
// characters after trimming, without control characters. For
// SessionBrowser it is the user agent of the browser, which is cut to 80
// characters and cleaned of control characters, never refused; it may be
// empty.
ClientName string
// SSHCode is the sign-in code of a user who turned the SSH code on, for
// SessionAPI (the API logs in with the code in one call). A browser login
// ignores it: the pages ask for the code in a second step
// (CompleteLogin).
SSHCode string
// Next is the local path a browser goes to after the login, kept with a
// pending login for CompleteLogin; the web layer has checked it.
Next string
}
ClientLogin is what a login names besides the username and the password.
type ColumnView ¶
type ColumnView struct {
// ID is the ID of the column.
ID uint64
// Name is the name of the column, unique in the room without regard to
// case.
Name string
// Position is the place of the column from the left, from 0.
Position int
// Last is true for the last column, which counts as done.
Last bool
// Tasks are the cards of the column from top to bottom.
Tasks []TaskCard
}
ColumnView is a column of a board with its cards.
type Comment ¶
type Comment struct {
Post
// Depth is how deep the comment is: 1 for a reply to the top-level post,
// 2 for a reply to that, and so on.
Depth int
// ParentID is the ID of the post or comment that this comment answers. It
// is the same as the embedded Post.ParentID.
ParentID uint64
// ParentAuthor is the author of the parent; the zero value when the parent
// is a deleted comment or post.
ParentAuthor UserRef
}
Comment is a comment in the thread of a post, with its place in the tree.
type Connections ¶ added in v1.2.0
type Connections struct {
// contains filtered or unexported fields
}
Connections counts the live connections of each user in this process, for the limit of SPEC D62: the event streams of the pages, the user's WebSocket of the API and the signalling sockets of calls are all counted, together. The count is in memory and per process, not per cluster. Make it with NewConnections; the server that serve makes owns it and hands the one value to the pages and the API. It is safe for concurrent use. A nil *Connections counts and limits nothing.
func NewConnections ¶ added in v1.2.0
func NewConnections(max int, refused *metrics.Counter) *Connections
NewConnections makes a counter that allows max connections per user; a max below 1 is MaxConnectionsPerUser. Each refusal is added to refused, which may be nil.
func (*Connections) Acquire ¶ added in v1.2.0
func (c *Connections) Acquire(userID uint64) (release func(), err error)
Acquire counts one more live connection of the user and returns the function that gives it back, which the caller defers right away. Calling it more than once gives back only one. When the user already holds the most it counts nothing and fails with TagConnectionsLimited (and the refusal is counted in the metrics). A user with no ID (0) is not counted. On a nil Connections it always succeeds.
func (*Connections) Open ¶ added in v1.2.0
func (c *Connections) Open(userID uint64) int
Open returns how many live connections the user holds now.
func (*Connections) Users ¶ added in v1.2.0
func (c *Connections) Users() int
Users returns how many users hold at least one live connection. It is 0 when every connection has ended, which the tests use to see that nothing leaked.
type ConversationHeader ¶
type ConversationHeader struct {
// ID is the ID of the conversation.
ID uint64
// Kind says whether it is direct or a group.
Kind ConversationKind
// Name is the name of a group as set; empty for none.
Name string
// DisplayName is the title as ConversationSummary.DisplayName.
DisplayName string
// Members are the current members, the asking actor included, in the
// order they joined.
Members []ConversationMemberView
// CanSend is false in a direct conversation whose other user is disabled:
// the messages are read but no new ones are sent (D32).
CanSend bool
// IsGroup is true for a group, where members are added, the group is
// renamed and members leave.
IsGroup bool
}
ConversationHeader is what the top of a conversation shows.
type ConversationKind ¶
type ConversationKind = store.ConversationKind
ConversationKind says how many people a conversation has. It is the store's type, so the web layer can name the values without importing the store.
const ( // ConversationDirect is a conversation between two users. ConversationDirect ConversationKind = store.ConversationDirect // ConversationGroup is a conversation of up to 50 users. ConversationGroup ConversationKind = store.ConversationGroup )
The two kinds of conversation (SPEC §7.11).
type ConversationMemberView ¶
type ConversationMemberView struct {
// User is the member.
User UserRef
// LastReadMessageID is the last message the member has read; 0 if none.
// It drives "Seen".
LastReadMessageID uint64
// Disabled is true when an admin disabled the user.
Disabled bool
}
ConversationMemberView is a member of a conversation.
type ConversationSummary ¶
type ConversationSummary struct {
// ID is the ID of the conversation.
ID uint64
// Kind says whether it is direct or a group.
Kind ConversationKind
// Name is the name of a group as set; empty for none and for a direct
// conversation.
Name string
// DisplayName is what the list shows: the name of a group, the other
// user's display name in a direct conversation, or the display names of
// the other members of a group with no name.
DisplayName string
// Members are the current members, the asking actor included.
Members []UserRef
// LastMessage is the newest message; nil when there is none.
LastMessage *LastMessage
// LastActivity is when the newest message was sent, or when the
// conversation was started if it has none.
LastActivity time.Time
// Unread is true when the conversation has a message of someone else,
// not deleted, after the last one the actor has read.
Unread bool
// Muted is true when the actor muted the conversation (SPEC §7.15): the
// list dims it and puts it at the end, and it is not in the unread count
// of conversations.
Muted bool
// CanSend is false in a direct conversation whose other user is disabled
// (D32), as ConversationHeader.CanSend.
CanSend bool
// SeenUpToID is the last message the other member of a direct
// conversation has read; 0 for a group and when they have read none. It
// drives "Seen" for a client that shows the list.
SeenUpToID uint64
}
ConversationSummary is a conversation in the list of one user.
type EntityType ¶
type EntityType = store.EntityType
EntityType is the kind of thing an audit event is about. It is the store's type, so the web layer can name the kinds without importing the store.
type EventKind ¶ added in v1.2.0
type EventKind int
EventKind says what happened, as far as the ringing decision cares.
const ( // EventNotification is a notification of §7.9: a mention, a reply, an // assignment or an addition to a room. It always reaches the bell; the // decision is only about the sound and the browser notification. EventNotification EventKind = iota // EventPost is a new top-level post in a room. EventPost // EventMessage is a new message in a conversation. EventMessage )
type FailureCounter ¶ added in v1.1.0
type FailureCounter interface {
// Count returns how many failures of key in the namespace ns are newer
// than now minus window.
Count(ctx context.Context, ns, key string, now time.Time, window time.Duration) (int, error)
// Add records a failure of key in ns at now. The failures older than
// window are forgotten, and so are all but the latest keep ones.
Add(ctx context.Context, ns, key string, now time.Time, window time.Duration, keep int) error
// Clear forgets every failure of key in ns.
Clear(ctx context.Context, ns, key string) error
}
FailureCounter keeps the times of the failed logins per key, for LoginLimiter. The in-memory counter is the default; with several processes the counter of internal/cluster keeps them in Redis, so that a limit holds across processes (SPEC D41, §8.1). Every method may fail, and then the limiter fails open (see LoginLimiter). An implementation is safe for concurrent use.
type FeedPage ¶
type FeedPage struct {
// Posts are the posts of the page, newest first.
Posts []Post
// HasNext is true when older posts exist.
HasNext bool
// NextBefore is the beforeID that asks for the next page: the ID of the
// last post of this page. It is 0 when HasNext is false.
NextBefore uint64
}
FeedPage is a page of the feed of a room.
type Format ¶
Format says how the body of a post is shown. It is the store's type, so the web layer can name the values without importing the store.
const ( // FormatText is a body shown as written: escaped, line breaks kept, links // made clickable. FormatText Format = store.FormatText // FormatMarkdown is a body rendered as markdown. FormatMarkdown Format = store.FormatMarkdown )
The two formats of SPEC §7.3.
type Health ¶ added in v1.1.0
type Health struct {
// contains filtered or unexported fields
}
Health is the service behind the health check of the server (SPEC D40).
func (*Health) Check ¶ added in v1.1.0
Check reports whether the database answers a ping within ctx. It returns nil when it does. It has no actor and no permission check: it is not an action of a user, anyone who can reach the server may ask, and it reveals nothing but the answer. A failure is returned as the store made it.
type HistoryPage ¶
type HistoryPage struct {
// Messages are the messages of the page, oldest first.
Messages []Message
// HasOlder is true when older messages exist.
HasOlder bool
// NextBefore is the before that asks for the next, older page: the ID of
// the first (oldest) message of this page. It is 0 when HasOlder is false.
NextBefore uint64
}
HistoryPage is a page of the messages of a conversation.
type InvitationInfo ¶ added in v1.1.0
type InvitationInfo struct {
// Role is the role the user who signs up with it gets.
Role store.Role
// ExpiresAt is when the invitation stops working.
ExpiresAt time.Time
}
InvitationInfo is what a person who holds an invitation link may know about it before signing up.
type IssuedInvitation ¶
type IssuedInvitation struct {
// Token is the secret in the link, <base URL>/invite/<token>.
Token string
// Role is the role of the user who signs up with it.
Role store.Role
// ExpiresAt is when the invitation stops working.
ExpiresAt time.Time
}
IssuedInvitation is a new invitation: the token, which is shown once and never stored, and the facts about it.
type IssuedResetLink ¶ added in v1.2.0
type IssuedResetLink struct {
// Token is the secret in the link, <base URL>/reset/<token>.
Token string
// UserID is the user the link is for.
UserID uint64
// Username is the username of that user.
Username string
// ExpiresAt is when the link stops working.
ExpiresAt time.Time
}
IssuedResetLink is a new password reset link: the token, which is shown once and never stored, and the facts about it.
type IssuedSSHCode ¶ added in v1.2.0
type IssuedSSHCode struct {
// Code is the 8 characters of the code, upper case and without a dash.
Code string
// ExpiresAt is when the code stops working.
ExpiresAt time.Time
}
IssuedSSHCode is a new sign-in code: the code, which is shown once and never stored (only its SHA-256 is), and when it stops working.
func (IssuedSSHCode) Formatted ¶ added in v1.2.0
func (c IssuedSSHCode) Formatted() string
Formatted returns the code as it is shown to people: two groups of four characters with a dash, K7QF-9MZP.
type LastMessage ¶
type LastMessage struct {
// ID is the ID of the message.
ID uint64
// Author is the author.
Author UserRef
// Preview is the start of its text in one line (about 100 characters),
// the names of its files when it has no text, or MessageDeletedPreview.
Preview string
// Deleted is true when the message was deleted.
Deleted bool
// CreatedAt is when the message was sent.
CreatedAt time.Time
}
LastMessage is the newest message of a conversation, for the list.
type LoginLimiter ¶
type LoginLimiter struct {
// contains filtered or unexported fields
}
LoginLimiter counts the failed logins per username and per client address in a sliding window and says when a further attempt must wait (SPEC §7.1). The counting is done by a FailureCounter: in memory by default, so that a restart forgets the failures, or in Redis when several processes share a limit. When the counter fails, the limiter fails open: it logs a warning, allows the attempt and counts nothing, because an outage of Redis must not lock everybody out (SPEC §8.1); the password is still checked. It is safe for concurrent use. Make it with NewLoginLimiter or NewLoginLimiterOn.
func NewLoginLimiter ¶
func NewLoginLimiter(clk clock.Clock) *LoginLimiter
NewLoginLimiter makes a limiter that blocks after 5 failures within 15 minutes, counted in memory on clk. A nil clk is the real clock.
func NewLoginLimiterOn ¶ added in v1.1.0
func NewLoginLimiterOn(clk clock.Clock, counter FailureCounter, logger *slog.Logger) *LoginLimiter
NewLoginLimiterOn is NewLoginLimiter with the counter that keeps the failures and the logger for the failures of the counter. A nil counter is the in-memory one, a nil clk the real clock and a nil logger discards the log.
func (*LoginLimiter) Allow ¶
func (l *LoginLimiter) Allow(ctx context.Context, username, ip string) bool
Allow reports whether a login attempt for username from the address ip may go on. It is false when either already failed the maximum number of times within the window. An empty ip is not counted. When the counter fails it is true.
func (*LoginLimiter) AllowAddr ¶ added in v1.2.0
func (l *LoginLimiter) AllowAddr(ctx context.Context, ip string) bool
AllowAddr reports whether a client address may go on, for the attempts that have no username to count, such as an SSH connection that offers keys. It is false when the address already failed the maximum number of times within the window (the failures of logins from the same address count too). An empty address is allowed. When the counter fails it is true.
func (*LoginLimiter) Fail ¶
func (l *LoginLimiter) Fail(ctx context.Context, username, ip string)
Fail records a failed login attempt for username from the address ip.
type LoginResult ¶ added in v1.1.0
type LoginResult struct {
// Token is the session token, shown once and never stored (only its
// SHA-256 is). It is empty when Pending is set.
Token string
// User is the user who logged in.
User User
// ExpiresAt is when the session ends if it is not used again.
ExpiresAt time.Time
// Pending is set when the password was right and the user has to type an
// SSH code before a session starts (SPEC §7.16): no session exists yet.
// Only a SessionBrowser login gets it; the API login asks for the code in
// the same call.
Pending *PendingLogin
// Next is the path stored with the pending login that CompleteLogin
// finished; empty otherwise and for the home page.
Next string
}
LoginResult is what a successful login returns, or, with Pending set, what a login that waits for the SSH code returns instead of a session.
type MarkUnread ¶ added in v1.2.0
type MarkUnread = store.MarkUnread
MarkUnread says what the unread count of a room counts (SPEC §7.17). It is the store's type.
type Member ¶
type Member struct {
// UserID is the ID of the user.
UserID uint64
// Username is the username of the user.
Username string
// DisplayName is the name shown to other people.
DisplayName string
// AvatarKey is the key of the user's avatar, for AvatarPath; empty when
// the user has none.
AvatarKey string
// AddedBy is the ID of the member who added the user; nil when the user
// joined by themselves or made the room.
AddedBy *uint64
// AddedByDisplayName is the display name of AddedBy; empty when AddedBy
// is nil.
AddedByDisplayName string
// AddedByUsername is the username of AddedBy; empty when AddedBy is nil.
AddedByUsername string
// JoinedAt is when the user became a member.
JoinedAt time.Time
}
Member is a member of a room as the services show it.
type Message ¶
type Message struct {
// ID is the ID of the message. Newer messages have larger IDs.
ID uint64
// Kind is MessageText, or MessageCall for the entry of a call, whose
// author is the caller, which has no body, files or reactions and which
// nobody can edit, delete or react to.
Kind MessageKind
// Call is the call of a call entry, as the asking user reads it; nil for a
// text message.
Call *CallEntry
// ConversationID is the conversation of the message.
ConversationID uint64
// Author is the author.
Author UserRef
// Body is the text as written; empty for a deleted message.
Body string
// CreatedAt is when the message was sent.
CreatedAt time.Time
// EditedAt is when the author last edited the message; nil if never.
EditedAt *time.Time
// Deleted is true for a deleted message, which shows as "message deleted".
Deleted bool
// ReplyTo is the quoted message; nil when the message is no reply.
ReplyTo *MessageQuote
// Attachments are the files of the message; empty for a deleted message.
Attachments []AttachmentView
// Reactions are the emoji that people put on the message, in the order the
// emoji were first used; empty for a deleted message.
Reactions []ReactionCount
// CanEdit is true when the asking actor may edit the message: its author,
// if it is not deleted.
CanEdit bool
// CanDelete is true when the asking actor may delete the message: its
// author, if it is not deleted.
CanDelete bool
// CanReact is true when the asking actor may react to the message: it is
// not deleted.
CanReact bool
}
Message is a private message as the services show it to one actor.
func (Message) Quote ¶
func (m Message) Quote() MessageQuote
Quote returns the message as a quote, which is what a reply to it shows: its author and the start of its text (or MessageDeletedPreview).
type MessageInput ¶
type MessageInput struct {
// Body is the text: at most 4,000 characters, trimmed. It may be empty
// when the message has an attachment.
Body string
// ReplyToID is the ID of the earlier message of the same conversation
// that this one answers; 0 for none.
ReplyToID uint64
// Uploads are the files of the message, as Messages.Upload returned them.
Uploads []Upload
}
MessageInput is what a person writes in the composer of a conversation.
type MessageKind ¶ added in v1.2.0
type MessageKind = store.MessageKind
MessageKind says whether a message is text or the entry of a call. It is the store's type.
const ( // MessageText is a message that a person wrote. MessageText MessageKind = store.MessageText // MessageCall is the entry that a finished call leaves in the conversation. MessageCall MessageKind = store.MessageCall )
The two kinds of message (SPEC §7.18).
type MessageQuote ¶
type MessageQuote struct {
// ID is the ID of the quoted message.
ID uint64
// Author is the author of the quoted message.
Author UserRef
// Preview is the start of its text in one line, the names of its files
// when it has no text, or MessageDeletedPreview.
Preview string
// Deleted is true when the quoted message was deleted.
Deleted bool
}
MessageQuote is the message that a message replies to, as a quote.
type MessageSearchPage ¶ added in v1.2.0
type MessageSearchPage struct {
// Query is the text that was searched, as typed.
Query string
// Results are the results of the page, newest first.
Results []MessageSearchResult
// HasMore is true when older results follow this page.
HasMore bool
// NextBefore is the before that asks for the next, older page: the ID of
// the oldest message of this page. It is 0 when HasMore is false.
NextBefore uint64
}
MessageSearchPage is a page of the results of a search of private messages.
type MessageSearchResult ¶ added in v1.2.0
type MessageSearchResult struct {
// MessageID is the ID of the message.
MessageID uint64
// ConversationID is the conversation of the message.
ConversationID uint64
// ConversationKind says whether the conversation is direct or a group.
ConversationKind ConversationKind
// ConversationTitle is the title of the conversation as the searching
// user sees it: the name of a group, else the display names of the other
// members.
ConversationTitle string
// Author is the author of the message.
Author UserRef
// CreatedAt is when the message was sent.
CreatedAt time.Time
// Snippet is the matching text, escaped, with the matches in <mark>; it
// holds no other HTML.
Snippet template.HTML
// Segments are Snippet as plain text in pieces, for a client that shows
// no HTML (see SearchResult.Segments).
Segments []SnippetSegment
}
MessageSearchResult is a private message found by a search.
type Messages ¶
type Messages struct {
// contains filtered or unexported fields
}
Messages is the service of private conversations and messages (SPEC §7.11, D32). Make it with NewMessages. It is safe for concurrent use. Only the members of a conversation use it: anyone else, admins included, and a member who left, get TagNotFound. It writes no audit events and makes no notifications.
func NewMessages ¶
func NewMessages(st *store.Store, clk clock.Clock, fs *files.Store, cfg MessagesConfig, pub Publisher) *Messages
NewMessages makes the service. The clock times the edits, deletions and departures; fs holds the files of the attachments; cfg has their limits. pub receives the live events of the changes, after they are committed; nil publishes nothing.
func (*Messages) AddMembers ¶
func (m *Messages) AddMembers(ctx context.Context, actor Actor, convID uint64, userIDs []uint64) error
AddMembers adds users to a group. A user who is a member already is left alone; one who left comes back and sees the whole history (D32). It fails with TagNotFound unless the actor is a member, with TagInvalidInput, with the messages under FieldUsers, for a direct conversation, an empty list, a user who does not exist or is disabled, and more than 50 members. The conversation hears conversation.updated and every member, the added ones too, conversation.changed; nothing is published when nobody was added.
func (*Messages) Attachment ¶
func (m *Messages) Attachment(ctx context.Context, actor Actor, attachmentID uint64) (AttachmentView, io.ReadSeekCloser, error)
Attachment returns an attachment of a message and its file for download. Only the members of the conversation may: a missing attachment, one of a deleted message and one of a conversation the actor is no member of fail with TagNotFound. The caller closes the file.
func (*Messages) Conversation ¶
func (m *Messages) Conversation(ctx context.Context, actor Actor, convID uint64) (ConversationHeader, error)
Conversation returns the header of a conversation: its title and its members with the last message each has read. It fails with TagNotFound unless the actor is a member.
func (*Messages) Conversations ¶
Conversations returns the conversations the actor is a member of, the most recent activity first. It runs a few queries, however many conversations there are. An actor with no ID fails with TagUnauthenticated.
func (*Messages) Delete ¶
Delete deletes a message: it stays in its place as "message deleted" with no body, attachments or reactions (D32), and the files of its attachments are removed from disk after the change is committed. Only the author may: another member gets TagForbidden. A message that does not exist, one of a conversation the actor is no member of and one that is deleted already fail with TagNotFound. The conversation hears message.deleted and every member conversation.changed.
func (*Messages) DiscardUploads ¶
DiscardUploads removes the files of uploads that no message took, for a caller that made them with Upload and then failed before it could pass them to Send. A file that an attachment already uses is left alone. An actor with no ID does nothing. Failures are logged, never returned.
func (*Messages) Edit ¶
func (m *Messages) Edit(ctx context.Context, actor Actor, msgID uint64, body string) (Message, error)
Edit changes the body of a message and sets its EditedAt. Only the author may: another member gets TagForbidden. A message that does not exist, one of a conversation the actor is no member of and a deleted message fail with TagNotFound. The body is trimmed, at most 4,000 characters, and empty only when the message has attachments; otherwise Edit fails with TagInvalidInput with the message under FieldBody. It does nothing, and publishes nothing, when the body stays. The conversation hears message.updated and every member conversation.changed.
func (*Messages) ForgetStaged ¶ added in v1.1.0
ForgetStaged ends the notes of uploads that StagedUploads returned and that Send took or refused, as Posts.ForgetStaged does. Failures are logged, never returned. An actor with no ID does nothing.
func (*Messages) GroupMentionCount ¶ added in v1.2.0
func (m *Messages) GroupMentionCount(ctx context.Context, actor Actor, convID uint64, body string) (int, error)
GroupMentionCount says how many people the group mentions of a message body would notify if the actor sent it in the conversation: the other members except those who turned the group mentions off or ignore them there, all of them for @room and @all, those online now for @here. It is 0 when the body holds no group mention, and always 0 in a direct conversation, which has none. A page asks it before a message is sent, to put the question "This will notify 14 people. Send anyway?" when it is above GroupMentionConfirmAbove. A conversation the actor is no member of fails with TagNotFound, a disabled or missing account with TagUnauthenticated.
func (*Messages) History ¶
func (m *Messages) History(ctx context.Context, actor Actor, convID, before uint64, limit int) (HistoryPage, error)
History returns a page of the messages of a conversation, oldest first within the page. before 0 starts from the newest message; another value returns the messages older than that ID. limit is the page size: 50 when it is 0 or less, at most 100. Deleted messages are included, as deleted. It fails with TagNotFound unless the actor is a member.
func (*Messages) Leave ¶
Leave takes the actor out of a group. The group stays for the others, and the actor no longer reads it. It fails with TagNotFound unless the actor is a member, with TagInvalidInput for a direct conversation, which nobody leaves. The conversation hears conversation.updated; the members who stay, and the one who left, hear conversation.changed.
func (*Messages) MarkRead ¶
MarkRead marks the conversation read up to the message upToID, which must be a message of the conversation: the last read message becomes the larger of the current one and upToID, so it never moves back. It fails with TagNotFound unless the actor is a member, and with TagInvalidInput, with the message under FieldMessage, for a message that is not in the conversation. When the last read message moved, conversation.read is published to the conversation (it drives "Seen") and to the actor.
func (*Messages) Message ¶
Message returns one message as the actor sees it, deleted or not. It fails with TagNotFound for a message that does not exist and for one of a conversation the actor is no member of (admins included), or left.
func (*Messages) OpenDirect ¶ added in v1.1.0
func (m *Messages) OpenDirect(ctx context.Context, actor Actor, userID uint64) (uint64, bool, error)
OpenDirect returns the ID of the direct conversation between the actor and the user, and makes it when there is none (SPEC D28: one for each pair), and says whether this call made it: created is false when the conversation existed, also when another call made it at the same time. Called at the same time for the same pair it still gives one conversation. It fails with TagInvalidInput, with the message under FieldUser, when the user is the actor, does not exist or is disabled. Both users hear of a new conversation as conversation.changed.
func (*Messages) React ¶
func (m *Messages) React(ctx context.Context, actor Actor, msgID uint64, emoji string) (Reactions, error)
React puts the emoji on the message as the actor, or takes it off when the actor put it there already, and returns the reactions of the message as the actor sees them. A message that does not exist, one of a conversation the actor is no member of and a deleted message fail with TagNotFound. An emoji that is not one fails with TagInvalidInput, with the message under FieldEmoji (SPEC §7.4). The conversation hears message.reaction.
func (*Messages) Rename ¶
Rename sets the name of a group; an empty name removes it. The name is trimmed, at most 80 characters. It fails with TagNotFound unless the actor is a member, with TagInvalidInput, with the message under FieldName, for a direct conversation or a name that is too long. The conversation hears conversation.updated and every member conversation.changed; nothing is published when the name stays.
func (*Messages) ResolveUsernames ¶
func (m *Messages) ResolveUsernames(ctx context.Context, actor Actor, usernames []string) ([]uint64, error)
ResolveUsernames returns the IDs of the users with these usernames, in the order given, for a form where people are named. Names are trimmed and lower cased, empty ones and repeats are dropped, and the actor may be among them. It fails with TagInvalidInput, with the message under FieldUsers, when no name is left, when there are more than 50, or when a name belongs to no user or to a disabled one (the message lists those names). An actor with no ID fails with TagUnauthenticated.
func (*Messages) Search ¶ added in v1.2.0
func (m *Messages) Search(ctx context.Context, actor Actor, query string, before uint64) (MessageSearchPage, error)
Search finds the private messages that match the query in the conversations the actor is a member of now, newest first, 30 a page (SPEC §7.11, D56). Admins are no exception, and neither is a member who left: a conversation the actor is no member of has no results. The messages from before the actor joined a group are searched, as the conversation shows them. before 0 starts from the newest message; another value returns the messages older than that ID, as the NextBefore of the page before it.
The query is parsed by ParseQuery, so words and phrases work as in SPEC §7.8 (a word matches as a prefix, a phrase in double quotes exactly), but the filters do not: a query with no word, which includes one made of filters only, fails with TagInvalidInput and the message "Type a word to search the messages."; a filter next to words fails with TagInvalidInput and a message that says filters do not work here (quoted, the same text is plain words). The message is under FieldQuery in the metadata "fields". A malformed date fails as ParseQuery says. An actor whose account is disabled or missing fails with TagUnauthenticated.
func (*Messages) Send ¶
func (m *Messages) Send(ctx context.Context, actor Actor, convID uint64, in MessageInput) (Message, error)
Send writes a message in a conversation as the actor and marks the conversation read up to it. The body is trimmed, at most 4,000 characters; it may be empty when there are uploads. in.ReplyToID must be a message of the same conversation that is not deleted. in.Uploads become the attachments (the limits are those of posts); when Send fails for any reason their files are removed from disk. It fails with TagNotFound unless the actor is a member, and with TagInvalidInput, with all the problems in the metadata "fields", for input that breaks a rule and in a direct conversation whose other user is disabled (D32). The conversation hears message.created, and every member conversation.changed.
func (*Messages) SetReaction ¶ added in v1.1.0
func (m *Messages) SetReaction(ctx context.Context, actor Actor, msgID uint64, emoji string, present bool) (Reactions, error)
SetReaction puts the emoji on the message as the actor (present true) or takes it off (present false) and returns the reactions of the message as the actor sees them. Unlike React it is idempotent: putting an emoji that is there, or taking off one that is not, changes nothing, and nothing is published then. The permissions and the errors are those of React.
func (*Messages) StagedUploads ¶ added in v1.1.0
StagedUploads turns the IDs that POST /uploads returned (Posts.UploadStaged) into the uploads that Send takes: a file is the same kind of thing for a post and a message, and one staged upload is attached to one of them. The permissions and the errors are those of Posts.StagedUploads: only the person who uploaded a file gets it back, and an ID that is not theirs fails the whole call with TagInvalidInput and the message under FieldAttachments. An actor with no ID fails with TagUnauthenticated. The call changes nothing; ForgetStaged ends the notes after Send.
func (*Messages) StartDirect ¶
StartDirect returns the ID of the direct conversation between the actor and the user, and makes it when there is none (SPEC D28: one for each pair). It is OpenDirect without the answer whether the conversation is new, and fails as OpenDirect does.
func (*Messages) StartGroup ¶
func (m *Messages) StartGroup(ctx context.Context, actor Actor, userIDs []uint64, name string) (uint64, error)
StartGroup makes a group of the actor and the users and returns its ID. At least two other users are needed (the actor and repeated users are not counted), at most 50 members including the actor; none may be disabled. The name is optional, trimmed, at most 80 characters. It fails with TagInvalidInput, with the messages under FieldUsers and FieldName. Every member hears of the new group as conversation.changed.
func (*Messages) Summary ¶ added in v1.1.0
func (m *Messages) Summary(ctx context.Context, actor Actor, convID uint64) (ConversationSummary, error)
Summary returns one conversation as the list shows it to the actor: the member list, the last message, whether it is unread, whether the actor can send and, in a direct conversation, how far the other user has read. It fails with TagNotFound unless the actor is a member (admins included, and a member who left).
func (*Messages) UnreadCount ¶
UnreadCount returns the number of conversations of the actor that have a message of someone else, not deleted, after the last one the actor has read (D32), with one query. An actor with no ID fails with TagUnauthenticated.
func (*Messages) Upload ¶
func (m *Messages) Upload(ctx context.Context, actor Actor, name string, r io.Reader) (Upload, error)
Upload stores a file that a person attached to the composer and returns what Send needs to attach it (MessageInput.Uploads). The limits and the cleaning of the name are those of Posts.Upload. An actor with no ID fails with TagUnauthenticated, a file over the limit with TagTooLarge. An upload that no message takes is left on disk: callers pass every upload to Send, which removes the files when it fails.
type MessagesConfig ¶
type MessagesConfig = PostsConfig
MessagesConfig holds the settings of the messages service; it has the fields of PostsConfig, and the same defaults.
type Notice ¶ added in v1.2.0
type Notice struct {
// Kind is the kind of the live event: live.KindNotificationCreated,
// live.KindPostCreated or live.KindMessageCreated.
Kind string
// ID identifies the event for the election of the tab that rings: "n<id>"
// for a notification, "p<id>" for a post, "m<id>" for a message.
ID string
// Text is the text of the browser notification, for example "Bob
// mentioned you in #general".
Text string
// Author is the user whose action it is.
Author UserRef
// PlaceName is the name of the room, or the title of the conversation.
PlaceName string
// RoomID is the room, 0 for a conversation.
RoomID uint64
// ConversationID is the conversation, 0 for a room.
ConversationID uint64
// PostID is the post or comment concerned; 0 when none.
PostID uint64
// RootID is the top-level post of the thread of PostID; 0 when none.
RootID uint64
// MessageID is the message concerned; 0 when none.
MessageID uint64
// NotificationKind is the kind of the notification of a
// live.KindNotificationCreated event; empty for the others.
NotificationKind NotificationKind
// Ring, Sound and Browser are the decision of the server for this user,
// copied from the event.
Ring bool
// Sound is the name of the sound to play; empty for none.
Sound SoundName
// Browser is true when the browser notification is wanted.
Browser bool
}
Notice is what the page or the client of a user needs to ring for one event of the user's stream (SPEC §7.15): who did what and where, never the body.
type Notification ¶
type Notification struct {
// ID is the ID of the notification; a larger ID is a newer one.
ID uint64
// Kind says why the user is notified.
Kind NotificationKind
// Actor is the user whose action caused it.
Actor UserRef
// RoomID and RoomName are the room of the notification.
RoomID uint64
RoomName string
// PostID is the post or comment of a mention, a reply or an assignment; 0
// for added_to_room. RootID is the top-level post of its thread (PostID
// itself for a top-level post), so that a link is /posts/<RootID>#post-<PostID>.
PostID uint64
RootID uint64
// TaskID and TaskTitle are the task of an assignment; 0 and empty for the
// other kinds.
TaskID uint64
TaskTitle string
// Others is the number of other people who replied within the minute that
// the notification took them in: "Bob and 2 others replied"; 0 for a
// single actor and for the kinds other than reply.
Others int
// Read is true when the user has read the notification; ReadAt is when.
Read bool
ReadAt *time.Time
// CreatedAt is when the notification was made.
CreatedAt time.Time
}
Notification is a notification of the asking user, with what a page needs to show it and to link to what it is about.
type NotificationKind ¶
type NotificationKind = store.NotificationKind
NotificationKind says why a user is notified (SPEC §7.9). It is the store's type, so the web layer can name the kinds without importing the store.
const ( // NotificationMention is an "@username" in a post or comment. NotificationMention NotificationKind = store.NotificationMention // NotificationReply is a comment made directly under the user's post or // comment. NotificationReply NotificationKind = store.NotificationReply // NotificationAssigned is a task newly assigned to the user. NotificationAssigned NotificationKind = store.NotificationAssigned // NotificationAddedToRoom is the user's addition to a room by someone // else. NotificationAddedToRoom NotificationKind = store.NotificationAddedToRoom // NotificationGroupMention is an @room, @all or @here that reached the // user (SPEC §7.15). It is shown as a mention. NotificationGroupMention NotificationKind = store.NotificationGroupMention // NotificationKeyword is a keyword of the user found in a post or comment // (SPEC §7.15). It is shown as a mention. NotificationKeyword NotificationKind = store.NotificationKeyword )
The kinds of notification.
type NotificationPage ¶
type NotificationPage struct {
// Notifications are the notifications of the page, newest first.
Notifications []Notification
// HasNext is true when older notifications exist.
HasNext bool
// NextBefore is the before that asks for the next page: the ID of the last
// notification of this page. It is 0 when HasNext is false.
NextBefore uint64
}
NotificationPage is a page of the notifications of a user.
type Notifications ¶
type Notifications struct {
// contains filtered or unexported fields
}
Notifications is the service of the notifications of a user (SPEC §7.9). A user sees only their own. Make it with NewNotifications. It is safe for concurrent use. The notifications themselves are made by the services of the actions that cause them, in the transaction of the action.
func NewNotifications ¶
func NewNotifications(st *store.Store, pub Publisher) *Notifications
NewNotifications makes the service. pub receives the live events of the changes, after they are committed; nil publishes nothing.
func (*Notifications) List ¶
func (n *Notifications) List(ctx context.Context, actor Actor, before uint64, limit int) (NotificationPage, error)
List returns a page of the actor's notifications, newest first. before 0 starts from the newest; another value returns the notifications older than that ID. limit is the page size: 30 when it is 0 or less, at most 100. Notifications of a room that the actor can no longer read are left out (SPEC D29, D30). An actor with no ID fails with TagUnauthenticated.
func (*Notifications) MarkRead ¶
MarkRead marks as read the actor's unread notifications with an ID up to upToID; newer ones stay unread. It publishes notification.read to the actor when it changed something, and room.unread for each room whose mention badge it changed (SPEC §7.17). An actor with no ID fails with TagUnauthenticated.
func (*Notifications) UnreadCount ¶
UnreadCount returns the number of unread notifications of the actor, not counting those of a room that the actor can no longer read. An actor with no ID fails with TagUnauthenticated.
type NotifyLevel ¶ added in v1.2.0
type NotifyLevel = store.NotifyLevel
NotifyLevel says what notifies a user, globally or in one place (SPEC §7.15). It is the store's type.
type PasswordChange ¶ added in v1.2.0
type PasswordChange struct {
// CurrentPassword is the password the person has now.
CurrentPassword string
// NewPassword is the password to set: at least 12 characters, and not the
// current one.
NewPassword string
// ClientIP is the address of the client, for the login limiter.
ClientIP string
}
PasswordChange is what a person gives to change their password.
type PendingLogin ¶ added in v1.2.0
type PendingLogin struct {
// Token is the secret of the cookie clowder_pending. It is shown once and
// never stored (only its SHA-256 is); PendingLoginInfo leaves it empty.
Token string
// Username is the username of the user, for the ssh command shown.
Username string
// ExpiresAt is when the pending login stops working.
ExpiresAt time.Time
// Next is the local path to go to after the login; empty for the home
// page.
Next string
}
PendingLogin is a login that waits for the SSH code (SPEC §7.16, D53).
type PlaceKind ¶ added in v1.2.0
type PlaceKind int
PlaceKind says what kind of place an event happened in (SPEC §7.15).
type PlaceNotify ¶ added in v1.2.0
type PlaceNotify = store.PlaceNotify
PlaceNotify is what a user chose to be notified about in one place (SPEC §7.15). It is the store's type.
type PlacePrefs ¶ added in v1.2.0
type PlacePrefs struct {
// Place is the room or conversation.
Place PlaceRef
// Direct is true for a conversation of two, which has no group mentions
// to ignore.
Direct bool
// Notify is what the actor is notified about in the place.
Notify PlaceNotify
// Sound is the choice of the sound in the place.
Sound PlaceSound
// IgnoreGroupMentions is true when @room, @all and @here are ignored in
// the place (used from step 18.4).
IgnoreGroupMentions bool
// MarkUnread is what the unread count of a room counts; MarkUnreadAll
// for a conversation, which always counts all its messages.
MarkUnread MarkUnread
// Muted is true when the place is muted.
Muted bool
}
PlacePrefs are the notification preferences of the actor in one place (SPEC §7.15). A place without saved preferences has the defaults.
func (PlacePrefs) IsDefault ¶ added in v1.2.0
func (p PlacePrefs) IsDefault() bool
IsDefault reports whether the preferences are all defaults.
type PlaceRef ¶ added in v1.2.0
type PlaceRef struct {
// RoomID is the room; 0 for a conversation.
RoomID uint64
// ConversationID is the conversation; 0 for a room.
ConversationID uint64
}
PlaceRef names a place: a room or a conversation. Exactly one of the IDs is not 0.
func ConversationRef ¶ added in v1.2.0
ConversationRef is the PlaceRef of a conversation.
type PlaceSound ¶ added in v1.2.0
type PlaceSound = store.PlaceSound
PlaceSound is the choice of the sound in one place. It is the store's type.
type PlaceUpdate ¶ added in v1.2.0
type PlaceUpdate struct {
// Notify is the new "Notify me about".
Notify *PlaceNotify
// Sound is the new sound choice.
Sound *PlaceSound
// IgnoreGroupMentions is the new value of "Ignore @room, @all and @here".
IgnoreGroupMentions *bool
// MarkUnread is the new "Mark as unread"; rooms only.
MarkUnread *MarkUnread
// Muted is the new value of the mute.
Muted *bool
}
PlaceUpdate is a change of the preferences of a place. A nil field keeps the value.
type Post ¶
type Post struct {
// ID is the ID of the post. Newer posts have larger IDs.
ID uint64
// RoomID is the ID of the room of the post.
RoomID uint64
// RoomName is the name of the room of the post.
RoomName string
// Author is the author; the zero value for a deleted post.
Author UserRef
// Format says how the body is shown.
Format Format
// Body is the text as written, for the edit form; empty for a deleted post.
Body string
// HTML is the body rendered safely (SPEC D9); empty for a deleted post.
HTML template.HTML
// Tags are the normalized tags, in the order the author gave them; empty
// for a deleted post.
Tags []string
// Attachments are the files of the post, in the order they were attached;
// empty for a deleted post.
Attachments []AttachmentView
// Tasks are the tasks of the post, oldest first, with the column they are
// in; empty for a deleted post.
Tasks []TaskCard
// CommentCount is the number of comments in the thread of the post, at any
// depth, not counting deleted ones. It is 0 for a comment.
CommentCount int
// Reactions are the emoji that people put on the post, in the order the
// emoji were first used, with their counts; empty for a deleted post.
Reactions []ReactionCount
// ParentID is the ID of the post or comment that this comment answers; 0
// for a top-level post.
ParentID uint64
// RootID is the ID of the top-level post of the thread of this comment; 0
// for a top-level post. For a reply to a top-level post it equals
// ParentID.
RootID uint64
// IsComment is true for a comment and false for a top-level post.
IsComment bool
// CreatedAt is when the post was written.
CreatedAt time.Time
// EditedAt is when the author last edited the post; nil if never.
EditedAt *time.Time
// Deleted is true for a post that stays only because it has replies (D21).
Deleted bool
// CanEdit is true when the asking actor may edit the post: its author, if
// the post is not deleted.
CanEdit bool
// CanDelete is true when the asking actor may delete the post: its author
// or an admin, if the post is not deleted.
CanDelete bool
// CanReact is true when the asking actor may react to the post: a member
// of its room, if the post is not deleted.
CanReact bool
// Following is true when the asking actor follows the post, so that its
// comments notify them (SPEC §7.15). Only a top-level post can be
// followed: for a comment it says whether the actor follows the
// top-level post of its thread.
Following bool
}
Post is a post as the services show it to one actor.
type PostInput ¶
type PostInput struct {
// Format is how the body is shown: FormatText or FormatMarkdown.
Format Format
// Body is the text of the post: at most 20,000 characters, not empty.
// Whitespace at its end is dropped.
Body string
// Tags are the labels of the post, as typed (ParseTags splits the field of
// the editor). Each is normalized (SPEC §7.7); at most 10 remain.
Tags []string
// Uploads are the new files of the post, as Posts.Upload returned them.
// They are attached to the post. The body may be empty when the post has
// at least one attachment or one task.
Uploads []Upload
// KeepAttachments is used by Edit only: the IDs of the attachments of the
// post that stay. Every other attachment of the post is removed, so a nil
// list removes them all. An ID that is not an attachment of the post makes
// the input invalid.
KeepAttachments []uint64
// Tasks are the tasks of the post (D17), at most 20. Create and Reply add
// them to the end of the first column of the board. Edit matches them by
// ID: the tasks of the post that are not listed are deleted, the listed
// ones change, those with ID 0 are added; so a nil list deletes them all.
// A task whose ID is not a task of the post makes the input invalid.
Tasks []TaskInput
}
PostInput is what a person types in the editor when they write or edit a post.
type Posts ¶
type Posts struct {
// contains filtered or unexported fields
}
Posts is the service of posts, their tags and their feeds (SPEC §7.3, §7.7). Make it with NewPosts. It is safe for concurrent use.
func NewPosts ¶
func NewPosts(st *store.Store, clk clock.Clock, md *markdown.Renderer, fs *files.Store, cfg PostsConfig, pub Publisher) *Posts
NewPosts makes the service. The clock times the edits and deletions; the renderer makes the HTML of the bodies; fs holds the files of the attachments; cfg has the limits of the attachments. pub receives the live events of the changes, after they are committed; nil publishes nothing.
func (*Posts) Attachment ¶
func (p *Posts) Attachment(ctx context.Context, actor Actor, id uint64) (AttachmentView, io.ReadSeekCloser, error)
Attachment returns an attachment and its file for download. The room of its post must be readable by the actor: a missing attachment, one of a deleted post, and a post in a room that the actor may not read fail with TagNotFound. The caller closes the file.
func (*Posts) Create ¶
Create writes a post in a room and its audit event post.created (the event never holds the body). Only members of the room post: a room that the actor may not read fails with TagNotFound, a visible room that the actor has not joined with TagForbidden. It fails with TagInvalidInput, with all the problems in the metadata "fields", for input that breaks a rule. in.Uploads become the attachments of the post; when Create fails for any reason, their files are removed from disk. It saves the post's mentions (the users named as @username who are enabled and can read the room, D26) and, in the same transaction, notifies them and the users assigned to its tasks, never the actor; a user gets at most one notification (SPEC D30).
func (*Posts) Delete ¶
Delete deletes a post or comment and writes post.deleted (entity type comment for a comment) with {"kept": bool}. The author or an admin who can read the room may; another reader gets TagForbidden, and a room that the actor may not read, a missing post and a deleted post fail with TagNotFound. A post or comment with replies stays as a deleted placeholder with no body, tags, reactions, mentions or attachments; one without replies disappears with everything on it (D21). When a comment disappears and its parent is a deleted placeholder with no other replies, the parent disappears too, and so on up the thread, up to the top-level post; those cleanups write no events. The files of the attachments that go are removed from disk after the change is committed. The notifications of the post and of its tasks are deleted with it, a kept placeholder included.
func (*Posts) DiscardUploads ¶
DiscardUploads removes the files of uploads that no post took, for a caller that made them with Upload and then failed before it could pass them to Create, Reply or Edit (which remove the files of their own failures). A file that an attachment already uses is left alone. An actor with no ID does nothing. Failures are logged, never returned.
func (*Posts) Edit ¶
Edit changes the body, the format, the tags and the attachments of a post or comment and writes post.edited (entity type comment for a comment) with only what changed (for the body that it changed and its length, never the text; for the attachments the names added and removed). The attachments listed in in.KeepAttachments stay, in.Uploads are added and the others are removed, their files from disk after the change is committed; when Edit fails for any reason, the files of in.Uploads are removed from disk. It does nothing, and writes no event, when nothing changed. Only the author may: another reader gets TagForbidden. A room that the actor may not read, a missing post and a deleted post fail with TagNotFound. It fails with TagInvalidInput, with all the problems in the metadata "fields", for input that breaks a rule. When the body or the format changed it rebuilds the mentions and notifies only the users newly mentioned, and it notifies the users newly assigned to a task of the post (not those who stay on it).
func (*Posts) Feed ¶
func (p *Posts) Feed(ctx context.Context, actor Actor, roomID, beforeID uint64, limit int) (FeedPage, error)
Feed returns a page of the top-level posts of a room that the actor may read, newest first. beforeID 0 starts from the newest post; another value returns the posts older than it. limit is the page size: 30 when it is 0 or less, at most 100. A deleted post that has replies appears as deleted. For a room that the actor may not read it fails with TagNotFound.
func (*Posts) Follow ¶ added in v1.2.0
Follow makes the actor follow a post, so that every comment in its thread notifies them with *Threads I follow* (SPEC §7.15). On a comment it acts on the top-level post of its thread. It is idempotent, and it brings back a follow that the actor removed. It writes no audit event (a follow is not among the actions of §7.10) and publishes nothing. A post that the actor may not read, a missing post and a deleted one fail with TagNotFound; a disabled or missing account fails with TagUnauthenticated. A visible room can be read, and so its posts followed, without being a member.
func (*Posts) ForgetStaged ¶ added in v1.1.0
ForgetStaged ends the notes of uploads that StagedUploads returned and that a post took or refused: the person has to upload a file again to attach it to another post. Failures are logged, never returned. An actor with no ID does nothing.
func (*Posts) Get ¶
Get returns a post or comment of a room that the actor may read; a deleted one that was kept comes back with Deleted set. A missing post and a room that the actor may not read fail with TagNotFound.
func (*Posts) GroupMentionCount ¶ added in v1.2.0
func (p *Posts) GroupMentionCount(ctx context.Context, actor Actor, roomID uint64, format Format, body string) (int, error)
GroupMentionCount says how many people the group mentions of a body would notify if the actor posted it in the room: the members of the room except the actor and those who turned the group mentions off or ignore them there, all of them for @room and @all, those online now for @here. It is 0 when the body holds no group mention. A page asks it before a post or comment is written, to put the question "This will notify 14 people. Send anyway?" when it is above GroupMentionConfirmAbove. The permission is that of posting: a room the actor may not read fails with TagNotFound, a visible room the actor has not joined with TagForbidden, a disabled or missing account with TagUnauthenticated.
func (*Posts) Preview ¶
func (p *Posts) Preview(_ context.Context, actor Actor, format Format, body string) (template.HTML, error)
Preview renders a body the way a post would show it, for the preview of the editor. Any logged-in actor may preview; an actor with no ID fails with TagUnauthenticated. It fails with TagInvalidInput, with the problems in the metadata "fields", for a format that is neither text nor markdown, a body that is not valid text and a body longer than 20,000 characters. An empty body previews as an empty result. A mention is shown as written, not as a link: only the mentions a post has saved become links.
func (*Posts) Reply ¶
func (p *Posts) Reply(ctx context.Context, actor Actor, parentID uint64, in PostInput) (Post, error)
Reply writes a comment under the post or comment parentID, in the thread of the same top-level post, and its audit event post.created with the entity type comment (the event never holds the body). Only members of the room reply: a room that the actor may not read, a missing parent and a parent that is deleted fail with TagNotFound, a visible room that the actor has not joined with TagForbidden. It fails with TagInvalidInput, with all the problems in the metadata "fields", for input that breaks a rule. in.Uploads become the attachments of the comment; when Reply fails for any reason, their files are removed from disk. It saves the mentions and notifies as Create does, and also the author of the parent (a reply); of one user the notification of the highest rank is made: assigned, then reply, then mention (SPEC D30).
func (*Posts) SetReaction ¶ added in v1.1.0
func (p *Posts) SetReaction(ctx context.Context, actor Actor, postID uint64, emoji string, present bool) (Reactions, error)
SetReaction puts the emoji on the post or comment as the actor (present true) or takes it off (present false) and returns the reactions of the post as the actor sees them. Unlike ToggleReaction it is idempotent: putting an emoji that is there, or taking off one that is not, changes nothing. The permissions and the errors are those of ToggleReaction. The change is published as reaction.changed only when something changed. Reactions are not audited (SPEC §7.10).
func (*Posts) StagedFileLimit ¶ added in v1.2.0
StagedFileLimit is the most files one person may have staged: StagedFilesFactor times the number of attachments of a post.
func (*Posts) StagedLimit ¶ added in v1.2.0
StagedLimit is the most bytes one person may have staged: StagedLimitFactor times the attachment limit.
func (*Posts) StagedUploads ¶ added in v1.1.0
StagedUploads turns the IDs that UploadStaged returned into the uploads that Create, Reply and Edit take. Only the person who uploaded a file gets it back: an ID that is unknown, that is not an ID, that another person uploaded, or whose note is damaged fails the whole call with TagInvalidInput and the message "Upload the files again." under FieldAttachments (the message does not say which of the cases it was). An actor with no ID fails with TagUnauthenticated. The call changes nothing; the post that takes the uploads checks the files (Create), and ForgetStaged ends the notes.
func (*Posts) SuggestTags ¶
SuggestTags returns up to 10 tag names that start with prefix (normalized like a tag), used on posts in rooms that the actor can read, ordered by name. An empty prefix suggests the first names.
func (*Posts) SweepStaged ¶ added in v1.1.0
SweepStaged removes the staged uploads that no post took and that are older than maxAge: the file and its note (SPEC §7.12). A person who uploads and never posts would otherwise fill the disk. The age is the time written in the note, by the clock of the service; a note that is damaged counts from when it was last written. The notes of every scope are swept, the messages' too. A note whose file an attachment uses is only ended, never the file. Several processes may run it at once on the shared directory: what another has removed already is skipped, not an error. A note or file that cannot be read or removed is logged and left for the next sweep. It returns the number of uploads removed, and fails with TagSweepCanceled when ctx is done, and with the error of the store when the notes cannot be listed.
func (*Posts) Thread ¶
Thread returns the top-level post and all the comments of the thread that postID belongs to: postID is the top-level post, or any comment of the thread (Focus is then that comment's ID). The comments come depth first, siblings oldest first. A missing post and a room that the actor may not read fail with TagNotFound.
func (*Posts) ToggleReaction ¶
func (p *Posts) ToggleReaction(ctx context.Context, actor Actor, postID uint64, emoji string) (Reactions, error)
ToggleReaction puts the emoji on the post or comment as the actor, or takes it off when the actor put it there already, and returns the reactions of the post as the actor sees them. Only members of the room react: a room that the actor may not read, a missing post and a deleted post fail with TagNotFound, a visible room that the actor has not joined with TagForbidden. An emoji that is not one fails with TagInvalidInput, with the message in the metadata "fields" under FieldEmoji. The change is published as reaction.changed to the room and to the thread after it is committed. Reactions are not audited (SPEC §7.10).
func (*Posts) Unfollow ¶ added in v1.2.0
Unfollow makes the actor stop following a post. It is Follow the other way, with the same rules: on a comment it acts on its top-level post, it is idempotent, and an automatic follow (writing in the thread, being mentioned) does not bring the follow back. The comments of a thread that the actor started or commented in still notify them as direct replies when they answer the actor's post or comment.
func (*Posts) Upload ¶
Upload stores a file that a person attached to the editor and returns what Create, Reply and Edit need to attach it (PostInput.Uploads). The file is at most the configured size; the name is cleaned (base name only, no control characters, at most 255 bytes, "file" when nothing is left). Any logged-in actor may upload; an actor with no ID fails with TagUnauthenticated, a file over the limit with TagTooLarge. An upload that no post takes is left on disk: callers pass every upload to the one call that makes the post, and that call removes the files when it fails.
func (*Posts) UploadStaged ¶ added in v1.1.0
func (p *Posts) UploadStaged(ctx context.Context, actor Actor, name string, r io.Reader) (StagedUpload, error)
UploadStaged is Upload for a client that attaches the file in a later request. Besides the file it keeps a note beside it that says who uploaded it and what Upload returned, so that StagedUploads can give the upload back to the same person and to nobody else. The note lies in the files directory, which the processes of a cluster share (SPEC §8.1). The permissions and the errors are those of Upload. A file that is never attached stays on disk with its note.
A person may have staged at most StagedLimit bytes (ten times the attachment limit, SPEC D62), counted from the notes that exist, the uploads of every other process included. An upload that would go past it is removed again and fails with TagStagedFull; one that reaches the limit exactly is kept. The notes are counted after the new one is written, so that uploads running at the same time cannot all slip under the limit.
type PostsConfig ¶
type PostsConfig struct {
// MaxAttachmentSize is the largest file, in bytes, that Upload accepts;
// 0 means the default (25 MB).
MaxAttachmentSize int64
// MaxAttachments is the most attachments one post may carry; 0 means the
// default (10).
MaxAttachments int
// Logger receives the files that could not be removed from disk. Nil
// means nothing is logged.
Logger *slog.Logger
// Presence tells who is online, for @here (SPEC §7.15). Nil means that
// nobody is.
Presence live.Presence
// StagedRefused counts the uploads that StagedLimit refused (the metric
// "staged" of clowder_limits_refused_total, SPEC D62). Nil counts
// nothing.
StagedRefused *metrics.Counter
}
PostsConfig holds the settings of the posts service.
type Prefs ¶ added in v1.2.0
type Prefs struct {
// contains filtered or unexported fields
}
Prefs is the service of the notification preferences of a user in one room or conversation (SPEC §7.15) and of the notices that the events of the user's stream carry. The global preferences are the settings (Accounts.Settings and Accounts.UpdateSettings). Make it with NewPrefs. It is safe for concurrent use.
func NewPrefs ¶ added in v1.2.0
NewPrefs makes the service. pub receives the live events of the changes, after they are committed; nil publishes nothing.
func (*Prefs) Notice ¶ added in v1.2.0
Notice reads what the page of the actor needs to ring for ev, an event of the actor's own topic with Ring set: a notification.created, a post.created or a message.created. It returns false, and no error, when there is nothing to ring for any more: the notification, post or message is gone, or the actor can no longer read the room or conversation. The text names the place, the author and, for a reply, the thread or, for an assignment, the task; it never holds the body of a post or message. A disabled or missing account fails with TagUnauthenticated.
func (*Prefs) Place ¶ added in v1.2.0
Place returns the actor's notification preferences in the room or conversation: the defaults while none are saved. See checkPlace for who may ask.
func (*Prefs) Places ¶ added in v1.2.0
Places returns the places in which the actor saved preferences (a place with the defaults has no row), rooms first by ID and then conversations by ID. A place that the actor can no longer read has no row: the rows go with the membership. A disabled or missing account fails with TagUnauthenticated.
func (*Prefs) UpdatePlace ¶ added in v1.2.0
func (p *Prefs) UpdatePlace(ctx context.Context, actor Actor, ref PlaceRef, update PlaceUpdate) (PlacePrefs, error)
UpdatePlace changes the actor's notification preferences in the room or conversation; a nil field of update keeps its value. It returns the preferences as they are now and publishes live.KindPlacePrefsChanged to the actor when something changed. Preferences that are all defaults again are deleted. See checkPlace for who may change them. An unknown choice, a mark of unread other than "all" in a conversation, and ignoring group mentions in a conversation of two fail with TagInvalidInput, with all the problems in the metadata "fields".
type Presence ¶ added in v1.2.0
type Presence struct {
// contains filtered or unexported fields
}
Presence is the service that tells who is online (SPEC §7.15): a user is online while a page stream or a WebSocket of theirs is open, in any process. Presence is not private: any user who is logged in may ask about any users. Make it with NewPresence. It is safe for concurrent use.
func NewPresence ¶ added in v1.2.0
NewPresence makes the service over the presence of the process (or of the cluster); nil means that nobody is online.
func (*Presence) Connect ¶ added in v1.2.0
Connect records one more open page stream or WebSocket of the user. The streams call it when they open. On a nil service it does nothing.
func (*Presence) Disconnect ¶ added in v1.2.0
Disconnect records that one of the open connections of the user closed. On a nil service it does nothing.
func (*Presence) Online ¶ added in v1.2.0
func (p *Presence) Online(ctx context.Context, actor Actor, userIDs []uint64) (map[uint64]bool, error)
Online returns the set of those among userIDs who are online now and whose account is not disabled; a user who is offline, disabled or unknown has no key. At most 100 IDs may be asked: more fails with TagInvalidInput, with the message under FieldUserIDs. A disabled or missing account fails with TagUnauthenticated. When the shared presence cannot be read (Redis) it fails with the error of the presence.
func (*Presence) OnlineIn ¶ added in v1.2.0
OnlineIn returns the set of those among the members of a place who are online now, for the dots of a members list. It does not check any permission: the caller has read the members already. A nil service, and a presence that cannot be read, say that nobody is online.
type ProcessDirectory ¶ added in v1.2.0
type ProcessDirectory interface {
// Alive reports whether the process with this ID is running. An error
// means the answer is not known.
Alive(ctx context.Context, process string) (bool, error)
}
ProcessDirectory says whether a process of the cluster is alive. The media address a process announces in Redis (SPEC D65) is how internal/cluster implements it.
type Publisher ¶
type Publisher interface {
// Publish delivers the event to whoever listens to its topic.
Publish(ev live.Event)
}
Publisher receives the live events of the services (SPEC §8). The hub of package live is one; so is live.Recorder, for tests. Publish must not block.
type Query ¶
type Query struct {
// Terms are the words and phrases; every one has to match.
Terms []Term
// Tags are the normalized tags of the #tag terms, without duplicates;
// the post has to carry all of them.
Tags []string
// Room is the name given in room:, empty when there is none. The last
// room: of a query counts.
Room string
// From is the lower-case username given in from:, empty when there is
// none. The last from: of a query counts.
From string
// After is the first instant of the day given in after: (UTC): posts on or
// after that day. Zero when there is none.
After time.Time
// Before is the first instant of the day given in before: (UTC): posts
// strictly before that day. Zero when there is none.
Before time.Time
// PostsOnly is true when the query has is:post.
PostsOnly bool
// CommentsOnly is true when the query has is:comment. With is:post too,
// nothing matches.
CommentsOnly bool
}
Query is a search query, parsed (SPEC §7.8). ParseQuery makes it.
func ParseQuery ¶
ParseQuery reads the text of the search box. It is a pure function, and nothing a user types is an error except a malformed date.
The text is split on white space into tokens:
- a token that starts with a double quote and has a closing quote later in the text is an exact phrase, whatever is between the quotes; a quote with no partner, or in the middle of a word, is an ordinary character
- #tag is a tag filter, normalized like the tags of a post (lower case, without the leading #); it may repeat, and all must be on the post. A "#" followed by something that is not a valid tag is a word
- room:<name>, from:<username>, after:<YYYY-MM-DD>, before:<YYYY-MM-DD>, is:post and is:comment are filters; the key is not case sensitive and the value may be in double quotes (room:"team news"). after: is on or after that day (UTC) and before: strictly before it. A key with an empty value, an unknown is: value and an unknown key (a:b) are words
- everything else is a word, matched as a prefix
Words and phrases have no FTS5 syntax: OR, NOT, NEAR, *, ^, -, : and parentheses are plain text. A word with no letter or digit is dropped; at most 32 words and phrases, and the first 500 characters of the text, count. A malformed date fails with TagInvalidInput and the message "Use dates like 2026-10-27." in the metadata "fields" under "q".
type ReactionCount ¶
type ReactionCount struct {
// Emoji is the emoji.
Emoji string
// Count is the number of people who reacted with it.
Count int
// Mine is true when the asking actor is one of them.
Mine bool
// Names are the display names of the people, in the order they reacted.
Names []string
// Users are the same people as Names, in the same order.
Users []UserRef
}
ReactionCount is one emoji on a post, with how many people put it there.
type Reactions ¶
type Reactions []ReactionCount
Reactions are the reactions on a post, ordered by the first use of each emoji.
type RepliesMode ¶ added in v1.2.0
type RepliesMode = store.RepliesMode
RepliesMode says which comments notify a user (SPEC §7.15). It is the store's type.
type ResetInput ¶ added in v1.2.0
type ResetInput struct {
// Token is the token of the link.
Token string
// NewPassword is the password to set: at least 12 characters, at most
// 1024 bytes.
NewPassword string
// ClientName names the browser (its user agent) in the session that the
// reset starts.
ClientName string
}
ResetInput is what a person gives to set a new password with a reset link.
type Ring ¶ added in v1.2.0
type Ring struct {
// Rings is true when the event rings at all: the place's choice of what
// notifies covers it and the place is not muted.
Rings bool
// Sound is the name of the sound to play; empty when the event rings
// without a sound (the user turned it off, globally or in the place), and
// always empty when Rings is false.
Sound SoundName
// Browser is true when a browser notification is wanted: the event rings
// and the user turned the browser notifications on.
Browser bool
}
Ring is the outcome of the ringing decision for one user and one event: the server puts it in the event for that user, and the page only obeys it.
type Role ¶
Role is what a user may do. It is the store's type, so the web layer can name the roles without importing the store.
type Room ¶
type Room struct {
// ID is the ID of the room.
ID uint64
// Name is the unique name of the room.
Name string
// Description tells what the room is for.
Description string
// Visibility says who sees the room.
Visibility Visibility
// CreatedBy is the ID of the user who made the room.
CreatedBy uint64
// Creator names the user who made the room.
Creator UserRef
// CreatedAt is when the room was made.
CreatedAt time.Time
// MemberCount is the number of members.
MemberCount int
// IsMember is true when the asking actor is a member.
IsMember bool
// CanManage is true when the asking actor may rename and delete the room:
// an admin, or the creator.
CanManage bool
// Muted is true when the asking actor muted the room (SPEC §7.15). Only
// Mine fills it.
Muted bool
// MentionsOnly is true when the asking actor chose "Only mentions" as what
// the room counts as unread (SPEC §7.15, §7.17). Only Mine fills it.
MentionsOnly bool
// UnreadPosts is the number of top-level posts of the room by others that
// the asking actor has not seen (SPEC §7.17, D55), up to UnreadPostsCap. It
// is the raw number: it does not depend on the preferences of the room. 0
// when the actor is not a member. Mine, Available, Get and Patch fill it.
UnreadPosts int
// UnreadMentions is the number of the actor's unread notifications in the
// room that are mentions (mention, group mention and keyword); 0 when the
// actor is not a member. Mine, Available, Get and Patch fill it.
UnreadMentions int
}
Room is a room as the services show it to one actor.
type RoomInput ¶
type RoomInput struct {
// Name is the name of the room: 1 to 64 characters, unique without regard
// to case. It is trimmed.
Name string
// Description is at most 500 characters. It is trimmed.
Description string
// Visibility is who sees the room. Create reads it; Update ignores it,
// because the visibility of a room does not change.
Visibility Visibility
}
RoomInput is what a person types when they make or change a room.
type RoomPatch ¶ added in v1.1.0
type RoomPatch struct {
// Name is the new name, or nil to keep the name.
Name *string
// Description is the new description, or nil to keep it.
Description *string
}
RoomPatch is a change of a room in which only the fields that are set change.
type RoomUnread ¶ added in v1.2.0
type RoomUnread struct {
// RoomID is the room.
RoomID uint64
// Posts is the number of top-level posts of the room that are not deleted,
// were written by someone else, and are newer than the member's mark, up to
// UnreadPostsCap.
Posts int
// Mentions is the number of the member's unread notifications in the room
// that are mentions: mention, group_mention and keyword.
Mentions int
}
RoomUnread holds the unread counts of one room for one member (SPEC §7.17, D55). They are the raw numbers: whether a muted room or a room that counts only mentions shows them is for the page (Room.Muted, Room.MentionsOnly).
type Rooms ¶
type Rooms struct {
// contains filtered or unexported fields
}
Rooms is the service of rooms and their memberships (SPEC §7.2). Make it with NewRooms. It is safe for concurrent use.
func NewRooms ¶
NewRooms makes the service. fs holds the files of the attachments, which Delete removes with the room; the logger receives the files that could not be removed, and may be nil. pub receives the live events of the changes, after they are committed; nil publishes nothing.
func (*Rooms) AddMember ¶
AddMember adds a user to a room and writes member.added. The actor must be a member of the room (any member adds any user, D15): a private room that the actor is not a member of fails with TagNotFound, a visible room that the actor has not joined with TagForbidden. It does nothing when the user is a member already. It fails with TagInvalidInput (field "user") when the user does not exist or is disabled. The added user is notified (added_to_room) unless they are the actor.
func (*Rooms) AdminMembers ¶
AdminMembers returns the members of any room, private ones included, ordered by display name, for the admin rooms page (D29). It needs no membership: only admins may, and anyone else gets TagForbidden. A room that does not exist fails with TagNotFound.
func (*Rooms) AllRooms ¶
AllRooms returns every room, private ones included, ordered by name, for the admin rooms page (D29). Only admins may; anyone else gets TagForbidden.
func (*Rooms) Available ¶ added in v1.1.0
Available returns the rooms the actor sees in a list: every visible room and the private rooms the actor is a member of, ordered by name. IsMember says which of them the actor has joined.
func (*Rooms) Candidates ¶
Candidates returns the active users who are not members of the room, ordered by username: the people the actor can add with AddMember. The rules are those of AddMember: a private room that the actor is not a member of fails with TagNotFound, a visible room that the actor has not joined with TagForbidden.
func (*Rooms) Create ¶
Create makes a room and makes the actor its first member, with the columns To do, In progress and Done, and writes the event room.created. Visible rooms are made by admins only (D15); private rooms by anyone. It fails with TagForbidden for a visible room of a member, and with TagInvalidInput, with all the problems in the metadata "fields", for input that breaks a rule (a name that is taken is one of them).
func (*Rooms) Delete ¶
Delete deletes a room with everything in it and writes room.deleted, which stays after the room is gone. Admins and the creator may; the creator of a private room must still be a member. Anyone else gets TagForbidden, or TagNotFound for a private room they are not a member of. The files of every attachment in the room are removed from disk after the change is committed.
func (*Rooms) Get ¶
Get returns a room that the actor may read: a visible room, or a room the actor is a member of. For any other room, including one that does not exist, it fails with TagNotFound.
func (*Rooms) Join ¶
Join makes the actor a member of a visible room and writes member.joined. It does nothing when the actor is a member already. A private room that the actor is not a member of fails with TagNotFound, like a room that does not exist.
func (*Rooms) Leave ¶
Leave removes the actor from a room and writes member.left. It does nothing when the actor is not a member. A private room that the actor is not a member of fails with TagNotFound. A private room may end with no members; admins keep it until they delete it.
func (*Rooms) MarkRead ¶ added in v1.2.0
MarkRead moves the actor's mark in the room forward to the post or comment upToID, which marks every post and comment up to it as seen (SPEC §7.17). It never moves the mark back, and caps it at the room's highest ID. It publishes room.unread to the actor when the mark moved. It does not touch the actor's notifications (Visit does).
A room that the actor may not read fails with TagNotFound; a visible room that the actor has not joined with TagForbidden. A post that does not exist or is not of this room fails with TagInvalidInput, with the problem in the metadata "fields" (FieldPostID).
func (*Rooms) Members ¶
Members returns the members of a room that the actor may read, ordered by display name. For any other room it fails with TagNotFound.
func (*Rooms) Mine ¶
Mine returns the rooms the actor is a member of, visible and private, ordered by name, except that the rooms the actor muted come last (SPEC §7.15) and say so in Muted. Each has its unread counts and says in MentionsOnly whether the actor counts only mentions there (SPEC §7.17).
func (*Rooms) MineOne ¶ added in v1.2.0
MineOne returns the room as Mine shows it in the sidebar of the actor: with Muted, MentionsOnly and the unread counts. It returns false when the actor is not a member of the room. It is a few small queries, for the stream that patches one entry of the sidebar.
func (*Rooms) Patch ¶ added in v1.1.0
func (r *Rooms) Patch(ctx context.Context, actor Actor, roomID uint64, patch RoomPatch) (Room, error)
Patch changes the name and the description of a room, the fields of patch that are set, and returns the room as the actor sees it afterwards. The rules, the audit event and the errors are those of Update, which it calls: admins and the creator may, and a private room that the actor may not read is TagNotFound for anyone but an admin.
func (*Rooms) RemoveMember ¶
RemoveMember removes a user from a room and writes member.removed. Only admins may, in any room, private ones too (D29); anyone else gets TagForbidden, or TagNotFound for a private room they are not a member of. It does nothing when the user is not a member.
func (*Rooms) SearchCandidates ¶ added in v1.1.0
func (r *Rooms) SearchCandidates(ctx context.Context, actor Actor, roomID uint64, prefix string) ([]User, error)
SearchCandidates returns the candidates of Candidates whose username or display name starts with prefix, in any case, 20 at most, ordered by username. An empty prefix returns the first 20. The permissions are those of Candidates.
func (*Rooms) Unread ¶ added in v1.2.0
Unread returns the unread counts of the actor in one room, and false when the actor is not a member of it (a room that does not exist, or that the actor left, has none). It is one small query. It is what a stream or a client reads when it hears room.unread.
func (*Rooms) Update ¶
Update changes the name and the description of a room and writes room.renamed with the fields that changed; it does nothing when nothing changed. The visibility of a room does not change, so in.Visibility is ignored. Admins and the creator may; the creator of a private room must still be a member. Anyone else gets TagForbidden, or TagNotFound for a private room they are not a member of. It fails with TagInvalidInput, with all the problems in the metadata "fields", for input that breaks a rule.
func (*Rooms) Visible ¶
Visible returns every visible room, ordered by name. IsMember says which of them the actor has joined.
func (*Rooms) Visit ¶ added in v1.2.0
Visit is what opening the feed or the board of a room does for the actor: it moves the mark to the room's highest ID at this moment, and marks the actor's unread mentions of the room (the notifications of the kinds mention, group_mention and keyword) as read, in one transaction, as Mattermost clears a channel's mentions when you view it (SPEC §7.17). It returns the mark as it was before, so that the caller can tell which posts it had read. It publishes room.unread to the actor when the mark or the mentions changed, and notification.read when mentions were read.
The caller reads the page's data first and calls Visit after, so that the posts it shows are the ones the mark covers. The actor does not have to be a member: for a visible room that they have not joined nothing is marked and the mark is 0. A room that the actor may not read fails with TagNotFound.
type SSHKey ¶ added in v1.2.0
type SSHKey struct {
// ID is the ID of the key.
ID uint64
// Name is the name the user gave the key.
Name string
// Type is the type of the key, such as ssh-ed25519.
Type string
// Fingerprint is the SHA-256 fingerprint, as ssh-keygen -l writes it.
Fingerprint string
// CreatedAt is when the key was added.
CreatedAt time.Time
// LastUsedAt is when the key last fetched a code; nil until then.
LastUsedAt *time.Time
}
SSHKey is a registered key as the services show it: never the key itself, only what a person needs to recognise it.
type SSHKeys ¶ added in v1.2.0
type SSHKeys struct {
// contains filtered or unexported fields
}
SSHKeys is the service of the SSH keys of a user (SPEC §7.16). A user manages their own keys only; adding and removing one needs the current password. Make it with NewSSHKeys. It is safe for concurrent use.
func NewSSHKeys ¶ added in v1.2.0
func NewSSHKeys(st *store.Store, clk clock.Clock, accounts *Accounts, server SSHServerInfo) *SSHKeys
NewSSHKeys makes the service. The password is checked by accounts, with its hashing gate and its login limiter. A nil clk is the real clock. server describes the SSH server that the user is shown.
func (*SSHKeys) Add ¶ added in v1.2.0
func (k *SSHKeys) Add(ctx context.Context, actor Actor, name, line, password, clientIP string) (SSHKey, error)
Add registers the public key line (the content of a .pub file) as a key of the actor with the name (1 to 40 characters, trimmed). The current password is checked first as ChangePassword checks it: a wrong one counts as a failed login of the username and of clientIP, and a username or address that the limiter blocks gets TagRateLimited. In one transaction it stores the key and writes the audit event user.ssh_key_added, with the name and the fingerprint and never the key.
Failures: TagInvalidInput for a name or a line that is not valid (fields "name" and "publicKey") and for a wrong password (field "currentPassword"); TagSSHKeyTypeRefused for a type outside the list of SPEC §7.16 (ssh-dss included); TagSSHKeyTooShort for an RSA key under 3,072 bits; TagConflict for a fingerprint that is registered already, whoever has it, and for a user who has 10 keys (both carry the message in the metadata "fields"); TagUnauthenticated for a disabled or missing account.
func (*SSHKeys) DisableSSHCode ¶ added in v1.2.0
func (k *SSHKeys) DisableSSHCode(ctx context.Context, actor Actor, currentPassword, clientIP string) error
DisableSSHCode turns off "Ask for an SSH code when I log in" for the actor. It needs the current password, checked as EnableSSHCode checks it, and works with the SSH server off too. It writes user.ssh_code_disabled; when the code is off already it changes nothing and writes no event. It fails with TagInvalidInput (field "currentPassword"), TagRateLimited or TagUnauthenticated like EnableSSHCode.
func (*SSHKeys) EnableSSHCode ¶ added in v1.2.0
func (k *SSHKeys) EnableSSHCode(ctx context.Context, actor Actor, currentPassword, clientIP string) error
EnableSSHCode turns on "Ask for an SSH code when I log in" for the actor (SPEC §7.16, D53). It needs the current password, checked as Add checks it (a wrong one counts as a failed login of the username and of clientIP), this process running the SSH server, and at least one key of the user that has fetched a code (its last use is set), which proves that the setup works. In one transaction it sets the flag and writes the audit event user.ssh_code_enabled; when the code is on already it changes nothing and writes no event. After the commit it publishes live.KindSettingsChanged.
Failures: TagInvalidInput for a wrong password (field "currentPassword"), TagRateLimited for a blocked username or address, TagSSHServerOff when the server is off, TagSSHCodeNotTried when no key fetched a code (both carry the message under the field "form") and TagUnauthenticated for a disabled or missing account.
func (*SSHKeys) List ¶ added in v1.2.0
List returns the keys of the actor, oldest first. A disabled or missing account fails with TagUnauthenticated.
func (*SSHKeys) Remove ¶ added in v1.2.0
func (k *SSHKeys) Remove(ctx context.Context, actor Actor, keyID uint64, password, clientIP string) error
Remove deletes the key keyID of the actor, after it checks the current password as Add does, and writes the audit event user.ssh_key_removed. A key that does not exist and a key of another user both fail with TagNotFound. A wrong password fails with TagInvalidInput (field "currentPassword"), a blocked username or address with TagRateLimited, a disabled or missing account with TagUnauthenticated and the last key of a user whose SSH code is on with TagSSHCodeNeedsKey.
func (*SSHKeys) RemoveSSHCode ¶ added in v1.2.0
RemoveSSHCode turns off the SSH code at login of the user userID, for a user who lost their keys (SPEC §7.16). Only admins may, for any user, themselves included, and it needs no password. It writes user.ssh_code_removed with the admin as the actor; when the code is off already it changes nothing and writes no event. It fails with TagForbidden for anyone but an admin (also for an actor whose role was taken away since the actor was built), TagUnauthenticated for a disabled or missing admin account and TagNotFound for an unknown user.
type SSHServer ¶ added in v1.2.0
type SSHServer struct {
// Enabled is true when the server runs.
Enabled bool
// HostFingerprint is the SHA-256 fingerprint of the host key; empty when
// the server is off.
HostFingerprint string
// Command is the ssh command that fetches a code; empty when the server
// is off.
Command string
}
SSHServer is what a user sees of the SSH server.
type SSHServerInfo ¶ added in v1.2.0
type SSHServerInfo struct {
// Addr is the address the server listens on; empty when it is off.
Addr string
// PublicHost is the host shown in the ssh command.
PublicHost string
// HostFingerprint is the SHA-256 fingerprint of the host key.
HostFingerprint string
}
SSHServerInfo describes the SSH server for the pages and the API. The zero value means the server is off.
type Search ¶
type Search struct {
// contains filtered or unexported fields
}
Search is the service of search (SPEC §7.8). Make it with NewSearch. It is safe for concurrent use.
func (*Search) Query ¶
Query searches the posts and comments that the actor may read: those in visible rooms and in the private rooms the actor is a member of (admins are no exception, D29), never a deleted one. q is parsed by ParseQuery, whose TagInvalidInput error it returns untouched. A query with neither words nor filters finds nothing and is no error. page starts at 1 (a smaller value counts as 1); a page has 20 results, and a page past the 1000th is empty.
type SearchPage ¶
type SearchPage struct {
// Query is the text that was searched, as typed.
Query string
// Parsed is Query, parsed.
Parsed Query
// Results are the results of the page: by relevance, then newest first;
// newest first when the query has no words.
Results []SearchResult
// Page is the number of the page, starting at 1.
Page int
// HasNext is true when more results follow this page.
HasNext bool
}
SearchPage is a page of search results.
type SearchResult ¶
type SearchResult struct {
// PostID is the ID of the post or comment.
PostID uint64
// RootID is the top-level post of a comment; 0 for a top-level post.
RootID uint64
// IsComment is true for a comment.
IsComment bool
// RoomID is the room of the post.
RoomID uint64
// RoomName is the name of the room.
RoomName string
// Author is the author of the post.
Author UserRef
// CreatedAt is when the post was written.
CreatedAt time.Time
// Snippet is the matching text, escaped, with the matches in <mark>; it
// holds no other HTML. Without words in the query it is the start of the
// post, cut at 200 characters.
Snippet template.HTML
// Segments are Snippet as plain text in pieces: each piece is text and
// says whether it is a match. Joined, the texts are the snippet without
// the markup; it is what a client that shows no HTML uses.
Segments []SnippetSegment
// Tags are the tags of the post, in the order the author gave them.
Tags []string
}
SearchResult is a post or comment found by a search.
type Session ¶
type Session struct {
// SessionID is the ID of the session, for Sessions and EndSession.
SessionID uint64
// Actor is the actor to pass to the services.
Actor Actor
// User is the logged-in user.
User User
// ExpiresAt is when the session ends, counting from its last use.
ExpiresAt time.Time
// Refreshed is true when this call moved the expiry (the last use was
// more than a minute old): the cookie must be sent again with a new
// Max-Age, so that it slides with the session.
Refreshed bool
}
Session is who a session token belongs to, as SessionActor returns it.
type SessionInfo ¶ added in v1.1.0
type SessionInfo struct {
// ID is the ID of the session, for EndSession.
ID uint64
// Kind says whether it is a browser or an API client.
Kind SessionKind
// ClientName is the user agent of the browser or the name the API client
// gave; empty for a session of version 1.0.
ClientName string
// CreatedAt is when the session was made.
CreatedAt time.Time
// LastSeenAt is when the session was last used.
LastSeenAt time.Time
// ExpiresAt is when the session ends, counting from its last use.
ExpiresAt time.Time
// Current is true for the session that made the request.
Current bool
}
SessionInfo is a session of a user as the user sees it in the list of their sessions: never the token.
type SessionKind ¶ added in v1.1.0
type SessionKind = store.SessionKind
SessionKind says where a session was made and where it is accepted: a browser session belongs to the pages and travels in the cookie, an API session to the API and travels in the Authorization header (SPEC D43). It is the store's type.
const ( // SessionBrowser is the kind of the sessions made by the login and // sign-up pages. SessionBrowser SessionKind = store.SessionBrowser // SessionAPI is the kind of the sessions made by the login of the API. SessionAPI SessionKind = store.SessionAPI )
The two kinds of sessions.
type Settings ¶ added in v1.2.0
type Settings struct {
// Theme is the look the user chose.
Theme Theme
// Sound is true when the user wants a sound for what is new.
Sound bool
// BrowserNotifications is true when the user wants notifications of the
// browser.
BrowserNotifications bool
// Notify is what rings the sound and shows a browser notification.
Notify NotifyLevel
// SoundName is the sound that plays.
SoundName SoundName
// Replies says which comments notify the user.
Replies RepliesMode
// Keywords are the mention keywords: up to 10 words or phrases of 1 to 32
// characters, unique ignoring case. Never nil.
Keywords []string
// GroupMentions is true when @room, @all and @here reach the user (the
// default).
GroupMentions bool
// SSHCodeRequired is true when the user turned on "Ask for an SSH code
// when I log in" (SPEC §7.16). It is read only here: EnableSSHCode and
// DisableSSHCode change it.
SSHCodeRequired bool
}
Settings are the preferences of a user (SPEC §7.14, §7.15), which follow the user to every browser and client.
type SettingsUpdate ¶ added in v1.2.0
type SettingsUpdate struct {
// Theme is the new theme.
Theme *Theme
// Sound is the new value of the sound.
Sound *bool
// BrowserNotifications is the new value of the browser notifications.
BrowserNotifications *bool
// Notify is the new value of "Notify me about".
Notify *NotifyLevel
// SoundName is the new sound.
SoundName *SoundName
// Replies is the new replies choice.
Replies *RepliesMode
// Keywords is the new list of mention keywords. Each is trimmed and its
// inner white space made one space; a blank one, one of more than 32
// characters, a duplicate (ignoring case) and a list of more than 10 are
// mistakes. A nil pointer keeps the list; a pointer to an empty list
// clears it.
Keywords *[]string
// GroupMentions is the new value of "@room, @all and @here".
GroupMentions *bool
}
SettingsUpdate is a change of the settings. A nil field keeps the value.
type SignIn ¶ added in v1.2.0
type SignIn struct {
// contains filtered or unexported fields
}
SignIn is the service behind the SSH server of SPEC §7.16: it says whether a key may fetch a code and makes the code. Make it with NewSignIn. It is safe for concurrent use.
func NewSignIn ¶ added in v1.2.0
NewSignIn makes the service. A nil clk is the real clock and a nil logger discards the log.
func (*SignIn) IssueCode ¶ added in v1.2.0
func (s *SignIn) IssueCode(ctx context.Context, username, fingerprint, addr string) (IssuedSSHCode, error)
IssueCode makes a sign-in code for the user with the username, for the key with the fingerprint, which addr (the address of the SSH client) asked for. It checks again that the key belongs to the enabled user, and fails with TagNotFound when it does not. A user gets at most 10 codes within 15 minutes, replaced and used ones counted, and the eleventh fails with TagSSHCodeLimit. In one transaction it marks the unused codes of the user as replaced, deletes the codes older than a day, stores the new code (the SHA-256 of its 8 characters) with an expiry of 60 seconds and sets the last use of the key. It writes no audit event. It logs the user, the fingerprint and addr at Info level, never the code.
func (*SignIn) KeyAllowed ¶ added in v1.2.0
KeyAllowed reports whether the key with the SHA-256 fingerprint belongs to the user with the username, who is not disabled. It answers only true or false, so that an unknown user, a disabled user and the key of another user look the same to the caller. A failure of the database is logged and answers false. The service takes the fingerprint (ssh.FingerprintSHA256) and not the key: the SSH server computes it once for both calls.
type SignInOption ¶ added in v1.2.0
type SignInOption func(*SignIn)
SignInOption changes how NewSignIn makes the service.
func WithCodesCounter ¶ added in v1.2.0
func WithCodesCounter(c *metrics.Counter) SignInOption
WithCodesCounter makes the service count each code it issues in c (metrics.Set.SSHCodes, SPEC D60). A nil counter counts nothing.
type SignUpOption ¶ added in v1.2.0
type SignUpOption func(*signUpSettings)
SignUpOption changes how SignUp treats a request.
func FromAddress ¶ added in v1.2.0
func FromAddress(clientIP string) SignUpOption
FromAddress tells SignUp the client address of the request, which the login limiter counts (SPEC D62; see SignUp). Without it nothing is limited or counted: that is for the demo data and the tests; the pages and the API always give it.
type SnippetSegment ¶ added in v1.1.0
type SnippetSegment struct {
// Text is the piece, as written (not escaped).
Text string
// Match is true for the words the query found.
Match bool
}
SnippetSegment is a piece of the snippet of a search result.
type SoundName ¶ added in v1.2.0
SoundName names one of the four sounds (SPEC §7.15). It is the store's type.
type StagedUpload ¶ added in v1.1.0
type StagedUpload struct {
// ID names the upload in StagedUploads. It is the key of the file: 64
// random hex characters nobody can guess.
ID string
// Upload is the file as Posts.Upload returned it.
Upload Upload
}
StagedUpload is a file uploaded for a later request to attach: the way a client of the API (SPEC §7.12) uploads, because its upload and its post are two requests. The ID is the one value the client keeps.
type TaskCard ¶
type TaskCard struct {
// ID is the ID of the task.
ID uint64
// Title is the title of the task.
Title string
// PostID is the ID of the post or comment the task was written in.
PostID uint64
// RootID is the ID of the top-level post of the thread of PostID, which a
// link back to the task needs; it is PostID itself for a top-level post.
RootID uint64
// ColumnID is the ID of the column the task is in.
ColumnID uint64
// ColumnName is the name of that column.
ColumnName string
// Done is true when the task is in the last column of the board, which
// counts as done (SPEC §7.6).
Done bool
// Assignees are the people the task is assigned to, in the order they were
// assigned.
Assignees []UserRef
// DueDate is the day the task is due, as midnight UTC; nil when it has no
// due date.
DueDate *time.Time
// Overdue is true when the due date is before today (UTC) and the task is
// not in the last column of the board, which counts as done (SPEC §7.6).
Overdue bool
// Position is the place of the task in its column, from 0 at the top.
Position int
}
TaskCard is a task as the board and the posts show it.
type TaskInput ¶
type TaskInput struct {
// ID is the ID of the task when Edit is given a task of the post that
// stays; 0 for a new task. Create and Reply accept only 0.
ID uint64
// Title is the title: 1 to 200 characters, trimmed.
Title string
// Assignees are the IDs of the members of the room that the task is
// assigned to: at most 10, duplicates are dropped.
Assignees []uint64
// DueDate is the day the task is due, or nil. Only the date counts: the
// service converts it to UTC and drops the time of day. The zero time is
// the same as nil.
DueDate *time.Time
}
TaskInput is a task as a person types it in the editor of a post or comment (D17): one row of the tasks field.
type TaskPatch ¶
type TaskPatch struct {
// Title is the new title: 1 to 200 characters, trimmed.
Title *string
// Assignees is the new list of assignees, members of the room, at most 10,
// duplicates dropped; an empty list unassigns everybody.
Assignees *[]uint64
// DueDate is the new due date; only the date counts, as in TaskInput.
DueDate *time.Time
// ClearDueDate removes the due date. Together with DueDate it is invalid.
ClearDueDate bool
}
TaskPatch is a change to a task made on the board. A nil field stays as it is.
type Term ¶
type Term struct {
// Text is the word or the phrase, without the quotes that made it a
// phrase.
Text string
// Phrase is true for an exact phrase, written in double quotes; a word
// matches as a prefix.
Phrase bool
}
Term is a word or an exact phrase of a search query.
type Thread ¶
type Thread struct {
// Root is the top-level post of the thread.
Root Post
// Comments are the comments depth first: every comment comes before its
// replies, and siblings are oldest first. A deleted comment that was kept
// for its replies is included, as deleted.
Comments []Comment
// Focus is the ID of the comment that Thread was asked for, or 0 when it
// was asked for the top-level post.
Focus uint64
}
Thread is a top-level post with all its comments, as one reader sees it.
type Upload ¶
type Upload struct {
// Key is the name of the file in the store: 64 lowercase hex characters.
Key string
// FileName is the cleaned name the file had when it was uploaded.
FileName string
// ContentType is the type found by sniffing the content.
ContentType string
// Size is the size in bytes.
Size int64
// Width and Height are the size in pixels of an image; 0 for any other
// file.
Width, Height int
}
Upload is a file that a person uploaded for a post and that is on disk but not yet on any post. Posts.Upload makes it; PostInput.Uploads takes it. Only the values that Upload returned are accepted: Create, Reply and Edit check that the file exists with that size and that no attachment uses it yet.
type User ¶
type User struct {
// ID is the ID of the user.
ID uint64
// Username is the unique, lower-case name used to log in.
Username string
// DisplayName is the name shown to other people.
DisplayName string
// Role is what the user may do.
Role store.Role
// Disabled is true when an admin disabled the account.
Disabled bool
// AvatarKey is the key of the user's avatar, for AvatarPath; empty when
// the user has none.
AvatarKey string
// CreatedAt is when the user signed up.
CreatedAt time.Time
// SSHCodeRequired is true when the user turned on the SSH code at login.
// Only Users fills it; the other services leave it false.
SSHCodeRequired bool
}
User is a user as the services show it: the data of a person without the password hash.
type UserRef ¶
type UserRef struct {
// ID is the ID of the user.
ID uint64
// Username is the username of the user.
Username string
// DisplayName is the name shown to other people.
DisplayName string
// AvatarKey is the key of the user's avatar, for AvatarPath; empty when
// the user has none.
AvatarKey string
}
UserRef names a user on a post.
type Visibility ¶
type Visibility = store.Visibility
Visibility says who sees a room. It is the store's type, so the web layer can name the values without importing the store.
const ( // VisibilityVisible is a room that every user sees and reads (D26). VisibilityVisible Visibility = store.VisibilityVisible // VisibilityPrivate is a room that only its members see. VisibilityPrivate Visibility = store.VisibilityPrivate )
The two visibilities of SPEC §7.2.
Source Files
¶
- accounts.go
- app.go
- attachments.go
- audit.go
- avatar.go
- board.go
- calls.go
- connections.go
- doc.go
- follow.go
- gate.go
- health.go
- limiter.go
- mentions.go
- messages.go
- messages_search.go
- messages_send.go
- notice.go
- notifications.go
- posts.go
- prefs.go
- presence.go
- profile.go
- publish.go
- reactions.go
- reset.go
- ring.go
- rooms.go
- search.go
- sessions.go
- signin.go
- sshkeys.go
- sshlogin.go
- staged.go
- tasks.go
- unread.go