Documentation
¶
Overview ¶
Package campaigns — export.go defines the JSON structure for campaign exports. A campaign export is a self-contained JSON document that captures all campaign data: metadata, entity types, entities, tags, relations, calendar, timelines, sessions, maps, notes, and addon configuration.
Media files are not embedded in the JSON itself; the export includes a media manifest with file metadata, and ?include_media=1 bundles the actual bytes alongside it in a zip (see export_handler.go).
Package campaigns — export_handler.go provides HTTP handlers for campaign export and import. Export downloads a JSON file (or a zip with media bytes when ?include_media=1 is set). Import accepts either format and creates a new campaign from it.
Package campaigns — export_service.go implements the campaign export/import business logic. Uses adapter interfaces for all cross-plugin data access to avoid circular imports.
Package campaigns — import.go handles parsing and applying campaign imports. Import creates a new campaign from a CampaignExport JSON document, remapping all IDs and foreign key references to avoid conflicts with existing data.
Package campaigns — import_media.go restores the picture files a ZIP export carries and points every reference in the file at the restored copies.
Package campaigns — import_report.go carries the per-object failure tally for a campaign import.
Import is deliberately best-effort: one bad row must not abandon a half-created campaign, so every importer catches its own per-row errors and moves on. A restore that quietly drops rows is worse than one that fails, because the operator stops looking — so ImportReport keeps the best-effort behaviour and adds the missing half: every skip is recorded, counted, and shown. The report threads through the importer adapters exactly like *IDMap does.
Package campaigns manages campaigns (worldbuilding containers) and their role-based membership system. A campaign is the top-level organizational unit that holds all entities, maps, timelines, etc.
This is a CORE plugin -- always enabled, cannot be disabled.
Package campaigns — smoketest.go provides a startup probe that verifies the campaign SELECT+Scan pattern works. Co-located with repository.go so that any change to the query or struct fields is immediately adjacent to the smoke test that validates them.
Index ¶
- Constants
- Variables
- func AllowPublicCampaignAccess(service CampaignService) echo.MiddlewareFunc
- func AppliedLookPicks(ap *Appearance, cc *CampaignContext, stored map[string]string) map[string]string
- func BlockFragmentURL(campaignID, blockType, onEntityID string) (string, bool)
- func BlockVisibleTo(ctx context.Context, cc *CampaignContext, checker BlockPlacementChecker, ...) bool
- func BuildFoundryConnectLine(baseURL, campaignID, key string) (string, error)
- func CleanNavPins(pins []string, pinnable map[string]bool) ([]string, error)
- func CleanOwnerNavPins(pins []string) ([]string, error)
- func ConfigureLeaving(svc CampaignService, chars CharacterReleaser, notifier LeaveNotifier)
- func ConfigureVisitPasses(svc CampaignService, v VisitPasses)
- func DeskPage(cc *CampaignContext, d *Desk) templ.Component
- func EmailLayoutOf(c *Campaign) mailbody.Layout
- func ExtensionDashboardPageURL(slug, campaignID string) (string, bool)
- func GuestHomeHasBlock(c *Campaign, blockType string) bool
- func GuestPreviewAsked(c *echo.Context) bool
- func GuestPreviewLowers(c *echo.Context, campaign *Campaign, member *CampaignMember) bool
- func GuestsNoteAsked(c *echo.Context, cc *CampaignContext) bool
- func HasExtensionDashboard(slug string) bool
- func HeroDays(n int) string
- func HomeBlockTypes() []string
- func HomeHasBlock(l *DashboardLayout, blockType string) bool
- func LookAccessAllows(setting string, cc *CampaignContext) bool
- func LookChoiceLabel(id string) string
- func MediaZipName(storedFilename string) string
- func MemberAccess(c *Campaign, m CampaignMember) string
- func MemberAccessLabel(c *Campaign, m CampaignMember) string
- func MemberAccessNote(c *Campaign, m CampaignMember) string
- func MemberHome(c *echo.Context) (id, name string, ok bool)
- func NavAppKey(slug string) string
- func NavCategoryKey(id int) string
- func NavKeyKind(key string) (kind, ref string, ok bool)
- func NavLinkKey(id string) string
- func OnCampaignDeleted(svc CampaignService, fn func(ctx context.Context, campaignID string))
- func OnMemberRemoved(svc CampaignService, fn func(ctx context.Context, campaignID, userID string))
- func OnMemberRoleChanged(svc CampaignService, ...)
- func OwnerCardVisible(ctx context.Context, cc *CampaignContext) bool
- func PinnableNavKeys(secs []NavSection) map[string]bool
- func PlaceableBlockTypes() []string
- func RedactMemberCharacters(members []CampaignMember, visibilityRole int, viewerID string)
- func RegisterExportRoutes(e *echo.Echo, eh *ExportHandler, svc CampaignService, authSvc auth.AuthService)
- func RegisterInviteRoutes(e *echo.Echo, ih *InviteHandler, svc CampaignService, authSvc auth.AuthService)
- func RegisterRoutes(e *echo.Echo, h *Handler, svc CampaignService, authSvc auth.AuthService)
- func RequireCampaignAccess(service CampaignService) echo.MiddlewareFunc
- func RequireCampaignAccessEvenIfArchived(service CampaignService) echo.MiddlewareFunc
- func RequireCapability(check func(*CampaignContext) bool, denyMsg string) echo.MiddlewareFunc
- func RequireRole(minRole Role) echo.MiddlewareFunc
- func RequireViewAccess() echo.MiddlewareFunc
- func ResolveDashboardTile(ctx context.Context, campaignID string, t tilegrid.Tile) (w, h int, ok bool)
- func ScanSmokeTest() database.SmokeTest
- func SetTileSizeResolver(r TileSizeResolver)
- func Slugify(name string) string
- func TileVisibleTo(config map[string]any, cc *CampaignContext) bool
- func ValidHomeAudience(name string) bool
- func ValidateHomeLayout(ctx context.Context, campaignID string, layout *DashboardLayout) error
- func ValidateTierDefinitions(defs []TierDefinition) error
- func ViewerAccessLabel(cc *CampaignContext) string
- func ViewingAsGuest(c *echo.Context, cc *CampaignContext) bool
- func ViewingAsPlayer(c *echo.Context, cc *CampaignContext) bool
- type AILook
- func (k *AILook) Answer(ctx context.Context, campaignID string, a aiplug.Actor, _ aiplug.Record) (string, string, error)
- func (k *AILook) Apply(ctx context.Context, campaignID string, a aiplug.Actor, r aiplug.Record) error
- func (*AILook) Brief() string
- func (*AILook) Doc() string
- func (*AILook) Export(context.Context, string, aiplug.Actor) (string, error)
- func (*AILook) Label() string
- func (*AILook) LookupInfo() aiplug.LookupInfo
- func (*AILook) Name() string
- func (k *AILook) Plan(ctx context.Context, campaignID string, a aiplug.Actor, r aiplug.Record) aiplug.Plan
- func (*AILook) Title(aiplug.Record) string
- type AILookDrafts
- type AISettings
- type AccountCampaignLister
- type AddMemberRequest
- type AddonExporter
- type AddonImporter
- type AddonLister
- type AdminSearchOptions
- type Appearance
- type AppearanceBrandInput
- type AppearanceColourInput
- type AppearanceHeaderInput
- type AppearanceInput
- type AppearanceSidebarInput
- type AuditLogger
- type BlockPlacementChecker
- type BrushPrefs
- type BundledMediaFile
- type CalendarExporter
- type CalendarImporter
- type Campaign
- func (c *Campaign) DirectorHome() *DashboardLayout
- func (c *Campaign) GetRoleDashboardJSON(roleName string) *DashboardLayout
- func (c *Campaign) HasSavedHome(audience string) bool
- func (c *Campaign) HomeLayout(audience string) (*DashboardLayout, bool)
- func (c *Campaign) IsArchived() bool
- func (c *Campaign) ParseDashboardLayout() *DashboardLayout
- func (c *Campaign) ParseOwnerDashboardLayout() *DashboardLayout
- func (c *Campaign) ParseRoleDashboardLayout(role Role) *DashboardLayout
- func (c *Campaign) ParseSettings() CampaignSettings
- func (c *Campaign) ParseSidebarConfig() SidebarConfig
- func (c *Campaign) RemoveRoleDashboardJSON(roleName string) (*string, error)
- func (c *Campaign) SetRoleDashboardJSON(roleName string, layout *DashboardLayout) (*string, error)
- type CampaignContext
- func (cc *CampaignContext) CanAuthorDmOnly() bool
- func (cc *CampaignContext) CanControlWorldState() bool
- func (cc *CampaignContext) DMTeamChrome() bool
- func (cc *CampaignContext) EffectiveRole() Role
- func (cc *CampaignContext) GuestCodePreviewContext(now time.Time) *CampaignContext
- func (cc *CampaignContext) GuestPreviewContext() *CampaignContext
- func (cc *CampaignContext) HomeAudience() string
- func (cc *CampaignContext) InGuestPreview() bool
- func (cc *CampaignContext) NewPagePrivacy(requested patch.Field[bool]) bool
- func (cc *CampaignContext) OwnerChrome() bool
- func (cc *CampaignContext) PlayerPreview() *CampaignContext
- func (cc *CampaignContext) VisibilityRole() int
- type CampaignExport
- type CampaignGroup
- type CampaignHookDispatcher
- type CampaignMember
- type CampaignRepository
- type CampaignService
- type CampaignSettings
- type CampaignTab
- type CampaignTabCard
- type CharacterListSeeder
- type CharacterReleaser
- type ConnectionRevoker
- type ConnectionsTab
- type ContentPacksCardRenderer
- type ContentTemplateSeeder
- type CreateCampaignInput
- type CreateCampaignRequest
- type CreateInviteInput
- type CustomizeArea
- type CustomizeCategory
- type CustomizeCategoryLister
- type CustomizeCrumb
- type CustomizeDraft
- type CustomizeDraftRepository
- type CustomizeDraftService
- type CustomizeFind
- type CustomizePart
- type CustomizeSection
- type CustomizeSummary
- type CustomizeTab
- type DashboardBlock
- type DashboardColumn
- type DashboardLayout
- type DashboardRow
- type DataTab
- type Desk
- type DeskAIFacts
- type DeskAIState
- type DeskBlank
- type DeskBlankKind
- type DeskBoard
- type DeskChangesFacts
- type DeskChip
- type DeskEntriesFacts
- type DeskFace
- type DeskFacts
- type DeskFeaturesTile
- type DeskFigure
- type DeskFlip
- type DeskFoundryFacts
- type DeskGoTile
- type DeskInputs
- type DeskKeysFacts
- type DeskLine
- type DeskLookTile
- type DeskMediaFacts
- type DeskOption
- type DeskPeopleTile
- type DeskProvider
- type DeskRequest
- type DeskService
- type DeskSlot
- type DeskTab
- type DeskTrashFacts
- type DeskValue
- type DeskView
- type EntityExporter
- type EntityImporter
- type EntityTypeLister
- type EntityTypeSeeder
- type ExportAddon
- type ExportAttendee
- type ExportCalendarCycle
- type ExportCalendarCycleEntry
- type ExportCalendarData
- type ExportCalendarEra
- type ExportCalendarEraLook
- type ExportCalendarEvent
- type ExportCalendarEventOverride
- type ExportCalendarEventRoll
- type ExportCalendarFestival
- type ExportCalendarMonth
- type ExportCalendarMoon
- type ExportCalendarMoonMark
- type ExportCalendarPartyMove
- type ExportCalendarPlaceWeather
- type ExportCalendarRollNight
- type ExportCalendarSeason
- type ExportCalendarSun
- type ExportCalendarWeather
- type ExportCalendarWeatherDay
- type ExportCalendarWeekday
- type ExportCampaignMeta
- type ExportDrawing
- type ExportEntity
- type ExportEntityData
- type ExportEntityGroup
- type ExportEntityPermission
- type ExportEntityTag
- type ExportEntityType
- type ExportEraPageVersion
- type ExportEventCategory
- type ExportEventConnection
- type ExportFieldSwitch
- type ExportFogRegion
- type ExportGroup
- type ExportHandler
- type ExportImportService
- func (s *ExportImportService) Export(ctx context.Context, campaignID string) (*CampaignExport, error)
- func (s *ExportImportService) Import(ctx context.Context, userID string, data *CampaignExport, ...) (*Campaign, *ImportReport, error)
- func (s *ExportImportService) MediaBundlerImpl() MediaBundler
- func (s *ExportImportService) SetAddonExporter(e AddonExporter)
- func (s *ExportImportService) SetAddonImporter(i AddonImporter)
- func (s *ExportImportService) SetCalendarExporter(e CalendarExporter)
- func (s *ExportImportService) SetCalendarImporter(i CalendarImporter)
- func (s *ExportImportService) SetEntityExporter(e EntityExporter)
- func (s *ExportImportService) SetEntityImporter(i EntityImporter)
- func (s *ExportImportService) SetGroupExporter(e GroupExporter)
- func (s *ExportImportService) SetGroupImporter(i GroupImporter)
- func (s *ExportImportService) SetMapExporter(e MapExporter)
- func (s *ExportImportService) SetMapImporter(i MapImporter)
- func (s *ExportImportService) SetMediaBundler(b MediaBundler)
- func (s *ExportImportService) SetMediaExporter(e MediaExporter)
- func (s *ExportImportService) SetMediaImporter(i MediaImporter)
- func (s *ExportImportService) SetNoteExporter(e NoteExporter)
- func (s *ExportImportService) SetNoteImporter(i NoteImporter)
- func (s *ExportImportService) SetPostExporter(e PostExporter)
- func (s *ExportImportService) SetPostImporter(i PostImporter)
- func (s *ExportImportService) SetQuestExporter(e QuestExporter)
- func (s *ExportImportService) SetQuestImporter(i QuestImporter)
- func (s *ExportImportService) SetRecipeExporter(e RecipeExporter)
- func (s *ExportImportService) SetRecipeImporter(i RecipeImporter)
- func (s *ExportImportService) SetRollTableExporter(e RollTableExporter)
- func (s *ExportImportService) SetRollTableImporter(i RollTableImporter)
- func (s *ExportImportService) SetSessionExporter(e SessionExporter)
- func (s *ExportImportService) SetSessionImporter(i SessionImporter)
- func (s *ExportImportService) SetTimelineExporter(e TimelineExporter)
- func (s *ExportImportService) SetTimelineImporter(i TimelineImporter)
- func (s *ExportImportService) Validate(data *CampaignExport) error
- type ExportLayer
- type ExportMap
- type ExportMarker
- type ExportMediaFile
- type ExportNote
- type ExportPost
- type ExportQuest
- type ExportRecipe
- type ExportRelation
- type ExportSession
- type ExportSessionEntity
- type ExportTag
- type ExportTimeline
- type ExportTimelineEvent
- type ExportTimelineEventLink
- type ExportToken
- type ExtensionEnableChecker
- type FeatureEnabler
- type FoundryCheck
- type FoundryCheckLevel
- type FoundryConnection
- type FoundryConnector
- type FoundryRowData
- type FoundryStatus
- type FoundryStatusLevel
- type GroupExporter
- type GroupImporter
- type GroupMemberInfo
- type GroupRepository
- type GroupService
- type GuestCode
- type GuestCodeRepository
- type GuestCodeService
- func (s *GuestCodeService) AdmitWithGuestCode(ctx context.Context, codeID, campaignID, userID string) error
- func (s *GuestCodeService) ClaimGuestCode(ctx context.Context, code string) (string, string, error)
- func (s *GuestCodeService) Create(ctx context.Context, campaignID, createdBy, note string, visitDays int) (*NewGuestCode, error)
- func (s *GuestCodeService) EndVisit(ctx context.Context, campaignID, id string) error
- func (s *GuestCodeService) EndVisits(ctx context.Context, campaignID, userID string) error
- func (s *GuestCodeService) List(ctx context.Context, campaignID string) ([]GuestCode, error)
- func (s *GuestCodeService) MakeVisitorPlayer(ctx context.Context, campaignID, id string) error
- func (s *GuestCodeService) MoveGuestMembership(ctx context.Context, campaignID, guestID, targetID string) error
- func (s *GuestCodeService) Now() time.Time
- func (s *GuestCodeService) Peek(ctx context.Context, code string) (campaignID string, ok bool)
- func (s *GuestCodeService) ReleaseGuestCode(ctx context.Context, codeID string)
- func (s *GuestCodeService) Remove(ctx context.Context, campaignID, id string) error
- func (s *GuestCodeService) VisitPass(ctx context.Context, campaignID, userID string) (until time.Time, live, found bool, err error)
- type Handler
- func (h *Handler) AcceptTransfer(c *echo.Context) error
- func (h *Handler) AddGroupMemberAPI(c *echo.Context) error
- func (h *Handler) AddMember(c *echo.Context) error
- func (h *Handler) AllowMemberBack(c *echo.Context) error
- func (h *Handler) ArchiveCampaign(c *echo.Context) error
- func (h *Handler) CampaignSettings(c *echo.Context) error
- func (h *Handler) CancelTransfer(c *echo.Context) error
- func (h *Handler) CategoryMenuVisible(cc *CampaignContext) map[int]bool
- func (h *Handler) ConnectionsPage(c *echo.Context) error
- func (h *Handler) Create(c *echo.Context) error
- func (h *Handler) CreateGroupAPI(c *echo.Context) error
- func (h *Handler) Customize(c *echo.Context) error
- func (h *Handler) CustomizeCategories(ctx context.Context, campaignID string) []CustomizeCategory
- func (h *Handler) CustomizeCategoriesPage(c *echo.Context) error
- func (h *Handler) CustomizeCategory(c *echo.Context) error
- func (h *Handler) CustomizeDraftFor(ctx context.Context, campaignID, userID string) (version int, draft json.RawMessage)
- func (h *Handler) CustomizeHere(c *echo.Context) error
- func (h *Handler) CustomizeHome(c *echo.Context) error
- func (h *Handler) CustomizeKitKeep(c *echo.Context) error
- func (h *Handler) CustomizeKitTry(c *echo.Context) error
- func (h *Handler) CustomizeLook(c *echo.Context) error
- func (h *Handler) CustomizePluginArea(c *echo.Context) error
- func (h *Handler) CustomizeSectionKeys() []string
- func (h *Handler) DataPage(c *echo.Context) error
- func (h *Handler) Delete(c *echo.Context) error
- func (h *Handler) DeleteAppearancePictureAPI(c *echo.Context) error
- func (h *Handler) DeleteCustomizeDraftAPI(c *echo.Context) error
- func (h *Handler) DeleteGroupAPI(c *echo.Context) error
- func (h *Handler) DeskFind(c *echo.Context) error
- func (h *Handler) DeskNeedsCount(c *echo.Context) error
- func (h *Handler) EditForm(c *echo.Context) error
- func (h *Handler) ExtensionsHub(c *echo.Context) error
- func (h *Handler) ExtensionsHubFragmentAPI(c *echo.Context) error
- func (h *Handler) FoundryPage(c *echo.Context) error
- func (h *Handler) GenerateJoinCode(c *echo.Context) error
- func (h *Handler) GetCustomizeDraftAPI(c *echo.Context) error
- func (h *Handler) GetDashboardLayout(c *echo.Context) error
- func (h *Handler) GetDmGrantsAPI(c *echo.Context) error
- func (h *Handler) GetEventTierDefinitionsAPI(c *echo.Context) error
- func (h *Handler) GetGroupAPI(c *echo.Context) error
- func (h *Handler) GetOwnerDashboardLayout(c *echo.Context) error
- func (h *Handler) GetSidebarConfig(c *echo.Context) error
- func (h *Handler) GroupsPage(c *echo.Context) error
- func (h *Handler) HomePreview(c *echo.Context) error
- func (h *Handler) Index(c *echo.Context) error
- func (h *Handler) InviteBox(c *echo.Context) error
- func (h *Handler) InviteBoxEmail(c *echo.Context) error
- func (h *Handler) InviteBoxEndVisit(c *echo.Context) error
- func (h *Handler) InviteBoxMakeCode(c *echo.Context) error
- func (h *Handler) InviteBoxMakeLink(c *echo.Context) error
- func (h *Handler) InviteBoxMakePlayer(c *echo.Context) error
- func (h *Handler) InviteBoxRemoveCode(c *echo.Context) error
- func (h *Handler) InviteBoxRevokeInvite(c *echo.Context) error
- func (h *Handler) InviteBoxRevokeLink(c *echo.Context) error
- func (h *Handler) JoinByCode(c *echo.Context) error
- func (h *Handler) KeepSetupStepPost(c *echo.Context) error
- func (h *Handler) LeaveCampaign(c *echo.Context) error
- func (h *Handler) ListGroupsAPI(c *echo.Context) error
- func (h *Handler) LookDraftPictures(ctx context.Context, cc *CampaignContext, draft json.RawMessage) map[string]string
- func (h *Handler) ManageFigure(ctx context.Context, lineID string) templ.Component
- func (h *Handler) ManageMast(ctx context.Context) *layouts.ManageMast
- func (h *Handler) Members(c *echo.Context) error
- func (h *Handler) NewForm(c *echo.Context) error
- func (h *Handler) NewFoundryConnectLine(c *echo.Context) error
- func (h *Handler) OwnerDashboard(c *echo.Context) error
- func (h *Handler) Picker(c *echo.Context) error
- func (h *Handler) PluginHub(c *echo.Context) error
- func (h *Handler) PluginHubFragment(c *echo.Context) error
- func (h *Handler) PublishCustomizeAPI(c *echo.Context) error
- func (h *Handler) PutCustomizeDraftAPI(c *echo.Context) error
- func (h *Handler) PutLookPick(c *echo.Context) error
- func (h *Handler) RegisterCustomizeSection(s CustomizeSection)
- func (h *Handler) RegisterCustomizeTab(factory func(*CampaignContext) CustomizeTab)
- func (h *Handler) RegisterDeskProvider(p DeskProvider)
- func (h *Handler) RegisterSettingsTab(factory func(*CampaignContext) SettingsTab)
- func (h *Handler) RemoveGroupMemberAPI(c *echo.Context) error
- func (h *Handler) RemoveMember(c *echo.Context) error
- func (h *Handler) ResetDashboardLayout(c *echo.Context) error
- func (h *Handler) ResetOwnerDashboardLayout(c *echo.Context) error
- func (h *Handler) RevokeJoinCode(c *echo.Context) error
- func (h *Handler) RunByBlock(c *echo.Context) error
- func (h *Handler) SaveAppearanceAPI(c *echo.Context) error
- func (h *Handler) SaveHeroChangesSetting(c *echo.Context) error
- func (h *Handler) SendTestEmailAPI(c *echo.Context) error
- func (h *Handler) SetAddonLister(lister AddonLister)
- func (h *Handler) SetAuditLogger(logger AuditLogger)
- func (h *Handler) SetBaseURL(url string)
- func (h *Handler) SetBrushPrefs(p BrushPrefs)
- func (h *Handler) SetContentPacksCardRenderer(r ContentPacksCardRenderer)
- func (h *Handler) SetCustomizeCategoryLister(l CustomizeCategoryLister)
- func (h *Handler) SetCustomizeDrafts(svc CustomizeDraftService)
- func (h *Handler) SetEntityLister(lister EntityTypeLister)
- func (h *Handler) SetExtensionEnableChecker(c ExtensionEnableChecker)
- func (h *Handler) SetFoundryConnector(c FoundryConnector)
- func (h *Handler) SetGroupService(svc GroupService)
- func (h *Handler) SetHeroChanges(on func(ctx context.Context, campaignID string) bool)
- func (h *Handler) SetInviteBox(invites InviteService, codes *GuestCodeService, baseURL string)
- func (h *Handler) SetInviteLister(svc InviteService)
- func (h *Handler) SetInviteService(svc InviteService)
- func (h *Handler) SetMediaUploader(uploader MediaUploader)
- func (h *Handler) SetPageCategoryLookup(l PageCategoryLookup)
- func (h *Handler) SetPiecePlaceable(fn func(block string) bool)
- func (h *Handler) SetRecentEntityLister(lister RecentEntityLister)
- func (h *Handler) SetSMTPChecker(checker SMTPChecker)
- func (h *Handler) SetSheetChecker(c SheetChecker)
- func (h *Handler) SetSystemAddonEnabler(enabler SystemAddonEnabler)
- func (h *Handler) SetSystemLister(lister SystemLister)
- func (h *Handler) SetTestMailer(m TestMailer)
- func (h *Handler) Settings(c *echo.Context) error
- func (h *Handler) SetupStepsBlock(c *echo.Context) error
- func (h *Handler) Show(c *echo.Context) error
- func (h *Handler) SidebarDrill(c *echo.Context) error
- func (h *Handler) ToggleViewAsPlayer(c *echo.Context) error
- func (h *Handler) Transfer(c *echo.Context) error
- func (h *Handler) TransferForm(c *echo.Context) error
- func (h *Handler) UnarchiveCampaign(c *echo.Context) error
- func (h *Handler) Update(c *echo.Context) error
- func (h *Handler) UpdateBrandingAPI(c *echo.Context) error
- func (h *Handler) UpdateDashboardLayout(c *echo.Context) error
- func (h *Handler) UpdateDefaultVisibilityAPI(c *echo.Context) error
- func (h *Handler) UpdateDetailsAPI(c *echo.Context) error
- func (h *Handler) UpdateDmGrantsAPI(c *echo.Context) error
- func (h *Handler) UpdateEventTierDefinitionsAPI(c *echo.Context) error
- func (h *Handler) UpdateGroupAPI(c *echo.Context) error
- func (h *Handler) UpdateHandoverSettingAPI(c *echo.Context) error
- func (h *Handler) UpdateMemberCharacterAPI(c *echo.Context) error
- func (h *Handler) UpdateNavPins(c *echo.Context) error
- func (h *Handler) UpdateOwnerDashboardLayout(c *echo.Context) error
- func (h *Handler) UpdateRole(c *echo.Context) error
- func (h *Handler) UpdateSidebarConfig(c *echo.Context) error
- func (h *Handler) UpdateSystemID(c *echo.Context) error
- func (h *Handler) UpdateWelcomeMessageAPI(c *echo.Context) error
- func (h *Handler) UploadAppearancePictureAPI(c *echo.Context) error
- func (h *Handler) ViewAs(c *echo.Context) error
- func (h *Handler) YourLook(c *echo.Context) error
- type HandoverStatus
- type HeroChangeForm
- type HeroChangeFormValues
- type HeroChangeRule
- type HeroChangesSetting
- type HomeSeen
- type HomeSeenStore
- type IDMap
- type ImportFailure
- type ImportMediaBundle
- type ImportReport
- func (r *ImportReport) Count() int
- func (r *ImportReport) CountsByKind() []KindCount
- func (r *ImportReport) Fail(section, kind, name, reason string)
- func (r *ImportReport) FailN(section, kind, name, reason string, n int)
- func (r *ImportReport) Failures() []ImportFailure
- func (r *ImportReport) HasFailures() bool
- func (r *ImportReport) Summary() string
- func (r *ImportReport) Truncated() int
- type InvitationSource
- type Invite
- type InviteBoxData
- type InviteHandler
- func (h *InviteHandler) AcceptInvitePage(c *echo.Context) error
- func (h *InviteHandler) CreateInviteAPI(c *echo.Context) error
- func (h *InviteHandler) ListInvitesAPI(c *echo.Context) error
- func (h *InviteHandler) RevokeInviteAPI(c *echo.Context) error
- func (h *InviteHandler) SetInvitations(src *InvitationSource)
- type InviteMailer
- type InviteRepository
- type InviteService
- type KindCount
- type LayoutPresetSeeder
- type LeaveNotifier
- type LeaveView
- type ListOptions
- type LookAccessInput
- type LookPart
- type LookSummary
- type MailService
- type MapExporter
- type MapImporter
- type MediaBundler
- type MediaCleaner
- type MediaExporter
- type MediaImporter
- type MediaUploader
- type MemberListView
- type MemberLister
- type MemberUser
- type NavAccess
- type NavApp
- type NavCategory
- type NavCategoryPlace
- type NavLayout
- type NavLayoutItem
- type NavLayoutSection
- type NavRow
- type NavSection
- type NavSectionsSource
- type NavSubcategory
- type NavViewer
- type NeedsYouItem
- type NewGuestCode
- type NextNightFunc
- type NoteExporter
- type NoteImporter
- type OwnedCampaign
- type OwnerPresence
- type OwnershipTransfer
- type PageCategoryLookup
- type PluginHubAddon
- type PostExporter
- type PostImporter
- type QuestExporter
- type QuestImporter
- type RecentEntity
- type RecentEntityLister
- type RecipeExporter
- type RecipeImporter
- type Role
- type RoleDashboardLayouts
- type RollTableExporter
- type RollTableImporter
- type SMTPChecker
- type SessionExporter
- type SessionImporter
- type SettingsEntityType
- type SettingsTab
- type SheetChecker
- type SidebarConfig
- type SidebarItem
- type SiteLookSource
- type SystemAddonEnabler
- type SystemCount
- type SystemLister
- type TestMailer
- type TierDefinition
- type TileSizeResolver
- type TimelineExporter
- type TimelineImporter
- type TopbarContent
- type TopbarLink
- type TopbarStyle
- type TransferOwnershipRequest
- type TrashedCampaign
- type UpdateCampaignDetailsInput
- type UpdateCampaignInput
- type UpdateCampaignRequest
- type UpdateRoleRequest
- type UpdateSidebarConfigRequest
- type UserFinder
- type UserFinderAdapter
- type VisitPasses
- type WhereWeLink
- type WorldbuildingPromptSeeder
Constants ¶
const ( // SystemFilterNone selects campaigns with no game system set. SystemFilterNone = "none" // SystemFilterCustom selects campaigns on a user-supplied ("custom:<url>") // system. They collapse into one chip because every URL is its own id and // a chip per URL would never stay small. SystemFilterCustom = "custom" )
const ( HeroChangeDefaultDays = 7 HeroChangeDefaultLevel = 2 )
HeroChangeDefaultDays and HeroChangeDefaultLevel are the numbers the form suggests before a rule exists: a week after making, and a week after each new level.
const ( // SectionCalendar is the export-envelope section heading for calendar data. SectionCalendar = "calendar" // SectionTimelines is the export-envelope section heading for timelines. SectionTimelines = "timelines" // KindCalendar is the singular noun for a calendar in a failure row. KindCalendar = "calendar" // KindTimeline is the singular noun for a timeline in a failure row. KindTimeline = "timeline" )
Report section and kind labels whose spelling collides with a plugin slug.
These are user-facing report headings ("calendar", "timelines") and singular human nouns ("calendar", "timeline"). Nothing resolves a plugin from them — they are never compared against a registry, never used to build a route, and never round-trip into the export envelope as a plugin identifier. But a bare literal at a call site is indistinguishable from a real cross-plugin reference to tools/check-plugin-isolation.sh, so the vocabulary lives here and call sites name the constant instead of the literal; the guard's const_registry_files list permits the literals on THESE const lines only. tools/test-plugin-isolation.sh pins that narrowness.
Labels that do not collide with a plugin slug ("notes", "maps", "entities", "sessions", …) are deliberately NOT hoisted here: they are ordinary prose and hoisting them would imply the guard cares about them.
const ( SectionRollTables = "rolling tables" KindRollTables = "rolling tables" SectionQuests = "quest sheets" KindQuest = "quest sheet" SectionRecipes = "crafting recipes" KindRecipe = "crafting recipe" )
Section and kind labels for the rolling tables, quest sheets and crafting recipes in an export. Worded to differ from the plugin slugs.
const ( LookAccessOwner = "owner" // Only the owner (who edits the campaign's look itself). LookAccessCoDM = "codm" // The owner and the DM team. LookAccessEveryone = "everyone" // Every member. )
The "who can change" settings: for each part of the look, the owner says who may pick their own version of it. A pick only ever changes what that person sees, so the setting widens a personal choice, never the campaign's look.
const ( LookPartSheet = "sheet" // The character sheet style. LookPartPage = "page" // The pages' style kit. LookPartHover = "hover" // The hover card look. LookPartDmScreen = "dmscreen" // The DM Screen's style kit. )
The parts of the look a member can pick for themselves.
const ( AccessPlayer = "player" AccessScribe = "scribe" AccessCoDM = "codm" )
Member access choices on the role menu.
const ( MaxCampaignNameLen = 200 MaxDescriptionLen = 5000 MaxWelcomeMessageLen = 500 )
Validation constants for campaign fields.
const ( PreviewPlayer = "player" PreviewGuest = "guest" PreviewGuestCode = "guestcode" )
The ways the DM team can look at the campaign as someone else: as a player, as a visitor with no code, and as a visitor who came in on a guest code (a look-around pass).
const ( HomeDefault = "default" HomePlayer = "player" HomeScribe = "scribe" HomeDirector = "director" HomeGuest = "guest" )
Home audiences: who a campaign home is arranged for. The names are the `?role=` values of the dashboard-layout endpoint.
const ( HeroChangeMaxDays = 365 HeroChangeMaxLevel = 100 )
HeroChangeMaxDays and HeroChangeMaxLevel bound what a Director may set.
const ( DefaultVisibilityDMOnly = "dm_only" DefaultVisibilityPrivate = "private" )
DefaultVisibility* are the accepted values of CampaignSettings.DefaultVisibility, as written by the campaign settings page (internal/plugins/campaigns/settings.templ). Empty is the fourth, unnamed state: "Everyone", the shipped default for a campaign that has never touched the setting.
The settings UI describes DM Only and Private as two different behaviours, but the storage layer has exactly one flag — entities.is_private — so both resolve to "start hidden" here. That is a known copy/product discrepancy, not a bug in this resolution.
const ( // Campaign dashboard blocks. BlockWelcomeBanner = "welcome_banner" // Campaign name + description hero. BlockQuickActions = "quick_actions" // All Pages / Members / Categories cards. BlockCategoryGrid = "category_grid" // Quick-nav grid of entity types. BlockRecentPages = "recent_pages" // Recently updated entities. BlockEntityList = "entity_list" // Filtered entity list by category. BlockTextBlock = "text_block" // Custom rich text / markdown. BlockPinnedPages = "pinned_pages" // Pinned entities grid. BlockCalendarPreview = "calendar_preview" // Upcoming calendar events. BlockTimelinePreview = "timeline_preview" // Timeline visualization preview. // BlockMapPreview ("map_preview") was retired — superseded by the // per-entity map_editor block (entity templates) and BlockMapFull // (dashboards). Constant removed; existing layouts with the type // silently drop the block at render via the case-handler removal. BlockRelationsGraph = "relations_graph" // Entity relations force-directed graph. BlockCalendarFull = "calendar_full" // Full interactive calendar grid view. BlockTimelineFull = "timeline_full" // Full timeline visualization with D3. BlockRelationsGraphFull = "relations_graph_full" // Large relations graph view. BlockMapFull = "map_full" // Full interactive map viewer with markers/drawings. BlockSessionTracker = "session_tracker" // Retired: a saved one draws the Coming up card. BlockActivityFeed = "activity_feed" // Recent campaign activity log. BlockSyncStatus = "sync_status" // Foundry VTT sync health/status. BlockComingUp = "coming_up" // Next game nights, what the viewer owes the table, next events. BlockStartHere = "start_here" // One page the owner picks, as the home's lead (entities plugin). BlockBrochure = "brochure" // One page the owner wrote for new players, as a small box that opens it folded out (entities plugin). BlockAtAGlance = "at_a_glance" // System, next game, last session, page count (internal/app). BlockParty = "party" // The claimed heroes: name, ancestry, class, level, player (entities plugin). BlockWhenWePlay = "when_we_play" // The times most of the table is free (sessions plugin). BlockWhenWeCouldPlay = "when_we_could_play" // Upcoming days: set nights and where the table tends to be free (sessions plugin). BlockNextGame = "next_game" // Days until the next set game night (sessions plugin). BlockTodayInWorld = "today_in_world" // The in-world date, weather, moons and next event (calendar plugin). BlockOpenQuests = "open_quests" // The open quests that most need attention (quests plugin). BlockWorldClocks = "world_clocks" // Trackers shown to everyone, drawn small (trackers plugin). BlockSinceLastHere = "since_last_here" // What changed since the member last pressed "Mark as seen" (assembled in internal/app). BlockWhereWePlay = "where_we_play" // The owner's Foundry address and voice channel, typed in the block's config. BlockHouseRules = "house_rules" // The rulebook's house chapters (systems). BlockLastTime = "last_time" // The latest session's recap, as its viewer may read it (sessions plugin). BlockGettingStarted = "getting_started" // A new player's steps, ticked as they are done (sessions plugin). BlockYourHero = "your_hero" // The viewer's own claimed hero, or a way to choose one (entities plugin). BlockTableAgreement = "table_agreement" // The owner's table agreement, typed into the block's config. BlockMakingAHero = "making_a_hero" // The owner's notes on making a hero, typed into the block's config. BlockRunBy = "run_by" // The owner and co-Directors by name (campaigns). BlockSetupSteps = "setup_steps" // The owner's "Getting your table ready" line, ticked from what exists (campaigns). // Category dashboard blocks. BlockCategoryHeader = "category_header" // Category name, icon, count, description. BlockEntityGrid = "entity_grid" // All entities in category as card grid. BlockSearchBar = "search_bar" // Search input for filtering within category. )
Supported dashboard block types. Each maps to a Templ component that knows how to render the block with its config. Used by both campaign and category dashboard editors.
const ( )
Built-in sections. Every sidebar has these three, in this order, ahead of any section the owner adds.
const ( SidebarTypeApp = "app" SidebarTypeAddon = "addon" // earlier spelling of an app item, still read as one SidebarTypeCategory = "category" SidebarTypeSection = "section" SidebarTypeLink = "link" // Dashboard and All Pages are placed by the sidebar itself; older configs // list them as items, which normalization skips. SidebarTypeDashboard = "dashboard" SidebarTypeAllPages = "all_pages" )
Sidebar item types stored in SidebarConfig.Items.
const ( )
Row kinds a NavRow reports.
const ExportFormat = "chronicle-campaign-v1"
ExportFormat is the format identifier for Chronicle campaign exports.
const ExportVersion = 1
ExportVersion is the current schema version.
NavKindCustom is the kind of a section the owner added; the built-in sections report their own id as their kind.
NavSectionDrawer is where an app the owner keeps in the drawer only is stored. It is not a sidebar section: no sidebar draws it, the app drawer lists it, and a member may still pin it for themselves.
const NotifMemberLeft = "member_left"
NotifMemberLeft is the bell type of the owner's "Tam left Therin" note. It has no category on the account page, so it is always delivered.
Variables ¶
var ( AppearanceLooks = []string{"classic", "parchment", "midnight", "forest", "ember", "frost", "arcane", "starship"} AppearancePageTones = []string{"cool", "warm", "paper"} AppearanceContrasts = []string{"standard", "high"} AppearanceBodyFonts = []string{"inter", "sourcesans", "atkinson", "literata", "sourceserif", "lora", "alegreya", "merriweather"} AppearanceHeadingFonts = []string{"same", "cinzel", "marcellus", "imfell", "cormorant", "fraunces", "playfair", "josefin", "chakra"} AppearanceTypeScales = []string{"standard", "compact", "roomy"} AppearanceButtonStyles = []string{"lift", "press", "glow", "ink", "keystone"} // AppearanceIconAmounts: "few" is the site's rule as written; "names" draws // a category's icon before a page's name in lists; "all" is "names" plus, // later, icons on buttons and menu rows. AppearanceIconAmounts = []string{"few", "names", "all"} AppearanceIconColours = []string{"ink", "accent", "category"} AppearanceElevations = []string{"standard", "flat", "dramatic", "ambient"} AppearanceSpeeds = []string{"standard", "snappy", "leisurely"} AppearanceScrims = []string{"medium", "light", "strong"} AppearanceWidgets = []string{"links", "text", "note", "search", "date", "weather", "moon", "era", "session"} AppearanceSidebars = []string{"charcoal", "ink", "tinted", "own"} AppearanceCorners = []string{"plain", "subtitle", "banner"} AppearanceGlows = []string{"accent", "own"} // AppearanceEntrances are how a card opens under the Material kit; Grow // is the base and is stored as unset. AppearanceEntrances = []string{"grow", "bloom", "unfold", "drop"} AppearanceHeights = []string{"slim", "tall"} AppearanceHoverCards = []string{"paper", "plain", "night", "compact"} // AppearanceSheetStyles are the character sheet styles sheet_styles.css // knows, keyed by the data-cz-sheet value; "modern" is the unstyled default. AppearanceSheetStyles = []string{"modern", "parchment", "ledger", "journal", "vellum", "night", "deck", "pencil", "starship", "neon", "runes", "brass"} // AppearancePageLooks restyle every block on a page through the shared // block parts without moving anything; page_look_annals.css draws Annals. AppearancePageLooks = []string{"standard", "annals"} // AppearanceCraftArts are the ways made items are drawn: the Dark // painted pictures (made_items.js), lifelike like the crafting bench, or // the softer illustrated set. AppearanceCraftArts = []string{"painted", "lifelike", "illustrated"} // AppearanceTimelinePopups are what opens over an event on a time line: // the classic hover card, or the fading corner that grows out of the bead. AppearanceTimelinePopups = []string{"classic", "corner"} // AppearanceStyleKits are the signed style kits style_kits.css draws // (ui-standard.md, "Style kits"); "material" is the base and adds nothing. AppearanceStyleKits = []string{"material", "sharp", "ornate", "flowing", "lumen", "sketchbook"} // AppearanceBuilderLooks are the skins the hero builder wears, written to // its mount as data-skin: plain is the base, paper the printed-page feel, // ornate the bound-volume one. AppearanceBuilderLooks = []string{"plain", "paper", "ornate"} // AppearanceEmailLayouts are the layouts internal/email draws the // campaign's emails in, Note first as the default. AppearanceEmailLayouts = emailLayoutIDs() )
The allowed values of each Appearance choice. The first entry is the Classic default; the save stores it as empty so defaults stay implicit.
var HandoverChoices = []int{0, 3, 6, 12}
HandoverChoices are the "If you're away" settings an owner can pick, in months. 0 is Never, the default: an admin can't hand the campaign over.
var LookParts = []LookPart{ {Key: LookPartSheet, Label: "Character sheet", Choices: AppearanceSheetStyles, Settings: []string{LookAccessOwner, LookAccessCoDM, LookAccessEveryone}, Default: LookAccessEveryone}, {Key: LookPartPage, Label: "Pages", Choices: AppearanceStyleKits, Settings: []string{LookAccessOwner, LookAccessCoDM, LookAccessEveryone}, Default: LookAccessOwner}, {Key: LookPartHover, Label: "Hover cards", Choices: AppearanceHoverCards, Settings: []string{LookAccessOwner, LookAccessCoDM, LookAccessEveryone}, Default: LookAccessOwner}, {Key: LookPartDmScreen, Label: "DM Screen", Choices: AppearanceStyleKits, Settings: []string{LookAccessOwner, LookAccessCoDM}, Default: LookAccessCoDM}, }
LookParts lists the parts in the order the pages show them. The DM Screen never allows everyone: it shows hidden material, so it stays with the DM team and so does its look. Pages and hover cards start with the owner so a campaign that never opens them looks the same to everyone.
var ValidBlockTypes = map[string]bool{ BlockWelcomeBanner: true, BlockQuickActions: true, BlockCategoryGrid: true, BlockRecentPages: true, BlockEntityList: true, BlockTextBlock: true, BlockPinnedPages: true, BlockCalendarPreview: true, BlockTimelinePreview: true, BlockRelationsGraph: true, BlockCalendarFull: true, BlockTimelineFull: true, BlockRelationsGraphFull: true, BlockMapFull: true, BlockSessionTracker: true, BlockActivityFeed: true, BlockSyncStatus: true, BlockComingUp: true, BlockStartHere: true, BlockBrochure: true, BlockAtAGlance: true, BlockParty: true, BlockWhenWePlay: true, BlockWhenWeCouldPlay: true, BlockNextGame: true, BlockTodayInWorld: true, BlockOpenQuests: true, BlockWorldClocks: true, BlockSinceLastHere: true, BlockWhereWePlay: true, BlockHouseRules: true, BlockLastTime: true, BlockYourHero: true, BlockTableAgreement: true, BlockMakingAHero: true, BlockRunBy: true, BlockSetupSteps: true, BlockGettingStarted: true, BlockCategoryHeader: true, BlockEntityGrid: true, BlockSearchBar: true, }
ValidBlockTypes is the set of supported dashboard block types. Used for validation when saving layouts (both campaign and category dashboards).
Functions ¶
func AllowPublicCampaignAccess ¶
func AllowPublicCampaignAccess(service CampaignService) echo.MiddlewareFunc
AllowPublicCampaignAccess is like RequireCampaignAccess but also allows unauthenticated users to view public campaigns. Non-member public visitors (logged-out, or authenticated but not a member) get MemberRole=RoleNone — strictly below RolePlayer — so they see only public/everyone content and never Player-only or Player-role tag-granted content. RolePlayer is reserved for authenticated party members.
Use this on view routes (/campaigns/:id, /campaigns/:id/entities, etc.). Mutating routes should still use RequireCampaignAccess + RequireRole.
func AppliedLookPicks ¶
func AppliedLookPicks(ap *Appearance, cc *CampaignContext, stored map[string]string) map[string]string
AppliedLookPicks filters a viewer's stored picks down to the ones that still count: the part must still be pickable by them and the value still valid. A pick that no longer counts is skipped, never deleted, so widening the setting again brings it back.
func BlockFragmentURL ¶
BlockFragmentURL is the address a placeable block loads its content from. A block on a page names that page in "on" so the fragment can check the placement; a block on a home sends none.
func BlockVisibleTo ¶
func BlockVisibleTo(ctx context.Context, cc *CampaignContext, checker BlockPlacementChecker, blockType, onEntityID, userID string) bool
BlockVisibleTo is the one rule every placeable fragment asks before it answers, so a block carries its own check rather than trusting where it was placed:
- a member always passes (each block still filters its content by viewer);
- since_last_here is a member's own and never passes a guest;
- any other block passes a guest only where the owner placed it: on the Guests home, or on the page named by onEntityID after the checker has verified that page. onEntityID alone is never trusted.
checker may be nil (nothing is placed on pages then).
func BuildFoundryConnectLine ¶
BuildFoundryConnectLine is the single definition of the connect-line wire format the Foundry module parses:
https base -> chronicle://host[:port]<path>/c/<campaignID>?key=<key> http base -> chronicle+http://host[:port]<path>/c/<campaignID>?key=<key>
The path is the base URL's path without a trailing slash (sub-path installs), and the key is query-escaped.
func CleanNavPins ¶
CleanNavPins checks a member's pins against what they may pin and returns them without repeats, in order. A key they cannot pin is refused rather than dropped, so a caller learns its view of the sidebar is out of date.
func CleanOwnerNavPins ¶
CleanOwnerNavPins checks the owner's own pins. The owner arranges the sidebar for everyone in the editor, so what they may pin for themselves is only the Manage tools, which no campaign layout holds. A key outside that set is refused, as CleanNavPins does for a member.
func ConfigureLeaving ¶
func ConfigureLeaving(svc CampaignService, chars CharacterReleaser, notifier LeaveNotifier)
ConfigureLeaving wires what leaving needs beyond the campaign's own data. Either may be nil, in which case that step is skipped.
func ConfigureVisitPasses ¶
func ConfigureVisitPasses(svc CampaignService, v VisitPasses)
ConfigureVisitPasses lets look-around passes open a campaign's view pages to their holders.
func DeskPage ¶
func DeskPage(cc *CampaignContext, d *Desk) templ.Component
DeskPage renders the owner's Campaign settings page. The page draws Find as a field on the title's row, so the frame is told not to draw the small button in its header: two Finds would also give the "/" shortcut two buttons to press.
func EmailLayoutOf ¶
EmailLayoutOf is the layout the owner picked for the campaign's emails, Note when unset or unknown.
func ExtensionDashboardPageURL ¶
ExtensionDashboardPageURL returns the dedicated dashboard-page URL for a slug (and true) when one exists, else ("", false).
func GuestHomeHasBlock ¶
GuestHomeHasBlock reports whether the campaign's Guests home places blockType.
func GuestPreviewAsked ¶
GuestPreviewAsked is the cheap first test for a door that does not run AllowPublicCampaignAccess: a read carrying a guest cookie. Whether it has any effect, and for which campaign, is GuestPreviewLowers' answer.
func GuestPreviewLowers ¶
func GuestPreviewLowers(c *echo.Context, campaign *Campaign, member *CampaignMember) bool
GuestPreviewLowers reports whether the guest preview lowers this member's request to a visitor's, by the same rule as the web middleware. It is for the REST API's session door, which resolves the member itself: the preview must show a visitor's view on every door a browser session opens, and a visitor has no session door at all.
func GuestsNoteAsked ¶
func GuestsNoteAsked(c *echo.Context, cc *CampaignContext) bool
GuestsNoteAsked reports whether this Home request is the DM team asking for the guests' dashboard of a private campaign. A player preview started from that address wins, so the page never claims two views at once. Display only.
func HasExtensionDashboard ¶
HasExtensionDashboard reports whether the given addon slug has a dashboard page. Read by addonListerAdapter in internal/app/routes.go to set PluginHubAddon.HasDashboard.
func HomeBlockTypes ¶
func HomeBlockTypes() []string
HomeBlockTypes lists the widgets a campaign home can hold, in the order the Customizer's palette offers them.
func HomeHasBlock ¶
func HomeHasBlock(l *DashboardLayout, blockType string) bool
HomeHasBlock reports whether a home layout places blockType in a column or a tile section. Home blocks that a visitor may see only where the owner chose to show them ask it of the Guests home, so placement is the consent: the fragment routes are reachable on any public campaign, and the layout is the only thing that says the owner wanted the block there.
func LookAccessAllows ¶
func LookAccessAllows(setting string, cc *CampaignContext) bool
LookAccessAllows reports whether a viewer falls inside an access setting. The owner is inside every setting. A non-member, or an unknown setting, is never inside.
func LookChoiceLabel ¶
LookChoiceLabel is the display name of one choice.
func MediaZipName ¶
MediaZipName is the media/ entry name the export gives a stored file: its basename, since the stored name carries date folders ("2026/03/<id>.png").
func MemberAccess ¶
func MemberAccess(c *Campaign, m CampaignMember) string
MemberAccess is the menu value for a member: Co-DM for a Scribe with the DM-only grant, otherwise their role. A Player who holds the grant (set up before the menu existed) reads as Player; MemberAccessNote says so.
func MemberAccessLabel ¶
func MemberAccessLabel(c *Campaign, m CampaignMember) string
MemberAccessLabel is the member's role as the People page words it.
func MemberAccessNote ¶
func MemberAccessNote(c *Campaign, m CampaignMember) string
MemberAccessNote explains the one setup the menu cannot show: a Player who can also read DM-only content. It keeps that until their role is changed.
func MemberHome ¶
MemberHome returns the id and name of the campaign a failed request was inside, for an error page's way back to its home. It answers only when the campaign middleware had already put a context on the request and the viewer is a member of it, so a hidden page's 404 says nothing about the campaign around it. ok is false everywhere else.
func NavCategoryKey ¶
NavCategoryKey returns the key of a category item.
func NavKeyKind ¶
NavKeyKind splits a key into the row kind it names (NavRowApp, NavRowCategory or NavRowLink) and its reference: an app's slug, a category's id or a link's id. ok is false for anything else.
func OnCampaignDeleted ¶
func OnCampaignDeleted(svc CampaignService, fn func(ctx context.Context, campaignID string))
OnCampaignDeleted registers fn to run after a campaign is purged from the Trash, not when it is moved there, so an Undo finds it whole.
func OnMemberRemoved ¶
func OnMemberRemoved(svc CampaignService, fn func(ctx context.Context, campaignID, userID string))
OnMemberRemoved registers fn to run after a user is removed from a campaign.
func OnMemberRoleChanged ¶
func OnMemberRoleChanged(svc CampaignService, fn func(ctx context.Context, campaignID, userID string, from, to Role))
OnMemberRoleChanged registers fn to run after a member's role changes to a different one (not on a no-op save), whether by an owner or an admin.
func OwnerCardVisible ¶
func OwnerCardVisible(ctx context.Context, cc *CampaignContext) bool
OwnerCardVisible reports whether a card that reads the owner's own routes (the activity log, the Foundry sync status) is drawn for this viewer. Those routes answer only the owner, so anyone else is shown nothing rather than a card that can only fail to load, and an owner looking as a player sees what a player sees. The block asks this itself, so it holds on any page it is placed on, not only on the owner's home.
func PinnableNavKeys ¶
func PinnableNavKeys(secs []NavSection) map[string]bool
PinnableNavKeys lists the rows a member may pin for themselves: every row of their sidebar (as ViewNav draws it before their own pins) outside Pinned. Rows the campaign already pins need no personal pin.
func PlaceableBlockTypes ¶
func PlaceableBlockTypes() []string
PlaceableBlockTypes lists the block types that may sit on any page, in the order a palette offers them.
func RedactMemberCharacters ¶
func RedactMemberCharacters(members []CampaignMember, visibilityRole int, viewerID string)
RedactMemberCharacters clears, for a viewer below Owner visibility, the character of every other member whose page players can't all see: a hidden hero's name must not reach the rest of the table through the member list. Custom-shared pages are cleared too; the list cannot tell which viewers a custom grant covers.
func RegisterExportRoutes ¶
func RegisterExportRoutes(e *echo.Echo, eh *ExportHandler, svc CampaignService, authSvc auth.AuthService)
RegisterExportRoutes sets up campaign export/import routes. Export is campaign-scoped (owner only). Import is auth-only (creates new campaign). Both are heavy (media zips, adapters across many tables), so they carry tight rate limits to stop a runaway refresh or POST flood from monopolizing the server.
func RegisterInviteRoutes ¶
func RegisterInviteRoutes(e *echo.Echo, ih *InviteHandler, svc CampaignService, authSvc auth.AuthService)
RegisterInviteRoutes sets up campaign invite routes. The accept page is publicly accessible (with optional auth). Invite CRUD is owner-only within the campaign scope.
func RegisterRoutes ¶
func RegisterRoutes(e *echo.Echo, h *Handler, svc CampaignService, authSvc auth.AuthService)
RegisterRoutes sets up all campaign-related routes on the given Echo instance. Campaign list and creation require auth. Campaign-scoped view routes allow public access to public campaigns. Mutating routes require membership.
func RequireCampaignAccess ¶
func RequireCampaignAccess(service CampaignService) echo.MiddlewareFunc
RequireCampaignAccess returns middleware that resolves the campaign from the :id URL parameter and the user's membership role. The resolved CampaignContext is injected into the Echo context for downstream handlers.
Behavior:
- If the user is a member → MemberRole is set from the campaign_members row
- If the user is NOT a member AND is a site admin → MemberRole = RoleNone, IsSiteAdmin = true (admin actions go through /admin routes)
- If the user is NOT a member AND is NOT an admin → 403 Forbidden
- If the campaign is archived, POST/PUT/PATCH/DELETE → 403 Forbidden (GET/HEAD/OPTIONS still pass). Checked only after the above, so a non-member's 403/404 is unchanged by archive state. This is the single default every route group built on this middleware inherits; RequireCampaignAccessEvenIfArchived is the deliberate, short exception list (see routes.go).
Must be applied AFTER auth.RequireAuth.
func RequireCampaignAccessEvenIfArchived ¶
func RequireCampaignAccessEvenIfArchived(service CampaignService) echo.MiddlewareFunc
RequireCampaignAccessEvenIfArchived is RequireCampaignAccess without the archive gate: same membership resolution, same 404/403 for a missing campaign or a non-member, but a write is never blocked for being archived. Reserved for the few actions that must keep working on an archived campaign — see routes.go for the short, commented list.
Must be applied AFTER auth.RequireAuth.
func RequireCapability ¶
func RequireCapability(check func(*CampaignContext) bool, denyMsg string) echo.MiddlewareFunc
RequireCapability gates a route on a CampaignContext capability predicate (e.g. (*CampaignContext).CanControlWorldState) rather than a flat MemberRole threshold — so a co-DM grantee passes where RequireRole(RoleOwner) would reject them. Must be applied after RequireCampaignAccess. denyMsg is the 403 message on failure.
func RequireRole ¶
func RequireRole(minRole Role) echo.MiddlewareFunc
RequireRole returns middleware that checks the user's membership role meets the minimum required level. Uses MemberRole (not admin bypass) so that admins who joined as Player are treated as Players for content access.
Must be applied AFTER RequireCampaignAccess.
func RequireViewAccess ¶
func RequireViewAccess() echo.MiddlewareFunc
RequireViewAccess gates a public-capable VIEW route on view eligibility rather than a role threshold: it passes when the requester is a real campaign member, a site admin, or the campaign is public. This is the correct gate for routes mounted under AllowPublicCampaignAccess — RequireRole(RolePlayer) would reject every anonymous/non-member RoleNone requester even on a public campaign, and promoting anon to RolePlayer would let Player-only content leak to the public. The visibility filter still strips Player-only content for RoleNone viewers, so they see only public/everyone data.
Must be applied AFTER AllowPublicCampaignAccess (which populates the context; for a PRIVATE campaign it already rejects anon -> 302 /login and authenticated non-members -> 403 before this runs, so IsPublic is only ever reached for genuinely public campaigns). Mutating or Player-only routes must keep RequireRole.
func ResolveDashboardTile ¶
func ResolveDashboardTile(ctx context.Context, campaignID string, t tilegrid.Tile) (w, h int, ok bool)
ResolveDashboardTile gives the size a dashboard tile is drawn at, falling back to its type's first allowed size when the stored one is no longer allowed. ok is false when the type allows no size.
func ScanSmokeTest ¶
ScanSmokeTest returns a startup probe that runs a real SELECT + Scan on the campaigns table. If the column list in the query doesn't match the Campaign struct's Scan destinations, this fails at startup instead of when a user visits the campaigns page.
func SetTileSizeResolver ¶
func SetTileSizeResolver(r TileSizeResolver)
SetTileSizeResolver wires the registry that answers tile sizes. Until it is set (unit tests), no block type can be a tile and a dashboard tile section draws its not-available notice.
func Slugify ¶
Slugify creates a URL-safe slug from a name. Lowercase, replace non-alphanumeric characters with hyphens, trim leading/trailing hyphens.
func TileVisibleTo ¶
func TileVisibleTo(config map[string]any, cc *CampaignContext) bool
TileVisibleTo reports whether a tile's config.visibility lets the viewer see it. It is the same rule entity pages apply to a block ("dm_only" shows only to those who can read DM-only content).
func ValidHomeAudience ¶
ValidHomeAudience reports whether name is one of the home audiences.
func ValidateHomeLayout ¶
func ValidateHomeLayout(ctx context.Context, campaignID string, layout *DashboardLayout) error
ValidateHomeLayout checks a layout against the rules every home is saved under, and cleans its Text Block content in place, so a change that doesn't come through the Customizer (an AI's) is held to the same ones.
func ValidateTierDefinitions ¶
func ValidateTierDefinitions(defs []TierDefinition) error
ValidateTierDefinitions is the check SetEventTierDefinitions runs, for a caller that must refuse a bad set before it saves one.
func ViewerAccessLabel ¶
func ViewerAccessLabel(cc *CampaignContext) string
ViewerAccessLabel is the viewer's own role in the People page's words, so a Co-DM reads "Co-DM" on the campaign home, not "Scribe". It is empty for a viewer with no role (a public or admin visit), so the home leaves the chip out rather than printing "None".
func ViewingAsGuest ¶
func ViewingAsGuest(c *echo.Context, cc *CampaignContext) bool
ViewingAsGuest reports whether the REAL owner or co-DM has the guest cookie on. It is the request, not the effect: on a private campaign guests cannot get in, so no downgrade happens there. A downgraded guest-preview context is not the DM team any more, so it answers false; read cc.Preview for that. Display only: never use it to grant.
func ViewingAsPlayer ¶
func ViewingAsPlayer(c *echo.Context, cc *CampaignContext) bool
ViewingAsPlayer reports whether the owner or a co-DM has "view as player" on in this campaign. The cookie is site-wide but its value is the id of the campaign it was turned on for, so a preview started in one campaign is not honoured in another. Handlers read it themselves because the layout context that also carries it is only filled in when a page renders. Display only: never use it to grant.
Types ¶
type AILook ¶
type AILook struct {
// contains filtered or unexported fields
}
AILook is the campaign's look as the AI engine sees it (aiplug): the `look` block that changes the Customizer's Look choices and the `campaign-look` lookup that reads them back. A block is a partial update over the one look every campaign has, and is stored through SaveAppearance, the call the Look screen's Save makes, so every value passes the screen's own checks.
func NewAILook ¶
func NewAILook(store aiLookStore, drafts AILookDrafts) *AILook
NewAILook builds the look's AI part over the campaign service and the Customize draft store.
func (*AILook) Answer ¶
func (k *AILook) Answer(ctx context.Context, campaignID string, a aiplug.Actor, _ aiplug.Record) (string, string, error)
Answer writes the look as a block. It is owner-only like the block, and a players-view key never gets it.
func (*AILook) Apply ¶
func (k *AILook) Apply(ctx context.Context, campaignID string, a aiplug.Actor, r aiplug.Record) error
Apply saves the look through SaveAppearance, the Look screen's own save, after checking the block again against the look as it is now.
func (*AILook) Doc ¶
Doc lists every key with the values the save accepts, built from the same lists the save checks.
func (*AILook) Export ¶
Export is empty: the look is long and `what: campaign-look` answers it on request, so it does not ride along in every export.
func (*AILook) LookupInfo ¶
func (*AILook) LookupInfo() aiplug.LookupInfo
LookupInfo describes `what: campaign-look` and its tool. It is not `looks`, which is the Armory's item looks.
type AILookDrafts ¶
type AILookDrafts interface {
Get(ctx context.Context, campaignID, userID string) (*CustomizeDraft, error)
}
AILookDrafts reads the owner's unpublished Customize draft. It may be nil (no drafts to protect).
type AISettings ¶
type AISettings struct {
// contains filtered or unexported fields
}
AISettings is the campaigns' part of the AI engine (aiplug): the `settings` lookup, which says what the Game & features screen and the campaign's details say, so an AI knows which parts of Chronicle the campaign uses.
It reads a fixed short list of fields instead of the settings JSON, so a field added to the settings later (a code, a key, a link) can never reach an AI by accident. People, roles, invites, join and guest codes, API keys, the Foundry link, the Your AI page, handover and deletion are not here.
func NewAISettings ¶
func NewAISettings(camps aiCampaignReader, addons AddonLister) *AISettings
NewAISettings builds the lookup. addons may be nil, which leaves the add-ons out of the Director's answer (a non-Director never gets them).
func (*AISettings) Answer ¶
func (s *AISettings) Answer(ctx context.Context, campaignID string, a aiplug.Actor, _ aiplug.Record) (string, string, error)
Answer reads as the Actor. Everyone gets the name, description and game system. Only the Director team (owner or co-DM) also gets the add-ons on and off and the importance levels: an enabled add-on may have no player screen, so listing them would tell a player's key (or Safe privacy) more than the player can see.
func (*AISettings) LookupInfo ¶
func (*AISettings) LookupInfo() aiplug.LookupInfo
LookupInfo describes `what: settings` and its tool. The tool is not owner-only: a player's key may call it, and gets what a player sees.
type AccountCampaignLister ¶
type AccountCampaignLister struct {
Service CampaignService
}
AccountCampaignLister gives Account settings the campaigns a person belongs to (auth.CampaignLister), so auth never imports this plugin.
func (AccountCampaignLister) SettingsCampaigns ¶
func (l AccountCampaignLister) SettingsCampaigns(ctx context.Context, userID string) (auth.CampaignSettingsList, error)
SettingsCampaigns lists the person's campaigns for the account rail.
type AddMemberRequest ¶
type AddMemberRequest struct {
Email string `json:"email" form:"email"`
Role string `json:"role" form:"role"`
}
AddMemberRequest holds the data for adding a member to a campaign.
type AddonExporter ¶
type AddonExporter interface {
ExportAddons(ctx context.Context, campaignID string) ([]ExportAddon, error)
}
AddonExporter gathers addon configuration for a campaign export.
type AddonImporter ¶
type AddonImporter interface {
ImportAddons(ctx context.Context, campaignID, userID string, data []ExportAddon, report *ImportReport) error
}
AddonImporter enables addons from import data.
type AddonLister ¶
type AddonLister interface {
ListForPluginHub(ctx context.Context, campaignID string) ([]PluginHubAddon, error)
}
AddonLister lists addons for the plugin hub page. Avoids importing the addons package directly.
type AdminSearchOptions ¶
type AdminSearchOptions struct {
// Query matches the campaign name as a case-insensitive substring.
Query string
// System is "" (all), SystemFilterNone, SystemFilterCustom or a system id.
System string
ListOptions
}
AdminSearchOptions are the already-validated inputs of the admin campaign list.
type Appearance ¶
type Appearance struct {
Look string `json:"look,omitempty"` // Look the owner started from; Custom is derived, never stored.
PageTone string `json:"page_tone,omitempty"` // "cool", "warm" or "paper".
Contrast string `json:"contrast,omitempty"` // "standard" or "high".
BodyFont string `json:"body_font,omitempty"` // Text face id (AppearanceBodyFonts).
HeadingFont string `json:"heading_font,omitempty"` // Heading face id (AppearanceHeadingFonts); "same" follows the text.
TypeScale string `json:"type_scale,omitempty"` // "compact", "standard" or "roomy".
ButtonStyle string `json:"button_style,omitempty"` // "lift", "press", "glow", "ink" or "keystone".
IconAmount string `json:"icon_amount,omitempty"` // How many icons show: "few" (default), "names" or "all".
IconColour string `json:"icon_colour,omitempty"` // What colours category icons: "ink" (default), "accent" or "category".
Elevation string `json:"elevation,omitempty"` // "flat", "standard", "dramatic" or "ambient".
MotionSpeed string `json:"motion_speed,omitempty"` // "snappy", "standard" or "leisurely".
ReduceMotion bool `json:"reduce_motion,omitempty"` // Calmer motion for every member of the campaign.
SidebarColour string `json:"sidebar_colour,omitempty"` // Menu colour: "charcoal" (default), "ink", "tinted" or "own".
SidebarOwn string `json:"sidebar_own,omitempty"` // The owner's menu colour, used when SidebarColour is "own".
SidebarCorner string `json:"sidebar_corner,omitempty"` // Menu's top-left corner: "plain", "subtitle" or "banner".
SidebarSubtitle string `json:"sidebar_subtitle,omitempty"` // The subtitle line under the name (corner "subtitle").
SidebarBanner string `json:"sidebar_banner,omitempty"` // Banner picture behind the name (corner "banner").
PeekGlow string `json:"peek_glow,omitempty"` // Hidden-menu edge glow: "accent" (default) or "own".
PeekGlowColour string `json:"peek_glow_colour,omitempty"` // The glow's own colour, used when PeekGlow is "own".
HeaderHeight string `json:"header_height,omitempty"` // "slim" (default) or "tall".
HoverCard string `json:"hover_card,omitempty"` // Hover card look: "paper" (default), "plain", "night" or "compact".
SheetStyle string `json:"sheet_style,omitempty"` // Character sheet style (AppearanceSheetStyles); "modern" is the default.
CraftArt string `json:"craft_art,omitempty"` // How made items are drawn (AppearanceCraftArts); "painted" is the default.
PageLook string `json:"page_look,omitempty"` // How pages draw their blocks (AppearancePageLooks); "standard" is the default.
TimelinePopup string `json:"timeline_popup,omitempty"` // What opens on a time line's event: "classic" (default) or "corner".
StyleKit string `json:"style_kit,omitempty"` // The pages' character under the Material page look (AppearanceStyleKits); "material" is the default.
Entrance string `json:"entrance,omitempty"` // How a card opens under the Material kit (AppearanceEntrances); empty is Grow.
MomentSheen bool `json:"moment_sheen,omitempty"` // Moments: an accent sweep across a page's header.
MomentCascade bool `json:"moment_cascade,omitempty"` // Moments: cards of a list stagger in.
MomentSpark bool `json:"moment_spark,omitempty"` // Moments: dots radiate from a save.
DmScreenKit string `json:"dmscreen_kit,omitempty"` // The DM Screen's own style kit (AppearanceStyleKits); empty wears the pages' kit.
EmailLayout string `json:"email_layout,omitempty"` // The campaign's emails (AppearanceEmailLayouts); empty is Note.
BuilderLook string `json:"builder_look,omitempty"` // How the hero builder looks (AppearanceBuilderLooks); empty is "plain".
// Who may pick their own version of a part (look_access.go); empty is the
// part's default.
AccessSheet string `json:"access_sheet,omitempty"`
AccessPage string `json:"access_page,omitempty"`
AccessHover string `json:"access_hover,omitempty"`
AccessDmScreen string `json:"access_dmscreen,omitempty"`
}
Appearance holds the Customize page's style choices that have no older home in CampaignSettings. Every empty field means the Classic look, so a campaign that never opens Customize renders exactly as Chronicle ships.
func (Appearance) EffectiveNavStyle ¶
func (a Appearance) EffectiveNavStyle() string
EffectiveNavStyle is the menu highlight this appearance shows.
type AppearanceBrandInput ¶
type AppearanceBrandInput struct {
Name string `json:"name"`
Logo string `json:"logo"`
Welcome string `json:"welcome"`
Backdrop string `json:"backdrop"`
}
AppearanceBrandInput is the Brand section. Pictures are media filenames from the Customize picture upload; empty removes the picture.
type AppearanceColourInput ¶
type AppearanceColourInput struct {
Accent string `json:"accent"`
S1 string `json:"s1"`
S2 string `json:"s2"`
Page string `json:"page"`
Contrast string `json:"contrast"`
}
AppearanceColourInput is the Colours section: Accent is Menus and links, S1 Headers and events, S2 Tags and marks. S1 and S2 empty follow Accent.
type AppearanceHeaderInput ¶
type AppearanceHeaderInput struct {
Bg string `json:"bg"`
Height string `json:"height"`
Color string `json:"color"`
From string `json:"from"`
To string `json:"to"`
Dir string `json:"dir"`
Image string `json:"image"`
Scrim string `json:"scrim"`
Widgets []string `json:"widgets"`
Links []TopbarLink `json:"links"`
Text string `json:"text"`
}
AppearanceHeaderInput is the Header section. Bg "" is the default header that matches the page.
type AppearanceInput ¶
type AppearanceInput struct {
Look string `json:"look"`
Brand AppearanceBrandInput `json:"brand"`
Header AppearanceHeaderInput `json:"header"`
Colours AppearanceColourInput `json:"colours"`
Style string `json:"style"`
Strength string `json:"strength"`
PageName string `json:"pageName"`
} `json:"nav"`
Type struct {
Body string `json:"body"`
Heading string `json:"heading"`
Scale string `json:"scale"`
} `json:"type"`
Buttons struct {
Style string `json:"style"`
} `json:"buttons"`
Icons struct {
Amount string `json:"amount"`
Colour string `json:"colour"`
} `json:"icons"`
Motion struct {
Elevation string `json:"elevation"`
Speed string `json:"speed"`
ReduceAll bool `json:"reduceAll"`
Entrance string `json:"entrance"` // One of AppearanceEntrances; empty keeps the stored one.
Sheen bool `json:"sheen"`
Cascade bool `json:"cascade"`
Spark bool `json:"spark"`
} `json:"motion"`
Sidebar AppearanceSidebarInput `json:"sidebar"`
Hover struct {
Look string `json:"look"`
TimelinePopup string `json:"timelinePopup"`
} `json:"hover"`
Sheet struct {
Style string `json:"style"`
CraftArt string `json:"craftArt"` // "painted", "lifelike" or "illustrated".
} `json:"sheet"`
Page struct {
Look string `json:"look"`
Kit string `json:"kit"`
DmKit string `json:"dmKit"` // "same" follows the pages' kit.
} `json:"page"`
Email struct {
Layout string `json:"layout"`
} `json:"email"`
Builder struct {
Look string `json:"look"` // One of AppearanceBuilderLooks; empty keeps the stored one.
} `json:"builder"`
// Access is who may change each part for themselves. Nil keeps what the
// campaign has stored.
Access *LookAccessInput `json:"access,omitempty"`
}
AppearanceInput is one Save from the Customize page: the whole draft, so every setting lands in a single write and nothing saved by half.
func (*AppearanceInput) AppearancePictures ¶
func (in *AppearanceInput) AppearancePictures() []string
AppearancePictures lists the picture filenames one Save writes, so the handler can check each belongs to this campaign before the service runs.
type AppearanceSidebarInput ¶
type AppearanceSidebarInput struct {
Colour string `json:"colour"`
Own string `json:"own"`
Corner string `json:"corner"`
Subtitle string `json:"subtitle"`
Banner string `json:"banner"`
Glow string `json:"glow"`
GlowColour string `json:"glowColour"`
}
AppearanceSidebarInput is the Sidebar section. Colour is the menu colour choice; Own, GlowColour and Banner only matter while the choice that uses them is selected, and are dropped otherwise so nothing stale is stored.
type AuditLogger ¶
type AuditLogger interface {
LogEvent(ctx context.Context, campaignID, userID, action string, details map[string]any) error
}
AuditLogger records audit events for campaign-scoped actions. Defined here as an interface to avoid circular imports with the audit plugin.
type BlockPlacementChecker ¶
type BlockPlacementChecker interface {
// GuestMaySee reports whether the page onEntityID exists in the campaign,
// the viewer may open it, and its layout, as that page wears it, draws
// blockType for a viewer without the Director's role. Any doubt is false.
GuestMaySee(ctx context.Context, campaignID, blockType, onEntityID, userID string, visibilityRole int) bool
}
BlockPlacementChecker answers whether the owner placed a block on a page a guest may open. The campaigns package cannot see entity layouts, so the entities plugin implements it and the app wires it into the handlers that draw the fragments.
type BrushPrefs ¶
type BrushPrefs interface {
BrushHidden(ctx context.Context, userID, campaignID string) (bool, error)
}
BrushPrefs reads one person's choice to hide the header's brush in one campaign. It is an interface so the campaigns plugin reads the person's display choices through the auth service, never its tables.
type BundledMediaFile ¶
type BundledMediaFile struct {
// Filename is the on-disk basename (UUID-based, the same name the
// MediaService uses to serve the file). Used as the zip entry name
// under media/. Must not contain path separators.
Filename string
// SizeBytes is the file size from the database. Used to enforce the
// per-bundle cap before any reader is opened.
SizeBytes int64
// MimeType is the stored mime type, surfaced in the manifest entry.
MimeType string
// Open returns a reader for the file's raw bytes. The handler is
// responsible for closing the returned ReadCloser.
Open func() (io.ReadCloser, error)
}
BundledMediaFile pairs a media file's metadata with an opener that returns the file's raw bytes. The export handler walks these and embeds each in the output zip when ?include_media=1 is set. Open is a function rather than an io.Reader so the handler can size-cap the total bundle before it touches disk for the bytes themselves.
type CalendarExporter ¶
type CalendarExporter interface {
ExportCalendar(ctx context.Context, campaignID string, entitySlugLookup func(string) string) (*ExportCalendarData, error)
}
CalendarExporter gathers calendar data for a campaign export.
type CalendarImporter ¶
type CalendarImporter interface {
ImportCalendar(ctx context.Context, campaignID string, data *ExportCalendarData, idMap *IDMap, report *ImportReport) error
}
CalendarImporter creates calendar from import data.
type Campaign ¶
type Campaign struct {
ID string `json:"id"`
Name string `json:"name"`
Slug string `json:"slug"`
Description *string `json:"description,omitempty"`
IsPublic bool `json:"is_public"`
Settings string `json:"settings"`
BackdropPath *string `json:"backdrop_path,omitempty"`
SidebarConfig string `json:"sidebar_config"`
DashboardLayout *string `json:"dashboard_layout,omitempty"` // JSON layout; nil = use hardcoded default.
OwnerDashboardLayout *string `json:"owner_dashboard_layout,omitempty"` // Owner-only dashboard layout; nil = use default.
CreatedBy string `json:"created_by"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
ArchivedAt *time.Time `json:"archived_at,omitempty"` // Soft-archive timestamp; nil = active.
JoinCode *string `json:"join_code,omitempty"` // Shareable invite code; nil = no active link.
}
Campaign represents a top-level worldbuilding container.
func (*Campaign) DirectorHome ¶
func (c *Campaign) DirectorHome() *DashboardLayout
DirectorHome is the home the DM team sees: the Everyone home plus whatever the Director's own saved home holds that the Everyone home does not.
Why a merge and not "the Director's saved home wins": a new campaign saves the Director a copy of the starter front page, and a saved Director layout used to shadow the Everyone home completely, so a widget added for everyone never reached the DM team. Merging at read time fixes that without rewriting any stored layout; the Director's saved home keeps its data and is read as "my extras on top of Everyone".
A Director block counts as already on the Everyone home when it shares an id with one there, or has the same type and settings (an older copy whose ids differ). Everyone's version then stands, so a block the Director once copied follows later edits to the Everyone home instead of freezing. Every other Director block is an extra and is placed after the Everyone row that the Director's layout kept it behind, so a setup note under the welcome banner stays under it.
func (*Campaign) GetRoleDashboardJSON ¶
func (c *Campaign) GetRoleDashboardJSON(roleName string) *DashboardLayout
GetRoleDashboardJSON extracts a single role's layout from the dashboard_layout column. Used by the API to return role-specific layouts to the editor.
func (*Campaign) HasSavedHome ¶
HasSavedHome reports whether the audience has a layout of its own saved.
func (*Campaign) HomeLayout ¶
func (c *Campaign) HomeLayout(audience string) (*DashboardLayout, bool)
HomeLayout returns the layout an audience sees and whether it is that audience's own saved layout (false means it is borrowed from a fallback). Fallbacks: guest → the built-in guest home; every other audience → the saved Default → the built-in home.
func (*Campaign) IsArchived ¶
IsArchived returns true if the campaign has been soft-archived.
func (*Campaign) ParseDashboardLayout ¶
func (c *Campaign) ParseDashboardLayout() *DashboardLayout
ParseDashboardLayout parses the campaign's dashboard_layout JSON into a DashboardLayout struct. Returns nil if the column is NULL (use default). For backward compatibility, this returns the "default" layout from the role-keyed format, or the bare layout from the legacy format.
func (*Campaign) ParseOwnerDashboardLayout ¶
func (c *Campaign) ParseOwnerDashboardLayout() *DashboardLayout
ParseOwnerDashboardLayout parses the campaign's owner_dashboard_layout JSON into a DashboardLayout struct. Returns nil if the column is NULL (use default).
func (*Campaign) ParseRoleDashboardLayout ¶
func (c *Campaign) ParseRoleDashboardLayout(role Role) *DashboardLayout
ParseRoleDashboardLayout returns the dashboard layout for the given role. Falls back: role-specific → default → nil (use hardcoded default). Handles both legacy format (bare layout) and new role-keyed format.
func (*Campaign) ParseSettings ¶
func (c *Campaign) ParseSettings() CampaignSettings
ParseSettings parses the campaign's settings JSON into a CampaignSettings struct. Returns a zero-value struct if parsing fails or settings are empty.
func (*Campaign) ParseSidebarConfig ¶
func (c *Campaign) ParseSidebarConfig() SidebarConfig
ParseSidebarConfig parses the campaign's sidebar_config JSON into a SidebarConfig struct. Returns an empty config on parse failure.
func (*Campaign) RemoveRoleDashboardJSON ¶
RemoveRoleDashboardJSON removes a single role's layout from the wrapper. Returns the new full JSON string, or nil if all roles are now empty.
func (*Campaign) SetRoleDashboardJSON ¶
func (c *Campaign) SetRoleDashboardJSON(roleName string, layout *DashboardLayout) (*string, error)
SetRoleDashboardJSON updates a single role's layout within the role-keyed wrapper format and returns the new full JSON string. Migrates legacy format to role-keyed format automatically.
type CampaignContext ¶
type CampaignContext struct {
Campaign *Campaign
MemberRole Role // Actual membership role, or RoleNone if not a member.
IsSiteAdmin bool // True if user has users.is_admin flag.
IsDmGranted bool // True if user has been granted dm_only visibility by Owner.
// IsMember is true only when MemberRole came from a real campaign_members
// row. False for anonymous visitors, authenticated non-members, and
// admins viewing without joining. Lets callers distinguish "RoleNone
// because not a member" from a genuine low role.
IsMember bool
// IsAnonymous is true when there is no authenticated session at all
// (logged-out public-campaign visitor). Implies !IsMember. Used by the
// glance badge to label content "visible to the public".
IsAnonymous bool
// VisitUntil is set for a signed-in non-member reading the campaign on a
// look-around pass: when the pass ends. They see what a public visitor
// sees (RoleNone), and write routes refuse them like any non-member.
VisitUntil *time.Time
// Preview, PreviewerRole and PreviewerCanDM exist ONLY to draw the
// preview's own chrome: the "Dashboard for" line, the strip, the eye and
// the way back. They record that the DM team is looking as someone else
// and who they really are. Nothing may ever grant access, widen
// visibility or pick a role from them; every access decision reads
// MemberRole, IsMember and IsDmGranted, which a preview has already
// lowered.
Preview string // "", PreviewPlayer, PreviewGuest or PreviewGuestCode
PreviewerRole Role // The viewer's real role while Preview is set.
PreviewerCanDM bool // Whether the viewer is really on the DM team.
}
CampaignContext holds the resolved campaign and the requesting user's effective permissions. Injected into the Echo context by RequireCampaignAccess middleware.
MemberRole is the actual campaign_members role (content visibility); IsSiteAdmin is the site-level admin flag (admin routes only) — an admin who joined as Player sees Player-visible content, and one who hasn't joined has MemberRole=RoleNone.
A non-member viewer (logged-out, or authenticated but not in the campaign) also gets MemberRole=RoleNone — strictly below RolePlayer, so RolePlayer always means "an authenticated party member". IsMember/ IsAnonymous record WHY MemberRole is RoleNone, so callers can tell "the public" from "a Player" without re-deriving it from the role int.
func GetCampaignContext ¶
func GetCampaignContext(c *echo.Context) *CampaignContext
GetCampaignContext retrieves the campaign context from the Echo context. Returns nil if RequireCampaignAccess middleware was not applied.
func (*CampaignContext) CanAuthorDmOnly ¶
func (cc *CampaignContext) CanAuthorDmOnly() bool
CanAuthorDmOnly reports whether the user may CREATE/mark dm_only content. Same co-DM capability as world-state control. Distinct from CanSeeDmOnly (read) — authoring is the write side a DmGrant also confers. Route the calendar create/edit and visibility UI through this so the grant is honored (not just VisibilityRole).
func (*CampaignContext) CanControlWorldState ¶
func (cc *CampaignContext) CanControlWorldState() bool
CanControlWorldState reports whether the user may drive live world-state (advance time, set weather/mood): the campaign Owner OR a DM-grantee. A DmGrant is a co-DM grant, not just secret-viewing — see CanAuthorDmOnly.
func (*CampaignContext) DMTeamChrome ¶
func (cc *CampaignContext) DMTeamChrome() bool
DMTeamChrome reports whether the viewer is really on the DM team, even while a preview has lowered their role. Chrome only (see Preview).
func (*CampaignContext) EffectiveRole ¶
func (cc *CampaignContext) EffectiveRole() Role
EffectiveRole returns the permission level to use for route-level authorization. Site admins who are not members still get RoleNone here -- they should use /admin routes instead for admin operations.
func (*CampaignContext) GuestCodePreviewContext ¶
func (cc *CampaignContext) GuestCodePreviewContext(now time.Time) *CampaignContext
GuestCodePreviewContext is GuestPreviewContext for a visitor who came in on a guest code: the same visitor, holding a look-around pass that ends a week from now. A pass gives exactly what a public visit gives (RoleNone) and opens a private campaign for reading, so this lowers a DM-team member as far as GuestPreviewContext does; ADR-076.
func (*CampaignContext) GuestPreviewContext ¶
func (cc *CampaignContext) GuestPreviewContext() *CampaignContext
GuestPreviewContext is the context a signed-in visitor who is not a member gets, with the real viewer recorded for the preview's chrome. It is built from nothing but the campaign, never copied from cc, so a field added to CampaignContext later defaults to no access in a guest preview. It can only lower privileges. Call it on the REAL context of a request from the DM team; ADR-074.
func (*CampaignContext) HomeAudience ¶
func (cc *CampaignContext) HomeAudience() string
HomeAudience returns which saved home this viewer gets: the owner and every co-DM get the Director's, a viewer with no membership gets the guest one, and members get their role's.
func (*CampaignContext) InGuestPreview ¶
func (cc *CampaignContext) InGuestPreview() bool
InGuestPreview reports whether this context is either guest preview. Chrome only (see Preview).
func (*CampaignContext) NewPagePrivacy ¶
func (cc *CampaignContext) NewPagePrivacy(requested patch.Field[bool]) bool
NewPagePrivacy is ResolveNewEntityPrivacy for a page this member is making. A Player's or Scribe's new page is always open to players: hidden pages are the owner's and Co-DMs', and everyone else sees what players see, so a page they made hidden would answer "not found" to them the moment they saved it. That includes a hero a player just made for themselves.
func (*CampaignContext) OwnerChrome ¶
func (cc *CampaignContext) OwnerChrome() bool
OwnerChrome reports whether the viewer is really the owner, even while a preview has lowered their role. Chrome only (see Preview).
func (*CampaignContext) PlayerPreview ¶
func (cc *CampaignContext) PlayerPreview() *CampaignContext
PlayerPreview is a copy of cc that draws a page as a player sees it, for an owner with "view as player" on: edit controls, owner menus and Director grants fall away. Display only: pass it to templates, never to a write or an access check.
func (*CampaignContext) VisibilityRole ¶
func (cc *CampaignContext) VisibilityRole() int
VisibilityRole returns the effective role for content visibility filtering. DM-granted users are treated as Owners for visibility purposes so they can see dm_only content, while their actual MemberRole stays unchanged for authorization (create/edit) checks.
For anonymous / non-member viewers this returns int(RoleNone) == 0, which is below RolePlayer (1). In the visibility filter a role-tier grant matches when subject_id <= viewerRole, so a viewer at 0 matches no Player-role grant — the public sees only content marked public/everyone (default + not-private, or an explicit 'public' grant), never Player-only or Player-role tag grants.
type CampaignExport ¶
type CampaignExport struct {
Format string `json:"format"` // "chronicle-campaign-v1"
Version int `json:"version"` // schema version
Campaign ExportCampaignMeta `json:"campaign"`
EntityTypes []ExportEntityType `json:"entity_types"`
Entities []ExportEntity `json:"entities"`
Tags []ExportTag `json:"tags"`
EntityTags []ExportEntityTag `json:"entity_tags"`
Relations []ExportRelation `json:"relations"`
Groups []ExportGroup `json:"groups,omitempty"`
Posts []ExportPost `json:"posts,omitempty"`
Calendar *ExportCalendarData `json:"calendar,omitempty"`
Timelines []ExportTimeline `json:"timelines,omitempty"`
Sessions []ExportSession `json:"sessions,omitempty"`
Maps []ExportMap `json:"maps,omitempty"`
Notes []ExportNote `json:"notes,omitempty"`
Addons []ExportAddon `json:"addons,omitempty"`
Media []ExportMediaFile `json:"media,omitempty"`
// RollTables is the campaign's rolling-tables document, kept as the
// plugin's own JSON so restoring it runs the plugin's validation.
RollTables json.RawMessage `json:"roll_tables,omitempty"`
Quests []ExportQuest `json:"quests,omitempty"`
Recipes []ExportRecipe `json:"recipes,omitempty"`
// ExportedAt records when this export was generated.
ExportedAt time.Time `json:"exported_at"`
}
CampaignExport is the top-level JSON envelope for a campaign export.
func DetectCampaignExport ¶
func DetectCampaignExport(data []byte) (*CampaignExport, error)
DetectCampaignExport validates that the given JSON is a valid Chronicle campaign export and returns the parsed structure. Returns an error if the format is unrecognized or the version is unsupported.
type CampaignGroup ¶
type CampaignGroup struct {
ID int `json:"id"`
CampaignID string `json:"campaign_id"`
Name string `json:"name"`
Description *string `json:"description,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Members []GroupMemberInfo `json:"members,omitempty"`
}
CampaignGroup is a named collection of campaign members used for per-entity permission grants (e.g., "Party A can see this entity").
type CampaignHookDispatcher ¶
type CampaignHookDispatcher interface {
DispatchCampaignDeleted(ctx context.Context, campaignID string)
}
CampaignHookDispatcher fires lifecycle events for WASM plugin notification. Implemented by the extensions HookDispatcher.
type CampaignMember ¶
type CampaignMember struct {
CampaignID string `json:"campaign_id"`
UserID string `json:"user_id"`
Role Role `json:"role"`
// CharacterEntityID is, from ListMembers, the character the member plays
// (the page they own, else the older per-member link); single-member
// reads return the stored link only.
CharacterEntityID *string `json:"character_entity_id,omitempty"`
JoinedAt time.Time `json:"joined_at"`
// Joined from users table for display purposes.
DisplayName string `json:"display_name,omitempty"`
Email string `json:"email,omitempty"`
AvatarPath *string `json:"avatar_path,omitempty"`
// IsGuest marks someone who joined with a guest code and has no email
// yet; Email is then empty.
IsGuest bool `json:"is_guest,omitempty"`
// CharacterName is that character's name, from ListMembers only.
CharacterName *string `json:"character_name,omitempty"`
// its name and id may go to members other than its player.
CharacterShared bool `json:"-"`
}
CampaignMember represents a user's membership in a campaign.
type CampaignRepository ¶
type CampaignRepository interface {
// Campaign CRUD
Create(ctx context.Context, campaign *Campaign) error
FindByID(ctx context.Context, id string) (*Campaign, error)
FindBySlug(ctx context.Context, slug string) (*Campaign, error)
ListByUser(ctx context.Context, userID string, opts ListOptions) ([]Campaign, int, error)
ListAll(ctx context.Context, opts ListOptions) ([]Campaign, int, error)
SearchAll(ctx context.Context, opts AdminSearchOptions) ([]Campaign, error)
CountBySystem(ctx context.Context, query string) ([]SystemCount, error)
ListPublic(ctx context.Context, limit int) ([]Campaign, error)
Update(ctx context.Context, campaign *Campaign) error
// UpdateDetails writes only the columns it is given (nil leaves a column
// alone), so a rename or a public/private flip cannot overwrite a
// description saved a moment earlier somewhere else. The description is a
// patch.Field because it has three states: absent keeps the column, null
// clears it, a value replaces it.
UpdateDetails(ctx context.Context, id string, name, slug *string, isPublic *bool, description patch.Field[string]) error
// MoveToTrash marks a campaign deleted without removing anything; Undo is
// RestoreFromTrash. See trash_repository.go.
MoveToTrash(ctx context.Context, id, byUserID, byName string, at time.Time) error
RestoreFromTrash(ctx context.Context, id string) error
ListTrashed(ctx context.Context) ([]TrashedCampaign, error)
ListPurgeDue(ctx context.Context, cutoff time.Time, all bool) ([]string, error)
ClaimForPurge(ctx context.Context, id string, at, olderThan time.Time) (bool, error)
// PurgeTrashed is the only hard delete of a campaign: it removes a row
// that was trashed and claimed, and nothing else.
PurgeTrashed(ctx context.Context, id string) error
SlugExists(ctx context.Context, slug string) (bool, error)
CountAll(ctx context.Context) (int, error)
// Membership
AddMember(ctx context.Context, member *CampaignMember) error
RemoveMember(ctx context.Context, campaignID, userID string) error
FindMember(ctx context.Context, campaignID, userID string) (*CampaignMember, error)
ListMembers(ctx context.Context, campaignID string) ([]CampaignMember, error)
UpdateMemberRole(ctx context.Context, campaignID, userID string, role Role) error
UpdateMemberCharacter(ctx context.Context, campaignID, userID string, characterEntityID *string) error
FindOwnerMember(ctx context.Context, campaignID string) (*CampaignMember, error)
// order pinned; nil when they have none or are not a member.
GetMemberNavPins(ctx context.Context, campaignID, userID string) ([]string, error)
// empty list clears them. It never touches another member's row.
SetMemberNavPins(ctx context.Context, campaignID, userID string, pins []string) error
// GetMemberLookPicks returns a member's own look picks in one campaign,
// keyed by part. Whether a pick still counts is decided by the caller.
GetMemberLookPicks(ctx context.Context, campaignID, userID string) (map[string]string, error)
// SetMemberLookPick stores one pick; an empty value clears it. It only
// ever touches the row of the campaign and user given.
SetMemberLookPick(ctx context.Context, campaignID, userID, part, value string) error
// Ownership transfer
CreateTransfer(ctx context.Context, transfer *OwnershipTransfer) error
FindTransferByToken(ctx context.Context, token string) (*OwnershipTransfer, error)
FindTransferByCampaign(ctx context.Context, campaignID string) (*OwnershipTransfer, error)
DeleteTransfer(ctx context.Context, id string) error
// DeleteTransfersInvolving cancels every pending hand-over to or from the user.
DeleteTransfersInvolving(ctx context.Context, userID string) error
// ListOwnedByUser lists campaigns the user created or holds the owner
// role in, archived ones included.
ListOwnedByUser(ctx context.Context, userID string) ([]OwnedCampaign, error)
// ListMemberCampaignIDs lists every campaign the user is a member of,
// archived ones included.
ListMemberCampaignIDs(ctx context.Context, userID string) ([]string, error)
// ListOwnedMembershipIDs lists the campaigns where the user holds the
// owner role now. Unlike ListOwnedByUser it ignores who created the
// campaign, so someone who handed one over is not still its owner.
ListOwnedMembershipIDs(ctx context.Context, userID string) ([]string, error)
// UpdateBackdropPath updates only the backdrop_path column.
UpdateBackdropPath(ctx context.Context, campaignID string, path *string) error
// UpdateSettings updates only the settings JSON column.
UpdateSettings(ctx context.Context, campaignID, settingsJSON string) error
// UpdateSettingsKeys sets top-level settings keys to the given JSON
// values (nil removes the key) and leaves every other key as stored.
UpdateSettingsKeys(ctx context.Context, campaignID string, keys map[string]json.RawMessage) error
// UpdateSidebarConfig updates only the sidebar_config JSON column.
UpdateSidebarConfig(ctx context.Context, campaignID, configJSON string) error
// UpdateDashboardLayout updates only the dashboard_layout JSON column.
// Pass nil to revert to the hardcoded default dashboard.
UpdateDashboardLayout(ctx context.Context, campaignID string, layoutJSON *string) error
// UpdateOwnerDashboardLayout updates only the owner_dashboard_layout JSON column.
// Pass nil to revert to the hardcoded default owner dashboard.
UpdateOwnerDashboardLayout(ctx context.Context, campaignID string, layoutJSON *string) error
// TransferOwnership atomically transfers campaign ownership from one user
// to another within a database transaction.
TransferOwnership(ctx context.Context, campaignID, fromUserID, toUserID string) error
// OwnerPresence returns each listed campaign's owner and when they last
// used the site.
OwnerPresence(ctx context.Context, campaignIDs []string) (map[string]OwnerPresence, error)
// ForceTransferOwnership is used by admins to take ownership. Atomically
// demotes current owner to Scribe and sets the new owner.
ForceTransferOwnership(ctx context.Context, campaignID, newOwnerID string) error
// ArchiveCampaign sets the archived_at timestamp, making the campaign read-only.
ArchiveCampaign(ctx context.Context, campaignID string) error
// UnarchiveCampaign clears the archived_at timestamp, restoring write access.
UnarchiveCampaign(ctx context.Context, campaignID string) error
// SetJoinCode stores a shareable invite code for the campaign.
SetJoinCode(ctx context.Context, campaignID, code string) error
// ClearJoinCode removes the shareable invite code.
ClearJoinCode(ctx context.Context, campaignID string) error
// FindByJoinCode looks up a campaign by its shareable invite code.
FindByJoinCode(ctx context.Context, code string) (*Campaign, error)
}
CampaignRepository defines the data access contract for campaign operations. All SQL lives in the concrete implementation -- no SQL leaks out.
func NewCampaignRepository ¶
func NewCampaignRepository(db *sql.DB) CampaignRepository
NewCampaignRepository creates a new repository backed by the given DB pool.
type CampaignService ¶
type CampaignService interface {
// Campaign CRUD
Create(ctx context.Context, userID string, input CreateCampaignInput) (*Campaign, error)
GetByID(ctx context.Context, id string) (*Campaign, error)
GetBySlug(ctx context.Context, slug string) (*Campaign, error)
List(ctx context.Context, userID string, opts ListOptions) ([]Campaign, int, error)
ListAll(ctx context.Context, opts ListOptions) ([]Campaign, int, error)
SearchAll(ctx context.Context, opts AdminSearchOptions) ([]Campaign, error)
CountBySystem(ctx context.Context, query string) ([]SystemCount, error)
ListPublic(ctx context.Context, limit int) ([]Campaign, error)
Update(ctx context.Context, campaignID string, input UpdateCampaignInput) (*Campaign, error)
// UpdateDetails is the partial save behind the desk's name and public
// blanks: absent keys keep what is stored, including the description.
UpdateDetails(ctx context.Context, campaignID string, input UpdateCampaignDetailsInput) (*Campaign, error)
// MoveToTrash is what "delete campaign" means: the campaign disappears for
// everyone and waits in the site Trash (trash_repository.go). PurgeTrashed
// is the only real delete.
MoveToTrash(ctx context.Context, campaignID, byUserID string) error
RestoreFromTrash(ctx context.Context, campaignID string) error
ListTrashed(ctx context.Context) ([]TrashedCampaign, error)
ListPurgeDue(ctx context.Context, cutoff time.Time, all bool) ([]string, error)
PurgeTrashed(ctx context.Context, campaignID string, olderThan time.Time) (bool, error)
CountAll(ctx context.Context) (int, error)
// Account deletion
OwnedCampaigns(ctx context.Context, userID string) ([]OwnedCampaign, error)
LeaveAllForDeletedAccount(ctx context.Context, userID string) error
// Membership
GetMember(ctx context.Context, campaignID, userID string) (*CampaignMember, error)
RemoveMember(ctx context.Context, campaignID, userID string) error
// LeaveCampaign ends the user's own membership: not a removal, so the
// join link still works for them. The owner must hand over instead.
LeaveCampaign(ctx context.Context, campaignID, userID string) error
// OwnedMemberships lists the campaigns the user owns now.
OwnedMemberships(ctx context.Context, userID string) ([]string, error)
// ClaimedCharacters names the characters the user holds, by campaign.
ClaimedCharacters(ctx context.Context, userID string, campaignIDs []string) (map[string][]string, error)
// ListRemovedMembers returns the people the owner removed who have not
// come back; AllowRemovedMemberBack lets one use the join link again.
ListRemovedMembers(ctx context.Context, campaignID string) ([]MemberUser, error)
AllowRemovedMemberBack(ctx context.Context, campaignID, userID string) error
UpdateMemberRole(ctx context.Context, campaignID, userID string, role Role) error
// SetMemberAccess applies a People role-menu choice: player, scribe or
// codm (a Scribe with the DM-only grant).
SetMemberAccess(ctx context.Context, campaignID, userID, access string) error
UpdateMemberCharacter(ctx context.Context, campaignID, userID string, characterEntityID *string) error
ListMembers(ctx context.Context, campaignID string) ([]CampaignMember, error)
// Ownership transfer
InitiateTransfer(ctx context.Context, campaignID, ownerID, targetEmail string) (*OwnershipTransfer, error)
// Hand-over after the owner is away: the owner's setting, the admin
// list's status and the admin's hand-over.
SetHandoverAfter(ctx context.Context, campaignID string, months int) error
HandoverStatuses(ctx context.Context, list []Campaign) (map[string]HandoverStatus, error)
AdminHandOver(ctx context.Context, campaignID, toUserID string) (*HandoverStatus, error)
AcceptTransfer(ctx context.Context, token string, acceptingUserID string) error
CancelTransfer(ctx context.Context, campaignID string) error
GetPendingTransfer(ctx context.Context, campaignID string) (*OwnershipTransfer, error)
// Backdrop and branding
// UpdateBranding sets the campaign's custom brand name and logo path.
UpdateBranding(ctx context.Context, campaignID, brandName, brandLogo string) error
UpdateDmGrants(ctx context.Context, campaignID string, userIDs []string) error
// IsUserDmGranted reports whether the user appears in the campaign's
// DmGrantIDs setting. Used by the WS hub to gate RequiresDM messages
// to non-Owner members the Owner has trusted with dm_only visibility.
IsUserDmGranted(ctx context.Context, campaignID, userID string) (bool, error)
// SetFoundryModulePin pins the campaign to a specific Foundry
// module version (or clears the pin when version is "").
SetFoundryModulePin(ctx context.Context, campaignID, version string) error
// GetFoundryModulePin returns the campaign's current Foundry
// module pin, or "" if none.
GetFoundryModulePin(ctx context.Context, campaignID string) (string, error)
// SetFoundryModulePinMode writes the campaign's pin_mode setting
// (one of foundry_vtt.PinMode* constants). Validation is the
// caller's responsibility, via foundry_vtt.IsValidPinMode.
SetFoundryModulePinMode(ctx context.Context, campaignID, mode string) error
// GetFoundryModulePinMode returns the campaign's pin_mode, or
// empty string if not yet set.
GetFoundryModulePinMode(ctx context.Context, campaignID string) (string, error)
// CampaignExistsByID is a thin existence check for adapters that
// don't need the full Campaign struct.
CampaignExistsByID(ctx context.Context, campaignID string) (bool, error)
// UpdateWelcomeMessage sets the campaign's MOTD banner message.
UpdateWelcomeMessage(ctx context.Context, campaignID, message string) error
// SaveAppearance writes one Save from the Customize page, every
// setting at once.
SaveAppearance(ctx context.Context, campaignID string, in AppearanceInput) error
// AdoptMaterialPageLook moves a campaign that never chose a page look to
// the Material one (Annals) and reports whether it changed anything.
AdoptMaterialPageLook(ctx context.Context, campaignID string) (bool, error)
// GetEventTierDefinitions returns the campaign's event tier vocabulary.
// Returns the platform default trio (major/standard/detail) when the
// campaign has no custom tier defs set — matches the empty-means-
// default semantic used for AccentColor / FontFamily / etc.
GetEventTierDefinitions(ctx context.Context, campaignID string) ([]TierDefinition, error)
// SetEventTierDefinitions replaces the campaign's tier vocabulary.
// Validates exactly-one-default, non-empty array, unique slugs,
// hex color format, prominence range.
SetEventTierDefinitions(ctx context.Context, campaignID string, defs []TierDefinition) error
// UpdateDefaultVisibility sets the default visibility for new entities.
UpdateDefaultVisibility(ctx context.Context, campaignID, visibility string) error
// Sidebar configuration
UpdateSidebarConfig(ctx context.Context, campaignID string, req UpdateSidebarConfigRequest) error
GetSidebarConfig(ctx context.Context, campaignID string) (*SidebarConfig, error)
// SetCategoryMenuVisibility shows or hides one category in the players'
// sidebar menu, leaving the rest of the sidebar config as stored.
SetCategoryMenuVisibility(ctx context.Context, campaignID string, typeID int, visible bool) error
// within its own section; see the function of the same name.
OrderNavCategories(ctx context.Context, campaignID string, apps []NavApp, cats []NavCategory, order []int) error
// EnsureSidebarItems is the one-time, idempotent boot reconciler that
// converts campaigns still on the legacy sidebar model onto the unified
// items model. Returns the number of campaigns converted.
EnsureSidebarItems(ctx context.Context) (int, error)
NavPins(ctx context.Context, campaignID, userID string) ([]string, error)
// returns what was stored. Owners are refused (they pin for everyone in
// the sidebar editor), and so is any row the member's sidebar does not show.
UpdateNavPins(ctx context.Context, cc *CampaignContext, userID string, pins []string) ([]string, error)
// MemberLookPicks returns the viewer's own look picks that still count
// under the campaign's current "who can change" settings, keyed by part.
// It reads nothing for a viewer who may pick nothing.
MemberLookPicks(ctx context.Context, cc *CampaignContext, userID string) (map[string]string, error)
// SetMemberLookPick stores (or, with an empty value, clears) the calling
// member's own pick for one part, after checking they may pick it now and
// the value is one of its choices.
SetMemberLookPick(ctx context.Context, cc *CampaignContext, userID, part, value string) error
// Dashboard layout
UpdateDashboardLayout(ctx context.Context, campaignID string, layout *DashboardLayout) error
UpdateDashboardLayoutRaw(ctx context.Context, campaignID string, layoutJSON *string) error
GetDashboardLayout(ctx context.Context, campaignID string) (*DashboardLayout, error)
ResetDashboardLayout(ctx context.Context, campaignID string) error
// Owner dashboard layout
UpdateOwnerDashboardLayout(ctx context.Context, campaignID string, layout *DashboardLayout) error
GetOwnerDashboardLayout(ctx context.Context, campaignID string) (*DashboardLayout, error)
ResetOwnerDashboardLayout(ctx context.Context, campaignID string) error
// Admin operations
ForceTransferOwnership(ctx context.Context, campaignID, newOwnerID string) error
AdminAddMember(ctx context.Context, campaignID, userID string, role Role) error
// Archive
ArchiveCampaign(ctx context.Context, campaignID string) error
UnarchiveCampaign(ctx context.Context, campaignID string) error
// Shareable invite link
GenerateJoinCode(ctx context.Context, campaignID string) (string, error)
RevokeJoinCode(ctx context.Context, campaignID string) error
// JoinByCode makes the user a player of the campaign the code opens and
// returns that campaign. joined is false when they were already a member,
// so following the link twice lands them in the campaign, not on an error.
JoinByCode(ctx context.Context, code, userID string) (campaign *Campaign, joined bool, err error)
// Game system
UpdateSystemID(ctx context.Context, campaignID, systemID string) error
// KeepSetupStep records that the owner passed on a setup step ("game" or
// "look") instead of doing it, so the setup line counts it as done.
KeepSetupStep(ctx context.Context, campaignID, step string) error
// Lifecycle hooks — set after construction to avoid circular initialization.
SetContentTemplateSeeder(seeder ContentTemplateSeeder)
SetWorldbuildingPromptSeeder(seeder WorldbuildingPromptSeeder)
SetLayoutPresetSeeder(seeder LayoutPresetSeeder)
// SetCharacterListSeeder sets what records a new campaign's character and
// NPC page types. Late-bound and nil-safe.
SetCharacterListSeeder(seeder CharacterListSeeder)
// SetFeatureEnabler sets what turns on the usual set of features for a
// new campaign. Late-bound and nil-safe: without it a campaign starts
// with every feature off.
SetFeatureEnabler(enabler FeatureEnabler)
// UpdateCharacterLists stores the page types the campaign lists as
// characters and as NPCs. Callers validate the IDs; this only persists.
UpdateCharacterLists(ctx context.Context, campaignID string, characterTypeIDs, npcTypeIDs []int) error
// UpdateHeroChanges stores when players may change their own hero's
// picks; nil means any time.
UpdateHeroChanges(ctx context.Context, campaignID string, rule *HeroChangeRule) error
// ClearCharacterLists removes both lists, so the campaign is seeded from
// its own page types the next time they are read.
ClearCharacterLists(ctx context.Context, campaignID string) error
SetMediaCleaner(cleaner MediaCleaner)
SetHookDispatcher(dispatcher CampaignHookDispatcher)
// SetConnectionRevoker injects the hub's revocation surface. Late-bound
// and nil-safe: a nil revoker only skips the live-drop, since a
// reconnect re-resolves role/grant from current settings anyway.
SetConnectionRevoker(cr ConnectionRevoker)
// UpdateNavPins checks pins against. Until it is set, pins are refused.
SetNavSectionsSource(src NavSectionsSource)
// SetSiteLookSource injects the site-wide look, so a new campaign can
// start with it. Late-bound and nil-safe: without it new campaigns start
// as Classic.
SetSiteLookSource(src SiteLookSource)
}
CampaignService handles business logic for campaign operations. It owns slug generation, membership rules, and ownership transfers.
func NewCampaignService ¶
func NewCampaignService(repo CampaignRepository, users UserFinder, mail MailService, seeder EntityTypeSeeder, baseURL string) CampaignService
NewCampaignService creates a new campaign service with the given dependencies. The mail and seeder parameters may be nil if the corresponding plugins are not yet wired.
type CampaignSettings ¶
type CampaignSettings struct {
AccentColor string `json:"accent_color,omitempty"` // Hex color, e.g. "#6366f1". "Site accent": overall feel — nav/chrome, links, selection, today ring.
AccentSurface1 string `json:"accent_surface_1,omitempty"` // Legacy surface-pair accent A (primary) for themed content surfaces. Empty = inherit AccentColor. Kept for back-compat; AccentApp takes precedence where both are consumed.
AccentSurface2 string `json:"accent_surface_2,omitempty"` // Legacy surface-pair accent B (secondary). Empty = inherit AccentColor. Kept for back-compat as the optional 4th slot, defaulting to AccentApp when unused.
AccentAction string `json:"accent_action,omitempty"` // "Action highlight" slot: primary buttons, hover/press states, FABs. Empty = inherit AccentColor.
AccentApp string `json:"accent_app,omitempty"` // "App accent" slot: per-app identity — character pages, calendar app, other apps. Empty = inherit AccentSurface1, then AccentColor.
DmGrantIDs []string `json:"dm_grant_ids,omitempty"` // User IDs granted dm_only visibility.
RemovedMemberIDs []string `json:"removed_member_ids,omitempty"` // People the owner removed; the join link turns them away.
BrandName string `json:"brand_name,omitempty"` // Custom sidebar brand name (replaces campaign name).
BrandLogo string `json:"brand_logo,omitempty"` // Media path for brand logo image.
TopbarStyle *TopbarStyle `json:"topbar_style,omitempty"` // Topbar visual customization.
TopbarContent *TopbarContent `json:"topbar_content,omitempty"` // Customizable topbar center content.
FontFamily string `json:"font_family,omitempty"` // Campaign body font: "serif", "sans-serif", "monospace", "georgia", "merriweather".
WelcomeMessage string `json:"welcome_message,omitempty"` // MOTD banner shown on campaign dashboard (max 500 chars).
Appearance *Appearance `json:"appearance,omitempty"` // Customize page style choices (look, menu highlight, type, buttons, motion); nil = Classic.
DefaultVisibility string `json:"default_visibility,omitempty"` // Default visibility for new entities: "", "dm_only", "private".
SystemID string `json:"system_id,omitempty"` // Game system ID (e.g. "dnd5e", "drawsteel") or "custom:<url>".
SetupKept []string `json:"setup_kept,omitempty"` // Setup steps the owner passed on instead of doing ("game", "look"); the others are worked out from what exists.
// HandoverAfterMonths is the owner's "If you're away" choice: how long
// they can be unseen before a site admin may hand the campaign to another
// member. 0 (the default) means never.
HandoverAfterMonths int `json:"handover_after_months,omitempty"`
// CharacterTypeIDs and NPCTypeIDs are the page types the owner chose to
// show as The Party and as NPCs. Pointers because "never chosen" (nil) and
// "chose none" (empty) differ: the one-time reconciler fills only nil.
CharacterTypeIDs *[]int `json:"character_type_ids,omitempty"`
NPCTypeIDs *[]int `json:"npc_type_ids,omitempty"`
// FoundryModulePin is the version string the campaign is pinned
// to for the Chronicle-served Foundry module catalog (e.g. "0.1.5").
// Empty = follow latest available (manifest endpoint resolves to
// LatestAvailable).
FoundryModulePin string `json:"foundry_module_pin,omitempty"`
// FoundryModulePinMode controls how AutoPinOnInstall treats the
// campaign when an admin installs a new module version. Valid
// values are the foundry_vtt.PinMode* constants:
// "preserve" → on install, campaign's pin is set to the previous
// version (state preserved).
// "promote" → on install, campaign's pin is set to the new
// version (auto-bump).
// "pinned" → explicit version pin; install doesn't touch.
// "approve_first" → on install, the campaign keeps its pin and the
// new version is held until the owner approves it.
// "automatic" → serves like "promote", but the owner chose it, so
// the ask-first default never replaces it.
// Empty string means "not yet set"; AutoPinOnInstall treats it the
// same as "promote".
FoundryModulePinMode string `json:"foundry_module_pin_mode,omitempty"`
// EventTierDefinitions holds the per-campaign event tier vocabulary.
// Empty/nil at read time returns the platform default trio
// (major / standard / detail) via GetEventTierDefinitions.
EventTierDefinitions []TierDefinition `json:"event_tier_definitions,omitempty"`
// HeroChanges is when players may change their own hero's picks. Nil
// means any time, as before the Director chose.
HeroChanges *HeroChangeRule `json:"hero_changes,omitempty"`
}
CampaignSettings holds campaign-level configuration stored as JSON in the campaigns.settings column. Accent color, display preferences, etc.
func (CampaignSettings) DefaultsToPrivate ¶
func (s CampaignSettings) DefaultsToPrivate() bool
DefaultsToPrivate reports whether this campaign's DefaultVisibility setting means "new content starts hidden from players".
func (CampaignSettings) ResolveNewEntityPrivacy ¶
func (s CampaignSettings) ResolveNewEntityPrivacy(requested patch.Field[bool]) bool
ResolveNewEntityPrivacy decides is_private for a newly created entity, merging the caller's request over the campaign's DefaultVisibility:
absent -> campaign default decides explicit false -> public, even under a private default explicit true -> private
requested is patch.Field[bool], not a plain bool, because a bool can't distinguish "omitted" from "sent false" — collapsing them made new entities public under a DM-only default. This is the only implementation; don't re-derive the rule inline.
An explicit JSON null is treated as absent (create has no stored value to clear), matching patch.Field.Val's rule that null on a NOT NULL column preserves rather than zeroes.
type CampaignTab ¶
type CampaignTab struct {
Campaign *Campaign
// Name and Description are typed into fields that save when left.
Name, Description *DeskBlank
// Access and Pages are two-way choices that save when pressed.
Access, Pages *DeskBlank
// Preview opens Home as a player or a guest sees it.
Preview DeskLine
Look LookSummary
// CustomizerHref opens the Customizer at its front page and PicturesHref
// at Look, where the emblem and the cover are chosen; Customize are the
// other Customize areas and the header brush, one row each.
CustomizerHref, PicturesHref string
Customize []DeskLine
// Card is what the campaign's card on My campaigns shows.
Card CampaignTabCard
}
CampaignTab is the Campaign tab's page.
type CampaignTabCard ¶
type CampaignTabCard struct {
Name, Description string
// Cover and Emblem are media paths; empty draws them from the colour and
// the name's first letter, as the banner does.
Cover, Emblem string
Public bool
Faces []DeskFace
}
CampaignTabCard is the campaign as its card shows it to people.
type CharacterListSeeder ¶
CharacterListSeeder records which page types a new campaign lists as characters and NPCs. Implemented by the entities plugin's character list service, and run after the entity types exist.
type CharacterReleaser ¶
type CharacterReleaser interface {
// ReleaseCharacters clears the user's claim on every character in the
// campaign and returns the names of the live ones, so the owner can be
// told which are free.
ReleaseCharacters(ctx context.Context, campaignID, userID string) ([]string, error)
// ClaimedCharacters names the live characters the user holds, by
// campaign, so the Leave box can say who goes back to the table.
ClaimedCharacters(ctx context.Context, userID string, campaignIDs []string) (map[string][]string, error)
}
CharacterReleaser hands a leaver's claimed characters back to the table ("Free to pick"). Campaigns can't reach into the entities plugin's repository, so the app wires this narrow door.
type ConnectionRevoker ¶
type ConnectionRevoker interface {
RevokeUser(campaignID, userID string)
RevokeCampaign(campaignID string)
}
ConnectionRevoker is the narrow hub view this plugin needs: drop a user's sockets when their access is lowered, or a whole campaign's once it's deleted. Declared locally, not imported.
type ConnectionsTab ¶
type ConnectionsTab struct {
// Foundry is the Foundry link's state; nil while Foundry sync is off,
// when FoundryOffHref leads to where it is switched on.
Foundry *DeskGoTile
FoundryOffHref string
AI DeskGoTile
// Keys is how many API keys are in use; nil when it could not be read.
Keys *DeskKeysFacts
// BaseURL is the server's address, for tools that call the API.
BaseURL string
}
ConnectionsTab is the Connections tab's page.
type ContentPacksCardRenderer ¶
type ContentPacksCardRenderer interface {
RenderCampaignExtensionList(ctx context.Context, cc *CampaignContext) (templ.Component, error)
}
ContentPacksCardRenderer is the inversion of the campaigns ↔ extensions import direction: the `extensions` plugin already imports `campaigns` (for `GetCampaignContext`), so to embed the per-campaign Content Packs list inside the Extensions hub we let the extensions plugin register a renderer with the campaigns Handler at startup. Mirrors the established interface-injection pattern (`AddonLister`, `MediaUploader`, `SMTPChecker`, ...).
Returning a `templ.Component` rather than rendering directly keeps the extensions plugin oblivious to the hub's chrome — the hub embeds the returned component inside its own card wrapper.
type ContentTemplateSeeder ¶
ContentTemplateSeeder seeds default content templates when a campaign is created. Implemented by the entities plugin's ContentTemplateService.
type CreateCampaignInput ¶
type CreateCampaignInput struct {
Name string
Description string
Genre string // Optional genre preset for entity type seeding.
// SkipEntityTypeSeed leaves the campaign with no default categories.
// Import sets it when the file carries its own, which would otherwise
// arrive as a second copy of every default ("Character", "Character 2").
SkipEntityTypeSeed bool
// SkipDefaultFeatures leaves every feature off. Import sets it: a
// restored campaign carries its own switches, and the usual set would
// turn on features the original had off.
SkipDefaultFeatures bool
}
CreateCampaignInput is the validated input for creating a campaign.
type CreateCampaignRequest ¶
type CreateCampaignRequest struct {
Name string `json:"name" form:"name"`
Description string `json:"description" form:"description"`
Genre string `json:"genre" form:"genre"`
}
CreateCampaignRequest holds the data submitted by the campaign creation form.
type CreateInviteInput ¶
CreateInviteInput holds the data needed to create a new campaign invite.
type CustomizeArea ¶
type CustomizeArea struct {
ID string `json:"id"`
Label string `json:"label"`
Icon string `json:"icon"`
Href string `json:"href"`
// Section is the draft section this area edits, so its tab can mark
// the areas holding unsaved changes. Empty for areas that save by
// themselves.
Section string `json:"section,omitempty"`
// Parts are what the tab's drawer lists: the Look's rooms, every
// category with its kinds, each home. Empty for an area with none.
Parts []CustomizePart `json:"-"`
// Part names the part open now, shown after the tab's label.
Part string `json:"-"`
// Blurb is what the area holds, for its Overview card, and Finds are the
// named things inside it for Find. Both come from a plugin's tab.
Blurb string `json:"-"`
Finds []CustomizeFind `json:"-"`
}
CustomizeArea is one part of Customize as Find and the save bar know it.
type CustomizeCategory ¶
type CustomizeCategory struct {
ID int `json:"id"`
Slug string `json:"slug"`
Name string `json:"name"`
NamePlural string `json:"namePlural"`
Icon string `json:"icon"`
Color string `json:"color"`
ParentID *int `json:"parentId,omitempty"`
Claimable bool `json:"claimable"`
// Pages counts live pages and Trashed those waiting in the Trash; a
// category with either cannot be deleted.
Pages int `json:"pages"`
Trashed int `json:"trashed"`
IsDefault bool `json:"isDefault"`
// DMOnly marks the Adventures category, which only the DM team sees.
DMOnly bool `json:"dmOnly"`
// Fields counts the category's fields, HomeLayout says its category home
// has an arrangement of its own, and Sample names one real page; the
// Customize wall words and draws the category from them.
Fields int `json:"fields"`
HomeLayout bool `json:"homeLayout"`
Sample string `json:"sample,omitempty"`
}
CustomizeCategory is one category as the Customize page lists it: the fields the owner can edit plus the counts that decide whether it can be deleted. Claimable is the effective value, after the heuristics that apply when the owner never chose.
type CustomizeCategoryLister ¶
type CustomizeCategoryLister interface {
ListCustomizeCategories(ctx context.Context, campaignID string) ([]CustomizeCategory, error)
}
CustomizeCategoryLister lists a campaign's categories for the Customize page. It is an interface so the campaigns plugin never imports entities.
type CustomizeCrumb ¶
CustomizeCrumb is one step in the area header's trail.
type CustomizeDraft ¶
type CustomizeDraft struct {
// Version counts the writes to this draft; a writer must echo the version
// it read so two tabs cannot overwrite each other.
Version int
Draft json.RawMessage
UpdatedAt time.Time
}
CustomizeDraft is the owner's unsaved Customize work for one campaign: a JSON object of named sections, each owned by the code that applies it.
type CustomizeDraftRepository ¶
type CustomizeDraftRepository interface {
// Get returns the draft, or nil, nil when there is none.
Get(ctx context.Context, campaignID, userID string) (*CustomizeDraft, error)
// Insert creates the first version of a draft. It reports false, nil
// when a row already exists, which is how a second tab's "no draft yet"
// write loses the race.
Insert(ctx context.Context, campaignID, userID string, draft []byte) (bool, error)
// Update replaces the draft and bumps its version, only while the stored
// version is still the one given. It reports false, nil on a mismatch.
Update(ctx context.Context, campaignID, userID string, version int, draft []byte) (bool, error)
// Delete removes the draft while its stored version matches; version 0
// removes it whatever its version. It reports whether a row was removed.
Delete(ctx context.Context, campaignID, userID string, version int) (bool, error)
}
CustomizeDraftRepository stores the owner's unsaved Customize work, one row per owner per campaign. Every write that changes an existing row is guarded by its version, so a stale tab can never overwrite newer work.
func NewCustomizeDraftRepository ¶
func NewCustomizeDraftRepository(db *sql.DB) CustomizeDraftRepository
NewCustomizeDraftRepository returns the MariaDB draft store.
type CustomizeDraftService ¶
type CustomizeDraftService interface {
// Get returns the owner's draft, or nil, nil when there is none.
Get(ctx context.Context, campaignID, userID string) (*CustomizeDraft, error)
// Save stores a draft. version is the one the caller last saw; 0 means
// "I believe there is no draft". A stale version is a Conflict. An empty
// object removes the draft and returns version 0.
Save(ctx context.Context, campaignID, userID string, version int, draft json.RawMessage, allowedKeys []string) (int, error)
// Discard removes the draft. version 0 removes it whatever its version.
Discard(ctx context.Context, campaignID, userID string, version int) error
}
CustomizeDraftService keeps the Customize draft on the server until the owner presses Save or Discard. It is separate from CampaignService because it knows nothing about what a section means, only how to store one safely.
func NewCustomizeDraftService ¶
func NewCustomizeDraftService(repo CustomizeDraftRepository) CustomizeDraftService
NewCustomizeDraftService creates the draft service.
type CustomizeFind ¶
type CustomizeFind struct {
Label, Words string
}
CustomizeFind is one thing inside a contributed tab that Find should know: the name shown, and other words someone might type for it.
type CustomizePart ¶
type CustomizePart struct {
Label string
Href string
// Key names a Look room, so the Look editor can mark the one open.
Key string
Color string // A category's colour; empty for other parts.
Pages int // A category's live pages.
// Kind is a sub-category, drawn under its parent.
Kind bool
// Quiet is a line about the area rather than one part of it ("All
// categories", "New category").
Quiet bool
Current bool
}
CustomizePart is one line in a tab's drawer.
type CustomizeSection ¶
type CustomizeSection struct {
// Key names the section in the draft: ^[a-z][a-z0-9_-]{0,31}$.
Key string
// Apply applies raw and returns what is still unapplied (nil when all of
// it applied). On error, remaining is what to keep in the draft; nil
// means keep raw unchanged.
Apply func(ctx context.Context, cc *CampaignContext, userID string, raw json.RawMessage) (remaining json.RawMessage, err error)
}
CustomizeSection is one named part of the Customize draft and the code that applies it.
A section's value may carry client-only keys that start with "_" (for example "_changes", the labels the page shows in its save bar). Apply must ignore keys it does not know, underscore ones included.
type CustomizeSummary ¶
type CustomizeSummary struct {
Text, Sub string
}
CustomizeSummary is a tab's "what is chosen now": a figure and an optional muted second part ("Jewelled, onyx" and "players pick their own").
type CustomizeTab ¶
type CustomizeTab struct {
ID string
Label string
Icon string
SortOrder int
Content templ.Component
Summary func(ctx context.Context) CustomizeSummary
Addon string
Paths []string
Here string
Blurb string
Finds []CustomizeFind
Section string
}
CustomizeTab is the declarative description of one plugin-contributed tab on the Customize page.
- ID: stable slug used as the Alpine tab key; URL-safe and constant.
- Label/Icon: button text / FontAwesome classes.
- SortOrder: order among contributed tabs (they all render after the built-in Layouts / Content Templates / Appearance tabs).
- Content: the tab body; the factory builds it per request so it can read live state for cc.Campaign.
- Summary: optional. What is chosen now, in a few words ("Atlas frame"), for the tab's row in the Customize block of Campaign settings and its card on the Overview. The plugin reads its own storage here, so the campaigns plugin never reads another plugin's tables. Nil shows the tab's name alone.
- Addon: optional. The add-on the tab belongs to; while it is off for the campaign the Customize block and the header's brush leave the tab out.
- Paths: optional. Campaign-relative path prefixes of the plugin's own pages ("/maps"); on them the header's brush offers this tab first.
- Here: the words of that brush row ("The frame around maps"); empty falls back to the tab's label.
- Blurb: optional. What is inside the tab, for its card on the Overview when it has no summary to show ("The dice everyone rolls, ...").
- Finds: optional. The named things inside the tab, so Find can open the tab by what it holds and not only by its name.
- Section: optional. The draft section the tab's changes live in. The tab then saves with the Customize save bar, so its rail entry shows the unsaved-changes dot, the bar names it when its section carries no labels of its own, and its body fills the page instead of sitting under a "saves by itself" note. Empty for a tab that saves by itself.
The Customize page is Owner-only, so a contributed tab needs no role of its own: every viewer of it is already an Owner.
type DashboardBlock ¶
type DashboardBlock struct {
ID string `json:"id"`
Type string `json:"type"`
Config map[string]any `json:"config,omitempty"`
}
DashboardBlock is a single content block within a column. The Type field determines which Templ component renders it. Config holds type-specific options (e.g. limit, entity_type_id).
func DashboardTileBlock ¶
func DashboardTileBlock(t tilegrid.Tile) DashboardBlock
DashboardTileBlock turns a tile into the block the dashboard block switch draws, so a tile and a column block share one renderer.
type DashboardColumn ¶
type DashboardColumn struct {
ID string `json:"id"`
Width int `json:"width"` // 1-12 grid units.
Blocks []DashboardBlock `json:"blocks"`
}
DashboardColumn is a column within a row. Width is 1-12 (12-column grid).
type DashboardLayout ¶
type DashboardLayout struct {
Rows []DashboardRow `json:"rows"`
}
DashboardLayout defines a configurable dashboard using a row/column/block grid system inspired by Kanka. Stored as JSON in the dashboard_layout column of campaigns (and entity_types for category dashboards). NULL means "use the hardcoded default dashboard".
func DefaultDashboardLayout ¶
func DefaultDashboardLayout() *DashboardLayout
DefaultDashboardLayout returns the synthesized dashboard layout used when a campaign has no custom layout saved. Single source of truth for both the live page render and the customization editor — operators see the same structure they're about to edit. Each row is full-width (12-grid) so existing block components render at their natural width.
func DefaultGuestDashboardLayout ¶
func DefaultGuestDashboardLayout() *DashboardLayout
DefaultGuestDashboardLayout is the home a visitor sees until the owner arranges one for guests: the about, the pages open to them and the latest of those. It holds no block a visitor can't use.
func (*DashboardLayout) ComingUpRepeats ¶
func (l *DashboardLayout) ComingUpRepeats() map[[3]int]bool
ComingUpRepeats marks, by row, column and block index, every Coming up block after the first. The retired session tracker draws the same card, so a layout holding both would otherwise show it twice.
type DashboardRow ¶
type DashboardRow struct {
ID string `json:"id"`
Kind string `json:"kind,omitempty"`
Columns []DashboardColumn `json:"columns"`
Tiles []tilegrid.Tile `json:"tiles,omitempty"`
}
DashboardRow is a horizontal row in the dashboard grid. An ordinary row (Kind empty) holds columns of blocks. A tile section (Kind "tiles") holds Tiles on a 4-column grid instead and has no columns; see internal/tilegrid.
type DataTab ¶
type DataTab struct {
// Storage is what the picture store holds; nil while Media is off.
Storage *DeskGoTile
Trash DeskGoTile
// Sections are the other plugins' parts of this tab (Import), each with
// its own heading and anchor, in their registered order.
Sections []SettingsTab
// Transfer leads to where ownership moves, on People.
Transfer string
}
DataTab is the Data tab's page.
type DeskAIFacts ¶
type DeskAIFacts struct {
State DeskAIState
Client string // what the AI app called itself; empty when it never said
CanAsk bool // may ask for changes; false is "only look"
// Waiting is how many of its requests wait for the owner's answer.
Waiting int
}
DeskAIFacts is the owner's AI connection and what it has waiting.
type DeskAIState ¶
type DeskAIState string
DeskAIState is where the owner's AI connection stands.
const ( DeskAINone DeskAIState = "none" DeskAIConnected DeskAIState = "connected" DeskAIPaused DeskAIState = "paused" DeskAIEnded DeskAIState = "ended" )
The states of the owner's AI connection.
type DeskBlank ¶
type DeskBlank struct {
Kind DeskBlankKind
// ID is stable for tests and for the page's own scripts.
ID string
// Label names what the blank sets, for the screen reader and the menu.
Label string
// Value is the stored value; Shown is the words on screen for it.
Value, Shown string
// Empty draws Shown (the word "None") in muted ink: there is no value.
Empty bool
Options []DeskOption
// URL, Method and Field say where a change goes: a JSON body of
// {Field: value} to URL. Bool sends the value as true or false instead
// of text, for the settings that are flags.
URL, Method, Field string
Bool bool
// Max is the longest text the route accepts; zero for a choice.
Max int
// Off is why the blank cannot be changed right now ("" when it can): an
// archived campaign is read-only, and its writes are refused.
Off string
}
DeskBlank is a row's value that saves the moment it is changed, through the existing route for that setting.
type DeskBlankKind ¶
type DeskBlankKind string
DeskBlankKind is how a blank is changed.
const ( DeskBlankChoice DeskBlankKind = "choice" DeskBlankName DeskBlankKind = "name" DeskBlankText DeskBlankKind = "text" )
The ways a blank changes: a small menu of choices, typing a one-line name, or typing a longer text in a field of a few lines.
type DeskBoard ¶
type DeskBoard struct {
// Needs is what waits on the owner; the tile is drawn only when it holds
// something.
Needs []NeedsYouItem
// Access and Pages flip between their two states where they stand.
Access, Pages DeskFlip
People DeskPeopleTile
System DeskGoTile
Edits DeskGoTile
Features DeskFeaturesTile
Look DeskLookTile
Foundry *DeskGoTile
AI DeskGoTile
Storage DeskGoTile
Trash DeskGoTile
}
DeskBoard is the Overview: one field per tile, drawn in a fixed order. A tile that belongs to an add-on (Foundry) is nil while its add-on is off.
type DeskChangesFacts ¶
type DeskChangesFacts struct {
Changes int // changes recorded in the last 7 days
Players int // how many different players made them
}
DeskChangesFacts counts what players changed in the last week.
type DeskEntriesFacts ¶
type DeskEntriesFacts struct {
Entries int // accepted entries, not drafts
Drafts int // drafts a player has handed in
Asks int // Ask-first picks a player is waiting on
}
DeskEntriesFacts counts the campaign's own rules entries and what waits on a Director in those lists.
func (DeskEntriesFacts) Waiting ¶
func (f DeskEntriesFacts) Waiting() int
Waiting is everything in the lists that waits for a Director.
type DeskFace ¶
type DeskFace struct {
Name, Role string
// Avatar is the person's picture, a media path; empty draws their initial.
Avatar string
// Hue picks one of a few tints for a face with no picture, from the
// person's id, so a face keeps its tint from visit to visit.
Hue int
}
DeskFace is one person on the People tile.
type DeskFacts ¶
type DeskFacts struct {
Changes *DeskChangesFacts
Media *DeskMediaFacts
Foundry *DeskFoundryFacts
AI *DeskAIFacts
Trash *DeskTrashFacts
Keys *DeskKeysFacts
Entries *DeskEntriesFacts
}
DeskFacts is the bag of numbers providers fill. Each pointer belongs to one slot; nil means the line has no numbers this time.
type DeskFeaturesTile ¶
type DeskFeaturesTile struct {
// Count is "12 of 15 on"; empty when the add-ons could not be read.
Count string
Chips []DeskChip
Href string
// Off is why the chips cannot be pressed now (an archived campaign).
Off string
}
DeskFeaturesTile is every installed feature as a chip that switches it on or off where it stands, through the add-ons store's own toggle route.
type DeskFigure ¶
type DeskFigure struct {
// State is the dot before the figures: "", "ok" or "warn".
State string
Parts []string
}
DeskFigure is what a Manage tool page draws beside its title: muted figures joined by a middle dot, with an optional state dot before them. It is built beside the desk's rows from the same facts, so the page and the row cannot disagree. The zero value draws nothing.
func (DeskFigure) Empty ¶
func (f DeskFigure) Empty() bool
Empty reports whether there is nothing to draw.
func (DeskFigure) Text ¶
func (f DeskFigure) Text() string
Text is the figures joined with a middle dot.
type DeskFlip ¶
DeskFlip is a tile that flips a two-way setting and saves at once. It wraps the same blank the Campaign tab's choice draws, so both save through the same route with the same words. The first option is the resting state and the second the pressed one (Private and Public, Hidden and Shown).
func (DeskFlip) Option ¶
func (f DeskFlip) Option(i int) DeskOption
Option is the flip's option at i (0 or 1); the zero option when it has none.
type DeskFoundryFacts ¶
type DeskFoundryFacts struct {
Connection FoundryConnection
}
DeskFoundryFacts is the campaign's Foundry link as the connector reports it.
type DeskGoTile ¶
type DeskGoTile struct {
Label string
Value DeskValue
// Hint is the muted line under the figure; empty draws none.
Hint string
// Mono is a short mark drawn before the figure (the game system's
// initials); empty draws none.
Mono string
Href string
}
DeskGoTile is a tile that shows a figure and leads to its tab or page. The figure is a DeskValue so its state dot and its "Open" fallback come from the same builders as the pages' figures.
type DeskInputs ¶
type DeskInputs struct {
Campaign *Campaign
Members []CampaignMember
// SystemID is the campaign's current game system id; empty when none.
SystemID string
// SystemName is the chosen game system's name; empty when none is chosen
// or the system list does not name it.
SystemName string
// FeaturesOn and FeaturesTotal count the installed features; both zero
// when the add-on list could not be read.
FeaturesOn, FeaturesTotal int
// Features is the add-on list itself, for the board's chips; nil when it
// could not be read.
Features []PluginHubAddon
// Addons says which add-ons are on for this campaign: the Foundry tile
// and the storage figures exist only while theirs is.
Addons map[string]bool
// Invited is how many invitations still wait for an answer; InvitedRead
// says they could be counted, so an unread count is never drawn as zero.
Invited int
InvitedRead bool
// GMTerm is the campaign's own word for its game master, for the words a
// service builds (the template reads it from its context instead).
GMTerm string
// Look is the saved look in words, for the Look tile and the Campaign
// tab's Look row.
Look LookSummary
// Categories are the campaign's categories; CategoriesRead says they
// could be read, so an unread list is never drawn as none.
Categories []CustomizeCategory
CategoriesRead bool
// Tabs are the areas other plugins add to Customize, in Customize's
// order, with their add-on on, each with what it says is chosen now.
Tabs []DeskTab
// BrushHidden is the viewer's own choice to hide the header's Customize
// brush in this campaign. It is the person's, not the campaign's.
BrushHidden bool
}
DeskInputs is everything campaigns itself knows that the desk draws: the campaign, its members and the game and features read through the existing listers. Gathered by the handler so the service stays free of Echo.
type DeskKeysFacts ¶
type DeskKeysFacts struct {
Count int
}
DeskKeysFacts is how many API keys the campaign has in use.
type DeskLine ¶
type DeskLine struct {
ID string
// Name is what the row is called, in a few words.
Name string
// Values stand beside the name: one value, or several quiet words.
Values []DeskValue
// Why is the reason a value of this row can be off, drawn under the row
// while one is. A blank carries its own reason (an archived campaign), so
// this is only for a row whose off state can change on the page.
Why string
}
DeskLine is one setting: its name, and the values that stand beside it.
type DeskLookTile ¶
type DeskLookTile struct {
Look LookSummary
Href string
}
DeskLookTile is the saved look in words, opening the Customizer.
type DeskMediaFacts ¶
DeskMediaFacts is what the campaign's picture store holds.
type DeskOption ¶
type DeskOption struct {
Value string `json:"v"`
Label string `json:"l"`
// Hint is a muted second line under the label.
Hint string `json:"h,omitempty"`
}
DeskOption is one choice in a blank's menu.
type DeskPeopleTile ¶
type DeskPeopleTile struct {
// Count is "5 members · 1 invited"; empty when the members could not be
// read.
Count string
Faces []DeskFace
// More is how many people the tile has no room to show.
More int
Href string
InviteHref string
}
DeskPeopleTile is the campaign's people as faces, with a way to invite.
type DeskProvider ¶
type DeskProvider interface {
// Slot is the one line this provider fills.
Slot() DeskSlot
// Facts reads that line's live numbers. An error degrades the line to
// "Open" and is logged; it never fails the page.
Facts(ctx context.Context, req DeskRequest) (DeskFacts, error)
}
DeskProvider is how another plugin tells the desk one line's numbers, the same inversion as the settings-tab registry: campaigns never imports the plugin, the plugin registers itself. Facts returns only the pointer for its own slot.
type DeskRequest ¶
DeskRequest says whose desk is being drawn. Providers read it, never an Echo context, so they stay plain services. The route is owner-only; a provider may rely on that and must still read only this campaign.
type DeskService ¶
type DeskService interface {
// Register adds a provider for its slot; a second one for the same slot
// replaces the first.
Register(p DeskProvider)
// Build reads every provider and builds the Overview's tiles. It never
// fails: a figure whose numbers are missing is the word "Open".
Build(ctx context.Context, req DeskRequest, in DeskInputs) *Desk
// Figure builds the figures a Manage tool page draws beside its title,
// from fresh numbers, so a change made on the page can redraw them
// without redrawing the page. False when the page's line does not exist
// for this campaign; an empty figure draws nothing.
Figure(ctx context.Context, req DeskRequest, in DeskInputs, id string) (DeskFigure, bool)
// Facts reads only the named slots' providers, for a tab that draws a
// few of the board's figures (Connections, Data). A slot whose provider
// fails or is missing stays nil.
Facts(ctx context.Context, req DeskRequest, slots ...DeskSlot) DeskFacts
// NeedsCount is how many things wait on the owner, for the sidebar's
// Manage row. It asks only the providers that feed Needs-you, so a count
// on every page does not cost the whole desk.
NeedsCount(ctx context.Context, req DeskRequest, in DeskInputs) int
}
DeskService builds the desk from campaigns' own data and whatever the registered providers can tell it.
func NewDeskService ¶
func NewDeskService() DeskService
NewDeskService returns an empty desk service; plugins register on it.
type DeskSlot ¶
type DeskSlot string
DeskSlot names one line of the desk that belongs to another plugin.
const ( DeskChanges DeskSlot = "changes" // what players changed DeskMedia DeskSlot = "media" // pictures and files DeskFoundry DeskSlot = "foundry" // the Foundry connection DeskAI DeskSlot = "ai" // the owner's AI connection DeskTrash DeskSlot = "trash" // pages waiting in the campaign Trash DeskKeys DeskSlot = "keys" // the campaign's API keys DeskEntries DeskSlot = "entries" // the campaign's own rules entries )
The slots a plugin can fill. A slot nobody fills, or whose provider fails, is drawn as the quiet word "Open" with no figure.
type DeskTab ¶
type DeskTab struct {
ID, Label string
Summary CustomizeSummary
}
DeskTab is one plugin-contributed Customize area as its row needs it.
type DeskTrashFacts ¶
type DeskTrashFacts struct {
Items int // pages, pictures, game nights and maps
Days int // how long each waits before it is gone for good
}
DeskTrashFacts is what waits in the campaign Trash.
type DeskValue ¶
type DeskValue struct {
// Text is the figure or the word; Sub is a muted second part ("this
// week", "310 MB").
Text, Sub string
// Href makes the value a link; unless Word is set it ends in a chevron.
Href string
// Word is a quiet word: text weight, no chevron.
Word bool
// State is the dot before the value: "", "ok" or "warn". State colours
// mean state only.
State string
// Swatch draws the campaign's colour as a dot before the value.
Swatch bool
// SubSwatch draws the campaign's colour as a dot at the start of the
// muted part, the colour's name standing beside it.
SubSwatch bool
// Joined puts a middle dot between the figure and its muted part, which
// then reads as more of the same answer ("8 · 1 hidden from players").
Joined bool
// Danger draws the word in the state red: only Delete.
Danger bool
// Blank is set for a value that is changed where it stands.
Blank *DeskBlank
// View is set for a word that opens the campaign as another kind of
// viewer, by posting the view-as form.
View *DeskView
// Off is why the value cannot be used right now ("" when it can).
Off string
// NeedsPublic marks the guest preview, which is off exactly while the
// campaign is private, so the page can enable it the moment the campaign
// is made public.
NeedsPublic bool
}
DeskValue is what stands beside a row's name. It is one of four things: a value that changes where it stands (Blank), a figure that opens its page (Href), a quiet word that acts or leads on (Word, with View or Href), or a figure with a state dot. It never holds a phrase.
type DeskView ¶
DeskView is the form behind "As a player" and "As a guest": it posts to the view-as route with who to look as and where to land.
type EntityExporter ¶
type EntityExporter interface {
ExportEntities(ctx context.Context, campaignID string) (*ExportEntityData, error)
}
EntityExporter gathers all entity-related data for a campaign export. Implemented as an adapter in app/routes.go to avoid circular imports.
type EntityImporter ¶
type EntityImporter interface {
ImportEntities(ctx context.Context, campaignID, userID string, data *ExportEntityData, idMap *IDMap, report *ImportReport) error
}
EntityImporter creates entities from import data, recording their new ids on idMap for cross-referencing by other importers. idMap.MediaIDs already holds the restored media files.
type EntityTypeLister ¶
type EntityTypeLister interface {
GetEntityTypesForSettings(ctx context.Context, campaignID string) ([]SettingsEntityType, error)
}
EntityTypeLister lists entity types for the settings page sidebar config. Avoids importing the entities package directly.
type EntityTypeSeeder ¶
type EntityTypeSeeder interface {
SeedDefaults(ctx context.Context, campaignID string) error
SeedGenre(ctx context.Context, campaignID string, genre string) error
}
EntityTypeSeeder seeds default entity types when a campaign is created. Implemented by the entities plugin's EntityService. Avoids importing the entities package directly.
type ExportAddon ¶
type ExportAddon struct {
Slug string `json:"slug"`
Enabled bool `json:"enabled"`
Config json.RawMessage `json:"config,omitempty"`
}
ExportAddon captures a per-campaign addon configuration.
type ExportAttendee ¶
type ExportAttendee struct {
UserID string `json:"user_id"`
Status string `json:"status"` // invited, accepted, declined, tentative
}
ExportAttendee captures a session attendee's RSVP status.
type ExportCalendarCycle ¶
type ExportCalendarCycle struct {
Name string `json:"name"`
CycleLength int `json:"cycle_length"`
Type string `json:"type"`
SortOrder int `json:"sort_order"`
Entries []ExportCalendarCycleEntry `json:"entries,omitempty"`
}
ExportCalendarCycle is a repeating named cycle (a zodiac of years, say) for export, with its entries. Additive.
type ExportCalendarCycleEntry ¶
type ExportCalendarCycleEntry struct {
Name string `json:"name"`
Icon *string `json:"icon,omitempty"`
YearOffset int `json:"year_offset"`
SortOrder int `json:"sort_order"`
}
ExportCalendarCycleEntry is a single entry within a cycle for export.
type ExportCalendarData ¶
type ExportCalendarData struct {
// Ref is the calendar's id in the exporting campaign, so a timeline can
// be bound back to the same calendar on import. Additive.
Ref string `json:"ref,omitempty"`
Name string `json:"name"`
Description *string `json:"description,omitempty"`
Mode string `json:"mode"`
Visibility string `json:"visibility,omitempty"`
VisibilityRules *string `json:"visibility_rules,omitempty"`
EpochName *string `json:"epoch_name,omitempty"`
CurrentYear int `json:"current_year"`
CurrentMonth int `json:"current_month"`
CurrentDay int `json:"current_day"`
CurrentHour int `json:"current_hour"`
CurrentMinute int `json:"current_minute"`
HoursPerDay int `json:"hours_per_day"`
MinutesPerHour int `json:"minutes_per_hour"`
SecondsPerMinute int `json:"seconds_per_minute"`
LeapYearEvery int `json:"leap_year_every"`
LeapYearOffset int `json:"leap_year_offset"`
// Hemisphere/ForecastsEnabled/MonthStartsNewWeek are additive fields:
// calendar.Calendar grew all of these under V5, and a restored campaign
// must carry the GM's actual configuration rather than falling back to
// the un-set/off defaults.
//
// TracksRealTime/RealTimeZone keep a calendar that follows real time
// doing so after a restore. The zone is the one the GM picked for their
// world, not a member's own; it is the one named exception to the
// scheduler-data export guard (sessions.TestScheduler_AbsentFromCampaignExport).
// Absent in older backups, which restore the calendar not following
// real time.
Hemisphere *string `json:"hemisphere,omitempty"`
ForecastsEnabled bool `json:"forecasts_enabled,omitempty"`
MonthStartsNewWeek bool `json:"month_starts_new_week,omitempty"`
TracksRealTime bool `json:"tracks_real_time,omitempty"`
RealTimeZone *string `json:"real_time_zone,omitempty"`
// EraLook is the calendar's era colours setting; nil in a backup from
// before it existed, which keeps the defaults on restore.
EraLook *ExportCalendarEraLook `json:"era_look,omitempty"`
// Sun is the calendar's kind of star; nil in a backup from before suns
// had a kind, which keeps the yellow sun on restore.
Sun *ExportCalendarSun `json:"sun,omitempty"`
Months []ExportCalendarMonth `json:"months"`
Weekdays []ExportCalendarWeekday `json:"weekdays"`
Moons []ExportCalendarMoon `json:"moons,omitempty"`
Seasons []ExportCalendarSeason `json:"seasons,omitempty"`
Eras []ExportCalendarEra `json:"eras,omitempty"`
// Cycles/Festivals/Weather are additive sub-resources, the same
// "restored config the GM set, not silently reset to nothing" case as
// the settings above.
Cycles []ExportCalendarCycle `json:"cycles,omitempty"`
Festivals []ExportCalendarFestival `json:"festivals,omitempty"`
Weather *ExportCalendarWeather `json:"weather,omitempty"`
// WeatherDays are the day-by-day readings, painted or generated, with
// their locks. Additive.
WeatherDays []ExportCalendarWeatherDay `json:"weather_days,omitempty"`
// PlaceWeather is the weather of each place with a climate of its own,
// and PartyMoves the days the party arrived somewhere. Places are named
// by page slug, since page ids are new in the restored campaign.
// Additive: absent in older backups, which restore no place weather.
PlaceWeather []ExportCalendarPlaceWeather `json:"place_weather,omitempty"`
PartyMoves []ExportCalendarPartyMove `json:"party_moves,omitempty"`
EventCategories []ExportEventCategory `json:"event_categories,omitempty"`
Events []ExportCalendarEvent `json:"events,omitempty"`
// AdditionalCalendars are the campaign's non-default calendars. They live
// under the primary rather than as a second envelope key so a file
// written by this version still reads in an importer that only knows the
// singular "calendar"; such an importer simply drops the extras. Only the
// primary carries EventCategories, because event kinds are campaign-wide
// and extras reference them by slug.
AdditionalCalendars []ExportCalendarData `json:"additional_calendars,omitempty"`
}
ExportCalendarData captures the full calendar configuration and events. Reuses the existing calendar export types for sub-resources.
Visibility/VisibilityRules are additive fields (V5, #778): a calendar can itself be dm_only (see calendar.Calendar), independent of any individual event's visibility. Omitting these on export would mean every restored calendar comes back as "everyone" regardless of how it was set before the backup — see calendarImportAdapter.ImportCalendar's doc comment for how a pre-V5 backup (which never had this field) is handled on import.
type ExportCalendarEra ¶
type ExportCalendarEra struct {
Name string `json:"name"`
StartYear int `json:"start_year"`
StartMonth int `json:"start_month,omitempty"`
StartDay int `json:"start_day,omitempty"`
EndYear *int `json:"end_year,omitempty"`
EndMonth *int `json:"end_month,omitempty"`
EndDay *int `json:"end_day,omitempty"`
Description *string `json:"description,omitempty"`
Color string `json:"color"`
SortOrder int `json:"sort_order"`
// Additive: the era's look and lore (calendar.Era). LoreEntitySlug names
// the lore page by slug, re-pointed at the restored page on import, the
// way an event's linked page is.
Color2 *string `json:"color_2,omitempty"`
Style string `json:"style,omitempty"`
Feel *string `json:"feel,omitempty"`
LoreEntitySlug *string `json:"lore_entity_slug,omitempty"`
DMNote *string `json:"dm_note,omitempty"`
HiddenUntilBegins bool `json:"hidden_until_begins,omitempty"`
// PageVersions are the pages' versions for this era, each naming its
// page by slug. Additive; an older backup has none.
PageVersions []ExportEraPageVersion `json:"page_versions,omitempty"`
}
ExportCalendarEra is an era definition for export.
StartMonth/StartDay/EndMonth/EndDay make the era day-granular (see calendar.Era). A backup (or importer) that omits them unmarshals as zero — calendarImportAdapter treats a zero StartMonth/StartDay as "day-level precision unknown" and defaults to month 1 day 1 of the year (and month 12 day 31 of EndYear when set), the same "whole year" reading Era.ContainsDate already gives an end year with no end month/day.
type ExportCalendarEraLook ¶
type ExportCalendarEraLook struct {
ColorsOn bool `json:"colors_on"`
Feel string `json:"feel"`
Intensity float64 `json:"intensity"`
Speed float64 `json:"speed"`
}
ExportCalendarEraLook is a calendar's era colours setting for export.
type ExportCalendarEvent ¶
type ExportCalendarEvent struct {
Name string `json:"name"`
Description *string `json:"description,omitempty"`
DescriptionHTML *string `json:"description_html,omitempty"`
EntitySlug *string `json:"entity_slug,omitempty"`
Year int `json:"year"`
Month int `json:"month"`
Day int `json:"day"`
StartHour *int `json:"start_hour,omitempty"`
StartMinute *int `json:"start_minute,omitempty"`
EndYear *int `json:"end_year,omitempty"`
EndMonth *int `json:"end_month,omitempty"`
EndDay *int `json:"end_day,omitempty"`
EndHour *int `json:"end_hour,omitempty"`
EndMinute *int `json:"end_minute,omitempty"`
IsRecurring bool `json:"is_recurring"`
RecurrenceType *string `json:"recurrence_type,omitempty"`
// RecurrenceInterval/RecurrenceEnd*/RecurrenceMaxOccurrences mirror
// calendar.Event's own recurrence fields — see that struct's doc comment.
RecurrenceInterval *int `json:"recurrence_interval,omitempty"`
RecurrenceEndYear *int `json:"recurrence_end_year,omitempty"`
RecurrenceEndMonth *int `json:"recurrence_end_month,omitempty"`
RecurrenceEndDay *int `json:"recurrence_end_day,omitempty"`
RecurrenceMaxOccurrences *int `json:"recurrence_max_occurrences,omitempty"`
Visibility string `json:"visibility"`
// VisibilityRules is the optional {allowed_users,denied_users} JSON
// blob (see calendar.VisibilityRules) — raw, not re-typed, so it
// round-trips exactly.
VisibilityRules *string `json:"visibility_rules,omitempty"`
Category *string `json:"category,omitempty"`
// Announced overrides the event's kind's default announced setting; nil
// means "inherit" (see calendar.Event.EffectiveAnnounced).
Announced *string `json:"announced,omitempty"`
Tier *string `json:"tier,omitempty"`
Color *string `json:"color,omitempty"`
Icon *string `json:"icon,omitempty"`
AllDay bool `json:"all_day,omitempty"`
// Payload is the raw JSON extras blob (e.g. a moon-night marker) — see
// calendar.Event.Payload / calendar.MoonNightPayload.
Payload *string `json:"payload,omitempty"`
// Ref is the event's id in the exporting campaign. RecurrenceRule is the
// event's repeat rule as stored, still naming moons, seasons and events
// by their exporting ids; the importer maps those through the Refs.
// Overrides are its "this one only" skips and moves. All additive.
Ref string `json:"ref,omitempty"`
RecurrenceRule json.RawMessage `json:"recurrence_rule,omitempty"`
Overrides []ExportCalendarEventOverride `json:"overrides,omitempty"`
// Roll is the event's dice or table roll and its stored nights.
// Additive.
Roll *ExportCalendarEventRoll `json:"roll,omitempty"`
// Status is what became of the event: happened, moved or called_off.
// Planned is left out, so a file from before it existed, or an event
// nobody answered, reads as planned. Outcome is the line on what
// happened; MovedFrom* is the day a moved event was planned for. All
// additive.
Status string `json:"status,omitempty"`
Outcome *string `json:"outcome,omitempty"`
MovedFromYear *int `json:"moved_from_year,omitempty"`
MovedFromMonth *int `json:"moved_from_month,omitempty"`
MovedFromDay *int `json:"moved_from_day,omitempty"`
}
ExportCalendarEvent captures a single calendar event.
RecurrenceInterval/RecurrenceEndYear/RecurrenceEndMonth/RecurrenceEndDay/ RecurrenceMaxOccurrences/VisibilityRules/Announced/Tier/Color/Icon/AllDay/ Payload are additive fields (V5, #778): calendar.Event grew all of these after this struct was written, and dropping them silently on export would have been exactly the "backup that looks complete but silently lost data" failure this restoration exists to fix — a dm_only event's per-user VisibilityRules allow/deny list and a moon-night Payload are both content a Director would reasonably expect a backup to keep.
type ExportCalendarEventOverride ¶
type ExportCalendarEventOverride struct {
Year int `json:"year"`
Month int `json:"month"`
Day int `json:"day"`
Action string `json:"action"`
NewYear *int `json:"new_year,omitempty"`
NewMonth *int `json:"new_month,omitempty"`
NewDay *int `json:"new_day,omitempty"`
}
ExportCalendarEventOverride is one skipped or moved occurrence of a repeating event: the date its repeat put it on, and for a move, where to.
type ExportCalendarEventRoll ¶
type ExportCalendarEventRoll struct {
Config json.RawMessage `json:"config"`
TableName string `json:"table_name,omitempty"`
Nights []ExportCalendarRollNight `json:"nights,omitempty"`
}
ExportCalendarEventRoll is an event's roll. Config is the calendar plugin's roll settings as stored, carried raw like RecurrenceRule; TableName names a table roll's table, which the import finds by name.
type ExportCalendarFestival ¶
type ExportCalendarFestival struct {
Name string `json:"name"`
Month *int `json:"month,omitempty"`
Day *int `json:"day,omitempty"`
AfterMonth *int `json:"after_month,omitempty"`
Description *string `json:"description,omitempty"`
Color *string `json:"color,omitempty"`
Icon *string `json:"icon,omitempty"`
SortOrder int `json:"sort_order"`
}
ExportCalendarFestival is a fixed calendar entry (holiday) for export. Additive.
type ExportCalendarMonth ¶
type ExportCalendarMonth struct {
Name string `json:"name"`
Days int `json:"days"`
SortOrder int `json:"sort_order"`
IsIntercalary bool `json:"is_intercalary"`
LeapYearDays int `json:"leap_year_days"`
}
ExportCalendarMonth is a month definition for export.
type ExportCalendarMoon ¶
type ExportCalendarMoon struct {
// Ref is the moon's id in the exporting campaign, so an event's repeat
// rule naming it can be pointed at the re-created moon on import.
Ref int `json:"ref,omitempty"`
Name string `json:"name"`
CycleDays float64 `json:"cycle_days"`
PhaseOffset float64 `json:"phase_offset"`
Color string `json:"color"`
HiddenFromPlayers *bool `json:"hidden_from_players"`
BaseDesign string `json:"base_design,omitempty"`
Tint *string `json:"tint,omitempty"`
PhaseSource string `json:"phase_source,omitempty"`
Size float64 `json:"size,omitempty"`
OrbitSpeed float64 `json:"orbit_speed,omitempty"`
// LoreEntitySlug names the moon's lore page by slug, re-pointed at the
// restored page on import, the way an era's is. Additive: an older
// backup has none.
LoreEntitySlug *string `json:"lore_entity_slug,omitempty"`
// PhaseMode is "manual" for a moon set by hand, with the Director's
// StateNames and Marks; empty (an older backup, or a cycling moon)
// restores it following its cycle. Additive.
PhaseMode string `json:"phase_mode,omitempty"`
StateNames map[string]string `json:"state_names,omitempty"`
Marks []ExportCalendarMoonMark `json:"marks,omitempty"`
}
ExportCalendarMoon is a moon definition for export.
HiddenFromPlayers must be exported: dropping it would make an imported campaign show a GM-only moon to players. It is a *bool, not bool, so a backup that omits the key can be told apart from one that explicitly recorded "visible": the exporter always writes a non-nil true/false, and a nil read back on import means "unknown, from an old backup" — see calendarImportAdapter.ImportCalendar, which fails that case closed (treats it as hidden), mirroring importCalendarVisibility's reasoning. BaseDesign/Tint/PhaseSource/Size/OrbitSpeed are additive fields: they drive the sky pane's rendering (calendar.Moon's own doc comment), and a restored moon keeps the look the GM actually picked rather than falling back to the library default.
type ExportCalendarMoonMark ¶
type ExportCalendarMoonMark struct {
Year int `json:"year"`
Month int `json:"month"`
Day int `json:"day"`
State string `json:"state"`
Shown bool `json:"shown"`
}
ExportCalendarMoonMark is one day a hand-set moon was set to a state, and whether players see the change.
type ExportCalendarPartyMove ¶
type ExportCalendarPartyMove struct {
Year int `json:"year"`
Month int `json:"month"`
Day int `json:"day"`
PlaceSlug string `json:"place_slug,omitempty"`
}
ExportCalendarPartyMove says the party is at PlaceSlug from this day until the next move; no slug means nowhere with a climate of its own.
type ExportCalendarPlaceWeather ¶
type ExportCalendarPlaceWeather struct {
PlaceSlug string `json:"place_slug"`
Days []ExportCalendarWeatherDay `json:"days"`
}
ExportCalendarPlaceWeather is one place's day readings.
type ExportCalendarRollNight ¶
type ExportCalendarRollNight struct {
Year int `json:"year"`
Month int `json:"month"`
Day int `json:"day"`
Total *int `json:"total,omitempty"`
Faces []int `json:"faces,omitempty"`
Entry string `json:"entry,omitempty"`
Source string `json:"source"`
Locked bool `json:"locked,omitempty"`
Told *bool `json:"told,omitempty"`
}
ExportCalendarRollNight is one night's stored result. Told is absent when the night follows its result's own "tell players".
type ExportCalendarSeason ¶
type ExportCalendarSeason struct {
// Ref: as ExportCalendarMoon.Ref, for a repeat rule naming a season.
Ref int `json:"ref,omitempty"`
Name string `json:"name"`
StartMonth int `json:"start_month"`
StartDay int `json:"start_day"`
EndMonth int `json:"end_month"`
EndDay int `json:"end_day"`
Description *string `json:"description,omitempty"`
Color string `json:"color"`
WeatherEffect *string `json:"weather_effect,omitempty"`
}
ExportCalendarSeason is a season definition for export.
type ExportCalendarSun ¶
ExportCalendarSun is a calendar's sun for export.
type ExportCalendarWeather ¶
type ExportCalendarWeather struct {
PresetID *string `json:"preset_id,omitempty"`
PresetLabel *string `json:"preset_label,omitempty"`
Icon *string `json:"icon,omitempty"`
Color *string `json:"color,omitempty"`
TemperatureCelsius *float64 `json:"temperature_celsius,omitempty"`
WindSpeedKPH *float64 `json:"wind_speed_kph,omitempty"`
WindSpeedTier *string `json:"wind_speed_tier,omitempty"`
WindDirection *string `json:"wind_direction,omitempty"`
WindDirectionDegrees *int `json:"wind_direction_degrees,omitempty"`
PrecipitationType *string `json:"precipitation_type,omitempty"`
PrecipitationIntensity *float64 `json:"precipitation_intensity,omitempty"`
ZoneID *string `json:"zone_id,omitempty"`
ZoneName *string `json:"zone_name,omitempty"`
Description *string `json:"description,omitempty"`
}
ExportCalendarWeather is the calendar's current weather reading for export: a GM-set reading, or one synced from an external tool, carried through a restore rather than left unset.
type ExportCalendarWeatherDay ¶
type ExportCalendarWeatherDay struct {
Year int `json:"year"`
Month int `json:"month"`
Day int `json:"day"`
Source string `json:"source"`
Locked bool `json:"locked,omitempty"`
ExportCalendarWeather
}
ExportCalendarWeatherDay is one day's weather reading: Month is the month's position in the calendar's order, Source "manual" (painted) or "generated".
type ExportCalendarWeekday ¶
ExportCalendarWeekday is a weekday definition for export.
type ExportCampaignMeta ¶
type ExportCampaignMeta struct {
Name string `json:"name"`
Description *string `json:"description,omitempty"`
IsPublic bool `json:"is_public"`
Settings json.RawMessage `json:"settings,omitempty"`
SidebarConfig json.RawMessage `json:"sidebar_config,omitempty"`
DashboardLayout json.RawMessage `json:"dashboard_layout,omitempty"`
}
ExportCampaignMeta holds the campaign-level configuration.
type ExportDrawing ¶
type ExportDrawing struct {
DrawingType string `json:"drawing_type"`
LayerName *string `json:"layer_name,omitempty"`
Points json.RawMessage `json:"points"`
StrokeColor string `json:"stroke_color"`
StrokeWidth float64 `json:"stroke_width"`
FillColor *string `json:"fill_color,omitempty"`
FillAlpha float64 `json:"fill_alpha"`
TextContent *string `json:"text_content,omitempty"`
FontSize *int `json:"font_size,omitempty"`
Rotation float64 `json:"rotation"`
Visibility string `json:"visibility"`
}
ExportDrawing captures a map drawing.
type ExportEntity ¶
type ExportEntity struct {
OriginalID string `json:"original_id"`
EntityTypeSlug string `json:"entity_type_slug"`
Name string `json:"name"`
Slug string `json:"slug"`
Entry *string `json:"entry,omitempty"`
EntryHTML *string `json:"entry_html,omitempty"`
ImagePath *string `json:"image_path,omitempty"`
CoverImagePath *string `json:"cover_image_path,omitempty"`
ParentSlug *string `json:"parent_slug,omitempty"`
// AlsoListedUnder holds the slugs of the other pages this page is listed
// under in the page tree (additive; older files simply lack it).
AlsoListedUnder []string `json:"also_listed_under,omitempty"`
TypeLabel *string `json:"type_label,omitempty"`
IsPrivate bool `json:"is_private"`
IsTemplate bool `json:"is_template"`
// ShopGood is additive; a file without it is read as an ordinary page.
ShopGood bool `json:"shop_good,omitempty"`
Visibility string `json:"visibility,omitempty"`
Permissions []ExportEntityPermission `json:"permissions,omitempty"`
FieldsData json.RawMessage `json:"fields_data,omitempty"`
FieldOverrides json.RawMessage `json:"field_overrides,omitempty"`
PopupConfig json.RawMessage `json:"popup_config,omitempty"`
// Layout is the key of the category layout the page chose (additive);
// empty means it follows its category.
Layout string `json:"layout,omitempty"`
// SetAside is the values a game system field switch took off this page,
// shown only to the GM and put back on switching back (additive).
SetAside json.RawMessage `json:"set_aside,omitempty"`
}
ExportEntity captures a single entity with all its data.
type ExportEntityData ¶
type ExportEntityData struct {
Types []ExportEntityType
Entities []ExportEntity
Tags []ExportTag
EntityTags []ExportEntityTag
Relations []ExportRelation
}
ExportEntityData holds all entity-related data for export.
type ExportEntityGroup ¶
type ExportEntityGroup struct {
Name string `json:"name"`
Color string `json:"color"`
SortOrder int `json:"sort_order"`
Members []string `json:"members,omitempty"` // Entity slugs.
}
ExportEntityGroup captures a timeline entity group (swim lane).
type ExportEntityPermission ¶
type ExportEntityPermission struct {
SubjectType string `json:"subject_type"` // "role", "user", "group"
SubjectID string `json:"subject_id"`
Permission string `json:"permission"` // "view", "edit"
}
ExportEntityPermission captures a single permission grant on an entity.
type ExportEntityTag ¶
type ExportEntityTag struct {
EntitySlug string `json:"entity_slug"`
TagSlug string `json:"tag_slug"`
}
ExportEntityTag captures a tag assignment to an entity.
type ExportEntityType ¶
type ExportEntityType struct {
// OriginalID is the entity type's original ID, used to remap entity references.
OriginalID int `json:"original_id"`
Slug string `json:"slug"`
Name string `json:"name"`
NamePlural string `json:"name_plural"`
Icon string `json:"icon"`
Color string `json:"color"`
Description *string `json:"description,omitempty"`
PinnedEntityIDs []string `json:"pinned_entity_ids,omitempty"`
DashboardLayout *string `json:"dashboard_layout,omitempty"`
Fields json.RawMessage `json:"fields"`
Layout json.RawMessage `json:"layout"`
SortOrder int `json:"sort_order"`
IsDefault bool `json:"is_default"`
// Enabled is a pointer so a file without the key leaves the type on
// rather than switching it off.
Enabled *bool `json:"enabled"`
// PresetCategory, ParentTypeSlug and Claimable are additive. They are
// what makes a type the campaign's Player Character category (and a
// sub-category of its parent); without them a restored PC type comes
// back as an ordinary top-level category nobody can claim from.
PresetCategory *string `json:"preset_category,omitempty"`
ParentTypeSlug *string `json:"parent_type_slug,omitempty"`
Claimable *bool `json:"claimable,omitempty"`
// PageLayouts is the category's named layouts besides Layout (additive).
PageLayouts json.RawMessage `json:"page_layouts,omitempty"`
// FieldSwitch is the owner's answer to a game system's offer of its own
// fields for this category (additive). Absent means never answered, so
// a restore shows the offer again.
FieldSwitch *ExportFieldSwitch `json:"field_switch,omitempty"`
}
ExportEntityType captures an entity type template with fields and layout.
type ExportEraPageVersion ¶
type ExportEraPageVersion struct {
EntitySlug string `json:"entity_slug"`
Name *string `json:"name,omitempty"`
Entry *string `json:"entry,omitempty"`
EntryHTML *string `json:"entry_html,omitempty"`
FieldsData map[string]any `json:"fields_data,omitempty"`
}
ExportEraPageVersion is one page's version for an era: only what it changes from the usual page. Its picture is not carried yet.
type ExportEventCategory ¶
type ExportEventCategory struct {
Slug string `json:"slug"`
Name string `json:"name"`
Icon string `json:"icon"`
Color string `json:"color"`
SortOrder int `json:"sort_order"`
DefaultAnnounced string `json:"default_announced,omitempty"`
}
ExportEventCategory is an event category definition for export.
DefaultAnnounced carries a category whose events are meant to be knowable ahead of time (a festival, say) through a restore, rather than falling back to "on_day".
type ExportEventConnection ¶
type ExportEventConnection struct {
SourceIndex int `json:"source_index"` // Index into the timeline's Events slice.
TargetIndex int `json:"target_index"` // Index into the timeline's Events slice.
Label *string `json:"label,omitempty"`
Color *string `json:"color,omitempty"`
Style string `json:"style"`
}
ExportEventConnection captures a connection between two timeline events. Source and target are identified by event index within the same timeline export.
type ExportFieldSwitch ¶
type ExportFieldSwitch struct {
// State is "switched", "dismissed" ("Not now") or "back" (switched,
// then switched back).
State string `json:"state"`
SystemID string `json:"system_id"`
PresetSlug string `json:"preset_slug"`
// OldFields is the field list from before the switch, which switching
// back restores; absent when the category began with the system's
// fields and has nothing to go back to.
OldFields json.RawMessage `json:"old_fields,omitempty"`
OldPresetCategory *string `json:"old_preset_category,omitempty"`
}
ExportFieldSwitch is a category's answer to a game system's field switch.
type ExportFogRegion ¶
type ExportFogRegion struct {
Points json.RawMessage `json:"points"`
IsExplored bool `json:"is_explored"`
}
ExportFogRegion captures a fog of war region.
type ExportGroup ¶
type ExportGroup struct {
Name string `json:"name"`
Description *string `json:"description,omitempty"`
MemberIDs []string `json:"member_ids,omitempty"`
}
ExportGroup captures a campaign group with its member user IDs. Member IDs are user UUIDs; they are only meaningful if the same users exist on the import target instance.
type ExportHandler ¶
type ExportHandler struct {
// contains filtered or unexported fields
}
ExportHandler handles export/import HTTP requests.
func NewExportHandler ¶
func NewExportHandler(exportSvc *ExportImportService) *ExportHandler
NewExportHandler creates a new export/import handler.
func (*ExportHandler) ExportCampaign ¶
func (h *ExportHandler) ExportCampaign(c *echo.Context) error
ExportCampaign exports a campaign as a JSON download (GET /campaigns/:id/export). When ?include_media=1 is set, the response is a zip containing the JSON envelope as campaign.json plus a media/ directory with each campaign-owned media file. Requires campaign owner role.
func (*ExportHandler) ImportCampaign ¶
func (h *ExportHandler) ImportCampaign(c *echo.Context) error
ImportCampaign imports a campaign from an uploaded JSON file or zip bundle (POST /campaigns/import). Creates a new campaign owned by the current user. A zip from ?include_media=1 also restores its picture files; a JSON upload carries none, and the report says which are missing.
func (*ExportHandler) ImportCampaignForm ¶
func (h *ExportHandler) ImportCampaignForm(c *echo.Context) error
ImportCampaignForm renders the import page with a file upload form (GET /campaigns/import).
type ExportImportService ¶
type ExportImportService struct {
// contains filtered or unexported fields
}
ExportImportService handles campaign export and import operations.
func NewExportImportService ¶
func NewExportImportService(campaigns CampaignService) *ExportImportService
NewExportImportService creates a new export/import service.
func (*ExportImportService) Export ¶
func (s *ExportImportService) Export(ctx context.Context, campaignID string) (*CampaignExport, error)
Export generates a complete campaign export as a CampaignExport struct. Requires the caller to have owner access to the campaign.
func (*ExportImportService) Import ¶
func (s *ExportImportService) Import(ctx context.Context, userID string, data *CampaignExport, media *ImportMediaBundle) (*Campaign, *ImportReport, error)
Import creates a new campaign from a CampaignExport. Returns the newly created campaign and a report of everything that could not be restored. Processes data in dependency order: campaign metadata, addons, media, entity types + entities + tags + relations, sidebar, groups, calendar, timelines, sessions, maps, notes, posts. Addons come first because they gate what may be created: the Player Character category is refused while its addon is off, so restoring it first keeps the player characters. Media comes before everything that points at a picture, so those references can be rewritten to the restored files. media is the ZIP's files, or nil for a JSON upload.
Import is best-effort: a single bad row must not abandon a half-built campaign. The returned *ImportReport is never nil; a non-zero Count() means the caller MUST tell the operator the restore is partial and what was lost.
func (*ExportImportService) MediaBundlerImpl ¶
func (s *ExportImportService) MediaBundlerImpl() MediaBundler
MediaBundler returns the wired bundler, or nil if none is configured. Used by the export handler to decide whether to honor ?include_media.
func (*ExportImportService) SetAddonExporter ¶
func (s *ExportImportService) SetAddonExporter(e AddonExporter)
SetAddonExporter wires the addon export adapter.
func (*ExportImportService) SetAddonImporter ¶
func (s *ExportImportService) SetAddonImporter(i AddonImporter)
SetAddonImporter wires the addon import adapter.
func (*ExportImportService) SetCalendarExporter ¶
func (s *ExportImportService) SetCalendarExporter(e CalendarExporter)
SetCalendarExporter wires the calendar export adapter.
func (*ExportImportService) SetCalendarImporter ¶
func (s *ExportImportService) SetCalendarImporter(i CalendarImporter)
SetCalendarImporter wires the calendar import adapter.
func (*ExportImportService) SetEntityExporter ¶
func (s *ExportImportService) SetEntityExporter(e EntityExporter)
SetEntityExporter wires the entity export adapter.
func (*ExportImportService) SetEntityImporter ¶
func (s *ExportImportService) SetEntityImporter(i EntityImporter)
SetEntityImporter wires the entity import adapter.
func (*ExportImportService) SetGroupExporter ¶
func (s *ExportImportService) SetGroupExporter(e GroupExporter)
SetGroupExporter wires the group export adapter.
func (*ExportImportService) SetGroupImporter ¶
func (s *ExportImportService) SetGroupImporter(i GroupImporter)
SetGroupImporter wires the group import adapter.
func (*ExportImportService) SetMapExporter ¶
func (s *ExportImportService) SetMapExporter(e MapExporter)
SetMapExporter wires the map export adapter.
func (*ExportImportService) SetMapImporter ¶
func (s *ExportImportService) SetMapImporter(i MapImporter)
SetMapImporter wires the map import adapter.
func (*ExportImportService) SetMediaBundler ¶
func (s *ExportImportService) SetMediaBundler(b MediaBundler)
SetMediaBundler wires the optional media bytes bundler. If unset, ?include_media=1 export requests fall back to the JSON-only path.
func (*ExportImportService) SetMediaExporter ¶
func (s *ExportImportService) SetMediaExporter(e MediaExporter)
SetMediaExporter wires the media export adapter.
func (*ExportImportService) SetMediaImporter ¶
func (s *ExportImportService) SetMediaImporter(i MediaImporter)
SetMediaImporter wires the media import adapter.
func (*ExportImportService) SetNoteExporter ¶
func (s *ExportImportService) SetNoteExporter(e NoteExporter)
SetNoteExporter wires the note export adapter.
func (*ExportImportService) SetNoteImporter ¶
func (s *ExportImportService) SetNoteImporter(i NoteImporter)
SetNoteImporter wires the note import adapter.
func (*ExportImportService) SetPostExporter ¶
func (s *ExportImportService) SetPostExporter(e PostExporter)
SetPostExporter wires the post export adapter.
func (*ExportImportService) SetPostImporter ¶
func (s *ExportImportService) SetPostImporter(i PostImporter)
SetPostImporter wires the post import adapter.
func (*ExportImportService) SetQuestExporter ¶
func (s *ExportImportService) SetQuestExporter(e QuestExporter)
SetQuestExporter wires the quest sheet export adapter.
func (*ExportImportService) SetQuestImporter ¶
func (s *ExportImportService) SetQuestImporter(i QuestImporter)
SetQuestImporter wires the quest sheet import adapter.
func (*ExportImportService) SetRecipeExporter ¶
func (s *ExportImportService) SetRecipeExporter(e RecipeExporter)
SetRecipeExporter wires the crafting recipe export adapter.
func (*ExportImportService) SetRecipeImporter ¶
func (s *ExportImportService) SetRecipeImporter(i RecipeImporter)
SetRecipeImporter wires the crafting recipe import adapter.
func (*ExportImportService) SetRollTableExporter ¶
func (s *ExportImportService) SetRollTableExporter(e RollTableExporter)
SetRollTableExporter wires the rolling-tables export adapter.
func (*ExportImportService) SetRollTableImporter ¶
func (s *ExportImportService) SetRollTableImporter(i RollTableImporter)
SetRollTableImporter wires the rolling-tables import adapter.
func (*ExportImportService) SetSessionExporter ¶
func (s *ExportImportService) SetSessionExporter(e SessionExporter)
SetSessionExporter wires the session export adapter.
func (*ExportImportService) SetSessionImporter ¶
func (s *ExportImportService) SetSessionImporter(i SessionImporter)
SetSessionImporter wires the session import adapter.
func (*ExportImportService) SetTimelineExporter ¶
func (s *ExportImportService) SetTimelineExporter(e TimelineExporter)
SetTimelineExporter wires the timeline export adapter.
func (*ExportImportService) SetTimelineImporter ¶
func (s *ExportImportService) SetTimelineImporter(i TimelineImporter)
SetTimelineImporter wires the timeline import adapter.
func (*ExportImportService) Validate ¶
func (s *ExportImportService) Validate(data *CampaignExport) error
Validate checks a CampaignExport for structural integrity before import. Returns nil if the export is valid, or an error describing the problem.
type ExportLayer ¶
type ExportLayer struct {
Name string `json:"name"`
LayerType string `json:"layer_type"`
Visible bool `json:"visible"`
Locked bool `json:"locked"`
Opacity float64 `json:"opacity"`
SortOrder int `json:"sort_order"`
}
ExportLayer captures a map layer.
type ExportMap ¶
type ExportMap struct {
Ref string `json:"ref,omitempty"`
Name string `json:"name"`
Description *string `json:"description,omitempty"`
ImageID *string `json:"image_id,omitempty"`
ImageWidth int `json:"image_width"`
ImageHeight int `json:"image_height"`
SortOrder int `json:"sort_order"`
Markers []ExportMarker `json:"markers,omitempty"`
Drawings []ExportDrawing `json:"drawings,omitempty"`
Layers []ExportLayer `json:"layers,omitempty"`
Tokens []ExportToken `json:"tokens,omitempty"`
FogRegions []ExportFogRegion `json:"fog_regions,omitempty"`
}
ExportMap captures a map with markers, drawings, layers, tokens, and fog. Ref is the map's id in the exporting campaign, so a marker that opens this map (ExportMarker.LinkedMapRef) can be pointed at its copy on import.
type ExportMarker ¶
type ExportMarker struct {
Name string `json:"name"`
Description *string `json:"description,omitempty"`
X float64 `json:"x"`
Y float64 `json:"y"`
Icon string `json:"icon"`
Color string `json:"color"`
EntitySlug *string `json:"entity_slug,omitempty"`
Visibility string `json:"visibility"`
// VisibilityRules is the pin's per-player allow/deny list, as stored
// (user ids). An import keeps it only when every id names a user of the
// target site; otherwise the pin becomes Director-only.
VisibilityRules *string `json:"visibility_rules,omitempty"`
// LinkedMapRef is the Ref of the exported map this marker opens.
LinkedMapRef *string `json:"linked_map_ref,omitempty"`
}
ExportMarker captures a map marker.
type ExportMediaFile ¶
type ExportMediaFile struct {
OriginalID string `json:"original_id"`
OriginalName string `json:"original_name"`
MimeType string `json:"mime_type"`
FileSize int64 `json:"file_size"`
UsageType string `json:"usage_type"`
// Filename is the file's zip entry name under media/. Additive: a
// manifest without it is paired by OriginalID, which the stored file
// is named after.
Filename string `json:"filename,omitempty"`
}
ExportMediaFile captures media file metadata for reference remapping. The bytes travel only in the ZIP export, as media/<Filename>.
type ExportNote ¶
type ExportNote struct {
Title string `json:"title"`
Entry *string `json:"entry,omitempty"`
EntryHTML *string `json:"entry_html,omitempty"`
EntitySlug *string `json:"entity_slug,omitempty"`
Color string `json:"color"`
Pinned bool `json:"pinned"`
// IsFolder marks a note that is a container for other notes rather
// than content itself.
IsFolder bool `json:"is_folder,omitempty"`
// Content is the legacy block content (text + checklists). Checklists
// live only here, never in Entry, so an export that drops this loses
// every checkbox in the campaign.
Content json.RawMessage `json:"content,omitempty"`
// ParentIndex is the index into the export's Notes slice of this
// note's containing folder, or nil for a top-level note. Index rather
// than ID for the same reason ExportEventConnection uses indices: note
// IDs are not stable across instances.
ParentIndex *int `json:"parent_index,omitempty"`
}
ExportNote captures a note. Only shared notes are exported since personal notes are user-specific.
type ExportPost ¶
type ExportPost struct {
EntitySlug string `json:"entity_slug"`
Name string `json:"name"`
Entry json.RawMessage `json:"entry,omitempty"`
EntryHTML *string `json:"entry_html,omitempty"`
IsPrivate bool `json:"is_private"`
SortOrder int `json:"sort_order"`
}
ExportPost captures an entity sub-note (post).
type ExportQuest ¶
type ExportQuest struct {
EntityID string `json:"entity_id"`
Name string `json:"name,omitempty"`
Sheet json.RawMessage `json:"sheet"`
}
ExportQuest is one page's quest sheet. EntityID is the page's original id; Sheet is the stored document, whose page and map references are original ids that import rewrites.
type ExportRecipe ¶
type ExportRecipe struct {
Name string `json:"name"`
Draft bool `json:"draft,omitempty"`
Recipe json.RawMessage `json:"recipe"`
}
ExportRecipe is one crafting recipe with its rules, looks and known list. Recipe is the crafting plugin's own JSON; item and character references in it are original page ids that import rewrites.
type ExportRelation ¶
type ExportRelation struct {
SourceEntitySlug string `json:"source_entity_slug"`
TargetEntitySlug string `json:"target_entity_slug"`
RelationType string `json:"relation_type"`
ReverseRelationType string `json:"reverse_relation_type"`
Metadata json.RawMessage `json:"metadata,omitempty"`
DmOnly bool `json:"dm_only,omitempty"`
}
ExportRelation captures a bidirectional relationship between two entities.
type ExportSession ¶
type ExportSession struct {
Name string `json:"name"`
Summary *string `json:"summary,omitempty"`
Notes *string `json:"notes,omitempty"`
NotesHTML *string `json:"notes_html,omitempty"`
Recap *string `json:"recap,omitempty"`
RecapHTML *string `json:"recap_html,omitempty"`
ScheduledDate *string `json:"scheduled_date,omitempty"`
ScheduledTime *string `json:"scheduled_time,omitempty"`
CalendarYear *int `json:"calendar_year,omitempty"`
CalendarMonth *int `json:"calendar_month,omitempty"`
CalendarDay *int `json:"calendar_day,omitempty"`
Status string `json:"status"`
IsRecurring bool `json:"is_recurring"`
RecurrenceType *string `json:"recurrence_type,omitempty"`
RecurrenceInterval int `json:"recurrence_interval,omitempty"`
SortOrder int `json:"sort_order"`
Entities []ExportSessionEntity `json:"entities,omitempty"`
Attendees []ExportAttendee `json:"attendees,omitempty"`
}
ExportSession captures a game session.
type ExportSessionEntity ¶
type ExportSessionEntity struct {
EntitySlug string `json:"entity_slug"`
Role string `json:"role"`
}
ExportSessionEntity captures an entity linked to a session.
type ExportTag ¶
type ExportTag struct {
OriginalID int `json:"original_id"`
Name string `json:"name"`
Slug string `json:"slug"`
// Color is the tag's own #rrggbb, or "" for a tag that follows the
// campaign's Tags and marks colour (and follows it again on import).
Color string `json:"color"`
DmOnly bool `json:"dm_only"`
}
ExportTag captures a tag definition.
type ExportTimeline ¶
type ExportTimeline struct {
Name string `json:"name"`
Description *string `json:"description,omitempty"`
DescriptionHTML *string `json:"description_html,omitempty"`
Color string `json:"color"`
Icon string `json:"icon"`
Visibility string `json:"visibility"`
SortOrder int `json:"sort_order"`
ZoomDefault string `json:"zoom_default"`
Events []ExportTimelineEvent `json:"events,omitempty"`
EntityGroups []ExportEntityGroup `json:"entity_groups,omitempty"`
Connections []ExportEventConnection `json:"connections,omitempty"`
// CalendarRef names the calendar the timeline draws on (its
// ExportCalendarData.Ref); NoCalendar marks a timeline with none.
// CalendarEventLinks are the calendar events shown on it. All additive:
// a file with neither field binds the timeline to the default calendar,
// as imports always did.
CalendarRef *string `json:"calendar_ref,omitempty"`
NoCalendar bool `json:"no_calendar,omitempty"`
CalendarEventLinks []ExportTimelineEventLink `json:"calendar_event_links,omitempty"`
}
ExportTimeline captures a timeline with its events, entity groups, and connections.
type ExportTimelineEvent ¶
type ExportTimelineEvent struct {
Name string `json:"name"`
Description *string `json:"description,omitempty"`
DescriptionHTML *string `json:"description_html,omitempty"`
EntitySlug *string `json:"entity_slug,omitempty"`
Year int `json:"year"`
Month int `json:"month"`
Day int `json:"day"`
StartHour *int `json:"start_hour,omitempty"`
StartMinute *int `json:"start_minute,omitempty"`
EndYear *int `json:"end_year,omitempty"`
EndMonth *int `json:"end_month,omitempty"`
EndDay *int `json:"end_day,omitempty"`
EndHour *int `json:"end_hour,omitempty"`
EndMinute *int `json:"end_minute,omitempty"`
IsRecurring bool `json:"is_recurring"`
RecurrenceType *string `json:"recurrence_type,omitempty"`
Category *string `json:"category,omitempty"`
Visibility string `json:"visibility"`
DisplayOrder int `json:"display_order"`
Label *string `json:"label,omitempty"`
Color *string `json:"color,omitempty"`
}
ExportTimelineEvent captures a standalone timeline event.
type ExportTimelineEventLink ¶
type ExportTimelineEventLink struct {
EventRef string `json:"event_ref"`
Label *string `json:"label,omitempty"`
ColorOverride *string `json:"color_override,omitempty"`
VisibilityOverride *string `json:"visibility_override,omitempty"`
VisibilityRules *string `json:"visibility_rules,omitempty"`
}
ExportTimelineEventLink is a calendar event shown on a timeline, with the timeline's own overrides for it. EventRef is the event's ExportCalendarEvent.Ref.
type ExportToken ¶
type ExportToken struct {
Name string `json:"name"`
EntitySlug *string `json:"entity_slug,omitempty"`
ImagePath *string `json:"image_path,omitempty"`
LayerName *string `json:"layer_name,omitempty"`
X float64 `json:"x"`
Y float64 `json:"y"`
Width float64 `json:"width"`
Height float64 `json:"height"`
Rotation float64 `json:"rotation"`
Scale float64 `json:"scale"`
IsHidden bool `json:"is_hidden"`
IsLocked bool `json:"is_locked"`
Bar1Value *int `json:"bar1_value,omitempty"`
Bar1Max *int `json:"bar1_max,omitempty"`
Bar2Value *int `json:"bar2_value,omitempty"`
Bar2Max *int `json:"bar2_max,omitempty"`
AuraRadius *float64 `json:"aura_radius,omitempty"`
AuraColor *string `json:"aura_color,omitempty"`
LightRadius *float64 `json:"light_radius,omitempty"`
LightDimRadius *float64 `json:"light_dim_radius,omitempty"`
LightColor *string `json:"light_color,omitempty"`
VisionEnabled bool `json:"vision_enabled"`
VisionRange *float64 `json:"vision_range,omitempty"`
Elevation int `json:"elevation"`
StatusEffects json.RawMessage `json:"status_effects,omitempty"`
}
ExportToken captures a map token.
type ExtensionEnableChecker ¶
type ExtensionEnableChecker interface {
IsEnabledForCampaign(ctx context.Context, campaignID string, addonSlug string) (bool, error)
}
ExtensionEnableChecker answers whether an addon is on for a campaign, for pages that change with it (the Customizer's character-claiming rows). Satisfied by addons.AddonService's IsEnabledForCampaign. A nil checker reads every addon as off.
type FeatureEnabler ¶
type FeatureEnabler interface {
EnableStarterFeatures(ctx context.Context, campaignID, userID string)
}
FeatureEnabler turns on the features a campaign starts with. The list of which ones lives with the composition root (internal/app), which knows the add-ons by name; campaigns only says when. One feature that cannot be turned on is skipped and logged by the implementation, never an error here, because the campaign exists and the owner can switch it on in Game & features.
type FoundryCheck ¶
type FoundryCheck struct {
Level FoundryCheckLevel
Title string
Detail string
}
FoundryCheck is one row of "Is everything working?".
func FoundryHealthChecks ¶
func FoundryHealthChecks(now time.Time, c FoundryConnection) []FoundryCheck
FoundryHealthChecks words what Chronicle knows about the campaign's Foundry link as a checklist. Only facts Chronicle records appear; each player's state is in the Players in Foundry card, from what Foundry reports.
type FoundryCheckLevel ¶
type FoundryCheckLevel string
FoundryCheckLevel is how a checklist row is marked.
const ( FoundryCheckOK FoundryCheckLevel = "ok" FoundryCheckWarn FoundryCheckLevel = "warn" FoundryCheckBad FoundryCheckLevel = "bad" FoundryCheckInfo FoundryCheckLevel = "info" )
type FoundryConnection ¶
type FoundryConnection struct {
// Connected is true while the websocket hub reports a live Foundry socket.
Connected bool
// HubLastSeen is the hub's last Foundry contact, nil if never recorded
// since this process started.
HubLastSeen *time.Time
// KeyLastUsed is the newest last_used_at across the campaign's active
// keys; it survives restarts, unlike the hub's in-memory record.
KeyLastUsed *time.Time
// ModuleVersion is the version reported by the most recently used active
// key, empty when no module has reported one.
ModuleVersion string
// KeyPrefix is the stored, non-secret start of the newest active key.
KeyPrefix string
// HasKey is true when the campaign has at least one active, unexpired key.
HasKey bool
// LinePreview is the connect line built with KeyPrefix and a trailing
// ellipsis. It carries nothing secret: the full key is never recoverable.
LinePreview string
// ServedVersion is the module version Chronicle serves this campaign,
// empty when no module is installed or it could not be read.
ServedVersion string
}
FoundryConnection is the raw, adapter-supplied picture of a campaign's Foundry link. Raw on purpose: the freshness rules live in ComputeFoundryStatus so they are tested in one place.
type FoundryConnector ¶
type FoundryConnector interface {
FoundryConnection(ctx context.Context, campaignID string) (FoundryConnection, error)
// NewFoundryConnectLine mints a new key and returns the full connect line.
// The raw key exists only inside the returned string.
NewFoundryConnectLine(ctx context.Context, campaignID, userID string) (string, error)
}
FoundryConnector is what the campaigns plugin needs from the sync plugin and the websocket hub. Nil means the row degrades to a plain link.
type FoundryRowData ¶
type FoundryRowData struct {
// Wired is false when no connector is configured; the row then shows only
// the settings link.
Wired bool
Status FoundryStatus
ModuleVersion string
HasKey bool
// Preview is the non-secret line start shown for an existing key.
Preview string
// NewLine is the full line, set only on the response to a fresh mint.
NewLine string
// contains filtered or unexported fields
}
FoundryRowData is everything the Foundry row renders.
type FoundryStatus ¶
type FoundryStatus struct {
Level FoundryStatusLevel
Text string
}
FoundryStatus is the computed status line.
func ComputeFoundryStatus ¶
func ComputeFoundryStatus(now time.Time, c FoundryConnection) FoundryStatus
ComputeFoundryStatus turns a connection into the dot level and wording. A live socket wins; otherwise the newer of the hub's last contact and the keys' last use decides, because the hub forgets on restart and a key forgets nothing.
type FoundryStatusLevel ¶
type FoundryStatusLevel string
FoundryStatusLevel drives the dot colour; the text is the accessible form.
const ( FoundryConnectedNow FoundryStatusLevel = "connected" FoundrySeenRecently FoundryStatusLevel = "recent" FoundrySeenLongAgo FoundryStatusLevel = "stale" FoundryNeverSeen FoundryStatusLevel = "never" )
type GroupExporter ¶
type GroupExporter interface {
ExportGroups(ctx context.Context, campaignID string) ([]ExportGroup, error)
}
GroupExporter gathers campaign groups for export.
type GroupImporter ¶
type GroupImporter interface {
ImportGroups(ctx context.Context, campaignID string, data []ExportGroup, report *ImportReport) error
}
GroupImporter creates campaign groups from import data.
type GroupMemberInfo ¶
type GroupMemberInfo struct {
UserID string `json:"user_id"`
DisplayName string `json:"display_name"`
Email string `json:"email"`
Role Role `json:"role"`
AvatarPath *string `json:"avatar_path,omitempty"`
}
GroupMemberInfo is a campaign member's summary within a group.
type GroupRepository ¶
type GroupRepository interface {
// CreateGroup creates a new campaign group. Returns the created group with its ID.
CreateGroup(ctx context.Context, campaignID, name string, description *string) (*CampaignGroup, error)
// ListGroups returns all groups for a campaign, ordered by name.
ListGroups(ctx context.Context, campaignID string) ([]CampaignGroup, error)
// GetGroup returns a single group by ID.
GetGroup(ctx context.Context, groupID int) (*CampaignGroup, error)
// UpdateGroup updates a group's name and description.
UpdateGroup(ctx context.Context, groupID int, name string, description *string) error
// DeleteGroup deletes a group and its memberships (cascade).
DeleteGroup(ctx context.Context, groupID int) error
// AddGroupMember adds a user to a group.
AddGroupMember(ctx context.Context, groupID int, userID string) error
// RemoveGroupMember removes a user from a group.
RemoveGroupMember(ctx context.Context, groupID int, userID string) error
// PruneNonMemberGroupRows deletes group rows of users no longer in the
// group's campaign.
PruneNonMemberGroupRows(ctx context.Context) (int64, error)
// ListGroupMembers returns all members of a group with display info.
ListGroupMembers(ctx context.Context, groupID int) ([]GroupMemberInfo, error)
}
GroupRepository manages campaign groups and their memberships.
func NewGroupRepository ¶
func NewGroupRepository(db *sql.DB) GroupRepository
NewGroupRepository creates a new group repository backed by the given DB pool.
type GroupService ¶
type GroupService interface {
CreateGroup(ctx context.Context, campaignID, name string, description *string) (*CampaignGroup, error)
ListGroups(ctx context.Context, campaignID string) ([]CampaignGroup, error)
GetGroup(ctx context.Context, groupID int) (*CampaignGroup, error)
UpdateGroup(ctx context.Context, groupID int, name string, description *string) error
DeleteGroup(ctx context.Context, groupID int) error
AddGroupMember(ctx context.Context, groupID int, userID string) error
RemoveGroupMember(ctx context.Context, groupID int, userID string) error
ListGroupMembers(ctx context.Context, groupID int) ([]GroupMemberInfo, error)
}
GroupService handles business logic for campaign group operations.
func NewGroupService ¶
func NewGroupService(repo GroupRepository) GroupService
NewGroupService creates a new group service.
type GuestCode ¶
type GuestCode struct {
ID string
CampaignID string
Note string
CreatedBy string
ExpiresAt time.Time
UsedBy *string
UsedAt *time.Time
CreatedAt time.Time
UsedByName string
// VisitDays is the look-around length; zero for a code that makes a player.
VisitDays int
// VisitUntil is when the visitor's access ends. Nil before the code is
// used, and again once the owner made them a player.
VisitUntil *time.Time
}
GuestCode is one code an owner made. The code itself is never stored.
type GuestCodeRepository ¶
type GuestCodeRepository interface {
Create(ctx context.Context, gc *GuestCode, codeHash string) error
ListByCampaign(ctx context.Context, campaignID string, since time.Time) ([]GuestCode, error)
CountLive(ctx context.Context, campaignID string, now time.Time) (int, error)
DeleteUnused(ctx context.Context, campaignID, id string) error
// Claim marks a live code used and returns it; a code that is unknown,
// used or expired is NotFound.
Claim(ctx context.Context, codeHash string, now time.Time) (id, campaignID string, err error)
Release(ctx context.Context, id string) error
// Peek reads the campaign a live code opens without using it; a code
// that is unknown, used, expired or whose campaign is in the Trash is
// NotFound.
Peek(ctx context.Context, codeHash string, now time.Time) (campaignID string, err error)
SetUsedBy(ctx context.Context, id, userID string) error
// FindByID loads one of a campaign's codes; another campaign's is NotFound.
FindByID(ctx context.Context, campaignID, id string) (*GuestCode, error)
// VisitDays is the code's look-around length, zero for a player's code.
VisitDays(ctx context.Context, id string) (int, error)
// StartVisit records who used a look-around pass and when it ends.
StartVisit(ctx context.Context, id, userID string, until time.Time) error
// FindVisit is when the user's latest look-around pass for the campaign
// ends, or nil when they have none.
FindVisit(ctx context.Context, campaignID, userID string) (*time.Time, error)
// EndVisit moves a running visit's end to now; an ended one is NotFound.
EndVisit(ctx context.Context, campaignID, id string, now time.Time) error
// ClearVisits removes the end of every pass the user holds for the
// campaign, once they are a member.
ClearVisits(ctx context.Context, campaignID, userID string) error
// EndVisitsFor moves the end of the user's running passes for the
// campaign to now. Having none is not an error.
EndVisitsFor(ctx context.Context, campaignID, userID string, now time.Time) error
// MoveMembership hands a guest's place in a campaign to another account,
// keeping that account's role when it is already a member.
MoveMembership(ctx context.Context, campaignID, fromUserID, toUserID string) error
}
GuestCodeRepository stores guest codes, keyed by the code's hash.
func NewGuestCodeRepository ¶
func NewGuestCodeRepository(db *sql.DB) GuestCodeRepository
NewGuestCodeRepository returns the MariaDB guest code store.
type GuestCodeService ¶
type GuestCodeService struct {
// contains filtered or unexported fields
}
GuestCodeService makes and redeems guest codes. It is also auth's GuestCodes adapter.
func NewGuestCodeService ¶
func NewGuestCodeService(repo GuestCodeRepository, campaigns CampaignRepository) *GuestCodeService
NewGuestCodeService returns the guest code service.
func (*GuestCodeService) AdmitWithGuestCode ¶
func (s *GuestCodeService) AdmitWithGuestCode(ctx context.Context, codeID, campaignID, userID string) error
AdmitWithGuestCode makes the user a player in the campaign, or for a look-around pass starts their visit; a visitor is never made a member.
func (*GuestCodeService) ClaimGuestCode ¶
ClaimGuestCode takes a code for one join. An archived campaign takes no one, so its codes are released untouched.
func (*GuestCodeService) Create ¶
func (s *GuestCodeService) Create(ctx context.Context, campaignID, createdBy, note string, visitDays int) (*NewGuestCode, error)
Create makes a one-use code for a campaign. visitDays above zero makes a look-around pass of that many days instead of a player's code.
func (*GuestCodeService) EndVisit ¶
func (s *GuestCodeService) EndVisit(ctx context.Context, campaignID, id string) error
EndVisit ends a running visit now. The pass stays listed, so the owner can still make them a player later.
func (*GuestCodeService) EndVisits ¶
func (s *GuestCodeService) EndVisits(ctx context.Context, campaignID, userID string) error
EndVisits ends the user's running passes for the campaign; the campaign service calls it when a member is removed.
func (*GuestCodeService) MakeVisitorPlayer ¶
func (s *GuestCodeService) MakeVisitorPlayer(ctx context.Context, campaignID, id string) error
MakeVisitorPlayer turns a visitor, current or ended, into a player. The membership comes first: if clearing the pass then fails, membership already outranks it.
func (*GuestCodeService) MoveGuestMembership ¶
func (s *GuestCodeService) MoveGuestMembership(ctx context.Context, campaignID, guestID, targetID string) error
MoveGuestMembership is the campaign step of merging a guest.
func (*GuestCodeService) Now ¶
func (s *GuestCodeService) Now() time.Time
Now is the service's clock, for the list's status labels.
func (*GuestCodeService) Peek ¶
Peek reports the campaign a live code opens, or false for a wrong, used, expired or archived-campaign code. Nothing is claimed.
func (*GuestCodeService) ReleaseGuestCode ¶
func (s *GuestCodeService) ReleaseGuestCode(ctx context.Context, codeID string)
ReleaseGuestCode puts a claimed code back.
func (*GuestCodeService) Remove ¶
func (s *GuestCodeService) Remove(ctx context.Context, campaignID, id string) error
Remove deletes an unused code.
func (*GuestCodeService) VisitPass ¶
func (s *GuestCodeService) VisitPass(ctx context.Context, campaignID, userID string) (until time.Time, live, found bool, err error)
VisitPass reports a non-member's look-around pass for the campaign: when it ends, and whether it is still running. found is false when they never had one, or the owner has since made them a player.
type Handler ¶
type Handler struct {
// contains filtered or unexported fields
}
Handler handles HTTP requests for campaign operations. Handlers are thin: bind request, call service, render response. No business logic lives here.
func NewHandler ¶
func NewHandler(service CampaignService) *Handler
NewHandler creates a new campaign handler.
func (*Handler) AcceptTransfer ¶
AcceptTransfer accepts a pending ownership transfer (GET /campaigns/:id/accept-transfer).
func (*Handler) AddGroupMemberAPI ¶
AddGroupMemberAPI adds a user to a campaign group (POST /campaigns/:id/groups/:gid/members).
func (*Handler) AddMember ¶
AddMember invites someone to the campaign by email (POST /campaigns/:id/members). They join when they accept, and the answer is the same whether or not the email has an account.
func (*Handler) AllowMemberBack ¶
AllowMemberBack lets a removed person use the join link again (POST /campaigns/:id/members/removed/:uid/allow).
func (*Handler) ArchiveCampaign ¶
ArchiveCampaign soft-archives a campaign (POST /campaigns/:id/archive).
func (*Handler) CampaignSettings ¶
CampaignSettings is one campaign's page in Account settings: GET /account/campaigns/:id. It gathers the settings that change only what this person sees in this campaign. The look picks save through the same endpoint as Your look, so the owner's limits apply unchanged. It resolves membership itself, with the same guest-preview refusal as the campaign routes' middleware, so the page keeps the account's frame instead of the campaign's sidebar.
func (*Handler) CancelTransfer ¶
CancelTransfer cancels a pending ownership transfer (POST /campaigns/:id/cancel-transfer).
func (*Handler) CategoryMenuVisible ¶
func (h *Handler) CategoryMenuVisible(cc *CampaignContext) map[int]bool
CategoryMenuVisible reports, per category id, the menu setting of every category that has a menu item. A category with no item is absent from the map and counts as visible, exactly as NormalizeNav treats it, so read it as "visible unless the map says false". When an id has several items the first wins, as in NormalizeNav.
func (*Handler) ConnectionsPage ¶
ConnectionsPage serves the Connections tab (GET /campaigns/:id/connections). Owner only, like every Campaign settings page.
func (*Handler) CreateGroupAPI ¶
CreateGroupAPI creates a new campaign group (POST /campaigns/:id/groups).
func (*Handler) CustomizeCategories ¶
func (h *Handler) CustomizeCategories(ctx context.Context, campaignID string) []CustomizeCategory
CustomizeCategories lists the campaign's categories for the Customize page. A failure is logged and reads as none, so the page still opens.
func (*Handler) CustomizeCategoriesPage ¶
CustomizeCategoriesPage is the grid of categories: GET /campaigns/:id/customize/categories.
func (*Handler) CustomizeCategory ¶
CustomizeCategory is one category's workspace: GET /campaigns/:id/customize/categories/:key and .../:key/:tab. The key is the category's id, or the draft key of one made in the draft.
func (*Handler) CustomizeDraftFor ¶
func (h *Handler) CustomizeDraftFor(ctx context.Context, campaignID, userID string) (version int, draft json.RawMessage)
CustomizeDraftFor returns the owner's stored draft for the Customize page to start from: its version and its sections. A failure is logged and reads as no draft, so the page still opens.
func (*Handler) CustomizeHere ¶
CustomizeHere answers the brush's first row for the page at ?path=, as {"row": {label, path, href}} or {"row": null}: GET /campaigns/:id/customize/here. Owner-only, like Customize itself. A path outside this campaign has no row.
func (*Handler) CustomizeHome ¶
CustomizeHome arranges one audience's campaign home: GET /campaigns/:id/customize/home[/:who]. The retired Overview tab's address goes to the Home pages area instead of a dead end.
func (*Handler) CustomizeKitKeep ¶
CustomizeKitKeep answers POST /campaigns/:id/customize/kit-try/keep {"kit": "ornate"}: the kit goes into the look section of the owner's Customize draft, and the answer is where the Look editor shows it. The draft is the same one Customize's frame keeps, so the kit waits there beside the owner's other unsaved changes until Save or Discard.
func (*Handler) CustomizeKitTry ¶
CustomizeKitTry answers GET /campaigns/:id/customize/kit-try with the style kits, the tokens that draw each of them on this campaign (layouts.KitTryCSS) and Material's card entrance, which the page wears only while no other kit is on. 404 when the page look is not Material, where no kit is drawn. With ?pages=1 it also lists the owner's own pages Customize › Look's example steps through (kitTryPages). Owner-only.
func (*Handler) CustomizeLook ¶
CustomizeLook is the signed Look editor: GET /campaigns/:id/customize/look.
func (*Handler) CustomizePluginArea ¶
CustomizePluginArea is an area a plugin contributes: GET /campaigns/:id/customize/x/:tab.
func (*Handler) CustomizeSectionKeys ¶
CustomizeSectionKeys lists the registered section keys in apply order.
func (*Handler) Delete ¶
Delete moves a campaign to the site Trash (DELETE /campaigns/:id). The owner sees it vanish; only a site admin can bring it back. Requires the request to include a confirm_name field that matches the campaign name exactly (S4).
func (*Handler) DeleteAppearancePictureAPI ¶
DeleteAppearancePictureAPI handles DELETE /campaigns/:id/appearance/picture?name=... It tidies a picture the Customize page uploaded but never saved. The page calls it fire-and-forget, so every "not yours to delete" case is a quiet no-op: a file the saved look still uses, another campaign's file, a file that did not come from this upload path, or one that is already gone. Only a malformed name is refused, since that is never a legitimate call.
func (*Handler) DeleteCustomizeDraftAPI ¶
DeleteCustomizeDraftAPI handles DELETE /campaigns/:id/customize/draft?version=n.
func (*Handler) DeleteGroupAPI ¶
DeleteGroupAPI deletes a campaign group (DELETE /campaigns/:id/groups/:gid).
func (*Handler) DeskFind ¶
DeskFind answers Find's list (GET /campaigns/:id/dashboard/find) as {"entries": [...]}. It is built on the server for the owner alone, and only when Find is opened, so no Manage page pays for it. The browser narrows it by what is typed; it never sees a tool the campaign switched off.
func (*Handler) DeskNeedsCount ¶
DeskNeedsCount answers how many things wait on the owner (GET /campaigns/:id/dashboard/needs), as {"count": N}. The sidebar's Manage row asks it after the page has drawn, so no page waits on the providers behind it. Only the add-on facts are read, since they alone decide Needs-you.
func (*Handler) EditForm ¶
EditForm redirects to the unified settings page (GET /campaigns/:id/edit). Kept for backward compatibility with bookmarks and links.
func (*Handler) ExtensionsHub ¶
ExtensionsHub renders the owner-only "Game & features" page.
Catalog source is the same `AddonLister.ListForPluginHub` the Features tab + the older /plugins page use; the `addonListerAdapter` sets HasDashboard from `HasExtensionDashboard` (see extensions_hub.go).
The Content Packs card is sourced from the extensions plugin via the `ContentPacksCardRenderer` interface; a nil renderer (or a render error) degrades gracefully — the hub omits the card and logs a warning instead of failing the page.
func (*Handler) ExtensionsHubFragmentAPI ¶
ExtensionsHubFragmentAPI returns the catalog grid as an HTMX fragment. The hub container in ExtensionsHubPage listens for the `extensions-hub-refresh` event and re-fetches via this endpoint; the existing addons-toggle handler emits the event via the HX-Trigger header when `redirect_to=extensions-hub` is posted alongside the toggle.
func (*Handler) FoundryPage ¶
FoundryPage renders GET /campaigns/:id/foundry (owner only).
func (*Handler) GenerateJoinCode ¶
GenerateJoinCode creates a shareable invite code (POST /campaigns/:id/join-code).
func (*Handler) GetCustomizeDraftAPI ¶
GetCustomizeDraftAPI handles GET /campaigns/:id/customize/draft.
func (*Handler) GetDashboardLayout ¶
GetDashboardLayout returns the current dashboard layout as JSON (GET /campaigns/:id/dashboard-layout). Supports ?role= (default/player/scribe/director/guest). With nothing saved for that audience it returns the layout the audience sees instead, so the editor opens on the real page; X-Layout-Saved says which it is.
func (*Handler) GetDmGrantsAPI ¶
GetDmGrantsAPI handles GET /campaigns/:id/dm-grants. Returns the current list of users granted dm_only visibility.
func (*Handler) GetEventTierDefinitionsAPI ¶
GetEventTierDefinitionsAPI handles GET /campaigns/:id/event-tier-definitions. Returns the per-campaign event tier vocabulary, falling back to the platform default trio when no override is set. Campaign-config surface, NOT exposed via syncapi.
func (*Handler) GetGroupAPI ¶
GetGroupAPI returns a single group with its members (GET /campaigns/:id/groups/:gid).
func (*Handler) GetOwnerDashboardLayout ¶
GetOwnerDashboardLayout returns the owner dashboard layout JSON (GET /campaigns/:id/owner-dashboard-layout).
func (*Handler) GetSidebarConfig ¶
GetSidebarConfig returns the sidebar configuration as JSON (GET /campaigns/:id/sidebar-config).
func (*Handler) GroupsPage ¶
GroupsPage renders the groups management page (GET /campaigns/:id/groups/manage).
func (*Handler) HomePreview ¶
HomePreview draws the blocks the Customizer sends as the campaign home draws them, so the editor shows the real home: POST /campaigns/:id/customize/home-preview with {"blocks":[{id,type,config}]}. It answers {"blocks":{id: html}}; a block that draws nothing is left out.
func (*Handler) InviteBoxEmail ¶
InviteBoxEmail invites by email (POST /campaigns/:id/invite-box/email). Nobody joins without accepting, and the answer is the same whether or not the address has an account, so the owner learns nothing about who has one.
func (*Handler) InviteBoxEndVisit ¶
InviteBoxEndVisit ends a look-around now (POST /campaigns/:id/invite-box/codes/:gcid/end).
func (*Handler) InviteBoxMakeCode ¶
InviteBoxMakeCode makes a guest code and shows it once (POST /campaigns/:id/invite-box/code).
func (*Handler) InviteBoxMakeLink ¶
InviteBoxMakeLink makes the campaign's invite link, replacing any earlier one (POST /campaigns/:id/invite-box/link).
func (*Handler) InviteBoxMakePlayer ¶
InviteBoxMakePlayer turns a visitor into a player (POST /campaigns/:id/invite-box/codes/:gcid/player).
func (*Handler) InviteBoxRemoveCode ¶
InviteBoxRemoveCode removes a code nobody used (DELETE /campaigns/:id/invite-box/codes/:gcid).
func (*Handler) InviteBoxRevokeInvite ¶
InviteBoxRevokeInvite withdraws an emailed invite (DELETE /campaigns/:id/invite-box/invites/:iid).
func (*Handler) InviteBoxRevokeLink ¶
InviteBoxRevokeLink ends the invite link (DELETE /campaigns/:id/invite-box/link).
func (*Handler) JoinByCode ¶
JoinByCode handles a user joining a campaign via invite code (GET /join/:code). It lands them inside the campaign, with a welcome line when they have just joined, rather than on the campaign list where the new one is easy to miss.
func (*Handler) KeepSetupStepPost ¶
KeepSetupStepPost passes a step on and answers with the line, unfolded, so the owner sees the step tick where they pressed. POST /campaigns/:id/setup-steps/:step/keep
func (*Handler) LeaveCampaign ¶
LeaveCampaign is a member leaving by their own choice (POST /campaigns/:id/leave). It always acts on the signed-in person, never on a user id from the request, so nobody can make someone else leave.
func (*Handler) ListGroupsAPI ¶
ListGroupsAPI returns all groups for a campaign (GET /campaigns/:id/groups).
func (*Handler) LookDraftPictures ¶
func (h *Handler) LookDraftPictures(ctx context.Context, cc *CampaignContext, draft json.RawMessage) map[string]string
LookDraftPictures maps each picture the draft's look uses to a URL the page can show. A name the campaign neither stores nor owns is left out: a hand-edited draft must never make the page mint a URL for another campaign's file.
func (*Handler) ManageFigure ¶
ManageFigure is a Manage page's own figures, for the frame to draw beside the title (layouts.SetManageFigure). It builds them from the same service and providers the desk uses, so the page opened by address and the page reached from the desk show the same figures. It returns nil for anyone who is not the campaign's owner and when the figures cannot be read; the frame then draws nothing.
func (*Handler) ManageMast ¶
func (h *Handler) ManageMast(ctx context.Context) *layouts.ManageMast
ManageMast reads the banner for the campaign in the render context. The frame asks only for the owner; this checks again, since a banner names things only the owner should see on these pages. Nil when the campaign cannot be read, and the frame then draws its plain title.
func (*Handler) Members ¶
Members returns the member list as JSON for API consumers (Alpine.js pickers) or redirects HTML requests to the settings People tab.
func (*Handler) NewFoundryConnectLine ¶
NewFoundryConnectLine handles POST /campaigns/:id/extensions/foundry/connect-line (owner only): mints a new key and swaps the Foundry row for one that shows the full connect line once. Older keys keep working; nothing is revoked.
The response carries the raw key, so it is marked no-store and the line is never logged.
func (*Handler) OwnerDashboard ¶
OwnerDashboard renders the owner's desk (GET /campaigns/:id/dashboard): plain sentences in groups, with live numbers. The route is owner-only; the check here is the same belt and braces the other owner pages carry, since every number on the desk is the owner's alone.
func (*Handler) Picker ¶
Picker returns an HTMX fragment listing the user's campaigns for the topbar campaign selector dropdown. Loads lazily on dropdown open.
func (*Handler) PluginHub ¶
PluginHub redirects the legacy plugin hub page (GET /campaigns/:id/plugins) to the top-level Extensions hub, which now owns the per-campaign feature catalog. Sub-fragment route (`/plugins/fragment`) stays for any HTMX consumers still pointed at it.
func (*Handler) PluginHubFragment ¶
PluginHubFragment returns the plugin hub list content as an HTMX fragment. Used for in-place refresh after toggling features. GET /campaigns/:id/plugins/fragment
func (*Handler) PublishCustomizeAPI ¶
PublishCustomizeAPI handles POST /campaigns/:id/customize/publish: it applies every section of the stored draft, each by the code that owns it. A section that fails stays in the draft, with whatever of it was not applied, so one bad section never costs the owner the rest of their work.
func (*Handler) PutCustomizeDraftAPI ¶
PutCustomizeDraftAPI handles PUT /campaigns/:id/customize/draft. The page calls it (debounced) as the owner edits.
func (*Handler) PutLookPick ¶
PutLookPick stores or clears the caller's own pick for one part: PUT /campaigns/:id/my-look/:part. The service checks the current "who can change" setting and the value; the row is the caller's own.
func (*Handler) RegisterCustomizeSection ¶
func (h *Handler) RegisterCustomizeSection(s CustomizeSection)
RegisterCustomizeSection adds a section. Registration order is apply order, so a section that depends on another (a category's menu entry needs the look's sidebar settings saved first) registers after it. A bad or repeated key is logged and ignored: a plugin wiring mistake must not stop the server from booting.
func (*Handler) RegisterCustomizeTab ¶
func (h *Handler) RegisterCustomizeTab(factory func(*CampaignContext) CustomizeTab)
RegisterCustomizeTab appends a tab factory, called by other plugins at startup. A nil factory is ignored so a plugin that conditionally exposes a tab can pass its own nil through.
func (*Handler) RegisterDeskProvider ¶
func (h *Handler) RegisterDeskProvider(p DeskProvider)
RegisterDeskProvider lets another plugin fill one line of the desk with its own numbers, the way RegisterSettingsTab lets it add a settings tab.
func (*Handler) RegisterSettingsTab ¶
func (h *Handler) RegisterSettingsTab(factory func(*CampaignContext) SettingsTab)
RegisterSettingsTab adds a part-factory to the Data tab. Called by other plugins at startup; the factory runs per request with the current CampaignContext so the part's Content can capture per-request state.
func (*Handler) RemoveGroupMemberAPI ¶
RemoveGroupMemberAPI removes a user from a campaign group (DELETE /campaigns/:id/groups/:gid/members/:uid).
func (*Handler) RemoveMember ¶
RemoveMember removes a user from the campaign (DELETE /campaigns/:id/members/:uid).
func (*Handler) ResetDashboardLayout ¶
ResetDashboardLayout removes the custom dashboard layout (DELETE /campaigns/:id/dashboard-layout). Supports ?role=. If "default", resets entire layout; any other audience removes only its own layout.
func (*Handler) ResetOwnerDashboardLayout ¶
ResetOwnerDashboardLayout removes the custom owner dashboard layout (DELETE /campaigns/:id/owner-dashboard-layout).
func (*Handler) RevokeJoinCode ¶
RevokeJoinCode removes the shareable invite code (DELETE /campaigns/:id/join-code).
func (*Handler) RunByBlock ¶
RunByBlock draws the block, or an empty answer that removes the placeholder for a visitor or when no one can be named. GET /campaigns/:id/run-by
func (*Handler) SaveAppearanceAPI ¶
SaveAppearanceAPI handles PUT /campaigns/:id/appearance: one Save from the Customize page, carrying the whole draft.
func (*Handler) SaveHeroChangesSetting ¶
SaveHeroChangesSetting stores when players may change their hero's picks and redraws the section. Owner only, like the rest of People.
Route: POST /campaigns/:id/members/hero-changes
func (*Handler) SendTestEmailAPI ¶
SendTestEmailAPI handles POST /campaigns/:id/appearance/email-test. It sends the owner a sample game night invite in the picked layout, to the address on their own account only, so the route can't mail anyone else.
func (*Handler) SetAddonLister ¶
func (h *Handler) SetAddonLister(lister AddonLister)
SetAddonLister sets the addon lister for the plugin hub page.
func (*Handler) SetAuditLogger ¶
func (h *Handler) SetAuditLogger(logger AuditLogger)
SetAuditLogger sets the audit logger for recording campaign mutations. Called after all plugins are wired to avoid initialization order issues.
func (*Handler) SetBaseURL ¶
SetBaseURL sets the public-facing base URL for generating integration URLs (e.g. Foundry VTT module install URL).
func (*Handler) SetBrushPrefs ¶
func (h *Handler) SetBrushPrefs(p BrushPrefs)
SetBrushPrefs wires the person's brush choice.
func (*Handler) SetContentPacksCardRenderer ¶
func (h *Handler) SetContentPacksCardRenderer(r ContentPacksCardRenderer)
SetContentPacksCardRenderer wires the extensions plugin's renderer into the campaigns Handler. Called once at startup from `internal/app/routes.go` after both plugins' handlers exist. nil is tolerated — the hub renders without a Content Packs card if the extensions plugin is not wired (matches addons-store's tolerance of a nil AddonLister).
func (*Handler) SetCustomizeCategoryLister ¶
func (h *Handler) SetCustomizeCategoryLister(l CustomizeCategoryLister)
SetCustomizeCategoryLister wires the category source for the Customize page.
func (*Handler) SetCustomizeDrafts ¶
func (h *Handler) SetCustomizeDrafts(svc CustomizeDraftService)
SetCustomizeDrafts wires the draft store. Late-bound like the other optional collaborators; the draft routes answer 500 until it is set.
func (*Handler) SetEntityLister ¶
func (h *Handler) SetEntityLister(lister EntityTypeLister)
SetEntityLister sets the entity type lister for the settings page. Called after both plugins are wired to avoid circular dependencies.
func (*Handler) SetExtensionEnableChecker ¶
func (h *Handler) SetExtensionEnableChecker(c ExtensionEnableChecker)
SetExtensionEnableChecker wires the addons-store check into the campaigns Handler. Matches the SetAddonLister / SetSMTPChecker shape; called once at startup.
func (*Handler) SetFoundryConnector ¶
func (h *Handler) SetFoundryConnector(c FoundryConnector)
SetFoundryConnector wires the Foundry connection status and connect-line source for the Foundry page. Late-bound because the websocket hub it reads is built after the campaign handler.
func (*Handler) SetGroupService ¶
func (h *Handler) SetGroupService(svc GroupService)
SetGroupService sets the group service for campaign group management.
func (*Handler) SetHeroChanges ¶
SetHeroChanges hands in whether players' hero picks can lock in a campaign. The lock lives in the entities plugin: it is left out while its table is unhealthy, and it applies only to heroes players claim, which the claiming add-on allows. The composition root judges both, since campaigns names neither; the section and its Find entry show only where it is true, so they never offer a rule nothing would enforce.
func (*Handler) SetInviteBox ¶
func (h *Handler) SetInviteBox(invites InviteService, codes *GuestCodeService, baseURL string)
SetInviteBox wires the People page's Invite someone box.
func (*Handler) SetInviteLister ¶
func (h *Handler) SetInviteLister(svc InviteService)
SetInviteLister lets the desk say how many invitations still wait. The same service the invite routes use.
func (*Handler) SetInviteService ¶
func (h *Handler) SetInviteService(svc InviteService)
SetInviteService wires the invitations the People page's add form sends.
func (*Handler) SetMediaUploader ¶
func (h *Handler) SetMediaUploader(uploader MediaUploader)
SetMediaUploader sets the media uploader for backdrop image uploads.
func (*Handler) SetPageCategoryLookup ¶
func (h *Handler) SetPageCategoryLookup(l PageCategoryLookup)
SetPageCategoryLookup wires the page-to-category lookup the brush uses.
func (*Handler) SetPiecePlaceable ¶
SetPiecePlaceable sets the check "For your pages" uses to leave out a piece whose block is not registered (its plugin failed to start). Injected so campaigns need not import the entities block registry.
func (*Handler) SetRecentEntityLister ¶
func (h *Handler) SetRecentEntityLister(lister RecentEntityLister)
SetRecentEntityLister sets the recent entity lister for the dashboard. Called after both plugins are wired to avoid circular dependencies.
func (*Handler) SetSMTPChecker ¶
func (h *Handler) SetSMTPChecker(checker SMTPChecker)
SetSMTPChecker sets the SMTP configuration checker for the settings page.
func (*Handler) SetSheetChecker ¶
func (h *Handler) SetSheetChecker(c SheetChecker)
SetSheetChecker wires the sheet check "Your look" uses to leave out the character sheet styles when there is no sheet for them to dress.
func (*Handler) SetSystemAddonEnabler ¶
func (h *Handler) SetSystemAddonEnabler(enabler SystemAddonEnabler)
SetSystemAddonEnabler sets the addon enabler for auto-enabling game system addons when the user changes the Game System dropdown.
func (*Handler) SetSystemLister ¶
func (h *Handler) SetSystemLister(lister SystemLister)
SetSystemLister sets the system lister for the game system dropdown.
func (*Handler) SetTestMailer ¶
func (h *Handler) SetTestMailer(m TestMailer)
SetTestMailer wires the mail sender for "Send me a test".
func (*Handler) Settings ¶
Settings renders the campaign settings page (GET /campaigns/:id/settings). Supports ?tab= query param to open a specific tab (general, people, integrations, activity).
func (*Handler) SetupStepsBlock ¶
SetupStepsBlock draws the line, or an empty answer that removes the placeholder once all four are done. GET /campaigns/:id/setup-steps
func (*Handler) Show ¶
Show renders the campaign dashboard (GET /campaigns/:id). Uses role-aware dashboard layout: each role can have its own Campaign Page layout, falling back to the default layout.
func (*Handler) SidebarDrill ¶
SidebarDrill returns the drill-down panel content for a sidebar category (GET /campaigns/:id/sidebar/drill/:slug). The LayoutInjector populates entity types and counts into the context, and the Templ component finds the matching entity type by slug.
func (*Handler) ToggleViewAsPlayer ¶
ToggleViewAsPlayer is the header eye (POST /campaigns/:id/toggle-view-mode) for the owner and co-DMs: any preview on goes off, otherwise the player preview starts. Display only: access control still uses the real role.
func (*Handler) TransferForm ¶
TransferForm sends an old link to the transfer form (GET /campaigns/:id/transfer) to where it lives, on People.
func (*Handler) UnarchiveCampaign ¶
UnarchiveCampaign restores a soft-archived campaign (POST /campaigns/:id/unarchive).
func (*Handler) UpdateBrandingAPI ¶
UpdateBrandingAPI handles PUT /campaigns/:id/branding. Sets the campaign's custom brand name and optional logo path.
func (*Handler) UpdateDashboardLayout ¶
UpdateDashboardLayout saves a new dashboard layout (PUT /campaigns/:id/dashboard-layout). Supports ?role= (default/player/scribe/director/guest) to update one audience's layout.
func (*Handler) UpdateDefaultVisibilityAPI ¶
UpdateDefaultVisibilityAPI handles PUT /campaigns/:id/default-visibility. Sets the default visibility applied to newly created entities.
func (*Handler) UpdateDetailsAPI ¶
UpdateDetailsAPI saves the desk's name, description and public blanks (PUT /campaigns/:id/details). It is a partial update: a key the body does not carry keeps what is stored. Owner only, like every other campaign setting.
func (*Handler) UpdateDmGrantsAPI ¶
UpdateDmGrantsAPI handles PUT /campaigns/:id/dm-grants. Sets which users are granted visibility of dm_only content (co-DM privileges).
func (*Handler) UpdateEventTierDefinitionsAPI ¶
UpdateEventTierDefinitionsAPI handles PUT /campaigns/:id/event-tier-definitions. Replaces the campaign's tier vocabulary. Validation (exactly-one-default, non-empty array, unique slugs, hex color, prominence 0-100) runs at the service layer.
func (*Handler) UpdateGroupAPI ¶
UpdateGroupAPI updates a campaign group (PUT /campaigns/:id/groups/:gid).
func (*Handler) UpdateHandoverSettingAPI ¶
UpdateHandoverSettingAPI saves the owner's "If you're away" choice (PUT /campaigns/:id/handover-setting). Only the owner themself may set it: it decides when others can take their campaign, so a Co-DM can't.
func (*Handler) UpdateMemberCharacterAPI ¶
UpdateMemberCharacterAPI sets a member's character entity assignment. PUT /campaigns/:id/members/:uid/character
func (*Handler) UpdateNavPins ¶
UpdateNavPins stores the caller's own pinned sidebar rows for this campaign (PUT /campaigns/:id/nav-pins, body {"pins": ["app:x", "cat:12"]}) and returns what was stored.
func (*Handler) UpdateOwnerDashboardLayout ¶
UpdateOwnerDashboardLayout saves the owner dashboard layout (PUT /campaigns/:id/owner-dashboard-layout).
func (*Handler) UpdateRole ¶
UpdateRole changes a member's role (PUT /campaigns/:id/members/:uid/role).
func (*Handler) UpdateSidebarConfig ¶
UpdateSidebarConfig updates the sidebar configuration (PUT /campaigns/:id/sidebar-config).
func (*Handler) UpdateSystemID ¶
UpdateSystemID sets the game system for a campaign (PUT /campaigns/:id/system). Also auto-enables the corresponding addon so the system's widgets and scripts are immediately available without a separate toggle in the Features tab.
func (*Handler) UpdateWelcomeMessageAPI ¶
UpdateWelcomeMessageAPI handles PUT /campaigns/:id/welcome-message. Sets the campaign's MOTD banner displayed on the dashboard.
func (*Handler) UploadAppearancePictureAPI ¶
UploadAppearancePictureAPI handles POST /campaigns/:id/appearance/picture. It stores the file and returns its name; nothing changes on the campaign until the owner saves the draft that uses it.
func (*Handler) ViewAs ¶
ViewAs is the one preview switch (POST /campaigns/:id/view-as), for the owner and co-DMs. "self" ends any preview. With next=home it lands on Home; with next=arrange it first ends the preview, because the Customizer is a members' page a guest cannot open, then opens the owner's editor for that audience's dashboard.
type HandoverStatus ¶
type HandoverStatus struct {
OwnerPresence
// AfterMonths is the owner's setting; 0 means never.
AfterMonths int
// OpensAt is when an admin may hand over; zero when never.
OpensAt time.Time
// Open is true once the owner has been away longer than they allowed.
Open bool
}
HandoverStatus is what Admin › Campaigns shows about one campaign.
type HeroChangeForm ¶
type HeroChangeForm struct {
When string `form:"when"`
Making string `form:"after_making"`
MakingDays string `form:"making_days"`
Level string `form:"after_level"`
FromLevel string `form:"from_level"`
LevelDays string `form:"level_days"`
}
HeroChangeForm is the rule's form as posted. A ticked box sends any non-empty value; numbers arrive as typed.
func (HeroChangeForm) Rule ¶
func (f HeroChangeForm) Rule() (*HeroChangeRule, error)
Rule reads the form into a rule; nil is any time. It refuses only what the form alone can tell (a ticked "after making" with no days); the range checks are HeroChangeRule.Validate's, run when the rule is stored.
func (HeroChangeForm) Values ¶
func (f HeroChangeForm) Values(from HeroChangeFormValues) HeroChangeFormValues
Values is the form redrawn as it was posted, after a refusal, so what was typed can be put right. A number box left blank or unreadable keeps the number it showed before (from), unless its box was ticked, where it shows 0 so the blank stays visible.
type HeroChangeFormValues ¶
type HeroChangeFormValues struct {
Ruled bool
AfterMaking bool
MakingDays int
AfterLevel bool
FromLevel int
LevelDays int
}
HeroChangeFormValues is the form's starting state: the stored rule, or the suggested numbers where it sets none.
type HeroChangeRule ¶
type HeroChangeRule struct {
// AfterMakingDays opens the picks for this many days after the hero is
// made; 0 does not.
AfterMakingDays int `json:"after_making_days,omitempty"`
// AfterLevel opens them for AfterLevelDays days each time the hero
// reaches a new level of FromLevel or more (every level-up when FromLevel
// is 0, 1 or 2). A level window always has a length, so a Director never
// has to remember to close it.
AfterLevel bool `json:"after_level,omitempty"`
FromLevel int `json:"from_level,omitempty"`
AfterLevelDays int `json:"after_level_days,omitempty"`
}
HeroChangeRule is the Director's choice of when a player may change the picks of their own hero: for some days after making it, after reaching a level, or both. Outside those times the picks are locked until a Director reopens one hero. Players may always write their hero's name and story.
func (*HeroChangeRule) FormValues ¶
func (r *HeroChangeRule) FormValues() HeroChangeFormValues
FormValues is the form's starting state for this rule.
func (*HeroChangeRule) Summary ¶
func (r *HeroChangeRule) Summary() string
Summary says the rule in one sentence, as a Director reads it. A nil rule is any time.
func (*HeroChangeRule) Validate ¶
func (r *HeroChangeRule) Validate() error
Validate refuses a rule that opens nothing or holds numbers out of range.
type HeroChangesSetting ¶
type HeroChangesSetting struct {
CampaignID string
CSRFToken string
Summary string
// Ruled is whether a rule is stored, which is when the Characters page
// lists each hero to reopen.
Ruled bool
Form HeroChangeFormValues
// Notice confirms a save; Err says why one was refused. Both empty on a
// plain page load.
Notice string
Err string
}
HeroChangesSetting is what the section draws.
type HomeSeen ¶
HomeSeen is what the block needs to know about one member: when they last pressed "Mark as seen" (nil if never) and when they joined, which stands in until they have.
type HomeSeenStore ¶
type HomeSeenStore interface {
// Get returns the member's marker; ok is false when the user is not a
// member of the campaign.
Get(ctx context.Context, campaignID, userID string) (seen HomeSeen, ok bool, err error)
// Mark moves the member's marker to at, and reports whether a member row
// was there to move.
Mark(ctx context.Context, campaignID, userID string, at time.Time) (bool, error)
}
HomeSeenStore reads and moves a member's marker.
func NewHomeSeenStore ¶
func NewHomeSeenStore(db *sql.DB) HomeSeenStore
NewHomeSeenStore creates the MariaDB-backed store.
type IDMap ¶
type IDMap struct {
// EntityTypeIDs maps original entity type ID → new entity type ID.
EntityTypeIDs map[int]int
// EntityIDs maps original entity ID → new entity ID.
EntityIDs map[string]string
// EntitySlugToID maps entity slug → new entity ID (for cross-references).
EntitySlugToID map[string]string
// TagIDs maps original tag ID → new tag ID.
TagIDs map[int]int
// TagSlugToID maps tag slug → new tag ID.
TagSlugToID map[string]int
// MediaIDs maps original media file ID → the restored file's new ID.
MediaIDs map[string]string
// MapIDs maps original map ID → new map ID.
MapIDs map[string]string
// CampaignID is the new campaign's ID.
CampaignID string
// CalendarID is the new calendar's ID (if created).
CalendarID string
// CalendarIDs maps original calendar ID → new calendar ID.
CalendarIDs map[string]string
// CalendarEventIDs maps original calendar event ID → new event ID.
CalendarEventIDs map[string]string
}
IDMap tracks the mapping from original IDs in the export to newly created IDs. Used during import to remap all foreign key references.
type ImportFailure ¶
type ImportFailure struct {
// Section is the export envelope section the object came from,
// e.g. "notes", "maps", "entities".
Section string
// Kind is a singular human noun for the object, e.g. "note",
// "map marker". Used to build the summary line.
Kind string
// Name is the best identifier available for the object — usually its
// title. May be empty for objects that have no name.
Name string
// Reason is a short, user-safe cause. Never a raw driver error.
Reason string
// Count is how many objects this record stands for. Normally 1. A
// section that loses a whole homogeneous batch — every media file in a
// zip, say — records it once with the real count rather than emitting
// hundreds of identical rows, so the tally stays exact without burying
// the interesting failures.
Count int
}
ImportFailure records one object the import could not create.
type ImportMediaBundle ¶
type ImportMediaBundle struct {
// contains filtered or unexported fields
}
ImportMediaBundle is the media/ entries of an uploaded ZIP export.
func NewImportMediaBundle ¶
func NewImportMediaBundle(r *zip.Reader) (*ImportMediaBundle, error)
NewImportMediaBundle indexes a zip's media/ entries by their basename. Entries in sub-folders or with unsafe names are ignored; more media entries than an import may carry is refused.
func (*ImportMediaBundle) Len ¶
func (b *ImportMediaBundle) Len() int
Len is the number of media entries in the zip.
func (*ImportMediaBundle) Read ¶
func (b *ImportMediaBundle) Read(f ExportMediaFile) (data []byte, ok bool, err error)
Read returns the bytes of the zip entry for a manifest row: by its Filename, or for a manifest written before Filename existed, by the entry named after its OriginalID. ok is false when the zip has no such entry.
func (*ImportMediaBundle) ReadAtMost ¶
func (b *ImportMediaBundle) ReadAtMost(f ExportMediaFile, limit int64) (data []byte, ok bool, err error)
ReadAtMost is Read for a file that may be at most limit bytes, the instance's upload limit: a larger entry is refused before it is inflated, from the size the zip declares, and again while reading, in case the declaration lies.
type ImportReport ¶
type ImportReport struct {
// contains filtered or unexported fields
}
ImportReport accumulates per-object failures during a campaign import.
All methods are safe on a nil receiver so an adapter can be exercised without one, and safe under concurrent use so a future parallel importer does not have to revisit this.
func NewImportReport ¶
func NewImportReport() *ImportReport
NewImportReport returns an empty report.
func (*ImportReport) Count ¶
func (r *ImportReport) Count() int
Count returns the exact number of failed objects, including any beyond the detail cap.
func (*ImportReport) CountsByKind ¶
func (r *ImportReport) CountsByKind() []KindCount
CountsByKind returns per-kind totals, largest first then alphabetical, so the summary line is stable between runs. Failures beyond the detail cap are attributed to the kind they were recorded under, which is why the cap is generous: the shape of a partial import matters as much as its size.
func (*ImportReport) Fail ¶
func (r *ImportReport) Fail(section, kind, name, reason string)
Fail records one failed object. reason should already be user-safe; callers holding a raw error should pass apperror.SafeMessage(err).
func (*ImportReport) FailN ¶
func (r *ImportReport) FailN(section, kind, name, reason string, n int)
FailN records n identical failures as a single detail row. Use it when a whole homogeneous batch is lost for one reason; use Fail when the objects are individually worth naming.
func (*ImportReport) Failures ¶
func (r *ImportReport) Failures() []ImportFailure
Failures returns a copy of the retained failure detail.
func (*ImportReport) HasFailures ¶
func (r *ImportReport) HasFailures() bool
HasFailures reports whether anything was dropped.
func (*ImportReport) Summary ¶
func (r *ImportReport) Summary() string
Summary renders the failure tally as one line naming how many of what failed, e.g. "3 notes, 1 map marker". Empty string when nothing failed.
func (*ImportReport) Truncated ¶
func (r *ImportReport) Truncated() int
Truncated returns how many failures were counted but not retained in detail. Non-zero means the detail list is incomplete; the count is not.
type InvitationSource ¶
type InvitationSource struct {
// contains filtered or unexported fields
}
InvitationSource answers the door's three lookups: a share link, an emailed invite and a guest code. Anything not valid right now, including a campaign that is archived or in the Trash, gives nil, so the pages stay plain and never confirm what is real.
func NewInvitationSource ¶
func NewInvitationSource(campaigns CampaignRepository, invites InviteRepository, codes *GuestCodeService, nextNight NextNightFunc) *InvitationSource
NewInvitationSource builds the door's lookups. nextNight may be nil.
func (*InvitationSource) ByGuestCode ¶
func (s *InvitationSource) ByGuestCode(ctx context.Context, code string) *auth.Invitation
ByGuestCode reads the invitation for a guest code that is still live.
func (*InvitationSource) ByLink ¶
func (s *InvitationSource) ByLink(ctx context.Context, code string) *auth.Invitation
ByLink reads the invitation for a campaign's share link.
func (*InvitationSource) ByToken ¶
func (s *InvitationSource) ByToken(ctx context.Context, token string) *auth.Invitation
ByToken reads the invitation for an emailed invite that is unused and unexpired.
type Invite ¶
type Invite struct {
ID string `json:"id"`
CampaignID string `json:"campaign_id"`
Email string `json:"email"`
Role string `json:"role"`
Token string `json:"-"` // Never exposed in JSON.
CreatedBy string `json:"created_by"`
CreatedAt time.Time `json:"created_at"`
ExpiresAt time.Time `json:"expires_at"`
AcceptedAt *time.Time `json:"accepted_at,omitempty"`
// Joined from users table for display.
CreatedByName string `json:"created_by_name,omitempty"`
}
Invite represents a pending invitation for a user to join a campaign.
type InviteBoxData ¶
type InviteBoxData struct {
CampaignID string
CSRF string
Now time.Time
// LinkURL is the campaign's live invite link, "" when there is none.
LinkURL string
// Invites are the emailed invites not yet accepted.
Invites []Invite
// Codes are the guest codes still open, plus the ones in use as a
// look-around pass, which keep Make player and End now.
Codes []GuestCode
// Fresh is a code just made: the only time it is shown.
Fresh *NewGuestCode
// JoinURL is the join page a code is typed at.
JoinURL string
// Mode is the choice left open: email, link or code.
Mode string
// Done is a plain confirmation; Err a refusal.
Done, Err string
// Figure redraws the People page's figures beside its title in place; the
// box's own changes move its invited count.
Figure templ.Component
// DoneLink is an invite's accept link, shown once when the site can't
// email it, so the owner can send it themselves.
DoneLink string
// EmailReady is false when the site can't send email.
EmailReady bool
}
InviteBoxData is everything the People page's "Invite someone" box draws: the three ways in, and the one list of whatever is still waiting.
type InviteHandler ¶
type InviteHandler struct {
// contains filtered or unexported fields
}
InviteHandler handles HTTP requests for campaign invites.
func NewInviteHandler ¶
func NewInviteHandler(service InviteService, campaigns CampaignService, baseURL string) *InviteHandler
NewInviteHandler creates a new invite handler.
func (*InviteHandler) AcceptInvitePage ¶
func (h *InviteHandler) AcceptInvitePage(c *echo.Context) error
AcceptInvitePage handles invite acceptance. GET /invites/accept?token=xxx
func (*InviteHandler) CreateInviteAPI ¶
func (h *InviteHandler) CreateInviteAPI(c *echo.Context) error
CreateInviteAPI creates a new campaign invite. POST /campaigns/:id/invites
func (*InviteHandler) ListInvitesAPI ¶
func (h *InviteHandler) ListInvitesAPI(c *echo.Context) error
ListInvitesAPI returns all invites for a campaign as JSON. GET /campaigns/:id/invites
func (*InviteHandler) RevokeInviteAPI ¶
func (h *InviteHandler) RevokeInviteAPI(c *echo.Context) error
RevokeInviteAPI deletes a pending invite. DELETE /campaigns/:id/invites/:inviteId
func (*InviteHandler) SetInvitations ¶
func (h *InviteHandler) SetInvitations(src *InvitationSource)
SetInvitations wires the invitation card on the accept page.
type InviteMailer ¶
type InviteMailer interface {
SendHTMLMail(ctx context.Context, to []string, subject, plainBody, htmlBody string) error
IsConfigured(ctx context.Context) bool
}
InviteMailer sends invite emails. Subset of smtp.MailService to avoid importing the smtp package directly.
type InviteRepository ¶
type InviteRepository interface {
Create(ctx context.Context, invite *Invite) error
GetByToken(ctx context.Context, token string) (*Invite, error)
ListByCampaign(ctx context.Context, campaignID string) ([]Invite, error)
MarkAccepted(ctx context.Context, id string) (bool, error)
// Delete removes an invite of the given campaign and reports whether a row
// was deleted, so a foreign or unknown ID is distinguishable from success.
Delete(ctx context.Context, campaignID, id string) (bool, error)
DeleteExpired(ctx context.Context, campaignID string) (int64, error)
GetByEmailAndCampaign(ctx context.Context, email, campaignID string) (*Invite, error)
}
InviteRepository handles persistence for campaign invites.
func NewInviteRepository ¶
func NewInviteRepository(db *sql.DB) InviteRepository
NewInviteRepository creates a new invite repository.
type InviteService ¶
type InviteService interface {
CreateInvite(ctx context.Context, campaignID, createdBy string, input CreateInviteInput) (*Invite, error)
ListInvites(ctx context.Context, campaignID string) ([]Invite, error)
RevokeInvite(ctx context.Context, campaignID, inviteID string) error
AcceptInvite(ctx context.Context, token string, userID string) (*Invite, error)
GetInviteByToken(ctx context.Context, token string) (*Invite, error)
}
InviteService handles business logic for campaign invites.
func NewInviteService ¶
func NewInviteService(repo InviteRepository, campaigns CampaignRepository, mailer InviteMailer, baseURL string) InviteService
NewInviteService creates a new invite service.
type LayoutPresetSeeder ¶
LayoutPresetSeeder seeds default layout presets when a campaign is created. Implemented by the entities plugin's LayoutPresetService.
type LeaveNotifier ¶
type LeaveNotifier interface {
// MemberLeft writes one bell row to each of userIDs. action is the label
// of the link, shown under the line.
MemberLeft(ctx context.Context, campaignID string, userIDs []string, message, detail, action, link string) error
}
LeaveNotifier tells the owner somebody left. The sessions plugin's notification store sits behind it.
type LeaveView ¶
LeaveView is what My campaigns needs to draw each card's menu: which campaigns the person owns (they hand over instead) and, for the rest, the characters that would go back to the table.
type ListOptions ¶
ListOptions holds pagination parameters for list queries.
func DefaultListOptions ¶
func DefaultListOptions() ListOptions
DefaultListOptions returns sensible defaults for pagination.
func (ListOptions) Offset ¶
func (o ListOptions) Offset() int
Offset returns the SQL OFFSET value for the current page.
type LookAccessInput ¶
type LookAccessInput struct {
Sheet string `json:"sheet"`
Page string `json:"page"`
Hover string `json:"hover"`
DmScreen string `json:"dmscreen"`
}
LookAccessInput is the "who can change" part of a Save from the Customize page. Empty means the part's default.
type LookPart ¶
type LookPart struct {
Key string
Label string
Choices []string // The values a pick may take; also the campaign look's own list.
// Settings are the access settings the owner may give this part.
Settings []string
Default string // Access setting used while the owner has not set one.
}
LookPart describes one part of the look a member may own a pick of.
func LookPartByKey ¶
LookPartByKey returns the part with the given key.
func PickableParts ¶
func PickableParts(ap *Appearance, cc *CampaignContext) []LookPart
PickableParts lists the parts the viewer may pick for themselves right now.
func ShownLookParts ¶
ShownLookParts drops the character sheet part when hasSheet says the campaign has no sheet: its styles would save and change nothing the member can find. hasSheet is asked only when the sheet part is there, and a nil check keeps every part.
func ValidateLookPick ¶
func ValidateLookPick(ap *Appearance, cc *CampaignContext, partKey, value string) (LookPart, error)
ValidateLookPick checks a member's pick before it is stored: the part must exist, the person must be allowed to pick it now, and the value must be one of the part's choices. An empty value is a reset and always passes.
func (LookPart) Access ¶
func (p LookPart) Access(ap *Appearance) string
Access is the setting in force for p. An empty or unknown stored value, or one the part does not allow (a hand-edited "everyone" on the DM Screen), reads as the part's default, so a bad value can never widen access.
func (LookPart) MayPick ¶
func (p LookPart) MayPick(ap *Appearance, cc *CampaignContext) bool
MayPick reports whether the viewer can keep a personal pick of p. The owner never does: their choice is the campaign's look itself.
type LookSummary ¶
type LookSummary struct {
Look, Colour, Pages string
}
LookSummary is the look in a DM's words: the starter look's name or "Custom", the colour's name ("" for a colour of the owner's own, which the row shows as its swatch alone) and the page style.
type MailService ¶
type MailService interface {
SendMail(ctx context.Context, to []string, subject, body string) error
IsConfigured(ctx context.Context) bool
}
MailService is the interface for sending email. Implemented by the SMTP plugin. Campaigns depends on this for ownership transfer emails. May be nil if SMTP is not configured.
type MapExporter ¶
type MapExporter interface {
ExportMaps(ctx context.Context, campaignID string, entitySlugLookup func(string) string) ([]ExportMap, error)
}
MapExporter gathers map data for a campaign export.
type MapImporter ¶
type MapImporter interface {
ImportMaps(ctx context.Context, campaignID, userID string, data []ExportMap, idMap *IDMap, report *ImportReport) error
}
MapImporter creates maps from import data.
type MediaBundler ¶
type MediaBundler interface {
BundleMedia(ctx context.Context, campaignID string) ([]BundledMediaFile, error)
}
MediaBundler returns the per-campaign media files paired with byte readers. Used by the export handler to build a zip-with-bytes when the caller opts in via ?include_media=1. Separate from MediaExporter because the JSON-only export path doesn't need the byte-opener machinery and shouldn't pay for it.
type MediaCleaner ¶
type MediaCleaner interface {
DeleteCampaignFiles(ctx context.Context, campaignID string) (int, error)
}
MediaCleaner handles bulk media file cleanup during campaign deletion. Implemented by the media service.
type MediaExporter ¶
type MediaExporter interface {
ExportMedia(ctx context.Context, campaignID string) ([]ExportMediaFile, error)
}
MediaExporter gathers media file metadata for a campaign export.
type MediaImporter ¶
type MediaImporter interface {
ImportMedia(ctx context.Context, campaignID, userID string, files []ExportMediaFile, bundle *ImportMediaBundle, idMap *IDMap, report *ImportReport) error
}
MediaImporter restores media files from an import, recording each original id's new id on idMap.MediaIDs. bundle is nil for a JSON-only upload, which carries no file bytes.
type MediaUploader ¶
type MediaUploader interface {
UploadBackdrop(ctx context.Context, campaignID, userID string, fileBytes []byte, originalName, mimeType string) (filename string, err error)
// OwnsFile reports whether filename is a media file uploaded to campaignID.
OwnsFile(ctx context.Context, campaignID, filename string) (bool, error)
// DeletePicture removes filename only if campaignID owns it and it was
// uploaded as an appearance picture; it reports whether it deleted
// anything. Any other file is left alone and is not an error.
DeletePicture(ctx context.Context, campaignID, filename string) (bool, error)
}
MediaUploader uploads media files for campaign backdrops. Avoids importing the media package directly.
type MemberListView ¶
type MemberListView struct {
Members []CampaignMember
Removed []MemberUser
CSRFToken string
ErrMsg string
Notice string
// NoticeLink is a link the owner passes on by hand, shown under Notice.
NoticeLink string
// Figure redraws the People page's figures beside its title in place
// after a change; nil when the page itself is being drawn.
Figure templ.Component
// HeroChanges is the "Changing heroes" section, drawn with the page
// only; nil for a list redraw and for anyone but the owner.
HeroChanges *HeroChangesSetting
}
MemberListView is what the member list draws: the members, the people the owner removed, and one message from the action just taken.
type MemberLister ¶
type MemberLister interface {
ListMembers(ctx context.Context, campaignID string) ([]CampaignMember, error)
}
MemberLister provides campaign membership data. Defined here so plugins (timeline, sessions, etc.) can depend on campaigns.MemberLister instead of duplicating the interface.
type MemberUser ¶
MemberUser is the minimal user info needed for membership operations.
type NavAccess ¶
type NavAccess int
NavAccess is the least a viewer needs to open an app's page. The sidebar never offers a row whose page would turn the viewer away.
const ( )
type NavApp ¶
type NavApp struct {
// never arranged the sidebar; every other app starts in Apps.
DefaultPinned bool
// hidden from them, say). Only the owner, who can fill it, still gets it.
Empty bool
}
NavApp is one app page the sidebar can list, resolved for a campaign.
type NavCategory ¶
type NavCategory struct {
}
NavCategory is a top-level category and its sub-categories.
type NavCategoryPlace ¶
type NavCategoryPlace struct {
}
NavCategoryPlace is one top-level category where the sidebar draws it: its section's id and title.
func NavCategoryOrder ¶
func NavCategoryOrder(items []SidebarItem, apps []NavApp, cats []NavCategory) []NavCategoryPlace
NavCategoryOrder lists every known category in the order the sidebar draws them, section by section, with where each sits.
type NavLayout ¶
type NavLayout struct {
Drawer []NavLayoutItem `json:"drawer"`
}
NavLayout is the owner's arrangement after normalization: the built-in sections, then the owner's own, each listing its items in order. It is also what the owner's editor starts from, so it keeps items a viewer would not see (hidden rows, apps turned off in Extensions).
func NormalizeNav ¶
func NormalizeNav(items []SidebarItem, apps []NavApp, cats []NavCategory) NavLayout
NormalizeNav reads the stored items into sections. apps lists every app the campaign could show, turned on or not, and cats every top-level category; items naming anything else are dropped, as are repeats.
Items saved before sections existed carry no section. They land where the old sidebar drew them: an app or link under a section heading stays in that section, any other app or link was in the list at the top (now Pinned), and a category stays in Categories. A heading the old editor saved hidden is no section for anyone: the rows after it stay under the visible heading before it, and an item naming it goes to its home section. Apps that are turned on but missing join Apps, or their default section when the owner never arranged anything, and categories that are missing join Categories, so nothing is ever left out.
type NavLayoutItem ¶
type NavLayoutItem struct {
}
NavLayoutItem is one item of a NavLayout, addressed by its key. A link carries its own label, target and icon.
type NavLayoutSection ¶
type NavLayoutSection struct {
}
NavLayoutSection is one section of a NavLayout. Label is set for the owner's own sections; the built-in ones are named by the sidebar.
type NavRow ¶
NavRow is one row of a viewer's sidebar.
func NavDrawerRows ¶
NavDrawerRows lists the apps kept in the drawer only that this viewer may open, as ViewNav would draw them, leaving out the ones they pinned (those are in their Pinned). A row hidden from players reaches only the owner.
type NavSection ¶
type NavSection struct {
}
NavSection is one section of a viewer's sidebar. Kind is the section's id for the built-in sections and NavKindCustom for the owner's own.
func AppendManagePins ¶
func AppendManagePins(secs []NavSection, pins []string, base string, media, foundry bool) []NavSection
AppendManagePins adds the owner's pinned Manage tools to the end of Pinned, marked personal. A tool whose add-on is off, or a key no tool has any more, is skipped rather than shown: a pin never outlives what it points at.
func ViewNav ¶
func ViewNav(layout NavLayout, apps []NavApp, cats []NavCategory, viewer NavViewer) []NavSection
ViewNav cuts a layout down to what one viewer's sidebar shows. A row hidden from players is kept only for an owner, and marked. An app is kept only when it is turned on, the viewer may open its page and, unless they own the campaign, it holds something they may see; a link only when its target is safe to follow. A non-owner's own pins then move their rows into Pinned, after the campaign's pins, so no row is ever shown twice.
type NavSectionsSource ¶
type NavSectionsSource interface {
}
NavSectionsSource draws a member's sidebar as ViewNav does, before their own pins are applied. The composition root provides it, because only it knows every plugin's apps and addons.
type NavSubcategory ¶
type NavSubcategory struct {
}
NavSubcategory is a sub-category, drawn as its own row under its parent.
type NavViewer ¶
type NavViewer struct {
// owner who is viewing the campaign as a player.
Owner bool
Access NavAccess
// non-owner has them; the owner pins for everyone in the layout itself.
Pins []string
}
NavViewer is who a sidebar is drawn for.
type NeedsYouItem ¶
type NeedsYouItem struct {
Lead string // the row's name
Rest string // what is wrong, in a few words
URL string // where the row goes
// State is the dot before the row: "warn" or "" for a plain dot. Amber
// here means state only; the Director's amber edge is never used.
State string
}
NeedsYouItem is one thing waiting on the owner, drawn like any other row of the page under "Needs you": its name, what is wrong in grey, and the whole row leading to it.
type NewGuestCode ¶
NewGuestCode is a freshly made code, shown to the owner once.
type NextNightFunc ¶
type NextNightFunc func(ctx context.Context, campaignID string, now time.Time) *auth.InvitationNight
NextNightFunc finds a campaign's next planned game night, nil when none. It is supplied by the app so campaigns imports no sessions code.
type NoteExporter ¶
type NoteExporter interface {
ExportNotes(ctx context.Context, campaignID string, entitySlugLookup func(string) string) ([]ExportNote, error)
}
NoteExporter gathers shared notes for a campaign export.
type NoteImporter ¶
type NoteImporter interface {
ImportNotes(ctx context.Context, campaignID, userID string, data []ExportNote, idMap *IDMap, report *ImportReport) error
}
NoteImporter creates notes from import data.
type OwnedCampaign ¶
OwnedCampaign is a campaign that stops its owner deleting their account until it is handed over or deleted. Archived campaigns count too.
type OwnerPresence ¶
OwnerPresence is who owns a campaign and when they last used the site.
type OwnershipTransfer ¶
type OwnershipTransfer struct {
ID string `json:"id"`
CampaignID string `json:"campaign_id"`
FromUserID string `json:"from_user_id"`
ToUserID string `json:"to_user_id"`
Token string `json:"-"` // Never expose in JSON.
ExpiresAt time.Time `json:"expires_at"`
CreatedAt time.Time `json:"created_at"`
}
OwnershipTransfer represents a pending campaign ownership transfer.
type PageCategoryLookup ¶
type PageCategoryLookup interface {
PageCategory(ctx context.Context, campaignID, entityID string) (typeID int, ok bool, err error)
}
PageCategoryLookup says which category a page of this campaign is in, so the brush can offer that category's page layout. False when the page is not this campaign's or does not exist.
type PluginHubAddon ¶
type PluginHubAddon struct {
AddonID int
Slug string
Name string
// Description is the addon's canonical one-line blurb, sourced from
// the addons service's single builtinAddons copy rather than
// re-derived or hand-maintained per render site (ADR-056).
Description string
Icon string
Category string
Enabled bool
Installed bool // Whether backing code exists (for showing Coming Soon vs toggle).
HasDashboard bool
// HasSetup is true when the addon has a registered SetupProvider (an
// extension settings/onboarding page). NeedsSetup is true when that page has
// outstanding, actionable checks for this campaign — the card shows a "Setup"
// nudge until the owner completes or dismisses it.
HasSetup bool
NeedsSetup bool
}
PluginHubAddon is a minimal addon representation for the plugin hub page and the top-level Extensions hub.
HasDashboard is set by addonListerAdapter for apps with a dedicated dashboard page (extensions_hub.go); those cards gain an "Open dashboard" link.
type PostExporter ¶
type PostExporter interface {
ExportPosts(ctx context.Context, campaignID string, entitySlugLookup func(string) string) ([]ExportPost, error)
}
PostExporter gathers entity posts (sub-notes) for export.
type PostImporter ¶
type PostImporter interface {
ImportPosts(ctx context.Context, campaignID, userID string, data []ExportPost, idMap *IDMap, report *ImportReport) error
}
PostImporter creates entity posts from import data.
type QuestExporter ¶
type QuestExporter interface {
ExportQuests(ctx context.Context, campaignID string) ([]ExportQuest, error)
}
QuestExporter gathers every quest sheet for a campaign export.
type QuestImporter ¶
type QuestImporter interface {
ImportQuests(ctx context.Context, campaignID, userID string, data []ExportQuest, idMap *IDMap, report *ImportReport) error
}
QuestImporter restores quest sheets onto the imported pages, using idMap to point their page, map and calendar-event references at the new campaign.
type RecentEntity ¶
type RecentEntity struct {
ID string
Name string
TypeName string
TypeIcon string
TypeColor string
ImagePath *string
IsPrivate bool
UpdatedAt time.Time
}
RecentEntity is a minimal entity representation for the dashboard recent pages section.
type RecentEntityLister ¶
type RecentEntityLister interface {
ListRecentForDashboard(ctx context.Context, campaignID string, role int, userID string, limit int) ([]RecentEntity, error)
}
RecentEntityLister returns recently updated entities for the campaign dashboard. Avoids importing the entities package directly.
type RecipeExporter ¶
type RecipeExporter interface {
ExportRecipes(ctx context.Context, campaignID string) ([]ExportRecipe, error)
}
RecipeExporter gathers crafting recipes for a campaign export.
type RecipeImporter ¶
type RecipeImporter interface {
ImportRecipes(ctx context.Context, campaignID, userID string, data []ExportRecipe, idMap *IDMap, report *ImportReport) error
}
RecipeImporter restores crafting recipes, using idMap for the item and character pages they name.
type Role ¶
type Role int
Role represents a user's permission level within a campaign. Higher numeric values indicate more permissions. Use >= comparisons:
if role >= RoleScribe { /* allow content creation */ }
const ( // RoleNone indicates the user has no membership in the campaign. // Used when a site admin accesses a campaign they haven't joined. RoleNone Role = 0 // RolePlayer grants read access to permitted content. Default role on join. RolePlayer Role = 1 // RoleScribe grants create/edit access to notes and entities. // The TTRPG note-taker / co-author. RoleScribe Role = 2 // RoleOwner grants full control over the campaign. One per campaign. // Can transfer ownership, manage members, and change settings. RoleOwner Role = 3 )
func RoleFromString ¶
RoleFromString converts a database role string to a Role constant.
func (Role) DisplayName ¶
DisplayName returns a human-readable label for the role.
type RoleDashboardLayouts ¶
type RoleDashboardLayouts struct {
Default *DashboardLayout `json:"default,omitempty"`
Player *DashboardLayout `json:"player,omitempty"`
Scribe *DashboardLayout `json:"scribe,omitempty"`
Director *DashboardLayout `json:"director,omitempty"`
Guest *DashboardLayout `json:"guest,omitempty"`
}
RoleDashboardLayouts holds per-role campaign page layouts. When the dashboard_layout column uses the new role-keyed format, each role can have its own layout. Players, Scribes and the Director fall back to Default when their own layout is nil; guests fall back to DefaultGuestDashboardLayout instead, so a home arranged for members never reaches a visitor.
type RollTableExporter ¶
type RollTableExporter interface {
ExportRollTables(ctx context.Context, campaignID string) (json.RawMessage, error)
}
RollTableExporter returns the campaign's rolling-tables document, or nil when it has none.
type RollTableImporter ¶
type RollTableImporter interface {
ImportRollTables(ctx context.Context, campaignID, userID string, data json.RawMessage, report *ImportReport) error
}
RollTableImporter restores the rolling-tables document.
type SMTPChecker ¶
SMTPChecker reports whether SMTP email delivery is configured. Used to show warnings on the settings page when email is unavailable.
type SessionExporter ¶
type SessionExporter interface {
ExportSessions(ctx context.Context, campaignID string, entitySlugLookup func(string) string) ([]ExportSession, error)
}
SessionExporter gathers session data for a campaign export.
type SessionImporter ¶
type SessionImporter interface {
ImportSessions(ctx context.Context, campaignID, userID string, data []ExportSession, idMap *IDMap, report *ImportReport) error
}
SessionImporter creates sessions from import data.
type SettingsEntityType ¶
type SettingsEntityType struct {
ID int `json:"id"`
Name string `json:"name"`
NamePlural string `json:"name_plural"`
Icon string `json:"icon"`
Color string `json:"color"`
Description *string `json:"description,omitempty"`
ParentTypeID *int `json:"parent_type_id,omitempty"`
}
SettingsEntityType is a minimal entity type representation for the settings and customization pages. Includes Description for the Category Dashboards tab.
type SettingsTab ¶
type SettingsTab struct {
ID string
Label string
Icon string
MinRole Role
SortOrder int
Content templ.Component
}
SettingsTab is one part another plugin adds to the Data tab.
- ID: stable slug, the part's anchor on Data (`/data#<id>`) and the old `/settings?tab=<id>` address that redirects there; keep it URL-safe and stable (bookmarks rely on it).
- Label/Icon: the part's heading, and the icon Find shows beside it.
- MinRole gates the part; a viewer below it does not get it.
- SortOrder orders the parts (multiples of 10) so a plugin can place its part between others.
- Content is the part's body, built per request by the plugin's factory.
type SheetChecker ¶
SheetChecker reports whether a campaign's game system draws a character sheet. Avoids importing the systems package.
type SidebarConfig ¶
type SidebarConfig struct {
// Items is the unified, ordered list of all sidebar items. Each item
// has a type (dashboard, addon, category, section, link, all_pages)
// and is rendered in array order. Owners can reorder, show/hide any item.
Items []SidebarItem `json:"items,omitempty"`
// HiddenEntityIDs is a set of individual entity IDs that should be
// hidden from the sidebar for non-owner roles.
HiddenEntityIDs []string `json:"hidden_entity_ids,omitempty"`
// HiddenNodeIDs is a set of sidebar folder node IDs that should be
// hidden from the sidebar for non-owner roles.
HiddenNodeIDs []string `json:"hidden_node_ids,omitempty"`
}
SidebarConfig holds campaign-level sidebar customization settings. Stored as JSON in campaigns.sidebar_config. Controls the ordered list of sidebar items plus the sets of individually-hidden entities and folder nodes. This is the single, unified sidebar model; the EnsureSidebarItems boot reconciler converts any straggler campaign onto Items (see sidebar_reconcile.go). An empty Items array is valid — it renders the default sidebar, synthesized by the render injector.
type SidebarItem ¶
type SidebarItem struct {
Type string `json:"type"` // "app" (or its older spelling "addon"), "category", "section", "link"; "dashboard" and "all_pages" in older configs
// Visible false hides the item from players. The owner still sees it,
// marked as hidden, so they can reach what they hid while they prep.
Visible bool `json:"visible"`
Slug string `json:"slug,omitempty"` // App slug (for type=app/addon).
TypeID int `json:"type_id,omitempty"` // Entity type ID (for type=category).
ID string `json:"id,omitempty"` // Unique ID (for sections/links).
Label string `json:"label,omitempty"` // Display label (for sections/links).
URL string `json:"url,omitempty"` // Link URL (for type=link).
Icon string `json:"icon,omitempty"` // FontAwesome icon (for type=link).
// Section is the section the item sits in: "pinned", "apps",
// "categories" or the id of one of the owner's sections. Empty on items
// saved before sections existed; NormalizeNav places those where the old
// sidebar drew them.
Section string `json:"section,omitempty"`
}
SidebarItem represents a single item in the unified sidebar navigation. Apps, categories, the owner's sections and links are all items, so owners can arrange everything with one mechanism; nav.go reads them into sections.
Nesting is intentionally NOT a field here. Whether a category renders nested under a parent is derived from entity_types.parent_type_id (the structural source of truth); a persisted "nested" flag would be a second source of truth that can drift.
func OrderNavCategories ¶
func OrderNavCategories(items []SidebarItem, apps []NavApp, cats []NavCategory, order []int) []SidebarItem
OrderNavCategories returns items with the categories in order (first wanted first) rearranged among themselves inside the section each sits in. Every other row, and every category order leaves out, keeps its place, so the owner's sections, apps and links are untouched and no category changes section.
A category the owner never arranged has no row, so one is written where the sidebar already draws it (the end of Categories) before the order applies. A sidebar never arranged at all also gets its default-pinned apps written: once any row is stored the sidebar treats the layout as arranged and would otherwise move those apps out of Pinned.
type SiteLookSource ¶
SiteLookSource reads the site-wide look an admin chose. The settings service implements it; campaigns reaches it only through this interface so the two plugins stay independent.
type SystemAddonEnabler ¶
type SystemAddonEnabler interface {
EnableSystemForCampaign(ctx context.Context, campaignID, systemSlug, userID string) error
DisableAllSystemsForCampaign(ctx context.Context, campaignID string) error
}
SystemAddonEnabler enables/disables game system addons for a campaign. Called when the user changes the Game System dropdown in settings.
type SystemCount ¶
type SystemCount struct {
// Key is a system id, SystemFilterNone or SystemFilterCustom.
Key string
Count int
}
SystemCount is one filter chip: a system key and how many campaigns it has.
type SystemLister ¶
type SystemLister interface {
ListSystems() []SystemOption
}
SystemLister lists available game systems for the settings page dropdown. Avoids importing the systems package directly (prevents import cycle).
type TestMailer ¶
type TestMailer interface {
SendHTMLMail(ctx context.Context, to []string, subject, plainBody, htmlBody string) error
IsConfigured(ctx context.Context) bool
}
TestMailer sends the Customize page's "Send me a test" email. Subset of smtp.MailService, like InviteMailer.
type TierDefinition ¶
type TierDefinition struct {
Slug string `json:"slug"` // e.g. "major", "standard", "detail", "encounter"
Name string `json:"name"` // display name
Color string `json:"color"` // hex, validated as #RRGGBB
Prominence int `json:"prominence"` // 0-100 visual weight; higher = larger/bolder render
IsDefault bool `json:"is_default"` // exactly one per definition set
}
TierDefinition is a single entry in the per-campaign event tier vocabulary. Slugs are stored on Event.Tier as foreign-key-like references; TierDefinition supplies the rendering hints (color, prominence) the calendar UI consumes. Exactly one tier per definition set carries IsDefault=true.
type TileSizeResolver ¶
type TileSizeResolver interface {
TileSizesFor(ctx context.Context, campaignID, blockType string, config map[string]any) []string
}
TileSizeResolver reports the sizes a block type can take in a tile section. The block registry lives in the entities plugin, which imports this one, so the dashboard reaches it through this interface, wired at startup.
type TimelineExporter ¶
type TimelineExporter interface {
ExportTimelines(ctx context.Context, campaignID string, entitySlugLookup func(string) string) ([]ExportTimeline, error)
}
TimelineExporter gathers timeline data for a campaign export.
type TimelineImporter ¶
type TimelineImporter interface {
ImportTimelines(ctx context.Context, campaignID, userID string, data []ExportTimeline, idMap *IDMap, report *ImportReport) error
}
TimelineImporter creates timelines from import data.
type TopbarContent ¶
type TopbarContent struct {
Mode string `json:"mode"` // "none", "links", "quote".
Quote string `json:"quote,omitempty"` // Text to display in quote mode (max 200 chars).
Links []TopbarLink `json:"links,omitempty"` // Quick-link buttons in links mode (max 8).
// Widgets is the header's widgets in order ("links", "text"), written by
// the Customize page. Nil means an older save: Mode alone decides.
Widgets []string `json:"widgets,omitempty"`
}
TopbarContent configures what the owner wants displayed in the topbar center area.
type TopbarLink ¶
type TopbarLink struct {
Label string `json:"label"` // Button text (max 30 chars).
URL string `json:"url"` // Navigation URL.
Icon string `json:"icon,omitempty"` // Optional FA icon class (e.g., "fa-user").
}
TopbarLink is a quick-link button displayed in the topbar center area.
type TopbarStyle ¶
type TopbarStyle struct {
Mode string `json:"mode"` // "solid", "gradient", "moving", "sky" or "image".
Color string `json:"color,omitempty"` // Hex color for solid mode.
GradientFrom string `json:"gradient_from,omitempty"` // Start color for gradient mode.
GradientTo string `json:"gradient_to,omitempty"` // End color for gradient mode.
GradientDir string `json:"gradient_dir,omitempty"` // Direction: "to-r", "to-br", etc.
ImagePath string `json:"image_path,omitempty"` // Media path for background image.
Scrim string `json:"scrim,omitempty"` // Shade over an image: "light", "strong"; empty = medium.
}
TopbarStyle configures the visual appearance of the campaign's top navigation bar.
type TransferOwnershipRequest ¶
type TransferOwnershipRequest struct {
Email string `json:"email" form:"email"`
}
TransferOwnershipRequest holds the data for initiating an ownership transfer.
type TrashedCampaign ¶
type TrashedCampaign struct {
ID string
Name string
Slug string
// DeletedAt starts the retention clock.
DeletedAt time.Time
// DeletedBy is the account that deleted it; DeletedByName is a copy of
// the name taken then, so the Trash still reads right if the account goes.
DeletedBy *string
DeletedByName string
// Emptying is true once the final delete has begun and Undo is refused.
Emptying bool
// StorageBytes is the size of the media it holds, which still counts
// against the site's storage while it waits.
StorageBytes int64
}
TrashedCampaign is a campaign waiting in the site Trash, as the admin Trash page needs it. It is a separate type from Campaign on purpose: a trashed campaign must never come back from the reads that open one, so nothing that takes a *Campaign can be handed a trashed row by mistake.
type UpdateCampaignDetailsInput ¶
type UpdateCampaignDetailsInput struct {
Name patch.Field[string] `json:"name"`
Description patch.Field[string] `json:"description"`
IsPublic patch.Field[bool] `json:"isPublic"`
}
UpdateCampaignDetailsInput is the owner's save of the details the desk changes where they stand: the name, the description, and whether people outside the campaign may read it. It is a partial update: a body naming one key leaves the others exactly as stored, and an explicit null description clears it.
type UpdateCampaignInput ¶
UpdateCampaignInput is the validated input for updating a campaign. A nil field is absent and keeps the stored value; a pointer to the empty string clears the description.
type UpdateCampaignRequest ¶
type UpdateCampaignRequest struct {
Name *string `json:"name" form:"name"`
Description *string `json:"description" form:"description"`
IsPublic *bool `json:"is_public" form:"is_public"`
}
UpdateCampaignRequest holds the data submitted by the campaign edit form.
Every field is a pointer: the Details tab posts only the description, so an absent name or is_public must keep what is stored rather than blank the name or flip a public campaign private.
type UpdateRoleRequest ¶
type UpdateRoleRequest struct {
Role string `json:"role" form:"role"`
}
UpdateRoleRequest holds the data for changing a member's role.
type UpdateSidebarConfigRequest ¶
type UpdateSidebarConfigRequest struct {
Items *[]SidebarItem `json:"items"`
HiddenEntityIDs *[]string `json:"hidden_entity_ids"`
HiddenNodeIDs *[]string `json:"hidden_node_ids"`
}
UpdateSidebarConfigRequest holds the data for updating sidebar configuration. Pointer fields let the server distinguish "field absent from JSON" (nil → preserve stored value) from "field explicitly sent" (non-nil → replace stored value, even an explicitly-empty slice clears the field).
type UserFinder ¶
type UserFinder interface {
FindUserByEmail(ctx context.Context, email string) (*MemberUser, error)
FindUserByID(ctx context.Context, id string) (*MemberUser, error)
}
UserFinder finds users for membership operations. Avoids importing the auth plugin's types directly. Implemented by UserFinderAdapter which wraps auth.UserRepository.
func NewUserFinderAdapter ¶
func NewUserFinderAdapter(repo auth.UserRepository) UserFinder
NewUserFinderAdapter creates a new adapter around the auth repository.
type UserFinderAdapter ¶
type UserFinderAdapter struct {
// contains filtered or unexported fields
}
UserFinderAdapter wraps auth.UserRepository to satisfy the UserFinder interface. This adapter pattern avoids importing auth types throughout the campaigns package — only this file references the auth package.
func (*UserFinderAdapter) FindUserByEmail ¶
func (a *UserFinderAdapter) FindUserByEmail(ctx context.Context, email string) (*MemberUser, error)
FindUserByEmail looks up a user by email and maps to MemberUser. A guest's placeholder address finds nobody: a guest belongs to one campaign and can't be added to, or handed, any other.
func (*UserFinderAdapter) FindUserByID ¶
func (a *UserFinderAdapter) FindUserByID(ctx context.Context, id string) (*MemberUser, error)
FindUserByID looks up a user by ID and maps to MemberUser.
type VisitPasses ¶
type VisitPasses interface {
VisitPass(ctx context.Context, campaignID, userID string) (until time.Time, live, found bool, err error)
// EndVisits ends every running pass the user holds for the campaign.
EndVisits(ctx context.Context, campaignID, userID string) error
}
VisitPasses is the guest-code side of look-around passes, as the access middleware needs it.
type WhereWeLink ¶
WhereWeLink is a typed-in address as the block draws it: the text to show and, only when it is a safe web address, the link to open.
func WhereWePlayLink ¶
func WhereWePlayLink(raw string) WhereWeLink
WhereWePlayLink turns what the owner typed into the Foundry row. A bare host ("foundry.example.com") gets https; only http and https addresses become links, so a javascript: or data: address is shown as text and never opened. Over-long input is shown cut.
Source Files
¶
- account_deletion.go
- account_settings.go
- admin_list.go
- ai_look.go
- ai_settings.go
- appearance.go
- appearance_handler.go
- customize_brush.go
- customize_categories.go
- customize_draft.go
- customize_draft_handler.go
- customize_draft_repo.go
- customize_homes.go
- customize_kit_try.go
- customize_look_section.go
- customize_pages.go
- customize_sections.go
- customize_state.go
- customize_summary.go
- customize_tabs.go
- customize_wall.go
- customize_wall_skin.go
- desk_board.go
- desk_find.go
- desk_foundry.go
- desk_handler.go
- desk_model.go
- desk_rows.go
- desk_service.go
- desk_view.go
- export.go
- export_handler.go
- export_service.go
- extension_enable.go
- extensions_hub.go
- extensions_hub_handler.go
- first_run_home.go
- foundry_connect.go
- foundry_page.go
- guest_code_labels.go
- guest_code_repository.go
- guest_codes.go
- handler.go
- handover.go
- hero_change_form.go
- hero_changes_setting.go
- home_merge.go
- home_placement.go
- home_seen.go
- import.go
- import_icons.go
- import_media.go
- import_report.go
- import_sidebar.go
- invitation_source.go
- invite_box.go
- invite_handler.go
- invite_model.go
- invite_repository.go
- invite_service.go
- leave.go
- leave_onclick.go
- look_access.go
- look_presets.go
- member_access.go
- middleware.go
- model.go
- nav.go
- nav_order.go
- needs_you.go
- removed_members.go
- repository.go
- routes.go
- run_by_block.go
- sample_email.go
- service.go
- settings_campaign.go
- settings_conn_data.go
- settings_mast.go
- settings_tabs.go
- setup_steps.go
- sidebar_reconcile.go
- smoketest.go
- tiles.go
- trash_repository.go
- user_finder.go
- view_preview.go
- your_look.go
- your_look_opening.go