Documentation
¶
Overview ¶
Package notes implements Chronicle's notes: the full-page Journal and the floating per-page Jot notes. Both are rows in one table; a note with no page (entity_id NULL) belongs to the Journal, a note on a page is that page's jot. Notes support folders, rich text (TipTap/ProseMirror), checklists, version history, audio attachments and a pessimistic edit lock with 5-minute expiry.
Who can read a note is decided by Note.CanView and its SQL twin in the repository; see Visibility for the four audiences.
Index ¶
- Constants
- func MarshalSharedWith(users []string) *string
- func MentionLines(body string) map[string]string
- func NewNoteServiceWithAttachments(repo NoteRepository, attRepo AttachmentRepository) *noteService
- func PlainText(body string, label func(noteID string) string) string
- func RegisterAppGrantRoutes(e *echo.Echo, h *Handler, gh *AppGrantHandler, grants AppGrantService, ...) *echo.Group
- func RegisterRoutes(e *echo.Echo, h *Handler, campaignSvc campaigns.CampaignService, ...)
- func RequireAppGrant(grants AppGrantService, gate AppGate) echo.MiddlewareFunc
- func StartAppGrantPruner(ctx context.Context, svc AppGrantService)
- func UnmarshalSharedWith(raw *string) []string
- type AppConnectionRevoker
- type AppGate
- type AppGrant
- type AppGrantHandler
- func (h *AppGrantHandler) Allow(c *echo.Context) error
- func (h *AppGrantHandler) AllowEmbedMode(mode string)
- func (h *AppGrantHandler) List(c *echo.Context) error
- func (h *AppGrantHandler) MediaLinks(c *echo.Context) error
- func (h *AppGrantHandler) Revoke(c *echo.Context) error
- func (h *AppGrantHandler) SetMediaLinker(l MediaLinker)
- func (h *AppGrantHandler) ShowAllow(c *echo.Context) error
- func (h *AppGrantHandler) ShowEmbed(c *echo.Context) error
- type AppGrantRepository
- type AppGrantService
- type AttachmentRepository
- type AttachmentService
- type Audience
- type Block
- type BulkRequest
- type BulkResult
- type CharacterLister
- type ChecklistItem
- type ClaimedCharacter
- type CreateNoteRequest
- type Handler
- func (h *Handler) Backlinks(c *echo.Context) error
- func (h *Handler) Bulk(c *echo.Context) error
- func (h *Handler) Create(c *echo.Context) error
- func (h *Handler) Delete(c *echo.Context) error
- func (h *Handler) DeleteAttachment(c *echo.Context) error
- func (h *Handler) EmbedFragment(c *echo.Context) error
- func (h *Handler) ForceUnlock(c *echo.Context) error
- func (h *Handler) Get(c *echo.Context) error
- func (h *Handler) GetVersion(c *echo.Context) error
- func (h *Handler) Heartbeat(c *echo.Context) error
- func (h *Handler) Index(c *echo.Context) error
- func (h *Handler) Labels(c *echo.Context) error
- func (h *Handler) List(c *echo.Context) error
- func (h *Handler) ListAttachments(c *echo.Context) error
- func (h *Handler) ListVersions(c *echo.Context) error
- func (h *Handler) Lock(c *echo.Context) error
- func (h *Handler) MembersAPI(c *echo.Context) error
- func (h *Handler) PageNames(c *echo.Context) error
- func (h *Handler) PageRefs(c *echo.Context) error
- func (h *Handler) RestoreVersion(c *echo.Context) error
- func (h *Handler) Search(c *echo.Context) error
- func (h *Handler) SendToJournal(c *echo.Context) error
- func (h *Handler) SetAttachmentService(as AttachmentService)
- func (h *Handler) SetCharacterLister(cl CharacterLister)
- func (h *Handler) SetJotsGate(g AppGate)
- func (h *Handler) SetMediaUploader(mu MediaUploader)
- func (h *Handler) SetMemberLister(ml MemberLister)
- func (h *Handler) SetPageLinker(pl PageLinker)
- func (h *Handler) SetPageNamer(pn PageNamer)
- func (h *Handler) SetPictureUploader(u PictureUploader)
- func (h *Handler) ShowJournal(c *echo.Context) error
- func (h *Handler) ToggleCheck(c *echo.Context) error
- func (h *Handler) Unlock(c *echo.Context) error
- func (h *Handler) Update(c *echo.Context) error
- func (h *Handler) UpdateTranscript(c *echo.Context) error
- func (h *Handler) UploadAttachment(c *echo.Context) error
- func (h *Handler) UploadPicture(c *echo.Context) error
- type IndexRow
- type JournalIndex
- type JournalView
- type Link
- type LinksIn
- type ListScope
- type MediaLinker
- type MediaUploader
- type MemberLister
- type NightEntries
- type NightTag
- type NoopNoteEventPublisher
- type Note
- type NoteAttachment
- type NoteEvent
- type NoteEventPublisher
- type NoteLabel
- type NoteRef
- type NoteRepository
- type NoteService
- type NoteVersion
- type OriginAllower
- type PageLinker
- type PageNamer
- type PageRef
- type PictureUploader
- type SearchHit
- type SendResult
- type ToggleCheckRequest
- type TreeRow
- type UpdateNoteRequest
- type Visibility
Constants ¶
const ( LinkNote = "note" LinkPage = "page" )
Link kinds.
const LockTimeout = 5 * time.Minute
LockTimeout is how long an edit lock remains valid without a heartbeat.
const MaxBulkIDs = 500
MaxBulkIDs caps one bulk request; the list pane selects in pages.
const MaxVersionsPerNote = 50
MaxVersionsPerNote caps the version history per note. Oldest versions are pruned when this limit is exceeded.
const NoteLinkText = "Journal note"
NoteLinkText is the stored text of every [[note]] anchor.
Variables ¶
This section is empty.
Functions ¶
func MarshalSharedWith ¶
MarshalSharedWith converts a SharedWith slice to JSON for database storage. Returns nil if the slice is nil (preserving the is_shared fallback behavior).
func MentionLines ¶
MentionLines returns, for each page linked in body, the text of the first paragraph (or list item, heading, cell) that links it, so a reader can be shown the line a page was named in. Note links keep their stored neutral text, never a title.
func NewNoteServiceWithAttachments ¶
func NewNoteServiceWithAttachments(repo NoteRepository, attRepo AttachmentRepository) *noteService
NewNoteServiceWithAttachments creates a note service with attachment support.
func PlainText ¶
PlainText returns a body's text with whitespace collapsed. Each note link reads as label(id): the target's title when the reader may see it, or a neutral word when not, never the stored anchor text.
func RegisterAppGrantRoutes ¶
func RegisterAppGrantRoutes(e *echo.Echo, h *Handler, gh *AppGrantHandler, grants AppGrantService, gate AppGate, campaignSvc campaigns.CampaignService, authSvc auth.AuthService) *echo.Group
RegisterAppGrantRoutes mounts the Allow window, the player's list of grants, and the notes JSON routes for an allowed app.
The app routes live under /api/ because they are authenticated by a Bearer grant, never a cookie, so the site's cookie CSRF check does not apply to them (it skips /api/). Each request still runs as the player at their live campaign role through RequireCampaignAccess.
It returns the app group so other plugins can add the few read-only routes the notes editor needs (page search), wired in app/routes.go.
func RegisterRoutes ¶
func RegisterRoutes(e *echo.Echo, h *Handler, campaignSvc campaigns.CampaignService, authSvc auth.AuthService)
RegisterRoutes sets up all note-related routes on the given Echo instance. Note routes are scoped to a campaign and require campaign membership. All members can manage their own notes and interact with shared notes.
func RequireAppGrant ¶
func RequireAppGrant(grants AppGrantService, gate AppGate) echo.MiddlewareFunc
RequireAppGrant authenticates a request by a notes grant token in Authorization: Bearer and makes it the grant's player for what follows. The grant is tied to one campaign; a token used against another campaign is refused here, before the campaign's own membership check runs. Must sit before campaigns.RequireCampaignAccess, which checks the player is still a member at their live role.
func StartAppGrantPruner ¶
func StartAppGrantPruner(ctx context.Context, svc AppGrantService)
StartAppGrantPruner deletes dead grants now and then once a day until ctx ends.
func UnmarshalSharedWith ¶
UnmarshalSharedWith parses the JSON shared_with column from the database.
Types ¶
type AppConnectionRevoker ¶
type AppConnectionRevoker interface {
// RevokeNotesAppClients closes the player's notes grant sockets in the
// campaign.
RevokeNotesAppClients(campaignID, userID string)
// RevokeNotesAppClientsEverywhere closes the user's notes grant sockets
// in every campaign.
RevokeNotesAppClientsEverywhere(userID string)
}
AppConnectionRevoker closes the live sockets a grant opened. Implemented by the WebSocket hub, wired in app/routes.go.
type AppGate ¶
AppGate says whether a campaign lets outside apps in at all. Wired to the campaign's Sync API switch, so an owner who turns it off cuts off every player's notebook too, as it cuts off the GM's sync.
type AppGrant ¶
type AppGrant struct {
ID string `json:"id"`
CampaignID string `json:"campaignId"`
UserID string `json:"userId"`
Origin string `json:"origin"`
CreatedAt time.Time `json:"createdAt"`
LastUsedAt *time.Time `json:"lastUsedAt,omitempty"`
RevokedAt *time.Time `json:"-"`
}
AppGrant is one player's grant, as shown back to them. The token is never part of it.
type AppGrantHandler ¶
type AppGrantHandler struct {
// contains filtered or unexported fields
}
AppGrantHandler serves the Allow window and the player's list of grants.
func NewAppGrantHandler ¶
func NewAppGrantHandler(grants AppGrantService, origins OriginAllower) *AppGrantHandler
NewAppGrantHandler creates the handler for the Allow window.
func (*AppGrantHandler) Allow ¶
func (h *AppGrantHandler) Allow(c *echo.Context) error
Allow makes a grant for the signed-in player (POST /campaigns/:id/notes/allow-app) and returns the token once, to the Allow window's own script, which hands it to the opener at exactly that origin.
func (*AppGrantHandler) AllowEmbedMode ¶
func (h *AppGrantHandler) AllowEmbedMode(mode string)
AllowEmbedMode lets the frame shell open in mode, for another plugin's page served over the same grant (wired in app/routes.go). The shell is the same empty page whatever the mode; notes_embed.js picks the fragment.
func (*AppGrantHandler) List ¶
func (h *AppGrantHandler) List(c *echo.Context) error
List returns the player's live grants (GET /campaigns/:id/notes/app-grants).
func (*AppGrantHandler) MediaLinks ¶
func (h *AppGrantHandler) MediaLinks(c *echo.Context) error
MediaLinks returns short-lived signed addresses for the pictures and voice memos in the notes a frame shows (POST /api/notes-app/campaigns/:id/notes/media-links). The frame's <img> and <audio> can't send the grant, so each gets a link instead; only files the player may open on the site are signed, the rest are left out.
func (*AppGrantHandler) Revoke ¶
func (h *AppGrantHandler) Revoke(c *echo.Context) error
Revoke ends one of the player's grants (DELETE /campaigns/:id/notes/app-grants/:gid).
func (*AppGrantHandler) SetMediaLinker ¶
func (h *AppGrantHandler) SetMediaLinker(l MediaLinker)
SetMediaLinker wires the media plugin's signer for MediaLinks.
func (*AppGrantHandler) ShowAllow ¶
func (h *AppGrantHandler) ShowAllow(c *echo.Context) error
ShowAllow renders the Allow window (GET /campaigns/:id/notes/allow-app). The page talks to the window that opened it, so it must keep its opener: the site-wide Cross-Origin-Opener-Policy of same-origin would cut that link. Framing stays forbidden by the site-wide headers.
func (*AppGrantHandler) ShowEmbed ¶
func (h *AppGrantHandler) ShowEmbed(c *echo.Context) error
ShowEmbed renders the empty shell an allowed app frames (GET /embed/campaigns/:id/notes/:mode, mode journal, jots or one added by AllowEmbedMode). It needs no sign-in and shows nothing about the campaign: the content arrives later over the grant the parent window hands it. Only the allowed origins may frame it; everywhere else the site stays unframeable.
type AppGrantRepository ¶
type AppGrantRepository interface {
Create(ctx context.Context, g *AppGrant, tokenHash string) error
FindByTokenHash(ctx context.Context, tokenHash string) (*AppGrant, error)
ListLive(ctx context.Context, campaignID, userID string) ([]AppGrant, error)
// ListLiveForUser is ListLive across every campaign.
ListLiveForUser(ctx context.Context, userID string) ([]AppGrant, error)
Revoke(ctx context.Context, id string, at time.Time) error
Touch(ctx context.Context, id string, at time.Time) error
RevokeAllForUser(ctx context.Context, userID string, at time.Time) error
// DeleteDead deletes every grant that can never authenticate again:
// revoked, or unused since idleBefore.
DeleteDead(ctx context.Context, idleBefore time.Time) (int64, error)
}
AppGrantRepository is the data access for notes_app_grants.
func NewAppGrantRepository ¶
func NewAppGrantRepository(db *sql.DB) AppGrantRepository
NewAppGrantRepository creates the MariaDB-backed app grant repository.
type AppGrantService ¶
type AppGrantService interface {
// Issue makes a grant for userID in campaignID and returns the token,
// which is not stored and cannot be recovered. origin must already have
// been checked against the allowed origins by the caller.
Issue(ctx context.Context, campaignID, userID, origin string) (token string, g *AppGrant, err error)
// Authenticate returns the live grant for token, or an Unauthorized error.
Authenticate(ctx context.Context, token string) (*AppGrant, error)
// List returns the player's live grants in the campaign, newest first.
List(ctx context.Context, campaignID, userID string) ([]AppGrant, error)
// Revoke ends one of the player's own grants. Someone else's grant, or
// one in another campaign, is NotFound.
Revoke(ctx context.Context, campaignID, userID, grantID string) error
// ListForUser returns the user's live grants in every campaign, newest
// first, for their account page.
ListForUser(ctx context.Context, userID string) ([]AppGrant, error)
// RevokeForUser ends one of the user's own grants in whichever campaign
// it is. Someone else's grant is NotFound.
RevokeForUser(ctx context.Context, userID, grantID string) error
// RevokeAllForUser ends every grant the user holds, in every campaign.
// Runs when all the user's sessions are destroyed (password reset or
// change, force sign-out), so a grant never outlives them.
RevokeAllForUser(ctx context.Context, userID string) error
// RevokeAllInCampaign ends every grant the user holds in one campaign.
// Runs when the user is removed from it, so being invited back does not
// bring an old grant back to life.
RevokeAllInCampaign(ctx context.Context, campaignID, userID string) error
// PruneDead deletes the grants that can never authenticate again, so a
// revoked or expired token's row doesn't stay in the table forever.
PruneDead(ctx context.Context) (int64, error)
// SetConnectionRevoker wires the live-socket drop that makes a revoke
// take effect on an open notes frame at once.
SetConnectionRevoker(r AppConnectionRevoker)
}
AppGrantService issues, checks and revokes app grants.
func NewAppGrantService ¶
func NewAppGrantService(repo AppGrantRepository) AppGrantService
NewAppGrantService creates the app grant service.
type AttachmentRepository ¶
type AttachmentRepository interface {
CreateAttachment(ctx context.Context, a *NoteAttachment) error
ListByNote(ctx context.Context, noteID string) ([]NoteAttachment, error)
FindAttachmentByID(ctx context.Context, id string) (*NoteAttachment, error)
DeleteAttachment(ctx context.Context, id string) error
UpdateTranscript(ctx context.Context, id string, transcript string) error
// NotesWithAttachments returns the ids of the campaign's notes that have
// at least one attachment. Unfiltered: callers intersect it with notes
// the viewer can see.
NotesWithAttachments(ctx context.Context, campaignID string) (map[string]bool, error)
}
AttachmentRepository defines the data access contract for note attachments.
func NewAttachmentRepository ¶
func NewAttachmentRepository(db *sql.DB) AttachmentRepository
NewAttachmentRepository creates a new MariaDB-backed attachment repository.
type AttachmentService ¶
type AttachmentService interface {
ListAttachments(ctx context.Context, noteID string) ([]NoteAttachment, error)
GetAttachment(ctx context.Context, id string) (*NoteAttachment, error)
CreateAttachment(ctx context.Context, a *NoteAttachment) error
DeleteAttachment(ctx context.Context, id string) (filePath string, err error)
UpdateTranscript(ctx context.Context, id, transcript string) error
}
AttachmentService defines the business logic for note attachments.
type Audience ¶
type Audience struct {
Everyone bool // shared with the party
GMs bool // shared with the campaign Owner and co-DMs
Users []string // the owner and anyone the note names
}
Audience is who may be told a note changed. Everyone overrides the rest.
type Block ¶
type Block struct {
Type string `json:"type"` // "text" or "checklist"
Value string `json:"value,omitempty"` // For type "text"
Items []ChecklistItem `json:"items,omitempty"` // For type "checklist"
}
Block is a single content block within a note. Discriminated by Type.
type BulkRequest ¶
type BulkRequest struct {
Action string `json:"action"` // archive, unarchive, move, visibility, delete
IDs []string `json:"ids"`
FolderID string `json:"folderId,omitempty"` // move: "" means the top level
Visibility Visibility `json:"visibility,omitempty"`
}
BulkRequest applies one action to many notes. Only the caller's own notes change; the rest are reported back as skipped.
type BulkResult ¶
BulkResult lists which notes the action changed and which it left alone.
type CharacterLister ¶
type CharacterLister interface {
ClaimedCharacters(ctx context.Context, campaignID, userID string) ([]ClaimedCharacter, error)
}
CharacterLister names the characters a player has claimed, for the Journal's "Playing …" card. An adapter over the entities service satisfies it, so this widget never imports a plugin.
type ChecklistItem ¶
ChecklistItem is a single item in a checklist block.
type ClaimedCharacter ¶
ClaimedCharacter is one character a player plays.
type CreateNoteRequest ¶
type CreateNoteRequest struct {
EntityID *string `json:"entityId,omitempty"`
ParentID *string `json:"parentId,omitempty"`
IsFolder bool `json:"isFolder,omitempty"`
Title string `json:"title"`
Content []Block `json:"content"`
Color string `json:"color,omitempty"`
// Visibility, when set, decides the audience instead of IsShared/SharedWith.
// Absent means private: a new note is private to its writer until they
// choose to share it.
Visibility Visibility `json:"visibility,omitempty"`
// ID lets an in-process caller that must find its note again (the DM
// Screen's notes) fix the id instead of drawing one. Never decoded from a
// request body, so API clients cannot choose ids.
ID string `json:"-"`
}
CreateNoteRequest holds the data submitted when creating a new note.
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
Handler handles HTTP requests for note operations. Handlers are thin: bind request, call service, render response. No business logic lives here.
func NewHandler ¶
func NewHandler(service NoteService) *Handler
NewHandler creates a new note handler backed by the given service.
func (*Handler) Backlinks ¶
Backlinks lists what links to a note, as far as the viewer may see: notes and pages (GET /campaigns/:id/notes/:noteId/backlinks).
func (*Handler) Bulk ¶
Bulk applies one action to several of the viewer's own notes (POST /campaigns/:id/notes/bulk).
func (*Handler) Delete ¶
Delete removes a note (DELETE /campaigns/:id/notes/:noteId). Only the note owner can delete.
func (*Handler) DeleteAttachment ¶
DeleteAttachment removes an attachment. DELETE /campaigns/:id/notes/:nid/attachments/:aid
func (*Handler) EmbedFragment ¶
EmbedFragment returns the Journal or the Jot notes panel as an HTML fragment for the frame an allowed app shows (GET /api/notes-app/campaigns/:id/notes/embed?mode=journal|jots&entity=). The same templates as the site, so the frame has every Journal feature.
func (*Handler) ForceUnlock ¶
ForceUnlock releases any user's lock (POST /campaigns/:id/notes/:noteId/force-unlock). Requires campaign owner role.
func (*Handler) GetVersion ¶
GetVersion returns a specific version (GET /campaigns/:id/notes/:noteId/versions/:vid).
func (*Handler) Heartbeat ¶
Heartbeat keeps the edit lock alive (POST /campaigns/:id/notes/:noteId/heartbeat).
func (*Handler) Labels ¶
Labels resolves [[note]] link labels for the viewer (GET /campaigns/:id/notes/labels?ids=a,b,…). A note the viewer cannot see is absent from the result, exactly like one that does not exist.
func (*Handler) List ¶
List returns notes for the current user in the campaign (GET /campaigns/:id/notes). Returns own notes + shared notes from other users. Supports ?scope=all (default), ?scope=campaign (campaign-wide only), and ?scope=entity&entity_id=<eid> (entity-scoped).
func (*Handler) ListAttachments ¶
ListAttachments returns attachments for a note. GET /campaigns/:id/notes/:nid/attachments
func (*Handler) ListVersions ¶
ListVersions returns version history (GET /campaigns/:id/notes/:noteId/versions).
func (*Handler) Lock ¶
Lock acquires the edit lock on a shared note (POST /campaigns/:id/notes/:noteId/lock).
func (*Handler) MembersAPI ¶
MembersAPI returns campaign members as JSON for the share-with-players picker. GET /campaigns/:id/notes/members
func (*Handler) PageNames ¶
PageNames names the pages behind jots, for the viewer (GET /campaigns/:id/notes/page-names?ids=a,b,…). A page the viewer cannot see is absent, exactly like one that does not exist.
func (*Handler) PageRefs ¶
PageRefs lists the viewer's Journal notes that link to a page (GET /campaigns/:id/notes/page-refs?entity_id=…).
func (*Handler) RestoreVersion ¶
RestoreVersion reverts a note to a previous version (POST /campaigns/:id/notes/:noteId/versions/:vid/restore).
func (*Handler) Search ¶
Search finds the viewer's notes by title or text (GET /campaigns/:id/notes/search?q=…[&jots=1]).
func (*Handler) SendToJournal ¶
SendToJournal copies one of the caller's jots into a new Journal note (POST /campaigns/:id/notes/:noteId/send-to-journal). Owner only.
func (*Handler) SetAttachmentService ¶
func (h *Handler) SetAttachmentService(as AttachmentService)
SetAttachmentService sets the attachment service for audio upload support.
func (*Handler) SetCharacterLister ¶
func (h *Handler) SetCharacterLister(cl CharacterLister)
SetCharacterLister sets the lookup behind the Journal's claim card.
func (*Handler) SetJotsGate ¶
SetJotsGate sets the check for whether Jot notes are on in a campaign (the "notes" addon), for the frames an outside app shows.
func (*Handler) SetMediaUploader ¶
func (h *Handler) SetMediaUploader(mu MediaUploader)
SetMediaUploader sets the media uploader for attachment file storage.
func (*Handler) SetMemberLister ¶
func (h *Handler) SetMemberLister(ml MemberLister)
SetMemberLister sets the member lister for the share-with-players picker.
func (*Handler) SetPageLinker ¶
func (h *Handler) SetPageLinker(pl PageLinker)
SetPageLinker sets the lookup of pages that link a note, for backlinks.
func (*Handler) SetPageNamer ¶
SetPageNamer sets the lookup that names the pages jots sit on.
func (*Handler) SetPictureUploader ¶
func (h *Handler) SetPictureUploader(u PictureUploader)
SetPictureUploader wires the store for pictures written into notes.
func (*Handler) ShowJournal ¶
ShowJournal renders the Journal (GET /campaigns/:id/journal, and /journal/:noteId to open it at one note). Full page or HTMX fragment.
func (*Handler) ToggleCheck ¶
ToggleCheck toggles a checklist item (POST /campaigns/:id/notes/:noteId/toggle).
func (*Handler) Update ¶
Update modifies an existing note (PUT /campaigns/:id/notes/:noteId). Access: anyone who can view the note may edit its title and body; only its owner may change sharing, pinning, archiving or its folder.
func (*Handler) UpdateTranscript ¶
UpdateTranscript saves or updates the transcript text for an attachment. PUT /campaigns/:id/notes/:nid/attachments/:aid/transcript
func (*Handler) UploadAttachment ¶
UploadAttachment uploads an audio file and attaches it to a note. POST /campaigns/:id/notes/:nid/attachments
func (*Handler) UploadPicture ¶
UploadPicture stores a picture a player is writing into a note and returns its media id (POST /campaigns/:id/notes/pictures). Open to every member who can use notes: unlike /media/upload it needs no Scribe role, because the file is private to the readers of the note that ends up holding it.
type IndexRow ¶
type IndexRow struct {
ID string `json:"id"`
Title string `json:"title"`
ParentID *string `json:"parentId,omitempty"`
IsFolder bool `json:"isFolder"`
UserID string `json:"userId"`
Visibility Visibility `json:"visibility"`
Pinned bool `json:"pinned"`
Archived bool `json:"archived"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
Snippet string `json:"snippet,omitempty"`
Links []Link `json:"links,omitempty"`
InCount int `json:"inCount"`
HasAudio bool `json:"hasAudio"`
LockedBy *string `json:"lockedBy,omitempty"`
// Night is set on a game night's entry: the night it belongs to.
Night *NightTag `json:"night,omitempty"`
}
IndexRow is one Journal note or folder as the list pane needs it: enough to draw, filter, group and peek at a row without loading its body.
type JournalIndex ¶
type JournalIndex struct {
Notes []IndexRow `json:"notes"`
}
JournalIndex is the Journal's list: every visible Journal note and folder.
type JournalView ¶
type JournalView struct {
NoteID string // the note to open (deep link), when id-shaped
IsGM bool // the campaign Owner or a co-DM
Character *ClaimedCharacter // a player's character, for the claim card
}
JournalView is what the Journal page needs from the server. The notes themselves load over the JSON routes, each behind the visibility gate, so nothing here reveals a note.
type Link ¶
type Link struct {
Kind string `json:"kind"`
ID string `json:"id"`
Label string `json:"label,omitempty"`
}
Link is one outgoing link in a note body. Label is set for page links only: the page name as written in the anchor, which the reader of this body can already see.
func ParseLinks ¶
ParseLinks returns the distinct outgoing links of a note body, in order.
type ListScope ¶
type ListScope struct {
// Kind is "" (all), "campaign" (Journal notes and folders: no page),
// "entity" (the jots on EntityID) or "jots" (every jot on any page).
Kind string
EntityID string
}
ListScope narrows ListVisible. The zero value lists every visible note.
type MediaLinker ¶
type MediaLinker interface {
SignedLinksForMember(ctx context.Context, campaignID, userID string, paths []string) map[string]string
}
MediaLinker signs media paths a member may open so a page with no session cookie (the frames) can load them. Implemented by the media plugin and wired in app/routes.go.
type MediaUploader ¶
type MediaUploader interface {
UploadRaw(ctx context.Context, campaignID, userID string, fileBytes []byte, originalName, mimeType string) (filePath string, err error)
}
MediaUploader is an interface for uploading files to the media system.
type MemberLister ¶
type MemberLister interface {
ListMembers(ctx context.Context, campaignID string) ([]campaigns.CampaignMember, error)
}
MemberLister is satisfied by CampaignService for fetching campaign members.
type NightEntries ¶
type NightEntries interface {
// EnsureEntries makes v's entries for the game nights that are due.
EnsureEntries(ctx context.Context, campaignID string, v permissions.Viewer) error
// Nights returns, for those of noteIDs that are game-night entries, the
// night each belongs to.
Nights(ctx context.Context, campaignID string, noteIDs []string) (map[string]NightTag, error)
}
NightEntries is the game-night side of the Journal, supplied by the sessions plugin. Each member's entry for a game night is an ordinary note it makes for them; the Journal asks for those to be made when it opens and tags each one with its night.
type NightTag ¶
type NightTag struct {
SessionID string `json:"sessionId"`
Date string `json:"date"`
Name string `json:"name"`
Time string `json:"time,omitempty"`
// Started is whether the night has begun: from then on the entry is
// read for the DM's check-in, if the DM can read it.
Started bool `json:"started"`
}
NightTag is the game night an entry belongs to.
type NoopNoteEventPublisher ¶
type NoopNoteEventPublisher struct{}
NoopNoteEventPublisher is a no-op implementation for tests.
func (NoopNoteEventPublisher) PublishNoteEvent ¶
func (NoopNoteEventPublisher) PublishNoteEvent(NoteEvent)
PublishNoteEvent discards the event.
type Note ¶
type Note struct {
ID string `json:"id"`
CampaignID string `json:"campaignId"`
UserID string `json:"userId"`
EntityID *string `json:"entityId,omitempty"` // nil = Journal note; set = that page's jot
LinkedNoteID *string `json:"linkedNoteId,omitempty"` // jot sent to the Journal: the note it became
ParentID *string `json:"parentId,omitempty"` // nil = top-level note/folder
IsFolder bool `json:"isFolder"` // true = folder container
Title string `json:"title"`
Content []Block `json:"content"` // Legacy block content
Entry *string `json:"entry,omitempty"` // ProseMirror JSON (rich text)
EntryHTML *string `json:"entryHtml,omitempty"` // Pre-rendered HTML from entry
Color string `json:"color"`
Pinned bool `json:"pinned"`
ArchivedAt *time.Time `json:"archivedAt,omitempty"`
Archived bool `json:"archived"` // derived from ArchivedAt
Visibility Visibility `json:"visibility"` // derived from the three sharing columns
LastEditedBy *string `json:"lastEditedBy,omitempty"`
LockedBy *string `json:"lockedBy,omitempty"`
LockedAt *time.Time `json:"lockedAt,omitempty"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
Note represents a single note within a campaign: a Journal note, a jot on a page, or a folder.
func (*Note) CanView ¶
func (n *Note) CanView(v permissions.Viewer, campaignID string) bool
CanView reports whether v may read this note within campaignID: its owner, anyone when it is shared with the party, a named person when it is shared with them, and the campaign's GMs (Owner or co-DM) when it is shared with the GM. Private is private from the GM too, so SkipsPerUserRules is never consulted, and an anonymous viewer sees nothing.
Lives on the model because every path that addresses a single note (the web routes and the REST API v1 routes) must apply the identical predicate, and neither the repository nor the service filters the single-resource path (`WHERE id = ?`); a route that forgets it is an IDOR. The repository's visibleFilter is the SQL twin of this function and must stay in step (TestDB_ListVisibilityMatchesCanView pins them together).
func (*Note) IsLocked ¶
IsLocked reports whether the note currently has an active (non-expired) lock.
func (*Note) IsLockedByUser ¶
IsLockedByUser reports whether the given user holds the active lock.
type NoteAttachment ¶
type NoteAttachment struct {
ID string `json:"id"`
NoteID string `json:"noteId"`
CampaignID string `json:"campaignId"`
FilePath string `json:"filePath"`
OriginalName string `json:"originalName"`
MimeType string `json:"mimeType"`
FileSize int64 `json:"fileSize"`
DurationSecs *int `json:"durationSecs,omitempty"`
Transcript *string `json:"transcript,omitempty"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
NoteAttachment represents a file attached to a note (audio, etc.).
type NoteEvent ¶
type NoteEvent struct {
Type string // "created", "updated" or "deleted"
CampaignID string
NoteID string
EntityID *string // the page a jot sits on; nil for a Journal note
Audience Audience
}
NoteEvent is what the live-updates layer hears when a note changes: IDs and who may hear about it, never the note itself, so a private note's title or body cannot ride a broadcast to someone who could not read it (#715).
type NoteEventPublisher ¶
type NoteEventPublisher interface {
PublishNoteEvent(ev NoteEvent)
}
NoteEventPublisher emits domain events when notes change. Implemented by the WebSocket EventBus adapter in app/routes.go.
type NoteLabel ¶
type NoteLabel struct {
Title string `json:"title"`
Archived bool `json:"archived"`
EntityID *string `json:"entityId,omitempty"`
}
NoteLabel is how a [[link]] to a note reads for this viewer.
type NoteRef ¶
type NoteRef struct {
ID string `json:"id"`
Title string `json:"title"`
Snippet string `json:"snippet,omitempty"`
EntityID *string `json:"entityId,omitempty"` // set for a jot: the page it sits on
Archived bool `json:"archived"`
}
NoteRef names a note the viewer can see, for backlink and reference lists.
type NoteRepository ¶
type NoteRepository interface {
Create(ctx context.Context, note *Note) error
FindByID(ctx context.Context, id string) (*Note, error)
Update(ctx context.Context, note *Note) error
Delete(ctx context.Context, id string) error
// ListVisible returns the notes in campaignID that v can read (the SQL
// twin of Note.CanView), narrowed by scope. Pinned first, then newest.
ListVisible(ctx context.Context, campaignID string, v permissions.Viewer, scope ListScope) ([]Note, error)
// ListTree returns the id, parent, owner and folder flag of every note in
// the campaign, with no visibility filter. Internal structure only (cycle
// and ownership checks when filing or deleting folders); never returned
// to a client.
ListTree(ctx context.Context, campaignID string) ([]TreeRow, error)
// ReparentToTop moves the given notes out of any folder.
ReparentToTop(ctx context.Context, ids []string) error
// FindByIDs loads the given notes, in no particular order. Unfiltered,
// like FindByID: the caller applies CanView to each.
FindByIDs(ctx context.Context, ids []string) ([]Note, error)
// ListVisibleLinking returns the notes v can see whose body links to the
// note (kind LinkNote) or page (LinkPage) targetID, newest first.
ListVisibleLinking(ctx context.Context, campaignID string, v permissions.Viewer, kind, targetID string) ([]Note, error)
// ViewerReadsMedia reports whether v can read at least one note bound to
// the note picture mediaID in campaignID (the SQL twin of Note.CanView over
// the bound notes). Indexed on the binding, not a scan of note bodies.
ViewerReadsMedia(ctx context.Context, campaignID, mediaID string, v permissions.Viewer) (bool, error)
// SyncPictureBindings binds the pictures of a newly created note, which has
// no stored body: every note picture in it that editorID uploaded.
SyncPictureBindings(ctx context.Context, noteID, campaignID, editorID string, html *string) error
// UpdateWithPictures saves note and settles its picture bindings in one
// transaction. A picture no longer in the text loses its binding whoever
// saved. A binding is added only when bindNew is set, the id was not in the
// stored body before this save, and editorID uploaded the picture; so an id
// someone else pasted never binds, even when the uploader saves the note
// later. bindNew is false for a restore.
UpdateWithPictures(ctx context.Context, note *Note, editorID string, bindNew bool) error
// campaign regardless of which user owns it.
//
// Deliberately has NO user filter: it exists so campaign export can
// capture the shared note corpus, which is campaign data rather than
// per-user data. Every other list method here is user-scoped and must
// stay that way (ADR-013). Callers of this one must be owner-gated —
// today the only caller is the campaign export adapter, and no HTTP
// route reaches it directly.
ListSharedByCampaign(ctx context.Context, campaignID string) ([]Note, error)
// AcquireLock attempts to set locked_by/locked_at for a note. Returns
// true if the lock was acquired, false if another user holds a live lock.
AcquireLock(ctx context.Context, noteID, userID string) (bool, error)
// ReleaseLock clears the lock on a note (only if held by the given user).
ReleaseLock(ctx context.Context, noteID, userID string) error
// ForceReleaseLock clears the lock regardless of who holds it.
ForceReleaseLock(ctx context.Context, noteID string) error
// RefreshLock updates locked_at to keep the lock alive (heartbeat).
RefreshLock(ctx context.Context, noteID, userID string) error
// CreateVersion inserts a version snapshot.
CreateVersion(ctx context.Context, v *NoteVersion) error
// ListVersions returns version history for a note, newest first.
ListVersions(ctx context.Context, noteID string, limit int) ([]NoteVersion, error)
// FindVersionByID retrieves a specific version.
FindVersionByID(ctx context.Context, id string) (*NoteVersion, error)
// PruneVersions deletes the oldest versions beyond the keep count.
PruneVersions(ctx context.Context, noteID string, keep int) error
}
NoteRepository defines the data access contract for note operations.
func NewNoteRepository ¶
func NewNoteRepository(db *sql.DB) NoteRepository
NewNoteRepository creates a new MariaDB-backed note repository.
type NoteService ¶
type NoteService interface {
// Create persists a new note owned by creator.
Create(ctx context.Context, campaignID string, creator permissions.Viewer, req CreateNoteRequest) (*Note, error)
GetByID(ctx context.Context, id string) (*Note, error)
// Update applies a partial update made by editor. The caller has already
// checked editor may view the note and stripped the owner-only fields
// (UpdateNoteRequest.StripOwnerOnly) when editor is not its owner.
Update(ctx context.Context, id string, editor permissions.Viewer, req UpdateNoteRequest) (*Note, error)
// Delete removes a note. Deleting a folder deletes the folder owner's
// notes inside it and moves everyone else's out to the top level.
Delete(ctx context.Context, id string) error
ToggleCheck(ctx context.Context, id string, req ToggleCheckRequest) (*Note, error)
// ListVisible returns the notes v can read, narrowed by scope.
ListVisible(ctx context.Context, campaignID string, v permissions.Viewer, scope ListScope) ([]Note, error)
// ListByUserAndCampaign lists what userID can read as a plain member:
// their own notes and the ones shared with them, never the ones shared
// only with the GM. Kept for callers that have a user but no role.
ListByUserAndCampaign(ctx context.Context, userID, campaignID string) ([]Note, error)
// The Journal's views (journal_service.go). Each reads only what v can see.
JournalIndex(ctx context.Context, campaignID string, v permissions.Viewer) (*JournalIndex, error)
Search(ctx context.Context, campaignID string, v permissions.Viewer, q string, withJots bool) ([]SearchHit, error)
Backlinks(ctx context.Context, campaignID string, v permissions.Viewer, noteID string) ([]NoteRef, error)
PageRefs(ctx context.Context, campaignID string, v permissions.Viewer, entityID string) ([]NoteRef, error)
Labels(ctx context.Context, campaignID string, v permissions.Viewer, ids []string) (map[string]*NoteLabel, error)
Bulk(ctx context.Context, campaignID string, v permissions.Viewer, req BulkRequest) (*BulkResult, error)
// SendToJournal copies v's own jot into a new private Journal note linked
// to the jot's page, and records it on the jot (jots.go).
SendToJournal(ctx context.Context, campaignID string, v permissions.Viewer, jotID, pageName string) (*SendResult, error)
// ViewerReadsMedia reports whether v can read a note bound to the note
// picture mediaID in campaignID (bound by the uploader's own save). The
// media plugin asks this to decide who may open a picture in notes.
ViewerReadsMedia(ctx context.Context, campaignID, mediaID string, v permissions.Viewer) (bool, error)
// all owners. Unlike the three list methods above it applies no per-user
// visibility filter, so it is owner-gated data: campaign export is the
// only caller. Notes are campaign content, and an export that omits them
// is a backup that quietly lies.
ListSharedByCampaign(ctx context.Context, campaignID string) ([]Note, error)
// Locking
AcquireLock(ctx context.Context, noteID, userID string) (*Note, error)
ReleaseLock(ctx context.Context, noteID, userID string) error
ForceReleaseLock(ctx context.Context, noteID string) error
Heartbeat(ctx context.Context, noteID, userID string) error
// Versions
ListVersions(ctx context.Context, noteID string) ([]NoteVersion, error)
GetVersion(ctx context.Context, versionID string) (*NoteVersion, error)
RestoreVersion(ctx context.Context, noteID, versionID, userID string) (*Note, error)
}
NoteService defines the business logic contract for notes.
func NewNoteService ¶
func NewNoteService(repo NoteRepository) NoteService
NewNoteService creates a new note service.
type NoteVersion ¶
type NoteVersion struct {
ID string `json:"id"`
NoteID string `json:"noteId"`
UserID string `json:"userId"`
Title string `json:"title"`
Content []Block `json:"content"`
Entry *string `json:"entry,omitempty"`
EntryHTML *string `json:"entryHtml,omitempty"`
CreatedAt time.Time `json:"createdAt"`
}
NoteVersion is a historical snapshot of a note's content at a point in time.
type OriginAllower ¶
type OriginAllower interface {
OriginAllowed(ctx context.Context, origin string) bool
// AllowedOrigins lists them, for the frame-ancestors of the notes pages
// an app shows in a frame.
AllowedOrigins(ctx context.Context) []string
}
OriginAllower says whether a web origin may receive a notes grant. It is the same list that lets that origin call Chronicle across sites (the site address plus the admin's allowed origins), so an admin who has not allowed a Foundry address cannot have players' notes handed to it.
type PageLinker ¶
type PageLinker interface {
PagesLinkingNote(ctx context.Context, campaignID string, v permissions.Viewer, seesSecrets bool, noteID string) ([]PageRef, error)
}
PageLinker lists the pages that link a note, only those the viewer may see. seesSecrets says whether the viewer reads a page's inline GM secrets; for anyone else a page whose only link sits inside one is left out, or the list would say what the secret mentions. An adapter over the entities service satisfies it, so this widget never imports a plugin.
type PageNamer ¶
type PageNamer interface {
PageNames(ctx context.Context, campaignID string, v permissions.Viewer, ids []string) (map[string]string, error)
}
PageNamer names pages for a viewer: only pages of the campaign the viewer may see, and nothing at all for the rest. An adapter over the entities service satisfies it, so this widget never imports a plugin.
type PageRef ¶
type PageRef struct {
ID string `json:"id"`
Name string `json:"name"`
TypeName string `json:"typeName,omitempty"`
}
PageRef names a page in a backlink list, and nothing of its body.
type PictureUploader ¶
type PictureUploader interface {
UploadPicture(ctx context.Context, campaignID, userID string, fileBytes []byte, originalName, mimeType string) (mediaID string, err error)
}
PictureUploader stores a picture written into a note and returns its media id. Separate from MediaUploader because the file is not an attachment: only readers of a note holding it may open it (media.UsageNoteImage).
type SendResult ¶
type SendResult struct {
Jot *Note `json:"jot"`
Note *Note `json:"note"`
Existing bool `json:"existing"` // sent before; nothing new was made
}
SendResult is a jot and the Journal note it was sent to.
type ToggleCheckRequest ¶
type ToggleCheckRequest struct {
BlockIndex int `json:"blockIndex"`
ItemIndex int `json:"itemIndex"`
}
ToggleCheckRequest toggles a single checklist item's checked state.
type UpdateNoteRequest ¶
type UpdateNoteRequest struct {
Title *string `json:"title,omitempty"`
Content *[]Block `json:"content,omitempty"`
Entry *string `json:"entry,omitempty"`
EntryHTML *string `json:"entryHtml,omitempty"`
Color *string `json:"color,omitempty"`
Pinned *bool `json:"pinned,omitempty"`
ParentID *string `json:"parentId,omitempty"` // move note into/out of folder ("" = top level)
// Visibility sets the audience in one field; wins over IsShared/SharedWith
// when both are sent. SharedWith supplies the people for "custom".
Visibility *Visibility `json:"visibility,omitempty"`
Archived *bool `json:"archived,omitempty"`
}
UpdateNoteRequest holds the data submitted when updating a note.
func (*UpdateNoteRequest) StripOwnerOnly ¶
func (r *UpdateNoteRequest) StripOwnerOnly()
StripOwnerOnly drops the fields only a note's owner may change, so a person the note is shared with can still save its title and body. Dropped, not refused: a client that echoes the whole note back must not fail the edit.
type Visibility ¶
type Visibility string
Visibility is who besides its owner can read a note. It is derived from three columns rather than stored as one, so the rows written before the GM state existed keep their exact audience and older sync clients that only know isShared/sharedWith keep working:
party is_shared = TRUE custom shared_with names at least one person gm shared_with_gm = TRUE (the campaign Owner and co-DMs) private none of the above: the owner alone, not even the GM
const ( VisibilityPrivate Visibility = "private" VisibilityGM Visibility = "gm" VisibilityParty Visibility = "party" VisibilityCustom Visibility = "custom" )
The four audiences a note can have.
func (Visibility) Valid ¶
func (v Visibility) Valid() bool
Valid reports whether v is one of the four audiences.