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 CleanClientName(kind SessionKind, name string) (string, error)
- func ParseTags(s string) []string
- type Accounts
- func (a *Accounts) APISessionActor(ctx context.Context, token string) (Session, error)
- func (a *Accounts) CreateInvitation(ctx context.Context, actor Actor, role store.Role) (IssuedInvitation, error)
- func (a *Accounts) CreateSystemInvitation(ctx context.Context, role store.Role) (IssuedInvitation, 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) (string, User, 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) 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) 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) SignUp(ctx context.Context, token, username, displayName, password string) (User, 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 ClientLogin
- type ColumnView
- type Comment
- type ConversationHeader
- type ConversationKind
- type ConversationMemberView
- type ConversationSummary
- type EntityType
- type FailureCounter
- type FeedPage
- type Format
- type Health
- type HistoryPage
- type InvitationInfo
- type IssuedInvitation
- type LastMessage
- type LoginLimiter
- type LoginResult
- type Member
- type Message
- type MessageInput
- type MessageQuote
- 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) 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) 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 Notification
- type NotificationKind
- type NotificationPage
- type Notifications
- 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) ForgetStaged(ctx context.Context, actor Actor, uploads []Upload)
- func (p *Posts) Get(ctx context.Context, actor Actor, postID uint64) (Post, 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) 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) 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 Publisher
- type Query
- type ReactionCount
- type Reactions
- type Role
- type Room
- type RoomInput
- type RoomPatch
- 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) Members(ctx context.Context, actor Actor, roomID uint64) ([]Member, error)
- func (r *Rooms) Mine(ctx context.Context, actor Actor) ([]Room, 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) Update(ctx context.Context, actor Actor, roomID uint64, in RoomInput) error
- func (r *Rooms) Visible(ctx context.Context, actor Actor) ([]Room, error)
- type Search
- type SearchPage
- type SearchResult
- type Session
- type SessionInfo
- type SessionKind
- type SnippetSegment
- type StagedUpload
- type TaskCard
- type TaskInput
- type TaskPatch
- type Term
- 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 )
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 )
The actions of SPEC §7.10.
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 ( // 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 ( // 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 ( // 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 FieldAttachments = "attachments"
FieldAttachments names the attachments of a post 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 ( // FieldQuery names the search box in the metadata "fields" of a // TagInvalidInput error. FieldQuery = "q" )
The limits of search (SPEC §7.8).
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 MessageDeletedPreview = "message deleted"
MessageDeletedPreview is the text shown instead of a deleted message, in a preview or a quote.
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 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.
Variables ¶
This section is empty.
Functions ¶
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").
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) 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) 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) 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).
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) (string, User, error)
Login is LoginClient for a browser that sends no name: a SessionBrowser session with an empty client name. It returns the token and the user.
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.
func (*Accounts) Logout ¶
Logout deletes the session of the cookie token. An unknown token is not an error.
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) 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 of the user, 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) SignUp ¶
func (a *Accounts) SignUp(ctx context.Context, token, username, displayName, password string) (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.
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
}
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 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
}
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 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
// 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 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 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.
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).
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
}
LoginResult is what a successful login returns.
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
// 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
// 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 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 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) 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) 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 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
// 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 )
The four 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. 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 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
}
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) 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) 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) 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) 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.
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
}
PostsConfig holds the settings of the posts service.
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 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
}
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 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) 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.
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) 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.
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 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 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
// CreatedAt is when the user signed up.
CreatedAt time.Time
}
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
}
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.