Take control over your live stream video by running it yourself. Streaming + chat out of the box.
HTML activitypubbroadcastingchatdecentralizedfederationfediversegolanghacktoberfesthlslivelivestreamowncastrtmpself-hostedstreaming-videovideo
Tell admins in Appearance config when plugins are also styling the page
Gabe Kangas7e968756d43b
diff --git a/main.go b/main.goindex 79a9252619..3ab69b8134 100644--- a/main.go+++ b/main.go@@ -335,22 +335,41 @@ func main() {// Stage 9: HTTP handler set. *Handlers is the dispatcher the router// binds methods on; the sub-handlers (admin, fediverse, indieauth,// moderation) hold their own narrower deps.+ // Plugin host getters: nil when the plugin host is disabled (boot+ // off or failed). Wired into both the admin handler set (for the+ // appearance style-contributors report) and the viewer handler set.+ var pluginActions func() []models.ExternalAction+ var pluginCSSContent func() []byte+ var pluginJSContent func() []byte+ var pluginPageContent func(*http.Request) []byte+ var pluginTabs func(*http.Request) []models.PluginTab+ var pluginStyleContributors func() []models.PluginStyleInfo+ if pluginHostInstance != nil {+ pluginActions = pluginHostInstance.Actions+ pluginCSSContent = pluginHostInstance.StylesContent+ pluginJSContent = pluginHostInstance.ScriptsContent+ pluginPageContent = pluginHostInstance.PageContent+ pluginTabs = pluginHostInstance.Tabs+ pluginStyleContributors = pluginHostInstance.StyleContributors+ }+adminHandlers := admin.New(admin.Deps{- Stream: streamSvc,- Rtmp: rtmpSvc,- Activitypub: apSvc,- Webhooks: webhooksSvc,- Chat: chatSvc,- Metrics: metricsSvc,- ConfigRepository: configRepository,- AuthRepository: authRepository,- FollowersRepository: followersRepository,- WebhookRepository: webhookRepository,- ChatMessageRepository: chatMessageRepository,- UserRepository: userRepository,- APBuilder: apBuilder,- APSigner: apSigner,- Config: cfg,+ Stream: streamSvc,+ Rtmp: rtmpSvc,+ Activitypub: apSvc,+ Webhooks: webhooksSvc,+ Chat: chatSvc,+ Metrics: metricsSvc,+ ConfigRepository: configRepository,+ AuthRepository: authRepository,+ FollowersRepository: followersRepository,+ WebhookRepository: webhookRepository,+ ChatMessageRepository: chatMessageRepository,+ UserRepository: userRepository,+ APBuilder: apBuilder,+ APSigner: apSigner,+ Config: cfg,+ PluginStyleContributors: pluginStyleContributors,})fediverseAuthSvc := fediverseauth.New()@@ -377,19 +396,6 @@ func main() {UserRepository: userRepository,})- var pluginActions func() []models.ExternalAction- var pluginCSSContent func() []byte- var pluginJSContent func() []byte- var pluginPageContent func(*http.Request) []byte- var pluginTabs func(*http.Request) []models.PluginTab- if pluginHostInstance != nil {- pluginActions = pluginHostInstance.Actions- pluginCSSContent = pluginHostInstance.StylesContent- pluginJSContent = pluginHostInstance.ScriptsContent- pluginPageContent = pluginHostInstance.PageContent- pluginTabs = pluginHostInstance.Tabs- }-h := handlers.NewHandlers(handlers.Deps{Cache: cacheContainer,Stream: streamSvc,diff --git a/models/pluginStyle.go b/models/pluginStyle.gonew file mode 100644index 0000000000..2996c0ac53--- /dev/null+++ b/models/pluginStyle.go@@ -0,0 +1,16 @@+package models++// PluginStyleInfo describes the viewer-page styling one enabled plugin+// contributes. The admin Appearance UI uses it to explain that plugin+// styles and the admin's own appearance settings are combined into the+// final look, and to flag the specific color swatches a plugin also+// sets. DeclaredVars holds the theme custom properties the plugin+// declares (without the leading `--`, e.g. "theme-color-action"); it+// can be empty when a plugin styles the page without touching a+// recognized appearance token. The host emits this list as+// `styleContributors` on the admin server config.+type PluginStyleInfo struct {+ Slug string `json:"slug"`+ Name string `json:"name"`+ DeclaredVars []string `json:"declaredVars"`+}diff --git a/pluginhost/pluginhost.go b/pluginhost/pluginhost.goindex 85f69ea8fe..9b439b3e66 100644--- a/pluginhost/pluginhost.go+++ b/pluginhost/pluginhost.go@@ -10,6 +10,8 @@ import ("net/http""os""path/filepath"+ "regexp"+ "sort""strings""time"@@ -207,6 +209,98 @@ func (p *Host) dynamicStyles() []byte {return buf.Bytes()}+// themeVarDeclRe matches a theme custom-property declaration in CSS,+// e.g. `--theme-color-action:` or `--theme-rounded-corners:`. The+// capture group is the variable name without the leading `--`, which+// matches the keys the admin Appearance UI uses for its color swatches+// (e.g. "theme-color-action").+var themeVarDeclRe = regexp.MustCompile(`--(theme-color-[a-z0-9-]+|theme-rounded-corners)\s*:`)++// StyleContributors returns one entry per enabled plugin (holding+// ui.modify) that contributes any CSS to the viewer page, covering both+// static manifest.styles and on_page_styles output — the same sources+// StylesContent concatenates. Plugins that contribute nothing are+// omitted, so a non-empty result means the admin's appearance settings+// are being combined with plugin styling. The viewer renders plugin+// styles below the admin's appearance variables and custom CSS, so the+// admin wins on overlap; this report lets the admin UI say so and point+// at the affected swatches.+func (p *Host) StyleContributors() []models.PluginStyleInfo {+ if p == nil || p.manager == nil {+ return nil+ }+ var out []models.PluginStyleInfo+ for _, l := range p.manager.Snapshot() {+ if l == nil || l.Manifest == nil {+ continue+ }+ if !manifestHasPermission(l.Manifest, plugins.PermUIModify) {+ continue+ }+ css := p.pluginStyleCSS(l)+ if len(css) == 0 {+ continue+ }+ out = append(out, models.PluginStyleInfo{+ Slug: l.Manifest.Slug,+ Name: l.Manifest.DisplayName,+ DeclaredVars: declaredThemeVars(css),+ })+ }+ return out+}++// pluginStyleCSS returns the CSS a single plugin contributes to the+// viewer page: its static manifest.styles files (read from the plugin's+// AssetsFS) followed by its on_page_styles output. It mirrors the+// per-plugin slice of StylesContent/dynamicStyles so the admin-facing+// token scan sees exactly what the viewer renders.+func (p *Host) pluginStyleCSS(l *plugins.Loaded) []byte {+ var buf bytes.Buffer+ if l.AssetsFS != nil {+ pluginPrefix := "/plugins/" + l.Manifest.Slug + "/"+ for _, entry := range l.Manifest.Styles {+ relPath := strings.TrimPrefix(entry, pluginPrefix)+ data, err := fs.ReadFile(l.AssetsFS, relPath)+ if err != nil {+ continue+ }+ buf.Write(data)+ if len(data) > 0 && data[len(data)-1] != '\n' {+ buf.WriteByte('\n')+ }+ }+ }+ if css, err := l.CallPageStyles(context.Background()); err == nil && css != "" {+ buf.WriteString(css)+ }+ return buf.Bytes()+}++// declaredThemeVars returns the sorted, de-duplicated set of theme+// custom-property names declared in a CSS blob (without the leading+// `--`), e.g. ["theme-color-action", "theme-rounded-corners"]. The+// names match the keys the admin Appearance UI uses, so it can badge+// the swatches a plugin also sets.+func declaredThemeVars(css []byte) []string {+ matches := themeVarDeclRe.FindAllSubmatch(css, -1)+ if len(matches) == 0 {+ return nil+ }+ seen := make(map[string]struct{}, len(matches))+ var vars []string+ for _, m := range matches {+ name := string(m[1])+ if _, ok := seen[name]; ok {+ continue+ }+ seen[name] = struct{}{}+ vars = append(vars, name)+ }+ sort.Strings(vars)+ return vars+}+// ScriptsContent mirrors StylesContent for manifest.scripts: returns// the concatenated JavaScript bytes contributed by every loaded// plugin, with `// plugin: <slug>` delimiters between contributions.diff --git a/pluginhost/pluginstyles_test.go b/pluginhost/pluginstyles_test.goindex bb8ea31a2b..18fff150d8 100644--- a/pluginhost/pluginstyles_test.go+++ b/pluginhost/pluginstyles_test.go@@ -33,6 +33,39 @@ func TestWriteWrappedScript(t *testing.T) {}}+func TestDeclaredThemeVars(t *testing.T) {+ css := []byte(`:root {+ --theme-color-action: #33d17a;+ --theme-color-background-main:#0b1020;+ --theme-rounded-corners: 8px;+ --not-a-theme-var: red;+ }+ .foo { color: var(--theme-color-action); } /* a use, not a decl */+ :root { --theme-color-action: #fff; } /* duplicate decl */`)++ got := declaredThemeVars(css)+ want := []string{+ "theme-color-action",+ "theme-color-background-main",+ "theme-rounded-corners",+ }+ if len(got) != len(want) {+ t.Fatalf("got %v, want %v", got, want)+ }+ for i := range want {+ // declaredThemeVars sorts its output, so positions are stable.+ if got[i] != want[i] {+ t.Errorf("var %d: got %q, want %q", i, got[i], want[i])+ }+ }++ // CSS with no theme declarations (only a var() use) yields nil so the+ // admin UI shows no swatch badges.+ if vars := declaredThemeVars([]byte(`.x { color: var(--theme-color-action); }`)); vars != nil {+ t.Errorf("expected nil for a var() use with no declaration, got %v", vars)+ }+}+func TestManifestHasPermission(t *testing.T) {m := &plugins.Manifest{Permissions: []string{"storage.kv", "ui.modify"}}if !manifestHasPermission(m, plugins.PermUIModify) {diff --git a/web/components/admin/config/general/AppearanceConfig.tsx b/web/components/admin/config/general/AppearanceConfig.tsxindex 41d9c680e4..8e1b1c5113 100644--- a/web/components/admin/config/general/AppearanceConfig.tsx+++ b/web/components/admin/config/general/AppearanceConfig.tsx@@ -1,6 +1,6 @@-import React, { FC, useContext, useCallback, useEffect, useState } from 'react';+import React, { FC, useContext, useCallback, useEffect, useMemo, useState } from 'react';-import { Button, Col, Collapse, Row, Slider, Space } from 'antd';+import { Alert, Button, Col, Collapse, Row, Slider, Space, Tooltip } from 'antd';import Paragraph from 'antd/lib/typography/Paragraph';import Title from 'antd/lib/typography/Title';import { useTranslation } from 'next-export-i18n';@@ -28,6 +28,10 @@ interface AppearanceVariable {type ColorCollectionProps = {variables: { name; description; value }[];+ // overrides maps a variable name (without the leading `--`) to the+ // display names of enabled plugins that also set it, so each swatch+ // can flag that a plugin is styling that color too.+ overrides: Record<string, string[]>;updateColor: (variable: string, color: string, description: string) => void;};@@ -82,11 +86,13 @@ const ColorPicker = React.memo(value,name,description,+ alsoSetBy,onChange,}: {value: string;name: string;description: string;+ alsoSetBy?: string[];onChange: (name: string, value: string, description: string) => void;}) => (<Col span={3} key={name}>@@ -100,11 +106,22 @@ const ColorPicker = React.memo(onChange={e => onChange(name, e.target.value, description)}/><div style={{ padding: '2px' }}>{description}</div>+ {alsoSetBy && alsoSetBy.length > 0 && (+ <Tooltip+ title={`Your value takes priority here. Use “Reset to Defaults” to fall back to ${alsoSetBy.join(+ ', ',+ )}'s color.`}+ >+ <div style={{ padding: '2px', fontSize: 11, opacity: 0.7 }}>+ also set by {alsoSetBy.join(', ')}+ </div>+ </Tooltip>+ )}</Col>),);-const ColorCollection: FC<ColorCollectionProps> = ({ variables, updateColor }) => {+const ColorCollection: FC<ColorCollectionProps> = ({ variables, overrides, updateColor }) => {const cc = variables.map(colorVar => {const { name, description, value } = colorVar;@@ -114,6 +131,7 @@ const ColorCollection: FC<ColorCollectionProps> = ({ variables, updateColor }) =value={value}name={name}description={description}+ alsoSetBy={overrides[name]}onChange={updateColor}/>);@@ -127,9 +145,25 @@ export default function Appearance() {const { t } = useTranslation();const serverStatusData = useContext(ServerStatusContext);const { serverConfig, setFieldInConfigState } = serverStatusData;- const { instanceDetails } = serverConfig;+ const { instanceDetails, styleContributors = [] } = serverConfig;const { appearanceVariables } = instanceDetails;+ // Map each appearance variable a plugin declares to the plugins that+ // set it, so each swatch can flag "also set by <plugin>". Plugin+ // styles render below the admin's appearance variables, so the admin's+ // value wins; the badge tells the admin a plugin is also driving that+ // color and that resetting falls back to the plugin's value.+ const pluginVarOverrides = useMemo(() => {+ const m: Record<string, string[]> = {};+ styleContributors.forEach(plugin => {+ (plugin.declaredVars || []).forEach(variable => {+ if (!m[variable]) m[variable] = [];+ m[variable].push(plugin.name);+ });+ });+ return m;+ }, [styleContributors]);+const [defaultValues, setDefaultValues] = useState<Record<string, AppearanceVariable>>();const [customValues, setCustomValues] = useState<Record<string, AppearanceVariable>>();@@ -246,6 +280,18 @@ export default function Appearance() {<Space direction="vertical"><Title>Customize Appearance</Title><Paragraph>The following colors are used across the user interface.</Paragraph>+ {styleContributors.length > 0 && (+ <Alert+ type="info"+ showIcon+ message="A plugin is styling your site"+ description={`${styleContributors.map(p => p.name).join(', ')} ${+ styleContributors.length === 1+ ? 'is applying its own styles'+ : 'are applying their own styles'+ } to your site, combined with the colors you set here. Your settings are applied on top, so they win where they overlap. If the page doesn't look the way you expect, use “Reset to Defaults” below to let the plugin styling show through, or disable the plugin from the Plugins page.`}+ />+ )}<div><Collapse defaultActiveKey={['1']}><Panel header={<strong>Section Colors</strong>} key="1">@@ -256,6 +302,7 @@ export default function Appearance() {<Row gutter={[16, 16]}><ColorCollectionvariables={transformToColorMap(componentColorVariables)}+ overrides={pluginVarOverrides}updateColor={updateColor}/></Row>@@ -264,6 +311,7 @@ export default function Appearance() {<Row gutter={[16, 16]}><ColorCollectionvariables={transformToColorMap(chatColorVariables)}+ overrides={pluginVarOverrides}updateColor={updateColor}/></Row>diff --git a/web/types/config-section.ts b/web/types/config-section.tsindex 45a3d6f525..975c30bd89 100644--- a/web/types/config-section.ts+++ b/web/types/config-section.ts@@ -96,6 +96,19 @@ export interface ExternalAction {openExternally: boolean;}+// PluginStyleInfo describes the page styling one enabled plugin+// contributes. The Appearance config uses it to tell the admin that+// plugin styles are combined with their own colors, and to flag the+// swatches a plugin also sets. declaredVars holds the theme custom+// properties the plugin declares (without the leading `--`, e.g.+// "theme-color-action"); it can be empty when a plugin styles the page+// without touching a recognized appearance token.+export interface PluginStyleInfo {+ slug: string;+ name: string;+ declaredVars: string[];+}+export interface Federation {enabled: boolean;isPrivate: boolean;@@ -135,6 +148,7 @@ export interface StreamKey {export interface ConfigDetails {externalActions: ExternalAction[];+ styleContributors: PluginStyleInfo[];ffmpegPath: string;instanceDetails: ConfigInstanceDetailsFields;rtmpServerPort: string;diff --git a/web/utils/server-status-context.tsx b/web/utils/server-status-context.tsxindex 9fc30b50fd..c6f5f2c660 100644--- a/web/utils/server-status-context.tsx+++ b/web/utils/server-status-context.tsx@@ -65,6 +65,7 @@ const initialServerConfigState: ConfigDetails = {discord: { enabled: false, webhook: '', goLiveMessage: '' },},externalActions: [],+ styleContributors: [],supportedCodecs: [],videoCodec: '',forbiddenUsernames: [],diff --git a/webserver/handlers/admin/admin.go b/webserver/handlers/admin/admin.goindex 464de5cd7f..6976d838d8 100644--- a/webserver/handlers/admin/admin.go+++ b/webserver/handlers/admin/admin.go@@ -3,6 +3,7 @@ package adminimport ("github.com/owncast/owncast/config""github.com/owncast/owncast/metrics"+ "github.com/owncast/owncast/models""github.com/owncast/owncast/persistence/authrepository""github.com/owncast/owncast/persistence/chatmessagerepository""github.com/owncast/owncast/persistence/configrepository"@@ -42,6 +43,15 @@ type Admin struct {apBuilder *apmodels.BuilderapSigner *apcrypto.Signercfg *config.Config++ // pluginStyleContributors, when non-nil, returns the per-plugin+ // page-styling report (which enabled plugins emit CSS and which+ // appearance tokens they set). Wired to the plugin host's+ // StyleContributors() method; nil when the plugin host is disabled.+ // GetServerConfig emits it as `styleContributors` so the admin+ // Appearance UI can flag plugin styling that combines with the+ // admin's own colors.+ pluginStyleContributors func() []models.PluginStyleInfo}// Deps lists every service a *Admin consumes. New deps appear here as@@ -62,25 +72,31 @@ type Deps struct {APBuilder *apmodels.BuilderAPSigner *apcrypto.SignerConfig *config.Config+ // PluginStyleContributors is an optional getter that returns the+ // per-plugin page-styling report. Wired by main.go to the plugin+ // host's StyleContributors() method; nil when the plugin host is+ // disabled.+ PluginStyleContributors func() []models.PluginStyleInfo}// New constructs the dependency-bearing admin handler set.func New(deps Deps) *Admin {return &Admin{- stream: deps.Stream,- rtmp: deps.Rtmp,- activitypub: deps.Activitypub,- webhooks: deps.Webhooks,- chat: deps.Chat,- metrics: deps.Metrics,- configRepository: deps.ConfigRepository,- authRepository: deps.AuthRepository,- followersRepository: deps.FollowersRepository,- webhookRepository: deps.WebhookRepository,- chatMessageRepository: deps.ChatMessageRepository,- userRepository: deps.UserRepository,- apBuilder: deps.APBuilder,- apSigner: deps.APSigner,- cfg: deps.Config,+ stream: deps.Stream,+ rtmp: deps.Rtmp,+ activitypub: deps.Activitypub,+ webhooks: deps.Webhooks,+ chat: deps.Chat,+ metrics: deps.Metrics,+ configRepository: deps.ConfigRepository,+ authRepository: deps.AuthRepository,+ followersRepository: deps.FollowersRepository,+ webhookRepository: deps.WebhookRepository,+ chatMessageRepository: deps.ChatMessageRepository,+ userRepository: deps.UserRepository,+ apBuilder: deps.APBuilder,+ apSigner: deps.APSigner,+ cfg: deps.Config,+ pluginStyleContributors: deps.PluginStyleContributors,}}diff --git a/webserver/handlers/admin/serverConfig.go b/webserver/handlers/admin/serverConfig.goindex 2457e2ea6a..dfeec1f15a 100644--- a/webserver/handlers/admin/serverConfig.go+++ b/webserver/handlers/admin/serverConfig.go@@ -79,6 +79,7 @@ func (a *Admin) GetServerConfig(w http.ResponseWriter, r *http.Request) {},S3: configRepository.GetS3Config(),ExternalActions: configRepository.GetExternalActions(),+ StyleContributors: a.styleContributorsOrEmpty(),SupportedCodecs: transcoder.GetCodecs(ffmpeg),VideoCodec: configRepository.GetVideoCodec(),ForbiddenUsernames: usernameBlocklist,@@ -105,6 +106,21 @@ func (a *Admin) GetServerConfig(w http.ResponseWriter, r *http.Request) {}}+// styleContributorsOrEmpty returns the plugin page-styling report, or+// an empty (non-nil) slice when the getter is unset (no plugin host) or+// returns nothing. The empty-slice contract keeps the JSON wire shape+// stable: `styleContributors: []` rather than null, so the admin UI+// doesn't need a defensive nil-check before iterating.+func (a *Admin) styleContributorsOrEmpty() []models.PluginStyleInfo {+ if a.pluginStyleContributors == nil {+ return []models.PluginStyleInfo{}+ }+ if c := a.pluginStyleContributors(); len(c) > 0 {+ return c+ }+ return []models.PluginStyleInfo{}+}+type serverConfigAdminResponse struct {InstanceDetails webConfigResponse `json:"instanceDetails"`Notifications notificationsConfigResponse `json:"notifications"`@@ -119,6 +135,7 @@ type serverConfigAdminResponse struct {Federation federationConfigResponse `json:"federation"`SupportedCodecs []string `json:"supportedCodecs"`ExternalActions []models.ExternalAction `json:"externalActions"`+ StyleContributors []models.PluginStyleInfo `json:"styleContributors"`ForbiddenUsernames []string `json:"forbiddenUsernames"`SuggestedUsernames []string `json:"suggestedUsernames"`StreamKeys []generated.StreamKey `json:"streamKeys"`