Take control over your live stream video by running it yourself. Streaming + chat out of the box.
HTML activitypubbroadcastingchatdecentralizedfederationfediversegolanghacktoberfesthlslivelivestreamowncastrtmpself-hostedstreaming-videovideo
Service dependency injection refactor (#4908)
Gabe Kangasd702eb418649
diff --git a/AGENTS.md b/AGENTS.mdindex 9ae1809639..20a09f4dca 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -51,7 +51,7 @@ This is a repository consisting of a Go backend and a React frontend. It support### Backend Structure-- `main.go`: Entry point. Initializes logging, database, config, core services, metrics, and the HTTP router.+- `main.go`: Entry point and composition root. Initializes logging, database, config, core services, metrics, then constructs every migrated service from `services/` and injects them into the HTTP router and other consumers. See "Service migration pattern" below for the policy.- `webserver/router/`: Chi (v5) HTTP router with HTTP/2 support. Routes organized under `/api/`, `/api/admin/`, federation endpoints, `/hls/`, and `/ws`.- `webserver/handlers/`: Request handlers for web, admin, static files, HLS streaming.- `webserver/handlers/generated/`: Auto-generated API types and Chi server stubs from OpenAPI spec. Do not hand-edit.@@ -65,6 +65,21 @@ This is a repository consisting of a Go backend and a React frontend. It support- `models/`: Shared data models.- `config/`: Configuration package with defaults and constants.- `tools/`: Separate `go.mod` for development tool dependencies installed to `./bin/`.+- `services/`: Migrated services (constructor-injected, no package-level state). See "Service migration pattern" below for the rules.++### Service migration pattern++Owncast is being moved off package-level singletons toward constructor-injected services. New code and migrated services follow these rules:++1. **A migrated service lives in `services/<domain>/`** and exposes `New(Deps) *Service`. Services with a lifecycle also expose `Start(ctx) error` / `Stop(ctx) error`. The package has no package-level state and no `Get()` (or equivalent) accessor.++2. **`main.go` is the composition root.** It's the only place that calls `services/*.New(...)`. Other code receives services via constructor injection. New deps appear in a `Deps` struct on each service or consumer.++3. **Existing `<pkg>.Get()` accessors (in `persistence/`) are deprecated** and exist only until their callers migrate. New code never calls `Get()`. PRs may reduce `Get()` callers; PRs must not add them.++When a service publishes events to multiple listeners, model the listeners as injected interfaces (`type StreamLifecycleListener interface { ... }`) and iterate them in the publisher. Don't introduce a generic event bus — explicit calls make stack traces, grep, and tests work the way the rest of the codebase expects.++The cache (`services/cache/`) is the first migrated service and is the reference shape; the `*Handlers` struct in `webserver/handlers/handlers.go` is the reference pattern for consumers of injected services.### Frontend Structurediff --git a/activitypub/activitypub.go b/activitypub/activitypub.godeleted file mode 100644index 9b9c6c0377..0000000000--- a/activitypub/activitypub.go+++ /dev/null@@ -1,96 +0,0 @@-package activitypub--import (- "github.com/owncast/owncast/activitypub/crypto"- "github.com/owncast/owncast/activitypub/inbox"- "github.com/owncast/owncast/activitypub/jobs"- "github.com/owncast/owncast/activitypub/outbox"- "github.com/owncast/owncast/activitypub/persistence"- "github.com/owncast/owncast/activitypub/persistence/followersrepository"- "github.com/owncast/owncast/activitypub/workerpool"- "github.com/owncast/owncast/persistence/configrepository"-- "github.com/owncast/owncast/core/data"- "github.com/owncast/owncast/models"- log "github.com/sirupsen/logrus"-)--// Start will initialize and start the federation support.-func Start(datastore *data.Datastore) {- configRepository := configrepository.Get()- persistence.Setup(datastore)-- outboundWorkerPoolSize := getOutboundWorkerPoolSize()- workerpool.InitOutboundWorkerPool(outboundWorkerPoolSize)- inbox.InitInboxWorkerPool()-- // Generate the keys for signing federated activity if needed.- if configRepository.GetPrivateKey() == "" {- privateKey, publicKey, err := crypto.GenerateKeys()- _ = configRepository.SetPrivateKey(string(privateKey))- _ = configRepository.SetPublicKey(string(publicKey))- if err != nil {- log.Errorln("Unable to get private key", err)- }- }-- // Start follower validation background job.- jobs.StartFollowerValidationJob()-}--func getOutboundWorkerPoolSize() int {- // Use a reasonable fixed worker pool size instead of scaling with followers- // This prevents excessive resource usage when streamers have many followers- const (- minWorkers = 10 // Minimum workers for small instances- maxWorkers = 50 // Maximum workers to prevent resource exhaustion- defaultWorkers = 20 // Default for most instances- )-- followersRepo := followersrepository.Get()- var followerCount int64- fc, err := followersRepo.GetCount()- if err != nil {- log.Errorln("Unable to get follower count", err)- return defaultWorkers- }- followerCount = fc-- // Scale more conservatively: start with base workers, add 1 worker per 100 followers- // This gives a much more reasonable scaling than the previous followerCount * 5- workers := minWorkers + int(followerCount/100)-- if workers > maxWorkers {- workers = maxWorkers- }-- log.Debugf("Initializing ActivityPub outbound worker pool with %d workers for %d followers", workers, followerCount)- return workers-}--// SendLive will send a "Go Live" message to followers.-func SendLive() error {- return outbox.SendLive()-}--// SendPublicFederatedMessage will send an arbitrary provided message to followers.-func SendPublicFederatedMessage(message string) error {- return outbox.SendPublicMessage(message)-}--// SendDirectFederatedMessage will send a direct message to a single account.-func SendDirectFederatedMessage(message, account string) error {- return outbox.SendDirectMessageToAccount(message, account)-}--// GetFollowerCount will return the local tracked follower count.-func GetFollowerCount() (int64, error) {- followersRepo := followersrepository.Get()- return followersRepo.GetCount()-}--// GetPendingFollowRequests will return the pending follow requests.-func GetPendingFollowRequests() ([]models.Follower, error) {- followersRepo := followersrepository.Get()- return followersRepo.GetPendingFollowRequests()-}diff --git a/activitypub/controllers/object.go b/activitypub/controllers/object.godeleted file mode 100644index 723360cfb6..0000000000--- a/activitypub/controllers/object.go+++ /dev/null@@ -1,58 +0,0 @@-package controllers--import (- "net/http"- "strings"-- "github.com/owncast/owncast/activitypub/apmodels"- "github.com/owncast/owncast/activitypub/crypto"- "github.com/owncast/owncast/activitypub/persistence"- "github.com/owncast/owncast/activitypub/requests"- "github.com/owncast/owncast/persistence/configrepository"- log "github.com/sirupsen/logrus"-)--// ObjectHandler handles requests for a single federated ActivityPub object.-func ObjectHandler(w http.ResponseWriter, r *http.Request) {- configRepository := configrepository.Get()-- if !configRepository.GetFederationEnabled() {- w.WriteHeader(http.StatusMethodNotAllowed)- return- }-- // If private federation mode is enabled do not allow access to objects.- if configRepository.GetFederationIsPrivate() {- w.WriteHeader(http.StatusNotFound)- return- }-- serverURL, err := apmodels.GetCanonicalServerURL()- if err != nil {- w.WriteHeader(http.StatusNotFound)- return- }- serverURL.Path = r.URL.Path- iri := serverURL.String()- object, _, _, err := persistence.GetObjectByIRI(iri)- if err != nil {- legacyIRI := strings.Join([]string{strings.TrimSuffix(configRepository.GetServerURL(), "/"), r.URL.Path}, "")- if legacyIRI == iri {- w.WriteHeader(http.StatusNotFound)- return- }- object, _, _, err = persistence.GetObjectByIRI(legacyIRI)- if err != nil {- w.WriteHeader(http.StatusNotFound)- return- }- }-- accountName := configRepository.GetDefaultFederationUsername()- actorIRI := apmodels.MakeLocalIRIForAccount(accountName)- publicKey := crypto.GetPublicKey(actorIRI)-- if err := requests.WriteResponse([]byte(object), w, publicKey); err != nil {- log.Errorln(err)- }-}diff --git a/activitypub/inbox/update.go b/activitypub/inbox/update.godeleted file mode 100644index 0a48780ef5..0000000000--- a/activitypub/inbox/update.go+++ /dev/null@@ -1,27 +0,0 @@-package inbox--import (- "context"-- "github.com/go-fed/activity/streams/vocab"- "github.com/owncast/owncast/activitypub/apmodels"- "github.com/owncast/owncast/activitypub/persistence/followersrepository"- "github.com/owncast/owncast/activitypub/resolvers"- log "github.com/sirupsen/logrus"-)--func handleUpdateRequest(c context.Context, activity vocab.ActivityStreamsUpdate) error {- // We only care about update events to followers.- if !apmodels.IsFirstObjectActivityStreamsPerson(activity.GetActivityStreamsObject()) {- return nil- }-- actor, err := resolvers.GetResolvedActorFromActorProperty(activity.GetActivityStreamsActor())- if err != nil {- log.Errorln(err)- return err- }-- followersRepo := followersrepository.Get()- return followersRepo.Update(actor.ActorIriString(), actor.InboxString(), actor.SharedInboxString(), actor.Name, actor.FullUsername, actor.ImageString())-}diff --git a/activitypub/inbox/workerpool.go b/activitypub/inbox/workerpool.godeleted file mode 100644index 5e786ccf23..0000000000--- a/activitypub/inbox/workerpool.go+++ /dev/null@@ -1,51 +0,0 @@-package inbox--import (- "runtime"-- "github.com/owncast/owncast/activitypub/apmodels"- log "github.com/sirupsen/logrus"-)--// workerPoolSize defines the number of concurrent ActivityPub handlers.-var workerPoolSize = runtime.GOMAXPROCS(0)--// Job struct bundling the ActivityPub and the payload in one struct.-type Job struct {- request apmodels.InboxRequest-}--var queue chan Job--// InitInboxWorkerPool starts n go routines that await ActivityPub jobs.-func InitInboxWorkerPool() {- queue = make(chan Job)-- // start workers- for i := 1; i <= workerPoolSize; i++ {- go worker(i, queue)- }-}--// AddToQueue will queue up an outbound http request.-func AddToQueue(req apmodels.InboxRequest) {- log.Tracef("Queued request for ActivityPub inbox handler")- queue <- Job{req}-}--func worker(workerID int, queue <-chan Job) {- log.Debugf("Started ActivityPub worker %d", workerID)-- for job := range queue {- func() {- defer func() {- if r := recover(); r != nil {- log.Errorf("Recovered from panic in ActivityPub worker %d: %v", workerID, r)- }- }()- handle(job.request)- }()-- log.Tracef("Done with ActivityPub inbox handler using worker %d", workerID)- }-}diff --git a/activitypub/jobs/followervalidation.go b/activitypub/jobs/followervalidation.godeleted file mode 100644index 325a7c2fc8..0000000000--- a/activitypub/jobs/followervalidation.go+++ /dev/null@@ -1,117 +0,0 @@-package jobs--import (- "time"-- "github.com/owncast/owncast/activitypub/persistence/followersrepository"- "github.com/owncast/owncast/activitypub/resolvers"- "github.com/owncast/owncast/config"- "github.com/owncast/owncast/models"- "github.com/owncast/owncast/persistence/configrepository"- log "github.com/sirupsen/logrus"-)--const (- // ValidationInterval is how often the validation job runs.- ValidationInterval = 1 * time.Hour- // FollowersPerRun is how many followers to validate per job run.- FollowersPerRun = 5- // FailureDurationThreshold is how long a follower must be unreachable before removal.- FailureDurationThreshold = 7 * 24 * time.Hour // 7 days- // DelayBetweenFollowers is the delay between validating individual followers.- DelayBetweenFollowers = 2 * time.Second-)--// GetValidationInterval returns the configured validation interval, or the default.-func GetValidationInterval() time.Duration {- if config.FollowerValidationInterval > 0 {- return config.FollowerValidationInterval- }- return ValidationInterval-}--// StartFollowerValidationJob starts the background job that periodically validates followers.-func StartFollowerValidationJob() {- interval := GetValidationInterval()- ticker := time.NewTicker(interval)- go func() {- for range ticker.C {- runFollowerValidation()- }- }()- log.Debugf("Follower validation job scheduled with interval %v", interval)-}--func runFollowerValidation() {- configRepo := configrepository.Get()- if !configRepo.GetFederationEnabled() {- return- }-- followersRepo := followersrepository.Get()- followers, err := followersRepo.GetFollowersToValidate(FollowersPerRun)- if err != nil {- log.Errorln("Failed to get followers for validation:", err)- return- }-- for _, follower := range followers {- validateAndUpdateFollower(followersRepo, follower)- time.Sleep(DelayBetweenFollowers)- }-}--func validateAndUpdateFollower(repo followersrepository.FollowersRepository, follower models.Follower) {- resolvedActor, err := resolvers.GetResolvedActorFromIRI(follower.ActorIRI)- if err != nil {- handleValidationFailure(repo, follower, err)- return- }-- // Success - clear failure timestamp and update data- if err := repo.UpdateFollowerValidationSuccess(follower.ActorIRI); err != nil {- log.Errorln("Failed to update validation success:", err)- }-- // Update follower data- if err := repo.Update(- resolvedActor.ActorIriString(),- resolvedActor.InboxString(),- resolvedActor.SharedInboxString(),- resolvedActor.Name,- resolvedActor.FullUsername,- resolvedActor.ImageString(),- ); err != nil {- log.Errorln("Failed to update follower data:", err)- }-}--func handleValidationFailure(repo followersrepository.FollowersRepository, follower models.Follower, resolveErr error) {- log.Debugf("Follower validation failed for %s: %v", follower.ActorIRI, resolveErr)-- // Check removal eligibility BEFORE updating failure timestamp.- // We use the existing FirstValidationFailureAt from the database to determine- // if this follower has been failing long enough to be removed.- // If FirstValidationFailureAt is not set, this is a new failure and we just record it.- shouldRemove := false- if follower.FirstValidationFailureAt.Valid {- failureDuration := time.Since(follower.FirstValidationFailureAt.Time)- shouldRemove = failureDuration >= FailureDurationThreshold- }-- // Update failure timestamp (sets first_validation_failure_at if not already set)- if err := repo.UpdateFollowerValidationFailure(follower.ActorIRI); err != nil {- log.Errorln("Failed to update validation failure:", err)- return- }-- // Remove follower if they've exceeded the failure threshold- if shouldRemove {- failureDuration := time.Since(follower.FirstValidationFailureAt.Time)- log.Infof("Removing follower %s after %v of consecutive failures",- follower.ActorIRI, failureDuration.Round(time.Hour))- if err := repo.RemoveByIRI(follower.ActorIRI); err != nil {- log.Errorln("Failed to remove invalid follower:", err)- }- }-}diff --git a/activitypub/persistence/persistence.go b/activitypub/persistence/persistence.godeleted file mode 100644index ed486b423e..0000000000--- a/activitypub/persistence/persistence.go+++ /dev/null@@ -1,159 +0,0 @@-package persistence--import (- "context"- "database/sql"- "fmt"- "time"-- "github.com/go-fed/activity/streams"- "github.com/go-fed/activity/streams/vocab"- "github.com/owncast/owncast/activitypub/resolvers"- "github.com/owncast/owncast/core/data"- "github.com/owncast/owncast/db"- "github.com/owncast/owncast/models"- "github.com/pkg/errors"-- log "github.com/sirupsen/logrus"-)--var _datastore *data.Datastore--// Setup will initialize the ActivityPub persistence layer with the provided datastore.-// ActivityPub-related tables (ap_followers, ap_outbox, ap_accepted_activities)-// are created by the goose migrations package.-func Setup(datastore *data.Datastore) {- _datastore = datastore- addFollowersFixtureData()-}--// GetDatastore returns the datastore instance for use by sub-repositories.-func GetDatastore() *data.Datastore {- return _datastore-}--// GetOutboxPostCount will return the number of posts in the outbox.-func GetOutboxPostCount() (int64, error) {- ctx := context.Background()- return _datastore.GetQueries().GetLocalPostCount(ctx)-}--// GetOutbox will return an instance of the outbox populated by stored items.-func GetOutbox(limit int, offset int) (vocab.ActivityStreamsOrderedCollection, error) {- collection := streams.NewActivityStreamsOrderedCollection()- orderedItems := streams.NewActivityStreamsOrderedItemsProperty()- rows, err := _datastore.GetQueries().GetOutboxWithOffset(- context.Background(),- db.GetOutboxWithOffsetParams{Limit: int64(limit), Offset: int64(offset)},- )- if err != nil {- return collection, err- }-- for _, value := range rows {- createCallback := func(c context.Context, activity vocab.ActivityStreamsCreate) error {- orderedItems.AppendActivityStreamsCreate(activity)- return nil- }- if err := resolvers.Resolve(context.Background(), value, createCallback); err != nil {- return collection, err- }- }-- return collection, nil-}--// AddToOutbox will store a single payload to the persistence layer.-func AddToOutbox(iri string, itemData []byte, typeString string, isLiveNotification bool) error {- tx, err := _datastore.DB.Begin()- if err != nil {- log.Debugln(err)- }- defer func() {- _ = tx.Rollback()- }()-- if err = _datastore.GetQueries().WithTx(tx).AddToOutbox(context.Background(), db.AddToOutboxParams{- Iri: iri,- Value: itemData,- Type: typeString,- LiveNotification: sql.NullBool{Bool: isLiveNotification, Valid: true},- }); err != nil {- return fmt.Errorf("error creating new item in federation outbox %s", err)- }-- return tx.Commit()-}--// GetObjectByIRI will return a string representation of a single object by the IRI.-func GetObjectByIRI(iri string) (string, bool, time.Time, error) {- row, err := _datastore.GetQueries().GetObjectFromOutboxByIRI(context.Background(), iri)- return string(row.Value), row.LiveNotification.Bool, row.CreatedAt.Time, err-}--// GetLocalPostCount will return the number of posts existing locally.-func GetLocalPostCount() (int64, error) {- ctx := context.Background()- return _datastore.GetQueries().GetLocalPostCount(ctx)-}--// SaveInboundFediverseActivity will save an event to the ap_inbound_activities table.-func SaveInboundFediverseActivity(objectIRI string, actorIRI string, eventType string, timestamp time.Time) error {- if err := _datastore.GetQueries().AddToAcceptedActivities(context.Background(), db.AddToAcceptedActivitiesParams{- Iri: objectIRI,- Actor: actorIRI,- Type: eventType,- Timestamp: timestamp,- }); err != nil {- return errors.Wrap(err, "error saving event "+objectIRI)- }-- return nil-}--// GetInboundActivities will return a collection of saved, federated activities-// limited and offset by the values provided to support pagination.-func GetInboundActivities(limit int, offset int) ([]models.FederatedActivity, int, error) {- ctx := context.Background()- rows, err := _datastore.GetQueries().GetInboundActivitiesWithOffset(ctx, db.GetInboundActivitiesWithOffsetParams{- Limit: int64(limit),- Offset: int64(offset),- })- if err != nil {- return nil, 0, err- }-- activities := make([]models.FederatedActivity, 0)-- total, err := _datastore.GetQueries().GetInboundActivityCount(context.Background())- if err != nil {- return nil, 0, errors.Wrap(err, "unable to fetch total activity count")- }-- for _, row := range rows {- singleActivity := models.FederatedActivity{- IRI: row.Iri,- ActorIRI: row.Actor,- Type: row.Type,- Timestamp: row.Timestamp,- }- activities = append(activities, singleActivity)- }-- return activities, int(total), nil-}--// HasPreviouslyHandledInboundActivity will return if we have previously handled-// an inbound federated activity.-func HasPreviouslyHandledInboundActivity(iri string, actorIRI string, eventType string) (bool, error) {- exists, err := _datastore.GetQueries().DoesInboundActivityExist(context.Background(), db.DoesInboundActivityExistParams{- Iri: iri,- Actor: actorIRI,- Type: eventType,- })- if err != nil {- return false, err- }-- return exists > 0, nil-}diff --git a/activitypub/workerpool/outbound.go b/activitypub/workerpool/outbound.godeleted file mode 100644index ad7f044596..0000000000--- a/activitypub/workerpool/outbound.go+++ /dev/null@@ -1,172 +0,0 @@-package workerpool--import (- "net/http"- "sync"- "time"-- "github.com/owncast/owncast/utils"- log "github.com/sirupsen/logrus"-)--// Job struct bundling the ActivityPub and the payload in one struct.-type Job struct {- request *http.Request-}--var queue chan Job--// Circuit breaker backoff durations for exponential backoff.-var circuitBreakerBackoffDurations = []time.Duration{- 1 * time.Minute, // 1st failure: 1 minute- 5 * time.Minute, // 2nd failure: 5 minutes- 15 * time.Minute, // 3rd failure: 15 minutes- 30 * time.Minute, // 4th failure: 30 minutes- 60 * time.Minute, // 5+ failures: 1 hour (max)-}--// httpClient is a configured HTTP client with timeouts and connection limits.-var httpClient *http.Client--// failedDomains tracks domains that are consistently failing with their failure count and backoff time.-var (- failedDomains = make(map[string]*domainFailure)- failedDomainsMutex sync.RWMutex-)--type domainFailure struct {- count int- lastFailed time.Time- backoffUntil time.Time-}--// InitOutboundWorkerPool starts n go routines that await ActivityPub jobs.-func InitOutboundWorkerPool(workerPoolSize int) {- // Use a larger buffer to decouple request creation from processing.- // This prevents SendToFollowers from blocking when many followers need updates.- const minQueueBuffer = 500- queueBuffer := workerPoolSize * 10- if queueBuffer < minQueueBuffer {- queueBuffer = minQueueBuffer- }- queue = make(chan Job, queueBuffer)-- // Initialize HTTP client with retry logic for transient failures- // The retryable client handles 502/503/504 errors automatically- httpClient = utils.GetRetryableHTTPClient()-- // start workers- for i := 1; i <= workerPoolSize; i++ {- go worker(i, queue)- }-}--// AddToOutboundQueue will queue up an outbound http request.-func AddToOutboundQueue(req *http.Request) {- // Check if domain should be skipped due to circuit breaker- if ShouldSkipDomain(req.URL.Host) {- log.Debugf("Skipping request to %s due to circuit breaker", req.URL.Host)- return- }-- select {- case queue <- Job{req}:- default:- log.Debugln("Outbound ActivityPub job queue is full")- queue <- Job{req} // will block until received by a worker at this point- }- log.Tracef("Queued request for ActivityPub destination %s", req.RequestURI)-}--func worker(workerID int, queue <-chan Job) {- log.Debugf("Started ActivityPub worker %d", workerID)-- for job := range queue {- if err := sendActivityPubMessageToInbox(job); err != nil {- log.Errorf("ActivityPub destination %s failed to send Error: %s", job.request.RequestURI, err)- recordDomainFailure(job.request.URL.Host)- } else {- // Reset domain failure count on success- resetDomainFailure(job.request.URL.Host)- }- log.Tracef("Done with ActivityPub destination %s using worker %d", job.request.RequestURI, workerID)- }-}--func sendActivityPubMessageToInbox(job Job) error {- resp, err := httpClient.Do(job.request)- if err != nil {- return err- }-- defer resp.Body.Close()-- // Consider HTTP 4xx and 5xx as failures for circuit breaker purposes- if resp.StatusCode >= 400 {- return &httpError{statusCode: resp.StatusCode, message: resp.Status}- }-- return nil-}--// httpError represents an HTTP error response.-type httpError struct {- statusCode int- message string-}--func (e *httpError) Error() string {- return e.message-}--// ShouldSkipDomain checks if a domain should be skipped due to circuit breaker.-// This is exported so callers can check before expensive operations like request signing.-func ShouldSkipDomain(domain string) bool {- failedDomainsMutex.RLock()- defer failedDomainsMutex.RUnlock()-- failure, exists := failedDomains[domain]- if !exists {- return false- }-- // If we're still in backoff period, skip this domain- return time.Now().Before(failure.backoffUntil)-}--// recordDomainFailure records a failure for a domain and implements exponential backoff.-func recordDomainFailure(domain string) {- failedDomainsMutex.Lock()- defer failedDomainsMutex.Unlock()-- failure, exists := failedDomains[domain]- if !exists {- failure = &domainFailure{}- failedDomains[domain] = failure- }-- failure.count++- failure.lastFailed = time.Now()-- // Use exponential backoff with pre-defined durations- backoffIndex := failure.count - 1- if backoffIndex >= len(circuitBreakerBackoffDurations) {- backoffIndex = len(circuitBreakerBackoffDurations) - 1- }-- backoffDuration := circuitBreakerBackoffDurations[backoffIndex]- failure.backoffUntil = time.Now().Add(backoffDuration)-- log.Warnf("Domain %s failed %d times, backing off for %v", domain, failure.count, backoffDuration)-}--// resetDomainFailure resets the failure count for a domain on successful delivery.-func resetDomainFailure(domain string) {- failedDomainsMutex.Lock()- defer failedDomainsMutex.Unlock()-- if failure, exists := failedDomains[domain]; exists && failure.count > 0 {- log.Debugf("Resetting failure count for domain %s after successful delivery", domain)- delete(failedDomains, domain)- }-}diff --git a/activitypub/workerpool/outbound_test.go b/activitypub/workerpool/outbound_test.godeleted file mode 100644index 2a6c28f323..0000000000--- a/activitypub/workerpool/outbound_test.go+++ /dev/null@@ -1,133 +0,0 @@-package workerpool--import (- "testing"- "time"-)--// resetCircuitBreakerForTesting clears all failed domain state for testing purposes.-// This function provides test isolation by resetting the global circuit breaker state.-func resetCircuitBreakerForTesting() {- failedDomainsMutex.Lock()- defer failedDomainsMutex.Unlock()- failedDomains = make(map[string]*domainFailure)-}--func TestCircuitBreaker(t *testing.T) {- // Ensure clean state before test- resetCircuitBreakerForTesting()- defer resetCircuitBreakerForTesting() // Clean up after test-- testDomain := "failing.example.com"-- // Initially, domain should not be skipped- if ShouldSkipDomain(testDomain) {- t.Error("Domain should not be skipped initially")- }-- // Record failures- recordDomainFailure(testDomain)- recordDomainFailure(testDomain)- recordDomainFailure(testDomain)-- // Domain should now be skipped- if !ShouldSkipDomain(testDomain) {- t.Error("Domain should be skipped after failures")- }-- // After successful delivery, domain should be reset- resetDomainFailure(testDomain)- if ShouldSkipDomain(testDomain) {- t.Error("Domain should not be skipped after reset")- }-}--func TestHTTPTimeouts(t *testing.T) {- // Ensure clean state before test- resetCircuitBreakerForTesting()- defer resetCircuitBreakerForTesting() // Clean up after test-- // Initialize HTTP client- InitOutboundWorkerPool(1)-- if httpClient == nil {- t.Error("HTTP client should be initialized")- }-- if httpClient.Timeout != 8*time.Second {- t.Errorf("HTTP client should have 8 second timeout, got %v", httpClient.Timeout)- }-}--func TestWorkerPoolSizing(t *testing.T) {- // Ensure clean state before test- resetCircuitBreakerForTesting()- defer resetCircuitBreakerForTesting() // Clean up after test-- // Test that queue buffer is at least the minimum (500) even for small worker pools- InitOutboundWorkerPool(5)-- if cap(queue) < 500 {- t.Errorf("Queue capacity should be at least 500, got %d", cap(queue))- }-- // Test that larger worker pools get proportionally larger buffers- InitOutboundWorkerPool(100)- if cap(queue) != 1000 {- t.Errorf("Queue capacity should be 1000 for 100 workers, got %d", cap(queue))- }-}--func TestBackoffDurations(t *testing.T) {- // Test that backoff durations are properly configured- expectedDurations := []time.Duration{- 1 * time.Minute,- 5 * time.Minute,- 15 * time.Minute,- 30 * time.Minute,- 60 * time.Minute,- }-- if len(circuitBreakerBackoffDurations) != len(expectedDurations) {- t.Errorf("Expected %d backoff durations, got %d", len(expectedDurations), len(circuitBreakerBackoffDurations))- }-- for i, expected := range expectedDurations {- if circuitBreakerBackoffDurations[i] != expected {- t.Errorf("Backoff duration at index %d: expected %v, got %v", i, expected, circuitBreakerBackoffDurations[i])- }- }-}--func TestCircuitBreakerIsolation(t *testing.T) {- // Test that multiple tests don't interfere with each other- resetCircuitBreakerForTesting()- defer resetCircuitBreakerForTesting()-- domain1 := "test1.example.com"- domain2 := "test2.example.com"-- // Neither domain should be blocked initially- if ShouldSkipDomain(domain1) || ShouldSkipDomain(domain2) {- t.Error("Domains should not be blocked initially")- }-- // Record failures for domain1 only- recordDomainFailure(domain1)- recordDomainFailure(domain1)- recordDomainFailure(domain1)-- // Only domain1 should be blocked- if !ShouldSkipDomain(domain1) {- t.Error("Domain1 should be blocked after failures")- }- if ShouldSkipDomain(domain2) {- t.Error("Domain2 should not be blocked")- }-- // Reset and verify clean state- resetCircuitBreakerForTesting()- if ShouldSkipDomain(domain1) || ShouldSkipDomain(domain2) {- t.Error("Both domains should be unblocked after reset")- }-}diff --git a/auth/fediverse/fediverse.go b/auth/fediverse/fediverse.goindex 375c9315c7..69b93e0e18 100644--- a/auth/fediverse/fediverse.go+++ b/auth/fediverse/fediverse.go@@ -20,43 +20,56 @@ type OTPRegistration struct {Account string}-// Key by access token to limit one OTP request for a person-// to be active at a time.-var (- pendingAuthRequests = make(map[string]OTPRegistration)- lock = sync.Mutex{}-)-const (registrationTimeout = time.Minute * 10maxPendingRequests = 1000)-func init() {- go setupExpiredRequestPruner()+// Service bundles the per-instance state for the Fediverse OTP flow.+// Construct once in main() with New() and call Start() to launch the+// expired-request pruner; inject into the handlers that need to register+// and validate OTPs.+type Service struct {+ // Key by access token to limit one OTP request for a person+ // to be active at a time.+ pendingAuthRequests map[string]OTPRegistration+ lock sync.Mutex+}++// New constructs a Service.+func New() *Service {+ return &Service{+ pendingAuthRequests: make(map[string]OTPRegistration),+ }+}++// Start launches the background goroutine that prunes expired OTP+// requests. Safe to call exactly once after New().+func (s *Service) Start() {+ go s.runExpiredRequestPruner()}-// Clear out any pending requests that have been pending for greater than-// the specified timeout value.-func setupExpiredRequestPruner() {+// runExpiredRequestPruner clears out any pending requests that have been+// pending for greater than the specified timeout value.+func (s *Service) runExpiredRequestPruner() {pruneExpiredRequestsTimer := time.NewTicker(registrationTimeout)for range pruneExpiredRequestsTimer.C {- lock.Lock()+ s.lock.Lock()log.Debugln("Pruning expired OTP requests.")- for k, v := range pendingAuthRequests {+ for k, v := range s.pendingAuthRequests {if time.Since(v.Timestamp) > registrationTimeout {- delete(pendingAuthRequests, k)+ delete(s.pendingAuthRequests, k)}}- lock.Unlock()+ s.lock.Unlock()}}// RegisterFediverseOTP will start the OTP flow for a user, creating a new// code and returning it to be sent to a destination.-func RegisterFediverseOTP(accessToken, userID, userDisplayName, account string) (OTPRegistration, bool, error) {- request, requestExists := pendingAuthRequests[accessToken]+func (s *Service) RegisterFediverseOTP(accessToken, userID, userDisplayName, account string) (OTPRegistration, bool, error) {+ request, requestExists := s.pendingAuthRequests[accessToken]// If a request is already registered and has not expired then return that// existing request.@@ -64,10 +77,10 @@ func RegisterFediverseOTP(accessToken, userID, userDisplayName, account string)return request, false, nil}- lock.Lock()- defer lock.Unlock()+ s.lock.Lock()+ defer s.lock.Unlock()- if len(pendingAuthRequests)+1 > maxPendingRequests {+ if len(s.pendingAuthRequests)+1 > maxPendingRequests {return request, false, errors.New("too many pending requests, please try again later")}@@ -79,23 +92,23 @@ func RegisterFediverseOTP(accessToken, userID, userDisplayName, account string)Account: strings.ToLower(account),Timestamp: time.Now(),}- pendingAuthRequests[accessToken] = r+ s.pendingAuthRequests[accessToken] = rreturn r, true, nil}// ValidateFediverseOTP will verify a OTP code for a auth request.-func ValidateFediverseOTP(accessToken, code string) (bool, *OTPRegistration) {- request, ok := pendingAuthRequests[accessToken]+func (s *Service) ValidateFediverseOTP(accessToken, code string) (bool, *OTPRegistration) {+ request, ok := s.pendingAuthRequests[accessToken]if !ok || request.Code != code || time.Since(request.Timestamp) > registrationTimeout {return false, nil}- lock.Lock()- defer lock.Unlock()+ s.lock.Lock()+ defer s.lock.Unlock()- delete(pendingAuthRequests, accessToken)+ delete(s.pendingAuthRequests, accessToken)return true, &request}diff --git a/auth/fediverse/fediverse_test.go b/auth/fediverse/fediverse_test.goindex c9b3b35502..eedb6b1fd2 100644--- a/auth/fediverse/fediverse_test.go+++ b/auth/fediverse/fediverse_test.go@@ -15,7 +15,8 @@ const ()func TestOTPFlowValidation(t *testing.T) {- r, success, err := RegisterFediverseOTP(accessToken, userID, userDisplayName, account)+ svc := New()+ r, success, err := svc.RegisterFediverseOTP(accessToken, userID, userDisplayName, account)if err != nil {t.Error(err)}@@ -36,7 +37,7 @@ func TestOTPFlowValidation(t *testing.T) {t.Error("Timestamp is empty")}- valid, registration := ValidateFediverseOTP(accessToken, r.Code)+ valid, registration := svc.ValidateFediverseOTP(accessToken, r.Code)if !valid {t.Error("Code is not valid")}@@ -55,8 +56,9 @@ func TestOTPFlowValidation(t *testing.T) {}func TestSingleOTPFlowRequest(t *testing.T) {- r1, _, _ := RegisterFediverseOTP(accessToken, userID, userDisplayName, account)- r2, s2, _ := RegisterFediverseOTP(accessToken, userID, userDisplayName, account)+ svc := New()+ r1, _, _ := svc.RegisterFediverseOTP(accessToken, userID, userDisplayName, account)+ r2, s2, _ := svc.RegisterFediverseOTP(accessToken, userID, userDisplayName, account)if r1.Code != r2.Code {t.Error("Only one registration should be permitted.")@@ -68,14 +70,15 @@ func TestSingleOTPFlowRequest(t *testing.T) {}func TestAccountCaseInsensitive(t *testing.T) {+ svc := New()account := "Account"accessToken := "another-fake-access-token"- r1, _, _ := RegisterFediverseOTP(accessToken, userID, userDisplayName, account)- _, reg1 := ValidateFediverseOTP(accessToken, r1.Code)+ r1, _, _ := svc.RegisterFediverseOTP(accessToken, userID, userDisplayName, account)+ _, reg1 := svc.ValidateFediverseOTP(accessToken, r1.Code)// Simulate second auth with account in different case- r2, _, _ := RegisterFediverseOTP(accessToken, userID, userDisplayName, strings.ToUpper(account))- _, reg2 := ValidateFediverseOTP(accessToken, r2.Code)+ r2, _, _ := svc.RegisterFediverseOTP(accessToken, userID, userDisplayName, strings.ToUpper(account))+ _, reg2 := svc.ValidateFediverseOTP(accessToken, r2.Code)if reg1.Account != reg2.Account {t.Errorf("Account names should be case-insensitive: %s %s", reg1.Account, reg2.Account)@@ -83,14 +86,15 @@ func TestAccountCaseInsensitive(t *testing.T) {}func TestLimitGlobalPendingRequests(t *testing.T) {- for i := 0; i < maxPendingRequests-1; i++ {+ svc := New()+ for i := 0; i < maxPendingRequests; i++ {at, _ := utils.GenerateRandomString(10)uid, _ := utils.GenerateRandomString(10)account, _ := utils.GenerateRandomString(10)- _, success, error := RegisterFediverseOTP(at, uid, "userDisplayName", account)+ _, success, error := svc.RegisterFediverseOTP(at, uid, "userDisplayName", account)if !success {- t.Error("Registration should be permitted.", i, " of ", len(pendingAuthRequests))+ t.Error("Registration should be permitted.", i, " of ", len(svc.pendingAuthRequests))}if error != nil {t.Error(error)@@ -101,7 +105,7 @@ func TestLimitGlobalPendingRequests(t *testing.T) {at, _ := utils.GenerateRandomString(10)uid, _ := utils.GenerateRandomString(10)account, _ := utils.GenerateRandomString(10)- _, success, error := RegisterFediverseOTP(at, uid, "userDisplayName", account)+ _, success, error := svc.RegisterFediverseOTP(at, uid, "userDisplayName", account)if success {t.Error("Registration should not be permitted.")}diff --git a/auth/indieauth/client.go b/auth/indieauth/client.goindex 7e2afde5d0..bb7fbef009 100644--- a/auth/indieauth/client.go+++ b/auth/indieauth/client.go@@ -8,49 +8,17 @@ import ("net/url""strconv""strings"- "sync"- "time"- "github.com/owncast/owncast/persistence/configrepository"- "github.com/owncast/owncast/utils""github.com/pkg/errors"log "github.com/sirupsen/logrus"-)-var (- pendingAuthRequests = make(map[string]*Request)- lock = sync.Mutex{}+ "github.com/owncast/owncast/utils")-const registrationTimeout = time.Minute * 10--func init() {- go setupExpiredRequestPruner()-}--// Clear out any pending requests that have been pending for greater than-// the specified timeout value.-func setupExpiredRequestPruner() {- pruneExpiredRequestsTimer := time.NewTicker(registrationTimeout)-- for range pruneExpiredRequestsTimer.C {- lock.Lock()- log.Debugln("Pruning expired IndieAuth requests.")- for k, v := range pendingAuthRequests {- if time.Since(v.Timestamp) > registrationTimeout {- delete(pendingAuthRequests, k)- }- }- lock.Unlock()- }-}-// StartAuthFlow will begin the IndieAuth flow by generating an auth request.-func StartAuthFlow(authHost, userID, accessToken, displayName string) (*url.URL, error) {- configRepository := configrepository.Get()-+func (s *Service) StartAuthFlow(authHost, userID, accessToken, displayName string) (*url.URL, error) {// Limit the number of pending requests- if len(pendingAuthRequests) >= maxPendingRequests {+ if len(s.pendingAuthRequests) >= maxPendingRequests {return nil, errors.New("Please try again later. Too many pending requests.")}@@ -70,7 +38,7 @@ func StartAuthFlow(authHost, userID, accessToken, displayName string) (*url.URL,return nil, errors.New("only servers secured with https are supported")}- serverURL := configRepository.GetServerURL()+ serverURL := s.configRepository.GetServerURL()if serverURL == "" {return nil, errors.New("Owncast server URL must be set when using auth")}@@ -80,15 +48,15 @@ func StartAuthFlow(authHost, userID, accessToken, displayName string) (*url.URL,return nil, errors.Wrap(err, "unable to generate IndieAuth request")}- pendingAuthRequests[r.State] = r+ s.pendingAuthRequests[r.State] = rreturn r.Redirect, nil}// HandleCallbackCode will handle the callback from the IndieAuth server// to continue the next step of the auth flow.-func HandleCallbackCode(code, state string) (*Request, *Response, error) {- request, exists := pendingAuthRequests[state]+func (s *Service) HandleCallbackCode(code, state string) (*Request, *Response, error) {+ request, exists := s.pendingAuthRequests[state]if !exists {return nil, nil, errors.New("no auth requests pending")}diff --git a/auth/indieauth/indieauth_test.go b/auth/indieauth/indieauth_test.goindex 89697c9253..02b99424f6 100644--- a/auth/indieauth/indieauth_test.go+++ b/auth/indieauth/indieauth_test.go@@ -6,18 +6,11 @@ import ("github.com/owncast/owncast/utils")-// isolatePendingServerAuthRequests gives a test its own pending-request map-// and restores the previous contents on cleanup, so tests in this package-// don't leak state into one another or become order-dependent.-func isolatePendingServerAuthRequests(t *testing.T) {- t.Helper()- prev := pendingServerAuthRequests- pendingServerAuthRequests = map[string]ServerAuthRequest{}- t.Cleanup(func() { pendingServerAuthRequests = prev })-}-func TestLimitGlobalPendingRequests(t *testing.T) {- isolatePendingServerAuthRequests(t)+ // Construct an isolated Service for this test. CompleteServerAuth is+ // not called here, so the ConfigRepository can be nil. Each Service owns+ // its own pending-request map, so no global reset is needed.+ svc := New(Deps{ConfigRepository: nil})// client_id and redirect_uri must be valid same-host absolute URLs to// pass StartServerAuth's validation; the slug just keeps them unique.@@ -33,41 +26,41 @@ func TestLimitGlobalPendingRequests(t *testing.T) {state, _ := utils.GenerateRandomString(10)me, _ := utils.GenerateRandomString(10)- _, err := StartServerAuth(cid, redirectURL, cc, state, me)+ _, err := svc.StartServerAuth(cid, redirectURL, cc, state, me)if err != nil {- t.Error("Registration should be permitted.", i, " of ", len(pendingServerAuthRequests), err)+ t.Error("Registration should be permitted.", i, " of ", len(svc.pendingServerAuthRequests), err)}}- // This should throw an error+ // This should throw an error.cid, redirectURL := clientURLs()cc, _ := utils.GenerateRandomString(10)state, _ := utils.GenerateRandomString(10)me, _ := utils.GenerateRandomString(10)- _, err := StartServerAuth(cid, redirectURL, cc, state, me)+ _, err := svc.StartServerAuth(cid, redirectURL, cc, state, me)if err == nil {t.Error("Registration should not be permitted.")}}func TestRejectMismatchedRedirectURI(t *testing.T) {- isolatePendingServerAuthRequests(t)+ svc := New(Deps{ConfigRepository: nil})// A redirect_uri on a different host than client_id must be rejected so// the auth endpoint can't be used as an open redirect.- if _, err := StartServerAuth("https://client.example", "https://attacker.example/callback", "cc", "state", "me"); err == nil {+ if _, err := svc.StartServerAuth("https://client.example", "https://attacker.example/callback", "cc", "state", "me"); err == nil {t.Error("redirect_uri on a foreign host should be rejected")}// A same-host redirect_uri is accepted.- if _, err := StartServerAuth("https://client.example", "https://client.example/callback", "cc", "state", "me"); err != nil {+ if _, err := svc.StartServerAuth("https://client.example", "https://client.example/callback", "cc", "state", "me"); err != nil {t.Error("same-host redirect_uri should be permitted:", err)}}func TestRejectNonWebRedirectURI(t *testing.T) {- isolatePendingServerAuthRequests(t)+ svc := New(Deps{ConfigRepository: nil})// Opaque/non-http(s) URIs (javascript:, data:, mailto:) have an empty// hostname; without a scheme+host check, two of them would pass the@@ -83,7 +76,7 @@ func TestRejectNonWebRedirectURI(t *testing.T) {}for _, tc := range cases {- if _, err := StartServerAuth(tc.clientID, tc.redirectURI, "cc", "state", "me"); err == nil {+ if _, err := svc.StartServerAuth(tc.clientID, tc.redirectURI, "cc", "state", "me"); err == nil {t.Errorf("%s: should be rejected", tc.name)}}diff --git a/auth/indieauth/server.go b/auth/indieauth/server.goindex 4ad37b5391..a9f2226f25 100644--- a/auth/indieauth/server.go+++ b/auth/indieauth/server.go@@ -6,7 +6,6 @@ import ("strings""time"- "github.com/owncast/owncast/persistence/configrepository""github.com/pkg/errors""github.com/teris-io/shortid")@@ -40,8 +39,6 @@ type ServerProfileResponse struct {ErrorDescription string `json:"error_description,omitempty"`}-var pendingServerAuthRequests = map[string]ServerAuthRequest{}-const maxPendingRequests = 100const (@@ -52,11 +49,7 @@ const (// StartServerAuth will handle the authentication for the admin user of this// Owncast server. Initiated via a GET of the auth endpoint.// https://indieweb.org/authorization-endpoint-func StartServerAuth(clientID, redirectURI, codeChallenge, state, me string) (*ServerAuthRequest, error) {- if len(pendingServerAuthRequests)+1 >= maxPendingRequests {- return nil, errors.New("Please try again later. Too many pending requests.")- }-+func (s *Service) StartServerAuth(clientID, redirectURI, codeChallenge, state, me string) (*ServerAuthRequest, error) {// Validate the redirect URI against the client ID before the auth// endpoint hands it to the browser. Without this the endpoint is an open// redirect: a crafted redirect_uri would send the generated auth code to@@ -65,6 +58,13 @@ func StartServerAuth(clientID, redirectURI, codeChallenge, state, me string) (*Sreturn nil, err}+ s.pendingServerAuthRequestsLock.Lock()+ defer s.pendingServerAuthRequestsLock.Unlock()++ if len(s.pendingServerAuthRequests)+1 >= maxPendingRequests {+ return nil, errors.New("Please try again later. Too many pending requests.")+ }+code := shortid.MustGenerate()r := ServerAuthRequest{@@ -77,7 +77,7 @@ func StartServerAuth(clientID, redirectURI, codeChallenge, state, me string) (*STimestamp: time.Now(),}- pendingServerAuthRequests[code] = r+ s.pendingServerAuthRequests[code] = rreturn &r, nil}@@ -126,10 +126,10 @@ func isWebURL(u *url.URL) bool {// CompleteServerAuth will verify that the values provided in the final step// of the IndieAuth flow are correct, and return some basic profile info.-func CompleteServerAuth(code, redirectURI, clientID string, codeVerifier string) (*ServerProfileResponse, error) {- configRepository := configrepository.Get()-- request, pending := pendingServerAuthRequests[code]+func (s *Service) CompleteServerAuth(code, redirectURI, clientID string, codeVerifier string) (*ServerProfileResponse, error) {+ s.pendingServerAuthRequestsLock.Lock()+ request, pending := s.pendingServerAuthRequests[code]+ s.pendingServerAuthRequestsLock.Unlock()if !pending {return nil, errors.New("no pending authentication request")}@@ -148,11 +148,11 @@ func CompleteServerAuth(code, redirectURI, clientID string, codeVerifier string)}response := ServerProfileResponse{- Me: configRepository.GetServerURL(),+ Me: s.configRepository.GetServerURL(),Profile: ServerProfile{- Name: configRepository.GetServerName(),- URL: configRepository.GetServerURL(),- Photo: fmt.Sprintf("%s/%s", configRepository.GetServerURL(), configRepository.GetLogoPath()),+ Name: s.configRepository.GetServerName(),+ URL: s.configRepository.GetServerURL(),+ Photo: fmt.Sprintf("%s/%s", s.configRepository.GetServerURL(), s.configRepository.GetLogoPath()),},}diff --git a/auth/indieauth/service.go b/auth/indieauth/service.gonew file mode 100644index 0000000000..34468dd5f8--- /dev/null+++ b/auth/indieauth/service.go@@ -0,0 +1,60 @@+package indieauth++import (+ "sync"+ "time"++ log "github.com/sirupsen/logrus"++ "github.com/owncast/owncast/persistence/configrepository"+)++const registrationTimeout = time.Minute * 10++// Service bundles the dependencies and per-instance state needed by the+// IndieAuth flows (both this Owncast server acting as a client against a+// remote IndieAuth endpoint, and this Owncast server acting as its own+// IndieAuth server). Construct once in main() and inject into HTTP+// handlers that drive auth flows.+type Service struct {+ configRepository configrepository.ConfigRepository++ pendingAuthRequestsLock sync.Mutex+ pendingAuthRequests map[string]*Request++ pendingServerAuthRequestsLock sync.Mutex+ pendingServerAuthRequests map[string]ServerAuthRequest+}++// Deps lists the services this Service needs.+type Deps struct {+ ConfigRepository configrepository.ConfigRepository+}++// New constructs a Service. It also starts a background goroutine that+// periodically prunes expired client-side auth requests.+func New(deps Deps) *Service {+ s := &Service{+ configRepository: deps.ConfigRepository,+ pendingAuthRequests: make(map[string]*Request),+ pendingServerAuthRequests: make(map[string]ServerAuthRequest),+ }+ go s.runExpiredRequestPruner()+ return s+}++// runExpiredRequestPruner clears out any pending client-side requests+// that have been waiting longer than registrationTimeout.+func (s *Service) runExpiredRequestPruner() {+ ticker := time.NewTicker(registrationTimeout)+ for range ticker.C {+ s.pendingAuthRequestsLock.Lock()+ log.Debugln("Pruning expired IndieAuth requests.")+ for k, v := range s.pendingAuthRequests {+ if time.Since(v.Timestamp) > registrationTimeout {+ delete(s.pendingAuthRequests, k)+ }+ }+ s.pendingAuthRequestsLock.Unlock()+ }+}diff --git a/config/config.go b/config/config.goindex 4e07c448f2..6462edb341 100644--- a/config/config.go+++ b/config/config.go@@ -2,51 +2,95 @@ package configimport ("fmt"+ "path/filepath""time")-// These are runtime-set values used for configuration.--// DatabaseFilePath is the path to the file ot be used as the global database for this run of the application.-var DatabaseFilePath = "data/owncast.db"--// LogDirectory is the path to various log files.-var LogDirectory = "./data/logs"--// TempDir is where we store temporary files.-var TempDir = "./data/tmp"+// Config holds runtime-mutable configuration for a single execution of the+// Owncast server. It is populated by the composition root (main.go) from+// CLI flags + persisted settings, then threaded by value-of-pointer into+// every service that reads any of these fields.+//+// All fields are runtime state — values that change between executions or+// are overridden at startup. Compile-time constants (see constants.go),+// build-time-set vars (VersionNumber, GitCommit, BuildPlatform), and the+// build-tag-driven EnableAutoUpdate remain package-level on purpose: they+// are not runtime state.+type Config struct {+ // DatabaseFilePath is the path to the file used as the global database+ // for this run of the application.+ DatabaseFilePath string++ // LogDirectory is the path to various log files.+ LogDirectory string++ // TempDir is where we store temporary files.+ TempDir string++ // BackupDirectory is the directory we write backup files to.+ BackupDirectory string++ // WebServerPort is the port the public webserver listens on.+ WebServerPort int++ // WebServerIP is the IP address to bind the web server to. All+ // interfaces by default.+ WebServerIP string++ // InternalHLSListenerPort is the port the in-process HLS receiver+ // binds to. Discovered at runtime when the receiver opens its+ // listener and read by the transcoder when it spins up.+ InternalHLSListenerPort string++ // EnableDebugFeatures prints additional data to help in debugging.+ EnableDebugFeatures bool++ // TemporaryStreamKey is a stream key set via the command line that+ // overrides the persisted keys for the duration of this process.+ TemporaryStreamKey string++ // FollowerValidationInterval is how often the follower validation+ // job runs. A zero value means use the package default.+ FollowerValidationInterval time.Duration+}-// EnableDebugFeatures will print additional data to help in debugging.-var EnableDebugFeatures = false+// NewDefault returns a *Config populated with the default startup values.+// main.go overlays CLI flag values on top of this before injecting it+// into services.+func NewDefault() *Config {+ return &Config{+ DatabaseFilePath: "data/owncast.db",+ LogDirectory: "./data/logs",+ TempDir: "./data/tmp",+ BackupDirectory: filepath.Join(DataDirectory, "backup"),+ WebServerPort: 8080,+ WebServerIP: "0.0.0.0",+ InternalHLSListenerPort: "8927",+ EnableDebugFeatures: false,+ TemporaryStreamKey: "",+ // FollowerValidationInterval defaults to 0; consumers use their+ // package-level default when zero.+ }+}-// VersionNumber is the current version string.+// VersionNumber is the current version string. Set at build time via+// linker flags; defaults to StaticVersionNumber for local builds.var VersionNumber = StaticVersionNumber-// WebServerPort is the port for Owncast's webserver that is used for this execution of the service.-var WebServerPort = 8080--// WebServerIP is the IP address to bind the web server to. All interfaces by default.-var WebServerIP = "0.0.0.0"--// InternalHLSListenerPort is the port for HLS writes that is used for this execution of the service.-var InternalHLSListenerPort = "8927"--// GitCommit is an optional commit this build was made from.+// GitCommit is an optional commit this build was made from. Set at+// build time via linker flags.var GitCommit = ""// BuildPlatform is the optional platform this release was built for.+// Set at build time via linker flags; "dev" for local builds.var BuildPlatform = "dev"-// EnableAutoUpdate will explicitly enable in-place auto-updates via the admin.+// EnableAutoUpdate will explicitly enable in-place auto-updates via the+// admin. Toggled by the enable_updates build tag (see+// updaterConfig_enabled.go); package-level because the build tag, not+// the runtime, owns its value.var EnableAutoUpdate = false-// A temporary stream key that can be set via the command line.-var TemporaryStreamKey = ""--// FollowerValidationInterval is how often the follower validation job runs.-// Defaults to 0 which means use the default (1 hour).-var FollowerValidationInterval time.Duration = 0-// GetCommit will return an identifier used for identifying the point in time this build took place.func GetCommit() string {if GitCommit == "" {diff --git a/config/constants.go b/config/constants.goindex 6f3c78bdb2..349fb21f8a 100644--- a/config/constants.go+++ b/config/constants.go@@ -19,9 +19,6 @@ const ()var (- // BackupDirectory is the directory we write backup files to.- BackupDirectory = filepath.Join(DataDirectory, "backup")-// HLSStoragePath is the directory HLS video is written to.HLSStoragePath = filepath.Join(DataDirectory, "hls")diff --git a/core/cache/cache.go b/core/cache/cache.godeleted file mode 100644index 1c9c2fb2b9..0000000000--- a/core/cache/cache.go+++ /dev/null@@ -1,82 +0,0 @@-package cache--import (- "time"-- "github.com/jellydator/ttlcache/v3"-)--// CacheContainer is a container for all caches.-type CacheContainer struct {- caches map[string]*CacheInstance-}--// CacheInstance is a single cache instance.-type CacheInstance struct {- cache *ttlcache.Cache[string, []byte]-}--// This is the global singleton instance. (To be removed after refactor).-var _instance *CacheContainer--// NewCache creates a new cache instance.-func NewGlobalCache() *CacheContainer {- _instance = &CacheContainer{- caches: make(map[string]*CacheInstance),- }-- return _instance-}--// GetCache returns the cache instance.-func GetGlobalCache() *CacheContainer {- if _instance != nil {- return _instance- }- return NewGlobalCache()-}--// GetOrCreateCache returns the cache instance or creates a new one.-func (c *CacheContainer) GetOrCreateCache(name string, expiration time.Duration) *CacheInstance {- if _, ok := c.caches[name]; !ok {- c.CreateCache(name, expiration)- }- return c.caches[name]-}--// CreateCache creates a new cache instance.-func (c *CacheContainer) CreateCache(name string, expiration time.Duration) *CacheInstance {- cache := ttlcache.New[string, []byte](- ttlcache.WithTTL[string, []byte](expiration),- ttlcache.WithDisableTouchOnHit[string, []byte](),- )- ci := &CacheInstance{cache: cache}- c.caches[name] = ci- go cache.Start()- return ci-}--// GetCache returns the cache instance.-func (c *CacheContainer) GetCache(name string) *CacheInstance {- return c.caches[name]-}--// GetValueForKey returns the value for the given key.-func (ci *CacheInstance) GetValueForKey(key string) []byte {- value := ci.cache.Get(key, ttlcache.WithDisableTouchOnHit[string, []byte]())- if value == nil {- return nil- }-- if value.IsExpired() {- return nil- }-- val := value.Value()- return val-}--// Set sets the value for the given key..-func (ci *CacheInstance) Set(key string, value []byte) {- ci.cache.Set(key, value, 0)-}diff --git a/core/cache/cache_test.go b/core/cache/cache_test.godeleted file mode 100644index 9d70f51145..0000000000--- a/core/cache/cache_test.go+++ /dev/null@@ -1,72 +0,0 @@-package cache--import (- "strconv"- "testing"- "time"-- "github.com/stretchr/testify/assert"-)--func TestCache(t *testing.T) {- expiration := 5 * time.Second- globalCache := GetGlobalCache()- assert.NotNil(t, globalCache, "NewGlobalCache should return a non-nil instance")- assert.Equal(t, globalCache, GetGlobalCache(), "GetGlobalCache should return the created instance")-- cacheName := "testCache"- globalCache.CreateCache(cacheName, expiration)-- createdCache := globalCache.GetCache(cacheName)- assert.NotNil(t, createdCache, "GetCache should return a non-nil cache")-- key := "testKey"- value := []byte("testValue")- createdCache.Set(key, value)-- // Wait for cache to expire- time.Sleep(expiration + 1*time.Second)-- // Verify that the cache has expired- ci := globalCache.GetCache(cacheName)- cachedValue := ci.GetValueForKey(key)- assert.Nil(t, cachedValue, "Cache should not contain the value after expiration")-}--func TestConcurrentAccess(t *testing.T) {- // Test concurrent access to the cache- globalCache := NewGlobalCache()- cacheName := "concurrentCache"- expiration := 5 * time.Second- globalCache.CreateCache(cacheName, expiration)-- // Start multiple goroutines to access the cache concurrently- numGoroutines := 10- keyPrefix := "key"- valuePrefix := "value"-- done := make(chan struct{})- for i := 0; i < numGoroutines; i++ {- go func(index int) {- defer func() { done <- struct{}{} }()-- cache := globalCache.GetCache(cacheName)- key := keyPrefix + strconv.Itoa(index)- value := valuePrefix + strconv.Itoa(index)-- cache.Set(key, []byte(value))-- // Simulate some work- time.Sleep(100 * time.Millisecond)-- ci := globalCache.GetCache(cacheName)- cachedValue := string(ci.GetValueForKey(key))- assert.Equal(t, value, cachedValue, "Cached value should match the set value")- }(i)- }-- // Wait for all goroutines to finish- for i := 0; i < numGoroutines; i++ {- <-done- }-}diff --git a/core/chat/chat.go b/core/chat/chat.godeleted file mode 100644index fd0bb91af2..0000000000--- a/core/chat/chat.go+++ /dev/null@@ -1,189 +0,0 @@-package chat--import (- "errors"- "net/http"- "sort"-- "github.com/owncast/owncast/config"- "github.com/owncast/owncast/core/chat/events"- "github.com/owncast/owncast/models"- "github.com/owncast/owncast/persistence/chatmessagerepository"- "github.com/owncast/owncast/persistence/configrepository"- "github.com/prometheus/client_golang/prometheus"- "github.com/prometheus/client_golang/prometheus/promauto"- log "github.com/sirupsen/logrus"-)--var (- getStatus func() models.Status- chatMessagesSentCounter prometheus.Gauge-)--// Start begins the chat server.-func Start(getStatusFunc func() models.Status) error {- setupPersistence()-- configRepository := configrepository.Get()-- getStatus = getStatusFunc- _server = NewChat()-- go _server.Run()-- log.Traceln("Chat server started with max connection count of", _server.maxSocketConnectionLimit)-- chatMessagesSentCounter = promauto.NewGauge(prometheus.GaugeOpts{- Name: "total_chat_message_count",- Help: "The number of chat messages incremented over time.",- ConstLabels: map[string]string{- "version": config.VersionNumber,- "host": configRepository.GetServerURL(),- },- })-- return nil-}--// GetClientsForUser will return chat connections that are owned by a specific user.-func GetClientsForUser(userID string) ([]*Client, error) {- _server.mu.Lock()- defer _server.mu.Unlock()-- clients := map[string][]*Client{}-- for _, client := range _server.clients {- clients[client.User.ID] = append(clients[client.User.ID], client)- }-- if _, exists := clients[userID]; !exists {- return nil, errors.New("no connections for user found")- }-- return clients[userID], nil-}--// FindClientByID will return a single connected client by ID.-func FindClientByID(clientID uint) (*Client, bool) {- client, found := _server.clients[clientID]- return client, found-}--// GetClients will return all the current chat clients connected.-func GetClients() []*Client {- clients := []*Client{}-- if _server == nil {- return clients- }-- // Convert the keyed map to a slice.- for _, client := range _server.clients {- clients = append(clients, client)- }-- sort.Slice(clients, func(i, j int) bool {- return clients[i].ConnectedAt.Before(clients[j].ConnectedAt)- })-- return clients-}--// SendSystemMessage will send a message string as a system message to all clients.-func SendSystemMessage(text string, ephemeral bool) error {- message := events.SystemMessageEvent{- MessageEvent: events.MessageEvent{- Body: text,- },- }- message.SetDefaults()- message.RenderBody()-- if err := Broadcast(&message); err != nil {- log.Errorln("error sending system message", err)- }-- if !ephemeral {- chatMessageRepository := chatmessagerepository.Get()- chatMessageRepository.SaveEvent(message.ID, nil, message.Body, message.GetMessageType(), nil, message.Timestamp, nil, nil, nil, nil)- }-- return nil-}--// SendFediverseAction will send a message indicating some Fediverse engagement took place.-func SendFediverseAction(eventType string, userAccountName string, image *string, body string, link string) error {- message := events.FediverseEngagementEvent{- Event: events.Event{- Type: eventType,- },- MessageEvent: events.MessageEvent{- Body: body,- },- UserAccountName: userAccountName,- Image: image,- Link: link,- }-- message.SetDefaults()-- if err := Broadcast(&message); err != nil {- log.Errorln("error sending system message", err)- return err- }-- chatMessageRepository := chatmessagerepository.Get()- chatMessageRepository.SaveFederatedAction(message)-- return nil-}--// SendSystemAction will send a system action string as an action event to all clients.-func SendSystemAction(text string, ephemeral bool) error {- message := events.ActionEvent{- MessageEvent: events.MessageEvent{- Body: text,- },- }-- message.SetDefaults()- message.RenderBody()-- if err := Broadcast(&message); err != nil {- log.Errorln("error sending system chat action")- }-- if !ephemeral {- chatMessageRepository := chatmessagerepository.Get()- chatMessageRepository.SaveEvent(message.ID, nil, message.Body, message.GetMessageType(), nil, message.Timestamp, nil, nil, nil, nil)- }-- return nil-}--// SendAllWelcomeMessage will send the chat message to all connected clients.-func SendAllWelcomeMessage() {- _server.sendAllWelcomeMessage()-}--// SendSystemMessageToClient will send a single message to a single connected chat client.-func SendSystemMessageToClient(clientID uint, text string) {- if client, foundClient := FindClientByID(clientID); foundClient {- _server.sendSystemMessageToClient(client, text)- }-}--// Broadcast will send all connected clients the outbound object provided.-func Broadcast(event events.OutboundEvent) error {- return _server.Broadcast(event.GetBroadcastPayload())-}--// HandleClientConnection handles a single inbound websocket connection.-func HandleClientConnection(w http.ResponseWriter, r *http.Request) {- _server.HandleClientConnection(w, r)-}--// DisconnectClients will forcefully disconnect all clients belonging to a user by ID.-func DisconnectClients(clients []*Client) {- _server.DisconnectClients(clients)-}diff --git a/core/chat/messages.go b/core/chat/messages.godeleted file mode 100644index 81ccf1e8e0..0000000000--- a/core/chat/messages.go+++ /dev/null@@ -1,37 +0,0 @@-package chat--import (- "errors"-- "github.com/owncast/owncast/core/chat/events"- "github.com/owncast/owncast/core/webhooks"- "github.com/owncast/owncast/persistence/chatmessagerepository"- log "github.com/sirupsen/logrus"-)--// SetMessagesVisibility will set the visibility of multiple messages by ID.-func SetMessagesVisibility(messageIDs []string, visibility bool) error {- // Save new message visibility- chatMessageRepository := chatmessagerepository.Get()- if err := chatMessageRepository.SetMessageVisibilityForMessageIDs(messageIDs, visibility); err != nil {- log.Errorln(err)- return err- }-- // Send an event letting the chat clients know to hide or show- // the messages.- event := events.SetMessageVisibilityEvent{- MessageIDs: messageIDs,- Visible: visibility,- }- event.Event.SetDefaults()-- payload := event.GetBroadcastPayload()- if err := _server.Broadcast(payload); err != nil {- return errors.New("error broadcasting message visibility payload " + err.Error())- }-- webhooks.SendChatEventSetMessageVisibility(event)-- return nil-}diff --git a/core/core.go b/core/core.godeleted file mode 100644index 3b9184ce56..0000000000--- a/core/core.go+++ /dev/null@@ -1,137 +0,0 @@-package core--import (- "os"- "path"- "path/filepath"-- log "github.com/sirupsen/logrus"-- "github.com/owncast/owncast/config"- "github.com/owncast/owncast/core/chat"- "github.com/owncast/owncast/core/rtmp"- "github.com/owncast/owncast/core/transcoder"- "github.com/owncast/owncast/core/webhooks"- "github.com/owncast/owncast/models"- "github.com/owncast/owncast/persistence/configrepository"- "github.com/owncast/owncast/persistence/notificationsrepository"- "github.com/owncast/owncast/utils"- "github.com/owncast/owncast/yp"-)--var (- _stats *models.Stats- _storage models.StorageProvider- _transcoder *transcoder.Transcoder- _yp *yp.YP- _broadcaster *models.Broadcaster- handler transcoder.HLSHandler- fileWriter = transcoder.FileWriterReceiverService{}-)--// Start starts up the core processing.-func Start() error {- resetDirectories()- configRepository := configrepository.Get()- // configRepository.PopulateDefaults()-- if err := configRepository.VerifySettings(); err != nil {- log.Error(err)- return err- }-- if err := setupStats(); err != nil {- log.Error("failed to setup the stats")- return err- }-- // The HLS handler takes the written HLS playlists and segments- // and makes storage decisions. It's rather simple right now- // but will play more useful when recordings come into play.- handler = transcoder.HLSHandler{}-- if err := setupStorage(); err != nil {- log.Errorln("storage error", err)- }-- fileWriter.SetupFileWriterReceiverService(&handler)-- if err := createInitialOfflineState(); err != nil {- log.Error("failed to create the initial offline state")- return err- }-- _yp = yp.NewYP(GetStatus)-- if err := chat.Start(GetStatus); err != nil {- log.Errorln(err)- }-- // start the rtmp server- go rtmp.Start(setStreamAsConnected, setBroadcaster)-- rtmpPort := configRepository.GetRTMPPortNumber()- if rtmpPort != 1935 {- log.Infof("RTMP is accepting inbound streams on port %d.", rtmpPort)- }-- webhooks.SetupWebhooks(GetStatus)-- notificationsrepository.Setup()-- return nil-}--func createInitialOfflineState() error {- transitionToOfflineVideoStreamContent()-- return nil-}--// transitionToOfflineVideoStreamContent will overwrite the current stream with the-// offline video stream state only. No live stream HLS segments will continue to be-// referenced.-func transitionToOfflineVideoStreamContent() {- log.Traceln("Firing transcoder with offline stream state")-- _transcoder := transcoder.NewTranscoder()- _transcoder.SetIdentifier("offline")- _transcoder.SetLatencyLevel(models.GetLatencyLevel(4))- _transcoder.SetIsEvent(true)-- offlineFilePath, err := saveOfflineClipToDisk("offline-v2.ts")- if err != nil {- log.Fatalln("unable to save offline clip:", err)- }-- _transcoder.SetInput(offlineFilePath)- go _transcoder.Start(false)-- // Copy the logo to be the thumbnail- configRepository := configrepository.Get()- logo := configRepository.GetLogoPath()- dst := filepath.Join(config.TempDir, "thumbnail.jpg")- if err = utils.Copy(filepath.Join("data", logo), dst); err != nil {- log.Warnln(err)- }-- // Delete the preview Gif- _ = os.Remove(path.Join(config.DataDirectory, "preview.gif"))-}--func resetDirectories() {- log.Trace("Resetting file directories to a clean slate.")-- // Wipe hls data directory- utils.CleanupDirectory(config.HLSStoragePath)-- // Remove the previous thumbnail- configRepository := configrepository.Get()- logo := configRepository.GetLogoPath()- if utils.DoesFileExists(logo) {- err := utils.Copy(path.Join("data", logo), filepath.Join(config.DataDirectory, "thumbnail.jpg"))- if err != nil {- log.Warnln(err)- }- }-}diff --git a/core/playlist/writer.go b/core/playlist/writer.godeleted file mode 100644index 20e451de1d..0000000000--- a/core/playlist/writer.go+++ /dev/null@@ -1,19 +0,0 @@-package playlist--import "os"--// WritePlaylist writes the playlist to disk.-func WritePlaylist(data string, filePath string) error {- // nolint:gosec- f, err := os.Create(filePath)- if err != nil {- return err- }- defer f.Close()-- if _, err := f.WriteString(data); err != nil {- return err- }-- return nil-}diff --git a/core/stats.go b/core/stats.godeleted file mode 100644index 40251b453b..0000000000--- a/core/stats.go+++ /dev/null@@ -1,148 +0,0 @@-package core--import (- "math"- "sync"- "time"-- log "github.com/sirupsen/logrus"-- "github.com/owncast/owncast/models"- "github.com/owncast/owncast/persistence/configrepository"- "github.com/owncast/owncast/services/geoip"-)--var (- l = &sync.RWMutex{}- _activeViewerPurgeTimeout = time.Second * 15- _geoIPClient = geoip.NewClient()-)--func setupStats() error {- s := getSavedStats()- _stats = &s-- statsSaveTimer := time.NewTicker(1 * time.Minute)- go func() {- for range statsSaveTimer.C {- saveStats()- }- }()-- viewerCountPruneTimer := time.NewTicker(5 * time.Second)- go func() {- for range viewerCountPruneTimer.C {- pruneViewerCount()- }- }()-- return nil-}--// IsStreamConnected checks if the stream is connected or not.-func IsStreamConnected() bool {- if !_stats.StreamConnected {- return false- }-- // Kind of a hack. It takes a handful of seconds between a RTMP connection and when HLS data is available.- // So account for that with an artificial buffer of four segments.- timeSinceLastConnected := time.Since(_stats.LastConnectTime.Time).Seconds()- configRepository := configrepository.Get()- waitTime := math.Max(float64(configRepository.GetStreamLatencyLevel().SecondsPerSegment)*3.0, 7)- if timeSinceLastConnected < waitTime {- return false- }-- return _stats.StreamConnected-}--// RemoveChatClient removes a client from the active clients record.-func RemoveChatClient(clientID string) {- log.Trace("Removing the client:", clientID)-- l.Lock()- delete(_stats.ChatClients, clientID)- l.Unlock()-}--// SetViewerActive sets a client as active and connected.-func SetViewerActive(viewer *models.Viewer) {- // Don't update viewer counts if a live stream session is not active.- if !_stats.StreamConnected {- return- }-- l.Lock()- defer l.Unlock()-- // Asynchronously, optionally, fetch GeoIP configRepository.- go func(viewer *models.Viewer) {- viewer.Geo = _geoIPClient.GetGeoFromIP(viewer.IPAddress)- }(viewer)-- if _, exists := _stats.Viewers[viewer.ClientID]; exists {- _stats.Viewers[viewer.ClientID].LastSeen = time.Now()- } else {- _stats.Viewers[viewer.ClientID] = viewer- }- _stats.SessionMaxViewerCount = int(math.Max(float64(len(_stats.Viewers)), float64(_stats.SessionMaxViewerCount)))- _stats.OverallMaxViewerCount = int(math.Max(float64(_stats.SessionMaxViewerCount), float64(_stats.OverallMaxViewerCount)))-}--// GetActiveViewers will return the active viewers.-func GetActiveViewers() map[string]*models.Viewer {- return _stats.Viewers-}--func pruneViewerCount() {- viewers := make(map[string]*models.Viewer)-- l.Lock()- defer l.Unlock()-- for viewerID, viewer := range _stats.Viewers {- viewerLastSeenTime := _stats.Viewers[viewerID].LastSeen- if time.Since(viewerLastSeenTime) < _activeViewerPurgeTimeout {- viewers[viewerID] = viewer- }- }-- _stats.Viewers = viewers-}--func saveStats() {- configRepository := configrepository.Get()- if err := configRepository.SetPeakOverallViewerCount(_stats.OverallMaxViewerCount); err != nil {- log.Errorln("error saving viewer count", err)- }- if err := configRepository.SetPeakSessionViewerCount(_stats.SessionMaxViewerCount); err != nil {- log.Errorln("error saving viewer count", err)- }- if _stats.LastDisconnectTime != nil && _stats.LastDisconnectTime.Valid {- if err := configRepository.SetLastDisconnectTime(_stats.LastDisconnectTime.Time); err != nil {- log.Errorln("error saving disconnect time", err)- }- }-}--func getSavedStats() models.Stats {- configRepository := configrepository.Get()- savedLastDisconnectTime, _ := configRepository.GetLastDisconnectTime()-- result := models.Stats{- ChatClients: make(map[string]models.Client),- Viewers: make(map[string]*models.Viewer),- SessionMaxViewerCount: configRepository.GetPeakSessionViewerCount(),- OverallMaxViewerCount: configRepository.GetPeakOverallViewerCount(),- LastDisconnectTime: savedLastDisconnectTime,- }-- // If the stats were saved > 5min ago then ignore the- // peak session count value, since the session is over.- if result.LastDisconnectTime == nil || !result.LastDisconnectTime.Valid || time.Since(result.LastDisconnectTime.Time).Minutes() > 5 {- result.SessionMaxViewerCount = 0- }-- return result-}diff --git a/core/status.go b/core/status.godeleted file mode 100644index e6213ada54..0000000000--- a/core/status.go+++ /dev/null@@ -1,46 +0,0 @@-package core--import (- "github.com/owncast/owncast/config"- "github.com/owncast/owncast/models"- "github.com/owncast/owncast/persistence/configrepository"-)--// GetStatus gets the status of the system.-func GetStatus() models.Status {- if _stats == nil {- return models.Status{}- }-- viewerCount := 0- if IsStreamConnected() {- viewerCount = len(_stats.Viewers)- }-- configRepository := configrepository.Get()- return models.Status{- Online: IsStreamConnected(),- ViewerCount: viewerCount,- OverallMaxViewerCount: _stats.OverallMaxViewerCount,- SessionMaxViewerCount: _stats.SessionMaxViewerCount,- LastDisconnectTime: _stats.LastDisconnectTime,- LastConnectTime: _stats.LastConnectTime,- VersionNumber: config.VersionNumber,- StreamTitle: configRepository.GetStreamTitle(),- }-}--// GetCurrentBroadcast will return the currently active broadcast.-func GetCurrentBroadcast() *models.CurrentBroadcast {- return _currentBroadcast-}--// setBroadcaster will store the current inbound broadcasting details.-func setBroadcaster(broadcaster models.Broadcaster) {- _broadcaster = &broadcaster-}--// GetBroadcaster will return the details of the currently active broadcaster.-func GetBroadcaster() *models.Broadcaster {- return _broadcaster-}diff --git a/core/storage.go b/core/storage.godeleted file mode 100644index e0941ad8ac..0000000000--- a/core/storage.go+++ /dev/null@@ -1,25 +0,0 @@-package core--import (- "github.com/owncast/owncast/core/storageproviders"- "github.com/owncast/owncast/persistence/configrepository"-)--func setupStorage() error {- configRepository := configrepository.Get()- s3Config := configRepository.GetS3Config()-- if s3Config.Enabled {- _storage = storageproviders.NewS3Storage()- } else {- _storage = storageproviders.NewLocalStorage()- }-- if err := _storage.Setup(); err != nil {- return err- }-- handler.Storage = _storage-- return nil-}diff --git a/core/streamState.go b/core/streamState.godeleted file mode 100644index 455baef0a5..0000000000--- a/core/streamState.go+++ /dev/null@@ -1,205 +0,0 @@-package core--import (- "context"- "io"- "time"-- log "github.com/sirupsen/logrus"-- "github.com/owncast/owncast/activitypub"- "github.com/owncast/owncast/config"- "github.com/owncast/owncast/core/chat"- "github.com/owncast/owncast/core/data"- "github.com/owncast/owncast/core/rtmp"- "github.com/owncast/owncast/core/transcoder"- "github.com/owncast/owncast/core/webhooks"- "github.com/owncast/owncast/models"- "github.com/owncast/owncast/persistence/configrepository"- "github.com/owncast/owncast/services/notifications"- "github.com/owncast/owncast/utils"-)--// After the stream goes offline this timer fires a full cleanup after N min.-var _offlineCleanupTimer *time.Timer--// While a stream takes place cleanup old HLS content every N min.-var _onlineCleanupTicker *time.Ticker--var _currentBroadcast *models.CurrentBroadcast--var _onlineTimerCancelFunc context.CancelFunc--var _lastNotified *time.Time--// setStreamAsConnected sets the stream as connected.-func setStreamAsConnected(rtmpOut *io.PipeReader) {- now := utils.NullTime{Time: time.Now(), Valid: true}- _stats.StreamConnected = true- _stats.LastDisconnectTime = nil- _stats.LastConnectTime = &now- _stats.SessionMaxViewerCount = 0-- configRepository := configrepository.Get()-- _currentBroadcast = &models.CurrentBroadcast{- LatencyLevel: configRepository.GetStreamLatencyLevel(),- OutputSettings: configRepository.GetStreamOutputVariants(),- }-- StopOfflineCleanupTimer()- startOnlineCleanupTimer()-- if _yp != nil {- go _yp.Start()- }-- segmentPath := config.HLSStoragePath-- if err := setupStorage(); err != nil {- log.Fatalln("failed to setup the storage", err)- }-- go func() {- _transcoder = transcoder.NewTranscoder()- _transcoder.TranscoderCompleted = func(error) {- SetStreamAsDisconnected()- _transcoder = nil- _currentBroadcast = nil- }- _transcoder.SetStdin(rtmpOut)- _transcoder.Start(true)- }()-- go webhooks.SendStreamStatusEvent(models.StreamStarted)- selectedThumbnailVideoQualityIndex, isVideoPassthrough := configRepository.FindHighestVideoQualityIndex(_currentBroadcast.OutputSettings)- transcoder.StartThumbnailGenerator(segmentPath, selectedThumbnailVideoQualityIndex, isVideoPassthrough)-- _ = chat.SendSystemAction("Stay tuned, the stream is **starting**!", true)- chat.SendAllWelcomeMessage()-- // Send delayed notification messages.- _onlineTimerCancelFunc = startLiveStreamNotificationsTimer()-}--// SetStreamAsDisconnected sets the stream as disconnected.-func SetStreamAsDisconnected() {- _ = chat.SendSystemAction("The stream is ending.", true)-- now := utils.NullTime{Time: time.Now(), Valid: true}- if _onlineTimerCancelFunc != nil {- _onlineTimerCancelFunc()- }-- _stats.StreamConnected = false- _stats.LastDisconnectTime = &now- _stats.LastConnectTime = nil- _broadcaster = nil-- offlineFilename := "offline-v2.ts"-- offlineFilePath, err := saveOfflineClipToDisk(offlineFilename)- if err != nil {- log.Errorln(err)- return- }-- transcoder.StopThumbnailGenerator()- rtmp.Disconnect()-- if _yp != nil {- _yp.Stop()- }-- // If there is no current broadcast available the previous stream- // likely failed for some reason. Don't try to append to it.- // Just transition to offline.- if _currentBroadcast == nil {- stopOnlineCleanupTimer()- transitionToOfflineVideoStreamContent()- log.Errorln("unexpected nil _currentBroadcast")- return- }-- for index := range _currentBroadcast.OutputSettings {- makeVariantIndexOffline(index, offlineFilePath, offlineFilename)- }-- StartOfflineCleanupTimer()- stopOnlineCleanupTimer()- saveStats()-- go webhooks.SendStreamStatusEvent(models.StreamStopped)-}--// StartOfflineCleanupTimer will fire a cleanup after n minutes being disconnected.-func StartOfflineCleanupTimer() {- _offlineCleanupTimer = time.NewTimer(5 * time.Minute)- go func() {- for range _offlineCleanupTimer.C {- // Set video to offline state- resetDirectories()- transitionToOfflineVideoStreamContent()- }- }()-}--// StopOfflineCleanupTimer will stop the previous cleanup timer.-func StopOfflineCleanupTimer() {- if _offlineCleanupTimer != nil {- _offlineCleanupTimer.Stop()- }-}--func startOnlineCleanupTimer() {- _onlineCleanupTicker = time.NewTicker(1 * time.Minute)- go func() {- for range _onlineCleanupTicker.C {- if err := _storage.Cleanup(); err != nil {- log.Errorln(err)- }- }- }()-}--func stopOnlineCleanupTimer() {- if _onlineCleanupTicker != nil {- _onlineCleanupTicker.Stop()- }-}--func startLiveStreamNotificationsTimer() context.CancelFunc {- // Send delayed notification messages.- c, cancelFunc := context.WithCancel(context.Background())- _onlineTimerCancelFunc = cancelFunc- go func(c context.Context) {- select {- case <-time.After(time.Minute * 2.0):- if _lastNotified != nil && time.Since(*_lastNotified) < 10*time.Minute {- return- }-- configRepository := configrepository.Get()- // Send Fediverse message.- if configRepository.GetFederationEnabled() {- log.Traceln("Sending Federated Go Live message.")- if err := activitypub.SendLive(); err != nil {- log.Errorln(err)- }- }-- // Send notification to those who have registered for them.- if notificationService, err := notifications.New(data.GetDatastore()); err != nil {- log.Errorln(err)- } else {- notificationService.Notify()- }-- now := time.Now()- _lastNotified = &now- case <-c.Done():- }- }(c)-- return cancelFunc-}diff --git a/core/webhooks/fediverseEngagement.go b/core/webhooks/fediverseEngagement.godeleted file mode 100644index 296c817e40..0000000000--- a/core/webhooks/fediverseEngagement.go+++ /dev/null@@ -1,33 +0,0 @@-package webhooks--import (- "github.com/owncast/owncast/activitypub/events"- "github.com/owncast/owncast/activitypub/persistence/followersrepository"- "github.com/owncast/owncast/models"-)--// SendFediverseEventFollow will send a user followed event to webhook-// destinations.-func SendFediverseEngagementFollowEvent(iri string) {- followersRepo := followersrepository.Get()- follower, err := followersRepo.GetByIRI(iri)- if err != nil {- return- }- userFollowedEvent := events.FediverseEngagementFollowEvent{}- userFollowedEvent.SetDefaults()- userFollowedEvent.Name = follower.Name- userFollowedEvent.Username = follower.Username- userFollowedEvent.Image = follower.Image.String()-- sendFediverseEngagementEventFollow(userFollowedEvent)-}--func sendFediverseEngagementEventFollow(event events.FediverseEngagementFollowEvent) {- webhookEvent := WebhookEvent{- Type: models.FediverseEngagementFollow,- EventData: event,- }-- SendEventToWebhooks(webhookEvent)-}diff --git a/core/webhooks/stream.go b/core/webhooks/stream.godeleted file mode 100644index 01c33f12ce..0000000000--- a/core/webhooks/stream.go+++ /dev/null@@ -1,31 +0,0 @@-package webhooks--import (- "time"-- "github.com/owncast/owncast/models"- "github.com/owncast/owncast/persistence/configrepository"- "github.com/teris-io/shortid"-)--// SendStreamStatusEvent will send all webhook destinations the current stream status.-func SendStreamStatusEvent(eventType models.EventType) {- sendStreamStatusEvent(eventType, shortid.MustGenerate(), time.Now())-}--func sendStreamStatusEvent(eventType models.EventType, id string, timestamp time.Time) {- configRepository := configrepository.Get()-- SendEventToWebhooks(WebhookEvent{- Type: eventType,- EventData: map[string]interface{}{- "id": id,- "name": configRepository.GetServerName(),- "summary": configRepository.GetServerSummary(),- "streamTitle": configRepository.GetStreamTitle(),- "status": getStatus(),- "serverURL": getServerURL(),- "timestamp": timestamp,- },- })-}diff --git a/core/webhooks/workerpool.go b/core/webhooks/workerpool.godeleted file mode 100644index 69f2b4fa5c..0000000000--- a/core/webhooks/workerpool.go+++ /dev/null@@ -1,96 +0,0 @@-package webhooks--import (- "bytes"- "encoding/json"- "net/http"- "runtime"- "sync"-- log "github.com/sirupsen/logrus"-- "github.com/owncast/owncast/models"- "github.com/owncast/owncast/persistence/webhookrepository"-)--// webhookWorkerPoolSize defines the number of concurrent HTTP webhook requests.-var webhookWorkerPoolSize = runtime.GOMAXPROCS(0)--// Job struct bundling the webhook and the payload in one struct.-type Job struct {- wg *sync.WaitGroup- payload WebhookEvent- webhook models.Webhook-}--var (- queue chan Job- getStatus func() models.Status-)--// SetupWebhooks initializes the webhook worker pool and sets the function to get the current status.-func SetupWebhooks(getStatusFunc func() models.Status) {- getStatus = getStatusFunc- initWorkerPool()-}--// initWorkerPool starts n go routines that await webhook jobs.-func initWorkerPool() {- queue = make(chan Job)-- // start workers- for i := 1; i <= webhookWorkerPoolSize; i++ {- go worker(i, queue)- }-}--func addToQueue(webhook models.Webhook, payload WebhookEvent, wg *sync.WaitGroup) {- log.Tracef("Queued Event %s for Webhook %s", payload.Type, webhook.URL)- queue <- Job{wg, payload, webhook}-}--func worker(workerID int, queue <-chan Job) {- log.Debugf("Started Webhook worker %d", workerID)-- for job := range queue {- log.Debugf("Event %s sent to Webhook %s using worker %d", job.payload.Type, job.webhook.URL, workerID)-- if err := sendWebhook(job); err != nil {- log.Errorf("Event: %s failed to send to webhook: %s Error: %s", job.payload.Type, job.webhook.URL, err)- }- log.Tracef("Done with Event %s to Webhook %s using worker %d", job.payload.Type, job.webhook.URL, workerID)- if job.wg != nil {- job.wg.Done()- }- }-}--func sendWebhook(job Job) error {- jsonText, err := json.Marshal(job.payload)- if err != nil {- return err- }-- req, err := http.NewRequest("POST", job.webhook.URL, bytes.NewReader(jsonText))- if err != nil {- return err- }-- req.Header.Set("Content-Type", "application/json")-- client := &http.Client{}-- resp, err := client.Do(req)- if err != nil {- return err- }-- defer resp.Body.Close()-- webhooksRepo := webhookrepository.Get()- if err := webhooksRepo.SetWebhookAsUsed(job.webhook); err != nil {- log.Warnln(err)- }-- return nil-}diff --git a/logging/logging.go b/logging/logging.goindex f511c1c397..a07126f326 100644--- a/logging/logging.go+++ b/logging/logging.go@@ -11,9 +11,10 @@ import ("time"rotatelogs "github.com/lestrrat-go/file-rotatelogs"- "github.com/owncast/owncast/utils""github.com/rifflock/lfshook"log "github.com/sirupsen/logrus"++ "github.com/owncast/owncast/utils")const maxLogEntries = 500@@ -29,9 +30,9 @@ type OCLogger struct {var Logger *OCLogger// Setup configures our custom logging destinations.-func Setup(enableDebugOptions bool, enableVerboseLogging bool) {+func Setup(logDirectory string, enableDebugOptions bool, enableVerboseLogging bool) {// Create the logging directory if needed- loggingDirectory := filepath.Dir(getLogFilePath())+ loggingDirectory := filepath.Dir(getLogFilePath(logDirectory))if !utils.DoesFileExists(loggingDirectory) {if err := os.Mkdir(loggingDirectory, 0o700); err != nil {log.Errorln("unable to create logs directory", loggingDirectory, err)@@ -39,7 +40,7 @@ func Setup(enableDebugOptions bool, enableVerboseLogging bool) {}// Write logs to a file- path := getLogFilePath()+ path := getLogFilePath(logDirectory)writer, _ := rotatelogs.New(path+".%Y%m%d%H%M",rotatelogs.WithLinkName(path),diff --git a/logging/paths.go b/logging/paths.goindex 31d05e9026..f54efd3c00 100644--- a/logging/paths.go+++ b/logging/paths.go@@ -2,15 +2,14 @@ package loggingimport ("path/filepath"-- "github.com/owncast/owncast/config")-// GetTranscoderLogFilePath returns the logging path for the transcoder log output.-func GetTranscoderLogFilePath() string {- return filepath.Join(config.LogDirectory, "transcoder.log")+// GetTranscoderLogFilePath returns the logging path for the transcoder log+// output relative to the provided log directory.+func GetTranscoderLogFilePath(logDirectory string) string {+ return filepath.Join(logDirectory, "transcoder.log")}-func getLogFilePath() string {- return filepath.Join(config.LogDirectory, "owncast.log")+func getLogFilePath(logDirectory string) string {+ return filepath.Join(logDirectory, "owncast.log")}diff --git a/main.go b/main.goindex c391382c88..75d432b174 100644--- a/main.go+++ b/main.go@@ -1,21 +1,46 @@package mainimport (+ "context""flag""os""strconv""time"+ log "github.com/sirupsen/logrus"++ fediverseauth "github.com/owncast/owncast/auth/fediverse"+ indieauthlib "github.com/owncast/owncast/auth/indieauth""github.com/owncast/owncast/logging"+ "github.com/owncast/owncast/persistence/authrepository"+ "github.com/owncast/owncast/persistence/chatmessagerepository""github.com/owncast/owncast/persistence/configrepository"- log "github.com/sirupsen/logrus"+ "github.com/owncast/owncast/persistence/notificationsrepository"+ "github.com/owncast/owncast/persistence/userrepository"+ "github.com/owncast/owncast/persistence/webhookrepository""github.com/owncast/owncast/config"- "github.com/owncast/owncast/core"- "github.com/owncast/owncast/core/data""github.com/owncast/owncast/metrics"+ "github.com/owncast/owncast/services/activitypub"+ "github.com/owncast/owncast/services/activitypub/apmodels"+ apcrypto "github.com/owncast/owncast/services/activitypub/crypto"+ "github.com/owncast/owncast/services/activitypub/persistence/followersrepository"+ apresolvers "github.com/owncast/owncast/services/activitypub/resolvers"+ "github.com/owncast/owncast/services/cache"+ "github.com/owncast/owncast/services/chat"+ "github.com/owncast/owncast/services/datastore"+ "github.com/owncast/owncast/services/rtmp"+ "github.com/owncast/owncast/services/stream"+ "github.com/owncast/owncast/services/webhooks""github.com/owncast/owncast/utils"+ "github.com/owncast/owncast/webserver/handlers"+ "github.com/owncast/owncast/webserver/handlers/admin"+ "github.com/owncast/owncast/webserver/handlers/auth/fediverse"+ "github.com/owncast/owncast/webserver/handlers/auth/indieauth"+ "github.com/owncast/owncast/webserver/handlers/moderation""github.com/owncast/owncast/webserver/router"+ "github.com/owncast/owncast/webserver/router/middleware"+ "github.com/owncast/owncast/yp")var (@@ -37,12 +62,17 @@ var (func main() {flag.Parse()+ // Construct the runtime config and overlay CLI flag values onto the+ // defaults. The resulting *Config is threaded into every consumer+ // that needs runtime configuration values.+ cfg := config.NewDefault()+if *logDirectory != "" {- config.LogDirectory = *logDirectory+ cfg.LogDirectory = *logDirectory}if *backupDirectory != "" {- config.BackupDirectory = *backupDirectory+ cfg.BackupDirectory = *backupDirectory}// Create the data directory if needed@@ -56,27 +86,27 @@ func main() {utils.MigrateCustomEmojiLocations()// Otherwise save the default emoji to the data directory.- if err := data.SetupEmojiDirectory(); err != nil {+ if err := datastore.SetupEmojiDirectory(); err != nil {log.Fatalln("Cannot set up emoji directory", err)}// Recreate the temp dir- if utils.DoesFileExists(config.TempDir) {- err := os.RemoveAll(config.TempDir)+ if utils.DoesFileExists(cfg.TempDir) {+ err := os.RemoveAll(cfg.TempDir)if err != nil {- log.Fatalln("Unable to remove temp dir! Check permissions.", config.TempDir, err)+ log.Fatalln("Unable to remove temp dir! Check permissions.", cfg.TempDir, err)}}- if err := os.Mkdir(config.TempDir, 0o700); err != nil {+ if err := os.Mkdir(cfg.TempDir, 0o700); err != nil {log.Fatalln("Unable to create temp dir!", err)}- configureLogging(*enableDebugOptions, *enableVerboseLogging)+ configureLogging(cfg.LogDirectory, *enableDebugOptions, *enableVerboseLogging)log.Infoln(config.GetReleaseString())// Allows a user to restore a specific database backupif *restoreDatabaseFile != "" {- databaseFile := config.DatabaseFilePath+ databaseFile := cfg.DatabaseFilePathif *dbFile != "" {databaseFile = *dbFile}@@ -89,33 +119,237 @@ func main() {log.Exit(0)}- config.EnableDebugFeatures = *enableDebugOptions+ cfg.EnableDebugFeatures = *enableDebugOptionsif *dbFile != "" {- config.DatabaseFilePath = *dbFile+ cfg.DatabaseFilePath = *dbFile}- if err := data.SetupPersistence(config.DatabaseFilePath); err != nil {+ dataStore, err := datastore.SetupPersistence(cfg.DatabaseFilePath, cfg.BackupDirectory)+ if err != nil {log.Fatalln("failed to open database", err)}- handleCommandLineFlags()+ // Composition root.+ //+ // Every service, handler, and repository is constructed here and+ // passed via explicit Deps structs to its consumers. main.go is the+ // only place that knows the concrete service implementations; no+ // other package reaches for a singleton via .Get() or a package-level+ // global. The order below reflects the dependency layering:+ //+ // 1. Repositories — wrap dataStore; depend on nothing else.+ // 2. ActivityPub helper builders — pure helpers built from repos.+ // 3. One-shot bootstrap — notificationsRepository.Setup() seeds+ // the browser-push keys before any service starts.+ // 4. Leaf services that depend only on repositories — yp,+ // middleware, indieauth, rtmp.+ // 5. Cycle-pair services — webhooks + chat + yp all need+ // streamSvc.GetStatus, but stream needs them too. Each is+ // constructed with a nil callback and rewired below via+ // SetGetStatus once streamSvc exists.+ // 6. activitypub + stream — depend on the cycle-pair services.+ // 7. SetGetStatus fill-in — resolves the cycle.+ // 8. Late services — metrics + fediverseAuth, depend on stream+ // and chat.+ // 9. HTTP handler set — admin, fediverse, indieauth, moderation,+ // then the top-level *Handlers that wires everything for the+ // router.+ // 10. router.Start — blocks; serves until shutdown.+ //+ // New deps land here, not as package-level globals. Construction+ // cycles get the SetGetStatus pattern, not a fresh shim.++ // Stage 1: repositories.+ configRepository := configrepository.New(dataStore)+ authRepository := authrepository.New(dataStore)+ followersRepository := followersrepository.New(dataStore)+ webhookRepository := webhookrepository.New(dataStore)+ chatMessageRepository := chatmessagerepository.New(dataStore)+ userRepository := userrepository.New(dataStore)+ notificationsRepository := notificationsrepository.New(dataStore, configRepository)++ handleCommandLineFlags(cfg, configRepository)++ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()++ cacheContainer := cache.New()+ defer cacheContainer.Stop()++ // Stage 2: ActivityPub helper types (Signer → Builder → Resolver).+ // Signer is the seed; Builder depends on Signer for actor public-key+ // embedding; Resolver depends on both for signing outbound IRI+ // fetches.+ apSigner := apcrypto.New(apcrypto.Deps{ConfigRepository: configRepository})+ apBuilder := apmodels.New(apmodels.Deps{ConfigRepository: configRepository, Signer: apSigner})+ apResolver := apresolvers.New(apresolvers.Deps{ConfigRepository: configRepository, Builder: apBuilder, Signer: apSigner})++ // Stage 3: one-shot bootstrap. Seeds browser-push keys + default+ // notification config before any service that reads them starts.+ notificationsRepository.Setup()- // starts the core- if err := core.Start(); err != nil {- log.Fatalln("failed to start the core package", err)+ // Stage 4: leaf services. Each depends only on repositories + cfg.+ ypSvc := yp.New(yp.Deps{+ GetStatus: nil, // stage 7+ ConfigRepository: configRepository,+ })++ mw := middleware.New(middleware.Deps{+ ConfigRepository: configRepository,+ AuthRepository: authRepository,+ UserRepository: userRepository,+ })+ indieauthSvc := indieauthlib.New(indieauthlib.Deps{+ ConfigRepository: configRepository,+ })++ rtmpSvc := rtmp.New(rtmp.Deps{+ ConfigRepository: configRepository,+ Config: cfg,+ })++ // Stage 5: cycle-pair services. webhooks + chat both want+ // streamSvc.GetStatus, but streamSvc consumes them in turn. Build+ // them with a nil GetStatus and rewire in stage 7.+ webhooksSvc := webhooks.New(webhooks.Deps{+ GetStatus: nil, // stage 7+ Followers: followersRepository,+ ConfigRepository: configRepository,+ WebhookRepository: webhookRepository,+ })++ chatSvc := chat.New(chat.Deps{+ GetStatus: nil, // stage 7+ Webhooks: webhooksSvc,+ Datastore: dataStore,+ ConfigRepository: configRepository,+ AuthRepository: authRepository,+ ChatMessageRepository: chatMessageRepository,+ UserRepository: userRepository,+ })++ // Stage 6: cycle-pair consumers. activitypub + stream sit on top of+ // the stage-5 services.+ apSvc := activitypub.New(activitypub.Deps{+ Datastore: dataStore,+ Webhooks: webhooksSvc,+ Chat: chatSvc,+ ConfigRepository: configRepository,+ FollowersRepository: followersRepository,+ Builder: apBuilder,+ Signer: apSigner,+ Resolver: apResolver,+ Config: cfg,+ })+ apSvc.Start()++ streamSvc := stream.New(stream.Deps{+ Rtmp: rtmpSvc,+ Activitypub: apSvc,+ Webhooks: webhooksSvc,+ Chat: chatSvc,+ YP: ypSvc,+ Datastore: dataStore,+ ConfigRepository: configRepository,+ Config: cfg,+ })++ // Stage 7: resolve the stream-status cycle. webhooks/chat/yp each+ // hold a func() Status that streamSvc now provides.+ webhooksSvc.SetGetStatus(streamSvc.GetStatus)+ chatSvc.SetGetStatus(streamSvc.GetStatus)+ ypSvc.SetGetStatus(streamSvc.GetStatus)++ if err := streamSvc.Start(ctx); err != nil {+ log.Fatalln("failed to start the stream service", err)}+ defer streamSvc.Stop(ctx)++ // Stage 8: late services. metrics polls stream + chat, fediverseAuth+ // owns OTP state for the chat-side handler.+ metricsSvc := metrics.New(metrics.Deps{+ Stream: streamSvc,+ Chat: chatSvc,+ ConfigRepository: configRepository,+ ChatMessageRepository: chatMessageRepository,+ UserRepository: userRepository,+ })+ go metricsSvc.Start()++ // 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.+ 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,+ })- go metrics.Start(core.GetStatus)+ fediverseAuthSvc := fediverseauth.New()+ fediverseAuthSvc.Start()- if err := router.Start(*enableVerboseLogging); err != nil {+ fediverseHandler := fediverse.New(fediverse.Deps{+ Activitypub: apSvc,+ Chat: chatSvc,+ FediverseAuth: fediverseAuthSvc,+ ConfigRepository: configRepository,+ UserRepository: userRepository,+ })++ indieauthHandler := indieauth.New(indieauth.Deps{+ Chat: chatSvc,+ UserRepository: userRepository,+ IndieAuth: indieauthSvc,+ Middleware: mw,+ })++ moderationHandler := moderation.New(moderation.Deps{+ Chat: chatSvc,+ ChatMessageRepository: chatMessageRepository,+ UserRepository: userRepository,+ })++ h := handlers.NewHandlers(handlers.Deps{+ Cache: cacheContainer,+ Stream: streamSvc,+ Chat: chatSvc,+ Admin: adminHandlers,+ Activitypub: apSvc,+ Fediverse: fediverseHandler,+ IndieAuth: indieauthHandler,+ Moderation: moderationHandler,+ Middleware: mw,+ YP: ypSvc,+ Metrics: metricsSvc,+ ConfigRepository: configRepository,+ FollowersRepository: followersRepository,+ ChatMessageRepository: chatMessageRepository,+ UserRepository: userRepository,+ NotificationsRepository: notificationsRepository,+ APBuilder: apBuilder,+ Config: cfg,+ })++ // Stage 10: serve. Blocks until shutdown.+ if err := router.Start(cfg, *enableVerboseLogging, h, mw, apSvc.Controllers()); err != nil {log.Fatalln("failed to start/run the router", err)}}-func handleCommandLineFlags() {- configRepository := configrepository.Get()-+func handleCommandLineFlags(cfg *config.Config, configRepository configrepository.ConfigRepository) {if *newAdminPassword != "" {if err := configRepository.SetAdminPassword(*newAdminPassword); err != nil {log.Errorln("Error setting your admin password.", err)@@ -127,7 +361,7 @@ func handleCommandLineFlags() {if *newStreamKey != "" {log.Println("Temporary stream key is set for this session.")- config.TemporaryStreamKey = *newStreamKey+ cfg.TemporaryStreamKey = *newStreamKey}// Set the web server port@@ -143,7 +377,7 @@ func handleCommandLineFlags() {log.Errorln(err)}}- config.WebServerPort = configRepository.GetHTTPPortNumber()+ cfg.WebServerPort = configRepository.GetHTTPPortNumber()// Set the web server ipif *webServerIPOverride != "" {@@ -152,7 +386,7 @@ func handleCommandLineFlags() {log.Errorln(err)}}- config.WebServerIP = configRepository.GetHTTPListenAddress()+ cfg.WebServerIP = configRepository.GetHTTPListenAddress()// Set the rtmp server portif *rtmpPortOverride > 0 {@@ -164,13 +398,13 @@ func handleCommandLineFlags() {// Set the follower validation intervalif *followerValidationIntervalSecs > 0 {- config.FollowerValidationInterval = time.Duration(*followerValidationIntervalSecs) * time.Second- log.Printf("Follower validation interval set to %v", config.FollowerValidationInterval)+ cfg.FollowerValidationInterval = time.Duration(*followerValidationIntervalSecs) * time.Second+ log.Printf("Follower validation interval set to %v", cfg.FollowerValidationInterval)}}-func configureLogging(enableDebugFeatures bool, enableVerboseLogging bool) {- logging.Setup(enableDebugFeatures, enableVerboseLogging)+func configureLogging(logDirectory string, enableDebugFeatures bool, enableVerboseLogging bool) {+ logging.Setup(logDirectory, enableDebugFeatures, enableVerboseLogging)log.SetFormatter(&log.TextFormatter{FullTimestamp: true,})diff --git a/metrics/alerting.go b/metrics/alerting.goindex ad3f9ad04d..ccba255721 100644--- a/metrics/alerting.go+++ b/metrics/alerting.go@@ -12,73 +12,67 @@ const (maxDiskAlertingThresholdPCT = 90)-var (- inCPUAlertingState = false- inRAMAlertingState = false- inDiskAlertingState = false-)-var errorResetDuration = time.Minute * 5const alertingError = "The %s utilization of %f%% could cause problems with video generation and delivery. Visit the documentation at http://owncast.online/docs/troubleshooting/ if you are experiencing issues."-func handleAlerting() {- handleCPUAlerting()- handleRAMAlerting()- handleDiskAlerting()+func (s *Service) handleAlerting() {+ s.handleCPUAlerting()+ s.handleRAMAlerting()+ s.handleDiskAlerting()}-func handleCPUAlerting() {- if len(metrics.CPUUtilizations) < 2 {+func (s *Service) handleCPUAlerting() {+ if len(s.metrics.CPUUtilizations) < 2 {return}- avg := recentAverage(metrics.CPUUtilizations)- if avg > maxCPUAlertingThresholdPCT && !inCPUAlertingState {+ avg := recentAverage(s.metrics.CPUUtilizations)+ if avg > maxCPUAlertingThresholdPCT && !s.inCPUAlertingState {log.Warnf(alertingError, "CPU", avg)- inCPUAlertingState = true+ s.inCPUAlertingState = trueresetTimer := time.NewTimer(errorResetDuration)go func() {<-resetTimer.C- inCPUAlertingState = false+ s.inCPUAlertingState = false}()}}-func handleRAMAlerting() {- if len(metrics.RAMUtilizations) < 2 {+func (s *Service) handleRAMAlerting() {+ if len(s.metrics.RAMUtilizations) < 2 {return}- avg := recentAverage(metrics.RAMUtilizations)- if avg > maxRAMAlertingThresholdPCT && !inRAMAlertingState {+ avg := recentAverage(s.metrics.RAMUtilizations)+ if avg > maxRAMAlertingThresholdPCT && !s.inRAMAlertingState {log.Warnf(alertingError, "memory", avg)- inRAMAlertingState = true+ s.inRAMAlertingState = trueresetTimer := time.NewTimer(errorResetDuration)go func() {<-resetTimer.C- inRAMAlertingState = false+ s.inRAMAlertingState = false}()}}-func handleDiskAlerting() {- if len(metrics.DiskUtilizations) < 2 {+func (s *Service) handleDiskAlerting() {+ if len(s.metrics.DiskUtilizations) < 2 {return}- avg := recentAverage(metrics.DiskUtilizations)+ avg := recentAverage(s.metrics.DiskUtilizations)- if avg > maxDiskAlertingThresholdPCT && !inDiskAlertingState {+ if avg > maxDiskAlertingThresholdPCT && !s.inDiskAlertingState {log.Warnf(alertingError, "disk", avg)- inDiskAlertingState = true+ s.inDiskAlertingState = trueresetTimer := time.NewTimer(errorResetDuration)go func() {<-resetTimer.C- inDiskAlertingState = false+ s.inDiskAlertingState = false}()}}diff --git a/metrics/hardware.go b/metrics/hardware.goindex b9c66d1680..03c37e0562 100644--- a/metrics/hardware.go+++ b/metrics/hardware.go@@ -13,9 +13,9 @@ import (// Max number of metrics we want to keep.const maxCollectionValues = 300-func collectCPUUtilization() {- if len(metrics.CPUUtilizations) > maxCollectionValues {- metrics.CPUUtilizations = metrics.CPUUtilizations[1:]+func (s *Service) collectCPUUtilization() {+ if len(s.metrics.CPUUtilizations) > maxCollectionValues {+ s.metrics.CPUUtilizations = s.metrics.CPUUtilizations[1:]}v, err := cpu.Percent(0, false)@@ -32,28 +32,28 @@ func collectCPUUtilization() {}metricValue := TimestampedValue{time.Now(), value}- metrics.CPUUtilizations = append(metrics.CPUUtilizations, metricValue)- cpuUsage.Set(metricValue.Value)+ s.metrics.CPUUtilizations = append(s.metrics.CPUUtilizations, metricValue)+ s.cpuUsage.Set(metricValue.Value)}-func collectRAMUtilization() {- if len(metrics.RAMUtilizations) > maxCollectionValues {- metrics.RAMUtilizations = metrics.RAMUtilizations[1:]+func (s *Service) collectRAMUtilization() {+ if len(s.metrics.RAMUtilizations) > maxCollectionValues {+ s.metrics.RAMUtilizations = s.metrics.RAMUtilizations[1:]}memoryUsage, _ := mem.VirtualMemory()metricValue := TimestampedValue{time.Now(), memoryUsage.UsedPercent}- metrics.RAMUtilizations = append(metrics.RAMUtilizations, metricValue)+ s.metrics.RAMUtilizations = append(s.metrics.RAMUtilizations, metricValue)}-func collectDiskUtilization() {+func (s *Service) collectDiskUtilization() {path := "./"diskUse, _ := disk.Usage(path)- if len(metrics.DiskUtilizations) > maxCollectionValues {- metrics.DiskUtilizations = metrics.DiskUtilizations[1:]+ if len(s.metrics.DiskUtilizations) > maxCollectionValues {+ s.metrics.DiskUtilizations = s.metrics.DiskUtilizations[1:]}metricValue := TimestampedValue{time.Now(), diskUse.UsedPercent}- metrics.DiskUtilizations = append(metrics.DiskUtilizations, metricValue)+ s.metrics.DiskUtilizations = append(s.metrics.DiskUtilizations, metricValue)}diff --git a/metrics/healthOverview.go b/metrics/healthOverview.goindex 2c966d5325..a82e35b9d9 100644--- a/metrics/healthOverview.go+++ b/metrics/healthOverview.go@@ -4,9 +4,7 @@ import ("fmt""sort"- "github.com/owncast/owncast/core""github.com/owncast/owncast/models"- "github.com/owncast/owncast/persistence/configrepository""github.com/owncast/owncast/utils")@@ -17,59 +15,58 @@ const ()// GetStreamHealthOverview will return the stream health overview.-func GetStreamHealthOverview() *models.StreamHealthOverview {- return metrics.streamHealthOverview+func (s *Service) GetStreamHealthOverview() *models.StreamHealthOverview {+ return s.metrics.streamHealthOverview}-func generateStreamHealthOverview() {+func (s *Service) generateStreamHealthOverview() {// Determine what percentage of total players are represented in our overview.- totalPlayerCount := len(core.GetActiveViewers())+ totalPlayerCount := len(s.stream.GetActiveViewers())if totalPlayerCount == 0 {- metrics.streamHealthOverview = nil+ s.metrics.streamHealthOverview = nilreturn}- pct := getClientErrorHeathyPercentage()+ pct := s.getClientErrorHeathyPercentage()if pct < 1 {- metrics.streamHealthOverview = nil+ s.metrics.streamHealthOverview = nilreturn}overview := &models.StreamHealthOverview{Healthy: pct > healthyPercentageMinValue,HealthyPercentage: pct,- Message: getStreamHealthOverviewMessage(),+ Message: s.getStreamHealthOverviewMessage(),}- if totalPlayerCount > 0 && len(windowedBandwidths) > 0 {- representation := utils.IntPercentage(len(windowedBandwidths), totalPlayerCount)+ if totalPlayerCount > 0 && len(s.windowedBandwidths) > 0 {+ representation := utils.IntPercentage(len(s.windowedBandwidths), totalPlayerCount)overview.Representation = representation}- metrics.streamHealthOverview = overview+ s.metrics.streamHealthOverview = overview}-func getStreamHealthOverviewMessage() string {- if message := wastefulBitrateOverviewMessage(); message != "" {+func (s *Service) getStreamHealthOverviewMessage() string {+ if message := s.wastefulBitrateOverviewMessage(); message != "" {return message- } else if message := cpuUsageHealthOverviewMessage(); message != "" {+ } else if message := s.cpuUsageHealthOverviewMessage(); message != "" {return message- } else if message := networkSpeedHealthOverviewMessage(); message != "" {+ } else if message := s.networkSpeedHealthOverviewMessage(); message != "" {return message- } else if message := errorCountHealthOverviewMessage(); message != "" {+ } else if message := s.errorCountHealthOverviewMessage(); message != "" {return message}return ""}-func networkSpeedHealthOverviewMessage() string {+func (s *Service) networkSpeedHealthOverviewMessage() string {type singleVariant struct {isVideoPassthrough boolbitrate int}- configRepository := configrepository.Get()- outputVariants := configRepository.GetStreamOutputVariants()+ outputVariants := s.configRepository.GetStreamOutputVariants()streamSortVariants := make([]singleVariant, len(outputVariants))for i, variant := range outputVariants {@@ -93,7 +90,7 @@ func networkSpeedHealthOverviewMessage() string {})lowestSupportedBitrate := float64(streamSortVariants[len(streamSortVariants)-1].bitrate)- totalNumberOfClients := len(windowedBandwidths)+ totalNumberOfClients := len(s.windowedBandwidths)if totalNumberOfClients == 0 {return ""@@ -102,7 +99,7 @@ func networkSpeedHealthOverviewMessage() string {// Determine healthy status based on bandwidth speeds of clients.unhealthyClientCount := 0- for _, speed := range windowedBandwidths {+ for _, speed := range s.windowedBandwidths {if int(speed) < int(lowestSupportedBitrate*1.1) {unhealthyClientCount++}@@ -118,13 +115,13 @@ func networkSpeedHealthOverviewMessage() string {// wastefulBitrateOverviewMessage attempts to determine if a streamer is sending to// Owncast at a bitrate higher than they're streaming to their viewers leading// to wasted CPU by having to compress it.-func wastefulBitrateOverviewMessage() string {- if len(metrics.CPUUtilizations) < 2 {+func (s *Service) wastefulBitrateOverviewMessage() string {+ if len(s.metrics.CPUUtilizations) < 2 {return ""}// Only return an alert if the CPU usage is around the max cpu threshold.- recentCPUUses := metrics.CPUUtilizations[len(metrics.CPUUtilizations)-2:]+ recentCPUUses := s.metrics.CPUUtilizations[len(s.metrics.CPUUtilizations)-2:]values := make([]float64, len(recentCPUUses))for i, val := range recentCPUUses {values[i] = val.Value@@ -135,12 +132,12 @@ func wastefulBitrateOverviewMessage() string {return ""}- currentBroadcast := core.GetCurrentBroadcast()+ currentBroadcast := s.stream.GetCurrentBroadcast()if currentBroadcast == nil {return ""}- currentBroadcaster := core.GetBroadcaster()+ currentBroadcaster := s.stream.GetBroadcaster()if currentBroadcast == nil {return ""}@@ -155,8 +152,7 @@ func wastefulBitrateOverviewMessage() string {return ""}- configRepository := configrepository.Get()- outputVariants := configRepository.GetStreamOutputVariants()+ outputVariants := s.configRepository.GetStreamOutputVariants()type singleVariant struct {isVideoPassthrough bool@@ -192,12 +188,12 @@ func wastefulBitrateOverviewMessage() string {return ""}-func cpuUsageHealthOverviewMessage() string {- if len(metrics.CPUUtilizations) < 2 {+func (s *Service) cpuUsageHealthOverviewMessage() string {+ if len(s.metrics.CPUUtilizations) < 2 {return ""}- recentCPUUses := metrics.CPUUtilizations[len(metrics.CPUUtilizations)-2:]+ recentCPUUses := s.metrics.CPUUtilizations[len(s.metrics.CPUUtilizations)-2:]values := make([]float64, len(recentCPUUses))for i, val := range recentCPUUses {values[i] = val.Value@@ -210,13 +206,13 @@ func cpuUsageHealthOverviewMessage() string {return fmt.Sprintf("The CPU usage on your server is over %d%%. This may cause video to be provided slower than necessary, causing buffering for your viewers. Consider increasing the resources available or reducing the number of output variants you made available.", maxCPUUsage)}-func errorCountHealthOverviewMessage() string {- totalNumberOfClients := len(windowedBandwidths)+func (s *Service) errorCountHealthOverviewMessage() string {+ totalNumberOfClients := len(s.windowedBandwidths)if totalNumberOfClients == 0 {return ""}- clientsWithErrors := getClientsWithErrorsCount()+ clientsWithErrors := s.getClientsWithErrorsCount()if clientsWithErrors == 0 {return ""@@ -230,8 +226,7 @@ func errorCountHealthOverviewMessage() string {healthyPercentage := utils.IntPercentage(clientsWithErrors, totalNumberOfClients)isUsingPassthrough := false- configRepository := configrepository.Get()- outputVariants := configRepository.GetStreamOutputVariants()+ outputVariants := s.configRepository.GetStreamOutputVariants()for _, variant := range outputVariants {if variant.IsVideoPassthrough {isUsingPassthrough = true@@ -242,7 +237,7 @@ func errorCountHealthOverviewMessage() string {return fmt.Sprintf("%d of %d viewers (%d%%) are experiencing errors. You're currently using a video passthrough output, often known for causing playback issues for people. It is suggested you turn it off.", clientsWithErrors, totalNumberOfClients, healthyPercentage)}- currentBroadcast := core.GetCurrentBroadcast()+ currentBroadcast := s.stream.GetCurrentBroadcast()if currentBroadcast != nil && currentBroadcast.LatencyLevel.SecondsPerSegment < 3 {return fmt.Sprintf("%d of %d viewers (%d%%) may be experiencing some issues. You may want to increase your latency buffer level in your video configuration to see if it helps.", clientsWithErrors, totalNumberOfClients, healthyPercentage)}@@ -253,9 +248,9 @@ func errorCountHealthOverviewMessage() string {return ""}-func getClientsWithErrorsCount() int {+func (s *Service) getClientsWithErrorsCount() int {clientsWithErrors := 0- for _, errors := range windowedErrorCounts {+ for _, errors := range s.windowedErrorCounts {if errors > 0 {clientsWithErrors++}@@ -263,13 +258,13 @@ func getClientsWithErrorsCount() int {return clientsWithErrors}-func getClientErrorHeathyPercentage() int {- totalNumberOfClients := len(windowedErrorCounts)+func (s *Service) getClientErrorHeathyPercentage() int {+ totalNumberOfClients := len(s.windowedErrorCounts)if totalNumberOfClients == 0 {return -1}- clientsWithErrors := getClientsWithErrorsCount()+ clientsWithErrors := s.getClientsWithErrorsCount()if clientsWithErrors == 0 {return 100diff --git a/metrics/metrics.go b/metrics/metrics.goindex 3d82f102ca..66f2ace303 100644--- a/metrics/metrics.go+++ b/metrics/metrics.go@@ -1,12 +1,22 @@+// Package metrics owns the Owncast metrics service: hardware, playback,+// chat and viewer metrics collection plus Prometheus exposition.+// Construct via New(Deps) and call Start to launch collection goroutines.package metricsimport ("sync""time"+ "github.com/nakabonne/tstorage"+ "github.com/prometheus/client_golang/prometheus"+"github.com/owncast/owncast/config""github.com/owncast/owncast/models"+ "github.com/owncast/owncast/persistence/chatmessagerepository""github.com/owncast/owncast/persistence/configrepository"+ "github.com/owncast/owncast/persistence/userrepository"+ "github.com/owncast/owncast/services/chat"+ "github.com/owncast/owncast/services/stream")// How often we poll for updates.@@ -49,56 +59,119 @@ type CollectedMetrics struct {m sync.Mutex `json:"-"`}-// Metrics is the shared Metrics instance.-var metrics *CollectedMetrics+// Deps lists the explicit dependencies of the metrics Service.+type Deps struct {+ Stream *stream.Service+ Chat *chat.Service+ ConfigRepository configrepository.ConfigRepository+ ChatMessageRepository chatmessagerepository.ChatMessageRepository+ UserRepository userrepository.UserRepository+}++// Service owns the per-instance metrics collection state: the collected+// time-series window, Prometheus gauges, the on-disk tstorage handle, and+// the windowed per-client maps. Construct via New(Deps); call Start to+// launch the collection goroutines.+type Service struct {+ stream *stream.Service+ chat *chat.Service+ configRepository configrepository.ConfigRepository+ chatMessageRepository chatmessagerepository.ChatMessageRepository+ userRepository userrepository.UserRepository++ // Metrics is the collected window of hardware/playback timestamped+ // values used by the admin health endpoints.+ metrics *CollectedMetrics++ // Prometheus collectors. Built by setupPrometheusCollectors() during+ // Start; do not access before Start.+ labels map[string]string+ activeViewerCount prometheus.Gauge+ activeChatClientCount prometheus.Gauge+ cpuUsage prometheus.Gauge+ chatUserCount prometheus.Gauge+ currentChatMessageCount prometheus.Gauge+ playbackErrorCount prometheus.Gauge++ // On-disk time-series store used by GetViewersOverTime and+ // GetChatClientCountOverTime. Opened by startViewerCollectionMetrics.+ storage tstorage.Storage++ // Windowed per-client playback values consumed by the periodic+ // playback aggregation pass.+ windowedErrorCounts map[string]float64+ windowedQualityVariantChanges map[string]float64+ windowedBandwidths map[string]float64+ windowedLatencies map[string]float64+ windowedDownloadDurations map[string]float64++ // Alerting state: whether we've already logged a threshold-exceeded+ // warning for the given resource (debounced by errorResetDuration).+ inCPUAlertingState bool+ inRAMAlertingState bool+ inDiskAlertingState bool+}-var _getStatus func() models.Status+// New constructs an idle metrics Service. Call Start to launch the+// collection goroutines and register the Prometheus collectors.+func New(deps Deps) *Service {+ return &Service{+ stream: deps.Stream,+ chat: deps.Chat,+ configRepository: deps.ConfigRepository,+ chatMessageRepository: deps.ChatMessageRepository,+ userRepository: deps.UserRepository,+ windowedErrorCounts: map[string]float64{},+ windowedQualityVariantChanges: map[string]float64{},+ windowedBandwidths: map[string]float64{},+ windowedLatencies: map[string]float64{},+ windowedDownloadDurations: map[string]float64{},+ }+}// Start will begin the metrics collection and alerting.-func Start(getStatus func() models.Status) {- configRepository := configrepository.Get()- _getStatus = getStatus- host := configRepository.GetServerURL()+func (s *Service) Start() {+ host := s.configRepository.GetServerURL()if host == "" {host = "unknown"}- labels = map[string]string{+ s.labels = map[string]string{"version": config.VersionNumber,"host": host,}- setupPrometheusCollectors()+ s.setupPrometheusCollectors()- metrics = new(CollectedMetrics)- go startViewerCollectionMetrics()+ s.metrics = new(CollectedMetrics)+ go s.startViewerCollectionMetrics()go func() {for range time.Tick(hardwareMetricsPollingInterval) {- handlePolling()+ s.handlePolling()}}()go func() {for range time.Tick(playbackMetricsPollingInterval) {- handlePlaybackPolling()+ s.handlePlaybackPolling()}}()}-func handlePolling() {- metrics.m.Lock()- defer metrics.m.Unlock()+func (s *Service) handlePolling() {+ s.metrics.m.Lock()+ defer s.metrics.m.Unlock()// Collect hardware stats- collectCPUUtilization()- collectRAMUtilization()- collectDiskUtilization()+ s.collectCPUUtilization()+ s.collectRAMUtilization()+ s.collectDiskUtilization()// Alerting- handleAlerting()+ s.handleAlerting()}// GetMetrics will return the collected metrics.-func GetMetrics() *CollectedMetrics {- return metrics+func (s *Service) GetMetrics() *CollectedMetrics {+ return s.metrics}diff --git a/metrics/playback.go b/metrics/playback.goindex 378a1b7fbf..53d7dcd809 100644--- a/metrics/playback.go+++ b/metrics/playback.go@@ -4,319 +4,308 @@ import ("math""time"- "github.com/owncast/owncast/core""github.com/owncast/owncast/utils")-// Playback error counts reported since the last time we collected metrics.-var (- windowedErrorCounts = map[string]float64{}- windowedQualityVariantChanges = map[string]float64{}- windowedBandwidths = map[string]float64{}- windowedLatencies = map[string]float64{}- windowedDownloadDurations = map[string]float64{}-)--func handlePlaybackPolling() {- metrics.m.Lock()- defer metrics.m.Unlock()+func (s *Service) handlePlaybackPolling() {+ s.metrics.m.Lock()+ defer s.metrics.m.Unlock()// Make sure this is fired first before all the values get cleared below.- if _getStatus().Online {- generateStreamHealthOverview()+ if s.stream.GetStatus().Online {+ s.generateStreamHealthOverview()}- collectPlaybackErrorCount()- collectLatencyValues()- collectSegmentDownloadDuration()- collectLowestBandwidth()- collectQualityVariantChanges()+ s.collectPlaybackErrorCount()+ s.collectLatencyValues()+ s.collectSegmentDownloadDuration()+ s.collectLowestBandwidth()+ s.collectQualityVariantChanges()}// RegisterPlaybackErrorCount will add to the windowed playback error count.-func RegisterPlaybackErrorCount(clientID string, count float64) {- metrics.m.Lock()- defer metrics.m.Unlock()- windowedErrorCounts[clientID] = count- // windowedErrorCounts = append(windowedErrorCounts, count)+func (s *Service) RegisterPlaybackErrorCount(clientID string, count float64) {+ s.metrics.m.Lock()+ defer s.metrics.m.Unlock()+ s.windowedErrorCounts[clientID] = count}// RegisterQualityVariantChangesCount will add to the windowed quality variant// change count.-func RegisterQualityVariantChangesCount(clientID string, count float64) {- metrics.m.Lock()- defer metrics.m.Unlock()- windowedQualityVariantChanges[clientID] = count+func (s *Service) RegisterQualityVariantChangesCount(clientID string, count float64) {+ s.metrics.m.Lock()+ defer s.metrics.m.Unlock()+ s.windowedQualityVariantChanges[clientID] = count}// RegisterPlayerBandwidth will add to the windowed playback bandwidth.-func RegisterPlayerBandwidth(clientID string, kbps float64) {- metrics.m.Lock()- defer metrics.m.Unlock()- windowedBandwidths[clientID] = kbps+func (s *Service) RegisterPlayerBandwidth(clientID string, kbps float64) {+ s.metrics.m.Lock()+ defer s.metrics.m.Unlock()+ s.windowedBandwidths[clientID] = kbps}// RegisterPlayerLatency will add to the windowed player latency values.-func RegisterPlayerLatency(clientID string, seconds float64) {- metrics.m.Lock()- defer metrics.m.Unlock()- windowedLatencies[clientID] = seconds+func (s *Service) RegisterPlayerLatency(clientID string, seconds float64) {+ s.metrics.m.Lock()+ defer s.metrics.m.Unlock()+ s.windowedLatencies[clientID] = seconds}// RegisterPlayerSegmentDownloadDuration will add to the windowed player segment// download duration values.-func RegisterPlayerSegmentDownloadDuration(clientID string, seconds float64) {- metrics.m.Lock()- defer metrics.m.Unlock()- windowedDownloadDurations[clientID] = seconds+func (s *Service) RegisterPlayerSegmentDownloadDuration(clientID string, seconds float64) {+ s.metrics.m.Lock()+ defer s.metrics.m.Unlock()+ s.windowedDownloadDurations[clientID] = seconds}// collectPlaybackErrorCount will take all of the error counts each individual// player reported and average them into a single metric. This is done so// one person with bad connectivity doesn't make it look like everything is// horrible for everyone.-func collectPlaybackErrorCount() {- valueSlice := utils.Float64MapToSlice(windowedErrorCounts)+func (s *Service) collectPlaybackErrorCount() {+ valueSlice := utils.Float64MapToSlice(s.windowedErrorCounts)count := utils.Sum(valueSlice)- windowedErrorCounts = map[string]float64{}+ s.windowedErrorCounts = map[string]float64{}- metrics.errorCount = append(metrics.errorCount, TimestampedValue{+ s.metrics.errorCount = append(s.metrics.errorCount, TimestampedValue{Time: time.Now(),Value: count,})- if len(metrics.errorCount) > maxCollectionValues {- metrics.errorCount = metrics.errorCount[1:]+ if len(s.metrics.errorCount) > maxCollectionValues {+ s.metrics.errorCount = s.metrics.errorCount[1:]}// Save to Prometheus collector.- playbackErrorCount.Set(count)+ s.playbackErrorCount.Set(count)}-func collectSegmentDownloadDuration() {+func (s *Service) collectSegmentDownloadDuration() {median := 0.0max := 0.0min := 0.0- valueSlice := utils.Float64MapToSlice(windowedDownloadDurations)+ valueSlice := utils.Float64MapToSlice(s.windowedDownloadDurations)if len(valueSlice) > 0 {median = utils.Median(valueSlice)min, max = utils.MinMax(valueSlice)- windowedDownloadDurations = map[string]float64{}+ s.windowedDownloadDurations = map[string]float64{}}- metrics.medianSegmentDownloadSeconds = append(metrics.medianSegmentDownloadSeconds, TimestampedValue{+ s.metrics.medianSegmentDownloadSeconds = append(s.metrics.medianSegmentDownloadSeconds, TimestampedValue{Time: time.Now(),Value: median,})- if len(metrics.medianSegmentDownloadSeconds) > maxCollectionValues {- metrics.medianSegmentDownloadSeconds = metrics.medianSegmentDownloadSeconds[1:]+ if len(s.metrics.medianSegmentDownloadSeconds) > maxCollectionValues {+ s.metrics.medianSegmentDownloadSeconds = s.metrics.medianSegmentDownloadSeconds[1:]}- metrics.minimumSegmentDownloadSeconds = append(metrics.minimumSegmentDownloadSeconds, TimestampedValue{+ s.metrics.minimumSegmentDownloadSeconds = append(s.metrics.minimumSegmentDownloadSeconds, TimestampedValue{Time: time.Now(),Value: min,})- if len(metrics.minimumSegmentDownloadSeconds) > maxCollectionValues {- metrics.minimumSegmentDownloadSeconds = metrics.minimumSegmentDownloadSeconds[1:]+ if len(s.metrics.minimumSegmentDownloadSeconds) > maxCollectionValues {+ s.metrics.minimumSegmentDownloadSeconds = s.metrics.minimumSegmentDownloadSeconds[1:]}- metrics.maximumSegmentDownloadSeconds = append(metrics.maximumSegmentDownloadSeconds, TimestampedValue{+ s.metrics.maximumSegmentDownloadSeconds = append(s.metrics.maximumSegmentDownloadSeconds, TimestampedValue{Time: time.Now(),Value: max,})- if len(metrics.maximumSegmentDownloadSeconds) > maxCollectionValues {- metrics.maximumSegmentDownloadSeconds = metrics.maximumSegmentDownloadSeconds[1:]+ if len(s.metrics.maximumSegmentDownloadSeconds) > maxCollectionValues {+ s.metrics.maximumSegmentDownloadSeconds = s.metrics.maximumSegmentDownloadSeconds[1:]}}// GetMedianDownloadDurationsOverTime will return a window of durations errors over time.-func GetMedianDownloadDurationsOverTime() []TimestampedValue {- return metrics.medianSegmentDownloadSeconds+func (s *Service) GetMedianDownloadDurationsOverTime() []TimestampedValue {+ return s.metrics.medianSegmentDownloadSeconds}// GetMaximumDownloadDurationsOverTime will return a maximum durations errors over time.-func GetMaximumDownloadDurationsOverTime() []TimestampedValue {- return metrics.maximumSegmentDownloadSeconds+func (s *Service) GetMaximumDownloadDurationsOverTime() []TimestampedValue {+ return s.metrics.maximumSegmentDownloadSeconds}// GetMinimumDownloadDurationsOverTime will return a maximum durations errors over time.-func GetMinimumDownloadDurationsOverTime() []TimestampedValue {- return metrics.minimumSegmentDownloadSeconds+func (s *Service) GetMinimumDownloadDurationsOverTime() []TimestampedValue {+ return s.metrics.minimumSegmentDownloadSeconds}// GetPlaybackErrorCountOverTime will return a window of playback errors over time.-func GetPlaybackErrorCountOverTime() []TimestampedValue {- return metrics.errorCount+func (s *Service) GetPlaybackErrorCountOverTime() []TimestampedValue {+ return s.metrics.errorCount}-func collectLatencyValues() {+func (s *Service) collectLatencyValues() {median := 0.0min := 0.0max := 0.0- valueSlice := utils.Float64MapToSlice(windowedLatencies)- windowedLatencies = map[string]float64{}+ valueSlice := utils.Float64MapToSlice(s.windowedLatencies)+ s.windowedLatencies = map[string]float64{}if len(valueSlice) > 0 {median = utils.Median(valueSlice)min, max = utils.MinMax(valueSlice)- windowedLatencies = map[string]float64{}+ s.windowedLatencies = map[string]float64{}}- metrics.medianLatency = append(metrics.medianLatency, TimestampedValue{+ s.metrics.medianLatency = append(s.metrics.medianLatency, TimestampedValue{Time: time.Now(),Value: median,})- if len(metrics.medianLatency) > maxCollectionValues {- metrics.medianLatency = metrics.medianLatency[1:]+ if len(s.metrics.medianLatency) > maxCollectionValues {+ s.metrics.medianLatency = s.metrics.medianLatency[1:]}- metrics.minimumLatency = append(metrics.minimumLatency, TimestampedValue{+ s.metrics.minimumLatency = append(s.metrics.minimumLatency, TimestampedValue{Time: time.Now(),Value: min,})- if len(metrics.minimumLatency) > maxCollectionValues {- metrics.minimumLatency = metrics.minimumLatency[1:]+ if len(s.metrics.minimumLatency) > maxCollectionValues {+ s.metrics.minimumLatency = s.metrics.minimumLatency[1:]}- metrics.maximumLatency = append(metrics.maximumLatency, TimestampedValue{+ s.metrics.maximumLatency = append(s.metrics.maximumLatency, TimestampedValue{Time: time.Now(),Value: max,})- if len(metrics.maximumLatency) > maxCollectionValues {- metrics.maximumLatency = metrics.maximumLatency[1:]+ if len(s.metrics.maximumLatency) > maxCollectionValues {+ s.metrics.maximumLatency = s.metrics.maximumLatency[1:]}}// GetMedianLatencyOverTime will return the median latency values over time.-func GetMedianLatencyOverTime() []TimestampedValue {- if len(metrics.medianLatency) == 0 {+func (s *Service) GetMedianLatencyOverTime() []TimestampedValue {+ if len(s.metrics.medianLatency) == 0 {return []TimestampedValue{}}- return metrics.medianLatency+ return s.metrics.medianLatency}// GetMinimumLatencyOverTime will return the min latency values over time.-func GetMinimumLatencyOverTime() []TimestampedValue {- if len(metrics.minimumLatency) == 0 {+func (s *Service) GetMinimumLatencyOverTime() []TimestampedValue {+ if len(s.metrics.minimumLatency) == 0 {return []TimestampedValue{}}- return metrics.minimumLatency+ return s.metrics.minimumLatency}// GetMaximumLatencyOverTime will return the max latency values over time.-func GetMaximumLatencyOverTime() []TimestampedValue {- if len(metrics.maximumLatency) == 0 {+func (s *Service) GetMaximumLatencyOverTime() []TimestampedValue {+ if len(s.metrics.maximumLatency) == 0 {return []TimestampedValue{}}- return metrics.maximumLatency+ return s.metrics.maximumLatency}// collectLowestBandwidth will collect the bandwidth currently collected// so we can report to the streamer the worst possible streaming condition// being experienced.-func collectLowestBandwidth() {+func (s *Service) collectLowestBandwidth() {min := 0.0median := 0.0max := 0.0- valueSlice := utils.Float64MapToSlice(windowedBandwidths)+ valueSlice := utils.Float64MapToSlice(s.windowedBandwidths)- if len(windowedBandwidths) > 0 {+ if len(s.windowedBandwidths) > 0 {min, max = utils.MinMax(valueSlice)min = math.Round(min)max = math.Round(max)median = utils.Median(valueSlice)- windowedBandwidths = map[string]float64{}+ s.windowedBandwidths = map[string]float64{}}- metrics.lowestBitrate = append(metrics.lowestBitrate, TimestampedValue{+ s.metrics.lowestBitrate = append(s.metrics.lowestBitrate, TimestampedValue{Time: time.Now(),Value: math.Round(min),})- if len(metrics.lowestBitrate) > maxCollectionValues {- metrics.lowestBitrate = metrics.lowestBitrate[1:]+ if len(s.metrics.lowestBitrate) > maxCollectionValues {+ s.metrics.lowestBitrate = s.metrics.lowestBitrate[1:]}- metrics.medianBitrate = append(metrics.medianBitrate, TimestampedValue{+ s.metrics.medianBitrate = append(s.metrics.medianBitrate, TimestampedValue{Time: time.Now(),Value: math.Round(median),})- if len(metrics.medianBitrate) > maxCollectionValues {- metrics.medianBitrate = metrics.medianBitrate[1:]+ if len(s.metrics.medianBitrate) > maxCollectionValues {+ s.metrics.medianBitrate = s.metrics.medianBitrate[1:]}- metrics.highestBitrate = append(metrics.highestBitrate, TimestampedValue{+ s.metrics.highestBitrate = append(s.metrics.highestBitrate, TimestampedValue{Time: time.Now(),Value: math.Round(max),})- if len(metrics.highestBitrate) > maxCollectionValues {- metrics.highestBitrate = metrics.highestBitrate[1:]+ if len(s.metrics.highestBitrate) > maxCollectionValues {+ s.metrics.highestBitrate = s.metrics.highestBitrate[1:]}}// GetSlowestDownloadRateOverTime will return the collected lowest bandwidth values// over time.-func GetSlowestDownloadRateOverTime() []TimestampedValue {- if len(metrics.lowestBitrate) == 0 {+func (s *Service) GetSlowestDownloadRateOverTime() []TimestampedValue {+ if len(s.metrics.lowestBitrate) == 0 {return []TimestampedValue{}}- return metrics.lowestBitrate+ return s.metrics.lowestBitrate}// GetMedianDownloadRateOverTime will return the collected median bandwidth values.-func GetMedianDownloadRateOverTime() []TimestampedValue {- if len(metrics.medianBitrate) == 0 {+func (s *Service) GetMedianDownloadRateOverTime() []TimestampedValue {+ if len(s.metrics.medianBitrate) == 0 {return []TimestampedValue{}}- return metrics.medianBitrate+ return s.metrics.medianBitrate}// GetMaximumDownloadRateOverTime will return the collected maximum bandwidth values.-func GetMaximumDownloadRateOverTime() []TimestampedValue {- if len(metrics.maximumLatency) == 0 {+func (s *Service) GetMaximumDownloadRateOverTime() []TimestampedValue {+ if len(s.metrics.maximumLatency) == 0 {return []TimestampedValue{}}- return metrics.maximumLatency+ return s.metrics.maximumLatency}// GetMinimumDownloadRateOverTime will return the collected minimum bandwidth values.-func GetMinimumDownloadRateOverTime() []TimestampedValue {- if len(metrics.minimumLatency) == 0 {+func (s *Service) GetMinimumDownloadRateOverTime() []TimestampedValue {+ if len(s.metrics.minimumLatency) == 0 {return []TimestampedValue{}}- return metrics.minimumLatency+ return s.metrics.minimumLatency}// GetMaxDownloadRateOverTime will return the collected highest bandwidth values.-func GetMaxDownloadRateOverTime() []TimestampedValue {- if len(metrics.highestBitrate) == 0 {+func (s *Service) GetMaxDownloadRateOverTime() []TimestampedValue {+ if len(s.metrics.highestBitrate) == 0 {return []TimestampedValue{}}- return metrics.highestBitrate+ return s.metrics.highestBitrate}-func collectQualityVariantChanges() {- valueSlice := utils.Float64MapToSlice(windowedQualityVariantChanges)+func (s *Service) collectQualityVariantChanges() {+ valueSlice := utils.Float64MapToSlice(s.windowedQualityVariantChanges)count := utils.Sum(valueSlice)- windowedQualityVariantChanges = map[string]float64{}+ s.windowedQualityVariantChanges = map[string]float64{}- metrics.qualityVariantChanges = append(metrics.qualityVariantChanges, TimestampedValue{+ s.metrics.qualityVariantChanges = append(s.metrics.qualityVariantChanges, TimestampedValue{Time: time.Now(),Value: count,})@@ -324,14 +313,14 @@ func collectQualityVariantChanges() {// GetQualityVariantChangesOverTime will return the collected quality variant// changes.-func GetQualityVariantChangesOverTime() []TimestampedValue {- return metrics.qualityVariantChanges+func (s *Service) GetQualityVariantChangesOverTime() []TimestampedValue {+ return s.metrics.qualityVariantChanges}// GetPlaybackMetricsRepresentation returns what percentage of all known players// the metrics represent.-func GetPlaybackMetricsRepresentation() int {- totalPlayerCount := len(core.GetActiveViewers())- representation := utils.IntPercentage(len(windowedBandwidths), totalPlayerCount)+func (s *Service) GetPlaybackMetricsRepresentation() int {+ totalPlayerCount := len(s.stream.GetActiveViewers())+ representation := utils.IntPercentage(len(s.windowedBandwidths), totalPlayerCount)return representation}diff --git a/metrics/prometheus.go b/metrics/prometheus.goindex 3fbe4235ef..c1740eb464 100644--- a/metrics/prometheus.go+++ b/metrics/prometheus.go@@ -5,51 +5,41 @@ import ("github.com/prometheus/client_golang/prometheus/promauto")-var (- labels map[string]string- activeViewerCount prometheus.Gauge- activeChatClientCount prometheus.Gauge- cpuUsage prometheus.Gauge- chatUserCount prometheus.Gauge- currentChatMessageCount prometheus.Gauge- playbackErrorCount prometheus.Gauge-)--func setupPrometheusCollectors() {+func (s *Service) setupPrometheusCollectors() {// Setup the Prometheus collectors.- activeViewerCount = promauto.NewGauge(prometheus.GaugeOpts{+ s.activeViewerCount = promauto.NewGauge(prometheus.GaugeOpts{Name: "owncast_instance_active_viewer_count",Help: "The number of viewers.",- ConstLabels: labels,+ ConstLabels: s.labels,})- activeChatClientCount = promauto.NewGauge(prometheus.GaugeOpts{+ s.activeChatClientCount = promauto.NewGauge(prometheus.GaugeOpts{Name: "owncast_instance_active_chat_client_count",Help: "The number of connected chat clients.",- ConstLabels: labels,+ ConstLabels: s.labels,})- chatUserCount = promauto.NewGauge(prometheus.GaugeOpts{+ s.chatUserCount = promauto.NewGauge(prometheus.GaugeOpts{Name: "owncast_instance_total_chat_users",Help: "The total number of chat users on this Owncast instance.",- ConstLabels: labels,+ ConstLabels: s.labels,})- currentChatMessageCount = promauto.NewGauge(prometheus.GaugeOpts{+ s.currentChatMessageCount = promauto.NewGauge(prometheus.GaugeOpts{Name: "owncast_instance_current_chat_message_count",Help: "The number of chat messages currently saved before cleanup.",- ConstLabels: labels,+ ConstLabels: s.labels,})- playbackErrorCount = promauto.NewGauge(prometheus.GaugeOpts{+ s.playbackErrorCount = promauto.NewGauge(prometheus.GaugeOpts{Name: "owncast_instance_playback_error_count",Help: "Errors collected from players within this window",- ConstLabels: labels,+ ConstLabels: s.labels,})- cpuUsage = promauto.NewGauge(prometheus.GaugeOpts{+ s.cpuUsage = promauto.NewGauge(prometheus.GaugeOpts{Name: "owncast_instance_cpu_usage",Help: "CPU usage as seen internally to Owncast.",- ConstLabels: labels,+ ConstLabels: s.labels,})}diff --git a/metrics/viewers.go b/metrics/viewers.goindex b1156bdc1d..3f579017b2 100644--- a/metrics/viewers.go+++ b/metrics/viewers.go@@ -4,44 +4,39 @@ import ("time""github.com/nakabonne/tstorage"- "github.com/owncast/owncast/core"- "github.com/owncast/owncast/core/chat"- "github.com/owncast/owncast/persistence/chatmessagerepository"- "github.com/owncast/owncast/persistence/userrepository"log "github.com/sirupsen/logrus")-var storage tstorage.Storage--func startViewerCollectionMetrics() {- storage, _ = tstorage.NewStorage(+func (s *Service) startViewerCollectionMetrics() {+ s.storage, _ = tstorage.NewStorage(tstorage.WithTimestampPrecision(tstorage.Seconds),tstorage.WithDataPath("./data/metrics"),)- defer storage.Close()+ defer s.storage.Close()- collectViewerCount()+ s.collectViewerCount()for range time.Tick(viewerMetricsPollingInterval) {- collectViewerCount()- collectChatClientCount()+ s.collectViewerCount()+ s.collectChatClientCount()}}-func collectViewerCount() {+func (s *Service) collectViewerCount() {// Don't collect metrics for viewers if there's no stream active.- if !core.GetStatus().Online {- activeViewerCount.Set(0)+ status := s.stream.GetStatus()+ if !status.Online {+ s.activeViewerCount.Set(0)return}- count := core.GetStatus().ViewerCount+ count := status.ViewerCount// Save active viewer count to our Prometheus collector.- activeViewerCount.Set(float64(count))+ s.activeViewerCount.Set(float64(count))// Insert active viewer count into our on-disk time series storage.- if err := storage.InsertRows([]tstorage.Row{+ if err := s.storage.InsertRows([]tstorage.Row{{Metric: activeViewerCountKey,DataPoint: tstorage.DataPoint{Timestamp: time.Now().Unix(), Value: float64(count)},@@ -51,24 +46,22 @@ func collectViewerCount() {}}-func collectChatClientCount() {- count := len(chat.GetClients())- activeChatClientCount.Set(float64(count))+func (s *Service) collectChatClientCount() {+ count := len(s.chat.GetClients())+ s.activeChatClientCount.Set(float64(count))// Total message count- chatMessageRepository := chatmessagerepository.Get()- cmc := chatMessageRepository.GetMessagesCount()+ cmc := s.chatMessageRepository.GetMessagesCount()// Insert message count into Prometheus collector.- currentChatMessageCount.Set(float64(cmc))+ s.currentChatMessageCount.Set(float64(cmc))// Total user count- userRepository := userrepository.Get()- uc := userRepository.GetUsersCount()+ uc := s.userRepository.GetUsersCount()// Insert user count into Prometheus collector.- chatUserCount.Set(float64(uc))+ s.chatUserCount.Set(float64(uc))// Insert active chat user count into our on-disk time series storage.- if err := storage.InsertRows([]tstorage.Row{+ if err := s.storage.InsertRows([]tstorage.Row{{Metric: activeChatClientCountKey,DataPoint: tstorage.DataPoint{Timestamp: time.Now().Unix(), Value: float64(count)},@@ -79,8 +72,8 @@ func collectChatClientCount() {}// GetViewersOverTime will return a window of viewer counts over time.-func GetViewersOverTime(start, end time.Time) []TimestampedValue {- p, err := storage.Select(activeViewerCountKey, nil, start.Unix(), end.Unix())+func (s *Service) GetViewersOverTime(start, end time.Time) []TimestampedValue {+ p, err := s.storage.Select(activeViewerCountKey, nil, start.Unix(), end.Unix())if err != nil && err != tstorage.ErrNoDataPoints {log.Errorln(err)}@@ -90,8 +83,8 @@ func GetViewersOverTime(start, end time.Time) []TimestampedValue {}// GetChatClientCountOverTime will return a window of connected chat clients over time.-func GetChatClientCountOverTime(start, end time.Time) []TimestampedValue {- p, err := storage.Select(activeChatClientCountKey, nil, start.Unix(), end.Unix())+func (s *Service) GetChatClientCountOverTime(start, end time.Time) []TimestampedValue {+ p, err := s.storage.Select(activeChatClientCountKey, nil, start.Unix(), end.Unix())if err != nil && err != tstorage.ErrNoDataPoints {log.Errorln(err)}diff --git a/notifications/browser/browser.go b/notifications/browser/browser.goindex 6d97a79498..6584d5c81a 100644--- a/notifications/browser/browser.go+++ b/notifications/browser/browser.go@@ -4,19 +4,20 @@ import ("encoding/json""github.com/SherClockHolmes/webpush-go"- "github.com/owncast/owncast/core/data""github.com/pkg/errors"++ "github.com/owncast/owncast/services/datastore")// Browser is an instance of the Browser service.type Browser struct {- datastore *data.Datastore+ datastore *datastore.DatastoreprivateKey stringpublicKey string}// New will create a new instance of the Browser service.-func New(datastore *data.Datastore, publicKey, privateKey string) (*Browser, error) {+func New(datastore *datastore.Datastore, publicKey, privateKey string) (*Browser, error) {return &Browser{datastore: datastore,privateKey: privateKey,diff --git a/persistence/authrepository/sqlauthrepository.go b/persistence/authrepository/sqlauthrepository.goindex 7ab667df53..603285e674 100644--- a/persistence/authrepository/sqlauthrepository.go+++ b/persistence/authrepository/sqlauthrepository.go@@ -1,27 +1,15 @@package authrepositoryimport (- "github.com/owncast/owncast/core/data"+ "github.com/owncast/owncast/services/datastore")type SqlAuthRepository struct {- datastore *data.Datastore-}--// NOTE: This is temporary during the transition period.-var temporaryGlobalInstance AuthRepository--// Get will return the user repository.-func Get() AuthRepository {- if temporaryGlobalInstance == nil {- i := New(data.GetDatastore())- temporaryGlobalInstance = i- }- return temporaryGlobalInstance+ datastore *datastore.Datastore}// New will create a new instance of the UserRepository.-func New(datastore *data.Datastore) *SqlAuthRepository {+func New(datastore *datastore.Datastore) *SqlAuthRepository {r := &SqlAuthRepository{datastore: datastore,}diff --git a/persistence/chatmessagerepository/chatmessagerepository.go b/persistence/chatmessagerepository/chatmessagerepository.goindex f5b8663160..5f4cc575ae 100644--- a/persistence/chatmessagerepository/chatmessagerepository.go+++ b/persistence/chatmessagerepository/chatmessagerepository.go@@ -7,9 +7,9 @@ import ("strings""time"- "github.com/owncast/owncast/core/chat/events"- "github.com/owncast/owncast/core/data""github.com/owncast/owncast/models"+ "github.com/owncast/owncast/services/chat/events"+ "github.com/owncast/owncast/services/datastore"log "github.com/sirupsen/logrus")@@ -29,23 +29,12 @@ type ChatMessageRepository interface {}type SqlChatMessageRepository struct {- datastore *data.Datastore+ datastore *datastore.Datastore+ historyCache *[]interface{}}-// NOTE: This is temporary during the transition period.-var temporaryGlobalInstance ChatMessageRepository--// Get will return the user repository.-func Get() ChatMessageRepository {- if temporaryGlobalInstance == nil {- i := New(data.GetDatastore())- temporaryGlobalInstance = i- }- return temporaryGlobalInstance-}--// New will create a new instance of the UserRepository.-func New(datastore *data.Datastore) ChatMessageRepository {+// New will create a new instance of the ChatMessageRepository.+func New(datastore *datastore.Datastore) ChatMessageRepository {r := SqlChatMessageRepository{datastore: datastore,}@@ -65,7 +54,7 @@ func (r *SqlChatMessageRepository) SaveFederatedAction(event events.FediverseEng// nolint: unparamfunc (r *SqlChatMessageRepository) SaveEvent(id string, userID *string, body string, eventType string, hidden *time.Time, timestamp time.Time, image *string, link *string, title *string, subtitle *string) {defer func() {- _historyCache = nil+ r.historyCache = nil}()tx, err := r.datastore.DB.Begin()@@ -282,12 +271,10 @@ func getChat(rows *sql.Rows) ([]interface{}, error) {return history, nil}-var _historyCache *[]interface{}-// GetChatModerationHistory will return all the chat messages suitable for moderation purposes.func (r *SqlChatMessageRepository) GetChatModerationHistory() []interface{} {- if _historyCache != nil {- return *_historyCache+ if r.historyCache != nil {+ return *r.historyCache}tx, err := r.datastore.DB.Begin()@@ -322,7 +309,7 @@ func (r *SqlChatMessageRepository) GetChatModerationHistory() []interface{} {return nil}- _historyCache = &result+ r.historyCache = &resultif err = tx.Commit(); err != nil {log.Errorln("error fetching chat moderation history", err)@@ -406,7 +393,7 @@ func (r *SqlChatMessageRepository) GetMessagesFromUser(userID string) ([]events.// GetMessageIdsForUserID will return the chat message IDs for a specific user.func (r *SqlChatMessageRepository) GetMessageIdsForUserID(userID string) ([]string, error) {defer func() {- _historyCache = nil+ r.historyCache = nil}()tx, err := r.datastore.DB.Begin()@@ -458,7 +445,7 @@ func (r *SqlChatMessageRepository) GetMessageIdsForUserID(userID string) ([]strifunc (r *SqlChatMessageRepository) SetMessageVisibilityForMessageIDs(messageIDs []string, visible bool) error {defer func() {- _historyCache = nil+ r.historyCache = nil}()if len(messageIDs) == 0 {diff --git a/persistence/configrepository/configMigrations.go b/persistence/configrepository/configMigrations.goindex 325f8769ff..e40f30346d 100644--- a/persistence/configrepository/configMigrations.go+++ b/persistence/configrepository/configMigrations.go@@ -3,9 +3,10 @@ package configrepositoryimport ("strings"- "github.com/owncast/owncast/core/data"- "github.com/owncast/owncast/webserver/handlers/generated"log "github.com/sirupsen/logrus"++ "github.com/owncast/owncast/services/datastore"+ "github.com/owncast/owncast/webserver/handlers/generated")const (@@ -13,7 +14,7 @@ const (datastoreValueVersionKey = "DATA_STORE_VERSION")-func migrateDatastoreValues(datastore *data.Datastore, configRepository ConfigRepository) {+func migrateDatastoreValues(datastore *datastore.Datastore, configRepository ConfigRepository) {currentVersion, _ := datastore.GetNumber(datastoreValueVersionKey)if currentVersion == 0 {currentVersion = datastoreValuesVersion@@ -39,7 +40,7 @@ func migrateDatastoreValues(datastore *data.Datastore, configRepository ConfigRe}}-func migrateToDatastoreValues1(datastore *data.Datastore) {+func migrateToDatastoreValues1(datastore *datastore.Datastore) {// Migrate the forbidden usernames to be a slice instead of a string.forbiddenUsernamesString, _ := datastore.GetString(blockedUsernamesKey)if forbiddenUsernamesString != "" {@@ -59,7 +60,7 @@ func migrateToDatastoreValues1(datastore *data.Datastore) {}}-func migrateToDatastoreValues2(datastore *data.Datastore, configRepository ConfigRepository) {+func migrateToDatastoreValues2(datastore *datastore.Datastore, configRepository ConfigRepository) {oldAdminPassword, _ := datastore.GetString("stream_key")// Avoids double hashing the password_ = datastore.SetString("admin_password_key", oldAdminPassword)@@ -79,7 +80,7 @@ func migrateToDatastoreValues3ServingEndpoint3(configRepository ConfigRepository_ = configRepository.SetVideoServingEndpoint(s3Config.ServingEndpoint)}-func migrateToDatastoreValues4(datastore *data.Datastore, configRepository ConfigRepository) {+func migrateToDatastoreValues4(datastore *datastore.Datastore, configRepository ConfigRepository) {unhashed_pass, _ := datastore.GetString("admin_password_key")err := configRepository.SetAdminPassword(unhashed_pass)if err != nil {diff --git a/persistence/configrepository/configrepository.go b/persistence/configrepository/configrepository.goindex 3e12651cd0..be2798b245 100644--- a/persistence/configrepository/configrepository.go+++ b/persistence/configrepository/configrepository.go@@ -77,7 +77,7 @@ type ConfigRepository interface {GetCustomJavascript() stringSetVideoCodec(codec string) errorGetVideoCodec() string- VerifySettings() error+ VerifySettings(temporaryStreamKey string) errorFindHighestVideoQualityIndex(qualities []models.StreamOutputVariant) (int, bool)GetForbiddenUsernameList() []stringSetForbiddenUsernameList(usernames []string) errordiff --git a/persistence/configrepository/defaults.go b/persistence/configrepository/defaults.goindex 6d05eb1abd..d6a536b9f4 100644--- a/persistence/configrepository/defaults.go+++ b/persistence/configrepository/defaults.go@@ -1,9 +1,10 @@package configrepositoryimport (+ log "github.com/sirupsen/logrus"+"github.com/owncast/owncast/config""github.com/owncast/owncast/models"- log "github.com/sirupsen/logrus")// PopulateDefaults will set default values in the database.diff --git a/persistence/configrepository/sqlconfigrepository.go b/persistence/configrepository/sqlconfigrepository.goindex b9e152e4c2..276336d20b 100644--- a/persistence/configrepository/sqlconfigrepository.go+++ b/persistence/configrepository/sqlconfigrepository.go@@ -7,34 +7,23 @@ import ("strings""time"+ "github.com/pkg/errors"+ log "github.com/sirupsen/logrus"+"github.com/owncast/owncast/config"- "github.com/owncast/owncast/core/data""github.com/owncast/owncast/models"+ "github.com/owncast/owncast/services/datastore""github.com/owncast/owncast/static""github.com/owncast/owncast/utils""github.com/owncast/owncast/webserver/handlers/generated"- "github.com/pkg/errors"- log "github.com/sirupsen/logrus")type SqlConfigRepository struct {- datastore *data.Datastore-}--// NOTE: This is temporary during the transition period.-var temporaryGlobalInstance ConfigRepository--// Get will return the user repository.-func Get() ConfigRepository {- if temporaryGlobalInstance == nil {- i := New(data.GetDatastore())- temporaryGlobalInstance = i- }- return temporaryGlobalInstance+ datastore *datastore.Datastore}// New will create a new instance of the UserRepository.-func New(datastore *data.Datastore) ConfigRepository {+func New(datastore *datastore.Datastore) ConfigRepository {r := SqlConfigRepository{datastore: datastore,}@@ -639,8 +628,11 @@ func (r *SqlConfigRepository) GetVideoCodec() string {}// VerifySettings will perform a sanity check for specific settings values.-func (r *SqlConfigRepository) VerifySettings() error {- if len(r.GetStreamKeys()) == 0 && config.TemporaryStreamKey == "" {+// temporaryStreamKey is the value of the optional --streamkey CLI flag; the+// repository checks it alongside the persisted stream-key list to decide+// whether the server has any usable stream key at all.+func (r *SqlConfigRepository) VerifySettings(temporaryStreamKey string) error {+ if len(r.GetStreamKeys()) == 0 && temporaryStreamKey == "" {log.Errorln("No stream key set. Streaming is disabled. Please set one via the admin or command line arguments")}diff --git a/persistence/legacymigrations/migrations.go b/persistence/legacymigrations/migrations.goindex 4e296fe021..ce16c46a81 100644--- a/persistence/legacymigrations/migrations.go+++ b/persistence/legacymigrations/migrations.go@@ -14,15 +14,16 @@ import ("path/filepath""time"- "github.com/owncast/owncast/config"- "github.com/owncast/owncast/utils"log "github.com/sirupsen/logrus""github.com/teris-io/shortid"++ "github.com/owncast/owncast/config"+ "github.com/owncast/owncast/utils")-func MigrateDatabaseSchema(db *sql.DB, from, to int) error {+func MigrateDatabaseSchema(db *sql.DB, backupDirectory string, from, to int) error {log.Printf("Migrating database from version %d to %d", from, to)- dbBackupFile := filepath.Join(config.BackupDirectory, fmt.Sprintf("owncast-v%d.bak", from))+ dbBackupFile := filepath.Join(backupDirectory, fmt.Sprintf("owncast-v%d.bak", from))utils.Backup(db, dbBackupFile)for v := from; v < to; v++ {log.Tracef("Migration step from %d to %d\n", v, v+1)diff --git a/persistence/legacymigrations/notifications.go b/persistence/legacymigrations/notifications.goindex a1bfc5534d..8c9a7b6d7b 100644--- a/persistence/legacymigrations/notifications.go+++ b/persistence/legacymigrations/notifications.go@@ -3,8 +3,9 @@ package legacymigrationsimport ("database/sql"- "github.com/owncast/owncast/utils"log "github.com/sirupsen/logrus"++ "github.com/owncast/owncast/utils")func CreateNotificationsTable(db *sql.DB) {diff --git a/persistence/legacymigrations/users.go b/persistence/legacymigrations/users.goindex 5bac1a7c80..5cf774953b 100644--- a/persistence/legacymigrations/users.go+++ b/persistence/legacymigrations/users.go@@ -3,8 +3,9 @@ package legacymigrationsimport ("database/sql"- "github.com/owncast/owncast/utils"log "github.com/sirupsen/logrus"++ "github.com/owncast/owncast/utils")func SetupUsers(db *sql.DB) {diff --git a/persistence/migrations/migrations.go b/persistence/migrations/migrations.goindex fe0f677b22..392b182195 100644--- a/persistence/migrations/migrations.go+++ b/persistence/migrations/migrations.go@@ -23,9 +23,10 @@ import ("fmt""strings"- "github.com/owncast/owncast/persistence/legacymigrations""github.com/pressly/goose/v3"log "github.com/sirupsen/logrus"++ "github.com/owncast/owncast/persistence/legacymigrations")//go:embed *.sql@@ -43,7 +44,8 @@ const legacyBaselineVersion = 9// For installs that predate goose, the legacy catch-up runs first and then// the baseline is recorded as applied (its statements are all IF NOT EXISTS// and become no-ops on an already-populated database).-func Run(db *sql.DB) error {+// backupDirectory is where the legacy bridge writes pre-migration backups.+func Run(db *sql.DB, backupDirectory string) error {legacyVersion, err := readLegacyVersion(db)if err != nil {return fmt.Errorf("reading legacy schema version: %w", err)@@ -52,7 +54,7 @@ func Run(db *sql.DB) error {if legacyVersion > 0 && legacyVersion < legacyBaselineVersion {log.Infof("Legacy schema at version %d; upgrading to %d before handing off to goose",legacyVersion, legacyBaselineVersion)- if err := legacymigrations.MigrateDatabaseSchema(db, legacyVersion, legacyBaselineVersion); err != nil {+ if err := legacymigrations.MigrateDatabaseSchema(db, backupDirectory, legacyVersion, legacyBaselineVersion); err != nil {return fmt.Errorf("legacy schema catch-up: %w", err)}}diff --git a/persistence/migrations/migrations_test.go b/persistence/migrations/migrations_test.goindex c59e73df55..7d26d9b233 100644--- a/persistence/migrations/migrations_test.go+++ b/persistence/migrations/migrations_test.go@@ -46,7 +46,7 @@ func mustExec(t *testing.T, db *sql.DB, query string) {func TestRun_FreshDatabase(t *testing.T) {db := openTestDB(t)- if err := Run(db); err != nil {+ if err := Run(db, t.TempDir()); err != nil {t.Fatalf("Run on fresh DB: %v", err)}@@ -72,7 +72,7 @@ func TestRun_FreshDatabase(t *testing.T) {}// Calling Run a second time should be a no-op (idempotent).- if err := Run(db); err != nil {+ if err := Run(db, t.TempDir()); err != nil {t.Fatalf("second Run: %v", err)}}@@ -87,7 +87,7 @@ func TestRun_LegacyDatabaseAtV9(t *testing.T) {var tableCount intmustScan(t, db.QueryRow(`SELECT count(*) FROM sqlite_master WHERE type='table'`), &tableCount)- if err := Run(db); err != nil {+ if err := Run(db, t.TempDir()); err != nil {t.Fatalf("Run on v9 legacy DB: %v", err)}@@ -114,9 +114,9 @@ func TestRun_LegacyDatabaseAtV9(t *testing.T) {// TestRun_LegacyDatabasePreV9 verifies that a pre-v9 install runs the legacy// bridge to reach v9, then goose records the baseline.func TestRun_LegacyDatabasePreV9(t *testing.T) {- // The legacy migration code writes a backup file to config.BackupDirectory.- // Use a temp working directory so the side effect is contained.- t.Chdir(t.TempDir())+ // The legacy migration code writes a backup file under the provided+ // backupDirectory; the test passes a temp dir so the side effect is+ // contained.db := openTestDB(t)@@ -126,7 +126,7 @@ func TestRun_LegacyDatabasePreV9(t *testing.T) {createV9Schema(t, db)mustExec(t, db, `UPDATE config SET value = 7 WHERE key = 'version'`)- if err := Run(db); err != nil {+ if err := Run(db, t.TempDir()); err != nil {t.Fatalf("Run on v7 legacy DB: %v", err)}diff --git a/persistence/notificationsrepository/integration_test.go b/persistence/notificationsrepository/integration_test.goindex 0b571770d4..bb8b8409c4 100644--- a/persistence/notificationsrepository/integration_test.go+++ b/persistence/notificationsrepository/integration_test.go@@ -3,13 +3,13 @@ package notificationsrepositoryimport ("testing"- "github.com/owncast/owncast/core/data""github.com/owncast/owncast/models""github.com/owncast/owncast/persistence/configrepository"+ "github.com/owncast/owncast/services/datastore")var (- integrationTestDatastore *data.Datastore+ integrationTestDatastore *datastore.DatastoreintegrationRepo NotificationsRepository)@@ -18,7 +18,7 @@ func init() {// This ensures we're using the same database setupintegrationTestDatastore = testDatastoreif integrationTestDatastore != nil {- integrationRepo = New(integrationTestDatastore)+ integrationRepo = New(integrationTestDatastore, configrepository.New(integrationTestDatastore))}}@@ -26,9 +26,9 @@ func TestIntegrationSetup(t *testing.T) {// This test ensures integration setup works properly// The actual setup is done in the init function belowif integrationTestDatastore == nil {- integrationTestDatastore = data.GetDatastore()- Setup()- integrationRepo = New(integrationTestDatastore)+ integrationTestDatastore = testDatastore+ integrationRepo = New(integrationTestDatastore, configrepository.New(integrationTestDatastore))+ integrationRepo.Setup()}if integrationRepo == nil {@@ -38,13 +38,13 @@ func TestIntegrationSetup(t *testing.T) {func TestBrowserPushSetupIntegration(t *testing.T) {// Test that browser push keys are generated during setup- configRepo := configrepository.Get()- pubKey, err := configRepo.GetBrowserPushPublicKey()+ configRepository := configrepository.New(testDatastore)+ pubKey, err := configRepository.GetBrowserPushPublicKey()if err != nil {t.Errorf("Should be able to get browser push public key: %v", err)}- privKey, err := configRepo.GetBrowserPushPrivateKey()+ privKey, err := configRepository.GetBrowserPushPrivateKey()if err != nil {t.Errorf("Should be able to get browser push private key: %v", err)}@@ -56,23 +56,23 @@ func TestBrowserPushSetupIntegration(t *testing.T) {}func TestBrowserPushConfigurationIntegration(t *testing.T) {- configRepo := configrepository.Get()+ configRepository := configrepository.New(testDatastore)// Test that browser push is enabled by default- browserConfig := configRepo.GetBrowserPushConfig()+ browserConfig := configRepository.GetBrowserPushConfig()if !browserConfig.Enabled {t.Error("Browser push should be enabled by default")}// Test that initial notification configuration flag is set- hasConfigured := configRepo.GetHasPerformedInitialNotificationsConfig()+ hasConfigured := configRepository.GetHasPerformedInitialNotificationsConfig()if !hasConfigured {t.Error("Should have performed initial notifications configuration")}}func TestDiscordConfigurationIntegration(t *testing.T) {- configRepo := configrepository.Get()+ configRepository := configrepository.New(testDatastore)// Test Discord configuration setupdiscordConfig := models.DiscordConfiguration{@@ -81,7 +81,7 @@ func TestDiscordConfigurationIntegration(t *testing.T) {GoLiveMessage: "Test stream is live!",}- err := configRepo.SetDiscordConfig(discordConfig)+ err := configRepository.SetDiscordConfig(discordConfig)if err != nil {t.Errorf("Failed to set Discord configuration: %v", err)}@@ -91,7 +91,7 @@ func TestDiscordConfigurationIntegration(t *testing.T) {Enabled: false,Webhook: "",}- err = configRepo.SetDiscordConfig(disabledConfig)+ err = configRepository.SetDiscordConfig(disabledConfig)if err != nil {t.Errorf("Failed to disable Discord configuration: %v", err)}@@ -144,19 +144,6 @@ func TestNotificationWorkflowIntegration(t *testing.T) {}}-func TestRepositoryGetSingleton(t *testing.T) {- // Test that Get() returns the same instance- repo1 := Get()- repo2 := Get()-- if repo1 != repo2 {- t.Error("Get() should return the same singleton instance")- }-- // Test that it implements the interface- var _ NotificationsRepository = repo1-}-func TestDatabaseTransactionIntegrity(t *testing.T) {channel := "TRANSACTION_TEST_CHANNEL"destinations := []string{"dest1", "dest2", "dest3"}diff --git a/persistence/notificationsrepository/notificationsrepository.go b/persistence/notificationsrepository/notificationsrepository.goindex e4a41b273e..2c180558ba 100644--- a/persistence/notificationsrepository/notificationsrepository.go+++ b/persistence/notificationsrepository/notificationsrepository.go@@ -4,50 +4,39 @@ import ("context""github.com/owncast/owncast/config"- "github.com/owncast/owncast/core/data""github.com/owncast/owncast/db""github.com/owncast/owncast/models""github.com/owncast/owncast/persistence/configrepository"+ "github.com/owncast/owncast/services/datastore"- "github.com/owncast/owncast/notifications/browser""github.com/pkg/errors"log "github.com/sirupsen/logrus"++ "github.com/owncast/owncast/notifications/browser")type NotificationsRepository interface {AddNotification(channel, destination string) errorRemoveNotificationForChannel(channel, destination string) errorGetNotificationDestinationsForChannel(channel string) ([]string, error)+ Setup()}// SqlNotificationsRepository handles database operations for notifications.type SqlNotificationsRepository struct {- datastore *data.Datastore-}--// NOTE: This is temporary during the transition period.-var temporaryGlobalInstance NotificationsRepository--// Get will return the notifications repository.-func Get() NotificationsRepository {- if temporaryGlobalInstance == nil {- i := New(data.GetDatastore())- temporaryGlobalInstance = i- }- return temporaryGlobalInstance+ datastore *datastore.Datastore+ configRepository configrepository.ConfigRepository}// Setup will perform any pre-use setup for the notifier.// The notifications table itself is created by the goose migrations package.-func Setup() {- initializeBrowserPushIfNeeded()+func (n *SqlNotificationsRepository) Setup() {+ n.initializeBrowserPushIfNeeded()}-func initializeBrowserPushIfNeeded() {- configRepository := configrepository.Get()-- pubKey, _ := configRepository.GetBrowserPushPublicKey()- privKey, _ := configRepository.GetBrowserPushPrivateKey()+func (n *SqlNotificationsRepository) initializeBrowserPushIfNeeded() {+ pubKey, _ := n.configRepository.GetBrowserPushPublicKey()+ privKey, _ := n.configRepository.GetBrowserPushPrivateKey()// We need browser push keys so people can register for pushes.if pubKey == "" || privKey == "" {@@ -56,26 +45,27 @@ func initializeBrowserPushIfNeeded() {log.Errorln("unable to initialize browser push notification keys", err)}- if err := configRepository.SetBrowserPushPrivateKey(browserPrivateKey); err != nil {+ if err := n.configRepository.SetBrowserPushPrivateKey(browserPrivateKey); err != nil {log.Errorln("unable to set browser push private key", err)}- if err := configRepository.SetBrowserPushPublicKey(browserPublicKey); err != nil {+ if err := n.configRepository.SetBrowserPushPublicKey(browserPublicKey); err != nil {log.Errorln("unable to set browser push public key", err)}}// Enable browser push notifications by default.- if !configRepository.GetHasPerformedInitialNotificationsConfig() {- _ = configRepository.SetBrowserPushConfig(models.BrowserNotificationConfiguration{Enabled: true, GoLiveMessage: config.GetDefaults().FederationGoLiveMessage})- _ = configRepository.SetHasPerformedInitialNotificationsConfig(true)+ if !n.configRepository.GetHasPerformedInitialNotificationsConfig() {+ _ = n.configRepository.SetBrowserPushConfig(models.BrowserNotificationConfiguration{Enabled: true, GoLiveMessage: config.GetDefaults().FederationGoLiveMessage})+ _ = n.configRepository.SetHasPerformedInitialNotificationsConfig(true)}}// New creates a new instance of the NotificationsRepository.-func New(datastore *data.Datastore) NotificationsRepository {+func New(datastore *datastore.Datastore, configRepository configrepository.ConfigRepository) NotificationsRepository {return &SqlNotificationsRepository{- datastore: datastore,+ datastore: datastore,+ configRepository: configRepository,}}diff --git a/persistence/notificationsrepository/notificationsrepository_test.go b/persistence/notificationsrepository/notificationsrepository_test.goindex fa44ccd1dd..86875f4be2 100644--- a/persistence/notificationsrepository/notificationsrepository_test.go+++ b/persistence/notificationsrepository/notificationsrepository_test.go@@ -2,28 +2,29 @@ package notificationsrepositoryimport ("fmt"+ "os""testing"- "github.com/owncast/owncast/core/data"+ "github.com/owncast/owncast/persistence/configrepository"+ "github.com/owncast/owncast/services/datastore")var (- testDatastore *data.Datastore+ testDatastore *datastore.DatastoretestRepo NotificationsRepository)func TestMain(m *testing.M) {// Create an in-memory database for testing- if err := data.SetupPersistence(":memory:"); err != nil {+ ds, err := datastore.SetupPersistence(":memory:", os.TempDir())+ if err != nil {panic(err)}+ testDatastore = ds- // Get the shared datastore instance- testDatastore = data.GetDatastore()-- // Setup the notifications repository- Setup()- testRepo = New(testDatastore)+ // Setup the notifications repository.+ testRepo = New(testDatastore, configrepository.New(testDatastore))+ testRepo.Setup()// Run testsm.Run()@@ -178,14 +179,8 @@ func TestNotificationRepositoryInterface(t *testing.T) {// Test that our implementation satisfies the interfacevar _ NotificationsRepository = &SqlNotificationsRepository{}- // Test that we can get the repository instance- repo := Get()- if repo == nil {- t.Error("Get() should return a non-nil repository instance")- }-// Test that New creates a valid repository- newRepo := New(testDatastore)+ newRepo := New(testDatastore, configrepository.New(testDatastore))if newRepo == nil {t.Error("New() should return a non-nil repository instance")}diff --git a/persistence/userrepository/userrepository.go b/persistence/userrepository/userrepository.goindex 5fe2d078a9..ed108043fc 100644--- a/persistence/userrepository/userrepository.go+++ b/persistence/userrepository/userrepository.go@@ -9,14 +9,15 @@ import ("time""github.com/owncast/owncast/config"- "github.com/owncast/owncast/core/data""github.com/owncast/owncast/db"+ "github.com/owncast/owncast/services/datastore"- "github.com/owncast/owncast/models"- "github.com/owncast/owncast/utils""github.com/pkg/errors""github.com/teris-io/shortid"+ "github.com/owncast/owncast/models"+ "github.com/owncast/owncast/utils"+log "github.com/sirupsen/logrus")@@ -45,23 +46,11 @@ type UserRepository interface {}type SqlUserRepository struct {- datastore *data.Datastore-}--// NOTE: This is temporary during the transition period.-var temporaryGlobalInstance UserRepository--// Get will return the user repository.-func Get() UserRepository {- if temporaryGlobalInstance == nil {- i := New(data.GetDatastore())- temporaryGlobalInstance = i- }- return temporaryGlobalInstance+ datastore *datastore.Datastore}// New will create a new instance of the UserRepository.-func New(datastore *data.Datastore) UserRepository {+func New(datastore *datastore.Datastore) UserRepository {r := SqlUserRepository{datastore: datastore,}diff --git a/persistence/webhookrepository/webhookrepository.go b/persistence/webhookrepository/webhookrepository.goindex 4a36b82994..61a50caed2 100644--- a/persistence/webhookrepository/webhookrepository.go+++ b/persistence/webhookrepository/webhookrepository.go@@ -6,9 +6,10 @@ import ("strings""time"- "github.com/owncast/owncast/core/data"- "github.com/owncast/owncast/models"log "github.com/sirupsen/logrus"++ "github.com/owncast/owncast/models"+ "github.com/owncast/owncast/services/datastore")type WebhookRepository interface {@@ -20,23 +21,11 @@ type WebhookRepository interface {}type SqlWebhookRepository struct {- datastore *data.Datastore-}--// NOTE: This is temporary during the transition period.-var temporaryGlobalInstance WebhookRepository--// Get will return the user repository.-func Get() WebhookRepository {- if temporaryGlobalInstance == nil {- i := New(data.GetDatastore())- temporaryGlobalInstance = i- }- return temporaryGlobalInstance+ datastore *datastore.Datastore}// New will create a new instance of the UserRepository.-func New(datastore *data.Datastore) WebhookRepository {+func New(datastore *datastore.Datastore) WebhookRepository {r := SqlWebhookRepository{datastore: datastore,}diff --git a/services/activitypub/activitypub.go b/services/activitypub/activitypub.gonew file mode 100644index 0000000000..dde3908033--- /dev/null+++ b/services/activitypub/activitypub.go@@ -0,0 +1,220 @@+// Package activitypub is the composition root for the federation+// subsystem. It wires together the persistence, workerpool, outbox,+// inbox, controllers, and jobs sub-services, exposes a small+// stream/admin-facing API (SendLive, SendPublic, GetFollowerCount, …),+// and hands the controllers set to the router.+package activitypub++import (+ log "github.com/sirupsen/logrus"++ "github.com/owncast/owncast/config"+ "github.com/owncast/owncast/models"+ "github.com/owncast/owncast/persistence/configrepository"+ "github.com/owncast/owncast/services/activitypub/apmodels"+ "github.com/owncast/owncast/services/activitypub/controllers"+ "github.com/owncast/owncast/services/activitypub/crypto"+ "github.com/owncast/owncast/services/activitypub/inbox"+ "github.com/owncast/owncast/services/activitypub/jobs"+ "github.com/owncast/owncast/services/activitypub/outbox"+ "github.com/owncast/owncast/services/activitypub/persistence"+ "github.com/owncast/owncast/services/activitypub/persistence/followersrepository"+ apresolvers "github.com/owncast/owncast/services/activitypub/resolvers"+ "github.com/owncast/owncast/services/activitypub/workerpool"+ "github.com/owncast/owncast/services/chat"+ "github.com/owncast/owncast/services/datastore"+ "github.com/owncast/owncast/services/webhooks"+)++// Service is the composed federation subsystem. Construct one in+// main.go with New(Deps) and call Start to spin up the worker pools and+// background jobs. Hand .Controllers() to the router for HTTP routing.+type Service struct {+ persistence *persistence.Service+ workerpool *workerpool.Service+ outbox *outbox.Service+ inbox *inbox.Service+ jobs *jobs.Service+ controllers *controllers.Controllers+ followers followersrepository.FollowersRepository+ configRepository configrepository.ConfigRepository+}++// Deps lists the explicit construction inputs for the federation+// subsystem.+type Deps struct {+ Datastore *datastore.Datastore+ Webhooks *webhooks.Service+ Chat *chat.Service+ ConfigRepository configrepository.ConfigRepository+ FollowersRepository followersrepository.FollowersRepository+ Builder *apmodels.Builder+ Signer *crypto.Signer+ Resolver *apresolvers.Resolver+ Config *config.Config+}++// New constructs the federation subsystem in dependency order. It does+// not spawn any goroutines or bind ports; call Start for that.+func New(deps Deps) *Service {+ persistenceSvc := persistence.New(deps.Datastore, deps.Resolver)+ followers := deps.FollowersRepository++ wpSvc := workerpool.New(outboundWorkerPoolSize(followers))++ outboxSvc := outbox.New(outbox.Deps{+ Persistence: persistenceSvc,+ Workerpool: wpSvc,+ Followers: followers,+ ConfigRepository: deps.ConfigRepository,+ Builder: deps.Builder,+ Signer: deps.Signer,+ Resolver: deps.Resolver,+ Config: deps.Config,+ })++ inboxSvc := inbox.New(inbox.Deps{+ Persistence: persistenceSvc,+ Workerpool: wpSvc,+ Followers: followers,+ Webhooks: deps.Webhooks,+ Chat: deps.Chat,+ ConfigRepository: deps.ConfigRepository,+ Builder: deps.Builder,+ Signer: deps.Signer,+ Resolver: deps.Resolver,+ })++ jobsSvc := jobs.New(jobs.Deps{+ Followers: followers,+ ConfigRepository: deps.ConfigRepository,+ Resolver: deps.Resolver,+ Config: deps.Config,+ })++ ctrls := controllers.New(controllers.Deps{+ Persistence: persistenceSvc,+ Outbox: outboxSvc,+ Inbox: inboxSvc,+ Followers: followers,+ ConfigRepository: deps.ConfigRepository,+ Builder: deps.Builder,+ Signer: deps.Signer,+ })++ return &Service{+ persistence: persistenceSvc,+ workerpool: wpSvc,+ outbox: outboxSvc,+ inbox: inboxSvc,+ jobs: jobsSvc,+ controllers: ctrls,+ followers: followers,+ configRepository: deps.ConfigRepository,+ }+}++// Start brings up the worker pools and recurring jobs. Also generates+// the signing keypair on first run.+func (s *Service) Start() {+ s.workerpool.Start()+ s.inbox.Start()++ // Generate the keys for signing federated activity if needed.+ if s.configRepository.GetPrivateKey() == "" {+ privateKey, publicKey, err := crypto.GenerateKeys()+ _ = s.configRepository.SetPrivateKey(string(privateKey))+ _ = s.configRepository.SetPublicKey(string(publicKey))+ if err != nil {+ log.Errorln("Unable to get private key", err)+ }+ }++ s.jobs.Start()+}++// Controllers returns the HTTP controller set so the router can mount+// federation routes against it.+func (s *Service) Controllers() *controllers.Controllers {+ return s.controllers+}++// Outbox returns the outbox service. Callers that send federated+// messages on behalf of the stream/admin layer go through this.+func (s *Service) Outbox() *outbox.Service {+ return s.outbox+}++// SendLive sends a "Go Live" message to followers.+func (s *Service) SendLive() error {+ return s.outbox.SendLive()+}++// SendPublicFederatedMessage sends an arbitrary message to all followers.+func (s *Service) SendPublicFederatedMessage(message string) error {+ return s.outbox.SendPublicMessage(message)+}++// SendDirectFederatedMessage sends a direct message to a single account.+func (s *Service) SendDirectFederatedMessage(message, account string) error {+ return s.outbox.SendDirectMessageToAccount(message, account)+}++// GetFollowerCount returns the local tracked follower count.+func (s *Service) GetFollowerCount() (int64, error) {+ return s.followers.GetCount()+}++// GetPendingFollowRequests returns the pending follow requests.+func (s *Service) GetPendingFollowRequests() ([]models.Follower, error) {+ return s.followers.GetPendingFollowRequests()+}++// UpdateFollowersWithAccountUpdates broadcasts a profile-update activity to followers.+func (s *Service) UpdateFollowersWithAccountUpdates() error {+ return s.outbox.UpdateFollowersWithAccountUpdates()+}++// GetInboundActivities returns saved inbound federated activities (paginated).+func (s *Service) GetInboundActivities(limit int, offset int) ([]models.FederatedActivity, int, error) {+ return s.persistence.GetInboundActivities(limit, offset)+}++// Followers returns the underlying followers repository for callers+// that need direct repo access (admin handlers paginating follower+// lists, etc.). Prefer the typed methods above where they exist.+func (s *Service) Followers() followersrepository.FollowersRepository {+ return s.followers+}++// Workerpool returns the outbound delivery worker pool. Exposed for the+// activitypub/requests helper functions that build and queue signed+// outbound requests directly.+func (s *Service) Workerpool() *workerpool.Service {+ return s.workerpool+}++// outboundWorkerPoolSize sizes the outbound delivery pool from the+// current follower count: base workers + 1 per 100 followers, clamped.+// Prevents excessive resource usage on instances with many followers.+func outboundWorkerPoolSize(followers followersrepository.FollowersRepository) int {+ const (+ minWorkers = 10+ maxWorkers = 50+ defaultWorkers = 20+ )++ fc, err := followers.GetCount()+ if err != nil {+ log.Errorln("Unable to get follower count", err)+ return defaultWorkers+ }++ workers := minWorkers + int(fc/100)+ if workers > maxWorkers {+ workers = maxWorkers+ }++ log.Debugf("Initializing ActivityPub outbound worker pool with %d workers for %d followers", workers, fc)+ return workers+}diff --git a/activitypub/apmodels/activity.go b/services/activitypub/apmodels/activity.gosimilarity index 92%rename from activitypub/apmodels/activity.gorename to services/activitypub/apmodels/activity.goindex 76aa06de60..71547b8c8b 100644--- a/activitypub/apmodels/activity.go+++ b/services/activitypub/apmodels/activity.go@@ -6,7 +6,6 @@ import ("github.com/go-fed/activity/streams""github.com/go-fed/activity/streams/vocab"- "github.com/owncast/owncast/persistence/configrepository")// PrivacyAudience represents the audience for an activity.@@ -100,11 +99,9 @@ func MakeActivityDirect(activity vocab.ActivityStreamsCreate, toIRI *url.URL) vo// MakeActivityPublic sets the required properties to make this activity// seen as public.-func MakeActivityPublic(activity vocab.ActivityStreamsCreate) vocab.ActivityStreamsCreate {- configRepository := configrepository.Get()-+func (b *Builder) MakeActivityPublic(activity vocab.ActivityStreamsCreate) vocab.ActivityStreamsCreate {// TO the public if we're not treating ActivityPub as "private".- if !configRepository.GetFederationIsPrivate() {+ if !b.configRepository.GetFederationIsPrivate() {public, _ := url.Parse(PUBLIC)to := streams.NewActivityStreamsToProperty()@@ -130,16 +127,15 @@ func MakeCreateActivity(activityID *url.URL) vocab.ActivityStreamsCreate {}// MakeUpdateActivity will return a new Update activity with the provided aID.-func MakeUpdateActivity(activityID *url.URL) vocab.ActivityStreamsUpdate {+func (b *Builder) MakeUpdateActivity(activityID *url.URL) vocab.ActivityStreamsUpdate {activity := streams.NewActivityStreamsUpdate()id := streams.NewJSONLDIdProperty()id.Set(activityID)activity.SetJSONLDId(id)// CC the public if we're not treating ActivityPub as "private".- configRepository := configrepository.Get()- if !configRepository.GetFederationIsPrivate() {+ if !b.configRepository.GetFederationIsPrivate() {public, _ := url.Parse(PUBLIC)cc := streams.NewActivityStreamsCcProperty()cc.AppendIRI(public)diff --git a/activitypub/apmodels/actor.go b/services/activitypub/apmodels/actor.gosimilarity index 91%rename from activitypub/apmodels/actor.gorename to services/activitypub/apmodels/actor.goindex 5e8dd1f35e..aaf3206280 100644--- a/activitypub/apmodels/actor.go+++ b/services/activitypub/apmodels/actor.go@@ -8,10 +8,9 @@ import ("github.com/go-fed/activity/streams""github.com/go-fed/activity/streams/vocab"- "github.com/owncast/owncast/activitypub/crypto"- "github.com/owncast/owncast/models"- "github.com/owncast/owncast/persistence/configrepository"log "github.com/sirupsen/logrus"++ "github.com/owncast/owncast/models")// ActivityPubActor represents a single actor in handling ActivityPub activity.@@ -214,31 +213,29 @@ func MakeActorPropertyWithID(idIRI *url.URL) vocab.ActivityStreamsActorProperty}// MakeServiceForAccount will create a new local actor service with the the provided username.-func MakeServiceForAccount(accountName string) vocab.ActivityStreamsService {- configRepository := configrepository.Get()-- actorIRI := MakeLocalIRIForAccount(accountName)+func (b *Builder) MakeServiceForAccount(accountName string) vocab.ActivityStreamsService {+ actorIRI := b.MakeLocalIRIForAccount(accountName)person := streams.NewActivityStreamsService()nameProperty := streams.NewActivityStreamsNameProperty()- nameProperty.AppendXMLSchemaString(configRepository.GetServerName())+ nameProperty.AppendXMLSchemaString(b.configRepository.GetServerName())person.SetActivityStreamsName(nameProperty)preferredUsernameProperty := streams.NewActivityStreamsPreferredUsernameProperty()preferredUsernameProperty.SetXMLSchemaString(accountName)person.SetActivityStreamsPreferredUsername(preferredUsernameProperty)- inboxIRI := MakeLocalIRIForResource("/user/" + accountName + "/inbox")+ inboxIRI := b.MakeLocalIRIForResource("/user/" + accountName + "/inbox")inboxProp := streams.NewActivityStreamsInboxProperty()inboxProp.SetIRI(inboxIRI)person.SetActivityStreamsInbox(inboxProp)needsFollowApprovalProperty := streams.NewActivityStreamsManuallyApprovesFollowersProperty()- needsFollowApprovalProperty.Set(configRepository.GetFederationIsPrivate())+ needsFollowApprovalProperty.Set(b.configRepository.GetFederationIsPrivate())person.SetActivityStreamsManuallyApprovesFollowers(needsFollowApprovalProperty)- outboxIRI := MakeLocalIRIForResource("/user/" + accountName + "/outbox")+ outboxIRI := b.MakeLocalIRIForResource("/user/" + accountName + "/outbox")outboxProp := streams.NewActivityStreamsOutboxProperty()outboxProp.SetIRI(outboxIRI)@@ -248,7 +245,7 @@ func MakeServiceForAccount(accountName string) vocab.ActivityStreamsService {id.Set(actorIRI)person.SetJSONLDId(id)- publicKey := crypto.GetPublicKey(actorIRI)+ publicKey := b.signer.GetPublicKey(actorIRI)publicKeyProp := streams.NewW3IDSecurityV1PublicKeyProperty()publicKeyType := streams.NewW3IDSecurityV1PublicKey()@@ -268,7 +265,7 @@ func MakeServiceForAccount(accountName string) vocab.ActivityStreamsService {publicKeyProp.AppendW3IDSecurityV1PublicKey(publicKeyType)person.SetW3IDSecurityV1PublicKey(publicKeyProp)- if t, err := configRepository.GetServerInitTime(); t != nil {+ if t, err := b.configRepository.GetServerInitTime(); t != nil {publishedDateProp := streams.NewActivityStreamsPublishedProperty()publishedDateProp.Set(t.Time)person.SetActivityStreamsPublished(publishedDateProp)@@ -279,8 +276,8 @@ func MakeServiceForAccount(accountName string) vocab.ActivityStreamsService {// Profile properties// Avatar- uniquenessString := configRepository.GetLogoUniquenessString()- userAvatarURLString := configRepository.GetServerURL() + "/logo/external"+ uniquenessString := b.configRepository.GetLogoUniquenessString()+ userAvatarURLString := b.configRepository.GetServerURL() + "/logo/external"userAvatarURL, err := url.Parse(userAvatarURLString)userAvatarURL.RawQuery = "uc=" + uniquenessStringif err != nil {@@ -311,14 +308,14 @@ func MakeServiceForAccount(accountName string) vocab.ActivityStreamsService {// Profile biosummaryProperty := streams.NewActivityStreamsSummaryProperty()- summaryProperty.AppendXMLSchemaString(configRepository.GetServerSummary())+ summaryProperty.AppendXMLSchemaString(b.configRepository.GetServerSummary())person.SetActivityStreamsSummary(summaryProperty)// Links- if serverURL := configRepository.GetServerURL(); serverURL != "" {+ if serverURL := b.configRepository.GetServerURL(); serverURL != "" {addMetadataLinkToProfile(person, "Stream", serverURL)}- for _, link := range configRepository.GetSocialHandles() {+ for _, link := range b.configRepository.GetSocialHandles() {addMetadataLinkToProfile(person, link.Platform, link.URL)}@@ -336,7 +333,7 @@ func MakeServiceForAccount(accountName string) vocab.ActivityStreamsService {// TagstagProp := streams.NewActivityStreamsTagProperty()- for _, tagString := range configRepository.GetServerMetadataTags() {+ for _, tagString := range b.configRepository.GetServerMetadataTags() {hashtag := MakeHashtag(tagString)tagProp.AppendTootHashtag(hashtag)}@@ -345,7 +342,7 @@ func MakeServiceForAccount(accountName string) vocab.ActivityStreamsService {// Work around an issue where a single attachment will not serialize// as an array, so add another item to the mix.- if len(configRepository.GetSocialHandles()) == 1 {+ if len(b.configRepository.GetSocialHandles()) == 1 {addMetadataLinkToProfile(person, "Owncast", "https://owncast.online")}diff --git a/activitypub/apmodels/actor_test.go b/services/activitypub/apmodels/actor_test.gosimilarity index 96%rename from activitypub/apmodels/actor_test.gorename to services/activitypub/apmodels/actor_test.goindex 72a4ea1d50..75c780d483 100644--- a/activitypub/apmodels/actor_test.go+++ b/services/activitypub/apmodels/actor_test.go@@ -10,8 +10,18 @@ import ("github.com/go-fed/activity/streams""github.com/go-fed/activity/streams/vocab"- "github.com/owncast/owncast/core/data"+"github.com/owncast/owncast/persistence/configrepository"+ "github.com/owncast/owncast/services/activitypub/crypto"+ "github.com/owncast/owncast/services/datastore"+)++// testBuilder is the *Builder used by tests in this package. Initialized+// in TestMain against an in-memory datastore so the config-reading+// methods (MakeServiceForAccount, MakeLocalIRIForAccount, etc.) work.+var (+ testBuilder *Builder+ testDatastore *datastore.Datastore)func makeFakeService() vocab.ActivityStreamsService {@@ -60,9 +70,15 @@ func TestMain(m *testing.M) {if err != nil {panic(err)}- data.SetupPersistence(dbFile.Name())+ ds, err := datastore.SetupPersistence(dbFile.Name(), os.TempDir())+ if err != nil {+ panic(err)+ }+ testDatastore = ds- configRepository := configrepository.Get()+ configRepository := configrepository.New(testDatastore)+ signer := crypto.New(crypto.Deps{ConfigRepository: configRepository})+ testBuilder = New(Deps{ConfigRepository: configRepository, Signer: signer})configRepository.SetServerURL("https://my.cool.site.biz")@@ -107,7 +123,7 @@ func TestAddMetadataLinkToProfile(t *testing.T) {}func TestMakeServiceForAccount(t *testing.T) {- person := MakeServiceForAccount("accountname")+ person := testBuilder.MakeServiceForAccount("accountname")expectedIRI := "https://my.cool.site.biz/federation/user/accountname"if person.GetJSONLDId().Get().String() != expectedIRI {t.Errorf("actor.IRI = %v, want %v", person.GetJSONLDId().Get().String(), expectedIRI)@@ -158,13 +174,13 @@ func TestMakeServiceForAccount(t *testing.T) {}func TestMakeServiceForAccountWithIDNServerURL(t *testing.T) {- configRepository := configrepository.Get()+ configRepository := configrepository.New(testDatastore)configRepository.SetServerURL("https://live.retrospection.みんな")t.Cleanup(func() {configRepository.SetServerURL("https://my.cool.site.biz")})- person := MakeServiceForAccount("retrots3m")+ person := testBuilder.MakeServiceForAccount("retrots3m")payload, err := Serialize(person)if err != nil {t.Fatal(err)diff --git a/services/activitypub/apmodels/builder.go b/services/activitypub/apmodels/builder.gonew file mode 100644index 0000000000..a832412b2d--- /dev/null+++ b/services/activitypub/apmodels/builder.go@@ -0,0 +1,44 @@+// Package apmodels owns the ActivityPub data-model builders and+// helpers: actor/service profiles, notes, activities, webfinger+// responses, IRI construction. The free-function nil-safety accessors+// in utils.go and the data-model types in actor.go, activity.go,+// hashtag.go, inboxRequest.go, message.go, webfinger.go remain+// package-level since they don't read configuration.+//+// The builders that DO read configuration (MakeServiceForAccount,+// MakeLocalIRIForAccount, MakeNote, MakeCreateActivity,+// GetCanonicalServerURL, GetLogoType, MakeActivityPublic,+// MakeUpdateActivity, MakeAddressingToFollowers, MakeWebfingerResponse,+// CreateCreateActivity, MakeLocalIRIForResource,+// MakeLocalIRIForStreamURL, MakeLocalIRIforLogo, MakeLocalURLForPath)+// are methods on *Builder. Construct in main.go with New(Deps); pass+// to consumers via their own Deps structs.+package apmodels++import (+ "github.com/owncast/owncast/persistence/configrepository"+ "github.com/owncast/owncast/services/activitypub/crypto"+)++// Builder is the dependency-bearing handle for the ActivityPub+// model-construction helpers. It reads from configRepository for+// server URL, federation flags, logo, etc., and delegates to the+// crypto.Signer for actor public-key lookup.+type Builder struct {+ configRepository configrepository.ConfigRepository+ signer *crypto.Signer+}++// Deps is the explicit dependency contract for Builder.+type Deps struct {+ ConfigRepository configrepository.ConfigRepository+ Signer *crypto.Signer+}++// New constructs a Builder with the provided dependencies.+func New(deps Deps) *Builder {+ return &Builder{+ configRepository: deps.ConfigRepository,+ signer: deps.Signer,+ }+}diff --git a/activitypub/apmodels/hashtag.go b/services/activitypub/apmodels/hashtag.gosimilarity index 100%rename from activitypub/apmodels/hashtag.gorename to services/activitypub/apmodels/hashtag.godiff --git a/activitypub/apmodels/inboxRequest.go b/services/activitypub/apmodels/inboxRequest.gosimilarity index 100%rename from activitypub/apmodels/inboxRequest.gorename to services/activitypub/apmodels/inboxRequest.godiff --git a/activitypub/apmodels/message.go b/services/activitypub/apmodels/message.gosimilarity index 91%rename from activitypub/apmodels/message.gorename to services/activitypub/apmodels/message.goindex 646057c362..0b08981cdc 100644--- a/activitypub/apmodels/message.go+++ b/services/activitypub/apmodels/message.go@@ -8,8 +8,8 @@ import ()// CreateCreateActivity will create a new Create Activity model with the provided ID and IRI.-func CreateCreateActivity(id string, localAccountIRI *url.URL) vocab.ActivityStreamsCreate {- objectID := MakeLocalIRIForResource(id)+func (b *Builder) CreateCreateActivity(id string, localAccountIRI *url.URL) vocab.ActivityStreamsCreate {+ objectID := b.MakeLocalIRIForResource(id)message := MakeCreateActivity(objectID)actorProp := streams.NewActivityStreamsActorProperty()diff --git a/activitypub/apmodels/utils.go b/services/activitypub/apmodels/utils.gosimilarity index 90%rename from activitypub/apmodels/utils.gorename to services/activitypub/apmodels/utils.goindex 4497d940b4..58d57823f4 100644--- a/activitypub/apmodels/utils.go+++ b/services/activitypub/apmodels/utils.go@@ -9,9 +9,9 @@ import ("github.com/go-fed/activity/streams""github.com/go-fed/activity/streams/vocab"- "github.com/owncast/owncast/persistence/configrepository"- "github.com/owncast/owncast/utils"log "github.com/sirupsen/logrus"++ "github.com/owncast/owncast/utils")// MakeRemoteIRIForResource will create an IRI for a remote location.@@ -28,8 +28,8 @@ func MakeRemoteIRIForResource(resourcePath string, host string) (*url.URL, error}// MakeLocalIRIForResource will create an IRI for the local server.-func MakeLocalIRIForResource(resourcePath string) *url.URL {- u, err := GetCanonicalServerURL()+func (b *Builder) MakeLocalIRIForResource(resourcePath string) *url.URL {+ u, err := b.GetCanonicalServerURL()if err != nil {log.Errorln("unable to parse local IRI url", err)return nil@@ -41,8 +41,8 @@ func MakeLocalIRIForResource(resourcePath string) *url.URL {}// MakeLocalIRIForAccount will return a full IRI for the local server account username.-func MakeLocalIRIForAccount(account string) *url.URL {- u, err := GetCanonicalServerURL()+func (b *Builder) MakeLocalIRIForAccount(account string) *url.URL {+ u, err := b.GetCanonicalServerURL()if err != nil {log.Errorln("unable to parse local IRI account server url", err)return nil@@ -54,10 +54,8 @@ func MakeLocalIRIForAccount(account string) *url.URL {}// GetCanonicalServerURL returns the local server URL with an ASCII/punycode hostname.-func GetCanonicalServerURL() (*url.URL, error) {- configRepository := configrepository.Get()-- host := configRepository.GetServerURL()+func (b *Builder) GetCanonicalServerURL() (*url.URL, error) {+ host := b.configRepository.GetServerURL()canonicalHost, err := utils.CanonicalizeURLHostname(host)if err != nil {return nil, err@@ -67,8 +65,8 @@ func GetCanonicalServerURL() (*url.URL, error) {}// MakeLocalURLForPath will return a full URL for a path on the local server.-func MakeLocalURLForPath(resourcePath string) *url.URL {- u, err := GetCanonicalServerURL()+func (b *Builder) MakeLocalURLForPath(resourcePath string) *url.URL {+ u, err := b.GetCanonicalServerURL()if err != nil {log.Errorln("unable to parse local server url", err)return nil@@ -89,21 +87,19 @@ func Serialize(obj vocab.Type) ([]byte, error) {}// MakeLocalIRIForStreamURL will return a full IRI for the local server stream url.-func MakeLocalIRIForStreamURL() *url.URL {- return MakeLocalURLForPath("/hls/stream.m3u8")+func (b *Builder) MakeLocalIRIForStreamURL() *url.URL {+ return b.MakeLocalURLForPath("/hls/stream.m3u8")}// MakeLocalIRIforLogo will return a full IRI for the local server logo.-func MakeLocalIRIforLogo() *url.URL {- return MakeLocalURLForPath("/logo/external")+func (b *Builder) MakeLocalIRIforLogo() *url.URL {+ return b.MakeLocalURLForPath("/logo/external")}// GetLogoType will return the rel value for the webfinger response and// the default static image is of type png.-func GetLogoType() string {- configRepository := configrepository.Get()-- imageFilename := configRepository.GetLogoPath()+func (b *Builder) GetLogoType() string {+ imageFilename := b.configRepository.GetLogoPath()if imageFilename == "" {return "image/png"}diff --git a/activitypub/apmodels/utils_test.go b/services/activitypub/apmodels/utils_test.gosimilarity index 100%rename from activitypub/apmodels/utils_test.gorename to services/activitypub/apmodels/utils_test.godiff --git a/activitypub/apmodels/webfinger.go b/services/activitypub/apmodels/webfinger.gosimilarity index 85%rename from activitypub/apmodels/webfinger.gorename to services/activitypub/apmodels/webfinger.goindex f8151ca9dd..b79854fb06 100644--- a/activitypub/apmodels/webfinger.go+++ b/services/activitypub/apmodels/webfinger.go@@ -24,11 +24,11 @@ type Link struct {}// MakeWebfingerResponse will create a new Webfinger response.-func MakeWebfingerResponse(account string, inbox string, host string) WebfingerResponse {- accountIRI := MakeLocalIRIForAccount(account)- streamIRI := MakeLocalIRIForStreamURL()- logoIRI := MakeLocalIRIforLogo()- logoType := GetLogoType()+func (b *Builder) MakeWebfingerResponse(account string, inbox string, host string) WebfingerResponse {+ accountIRI := b.MakeLocalIRIForAccount(account)+ streamIRI := b.MakeLocalIRIForStreamURL()+ logoIRI := b.MakeLocalIRIforLogo()+ logoType := b.GetLogoType()return WebfingerResponse{Subject: fmt.Sprintf("acct:%s@%s", account, host),Aliases: []string{diff --git a/activitypub/controllers/actors.go b/services/activitypub/controllers/actors.gosimilarity index 57%rename from activitypub/controllers/actors.gorename to services/activitypub/controllers/actors.goindex 9a8d62e626..749795f454 100644--- a/activitypub/controllers/actors.go+++ b/services/activitypub/controllers/actors.go@@ -6,17 +6,12 @@ import (log "github.com/sirupsen/logrus"- "github.com/owncast/owncast/activitypub/apmodels"- "github.com/owncast/owncast/activitypub/crypto"- "github.com/owncast/owncast/activitypub/requests"- "github.com/owncast/owncast/persistence/configrepository"+ "github.com/owncast/owncast/services/activitypub/requests")// ActorHandler handles requests for a single actor.-func ActorHandler(w http.ResponseWriter, r *http.Request) {- configRepository := configrepository.Get()-- if !configRepository.GetFederationEnabled() {+func (c *Controllers) ActorHandler(w http.ResponseWriter, r *http.Request) {+ if !c.configRepository.GetFederationEnabled() {w.WriteHeader(http.StatusMethodNotAllowed)return}@@ -24,7 +19,7 @@ func ActorHandler(w http.ResponseWriter, r *http.Request) {pathComponents := strings.Split(r.URL.Path, "/")accountName := pathComponents[3]- if _, valid := configRepository.GetFederatedInboxMap()[accountName]; !valid {+ if _, valid := c.configRepository.GetFederatedInboxMap()[accountName]; !valid {// User is not validw.WriteHeader(http.StatusNotFound)return@@ -33,14 +28,14 @@ func ActorHandler(w http.ResponseWriter, r *http.Request) {// If this request is for an actor's inbox then pass// the request to the inbox controller.if len(pathComponents) == 5 && pathComponents[4] == "inbox" {- InboxHandler(w, r)+ c.InboxHandler(w, r)return} else if len(pathComponents) == 5 && pathComponents[4] == "outbox" {- OutboxHandler(w, r)+ c.OutboxHandler(w, r)return} else if len(pathComponents) == 5 && pathComponents[4] == "followers" {// followers list- FollowersHandler(w, r)+ c.FollowersHandler(w, r)return} else if len(pathComponents) == 5 && pathComponents[4] == "following" {// following list (none)@@ -48,11 +43,11 @@ func ActorHandler(w http.ResponseWriter, r *http.Request) {return}- actorIRI := apmodels.MakeLocalIRIForAccount(accountName)- publicKey := crypto.GetPublicKey(actorIRI)- person := apmodels.MakeServiceForAccount(accountName)+ actorIRI := c.builder.MakeLocalIRIForAccount(accountName)+ publicKey := c.signer.GetPublicKey(actorIRI)+ person := c.builder.MakeServiceForAccount(accountName)- if err := requests.WriteStreamResponse(person, w, publicKey); err != nil {+ if err := requests.WriteStreamResponse(person, w, publicKey, c.signer); err != nil {log.Errorln("unable to write stream response for actor handler", err)w.WriteHeader(http.StatusInternalServerError)returndiff --git a/services/activitypub/controllers/controllers.go b/services/activitypub/controllers/controllers.gonew file mode 100644index 0000000000..cf82ba9cf0--- /dev/null+++ b/services/activitypub/controllers/controllers.go@@ -0,0 +1,55 @@+// Package controllers hosts the HTTP request handlers for the+// ActivityPub federation surface: actor, inbox, outbox, followers,+// nodeinfo, webfinger and host-meta endpoints. Construct *Controllers+// in main.go (via activitypub.New) with the back-end services and+// register the methods on the router.+package controllers++import (+ "github.com/owncast/owncast/persistence/configrepository"+ "github.com/owncast/owncast/services/activitypub/apmodels"+ "github.com/owncast/owncast/services/activitypub/crypto"+ "github.com/owncast/owncast/services/activitypub/inbox"+ "github.com/owncast/owncast/services/activitypub/outbox"+ "github.com/owncast/owncast/services/activitypub/persistence"+ "github.com/owncast/owncast/services/activitypub/persistence/followersrepository"+)++// Controllers is the dependency-bearing HTTP handler set for+// ActivityPub. Construct with New(Deps); register methods on the+// router. Pure helpers (createPageURL, writeResponse) and stateless+// handlers (ActorHandler, WebfingerHandler, HostMetaController) remain+// package-level free functions.+type Controllers struct {+ persistence *persistence.Service+ outbox *outbox.Service+ inbox *inbox.Service+ followers followersrepository.FollowersRepository+ configRepository configrepository.ConfigRepository+ builder *apmodels.Builder+ signer *crypto.Signer+}++// Deps lists every service the *Controllers consume.+type Deps struct {+ Persistence *persistence.Service+ Outbox *outbox.Service+ Inbox *inbox.Service+ Followers followersrepository.FollowersRepository+ ConfigRepository configrepository.ConfigRepository+ Builder *apmodels.Builder+ Signer *crypto.Signer+}++// New constructs the controllers set with explicit dependencies.+func New(deps Deps) *Controllers {+ return &Controllers{+ persistence: deps.Persistence,+ outbox: deps.Outbox,+ inbox: deps.Inbox,+ followers: deps.Followers,+ configRepository: deps.ConfigRepository,+ builder: deps.Builder,+ signer: deps.Signer,+ }+}diff --git a/activitypub/controllers/followers.go b/services/activitypub/controllers/followers.gosimilarity index 71%rename from activitypub/controllers/followers.gorename to services/activitypub/controllers/followers.goindex 6b97bd2571..bc9e6d5e1e 100644--- a/activitypub/controllers/followers.go+++ b/services/activitypub/controllers/followers.go@@ -7,15 +7,12 @@ import ("strconv""strings"+ "github.com/go-fed/activity/streams"+ "github.com/go-fed/activity/streams/vocab""github.com/pkg/errors"log "github.com/sirupsen/logrus"- "github.com/go-fed/activity/streams"- "github.com/go-fed/activity/streams/vocab"- "github.com/owncast/owncast/activitypub/apmodels"- "github.com/owncast/owncast/activitypub/crypto"- "github.com/owncast/owncast/activitypub/persistence/followersrepository"- "github.com/owncast/owncast/activitypub/requests"+ "github.com/owncast/owncast/services/activitypub/requests")const (@@ -23,7 +20,7 @@ const ()// FollowersHandler will return the list of remote followers on the Fediverse.-func FollowersHandler(w http.ResponseWriter, r *http.Request) {+func (c *Controllers) FollowersHandler(w http.ResponseWriter, r *http.Request) {if r.Method != http.MethodGet {w.WriteHeader(http.StatusMethodNotAllowed)return@@ -32,9 +29,9 @@ func FollowersHandler(w http.ResponseWriter, r *http.Request) {var response interface{}var err errorif r.URL.Query().Get("page") != "" {- response, err = getFollowersPage(r.URL.Query().Get("page"), r)+ response, err = c.getFollowersPage(r.URL.Query().Get("page"), r)} else {- response, err = getInitialFollowersRequest(r)+ response, err = c.getInitialFollowersRequest(r)}if response == nil {@@ -50,20 +47,19 @@ func FollowersHandler(w http.ResponseWriter, r *http.Request) {pathComponents := strings.Split(r.URL.Path, "/")accountName := pathComponents[3]- actorIRI := apmodels.MakeLocalIRIForAccount(accountName)- publicKey := crypto.GetPublicKey(actorIRI)+ actorIRI := c.builder.MakeLocalIRIForAccount(accountName)+ publicKey := c.signer.GetPublicKey(actorIRI)- if err := requests.WriteStreamResponse(response.(vocab.Type), w, publicKey); err != nil {+ if err := requests.WriteStreamResponse(response.(vocab.Type), w, publicKey, c.signer); err != nil {log.Errorln("unable to write stream response for followers handler", err)}}-func getInitialFollowersRequest(r *http.Request) (vocab.ActivityStreamsOrderedCollection, error) {- followersRepo := followersrepository.Get()- followerCount, _ := followersRepo.GetCount()+func (c *Controllers) getInitialFollowersRequest(r *http.Request) (vocab.ActivityStreamsOrderedCollection, error) {+ followerCount, _ := c.followers.GetCount()collection := streams.NewActivityStreamsOrderedCollection()idProperty := streams.NewJSONLDIdProperty()- id, err := createPageURL(r, nil)+ id, err := c.createPageURL(r, nil)if err != nil {return nil, errors.Wrap(err, "unable to create followers page property")}@@ -76,7 +72,7 @@ func getInitialFollowersRequest(r *http.Request) (vocab.ActivityStreamsOrderedCofirst := streams.NewActivityStreamsFirstProperty()page := "1"- firstIRI, err := createPageURL(r, &page)+ firstIRI, err := c.createPageURL(r, &page)if err != nil {return nil, errors.Wrap(err, "unable to create first page property")}@@ -87,26 +83,25 @@ func getInitialFollowersRequest(r *http.Request) (vocab.ActivityStreamsOrderedCoreturn collection, nil}-func getFollowersPage(page string, r *http.Request) (vocab.ActivityStreamsOrderedCollectionPage, error) {+func (c *Controllers) getFollowersPage(page string, r *http.Request) (vocab.ActivityStreamsOrderedCollectionPage, error) {pageInt, err := strconv.Atoi(page)if err != nil {return nil, errors.Wrap(err, "unable to parse page number")}- followersRepo := followersrepository.Get()- followerCount, err := followersRepo.GetCount()+ followerCount, err := c.followers.GetCount()if err != nil {return nil, errors.Wrap(err, "unable to get follower count")}- followers, _, err := followersRepo.GetFollowers(followersPageSize, (pageInt-1)*followersPageSize)+ followers, _, err := c.followers.GetFollowers(followersPageSize, (pageInt-1)*followersPageSize)if err != nil {return nil, errors.Wrap(err, "unable to get federation followers")}collectionPage := streams.NewActivityStreamsOrderedCollectionPage()idProperty := streams.NewJSONLDIdProperty()- id, err := createPageURL(r, &page)+ id, err := c.createPageURL(r, &page)if err != nil {return nil, errors.Wrap(err, "unable to create followers page ID")}@@ -122,7 +117,7 @@ func getFollowersPage(page string, r *http.Request) (vocab.ActivityStreamsOrderecollectionPage.SetActivityStreamsOrderedItems(orderedItems)partOf := streams.NewActivityStreamsPartOfProperty()- partOfIRI, err := createPageURL(r, nil)+ partOfIRI, err := c.createPageURL(r, nil)if err != nil {return nil, errors.Wrap(err, "unable to create partOf property for followers page")}@@ -133,7 +128,7 @@ func getFollowersPage(page string, r *http.Request) (vocab.ActivityStreamsOrdereif pageInt*followersPageSize < int(followerCount) {next := streams.NewActivityStreamsNextProperty()nextPage := fmt.Sprintf("%d", pageInt+1)- nextIRI, err := createPageURL(r, &nextPage)+ nextIRI, err := c.createPageURL(r, &nextPage)if err != nil {return nil, errors.Wrap(err, "unable to create next page property")}@@ -145,8 +140,8 @@ func getFollowersPage(page string, r *http.Request) (vocab.ActivityStreamsOrderereturn collectionPage, nil}-func createPageURL(r *http.Request, page *string) (*url.URL, error) {- pageURL, err := apmodels.GetCanonicalServerURL()+func (c *Controllers) createPageURL(r *http.Request, page *string) (*url.URL, error) {+ pageURL, err := c.builder.GetCanonicalServerURL()if err != nil {return nil, errors.Wrap(err, "unable to parse server URL")}diff --git a/activitypub/controllers/inbox.go b/services/activitypub/controllers/inbox.gosimilarity index 66%rename from activitypub/controllers/inbox.gorename to services/activitypub/controllers/inbox.goindex 5d85fea79a..44e1ecb2d4 100644--- a/activitypub/controllers/inbox.go+++ b/services/activitypub/controllers/inbox.go@@ -5,26 +5,22 @@ import ("net/http""strings"- "github.com/owncast/owncast/activitypub/apmodels"- "github.com/owncast/owncast/activitypub/inbox"- "github.com/owncast/owncast/persistence/configrepository"-log "github.com/sirupsen/logrus"++ "github.com/owncast/owncast/services/activitypub/apmodels")// InboxHandler handles inbound federated requests.-func InboxHandler(w http.ResponseWriter, r *http.Request) {+func (c *Controllers) InboxHandler(w http.ResponseWriter, r *http.Request) {if r.Method == http.MethodPost {- acceptInboxRequest(w, r)+ c.acceptInboxRequest(w, r)} else {w.WriteHeader(http.StatusMethodNotAllowed)}}-func acceptInboxRequest(w http.ResponseWriter, r *http.Request) {- configRepository := configrepository.Get()-- if !configRepository.GetFederationEnabled() {+func (c *Controllers) acceptInboxRequest(w http.ResponseWriter, r *http.Request) {+ if !c.configRepository.GetFederationEnabled() {w.WriteHeader(http.StatusMethodNotAllowed)return}@@ -41,7 +37,7 @@ func acceptInboxRequest(w http.ResponseWriter, r *http.Request) {// The account this request is for must match the account name we have set// for federation.- if forLocalAccount != configRepository.GetFederationUsername() {+ if forLocalAccount != c.configRepository.GetFederationUsername() {w.WriteHeader(http.StatusNotFound)return}@@ -53,6 +49,6 @@ func acceptInboxRequest(w http.ResponseWriter, r *http.Request) {}inboxRequest := apmodels.InboxRequest{Request: r, ForLocalAccount: forLocalAccount, Body: data}- inbox.AddToQueue(inboxRequest)+ c.inbox.AddToQueue(inboxRequest)w.WriteHeader(http.StatusAccepted)}diff --git a/activitypub/controllers/nodeinfo.go b/services/activitypub/controllers/nodeinfo.gosimilarity index 73%rename from activitypub/controllers/nodeinfo.gorename to services/activitypub/controllers/nodeinfo.goindex 390024a0fd..a7fc9e1560 100644--- a/activitypub/controllers/nodeinfo.go+++ b/services/activitypub/controllers/nodeinfo.go@@ -5,13 +5,10 @@ import ("net/http""net/url"- "github.com/owncast/owncast/activitypub/apmodels"- "github.com/owncast/owncast/activitypub/crypto"- "github.com/owncast/owncast/activitypub/persistence"- "github.com/owncast/owncast/activitypub/requests"- "github.com/owncast/owncast/config"- "github.com/owncast/owncast/persistence/configrepository"log "github.com/sirupsen/logrus"++ "github.com/owncast/owncast/config"+ "github.com/owncast/owncast/services/activitypub/requests")const (@@ -22,7 +19,7 @@ const ()// NodeInfoController returns the V1 node info response.-func NodeInfoController(w http.ResponseWriter, r *http.Request) {+func (c *Controllers) NodeInfoController(w http.ResponseWriter, r *http.Request) {type links struct {Rel string `json:"rel"`Href string `json:"href"`@@ -32,14 +29,12 @@ func NodeInfoController(w http.ResponseWriter, r *http.Request) {Links []links `json:"links"`}- configRepository := configrepository.Get()-- if !configRepository.GetFederationEnabled() {+ if !c.configRepository.GetFederationEnabled() {w.WriteHeader(http.StatusMethodNotAllowed)return}- v2, err := apmodels.GetCanonicalServerURL()+ v2, err := c.builder.GetCanonicalServerURL()if err != nil {w.WriteHeader(http.StatusInternalServerError)return@@ -55,13 +50,13 @@ func NodeInfoController(w http.ResponseWriter, r *http.Request) {},},}- if err := writeResponse(res, w); err != nil {+ if err := c.writeResponse(res, w); err != nil {log.Errorln(err)}}// NodeInfoV2Controller returns the V2 node info response.-func NodeInfoV2Controller(w http.ResponseWriter, r *http.Request) {+func (c *Controllers) NodeInfoV2Controller(w http.ResponseWriter, r *http.Request) {type metadata struct {ChatEnabled bool `json:"chat_enabled"`}@@ -92,14 +87,12 @@ func NodeInfoV2Controller(w http.ResponseWriter, r *http.Request) {Metadata metadata `json:"metadata"`}- configRepository := configrepository.Get()-- if !configRepository.GetFederationEnabled() {+ if !c.configRepository.GetFederationEnabled() {w.WriteHeader(http.StatusMethodNotAllowed)return}- localPostCount, _ := persistence.GetLocalPostCount()+ localPostCount, _ := c.persistence.GetLocalPostCount()res := response{Version: "2.0",@@ -122,17 +115,17 @@ func NodeInfoV2Controller(w http.ResponseWriter, r *http.Request) {OpenRegistrations: false,Protocols: []string{protocolActivityPub},Metadata: metadata{- ChatEnabled: !configRepository.GetChatDisabled(),+ ChatEnabled: !c.configRepository.GetChatDisabled(),},}- if err := writeResponse(res, w); err != nil {+ if err := c.writeResponse(res, w); err != nil {log.Errorln(err)}}// XNodeInfo2Controller returns the x-nodeinfo2.-func XNodeInfo2Controller(w http.ResponseWriter, r *http.Request) {+func (c *Controllers) XNodeInfo2Controller(w http.ResponseWriter, r *http.Request) {type Organization struct {Name string `json:"name"`Contact string `json:"contact"`@@ -168,24 +161,22 @@ func XNodeInfo2Controller(w http.ResponseWriter, r *http.Request) {OpenRegistrations bool `json:"openRegistrations"`}- configRepository := configrepository.Get()-- if !configRepository.GetFederationEnabled() {+ if !c.configRepository.GetFederationEnabled() {w.WriteHeader(http.StatusMethodNotAllowed)return}- serverURL := configRepository.GetServerURL()+ serverURL := c.configRepository.GetServerURL()if serverURL == "" {w.WriteHeader(http.StatusNotFound)return}- localPostCount, _ := persistence.GetLocalPostCount()+ localPostCount, _ := c.persistence.GetLocalPostCount()res := &response{Organization: Organization{- Name: configRepository.GetServerName(),+ Name: c.configRepository.GetServerName(),Contact: serverURL,},Server: Server{@@ -213,13 +204,13 @@ func XNodeInfo2Controller(w http.ResponseWriter, r *http.Request) {},}- if err := writeResponse(res, w); err != nil {+ if err := c.writeResponse(res, w); err != nil {log.Errorln(err)}}// InstanceV1Controller returns the v1 instance details.-func InstanceV1Controller(w http.ResponseWriter, r *http.Request) {+func (c *Controllers) InstanceV1Controller(w http.ResponseWriter, r *http.Request) {type Stats struct {UserCount int `json:"user_count"`StatusCount int `json:"status_count"`@@ -239,14 +230,12 @@ func InstanceV1Controller(w http.ResponseWriter, r *http.Request) {InvitesEnabled bool `json:"invites_enabled"`}- configRepository := configrepository.Get()-- if !configRepository.GetFederationEnabled() {+ if !c.configRepository.GetFederationEnabled() {w.WriteHeader(http.StatusMethodNotAllowed)return}- serverURL := configRepository.GetServerURL()+ serverURL := c.configRepository.GetServerURL()if serverURL == "" {w.WriteHeader(http.StatusNotFound)return@@ -259,13 +248,13 @@ func InstanceV1Controller(w http.ResponseWriter, r *http.Request) {}thumbnail.Path = "/logo/external"- localPostCount, _ := persistence.GetLocalPostCount()+ localPostCount, _ := c.persistence.GetLocalPostCount()res := response{URI: serverURL,- Title: configRepository.GetServerName(),- ShortDescription: configRepository.GetServerSummary(),- Description: configRepository.GetServerSummary(),+ Title: c.configRepository.GetServerName(),+ ShortDescription: c.configRepository.GetServerSummary(),+ Description: c.configRepository.GetServerSummary(),Version: config.GetReleaseString(),Stats: Stats{UserCount: 1,@@ -278,32 +267,28 @@ func InstanceV1Controller(w http.ResponseWriter, r *http.Request) {InvitesEnabled: false,}- if err := writeResponse(res, w); err != nil {+ if err := c.writeResponse(res, w); err != nil {log.Errorln(err)}}-func writeResponse(payload interface{}, w http.ResponseWriter) error {- configRepository := configrepository.Get()+func (c *Controllers) writeResponse(payload interface{}, w http.ResponseWriter) error {+ accountName := c.configRepository.GetDefaultFederationUsername()+ actorIRI := c.builder.MakeLocalIRIForAccount(accountName)+ publicKey := c.signer.GetPublicKey(actorIRI)- accountName := configRepository.GetDefaultFederationUsername()- actorIRI := apmodels.MakeLocalIRIForAccount(accountName)- publicKey := crypto.GetPublicKey(actorIRI)-- return requests.WritePayloadResponse(payload, w, publicKey)+ return requests.WritePayloadResponse(payload, w, publicKey, c.signer)}// HostMetaController points to webfinger.-func HostMetaController(w http.ResponseWriter, r *http.Request) {- configRepository := configrepository.Get()-- if !configRepository.GetFederationEnabled() {+func (c *Controllers) HostMetaController(w http.ResponseWriter, r *http.Request) {+ if !c.configRepository.GetFederationEnabled() {w.WriteHeader(http.StatusMethodNotAllowed)log.Debugln("host meta request rejected! Federation is not enabled")return}- serverURL, err := apmodels.GetCanonicalServerURL()+ serverURL, err := c.builder.GetCanonicalServerURL()if err != nil {w.WriteHeader(http.StatusNotFound)returndiff --git a/services/activitypub/controllers/object.go b/services/activitypub/controllers/object.gonew file mode 100644index 0000000000..5d8f6dbc73--- /dev/null+++ b/services/activitypub/controllers/object.go@@ -0,0 +1,53 @@+package controllers++import (+ "net/http"+ "strings"++ log "github.com/sirupsen/logrus"++ "github.com/owncast/owncast/services/activitypub/requests"+)++// ObjectHandler handles requests for a single federated ActivityPub object.+func (c *Controllers) ObjectHandler(w http.ResponseWriter, r *http.Request) {+ if !c.configRepository.GetFederationEnabled() {+ w.WriteHeader(http.StatusMethodNotAllowed)+ return+ }++ // If private federation mode is enabled do not allow access to objects.+ if c.configRepository.GetFederationIsPrivate() {+ w.WriteHeader(http.StatusNotFound)+ return+ }++ serverURL, err := c.builder.GetCanonicalServerURL()+ if err != nil {+ w.WriteHeader(http.StatusNotFound)+ return+ }+ serverURL.Path = r.URL.Path+ iri := serverURL.String()+ object, _, _, err := c.persistence.GetObjectByIRI(iri)+ if err != nil {+ legacyIRI := strings.Join([]string{strings.TrimSuffix(c.configRepository.GetServerURL(), "/"), r.URL.Path}, "")+ if legacyIRI == iri {+ w.WriteHeader(http.StatusNotFound)+ return+ }+ object, _, _, err = c.persistence.GetObjectByIRI(legacyIRI)+ if err != nil {+ w.WriteHeader(http.StatusNotFound)+ return+ }+ }++ accountName := c.configRepository.GetDefaultFederationUsername()+ actorIRI := c.builder.MakeLocalIRIForAccount(accountName)+ publicKey := c.signer.GetPublicKey(actorIRI)++ if err := requests.WriteResponse([]byte(object), w, publicKey, c.signer); err != nil {+ log.Errorln(err)+ }+}diff --git a/activitypub/controllers/outbox.go b/services/activitypub/controllers/outbox.gosimilarity index 73%rename from activitypub/controllers/outbox.gorename to services/activitypub/controllers/outbox.goindex b36270cdf0..3bcc930aa0 100644--- a/activitypub/controllers/outbox.go+++ b/services/activitypub/controllers/outbox.go@@ -8,12 +8,10 @@ import ("github.com/go-fed/activity/streams""github.com/go-fed/activity/streams/vocab"- "github.com/owncast/owncast/activitypub/apmodels"- "github.com/owncast/owncast/activitypub/crypto"- "github.com/owncast/owncast/activitypub/persistence"- "github.com/owncast/owncast/activitypub/requests""github.com/pkg/errors"log "github.com/sirupsen/logrus"++ "github.com/owncast/owncast/services/activitypub/requests")const (@@ -21,7 +19,7 @@ const ()// OutboxHandler will handle requests for the local ActivityPub outbox.-func OutboxHandler(w http.ResponseWriter, r *http.Request) {+func (c *Controllers) OutboxHandler(w http.ResponseWriter, r *http.Request) {if r.Method != http.MethodGet {w.WriteHeader(http.StatusMethodNotAllowed)return@@ -30,9 +28,9 @@ func OutboxHandler(w http.ResponseWriter, r *http.Request) {var response interface{}var err errorif r.URL.Query().Get("page") != "" {- response, err = getOutboxPage(r.URL.Query().Get("page"), r)+ response, err = c.getOutboxPage(r.URL.Query().Get("page"), r)} else {- response, err = getInitialOutboxHandler(r)+ response, err = c.getInitialOutboxHandler(r)}if response == nil {@@ -48,17 +46,17 @@ func OutboxHandler(w http.ResponseWriter, r *http.Request) {pathComponents := strings.Split(r.URL.Path, "/")accountName := pathComponents[3]- actorIRI := apmodels.MakeLocalIRIForAccount(accountName)- publicKey := crypto.GetPublicKey(actorIRI)+ actorIRI := c.builder.MakeLocalIRIForAccount(accountName)+ publicKey := c.signer.GetPublicKey(actorIRI)- if err := requests.WriteStreamResponse(response.(vocab.Type), w, publicKey); err != nil {+ if err := requests.WriteStreamResponse(response.(vocab.Type), w, publicKey, c.signer); err != nil {log.Errorln("unable to write stream response for outbox handler", err)}}// ActorObjectHandler will handle the request for a single ActivityPub object.-func ActorObjectHandler(w http.ResponseWriter, r *http.Request) {- object, _, _, err := persistence.GetObjectByIRI(r.URL.Path)+func (c *Controllers) ActorObjectHandler(w http.ResponseWriter, r *http.Request) {+ object, _, _, err := c.persistence.GetObjectByIRI(r.URL.Path)if err != nil {w.WriteHeader(http.StatusNotFound)return@@ -71,18 +69,18 @@ func ActorObjectHandler(w http.ResponseWriter, r *http.Request) {}}-func getInitialOutboxHandler(r *http.Request) (vocab.ActivityStreamsOrderedCollection, error) {+func (c *Controllers) getInitialOutboxHandler(r *http.Request) (vocab.ActivityStreamsOrderedCollection, error) {collection := streams.NewActivityStreamsOrderedCollection()idProperty := streams.NewJSONLDIdProperty()- id, err := createPageURL(r, nil)+ id, err := c.createPageURL(r, nil)if err != nil {return nil, errors.Wrap(err, "unable to create followers page property")}idProperty.SetIRI(id)collection.SetJSONLDId(idProperty)- totalPosts, err := persistence.GetOutboxPostCount()+ totalPosts, err := c.persistence.GetOutboxPostCount()if err != nil {return nil, errors.Wrap(err, "unable to get outbox post count")}@@ -92,7 +90,7 @@ func getInitialOutboxHandler(r *http.Request) (vocab.ActivityStreamsOrderedCollefirst := streams.NewActivityStreamsFirstProperty()page := "1"- firstIRI, err := createPageURL(r, &page)+ firstIRI, err := c.createPageURL(r, &page)if err != nil {return nil, errors.Wrap(err, "unable to create first page property")}@@ -103,20 +101,20 @@ func getInitialOutboxHandler(r *http.Request) (vocab.ActivityStreamsOrderedCollereturn collection, nil}-func getOutboxPage(page string, r *http.Request) (vocab.ActivityStreamsOrderedCollectionPage, error) {+func (c *Controllers) getOutboxPage(page string, r *http.Request) (vocab.ActivityStreamsOrderedCollectionPage, error) {pageInt, err := strconv.Atoi(page)if err != nil {return nil, errors.Wrap(err, "unable to parse page number")}- postCount, err := persistence.GetOutboxPostCount()+ postCount, err := c.persistence.GetOutboxPostCount()if err != nil {return nil, errors.Wrap(err, "unable to get outbox post count")}collectionPage := streams.NewActivityStreamsOrderedCollectionPage()idProperty := streams.NewJSONLDIdProperty()- id, err := createPageURL(r, &page)+ id, err := c.createPageURL(r, &page)if err != nil {return nil, errors.Wrap(err, "unable to create followers page ID")}@@ -125,7 +123,7 @@ func getOutboxPage(page string, r *http.Request) (vocab.ActivityStreamsOrderedCoorderedItems := streams.NewActivityStreamsOrderedItemsProperty()- outboxItems, err := persistence.GetOutbox(outboxPageSize, (pageInt-1)*outboxPageSize)+ outboxItems, err := c.persistence.GetOutbox(outboxPageSize, (pageInt-1)*outboxPageSize)if err != nil {return nil, errors.Wrap(err, "unable to get federation followers")}@@ -133,7 +131,7 @@ func getOutboxPage(page string, r *http.Request) (vocab.ActivityStreamsOrderedCocollectionPage.SetActivityStreamsOrderedItems(orderedItems)partOf := streams.NewActivityStreamsPartOfProperty()- partOfIRI, err := createPageURL(r, nil)+ partOfIRI, err := c.createPageURL(r, nil)if err != nil {return nil, errors.Wrap(err, "unable to create partOf property for outbox page")}@@ -144,7 +142,7 @@ func getOutboxPage(page string, r *http.Request) (vocab.ActivityStreamsOrderedCoif pageInt*followersPageSize < int(postCount) {next := streams.NewActivityStreamsNextProperty()nextPage := fmt.Sprintf("%d", pageInt+1)- nextIRI, err := createPageURL(r, &nextPage)+ nextIRI, err := c.createPageURL(r, &nextPage)if err != nil {return nil, errors.Wrap(err, "unable to create next page property")}diff --git a/activitypub/controllers/webfinger.go b/services/activitypub/controllers/webfinger.gosimilarity index 77%rename from activitypub/controllers/webfinger.gorename to services/activitypub/controllers/webfinger.goindex 51e3efcdbc..820d2d20f3 100644--- a/activitypub/controllers/webfinger.go+++ b/services/activitypub/controllers/webfinger.go@@ -5,26 +5,23 @@ import ("net/http""strings"- "github.com/owncast/owncast/activitypub/apmodels"- "github.com/owncast/owncast/persistence/configrepository"- "github.com/owncast/owncast/utils"log "github.com/sirupsen/logrus"++ "github.com/owncast/owncast/utils")// WebfingerHandler will handle webfinger lookup requests.-func WebfingerHandler(w http.ResponseWriter, r *http.Request) {- configRepository := configrepository.Get()-- if !configRepository.GetFederationEnabled() {+func (c *Controllers) WebfingerHandler(w http.ResponseWriter, r *http.Request) {+ if !c.configRepository.GetFederationEnabled() {w.WriteHeader(http.StatusMethodNotAllowed)log.Debugln("webfinger request rejected! Federation is not enabled")return}- instanceURL, err := apmodels.GetCanonicalServerURL()+ instanceURL, err := c.builder.GetCanonicalServerURL()if err != nil {w.WriteHeader(http.StatusNotFound)- log.Warnln("webfinger request rejected! Federation is enabled but server URL host cannot be canonicalized: " + configRepository.GetServerURL())+ log.Warnln("webfinger request rejected! Federation is enabled but server URL host cannot be canonicalized: " + c.configRepository.GetServerURL())return}instanceHostString := instanceURL.Host@@ -53,7 +50,7 @@ func WebfingerHandler(w http.ResponseWriter, r *http.Request) {return}- if _, valid := configRepository.GetFederatedInboxMap()[user]; !valid {+ if _, valid := c.configRepository.GetFederatedInboxMap()[user]; !valid {w.WriteHeader(http.StatusNotFound)log.Debugln("webfinger request rejected! Invalid user: " + user)return@@ -67,7 +64,7 @@ func WebfingerHandler(w http.ResponseWriter, r *http.Request) {return}- webfingerResponse := apmodels.MakeWebfingerResponse(user, user, host)+ webfingerResponse := c.builder.MakeWebfingerResponse(user, user, host)w.Header().Set("Content-Type", "application/jrd+json")diff --git a/activitypub/controllers/webfinger_test.go b/services/activitypub/controllers/webfinger_test.gosimilarity index 76%rename from activitypub/controllers/webfinger_test.gorename to services/activitypub/controllers/webfinger_test.goindex 86beb8b2fa..cdf6b5dbbb 100644--- a/activitypub/controllers/webfinger_test.go+++ b/services/activitypub/controllers/webfinger_test.go@@ -8,8 +8,19 @@ import ("os""testing"- "github.com/owncast/owncast/core/data""github.com/owncast/owncast/persistence/configrepository"+ "github.com/owncast/owncast/services/activitypub/apmodels"+ apcrypto "github.com/owncast/owncast/services/activitypub/crypto"+ "github.com/owncast/owncast/services/datastore"+)++// testControllers is the *Controllers used by tests in this package.+// Webfinger is stateless apart from the builder + configRepository, so+// only those deps are populated; if other handler tests land here that+// hit additional deps, expand the construction below.+var (+ testControllers = &Controllers{}+ testDatastore *datastore.Datastore)func TestMain(m *testing.M) {@@ -19,9 +30,20 @@ func TestMain(m *testing.M) {}defer os.Remove(dbFile.Name())- if err := data.SetupPersistence(dbFile.Name()); err != nil {+ ds, err := datastore.SetupPersistence(dbFile.Name(), os.TempDir())+ if err != nil {panic(err)}+ testDatastore = ds++ cfg := configrepository.New(testDatastore)+ signer := apcrypto.New(apcrypto.Deps{ConfigRepository: cfg})+ builder := apmodels.New(apmodels.Deps{ConfigRepository: cfg, Signer: signer})+ testControllers = &Controllers{+ configRepository: cfg,+ builder: builder,+ signer: signer,+ }os.Exit(m.Run())}@@ -59,7 +81,7 @@ func TestWebfingerHandlerWithIDNHost(t *testing.T) {for _, tt := range tests {t.Run(tt.name, func(t *testing.T) {- configRepository := configrepository.Get()+ configRepository := configrepository.New(testDatastore)configRepository.SetFederationEnabled(true)configRepository.SetFederationUsername("retrots3m")configRepository.SetServerURL(tt.serverURL)@@ -67,7 +89,7 @@ func TestWebfingerHandlerWithIDNHost(t *testing.T) {req := httptest.NewRequest(http.MethodGet, "/.well-known/webfinger?resource="+url.QueryEscape(tt.resource), nil)w := httptest.NewRecorder()- WebfingerHandler(w, req)+ testControllers.WebfingerHandler(w, req)if w.Code != http.StatusOK {t.Fatalf("status = %d, want %d", w.Code, http.StatusOK)diff --git a/activitypub/crypto/keys.go b/services/activitypub/crypto/keys.gosimilarity index 83%rename from activitypub/crypto/keys.gorename to services/activitypub/crypto/keys.goindex 16161f98da..fcc24a1208 100644--- a/activitypub/crypto/keys.go+++ b/services/activitypub/crypto/keys.go@@ -8,15 +8,12 @@ import ("errors""net/url"- "github.com/owncast/owncast/persistence/configrepository"log "github.com/sirupsen/logrus")// GetPublicKey will return the public key for the provided actor.-func GetPublicKey(actorIRI *url.URL) PublicKey {- configRepository := configrepository.Get()-- key := configRepository.GetPublicKey()+func (s *Signer) GetPublicKey(actorIRI *url.URL) PublicKey {+ key := s.configRepository.GetPublicKey()idURL, err := url.Parse(actorIRI.String() + "#main-key")if err != nil {log.Errorln("unable to parse actor iri string", idURL, err)@@ -30,10 +27,8 @@ func GetPublicKey(actorIRI *url.URL) PublicKey {}// GetPrivateKey will return the internal server private key.-func GetPrivateKey() *rsa.PrivateKey {- configRepository := configrepository.Get()-- key := configRepository.GetPrivateKey()+func (s *Signer) GetPrivateKey() *rsa.PrivateKey {+ key := s.configRepository.GetPrivateKey()block, _ := pem.Decode([]byte(key))if block == nil {@@ -51,6 +46,7 @@ func GetPrivateKey() *rsa.PrivateKey {}// GenerateKeys will generate the private/public key pair needed for federation.+// This is a pure utility; no Signer state is required.func GenerateKeys() ([]byte, []byte, error) {// generate keyprivatekey, err := rsa.GenerateKey(rand.Reader, 2048)diff --git a/activitypub/crypto/publicKey.go b/services/activitypub/crypto/publicKey.gosimilarity index 100%rename from activitypub/crypto/publicKey.gorename to services/activitypub/crypto/publicKey.godiff --git a/activitypub/crypto/sign.go b/services/activitypub/crypto/sign.gosimilarity index 84%rename from activitypub/crypto/sign.gorename to services/activitypub/crypto/sign.goindex 48550976e5..65920a2a93 100644--- a/activitypub/crypto/sign.go+++ b/services/activitypub/crypto/sign.go@@ -9,13 +9,14 @@ import ("time""github.com/go-fed/httpsig"- "github.com/owncast/owncast/config"log "github.com/sirupsen/logrus"++ "github.com/owncast/owncast/config")// SignResponse will sign a response using the provided response body and public key.-func SignResponse(w http.ResponseWriter, body []byte, publicKey PublicKey) error {- privateKey := GetPrivateKey()+func (s *Signer) SignResponse(w http.ResponseWriter, body []byte, publicKey PublicKey) error {+ privateKey := s.GetPrivateKey()return signResponse(privateKey, *publicKey.ID, body, w)}@@ -40,9 +41,9 @@ func signResponse(privateKey crypto.PrivateKey, pubKeyID url.URL, body []byte, w}// SignRequest will sign an ounbound request given the provided body.-func SignRequest(req *http.Request, body []byte, actorIRI *url.URL) error {- publicKey := GetPublicKey(actorIRI)- privateKey := GetPrivateKey()+func (s *Signer) SignRequest(req *http.Request, body []byte, actorIRI *url.URL) error {+ publicKey := s.GetPublicKey(actorIRI)+ privateKey := s.GetPrivateKey()return signRequest(privateKey, publicKey.ID.String(), body, req)}@@ -72,7 +73,7 @@ func signRequest(privateKey crypto.PrivateKey, pubKeyID string, body []byte, r *}// CreateSignedRequest will create a signed POST request of a payload to the provided destination.-func CreateSignedRequest(payload []byte, url *url.URL, fromActorIRI *url.URL) (*http.Request, error) {+func (s *Signer) CreateSignedRequest(payload []byte, url *url.URL, fromActorIRI *url.URL) (*http.Request, error) {log.Debugln("Sending", string(payload), "to", url)req, _ := http.NewRequest("POST", url.String(), bytes.NewBuffer(payload))@@ -81,7 +82,7 @@ func CreateSignedRequest(payload []byte, url *url.URL, fromActorIRI *url.URL) (*req.Header.Set("User-Agent", ua)req.Header.Set("Content-Type", "application/activity+json")- if err := SignRequest(req, payload, fromActorIRI); err != nil {+ if err := s.SignRequest(req, payload, fromActorIRI); err != nil {log.Errorln("error signing request:", err)return nil, err}diff --git a/services/activitypub/crypto/signer.go b/services/activitypub/crypto/signer.gonew file mode 100644index 0000000000..c7eeaad08c--- /dev/null+++ b/services/activitypub/crypto/signer.go@@ -0,0 +1,27 @@+// Package crypto holds the ActivityPub signing/verification surface:+// keypair lookup, request signing, response signing, and signed-request+// construction. Construct a *Signer in main.go with New(Deps) and pass+// it to consumers (apmodels.Builder, apresolvers.Resolver, outbox,+// controllers, etc.) via their own Deps structs.+package crypto++import "github.com/owncast/owncast/persistence/configrepository"++// Signer is the dependency-bearing handle for the crypto helpers.+// It reads the local server's PEM-encoded keypair from the+// configRepository each time keys are needed. Construct with New(Deps).+type Signer struct {+ configRepository configrepository.ConfigRepository+}++// Deps is the explicit dependency contract for Signer.+type Deps struct {+ ConfigRepository configrepository.ConfigRepository+}++// New constructs a Signer with the provided dependencies.+func New(deps Deps) *Signer {+ return &Signer{+ configRepository: deps.ConfigRepository,+ }+}diff --git a/activitypub/events/events.go b/services/activitypub/events/events.gosimilarity index 100%rename from activitypub/events/events.gorename to services/activitypub/events/events.godiff --git a/activitypub/events/fediverseEngagementFollowEvent.go b/services/activitypub/events/fediverseEngagementFollowEvent.gosimilarity index 100%rename from activitypub/events/fediverseEngagementFollowEvent.gorename to services/activitypub/events/fediverseEngagementFollowEvent.godiff --git a/activitypub/inbox/announce.go b/services/activitypub/inbox/announce.gosimilarity index 52%rename from activitypub/inbox/announce.gorename to services/activitypub/inbox/announce.goindex 322c02c37e..0303b38397 100644--- a/activitypub/inbox/announce.go+++ b/services/activitypub/inbox/announce.go@@ -5,13 +5,13 @@ import ("time""github.com/go-fed/activity/streams/vocab"- "github.com/owncast/owncast/activitypub/apmodels"- "github.com/owncast/owncast/activitypub/persistence"- "github.com/owncast/owncast/core/chat/events""github.com/pkg/errors"++ "github.com/owncast/owncast/services/activitypub/apmodels"+ "github.com/owncast/owncast/services/chat/events")-func handleAnnounceRequest(c context.Context, activity vocab.ActivityStreamsAnnounce) error {+func (s *Service) handleAnnounceRequest(c context.Context, activity vocab.ActivityStreamsAnnounce) error {objectIRI, err := apmodels.GetIRIStringFromObjectProperty(activity.GetActivityStreamsObject())if err != nil {return errors.Wrap(err, "announce activity is missing object IRI")@@ -24,25 +24,25 @@ func handleAnnounceRequest(c context.Context, activity vocab.ActivityStreamsAnnoactorReference := activity.GetActivityStreamsActor()- if hasPreviouslyhandled, err := persistence.HasPreviouslyHandledInboundActivity(objectIRI, actorIRI, events.FediverseEngagementRepost); hasPreviouslyhandled || err != nil {+ if hasPreviouslyhandled, err := s.persistence.HasPreviouslyHandledInboundActivity(objectIRI, actorIRI, events.FediverseEngagementRepost); hasPreviouslyhandled || err != nil {return errors.Wrap(err, "inbound activity of share/re-post has already been handled")}// Shares need to match a post we had already sent.- _, isLiveNotification, timestamp, err := persistence.GetObjectByIRI(objectIRI)+ _, isLiveNotification, timestamp, err := s.persistence.GetObjectByIRI(objectIRI)if err != nil {return errors.Wrap(err, "Could not find post locally")}- // Don't allow old activities to be liked+ // Don't allow old activities to be liked.if time.Since(timestamp) > maxAgeForEngagement {return errors.New("Activity is too old to be shared")}- // Save as an accepted activity- if err := persistence.SaveInboundFediverseActivity(objectIRI, actorIRI, events.FediverseEngagementRepost, time.Now()); err != nil {+ // Save as an accepted activity.+ if err := s.persistence.SaveInboundFediverseActivity(objectIRI, actorIRI, events.FediverseEngagementRepost, time.Now()); err != nil {return errors.Wrap(err, "unable to save inbound share/re-post activity")}- return handleEngagementActivity(events.FediverseEngagementRepost, isLiveNotification, actorReference, events.FediverseEngagementRepost)+ return s.handleEngagementActivity(events.FediverseEngagementRepost, isLiveNotification, actorReference, events.FediverseEngagementRepost)}diff --git a/activitypub/inbox/chat.go b/services/activitypub/inbox/chat.gosimilarity index 66%rename from activitypub/inbox/chat.gorename to services/activitypub/inbox/chat.goindex d1cfdaeb3f..4295d1e00c 100644--- a/activitypub/inbox/chat.go+++ b/services/activitypub/inbox/chat.go@@ -5,10 +5,8 @@ import ("github.com/go-fed/activity/streams/vocab""github.com/microcosm-cc/bluemonday"- "github.com/owncast/owncast/activitypub/resolvers"- "github.com/owncast/owncast/core/chat"- "github.com/owncast/owncast/core/chat/events"- "github.com/owncast/owncast/persistence/configrepository"++ "github.com/owncast/owncast/services/chat/events")// sanitizeActorName strips HTML tags from the ActivityPub actor display name.@@ -22,21 +20,19 @@ func sanitizeActorName(displayName, username string) string {return name}-func handleEngagementActivity(eventType events.EventType, isLiveNotification bool, actorReference vocab.ActivityStreamsActorProperty, action string) error {- configRepository := configrepository.Get()-+func (s *Service) handleEngagementActivity(eventType events.EventType, isLiveNotification bool, actorReference vocab.ActivityStreamsActorProperty, action string) error {// Do nothing if displaying engagement actions has been turned off.- if !configRepository.GetFederationShowEngagement() {+ if !s.configRepository.GetFederationShowEngagement() {return nil}// Do nothing if chat is disabled- if configRepository.GetChatDisabled() {+ if s.configRepository.GetChatDisabled() {return nil}// Get actor of the action- actor, err := resolvers.GetResolvedActorFromActorProperty(actorReference)+ actor, err := s.resolver.GetResolvedActorFromActorProperty(actorReference)if err != nil {return fmt.Errorf("unable to resolve actor for engagement activity: %w", err)}@@ -50,11 +46,11 @@ func handleEngagementActivity(eventType events.EventType, isLiveNotification booif isLiveNotification && action == events.FediverseEngagementLike {suffix = "liked that this stream went live."} else if action == events.FediverseEngagementLike {- suffix = fmt.Sprintf("liked a post from %s.", configRepository.GetServerName())+ suffix = fmt.Sprintf("liked a post from %s.", s.configRepository.GetServerName())} else if isLiveNotification && action == events.FediverseEngagementRepost {suffix = "shared this stream with their followers."} else if action == events.FediverseEngagementRepost {- suffix = fmt.Sprintf("shared a post from %s.", configRepository.GetServerName())+ suffix = fmt.Sprintf("shared a post from %s.", s.configRepository.GetServerName())} else if action == events.FediverseEngagementFollow {suffix = "followed this stream."} else {@@ -67,7 +63,7 @@ func handleEngagementActivity(eventType events.EventType, isLiveNotification booimage = &imageStr}- if err := chat.SendFediverseAction(eventType, actor.FullUsername, image, body, actorIRI); err != nil {+ if err := s.chat.SendFediverseAction(eventType, actor.FullUsername, image, body, actorIRI); err != nil {return err}diff --git a/activitypub/inbox/chat_test.go b/services/activitypub/inbox/chat_test.gosimilarity index 100%rename from activitypub/inbox/chat_test.gorename to services/activitypub/inbox/chat_test.godiff --git a/activitypub/inbox/constants.go b/services/activitypub/inbox/constants.gosimilarity index 100%rename from activitypub/inbox/constants.gorename to services/activitypub/inbox/constants.godiff --git a/activitypub/inbox/create.go b/services/activitypub/inbox/create.gosimilarity index 66%rename from activitypub/inbox/create.gorename to services/activitypub/inbox/create.goindex fb887315a1..824579ca99 100644--- a/activitypub/inbox/create.go+++ b/services/activitypub/inbox/create.go@@ -4,11 +4,12 @@ import ("context""github.com/go-fed/activity/streams/vocab"- "github.com/owncast/owncast/activitypub/apmodels""github.com/pkg/errors"++ "github.com/owncast/owncast/services/activitypub/apmodels")-func handleCreateRequest(c context.Context, activity vocab.ActivityStreamsCreate) error {+func (s *Service) handleCreateRequest(c context.Context, activity vocab.ActivityStreamsCreate) error {iri, err := apmodels.GetIRIStringFromJSONLDIdProperty(activity.GetJSONLDId())if err != nil {return errors.Wrap(err, "create activity is missing IRI")diff --git a/activitypub/inbox/follow.go b/services/activitypub/inbox/follow.gosimilarity index 51%rename from activitypub/inbox/follow.gorename to services/activitypub/inbox/follow.goindex 9a8f14870b..a482a4ea20 100644--- a/activitypub/inbox/follow.go+++ b/services/activitypub/inbox/follow.go@@ -6,24 +6,16 @@ import ("time""github.com/go-fed/activity/streams/vocab"- "github.com/owncast/owncast/activitypub/apmodels"- "github.com/owncast/owncast/activitypub/persistence"- "github.com/owncast/owncast/activitypub/persistence/followersrepository"- "github.com/owncast/owncast/activitypub/requests"- "github.com/owncast/owncast/activitypub/resolvers"- "github.com/owncast/owncast/core/chat/events"- "github.com/owncast/owncast/core/webhooks"- "github.com/owncast/owncast/persistence/configrepository""github.com/pkg/errors"-log "github.com/sirupsen/logrus"-)-func handleFollowInboxRequest(c context.Context, activity vocab.ActivityStreamsFollow) error {- configRepository := configrepository.Get()- followersRepo := followersrepository.Get()+ "github.com/owncast/owncast/services/activitypub/apmodels"+ "github.com/owncast/owncast/services/activitypub/requests"+ "github.com/owncast/owncast/services/chat/events"+)- follow, err := resolvers.MakeFollowRequest(c, activity)+func (s *Service) handleFollowInboxRequest(c context.Context, activity vocab.ActivityStreamsFollow) error {+ follow, err := s.resolver.MakeFollowRequest(c, activity)if err != nil {log.Errorln("unable to create follow inbox request", err)return err@@ -33,16 +25,16 @@ func handleFollowInboxRequest(c context.Context, activity vocab.ActivityStreamsFreturn fmt.Errorf("unable to handle request")}- approved := !configRepository.GetFederationIsPrivate()+ approved := !s.configRepository.GetFederationIsPrivate()followRequest := *follow- if err := followersRepo.Add(followRequest, approved); err != nil {+ if err := s.followers.Add(followRequest, approved); err != nil {log.Errorln("unable to save follow request", err)return err}- localAccountName := configRepository.GetDefaultFederationUsername()+ localAccountName := s.configRepository.GetDefaultFederationUsername()objectIRI, err := apmodels.GetIRIStringFromObjectProperty(activity.GetActivityStreamsObject())if err != nil {@@ -57,38 +49,38 @@ func handleFollowInboxRequest(c context.Context, activity vocab.ActivityStreamsFactorReference := activity.GetActivityStreamsActor()if approved {- if err := requests.SendFollowAccept(follow.Inbox, activity, localAccountName); err != nil {+ if err := requests.SendFollowAccept(s.workerpool, follow.Inbox, activity, localAccountName, s.builder, s.signer); err != nil {log.Errorln("unable to send follow accept", err)return err}- go webhooks.SendFediverseEngagementFollowEvent(actorIRI)+ go s.webhooks.SendFediverseEngagementFollowEvent(actorIRI)}// If this request is approved and we have not previously sent an action to// chat due to a previous follow request, then do so.hasPreviouslyhandled := true // Default so we don't send anything if it fails.if approved {- hasPreviouslyhandled, err = persistence.HasPreviouslyHandledInboundActivity(objectIRI, actorIRI, events.FediverseEngagementFollow)+ hasPreviouslyhandled, err = s.persistence.HasPreviouslyHandledInboundActivity(objectIRI, actorIRI, events.FediverseEngagementFollow)if err != nil {log.Errorln("error checking for previously handled follow activity", err)}}// Save this follow action to our activities table.- if err := persistence.SaveInboundFediverseActivity(objectIRI, actorIRI, events.FediverseEngagementFollow, time.Now()); err != nil {+ if err := s.persistence.SaveInboundFediverseActivity(objectIRI, actorIRI, events.FediverseEngagementFollow, time.Now()); err != nil {return errors.Wrap(err, "unable to save inbound share/re-post activity")}// Send action to chat if it has not been previously handled.if !hasPreviouslyhandled {- return handleEngagementActivity(events.FediverseEngagementFollow, false, actorReference, events.FediverseEngagementFollow)+ return s.handleEngagementActivity(events.FediverseEngagementFollow, false, actorReference, events.FediverseEngagementFollow)}return nil}-func handleUnfollowRequest(c context.Context, activity vocab.ActivityStreamsUndo) error {- request := resolvers.MakeUnFollowRequest(c, activity)+func (s *Service) handleUnfollowRequest(c context.Context, activity vocab.ActivityStreamsUndo) error {+ request := s.resolver.MakeUnFollowRequest(c, activity)if request == nil {log.Errorf("unable to handle unfollow request")return errors.New("unable to handle unfollow request")@@ -97,6 +89,5 @@ func handleUnfollowRequest(c context.Context, activity vocab.ActivityStreamsUndounfollowRequest := *requestlog.Traceln("unfollow request:", unfollowRequest)- followersRepo := followersrepository.Get()- return followersRepo.Remove(unfollowRequest)+ return s.followers.Remove(unfollowRequest)}diff --git a/activitypub/inbox/like.go b/services/activitypub/inbox/like.gosimilarity index 52%rename from activitypub/inbox/like.gorename to services/activitypub/inbox/like.goindex e7bc744fa3..89154e974f 100644--- a/activitypub/inbox/like.go+++ b/services/activitypub/inbox/like.go@@ -5,13 +5,13 @@ import ("time""github.com/go-fed/activity/streams/vocab"- "github.com/owncast/owncast/activitypub/apmodels"- "github.com/owncast/owncast/activitypub/persistence"- "github.com/owncast/owncast/core/chat/events""github.com/pkg/errors"++ "github.com/owncast/owncast/services/activitypub/apmodels"+ "github.com/owncast/owncast/services/chat/events")-func handleLikeRequest(c context.Context, activity vocab.ActivityStreamsLike) error {+func (s *Service) handleLikeRequest(c context.Context, activity vocab.ActivityStreamsLike) error {objectIRI, err := apmodels.GetIRIStringFromObjectProperty(activity.GetActivityStreamsObject())if err != nil {return errors.Wrap(err, "like activity is missing object IRI")@@ -24,25 +24,25 @@ func handleLikeRequest(c context.Context, activity vocab.ActivityStreamsLike) eractorReference := activity.GetActivityStreamsActor()- if hasPreviouslyhandled, err := persistence.HasPreviouslyHandledInboundActivity(objectIRI, actorIRI, events.FediverseEngagementLike); hasPreviouslyhandled || err != nil {+ if hasPreviouslyhandled, err := s.persistence.HasPreviouslyHandledInboundActivity(objectIRI, actorIRI, events.FediverseEngagementLike); hasPreviouslyhandled || err != nil {return errors.Wrap(err, "inbound activity of like has already been handled")}// Likes need to match a post we had already sent.- _, isLiveNotification, timestamp, err := persistence.GetObjectByIRI(objectIRI)+ _, isLiveNotification, timestamp, err := s.persistence.GetObjectByIRI(objectIRI)if err != nil {return errors.Wrap(err, "Could not find post locally")}- // Don't allow old activities to be liked+ // Don't allow old activities to be liked.if time.Since(timestamp) > maxAgeForEngagement {return errors.New("Activity is too old to be liked")}- // Save as an accepted activity- if err := persistence.SaveInboundFediverseActivity(objectIRI, actorIRI, events.FediverseEngagementLike, time.Now()); err != nil {+ // Save as an accepted activity.+ if err := s.persistence.SaveInboundFediverseActivity(objectIRI, actorIRI, events.FediverseEngagementLike, time.Now()); err != nil {return errors.Wrap(err, "unable to save inbound like activity")}- return handleEngagementActivity(events.FediverseEngagementLike, isLiveNotification, actorReference, events.FediverseEngagementLike)+ return s.handleEngagementActivity(events.FediverseEngagementLike, isLiveNotification, actorReference, events.FediverseEngagementLike)}diff --git a/activitypub/inbox/nil_safety_test.go b/services/activitypub/inbox/nil_safety_test.gosimilarity index 80%rename from activitypub/inbox/nil_safety_test.gorename to services/activitypub/inbox/nil_safety_test.goindex 039ed5564c..3c2814abc8 100644--- a/activitypub/inbox/nil_safety_test.go+++ b/services/activitypub/inbox/nil_safety_test.go@@ -8,6 +8,13 @@ import ("github.com/go-fed/activity/streams")+// testInbox carries no deps. Every assertion in this file exercises an+// early-return path that fails before the handler touches persistence or+// the followers repo, so nil deps are intentional. If a future test+// runs further into a handler it must construct a Service with real+// deps instead.+var testInbox = &Service{}+func mustParseURL(s string) *url.URL {u, err := url.Parse(s)if err != nil {@@ -25,7 +32,7 @@ func TestHandleFollowWithNilObject(t *testing.T) {// Don't set object or actor - they will be nil// This should return an error, not panic- err := handleFollowInboxRequest(context.Background(), activity)+ err := testInbox.handleFollowInboxRequest(context.Background(), activity)if err == nil {t.Error("handleFollowInboxRequest with nil object should return error")}@@ -37,7 +44,7 @@ func TestHandleFollowWithEmptyObject(t *testing.T) {activity.SetActivityStreamsObject(object)// Object is set but empty (no items)- err := handleFollowInboxRequest(context.Background(), activity)+ err := testInbox.handleFollowInboxRequest(context.Background(), activity)if err == nil {t.Error("handleFollowInboxRequest with empty object should return error")}@@ -56,7 +63,7 @@ func TestHandleFollowWithNilActorIRI(t *testing.T) {activity.SetActivityStreamsObject(object)// Actor is nil- err := handleFollowInboxRequest(context.Background(), activity)+ err := testInbox.handleFollowInboxRequest(context.Background(), activity)if err == nil {t.Error("handleFollowInboxRequest with nil actor should return error")}@@ -66,7 +73,7 @@ func TestHandleAnnounceWithNilObject(t *testing.T) {activity := streams.NewActivityStreamsAnnounce()// Don't set object or actor- err := handleAnnounceRequest(context.Background(), activity)+ err := testInbox.handleAnnounceRequest(context.Background(), activity)if err == nil {t.Error("handleAnnounceRequest with nil object should return error")}@@ -77,7 +84,7 @@ func TestHandleAnnounceWithEmptyObject(t *testing.T) {object := streams.NewActivityStreamsObjectProperty()activity.SetActivityStreamsObject(object)- err := handleAnnounceRequest(context.Background(), activity)+ err := testInbox.handleAnnounceRequest(context.Background(), activity)if err == nil {t.Error("handleAnnounceRequest with empty object should return error")}@@ -92,7 +99,7 @@ func TestHandleAnnounceWithNilActorIRI(t *testing.T) {activity.SetActivityStreamsObject(object)// Actor is nil- err := handleAnnounceRequest(context.Background(), activity)+ err := testInbox.handleAnnounceRequest(context.Background(), activity)if err == nil {t.Error("handleAnnounceRequest with nil actor should return error")}@@ -102,7 +109,7 @@ func TestHandleLikeWithNilObject(t *testing.T) {activity := streams.NewActivityStreamsLike()// Don't set object or actor- err := handleLikeRequest(context.Background(), activity)+ err := testInbox.handleLikeRequest(context.Background(), activity)if err == nil {t.Error("handleLikeRequest with nil object should return error")}@@ -113,7 +120,7 @@ func TestHandleLikeWithEmptyObject(t *testing.T) {object := streams.NewActivityStreamsObjectProperty()activity.SetActivityStreamsObject(object)- err := handleLikeRequest(context.Background(), activity)+ err := testInbox.handleLikeRequest(context.Background(), activity)if err == nil {t.Error("handleLikeRequest with empty object should return error")}@@ -128,7 +135,7 @@ func TestHandleLikeWithNilActorIRI(t *testing.T) {activity.SetActivityStreamsObject(object)// Actor is nil- err := handleLikeRequest(context.Background(), activity)+ err := testInbox.handleLikeRequest(context.Background(), activity)if err == nil {t.Error("handleLikeRequest with nil actor should return error")}@@ -138,7 +145,7 @@ func TestHandleCreateWithNilId(t *testing.T) {activity := streams.NewActivityStreamsCreate()// Don't set JSONLD ID- err := handleCreateRequest(context.Background(), activity)+ err := testInbox.handleCreateRequest(context.Background(), activity)if err == nil {t.Error("handleCreateRequest with nil ID should return error")}@@ -150,7 +157,7 @@ func TestHandleCreateWithIdButNilIRI(t *testing.T) {// Set the ID property but don't set an IRI on itactivity.SetJSONLDId(id)- err := handleCreateRequest(context.Background(), activity)+ err := testInbox.handleCreateRequest(context.Background(), activity)if err == nil {t.Error("handleCreateRequest with ID but nil IRI should return error")}@@ -161,7 +168,7 @@ func TestHandleUpdateWithNilObject(t *testing.T) {// Don't set object - should return nil (not an error, just skip)// This should not panic and should return nil since we only care about Person updates- err := handleUpdateRequest(context.Background(), activity)+ err := testInbox.handleUpdateRequest(context.Background(), activity)if err != nil {t.Errorf("handleUpdateRequest with nil object should return nil (skip), got %v", err)}@@ -173,7 +180,7 @@ func TestHandleUpdateWithEmptyObject(t *testing.T) {activity.SetActivityStreamsObject(object)// Should return nil since empty object means it's not a Person update- err := handleUpdateRequest(context.Background(), activity)+ err := testInbox.handleUpdateRequest(context.Background(), activity)if err != nil {t.Errorf("handleUpdateRequest with empty object should return nil (skip), got %v", err)}@@ -187,7 +194,7 @@ func TestHandleUpdateWithNonPersonObject(t *testing.T) {activity.SetActivityStreamsObject(object)// Should return nil since it's not a Person update- err := handleUpdateRequest(context.Background(), activity)+ err := testInbox.handleUpdateRequest(context.Background(), activity)if err != nil {t.Errorf("handleUpdateRequest with non-Person object should return nil (skip), got %v", err)}@@ -206,7 +213,7 @@ func TestNilSafetyNoPanic(t *testing.T) {}}()activity := streams.NewActivityStreamsFollow()- _ = handleFollowInboxRequest(ctx, activity)+ _ = testInbox.handleFollowInboxRequest(ctx, activity)})t.Run("Announce with nil properties", func(t *testing.T) {@@ -216,7 +223,7 @@ func TestNilSafetyNoPanic(t *testing.T) {}}()activity := streams.NewActivityStreamsAnnounce()- _ = handleAnnounceRequest(ctx, activity)+ _ = testInbox.handleAnnounceRequest(ctx, activity)})t.Run("Like with nil properties", func(t *testing.T) {@@ -226,7 +233,7 @@ func TestNilSafetyNoPanic(t *testing.T) {}}()activity := streams.NewActivityStreamsLike()- _ = handleLikeRequest(ctx, activity)+ _ = testInbox.handleLikeRequest(ctx, activity)})t.Run("Create with nil properties", func(t *testing.T) {@@ -236,7 +243,7 @@ func TestNilSafetyNoPanic(t *testing.T) {}}()activity := streams.NewActivityStreamsCreate()- _ = handleCreateRequest(ctx, activity)+ _ = testInbox.handleCreateRequest(ctx, activity)})t.Run("Update with nil properties", func(t *testing.T) {@@ -246,6 +253,6 @@ func TestNilSafetyNoPanic(t *testing.T) {}}()activity := streams.NewActivityStreamsUpdate()- _ = handleUpdateRequest(ctx, activity)+ _ = testInbox.handleUpdateRequest(ctx, activity)})}diff --git a/services/activitypub/inbox/service.go b/services/activitypub/inbox/service.gonew file mode 100644index 0000000000..4e8bb53724--- /dev/null+++ b/services/activitypub/inbox/service.go@@ -0,0 +1,107 @@+// Package inbox is the inbound side of the ActivityPub federation+// subsystem: parses verified inbound activities, dispatches them to+// per-type handlers (Follow, Like, Announce, Undo, Create, Update), and+// records accepted activities. Construct via New(Deps) and call+// Start(ctx) to spin up the request worker pool.+package inbox++import (+ "runtime"++ log "github.com/sirupsen/logrus"++ "github.com/owncast/owncast/persistence/configrepository"+ "github.com/owncast/owncast/services/activitypub/apmodels"+ apcrypto "github.com/owncast/owncast/services/activitypub/crypto"+ "github.com/owncast/owncast/services/activitypub/persistence"+ "github.com/owncast/owncast/services/activitypub/persistence/followersrepository"+ apresolvers "github.com/owncast/owncast/services/activitypub/resolvers"+ "github.com/owncast/owncast/services/activitypub/workerpool"+ "github.com/owncast/owncast/services/chat"+ "github.com/owncast/owncast/services/webhooks"+)++// Job bundles a single inbound HTTP request for a worker.+type Job struct {+ request apmodels.InboxRequest+}++// Service owns the inbound inbox worker pool and routes verified+// activities to their per-type handlers. It composes the persistence+// service (to record accepted activities) and the followers repository+// (to track follow/unfollow state).+type Service struct {+ workerPoolSize int+ queue chan Job++ persistence *persistence.Service+ workerpool *workerpool.Service+ webhooks *webhooks.Service+ chat *chat.Service+ followers followersrepository.FollowersRepository+ configRepository configrepository.ConfigRepository+ builder *apmodels.Builder+ signer *apcrypto.Signer+ resolver *apresolvers.Resolver+}++// Deps is the explicit dependency contract for inbox.+type Deps struct {+ Persistence *persistence.Service+ Workerpool *workerpool.Service+ Webhooks *webhooks.Service+ Chat *chat.Service+ Followers followersrepository.FollowersRepository+ ConfigRepository configrepository.ConfigRepository+ Builder *apmodels.Builder+ Signer *apcrypto.Signer+ Resolver *apresolvers.Resolver+}++// New constructs an idle inbox Service. Call Start to launch the worker+// pool.+func New(deps Deps) *Service {+ return &Service{+ workerPoolSize: runtime.GOMAXPROCS(0),+ persistence: deps.Persistence,+ workerpool: deps.Workerpool,+ webhooks: deps.Webhooks,+ chat: deps.Chat,+ followers: deps.Followers,+ configRepository: deps.ConfigRepository,+ builder: deps.Builder,+ signer: deps.Signer,+ resolver: deps.Resolver,+ }+}++// Start launches the inbox worker pool. Safe to call once.+func (s *Service) Start() {+ s.queue = make(chan Job)+ for i := 1; i <= s.workerPoolSize; i++ {+ go s.worker(i)+ }+}++// AddToQueue queues an inbound request for the worker pool.+func (s *Service) AddToQueue(req apmodels.InboxRequest) {+ log.Tracef("Queued request for ActivityPub inbox handler")+ s.queue <- Job{req}+}++func (s *Service) worker(workerID int) {+ log.Debugf("Started ActivityPub worker %d", workerID)++ for job := range s.queue {+ func() {+ defer func() {+ if r := recover(); r != nil {+ log.Errorf("Recovered from panic in ActivityPub worker %d: %v", workerID, r)+ }+ }()+ s.handle(job.request)+ }()++ log.Tracef("Done with ActivityPub inbox handler using worker %d", workerID)+ }+}diff --git a/activitypub/inbox/undo.go b/services/activitypub/inbox/undo.gosimilarity index 77%rename from activitypub/inbox/undo.gorename to services/activitypub/inbox/undo.goindex fd18fc6bbe..e44d219e8c 100644--- a/activitypub/inbox/undo.go+++ b/services/activitypub/inbox/undo.go@@ -8,13 +8,13 @@ import ("github.com/go-fed/activity/streams/vocab")-func handleUndoInboxRequest(c context.Context, activity vocab.ActivityStreamsUndo) error {+func (s *Service) handleUndoInboxRequest(c context.Context, activity vocab.ActivityStreamsUndo) error {// Determine if this is an undo of a follow, favorite, announce, etc.o := activity.GetActivityStreamsObject()for iter := o.Begin(); iter != o.End(); iter = iter.Next() {if iter.IsActivityStreamsFollow() {// This is an Unfollow request- if err := handleUnfollowRequest(c, activity); err != nil {+ if err := s.handleUnfollowRequest(c, activity); err != nil {return err}} else {diff --git a/services/activitypub/inbox/update.go b/services/activitypub/inbox/update.gonew file mode 100644index 0000000000..4bad0f2a23--- /dev/null+++ b/services/activitypub/inbox/update.go@@ -0,0 +1,25 @@+package inbox++import (+ "context"++ "github.com/go-fed/activity/streams/vocab"+ log "github.com/sirupsen/logrus"++ "github.com/owncast/owncast/services/activitypub/apmodels"+)++func (s *Service) handleUpdateRequest(c context.Context, activity vocab.ActivityStreamsUpdate) error {+ // We only care about update events to followers.+ if !apmodels.IsFirstObjectActivityStreamsPerson(activity.GetActivityStreamsObject()) {+ return nil+ }++ actor, err := s.resolver.GetResolvedActorFromActorProperty(activity.GetActivityStreamsActor())+ if err != nil {+ log.Errorln(err)+ return err+ }++ return s.followers.Update(actor.ActorIriString(), actor.InboxString(), actor.SharedInboxString(), actor.Name, actor.FullUsername, actor.ImageString())+}diff --git a/activitypub/inbox/worker.go b/services/activitypub/inbox/worker.gosimilarity index 76%rename from activitypub/inbox/worker.gorename to services/activitypub/inbox/worker.goindex 294a0dcbf6..75b43cf41c 100644--- a/activitypub/inbox/worker.go+++ b/services/activitypub/inbox/worker.go@@ -9,19 +9,15 @@ import ("net/url""strings"- "github.com/pkg/errors"-"github.com/go-fed/httpsig"- "github.com/owncast/owncast/activitypub/apmodels"- "github.com/owncast/owncast/activitypub/persistence/followersrepository"- "github.com/owncast/owncast/activitypub/resolvers"- "github.com/owncast/owncast/persistence/configrepository"-+ "github.com/pkg/errors"log "github.com/sirupsen/logrus"++ "github.com/owncast/owncast/services/activitypub/apmodels")-func handle(request apmodels.InboxRequest) {- if verified, err := Verify(request.Request); err != nil {+func (s *Service) handle(request apmodels.InboxRequest) {+ if verified, err := s.Verify(request.Request); err != nil {log.Debugln("Error in attempting to verify request", err)return} else if !verified {@@ -29,7 +25,7 @@ func handle(request apmodels.InboxRequest) {return}- if err := resolvers.Resolve(context.Background(), request.Body, handleUpdateRequest, handleFollowInboxRequest, handleLikeRequest, handleAnnounceRequest, handleUndoInboxRequest, handleCreateRequest); err != nil {+ if err := s.resolver.Resolve(context.Background(), request.Body, s.handleUpdateRequest, s.handleFollowInboxRequest, s.handleLikeRequest, s.handleAnnounceRequest, s.handleUndoInboxRequest, s.handleCreateRequest); err != nil {log.Debugln("resolver error:", err)}}@@ -37,7 +33,7 @@ func handle(request apmodels.InboxRequest) {// Verify will Verify the http signature of an inbound request as well as// check it against the list of blocked domains.// nolint: cyclop-func Verify(request *http.Request) (bool, error) {+func (s *Service) Verify(request *http.Request) (bool, error) {verifier, err := httpsig.NewVerifier(request)if err != nil {return false, errors.Wrap(err, "failed to create key verifier for request")@@ -72,7 +68,7 @@ func Verify(request *http.Request) (bool, error) {return false, errors.New("Unable to determine algorithm to verify request")}- publicKey, err := resolvers.GetResolvedPublicKeyFromIRI(pubKeyID.String())+ publicKey, err := s.resolver.GetResolvedPublicKeyFromIRI(pubKeyID.String())if err != nil {return false, errors.Wrap(err, "failed to resolve actor from IRI to fetch key")}@@ -87,12 +83,12 @@ func Verify(request *http.Request) (bool, error) {}// Test to see if the actor is in the list of blocked federated domains.- if isBlockedDomain(publicKeyActorIRI.Hostname()) {+ if s.isBlockedDomain(publicKeyActorIRI.Hostname()) {return false, errors.New("domain is blocked")}// If actor is specifically blocked, then fail validation.- if blocked, err := isBlockedActor(publicKeyActorIRI); err != nil || blocked {+ if blocked, err := s.isBlockedActor(publicKeyActorIRI); err != nil || blocked {return false, err}@@ -133,10 +129,8 @@ func Verify(request *http.Request) (bool, error) {return false, fmt.Errorf("http signature verification error(s) for: %s: %+v", pubKeyID.String(), triedAlgos)}-func isBlockedDomain(domain string) bool {- configRepository := configrepository.Get()-- blockedDomains := configRepository.GetBlockedFederatedDomains()+func (s *Service) isBlockedDomain(domain string) bool {+ blockedDomains := s.configRepository.GetBlockedFederatedDomains()for _, blockedDomain := range blockedDomains {if strings.Contains(domain, blockedDomain) {@@ -147,9 +141,8 @@ func isBlockedDomain(domain string) bool {return false}-func isBlockedActor(actorIRI *url.URL) (bool, error) {- followersRepo := followersrepository.Get()- blockedactor, err := followersRepo.GetByIRI(actorIRI.String())+func (s *Service) isBlockedActor(actorIRI *url.URL) (bool, error) {+ blockedactor, err := s.followers.GetByIRI(actorIRI.String())if blockedactor != nil && blockedactor.DisabledAt != nil {return true, errors.Wrap(err, "remote actor is blocked")diff --git a/activitypub/inbox/worker_test.go b/services/activitypub/inbox/worker_test.gosimilarity index 67%rename from activitypub/inbox/worker_test.gorename to services/activitypub/inbox/worker_test.goindex 03fc7c4b27..547aa34b18 100644--- a/activitypub/inbox/worker_test.go+++ b/services/activitypub/inbox/worker_test.go@@ -2,15 +2,17 @@ package inboximport ("net/url"+ "os""testing""github.com/go-fed/activity/streams""github.com/go-fed/activity/streams/vocab"- "github.com/owncast/owncast/activitypub/apmodels"- "github.com/owncast/owncast/activitypub/persistence"- "github.com/owncast/owncast/activitypub/persistence/followersrepository"- "github.com/owncast/owncast/core/data"+"github.com/owncast/owncast/persistence/configrepository"+ "github.com/owncast/owncast/services/activitypub/apmodels"+ "github.com/owncast/owncast/services/activitypub/persistence"+ "github.com/owncast/owncast/services/activitypub/persistence/followersrepository"+ "github.com/owncast/owncast/services/datastore")func makeFakePerson() vocab.ActivityStreamsPerson {@@ -49,16 +51,32 @@ func makeFakePerson() vocab.ActivityStreamsPerson {return person}+// testService is the inbox Service used by tests in this file. It's+// initialized in TestMain with a real in-memory datastore so handler+// methods that hit persistence/followers work.+var (+ testService *Service+ testDatastore *datastore.Datastore+)+func TestMain(m *testing.M) {- data.SetupPersistence(":memory:")- configRepository := configrepository.Get()+ ds, err := datastore.SetupPersistence(":memory:", os.TempDir())+ if err != nil {+ panic(err)+ }+ testDatastore = ds+ configRepository := configrepository.New(testDatastore)configRepository.SetServerURL("https://my.cool.site.biz")- persistence.Setup(data.GetDatastore())+ persistenceSvc := persistence.New(testDatastore, nil)+ testService = New(Deps{+ Persistence: persistenceSvc,+ Followers: followersrepository.New(testDatastore),+ })m.Run()}func TestBlockedDomains(t *testing.T) {- configRepository := configrepository.Get()+ configRepository := configrepository.New(testDatastore)person := makeFakePerson()@@ -80,16 +98,16 @@ func TestBlockedDomains(t *testing.T) {func TestBlockedActors(t *testing.T) {person := makeFakePerson()fakeRequest := streams.NewActivityStreamsFollow()- followersRepo := followersrepository.Get()- followersRepo.Add(apmodels.ActivityPubActor{+ followersRepository := followersrepository.New(testDatastore)+ followersRepository.Add(apmodels.ActivityPubActor{ActorIri: person.GetJSONLDId().GetIRI(),Inbox: person.GetJSONLDId().GetIRI(),FollowRequestIri: person.GetJSONLDId().GetIRI(),RequestObject: fakeRequest,}, false)- followersRepo.BlockOrReject(person.GetJSONLDId().GetIRI().String())+ followersRepository.BlockOrReject(person.GetJSONLDId().GetIRI().String())- blocked, err := isBlockedActor(person.GetJSONLDId().GetIRI())+ blocked, err := testService.isBlockedActor(person.GetJSONLDId().GetIRI())if err != nil {t.Error(err)return@@ -100,7 +118,7 @@ func TestBlockedActors(t *testing.T) {}failedBlockIRI, _ := url.Parse("https://freedom.eagle/user/mrbar")- failedBlock, err := isBlockedActor(failedBlockIRI)+ failedBlock, err := testService.isBlockedActor(failedBlockIRI)if failedBlock {t.Error("Invalid blocking of unblocked actor IRI")diff --git a/services/activitypub/jobs/followervalidation.go b/services/activitypub/jobs/followervalidation.gonew file mode 100644index 0000000000..468d99a891--- /dev/null+++ b/services/activitypub/jobs/followervalidation.go@@ -0,0 +1,145 @@+// Package jobs hosts the background validators and periodic tasks for+// the ActivityPub subsystem. Construct *Service with the followers+// repository and call Start to schedule the recurring follower+// validation pass.+package jobs++import (+ "time"++ log "github.com/sirupsen/logrus"++ "github.com/owncast/owncast/config"+ "github.com/owncast/owncast/models"+ "github.com/owncast/owncast/persistence/configrepository"+ "github.com/owncast/owncast/services/activitypub/persistence/followersrepository"+ apresolvers "github.com/owncast/owncast/services/activitypub/resolvers"+)++const (+ // ValidationInterval is how often the validation job runs.+ ValidationInterval = 1 * time.Hour+ // FollowersPerRun is how many followers to validate per job run.+ FollowersPerRun = 5+ // FailureDurationThreshold is how long a follower must be unreachable before removal.+ FailureDurationThreshold = 7 * 24 * time.Hour+ // DelayBetweenFollowers is the delay between validating individual followers.+ DelayBetweenFollowers = 2 * time.Second+)++// GetValidationInterval returns the configured validation interval (from+// the supplied Config) when non-zero, otherwise the default+// ValidationInterval.+func GetValidationInterval(cfg *config.Config) time.Duration {+ if cfg != nil && cfg.FollowerValidationInterval > 0 {+ return cfg.FollowerValidationInterval+ }+ return ValidationInterval+}++// Service runs the recurring AP-side jobs.+type Service struct {+ followers followersrepository.FollowersRepository+ configRepository configrepository.ConfigRepository+ resolver *apresolvers.Resolver+ cfg *config.Config+}++// Deps is the dependency contract for jobs.+type Deps struct {+ Followers followersrepository.FollowersRepository+ ConfigRepository configrepository.ConfigRepository+ Resolver *apresolvers.Resolver+ Config *config.Config+}++// New constructs the jobs Service. Call Start to schedule the+// recurring tasks.+func New(deps Deps) *Service {+ return &Service{+ followers: deps.Followers,+ configRepository: deps.ConfigRepository,+ resolver: deps.Resolver,+ cfg: deps.Config,+ }+}++// Start schedules the follower-validation tick.+func (s *Service) Start() {+ interval := GetValidationInterval(s.cfg)+ ticker := time.NewTicker(interval)+ go func() {+ for range ticker.C {+ s.runFollowerValidation()+ }+ }()+ log.Debugf("Follower validation job scheduled with interval %v", interval)+}++func (s *Service) runFollowerValidation() {+ if !s.configRepository.GetFederationEnabled() {+ return+ }++ followers, err := s.followers.GetFollowersToValidate(FollowersPerRun)+ if err != nil {+ log.Errorln("Failed to get followers for validation:", err)+ return+ }++ for _, follower := range followers {+ s.validateAndUpdateFollower(follower)+ time.Sleep(DelayBetweenFollowers)+ }+}++func (s *Service) validateAndUpdateFollower(follower models.Follower) {+ resolvedActor, err := s.resolver.GetResolvedActorFromIRI(follower.ActorIRI)+ if err != nil {+ s.handleValidationFailure(follower, err)+ return+ }++ // Success — clear failure timestamp and refresh actor data.+ if err := s.followers.UpdateFollowerValidationSuccess(follower.ActorIRI); err != nil {+ log.Errorln("Failed to update validation success:", err)+ }++ if err := s.followers.Update(+ resolvedActor.ActorIriString(),+ resolvedActor.InboxString(),+ resolvedActor.SharedInboxString(),+ resolvedActor.Name,+ resolvedActor.FullUsername,+ resolvedActor.ImageString(),+ ); err != nil {+ log.Errorln("Failed to update follower data:", err)+ }+}++func (s *Service) handleValidationFailure(follower models.Follower, resolveErr error) {+ log.Debugf("Follower validation failed for %s: %v", follower.ActorIRI, resolveErr)++ // Check removal eligibility BEFORE updating the failure timestamp.+ // FirstValidationFailureAt being unset means this is a new failure+ // and we just record it.+ shouldRemove := false+ if follower.FirstValidationFailureAt.Valid {+ failureDuration := time.Since(follower.FirstValidationFailureAt.Time)+ shouldRemove = failureDuration >= FailureDurationThreshold+ }++ if err := s.followers.UpdateFollowerValidationFailure(follower.ActorIRI); err != nil {+ log.Errorln("Failed to update validation failure:", err)+ return+ }++ if shouldRemove {+ failureDuration := time.Since(follower.FirstValidationFailureAt.Time)+ log.Infof("Removing follower %s after %v of consecutive failures",+ follower.ActorIRI, failureDuration.Round(time.Hour))+ if err := s.followers.RemoveByIRI(follower.ActorIRI); err != nil {+ log.Errorln("Failed to remove invalid follower:", err)+ }+ }+}diff --git a/activitypub/jobs/followervalidation_test.go b/services/activitypub/jobs/followervalidation_test.gosimilarity index 93%rename from activitypub/jobs/followervalidation_test.gorename to services/activitypub/jobs/followervalidation_test.goindex 0bfe9d0bb8..974e07b147 100644--- a/activitypub/jobs/followervalidation_test.go+++ b/services/activitypub/jobs/followervalidation_test.go@@ -7,10 +7,10 @@ import ("time""github.com/go-fed/activity/streams"- "github.com/owncast/owncast/activitypub/apmodels"- "github.com/owncast/owncast/activitypub/persistence"- "github.com/owncast/owncast/activitypub/persistence/followersrepository"- "github.com/owncast/owncast/core/data"++ "github.com/owncast/owncast/services/activitypub/apmodels"+ "github.com/owncast/owncast/services/activitypub/persistence/followersrepository"+ "github.com/owncast/owncast/services/datastore""github.com/owncast/owncast/utils")@@ -20,7 +20,7 @@ func TestMain(m *testing.M) {os.Exit(code)}-var datastore *data.Datastore+var testDatastore *datastore.Datastorefunc setup() {resetTestDatabase()@@ -28,16 +28,18 @@ func setup() {// resetTestDatabase initializes a fresh in-memory database for testing.func resetTestDatabase() {- data.SetupPersistence(":memory:")- datastore = data.GetDatastore()- persistence.Setup(datastore)+ ds, err := datastore.SetupPersistence(":memory:", os.TempDir())+ if err != nil {+ panic(err)+ }+ testDatastore = ds}// setupTestWithRepo resets the database and returns a new repository instance.func setupTestWithRepo(t *testing.T) followersrepository.FollowersRepository {t.Helper()resetTestDatabase()- return followersrepository.New(datastore)+ return followersrepository.New(testDatastore)}func createTestFollower(repo followersrepository.FollowersRepository, iri, inbox, name, username string) {@@ -215,7 +217,7 @@ func TestFailureDurationThresholdLogic(t *testing.T) {// Set first_validation_failure_at to 8 days ago (past threshold)eightDaysAgo := time.Now().Add(-8 * 24 * time.Hour)- _, err := datastore.DB.Exec(+ _, err := testDatastore.DB.Exec("UPDATE ap_followers SET first_validation_failure_at = ? WHERE iri = ?",eightDaysAgo, testIRI,)@@ -264,7 +266,7 @@ func TestFailureNotRemovedBeforeThreshold(t *testing.T) {// Set first_validation_failure_at to 1 day ago (not past threshold)oneDayAgo := time.Now().Add(-1 * 24 * time.Hour)- _, err := datastore.DB.Exec(+ _, err := testDatastore.DB.Exec("UPDATE ap_followers SET first_validation_failure_at = ? WHERE iri = ?",oneDayAgo, testIRI,)@@ -312,12 +314,12 @@ func TestFollowersOrderedByOldestValidatedFirst(t *testing.T) {// Set different last_validated_at timesnow := time.Now()- _, err := datastore.DB.Exec("UPDATE ap_followers SET last_validated_at = ? WHERE iri = ?",+ _, err := testDatastore.DB.Exec("UPDATE ap_followers SET last_validated_at = ? WHERE iri = ?",now.Add(-3*time.Hour), iri1)if err != nil {t.Fatalf("Error updating: %s", err)}- _, err = datastore.DB.Exec("UPDATE ap_followers SET last_validated_at = ? WHERE iri = ?",+ _, err = testDatastore.DB.Exec("UPDATE ap_followers SET last_validated_at = ? WHERE iri = ?",now.Add(-1*time.Hour), iri2)if err != nil {t.Fatalf("Error updating: %s", err)diff --git a/activitypub/outbox/nil_safety_test.go b/services/activitypub/outbox/nil_safety_test.gosimilarity index 83%rename from activitypub/outbox/nil_safety_test.gorename to services/activitypub/outbox/nil_safety_test.goindex 8b63340b2b..685f41aea6 100644--- a/activitypub/outbox/nil_safety_test.go+++ b/services/activitypub/outbox/nil_safety_test.go@@ -7,6 +7,11 @@ import ("github.com/go-fed/activity/streams/vocab")+// testOutbox carries no deps. Every assertion in this file exercises+// the early-error path inside Add (nil IRI extraction), which returns+// before deps are touched.+var testOutbox = &Service{}+// TestAddWithNilId verifies that Add doesn't panic when given an item with nil JSONLD ID.func TestAddWithNilId(t *testing.T) {defer func() {@@ -18,7 +23,7 @@ func TestAddWithNilId(t *testing.T) {note := streams.NewActivityStreamsNote()// Don't set JSONLD ID- err := Add(note, "test-id", false)+ err := testOutbox.Add(note, "test-id", false)if err == nil {t.Error("Add with nil ID should return error")}@@ -38,7 +43,7 @@ func TestAddWithIdButNilIRI(t *testing.T) {// Set the ID property but don't set an IRI on itnote.SetJSONLDId(id)- err := Add(note, "test-id", false)+ err := testOutbox.Add(note, "test-id", false)if err == nil {t.Error("Add with ID but nil IRI should return error")}@@ -73,7 +78,7 @@ func TestAddNoPanic(t *testing.T) {t.Errorf("Add panicked: %v", r)}}()- _ = Add(tc.item(), "test-id", false)+ _ = testOutbox.Add(tc.item(), "test-id", false)})}}diff --git a/activitypub/outbox/outbox.go b/services/activitypub/outbox/outbox.gosimilarity index 51%rename from activitypub/outbox/outbox.gorename to services/activitypub/outbox/outbox.goindex 50a0262a41..f5fe4cef49 100644--- a/activitypub/outbox/outbox.go+++ b/services/activitypub/outbox/outbox.go@@ -1,3 +1,8 @@+// Package outbox is the federated-message producer for the ActivityPub+// subsystem: builds Create activities, addresses them to followers, and+// hands the signed bytes to the outbound worker pool. Construct via+// New(Deps) with persistence + workerpool services; all entry points+// are methods on *Service.package outboximport (@@ -10,28 +15,66 @@ import ("github.com/go-fed/activity/streams""github.com/go-fed/activity/streams/vocab"- "github.com/owncast/owncast/activitypub/apmodels"- "github.com/owncast/owncast/activitypub/crypto"- "github.com/owncast/owncast/activitypub/persistence"- "github.com/owncast/owncast/activitypub/persistence/followersrepository"- "github.com/owncast/owncast/activitypub/requests"- "github.com/owncast/owncast/activitypub/resolvers"- "github.com/owncast/owncast/activitypub/webfinger"- "github.com/owncast/owncast/activitypub/workerpool"- "github.com/owncast/owncast/persistence/configrepository""github.com/pkg/errors"+ log "github.com/sirupsen/logrus"+ "github.com/teris-io/shortid""github.com/owncast/owncast/config"+ "github.com/owncast/owncast/persistence/configrepository"+ "github.com/owncast/owncast/services/activitypub/apmodels"+ apcrypto "github.com/owncast/owncast/services/activitypub/crypto"+ "github.com/owncast/owncast/services/activitypub/persistence"+ "github.com/owncast/owncast/services/activitypub/persistence/followersrepository"+ "github.com/owncast/owncast/services/activitypub/requests"+ apresolvers "github.com/owncast/owncast/services/activitypub/resolvers"+ "github.com/owncast/owncast/services/activitypub/webfinger"+ "github.com/owncast/owncast/services/activitypub/workerpool""github.com/owncast/owncast/utils"- log "github.com/sirupsen/logrus"- "github.com/teris-io/shortid")-// SendLive will send all followers the message saying you started a live stream.-func SendLive() error {- configRepository := configrepository.Get()+// Service is the outbound side of federation. It composes a *persistence.Service+// for storing what we send and a *workerpool.Service for actually+// delivering it.+type Service struct {+ persistence *persistence.Service+ workerpool *workerpool.Service+ followers followersrepository.FollowersRepository+ configRepository configrepository.ConfigRepository+ builder *apmodels.Builder+ signer *apcrypto.Signer+ resolver *apresolvers.Resolver+ cfg *config.Config+}- textContent := configRepository.GetFederationGoLiveMessage()+// Deps is the explicit dependency contract for outbox.+type Deps struct {+ Persistence *persistence.Service+ Workerpool *workerpool.Service+ Followers followersrepository.FollowersRepository+ ConfigRepository configrepository.ConfigRepository+ Builder *apmodels.Builder+ Signer *apcrypto.Signer+ Resolver *apresolvers.Resolver+ Config *config.Config+}++// New constructs an outbox Service. All deps are required.+func New(deps Deps) *Service {+ return &Service{+ persistence: deps.Persistence,+ workerpool: deps.Workerpool,+ followers: deps.Followers,+ configRepository: deps.ConfigRepository,+ builder: deps.Builder,+ signer: deps.Signer,+ resolver: deps.Resolver,+ cfg: deps.Config,+ }+}++// SendLive notifies all followers that the stream has gone live.+func (s *Service) SendLive() error {+ textContent := s.configRepository.GetFederationGoLiveMessage()// If the message is empty then do not send it.if textContent == "" {@@ -42,7 +85,7 @@ func SendLive() error {reg := regexp.MustCompile("[^a-zA-Z0-9]+")tagProp := streams.NewActivityStreamsTagProperty()- for _, tagString := range configRepository.GetServerMetadataTags() {+ for _, tagString := range s.configRepository.GetServerMetadataTags() {tagWithoutSpecialCharacters := reg.ReplaceAllString(tagString, "")hashtag := apmodels.MakeHashtag(tagWithoutSpecialCharacters)tagProp.AppendTootHashtag(hashtag)@@ -50,9 +93,8 @@ func SendLive() error {tagStrings = append(tagStrings, tagString)}- // Manually add Owncast hashtag if it doesn't already exist so it shows up- // in Owncast search results.- // We can remove this down the road, but it'll be nice for now.+ // Manually add Owncast hashtag if it doesn't already exist so it+ // shows up in Owncast search results.if _, exists := utils.FindInSlice(tagStrings, "owncast"); !exists {hashtag := apmodels.MakeHashtag("owncast")tagProp.AppendTootHashtag(hashtag)@@ -61,14 +103,14 @@ func SendLive() error {tagsString := strings.Join(tagStrings, " ")var streamTitle string- if title := configRepository.GetStreamTitle(); title != "" {+ if title := s.configRepository.GetStreamTitle(); title != "" {streamTitle = fmt.Sprintf("<p>%s</p>", title)}- textContent = fmt.Sprintf("<p>%s</p>%s<p>%s</p><p><a href=\"%s\">%s</a></p>", textContent, streamTitle, tagsString, configRepository.GetServerURL(), configRepository.GetServerURL())+ textContent = fmt.Sprintf("<p>%s</p>%s<p>%s</p><p><a href=\"%s\">%s</a></p>", textContent, streamTitle, tagsString, s.configRepository.GetServerURL(), s.configRepository.GetServerURL())- activity, _, note, noteID := createBaseOutboundMessage(textContent)+ activity, _, note, noteID := s.createBaseOutboundMessage(textContent)- to, cc := getAddressingToFollowers()+ to, cc := s.getAddressingToFollowers()note.SetActivityStreamsTo(to)note.SetActivityStreamsCc(cc)activity.SetActivityStreamsTo(to)@@ -77,12 +119,12 @@ func SendLive() error {note.SetActivityStreamsTag(tagProp)// Attach an image along with the Federated message.- previewURL, err := url.Parse(configRepository.GetServerURL())+ previewURL, err := url.Parse(s.configRepository.GetServerURL())if err == nil {var imageToAttach stringvar mediaType string- previewGif := filepath.Join(config.TempDir, "preview.gif")- thumbnailJpg := filepath.Join(config.TempDir, "thumbnail.jpg")+ previewGif := filepath.Join(s.cfg.TempDir, "preview.gif")+ thumbnailJpg := filepath.Join(s.cfg.TempDir, "thumbnail.jpg")uniquenessString := shortid.MustGenerate()if utils.DoesFileExists(previewGif) {imageToAttach = "preview.gif"@@ -98,8 +140,7 @@ func SendLive() error {}}- if configRepository.GetNSFW() {- // Mark content as sensitive.+ if s.configRepository.GetNSFW() {sensitive := streams.NewActivityStreamsSensitiveProperty()sensitive.AppendXMLSchemaBoolean(true)note.SetActivityStreamsSensitive(sensitive)@@ -111,19 +152,19 @@ func SendLive() error {return errors.New("unable to serialize go live message activity " + err.Error())}- if err := SendToFollowers(b); err != nil {+ if err := s.SendToFollowers(b); err != nil {return err}- if err := Add(note, noteID, true); err != nil {+ if err := s.Add(note, noteID, true); err != nil {return err}return nil}-// SendDirectMessageToAccount will send a direct message to a single account.-func SendDirectMessageToAccount(textContent, account string) error {+// SendDirectMessageToAccount sends a direct message to a single account.+func (s *Service) SendDirectMessageToAccount(textContent, account string) error {links, err := webfinger.GetWebfingerLinks(account)if err != nil {return errors.Wrap(err, "unable to get webfinger links when sending private message")@@ -131,14 +172,14 @@ func SendDirectMessageToAccount(textContent, account string) error {user := apmodels.MakeWebFingerRequestResponseFromData(links)iri := user.Self- actor, err := resolvers.GetResolvedActorFromIRI(iri)+ actor, err := s.resolver.GetResolvedActorFromIRI(iri)if err != nil {return errors.Wrap(err, "unable to resolve actor to send message to")}- activity, _, note, _ := createBaseOutboundMessage(textContent)+ activity, _, note, _ := s.createBaseOutboundMessage(textContent)- // Set direct message visibility+ // Set direct message visibility.activity = apmodels.MakeActivityDirect(activity, actor.ActorIri)note = apmodels.MakeNoteDirect(note, actor.ActorIri)object := activity.GetActivityStreamsObject()@@ -150,11 +191,11 @@ func SendDirectMessageToAccount(textContent, account string) error {return errors.Wrap(err, "unable to serialize custom fediverse message activity")}- return SendToUser(actor.Inbox, b)+ return s.SendToUser(actor.Inbox, b)}-// SendPublicMessage will send a public message to all followers.-func SendPublicMessage(textContent string) error {+// SendPublicMessage sends a public message to all followers.+func (s *Service) SendPublicMessage(textContent string) error {originalContent := textContenttextContent = utils.RenderSimpleMarkdown(textContent)@@ -165,19 +206,18 @@ func SendPublicMessage(textContent string) error {for _, hashtag := range hashtagStrings {tagWithoutHashtag := strings.TrimPrefix(hashtag, "#")- // Replace the instances of the tag with a link to the tag page.+ // Replace each instance with a link to the tag page.tagHTML := getHashtagLinkHTMLFromTagString(tagWithoutHashtag)textContent = strings.ReplaceAll(textContent, hashtag, tagHTML)- // Create Hashtag object for the tag.hashtag := apmodels.MakeHashtag(tagWithoutHashtag)tagProp.AppendTootHashtag(hashtag)}- activity, _, note, noteID := createBaseOutboundMessage(textContent)+ activity, _, note, noteID := s.createBaseOutboundMessage(textContent)note.SetActivityStreamsTag(tagProp)- to, cc := getAddressingToFollowers()+ to, cc := s.getAddressingToFollowers()note.SetActivityStreamsTo(to)note.SetActivityStreamsCc(cc)activity.SetActivityStreamsTo(to)@@ -189,36 +229,35 @@ func SendPublicMessage(textContent string) error {return errors.New("unable to serialize custom fediverse message activity " + err.Error())}- if err := SendToFollowers(b); err != nil {+ if err := s.SendToFollowers(b); err != nil {return err}- if err := Add(note, noteID, false); err != nil {+ if err := s.Add(note, noteID, false); err != nil {return err}return nil}-// if public, cc the followers and to the Public uri, else private, address followers directly.-func getAddressingToFollowers() (vocab.ActivityStreamsToProperty, vocab.ActivityStreamsCcProperty) {- configRepository := configrepository.Get()- username := configRepository.GetDefaultFederationUsername()+// getAddressingToFollowers builds the to/cc properties for a follower-addressed+// activity: public → cc:followers, to:public; private → to:followers.+func (s *Service) getAddressingToFollowers() (vocab.ActivityStreamsToProperty, vocab.ActivityStreamsCcProperty) {+ username := s.configRepository.GetDefaultFederationUsername()- followersIRI := apmodels.MakeLocalIRIForAccount(username)+ followersIRI := s.builder.MakeLocalIRIForAccount(username)followersIRI = followersIRI.JoinPath("followers")- return apmodels.MakeAddressingToFollowers(followersIRI, !configRepository.GetFederationIsPrivate())+ return apmodels.MakeAddressingToFollowers(followersIRI, !s.configRepository.GetFederationIsPrivate())}// nolint: unparam-func createBaseOutboundMessage(textContent string) (vocab.ActivityStreamsCreate, string, vocab.ActivityStreamsNote, string) {- configRepository := configrepository.Get()- localActor := apmodels.MakeLocalIRIForAccount(configRepository.GetDefaultFederationUsername())+func (s *Service) createBaseOutboundMessage(textContent string) (vocab.ActivityStreamsCreate, string, vocab.ActivityStreamsNote, string) {+ localActor := s.builder.MakeLocalIRIForAccount(s.configRepository.GetDefaultFederationUsername())noteID := shortid.MustGenerate()- noteIRI := apmodels.MakeLocalIRIForResource(noteID)+ noteIRI := s.builder.MakeLocalIRIForResource(noteID)id := shortid.MustGenerate()- activity := apmodels.CreateCreateActivity(id, localActor)+ activity := s.builder.CreateCreateActivity(id, localActor)object := streams.NewActivityStreamsObjectProperty()activity.SetActivityStreamsObject(object)@@ -228,27 +267,25 @@ func createBaseOutboundMessage(textContent string) (vocab.ActivityStreamsCreate,return activity, id, note, noteID}-// Get Hashtag HTML link for a given tag (without # prefix).+// getHashtagLinkHTMLFromTagString returns the HTML link for a tag (without the # prefix).func getHashtagLinkHTMLFromTagString(baseHashtag string) string {return fmt.Sprintf("<a class=\"hashtag\" href=\"https://owncast.directory/tags/%s\">#%s</a>", baseHashtag, baseHashtag)}-// SendToFollowers will send an arbitrary payload to all follower inboxes.-// It uses shared inboxes when available to reduce the number of outbound requests.-func SendToFollowers(payload []byte) error {- configRepository := configrepository.Get()- followersRepo := followersrepository.Get()- localActor := apmodels.MakeLocalIRIForAccount(configRepository.GetDefaultFederationUsername())+// SendToFollowers sends an arbitrary payload to all follower inboxes,+// preferring shared inboxes to reduce outbound request count.+func (s *Service) SendToFollowers(payload []byte) error {+ localActor := s.builder.MakeLocalIRIForAccount(s.configRepository.GetDefaultFederationUsername())- // Get unique delivery inboxes (prefers shared inboxes over individual inboxes)- inboxes, err := followersRepo.GetUniqueDeliveryInboxes()+ // Prefer shared inboxes over individual inboxes.+ inboxes, err := s.followers.GetUniqueDeliveryInboxes()if err != nil {log.Errorln("unable to fetch delivery inboxes", err)return errors.New("unable to fetch delivery inboxes to send payload to")}- // Batch size and delay to prevent resource exhaustion during delivery.- // This spreads CPU load from cryptographic signing over time.+ // Batch size and delay to prevent resource exhaustion during+ // delivery; spreads CPU load from cryptographic signing over time.const batchSize = 50const batchDelay = 100 * time.Millisecond@@ -262,9 +299,10 @@ func SendToFollowers(payload []byte) error {continue}- // SSRF protection: reject non-HTTPS schemes and internal/loopback hosts.- // A malicious remote actor could set their inbox to an internal address- // to trick this server into making requests to internal services.+ // SSRF protection: reject non-HTTPS schemes and+ // internal/loopback hosts. A malicious remote actor could set+ // their inbox to an internal address to trick this server into+ // making requests to internal services.if inbox.Scheme != "https" {log.Warnln("rejecting non-HTTPS inbox URL for SSRF protection:", inboxURL)continue@@ -274,26 +312,27 @@ func SendToFollowers(payload []byte) error {continue}- // Pre-check circuit breaker BEFORE expensive cryptographic signing.- // This saves CPU cycles for domains we know are failing.- if workerpool.ShouldSkipDomain(inbox.Host) {+ // Pre-check circuit breaker BEFORE expensive cryptographic+ // signing. This saves CPU cycles for domains we know are+ // failing.+ if s.workerpool.ShouldSkipDomain(inbox.Host) {skipped++continue}- req, err := crypto.CreateSignedRequest(payload, inbox, localActor)+ req, err := s.signer.CreateSignedRequest(payload, inbox, localActor)if err != nil {log.Errorln("unable to create outbox request", inboxURL, err)continue}- workerpool.AddToOutboundQueue(req)+ s.workerpool.AddToOutboundQueue(req)queued++- // Add a small delay between batches to spread out CPU and network load.- // This helps prevent ActivityPub delivery from competing with video encoding.- // Use queued count (not loop index) to ensure consistent rate limiting- // even when followers are skipped due to circuit breaker or parse errors.+ // Spread CPU and network load across batches so ActivityPub+ // delivery doesn't compete with video encoding. Use queued count+ // (not loop index) so rate limiting is consistent even when+ // followers are skipped due to circuit breaker or parse errors.if queued%batchSize == 0 && i+1 < len(inboxes) {time.Sleep(batchDelay)}@@ -306,8 +345,8 @@ func SendToFollowers(payload []byte) error {return nil}-// SendToUser will send a payload to a single specific inbox.-func SendToUser(inbox *url.URL, payload []byte) error {+// SendToUser sends a payload to a single specific inbox.+func (s *Service) SendToUser(inbox *url.URL, payload []byte) error {// SSRF protection: reject non-HTTPS schemes and internal/loopback hosts.if inbox.Scheme != "https" {return errors.Errorf("rejecting non-HTTPS inbox URL for SSRF protection: %s", inbox.String())@@ -316,34 +355,31 @@ func SendToUser(inbox *url.URL, payload []byte) error {return errors.Errorf("rejecting internal/loopback inbox URL for SSRF protection: %s", inbox.String())}- configRepository := configrepository.Get()- localActor := apmodels.MakeLocalIRIForAccount(configRepository.GetDefaultFederationUsername())+ localActor := s.builder.MakeLocalIRIForAccount(s.configRepository.GetDefaultFederationUsername())- req, err := requests.CreateSignedRequest(payload, inbox, localActor)+ req, err := requests.CreateSignedRequest(payload, inbox, localActor, s.signer)if err != nil {return errors.Wrap(err, "unable to create outbox request")}- workerpool.AddToOutboundQueue(req)+ s.workerpool.AddToOutboundQueue(req)return nil}-// UpdateFollowersWithAccountUpdates will send an update to all followers alerting of a profile update.-func UpdateFollowersWithAccountUpdates() error {- configRepository := configrepository.Get()-- // Don't do anything if federation is disabled.- if !configRepository.GetFederationEnabled() {+// UpdateFollowersWithAccountUpdates broadcasts a profile-update Activity+// to all followers.+func (s *Service) UpdateFollowersWithAccountUpdates() error {+ if !s.configRepository.GetFederationEnabled() {return nil}id := shortid.MustGenerate()- objectID := apmodels.MakeLocalIRIForResource(id)- activity := apmodels.MakeUpdateActivity(objectID)+ objectID := s.builder.MakeLocalIRIForResource(id)+ activity := s.builder.MakeUpdateActivity(objectID)actor := streams.NewActivityStreamsPerson()- actorID := apmodels.MakeLocalIRIForAccount(configRepository.GetDefaultFederationUsername())+ actorID := s.builder.MakeLocalIRIForAccount(s.configRepository.GetDefaultFederationUsername())actorIDProperty := streams.NewJSONLDIdProperty()actorIDProperty.Set(actorID)actor.SetJSONLDId(actorIDProperty)@@ -361,11 +397,11 @@ func UpdateFollowersWithAccountUpdates() error {log.Errorln("unable to serialize send update actor activity", err)return errors.New("unable to serialize send update actor activity")}- return SendToFollowers(b)+ return s.SendToFollowers(b)}-// Add will save an ActivityPub object to the datastore.-func Add(item vocab.Type, id string, isLiveNotification bool) error {+// Add saves an ActivityPub object to the datastore.+func (s *Service) Add(item vocab.Type, id string, isLiveNotification bool) error {iri, err := apmodels.GetIRIStringFromJSONLDIdProperty(item.GetJSONLDId())if err != nil {log.Errorln("Unable to get iri from item:", err)@@ -379,5 +415,5 @@ func Add(item vocab.Type, id string, isLiveNotification bool) error {return err}- return persistence.AddToOutbox(iri, b, typeString, isLiveNotification)+ return s.persistence.AddToOutbox(iri, b, typeString, isLiveNotification)}diff --git a/activitypub/persistence/followers_fixture.go b/services/activitypub/persistence/followers_fixture.gosimilarity index 84%rename from activitypub/persistence/followers_fixture.gorename to services/activitypub/persistence/followers_fixture.goindex 6f7a462732..3d797d8132 100644--- a/activitypub/persistence/followers_fixture.go+++ b/services/activitypub/persistence/followers_fixture.go@@ -10,9 +10,10 @@ import ("os""github.com/go-fed/activity/streams"- "github.com/owncast/owncast/activitypub/apmodels"- "github.com/owncast/owncast/activitypub/persistence/followersrepository"log "github.com/sirupsen/logrus"++ "github.com/owncast/owncast/services/activitypub/apmodels"+ "github.com/owncast/owncast/services/activitypub/persistence/followersrepository")type fixtureFollower struct {@@ -23,7 +24,7 @@ type fixtureFollower struct {Image string `json:"image"`}-func addFollowersFixtureData() {+func (s *Service) addFollowersFixtureData() {log.Println("Adding followers fixture data...")file, err := os.Open("./test/fixture/followers_fixture.json")if err != nil {@@ -39,7 +40,7 @@ func addFollowersFixtureData() {return}- followersRepo := followersrepository.New(_datastore)+ followersRepo := followersrepository.New(s.datastore)for _, f := range followers {actorIRI, _ := url.Parse(f.ActorIRI)inboxURL, _ := url.Parse(f.Inbox)diff --git a/activitypub/persistence/followers_nofixture.go b/services/activitypub/persistence/followers_nofixture.gosimilarity index 61%rename from activitypub/persistence/followers_nofixture.gorename to services/activitypub/persistence/followers_nofixture.goindex 30a881e3f8..ff9d163425 100644--- a/activitypub/persistence/followers_nofixture.go+++ b/services/activitypub/persistence/followers_nofixture.go@@ -3,6 +3,6 @@package persistence-func addFollowersFixtureData() {+func (s *Service) addFollowersFixtureData() {// no-op}diff --git a/activitypub/persistence/followers_test.go b/services/activitypub/persistence/followers_test.gosimilarity index 90%rename from activitypub/persistence/followers_test.gorename to services/activitypub/persistence/followers_test.goindex f1044a8697..a4966978a0 100644--- a/activitypub/persistence/followers_test.go+++ b/services/activitypub/persistence/followers_test.go@@ -7,10 +7,11 @@ import ("testing""github.com/go-fed/activity/streams"- "github.com/owncast/owncast/activitypub/apmodels"- "github.com/owncast/owncast/activitypub/persistence/followersrepository"- "github.com/owncast/owncast/core/data"+"github.com/owncast/owncast/models"+ "github.com/owncast/owncast/services/activitypub/apmodels"+ "github.com/owncast/owncast/services/activitypub/persistence/followersrepository"+ "github.com/owncast/owncast/services/datastore""github.com/owncast/owncast/utils")@@ -20,11 +21,19 @@ func TestMain(m *testing.M) {os.Exit(code)}+// _datastore is the test-local datastore handle. Each setup sets it+// to a fresh in-memory database; the package no longer maintains a+// global one.+var _datastore *datastore.Datastore+var followers = []models.Follower{}func setup() {- data.SetupPersistence(":memory:")- _datastore = data.GetDatastore()+ ds, err := datastore.SetupPersistence(":memory:", os.TempDir())+ if err != nil {+ panic(err)+ }+ _datastore = dsfollowersRepo := followersrepository.New(_datastore)@@ -149,8 +158,10 @@ func createTestFollower(followersRepo followersrepository.FollowersRepository, afunc TestGetUniqueDeliveryInboxes(t *testing.T) {// Set up a fresh database for this test- data.SetupPersistence(":memory:")- ds := data.GetDatastore()+ ds, err := datastore.SetupPersistence(":memory:", os.TempDir())+ if err != nil {+ t.Fatalf("setup error: %s", err)+ }_datastore = dsfollowersRepo := followersrepository.New(ds)@@ -246,8 +257,10 @@ func TestGetUniqueDeliveryInboxes(t *testing.T) {func TestSharedInboxPreferredOverIndividual(t *testing.T) {// Set up a fresh database for this test- data.SetupPersistence(":memory:")- ds := data.GetDatastore()+ ds, err := datastore.SetupPersistence(":memory:", os.TempDir())+ if err != nil {+ t.Fatalf("setup error: %s", err)+ }_datastore = dsfollowersRepo := followersrepository.New(ds)@@ -282,8 +295,10 @@ func TestSharedInboxPreferredOverIndividual(t *testing.T) {func TestIndividualInboxUsedWhenNoSharedInbox(t *testing.T) {// Set up a fresh database for this test- data.SetupPersistence(":memory:")- ds := data.GetDatastore()+ ds, err := datastore.SetupPersistence(":memory:", os.TempDir())+ if err != nil {+ t.Fatalf("setup error: %s", err)+ }_datastore = dsfollowersRepo := followersrepository.New(ds)diff --git a/activitypub/persistence/followersrepository/followersrepository.go b/services/activitypub/persistence/followersrepository/followersrepository.gosimilarity index 96%rename from activitypub/persistence/followersrepository/followersrepository.gorename to services/activitypub/persistence/followersrepository/followersrepository.goindex a4a197d594..577b371a13 100644--- a/activitypub/persistence/followersrepository/followersrepository.go+++ b/services/activitypub/persistence/followersrepository/followersrepository.go@@ -9,13 +9,14 @@ import ("github.com/go-fed/activity/streams""github.com/go-fed/activity/streams/vocab"- "github.com/owncast/owncast/activitypub/apmodels"- "github.com/owncast/owncast/core/data"+ "github.com/pkg/errors"+ log "github.com/sirupsen/logrus"+"github.com/owncast/owncast/db""github.com/owncast/owncast/models"+ "github.com/owncast/owncast/services/activitypub/apmodels"+ "github.com/owncast/owncast/services/datastore""github.com/owncast/owncast/utils"- "github.com/pkg/errors"- log "github.com/sirupsen/logrus")// FollowersRepository handles persistence of ActivityPub followers.@@ -54,23 +55,11 @@ type FollowersRepository interface {// SqlFollowersRepository is the SQL-based implementation of FollowersRepository.type SqlFollowersRepository struct {- datastore *data.Datastore-}--// NOTE: This is temporary during the transition period.-var temporaryGlobalInstance FollowersRepository--// Get returns the followers repository singleton.-func Get() FollowersRepository {- if temporaryGlobalInstance == nil {- i := New(data.GetDatastore())- temporaryGlobalInstance = i- }- return temporaryGlobalInstance+ datastore *datastore.Datastore}// New creates a new instance of the FollowersRepository.-func New(datastore *data.Datastore) FollowersRepository {+func New(datastore *datastore.Datastore) FollowersRepository {r := SqlFollowersRepository{datastore: datastore,}diff --git a/services/activitypub/persistence/persistence.go b/services/activitypub/persistence/persistence.gonew file mode 100644index 0000000000..254250588d--- /dev/null+++ b/services/activitypub/persistence/persistence.go@@ -0,0 +1,172 @@+// Package persistence is the storage layer for the ActivityPub+// subsystem: federated outbox posts, accepted inbound activities, and+// the followers fixture loader. Construct one in main.go (or via+// activitypub.New) with the datastore; everything else goes through the+// returned *Service.+package persistence++import (+ "context"+ "database/sql"+ "fmt"+ "time"++ "github.com/go-fed/activity/streams"+ "github.com/go-fed/activity/streams/vocab"+ "github.com/pkg/errors"+ log "github.com/sirupsen/logrus"++ "github.com/owncast/owncast/db"+ "github.com/owncast/owncast/models"+ apresolvers "github.com/owncast/owncast/services/activitypub/resolvers"+ "github.com/owncast/owncast/services/datastore"+)++// Service owns the ActivityPub persistence operations.+type Service struct {+ datastore *datastore.Datastore+ resolver *apresolvers.Resolver+}++// New constructs a persistence Service bound to the given datastore.+// Side effect: loads followers fixture data (no-op in the default build+// tag; populated when the `fixture` build tag is set). The resolver is+// required for outbox deserialization in GetOutbox; pass nil only if+// you do not call that method.+func New(ds *datastore.Datastore, resolver *apresolvers.Resolver) *Service {+ s := &Service{datastore: ds, resolver: resolver}+ s.addFollowersFixtureData()+ return s+}++// Datastore returns the underlying datastore. Provided so sub-services+// (followers repository, etc.) can be constructed from the same handle.+func (s *Service) Datastore() *datastore.Datastore {+ return s.datastore+}++// GetOutboxPostCount returns the number of posts in the outbox.+func (s *Service) GetOutboxPostCount() (int64, error) {+ ctx := context.Background()+ return s.datastore.GetQueries().GetLocalPostCount(ctx)+}++// GetOutbox returns an instance of the outbox populated by stored items.+func (s *Service) GetOutbox(limit int, offset int) (vocab.ActivityStreamsOrderedCollection, error) {+ collection := streams.NewActivityStreamsOrderedCollection()+ orderedItems := streams.NewActivityStreamsOrderedItemsProperty()+ rows, err := s.datastore.GetQueries().GetOutboxWithOffset(+ context.Background(),+ db.GetOutboxWithOffsetParams{Limit: int64(limit), Offset: int64(offset)},+ )+ if err != nil {+ return collection, err+ }++ for _, value := range rows {+ createCallback := func(c context.Context, activity vocab.ActivityStreamsCreate) error {+ orderedItems.AppendActivityStreamsCreate(activity)+ return nil+ }+ if err := s.resolver.Resolve(context.Background(), value, createCallback); err != nil {+ return collection, err+ }+ }++ return collection, nil+}++// AddToOutbox stores a single payload to the persistence layer.+func (s *Service) AddToOutbox(iri string, itemData []byte, typeString string, isLiveNotification bool) error {+ tx, err := s.datastore.DB.Begin()+ if err != nil {+ log.Debugln(err)+ }+ defer func() {+ _ = tx.Rollback()+ }()++ if err = s.datastore.GetQueries().WithTx(tx).AddToOutbox(context.Background(), db.AddToOutboxParams{+ Iri: iri,+ Value: itemData,+ Type: typeString,+ LiveNotification: sql.NullBool{Bool: isLiveNotification, Valid: true},+ }); err != nil {+ return fmt.Errorf("error creating new item in federation outbox %s", err)+ }++ return tx.Commit()+}++// GetObjectByIRI returns a string representation of a single object by the IRI.+func (s *Service) GetObjectByIRI(iri string) (string, bool, time.Time, error) {+ row, err := s.datastore.GetQueries().GetObjectFromOutboxByIRI(context.Background(), iri)+ return string(row.Value), row.LiveNotification.Bool, row.CreatedAt.Time, err+}++// GetLocalPostCount returns the number of posts existing locally.+func (s *Service) GetLocalPostCount() (int64, error) {+ ctx := context.Background()+ return s.datastore.GetQueries().GetLocalPostCount(ctx)+}++// SaveInboundFediverseActivity saves an event to the ap_inbound_activities table.+func (s *Service) SaveInboundFediverseActivity(objectIRI string, actorIRI string, eventType string, timestamp time.Time) error {+ if err := s.datastore.GetQueries().AddToAcceptedActivities(context.Background(), db.AddToAcceptedActivitiesParams{+ Iri: objectIRI,+ Actor: actorIRI,+ Type: eventType,+ Timestamp: timestamp,+ }); err != nil {+ return errors.Wrap(err, "error saving event "+objectIRI)+ }++ return nil+}++// GetInboundActivities returns a paginated collection of saved+// federated activities along with the total count.+func (s *Service) GetInboundActivities(limit int, offset int) ([]models.FederatedActivity, int, error) {+ ctx := context.Background()+ rows, err := s.datastore.GetQueries().GetInboundActivitiesWithOffset(ctx, db.GetInboundActivitiesWithOffsetParams{+ Limit: int64(limit),+ Offset: int64(offset),+ })+ if err != nil {+ return nil, 0, err+ }++ activities := make([]models.FederatedActivity, 0)++ total, err := s.datastore.GetQueries().GetInboundActivityCount(context.Background())+ if err != nil {+ return nil, 0, errors.Wrap(err, "unable to fetch total activity count")+ }++ for _, row := range rows {+ singleActivity := models.FederatedActivity{+ IRI: row.Iri,+ ActorIRI: row.Actor,+ Type: row.Type,+ Timestamp: row.Timestamp,+ }+ activities = append(activities, singleActivity)+ }++ return activities, int(total), nil+}++// HasPreviouslyHandledInboundActivity reports whether we have previously+// handled an inbound federated activity matching iri/actorIRI/eventType.+func (s *Service) HasPreviouslyHandledInboundActivity(iri string, actorIRI string, eventType string) (bool, error) {+ exists, err := s.datastore.GetQueries().DoesInboundActivityExist(context.Background(), db.DoesInboundActivityExistParams{+ Iri: iri,+ Actor: actorIRI,+ Type: eventType,+ })+ if err != nil {+ return false, err+ }++ return exists > 0, nil+}diff --git a/activitypub/requests/acceptFollow.go b/services/activitypub/requests/acceptFollow.gosimilarity index 61%rename from activitypub/requests/acceptFollow.gorename to services/activitypub/requests/acceptFollow.goindex 27b7787589..7ff17c24f9 100644--- a/activitypub/requests/acceptFollow.go+++ b/services/activitypub/requests/acceptFollow.go@@ -6,17 +6,20 @@ import ("github.com/go-fed/activity/streams""github.com/go-fed/activity/streams/vocab"- "github.com/owncast/owncast/activitypub/apmodels"- "github.com/owncast/owncast/activitypub/crypto"- "github.com/owncast/owncast/activitypub/workerpool"- "github.com/owncast/owncast/utils""github.com/pkg/errors"+ "github.com/owncast/owncast/services/activitypub/apmodels"+ "github.com/owncast/owncast/services/activitypub/crypto"+ "github.com/owncast/owncast/services/activitypub/workerpool"+ "github.com/owncast/owncast/utils"+"github.com/teris-io/shortid")-// SendFollowAccept will send an accept activity to a follow request from a specified local user.-func SendFollowAccept(inbox *url.URL, originalFollowActivity vocab.ActivityStreamsFollow, fromLocalAccountName string) error {+// SendFollowAccept will send an accept activity to a follow request+// from a specified local user, queuing the outbound delivery on the+// provided workerpool.+func SendFollowAccept(wp *workerpool.Service, inbox *url.URL, originalFollowActivity vocab.ActivityStreamsFollow, fromLocalAccountName string, builder *apmodels.Builder, signer *crypto.Signer) error {// SSRF protection: reject non-HTTPS schemes and internal/loopback hosts.if inbox.Scheme != "https" {return errors.Errorf("rejecting non-HTTPS inbox URL for SSRF protection: %s", inbox.String())@@ -25,26 +28,26 @@ func SendFollowAccept(inbox *url.URL, originalFollowActivity vocab.ActivityStreareturn errors.Errorf("rejecting internal/loopback inbox URL for SSRF protection: %s", inbox.String())}- followAccept := makeAcceptFollow(originalFollowActivity, fromLocalAccountName)- localAccountIRI := apmodels.MakeLocalIRIForAccount(fromLocalAccountName)+ followAccept := makeAcceptFollow(originalFollowActivity, fromLocalAccountName, builder)+ localAccountIRI := builder.MakeLocalIRIForAccount(fromLocalAccountName)var jsonmap map[string]interface{}jsonmap, _ = streams.Serialize(followAccept)b, _ := json.Marshal(jsonmap)- req, err := crypto.CreateSignedRequest(b, inbox, localAccountIRI)+ req, err := signer.CreateSignedRequest(b, inbox, localAccountIRI)if err != nil {return err}- workerpool.AddToOutboundQueue(req)+ wp.AddToOutboundQueue(req)return nil}-func makeAcceptFollow(originalFollowActivity vocab.ActivityStreamsFollow, fromAccountName string) vocab.ActivityStreamsAccept {+func makeAcceptFollow(originalFollowActivity vocab.ActivityStreamsFollow, fromAccountName string, builder *apmodels.Builder) vocab.ActivityStreamsAccept {acceptIDString := shortid.MustGenerate()- acceptID := apmodels.MakeLocalIRIForResource(acceptIDString)- actorID := apmodels.MakeLocalIRIForAccount(fromAccountName)+ acceptID := builder.MakeLocalIRIForResource(acceptIDString)+ actorID := builder.MakeLocalIRIForAccount(fromAccountName)accept := streams.NewActivityStreamsAccept()idProperty := streams.NewJSONLDIdProperty()diff --git a/activitypub/requests/http.go b/services/activitypub/requests/http.gosimilarity index 78%rename from activitypub/requests/http.gorename to services/activitypub/requests/http.goindex 1c879cb7b0..81b33889bc 100644--- a/activitypub/requests/http.go+++ b/services/activitypub/requests/http.go@@ -9,14 +9,15 @@ import ("github.com/go-fed/activity/streams""github.com/go-fed/activity/streams/vocab"- "github.com/owncast/owncast/activitypub/crypto"+"github.com/owncast/owncast/config"+ "github.com/owncast/owncast/services/activitypub/crypto"log "github.com/sirupsen/logrus")// WriteStreamResponse will write a ActivityPub object to the provided ResponseWriter and sign with the provided key.-func WriteStreamResponse(item vocab.Type, w http.ResponseWriter, publicKey crypto.PublicKey) error {+func WriteStreamResponse(item vocab.Type, w http.ResponseWriter, publicKey crypto.PublicKey, signer *crypto.Signer) error {var jsonmap map[string]interface{}jsonmap, _ = streams.Serialize(item)b, err := json.Marshal(jsonmap)@@ -24,24 +25,24 @@ func WriteStreamResponse(item vocab.Type, w http.ResponseWriter, publicKey cryptreturn err}- return WriteResponse(b, w, publicKey)+ return WriteResponse(b, w, publicKey, signer)}// WritePayloadResponse will write any arbitrary object to the provided ResponseWriter and sign with the provided key.-func WritePayloadResponse(payload interface{}, w http.ResponseWriter, publicKey crypto.PublicKey) error {+func WritePayloadResponse(payload interface{}, w http.ResponseWriter, publicKey crypto.PublicKey, signer *crypto.Signer) error {b, err := json.Marshal(payload)if err != nil {return err}- return WriteResponse(b, w, publicKey)+ return WriteResponse(b, w, publicKey, signer)}// WriteResponse will write any arbitrary payload to the provided ResponseWriter and sign with the provided key.-func WriteResponse(payload []byte, w http.ResponseWriter, publicKey crypto.PublicKey) error {+func WriteResponse(payload []byte, w http.ResponseWriter, publicKey crypto.PublicKey, signer *crypto.Signer) error {w.Header().Set("Content-Type", "application/activity+json")- if err := crypto.SignResponse(w, payload, publicKey); err != nil {+ if err := signer.SignResponse(w, payload, publicKey); err != nil {w.WriteHeader(http.StatusInternalServerError)log.Errorln("unable to sign response", err)return err@@ -56,7 +57,7 @@ func WriteResponse(payload []byte, w http.ResponseWriter, publicKey crypto.Publi}// CreateSignedRequest will create a signed POST request of a payload to the provided destination.-func CreateSignedRequest(payload []byte, url *url.URL, fromActorIRI *url.URL) (*http.Request, error) {+func CreateSignedRequest(payload []byte, url *url.URL, fromActorIRI *url.URL, signer *crypto.Signer) (*http.Request, error) {log.Debugln("Sending", string(payload), "to", url)req, _ := http.NewRequest(http.MethodPost, url.String(), bytes.NewBuffer(payload))@@ -65,7 +66,7 @@ func CreateSignedRequest(payload []byte, url *url.URL, fromActorIRI *url.URL) (*req.Header.Set("User-Agent", ua)req.Header.Set("Content-Type", "application/activity+json")- if err := crypto.SignRequest(req, payload, fromActorIRI); err != nil {+ if err := signer.SignRequest(req, payload, fromActorIRI); err != nil {log.Errorln("error signing request:", err)return nil, err}diff --git a/activitypub/resolvers/follow.go b/services/activitypub/resolvers/follow.gosimilarity index 67%rename from activitypub/resolvers/follow.gorename to services/activitypub/resolvers/follow.goindex fabb4df243..237cf22c9d 100644--- a/activitypub/resolvers/follow.go+++ b/services/activitypub/resolvers/follow.go@@ -5,18 +5,19 @@ import ("fmt""github.com/go-fed/activity/streams/vocab"- "github.com/owncast/owncast/activitypub/apmodels""github.com/pkg/errors"log "github.com/sirupsen/logrus"++ "github.com/owncast/owncast/services/activitypub/apmodels")-func getPersonFromFollow(activity vocab.ActivityStreamsFollow) (apmodels.ActivityPubActor, error) {- return GetResolvedActorFromActorProperty(activity.GetActivityStreamsActor())+func (r *Resolver) getPersonFromFollow(activity vocab.ActivityStreamsFollow) (apmodels.ActivityPubActor, error) {+ return r.GetResolvedActorFromActorProperty(activity.GetActivityStreamsActor())}// MakeFollowRequest will convert an inbound Follow request to our internal actor model.-func MakeFollowRequest(c context.Context, activity vocab.ActivityStreamsFollow) (*apmodels.ActivityPubActor, error) {- person, err := getPersonFromFollow(activity)+func (r *Resolver) MakeFollowRequest(c context.Context, activity vocab.ActivityStreamsFollow) (*apmodels.ActivityPubActor, error) {+ person, err := r.getPersonFromFollow(activity)if err != nil {return nil, errors.Wrap(err, "unable to resolve person from follow request")}@@ -40,8 +41,8 @@ func MakeFollowRequest(c context.Context, activity vocab.ActivityStreamsFollow)}// MakeUnFollowRequest will convert an inbound Unfollow request to our internal actor model.-func MakeUnFollowRequest(c context.Context, activity vocab.ActivityStreamsUndo) *apmodels.ActivityPubActor {- person, err := GetResolvedActorFromActorProperty(activity.GetActivityStreamsActor())+func (r *Resolver) MakeUnFollowRequest(c context.Context, activity vocab.ActivityStreamsUndo) *apmodels.ActivityPubActor {+ person, err := r.GetResolvedActorFromActorProperty(activity.GetActivityStreamsActor())if err != nil {log.Errorln("unable to resolve person from actor iri", person.ActorIri, err)return nildiff --git a/activitypub/resolvers/nil_safety_test.go b/services/activitypub/resolvers/nil_safety_test.gosimilarity index 84%rename from activitypub/resolvers/nil_safety_test.gorename to services/activitypub/resolvers/nil_safety_test.goindex 9b8278eee8..0ac656620b 100644--- a/activitypub/resolvers/nil_safety_test.go+++ b/services/activitypub/resolvers/nil_safety_test.go@@ -15,6 +15,11 @@ func mustParseURL(s string) *url.URL {return u}+// testResolver carries no deps. Every assertion in this file exercises+// an early-error path inside GetResolvedActorFromActorProperty (nil or+// empty actor property), which returns before deps are touched.+var testResolver = &Resolver{}+// TestGetResolvedActorFromActorPropertyWithNil verifies that the function// doesn't panic when given a nil actor property.func TestGetResolvedActorFromActorPropertyWithNil(t *testing.T) {@@ -24,7 +29,7 @@ func TestGetResolvedActorFromActorPropertyWithNil(t *testing.T) {}}()- _, err := GetResolvedActorFromActorProperty(nil)+ _, err := testResolver.GetResolvedActorFromActorProperty(nil)if err == nil {t.Error("GetResolvedActorFromActorProperty(nil) should return error")}@@ -40,7 +45,7 @@ func TestGetResolvedActorFromActorPropertyWithEmpty(t *testing.T) {}()actor := streams.NewActivityStreamsActorProperty()- _, err := GetResolvedActorFromActorProperty(actor)+ _, err := testResolver.GetResolvedActorFromActorProperty(actor)if err == nil {t.Error("GetResolvedActorFromActorProperty with empty actor should return error")}@@ -69,7 +74,7 @@ func TestGetResolvedActorFromActorPropertyWithPersonMissingFields(t *testing.T)// Person has no ID, inbox, username, or public keyactor.AppendActivityStreamsPerson(person)- _, err := GetResolvedActorFromActorProperty(actor)+ _, err := testResolver.GetResolvedActorFromActorProperty(actor)if err == nil {t.Error("GetResolvedActorFromActorProperty with incomplete Person should return error")}@@ -89,7 +94,7 @@ func TestGetResolvedActorFromActorPropertyWithServiceMissingFields(t *testing.T)// Service has no ID, inbox, username, or public keyactor.AppendActivityStreamsService(service)- _, err := GetResolvedActorFromActorProperty(actor)+ _, err := testResolver.GetResolvedActorFromActorProperty(actor)if err == nil {t.Error("GetResolvedActorFromActorProperty with incomplete Service should return error")}@@ -109,7 +114,7 @@ func TestGetResolvedActorFromActorPropertyWithApplicationMissingFields(t *testin// Application has no ID, inbox, username, or public keyactor.AppendActivityStreamsApplication(app)- _, err := GetResolvedActorFromActorProperty(actor)+ _, err := testResolver.GetResolvedActorFromActorProperty(actor)if err == nil {t.Error("GetResolvedActorFromActorProperty with incomplete Application should return error")}@@ -124,7 +129,7 @@ func TestNilSafetyNoPanic(t *testing.T) {t.Errorf("panicked: %v", r)}}()- _, _ = GetResolvedActorFromActorProperty(nil)+ _, _ = testResolver.GetResolvedActorFromActorProperty(nil)})t.Run("GetResolvedActorFromActorProperty with empty", func(t *testing.T) {@@ -133,7 +138,7 @@ func TestNilSafetyNoPanic(t *testing.T) {t.Errorf("panicked: %v", r)}}()- _, _ = GetResolvedActorFromActorProperty(streams.NewActivityStreamsActorProperty())+ _, _ = testResolver.GetResolvedActorFromActorProperty(streams.NewActivityStreamsActorProperty())})t.Run("GetResolvedActorFromActorProperty with Person no fields", func(t *testing.T) {@@ -144,7 +149,7 @@ func TestNilSafetyNoPanic(t *testing.T) {}()actor := streams.NewActivityStreamsActorProperty()actor.AppendActivityStreamsPerson(streams.NewActivityStreamsPerson())- _, _ = GetResolvedActorFromActorProperty(actor)+ _, _ = testResolver.GetResolvedActorFromActorProperty(actor)})t.Run("GetResolvedActorFromActorProperty with Service no fields", func(t *testing.T) {@@ -155,7 +160,7 @@ func TestNilSafetyNoPanic(t *testing.T) {}()actor := streams.NewActivityStreamsActorProperty()actor.AppendActivityStreamsService(streams.NewActivityStreamsService())- _, _ = GetResolvedActorFromActorProperty(actor)+ _, _ = testResolver.GetResolvedActorFromActorProperty(actor)})t.Run("GetResolvedActorFromActorProperty with Application no fields", func(t *testing.T) {@@ -166,6 +171,6 @@ func TestNilSafetyNoPanic(t *testing.T) {}()actor := streams.NewActivityStreamsActorProperty()actor.AppendActivityStreamsApplication(streams.NewActivityStreamsApplication())- _, _ = GetResolvedActorFromActorProperty(actor)+ _, _ = testResolver.GetResolvedActorFromActorProperty(actor)})}diff --git a/activitypub/resolvers/resolve.go b/services/activitypub/resolvers/resolve.gosimilarity index 84%rename from activitypub/resolvers/resolve.gorename to services/activitypub/resolvers/resolve.goindex 8efada6c92..4a797e355e 100644--- a/activitypub/resolvers/resolve.go+++ b/services/activitypub/resolvers/resolve.go@@ -8,16 +8,15 @@ import ("github.com/go-fed/activity/streams""github.com/go-fed/activity/streams/vocab"- "github.com/owncast/owncast/activitypub/apmodels"- "github.com/owncast/owncast/activitypub/crypto"- "github.com/owncast/owncast/persistence/configrepository"- "github.com/owncast/owncast/utils""github.com/pkg/errors"log "github.com/sirupsen/logrus"++ "github.com/owncast/owncast/services/activitypub/apmodels"+ "github.com/owncast/owncast/utils")// Resolve will translate a raw ActivityPub payload and fire the callback associated with that activity type.-func Resolve(c context.Context, data []byte, callbacks ...interface{}) error {+func (r *Resolver) Resolve(c context.Context, data []byte, callbacks ...interface{}) error {jsonResolver, err := streams.NewJSONResolver(callbacks...)if err != nil {// Something in the setup was wrong. For example, a callback has an@@ -48,15 +47,14 @@ func Resolve(c context.Context, data []byte, callbacks ...interface{}) error {// ResolveIRI will resolve an IRI and call the correct callback for the resolved type.// Uses a retryable HTTP client for resilience against transient failures.-func ResolveIRI(c context.Context, iri string, callbacks ...interface{}) error {- configRepository := configrepository.Get()+func (r *Resolver) ResolveIRI(c context.Context, iri string, callbacks ...interface{}) error {log.Debugln("Resolving", iri)req, _ := http.NewRequest(http.MethodGet, iri, nil)req.Header.Set("Accept", "application/activity+json, application/ld+json")- actor := apmodels.MakeLocalIRIForAccount(configRepository.GetDefaultFederationUsername())- if err := crypto.SignRequest(req, nil, actor); err != nil {+ actor := r.builder.MakeLocalIRIForAccount(r.configRepository.GetDefaultFederationUsername())+ if err := r.signer.SignRequest(req, nil, actor); err != nil {return err}@@ -77,13 +75,13 @@ func ResolveIRI(c context.Context, iri string, callbacks ...interface{}) error {return err}- return Resolve(c, data, callbacks...)+ return r.Resolve(c, data, callbacks...)}// GetResolvedActorFromActorProperty resolve an external actor property to a// fully populated internal actor representation.// Returns an error if the actor cannot be resolved or is missing required fields.-func GetResolvedActorFromActorProperty(actor vocab.ActivityStreamsActorProperty) (apmodels.ActivityPubActor, error) {+func (r *Resolver) GetResolvedActorFromActorProperty(actor vocab.ActivityStreamsActorProperty) (apmodels.ActivityPubActor, error) {var apActor apmodels.ActivityPubActorif actor == nil || actor.Empty() || actor.Len() == 0 || actor.At(0) == nil {@@ -100,7 +98,7 @@ func GetResolvedActorFromActorProperty(actor vocab.ActivityStreamsActorProperty)if iri == nil {return apActor, errors.New("actor IRI is nil despite IsIRI() returning true")}- return GetResolvedActorFromIRI(iri.String())+ return r.GetResolvedActorFromIRI(iri.String())}if actorObjectOrIRI.IsActivityStreamsPerson() {@@ -124,7 +122,7 @@ func GetResolvedActorFromActorProperty(actor vocab.ActivityStreamsActorProperty)}// GetResolvedPublicKeyFromIRI will resolve a publicKey IRI string to a vocab.W3IDSecurityV1PublicKey.-func GetResolvedPublicKeyFromIRI(publicKeyIRI string) (vocab.W3IDSecurityV1PublicKey, error) {+func (r *Resolver) GetResolvedPublicKeyFromIRI(publicKeyIRI string) (vocab.W3IDSecurityV1PublicKey, error) {var err errorvar pubkey vocab.W3IDSecurityV1PublicKeyresolved := false@@ -174,7 +172,7 @@ func GetResolvedPublicKeyFromIRI(publicKeyIRI string) (vocab.W3IDSecurityV1Publireturn nil}- if e := ResolveIRI(context.Background(), publicKeyIRI, personCallback, serviceCallback, applicationCallback, pubkeyCallback); e != nil {+ if e := r.ResolveIRI(context.Background(), publicKeyIRI, personCallback, serviceCallback, applicationCallback, pubkeyCallback); e != nil {err = e}@@ -191,7 +189,7 @@ func GetResolvedPublicKeyFromIRI(publicKeyIRI string) (vocab.W3IDSecurityV1Publi// GetResolvedActorFromIRI will resolve an IRI string to a fully populated actor.// Returns an error if the actor cannot be resolved or is missing required fields.-func GetResolvedActorFromIRI(personOrServiceIRI string) (apmodels.ActivityPubActor, error) {+func (r *Resolver) GetResolvedActorFromIRI(personOrServiceIRI string) (apmodels.ActivityPubActor, error) {var resolveErr errorvar apActor apmodels.ActivityPubActorresolved := false@@ -226,7 +224,7 @@ func GetResolvedActorFromIRI(personOrServiceIRI string) (apmodels.ActivityPubActreturn nil}- if e := ResolveIRI(context.Background(), personOrServiceIRI, personCallback, serviceCallback, applicationCallback); e != nil {+ if e := r.ResolveIRI(context.Background(), personOrServiceIRI, personCallback, serviceCallback, applicationCallback); e != nil {resolveErr = errors.Wrap(e, "error resolving actor from IRI")}diff --git a/services/activitypub/resolvers/resolver.go b/services/activitypub/resolvers/resolver.gonew file mode 100644index 0000000000..09fb09c073--- /dev/null+++ b/services/activitypub/resolvers/resolver.go@@ -0,0 +1,39 @@+// Package resolvers translates raw ActivityPub payloads and IRIs into+// our internal actor model: fetching, signing, resolving callbacks, and+// constructing follow/unfollow request representations. Construct a+// *Resolver in main.go with New(Deps) and pass it to consumers+// (inbox.*Service, jobs.*Service, outbox.*Service, persistence.*Service)+// via their own Deps structs.+package resolvers++import (+ "github.com/owncast/owncast/persistence/configrepository"+ "github.com/owncast/owncast/services/activitypub/apmodels"+ "github.com/owncast/owncast/services/activitypub/crypto"+)++// Resolver is the dependency-bearing handle for the ActivityPub+// resolver helpers. It reads federation defaults from+// configRepository, signs outbound requests with the *crypto.Signer,+// and uses the *apmodels.Builder for local IRI construction.+type Resolver struct {+ configRepository configrepository.ConfigRepository+ builder *apmodels.Builder+ signer *crypto.Signer+}++// Deps is the explicit dependency contract for Resolver.+type Deps struct {+ ConfigRepository configrepository.ConfigRepository+ Builder *apmodels.Builder+ Signer *crypto.Signer+}++// New constructs a Resolver with the provided dependencies.+func New(deps Deps) *Resolver {+ return &Resolver{+ configRepository: deps.ConfigRepository,+ builder: deps.Builder,+ signer: deps.Signer,+ }+}diff --git a/activitypub/webfinger/webfinger.go b/services/activitypub/webfinger/webfinger.gosimilarity index 100%rename from activitypub/webfinger/webfinger.gorename to services/activitypub/webfinger/webfinger.godiff --git a/services/activitypub/workerpool/outbound.go b/services/activitypub/workerpool/outbound.gonew file mode 100644index 0000000000..7e78723a3b--- /dev/null+++ b/services/activitypub/workerpool/outbound.go@@ -0,0 +1,177 @@+// Package workerpool is the outbound HTTP delivery pool for the+// ActivityPub subsystem. It maintains a bounded worker pool that posts+// signed activities to follower inboxes, with per-domain circuit+// breaking on repeated failure.+package workerpool++import (+ "net/http"+ "sync"+ "time"++ log "github.com/sirupsen/logrus"++ "github.com/owncast/owncast/utils"+)++// Job bundles a single outbound HTTP request for a worker.+type Job struct {+ request *http.Request+}++// circuitBreakerBackoffDurations is the exponential backoff schedule+// applied to a domain after consecutive delivery failures.+var circuitBreakerBackoffDurations = []time.Duration{+ 1 * time.Minute,+ 5 * time.Minute,+ 15 * time.Minute,+ 30 * time.Minute,+ 60 * time.Minute,+}++// Service owns the worker pool, HTTP client, and per-domain circuit+// breaker state. Construct with New(workerPoolSize) then call Start to+// spin up workers.+type Service struct {+ workerPoolSize int++ queue chan Job+ httpClient *http.Client++ failedDomainsMu sync.RWMutex+ failedDomains map[string]*domainFailure+}++type domainFailure struct {+ count int+ lastFailed time.Time+ backoffUntil time.Time+}++// New constructs an idle Service sized for the given worker count. Call+// Start to bind the HTTP client and launch the worker goroutines.+func New(workerPoolSize int) *Service {+ return &Service{+ workerPoolSize: workerPoolSize,+ failedDomains: make(map[string]*domainFailure),+ }+}++// Start initializes the HTTP client and worker goroutines. Safe to call+// once; subsequent calls reset the pool.+func (s *Service) Start() {+ // Use a larger buffer to decouple request creation from processing.+ // This prevents SendToFollowers from blocking when many followers+ // need updates.+ const minQueueBuffer = 500+ queueBuffer := s.workerPoolSize * 10+ if queueBuffer < minQueueBuffer {+ queueBuffer = minQueueBuffer+ }+ s.queue = make(chan Job, queueBuffer)++ // HTTP client with retry logic for transient failures (502/503/504).+ s.httpClient = utils.GetRetryableHTTPClient()++ for i := 1; i <= s.workerPoolSize; i++ {+ go s.worker(i)+ }+}++// AddToOutboundQueue queues an outbound HTTP request for delivery.+func (s *Service) AddToOutboundQueue(req *http.Request) {+ if s.ShouldSkipDomain(req.URL.Host) {+ log.Debugf("Skipping request to %s due to circuit breaker", req.URL.Host)+ return+ }++ select {+ case s.queue <- Job{req}:+ default:+ log.Debugln("Outbound ActivityPub job queue is full")+ s.queue <- Job{req} // blocks until a worker drains+ }+ log.Tracef("Queued request for ActivityPub destination %s", req.RequestURI)+}++func (s *Service) worker(workerID int) {+ log.Debugf("Started ActivityPub worker %d", workerID)++ for job := range s.queue {+ if err := s.sendActivityPubMessageToInbox(job); err != nil {+ log.Errorf("ActivityPub destination %s failed to send Error: %s", job.request.RequestURI, err)+ s.recordDomainFailure(job.request.URL.Host)+ } else {+ s.resetDomainFailure(job.request.URL.Host)+ }+ log.Tracef("Done with ActivityPub destination %s using worker %d", job.request.RequestURI, workerID)+ }+}++func (s *Service) sendActivityPubMessageToInbox(job Job) error {+ resp, err := s.httpClient.Do(job.request)+ if err != nil {+ return err+ }+ defer resp.Body.Close()++ // HTTP 4xx and 5xx count as failures for circuit-breaker purposes.+ if resp.StatusCode >= 400 {+ return &httpError{statusCode: resp.StatusCode, message: resp.Status}+ }+ return nil+}++// httpError represents an HTTP error response.+type httpError struct {+ statusCode int+ message string+}++func (e *httpError) Error() string { return e.message }++// ShouldSkipDomain reports whether the given domain is currently inside+// its circuit-breaker backoff window.+func (s *Service) ShouldSkipDomain(domain string) bool {+ s.failedDomainsMu.RLock()+ defer s.failedDomainsMu.RUnlock()++ failure, exists := s.failedDomains[domain]+ if !exists {+ return false+ }+ return time.Now().Before(failure.backoffUntil)+}++func (s *Service) recordDomainFailure(domain string) {+ s.failedDomainsMu.Lock()+ defer s.failedDomainsMu.Unlock()++ failure, exists := s.failedDomains[domain]+ if !exists {+ failure = &domainFailure{}+ s.failedDomains[domain] = failure+ }++ failure.count+++ failure.lastFailed = time.Now()++ backoffIndex := failure.count - 1+ if backoffIndex >= len(circuitBreakerBackoffDurations) {+ backoffIndex = len(circuitBreakerBackoffDurations) - 1+ }+ backoffDuration := circuitBreakerBackoffDurations[backoffIndex]+ failure.backoffUntil = time.Now().Add(backoffDuration)++ log.Warnf("Domain %s failed %d times, backing off for %v", domain, failure.count, backoffDuration)+}++func (s *Service) resetDomainFailure(domain string) {+ s.failedDomainsMu.Lock()+ defer s.failedDomainsMu.Unlock()++ if failure, exists := s.failedDomains[domain]; exists && failure.count > 0 {+ log.Debugf("Resetting failure count for domain %s after successful delivery", domain)+ delete(s.failedDomains, domain)+ }+}diff --git a/services/activitypub/workerpool/outbound_test.go b/services/activitypub/workerpool/outbound_test.gonew file mode 100644index 0000000000..4a8d0a698c--- /dev/null+++ b/services/activitypub/workerpool/outbound_test.go@@ -0,0 +1,112 @@+package workerpool++import (+ "testing"+ "time"+)++func newTestService() *Service {+ return New(1)+}++func TestCircuitBreaker(t *testing.T) {+ s := newTestService()++ testDomain := "failing.example.com"++ // Initially, domain should not be skipped.+ if s.ShouldSkipDomain(testDomain) {+ t.Error("Domain should not be skipped initially")+ }++ // Record failures.+ s.recordDomainFailure(testDomain)+ s.recordDomainFailure(testDomain)+ s.recordDomainFailure(testDomain)++ // Domain should now be skipped.+ if !s.ShouldSkipDomain(testDomain) {+ t.Error("Domain should be skipped after failures")+ }++ // After successful delivery, domain should be reset.+ s.resetDomainFailure(testDomain)+ if s.ShouldSkipDomain(testDomain) {+ t.Error("Domain should not be skipped after reset")+ }+}++func TestHTTPTimeouts(t *testing.T) {+ s := New(1)+ s.Start()++ if s.httpClient == nil {+ t.Error("HTTP client should be initialized")+ }++ if s.httpClient.Timeout != 8*time.Second {+ t.Errorf("HTTP client should have 8 second timeout, got %v", s.httpClient.Timeout)+ }+}++func TestWorkerPoolSizing(t *testing.T) {+ // Queue buffer should be at least the 500-item minimum even for+ // small worker pools.+ s := New(5)+ s.Start()+ if cap(s.queue) < 500 {+ t.Errorf("Queue capacity should be at least 500, got %d", cap(s.queue))+ }++ // Larger worker pools get proportionally larger buffers.+ s2 := New(100)+ s2.Start()+ if cap(s2.queue) != 1000 {+ t.Errorf("Queue capacity should be 1000 for 100 workers, got %d", cap(s2.queue))+ }+}++func TestBackoffDurations(t *testing.T) {+ expectedDurations := []time.Duration{+ 1 * time.Minute,+ 5 * time.Minute,+ 15 * time.Minute,+ 30 * time.Minute,+ 60 * time.Minute,+ }++ if len(circuitBreakerBackoffDurations) != len(expectedDurations) {+ t.Errorf("Expected %d backoff durations, got %d", len(expectedDurations), len(circuitBreakerBackoffDurations))+ }++ for i, expected := range expectedDurations {+ if circuitBreakerBackoffDurations[i] != expected {+ t.Errorf("Backoff duration at index %d: expected %v, got %v", i, expected, circuitBreakerBackoffDurations[i])+ }+ }+}++func TestCircuitBreakerIsolation(t *testing.T) {+ s := newTestService()++ domain1 := "test1.example.com"+ domain2 := "test2.example.com"++ // Neither domain should be blocked initially.+ if s.ShouldSkipDomain(domain1) || s.ShouldSkipDomain(domain2) {+ t.Error("Domains should not be blocked initially")+ }++ // Record failures for domain1 only.+ s.recordDomainFailure(domain1)+ s.recordDomainFailure(domain1)+ s.recordDomainFailure(domain1)++ // Only domain1 should be blocked.+ if !s.ShouldSkipDomain(domain1) {+ t.Error("Domain1 should be blocked after failures")+ }+ if s.ShouldSkipDomain(domain2) {+ t.Error("Domain2 should not be blocked")+ }+}diff --git a/services/cache/cache.go b/services/cache/cache.gonew file mode 100644index 0000000000..1b58070ab7--- /dev/null+++ b/services/cache/cache.go@@ -0,0 +1,71 @@+// Package cache is a registry of named TTL-keyed caches. A Container is+// constructed once in main() and injected into any service that needs to+// cache byte payloads with an expiration.+package cache++import (+ "sync"+ "time"++ "github.com/jellydator/ttlcache/v3"+)++// Container is a registry of named caches. Use New() to construct one in+// main() and pass it to consumers as a constructor dependency.+type Container struct {+ mu sync.Mutex+ caches map[string]*Instance+}++// Instance is a single TTL-keyed cache.+type Instance struct {+ cache *ttlcache.Cache[string, []byte]+}++// New returns an empty Container.+func New() *Container {+ return &Container{caches: make(map[string]*Instance)}+}++// GetOrCreate returns the named cache, creating it with the given TTL on+// first use. Concurrent calls are safe.+func (c *Container) GetOrCreate(name string, ttl time.Duration) *Instance {+ c.mu.Lock()+ defer c.mu.Unlock()+ if existing, ok := c.caches[name]; ok {+ return existing+ }+ cache := ttlcache.New[string, []byte](+ ttlcache.WithTTL[string, []byte](ttl),+ ttlcache.WithDisableTouchOnHit[string, []byte](),+ )+ inst := &Instance{cache: cache}+ c.caches[name] = inst+ go cache.Start()+ return inst+}++// Stop halts every cache's TTL-eviction goroutine. Safe to call once at+// shutdown.+func (c *Container) Stop() {+ c.mu.Lock()+ defer c.mu.Unlock()+ for _, inst := range c.caches {+ inst.cache.Stop()+ }+}++// Get fetches the value for the given key. Returns nil if the key is+// absent or has expired.+func (i *Instance) Get(key string) []byte {+ v := i.cache.Get(key, ttlcache.WithDisableTouchOnHit[string, []byte]())+ if v == nil || v.IsExpired() {+ return nil+ }+ return v.Value()+}++// Set stores the value for the given key under the cache's configured TTL.+func (i *Instance) Set(key string, value []byte) {+ i.cache.Set(key, value, 0)+}diff --git a/services/cache/cache_test.go b/services/cache/cache_test.gonew file mode 100644index 0000000000..56f38fb7db--- /dev/null+++ b/services/cache/cache_test.go@@ -0,0 +1,77 @@+package cache++import (+ "strconv"+ "testing"+ "time"++ "github.com/stretchr/testify/assert"+)++func TestExpiration(t *testing.T) {+ ttl := 500 * time.Millisecond+ c := New()+ defer c.Stop()++ inst := c.GetOrCreate("expiring", ttl)+ inst.Set("k", []byte("v"))++ if got := inst.Get("k"); string(got) != "v" {+ t.Fatalf("immediate read: got %q want %q", got, "v")+ }++ time.Sleep(ttl + 250*time.Millisecond)+ if got := inst.Get("k"); got != nil {+ t.Errorf("after TTL: expected nil, got %q", got)+ }+}++func TestGetOrCreateReusesInstance(t *testing.T) {+ c := New()+ defer c.Stop()++ a := c.GetOrCreate("named", time.Minute)+ b := c.GetOrCreate("named", time.Minute)+ assert.Same(t, a, b, "GetOrCreate must return the same Instance for the same name")+}++func TestMissingKeyReturnsNil(t *testing.T) {+ c := New()+ defer c.Stop()++ inst := c.GetOrCreate("empty", time.Minute)+ assert.Nil(t, inst.Get("never-set"))+}++func TestConcurrentSetAndGet(t *testing.T) {+ c := New()+ defer c.Stop()++ inst := c.GetOrCreate("concurrent", 5*time.Second)+ const goroutines = 10++ done := make(chan struct{})+ for i := 0; i < goroutines; i++ {+ go func(idx int) {+ defer func() { done <- struct{}{} }()++ key := "key" + strconv.Itoa(idx)+ val := "val" + strconv.Itoa(idx)+ inst.Set(key, []byte(val))+ time.Sleep(50 * time.Millisecond)+ assert.Equal(t, val, string(inst.Get(key)))+ }(i)+ }+ for i := 0; i < goroutines; i++ {+ <-done+ }+}++func TestStopIsIdempotent(t *testing.T) {+ c := New()+ c.GetOrCreate("a", time.Minute)+ c.GetOrCreate("b", time.Minute)+ c.Stop()+ // Calling Stop on an empty container after Stop should not panic.+ c.Stop()+}diff --git a/services/chat/chat.go b/services/chat/chat.gonew file mode 100644index 0000000000..9fe1f8ef43--- /dev/null+++ b/services/chat/chat.go@@ -0,0 +1,216 @@+// Package chat is the chat subsystem service: a websocket server that+// accepts client connections, broadcasts inbound messages, fans out+// system + action messages, and forwards chat events to webhooks.+// Construct via New(Deps) and call Start to launch the broadcast loop.+package chat++import (+ "errors"+ "net/http"+ "sort"++ "github.com/prometheus/client_golang/prometheus"+ "github.com/prometheus/client_golang/prometheus/promauto"+ log "github.com/sirupsen/logrus"++ "github.com/owncast/owncast/config"+ "github.com/owncast/owncast/models"+ "github.com/owncast/owncast/persistence/authrepository"+ "github.com/owncast/owncast/persistence/chatmessagerepository"+ "github.com/owncast/owncast/persistence/configrepository"+ "github.com/owncast/owncast/persistence/userrepository"+ "github.com/owncast/owncast/services/chat/events"+ "github.com/owncast/owncast/services/datastore"+ "github.com/owncast/owncast/services/webhooks"+)++// Deps lists the explicit dependencies for the chat Service.+type Deps struct {+ GetStatus func() models.Status+ Webhooks *webhooks.Service+ Datastore *datastore.Datastore+ ConfigRepository configrepository.ConfigRepository+ AuthRepository authrepository.AuthRepository+ ChatMessageRepository chatmessagerepository.ChatMessageRepository+ UserRepository userrepository.UserRepository+}++// New constructs a chat Service. Call Start to launch the broadcast+// loop and register the Prometheus counter.+func New(deps Deps) *Service {+ s := newServer(deps.Webhooks)+ s.getStatus = deps.GetStatus+ s.datastore = deps.Datastore+ s.configRepository = deps.ConfigRepository+ s.authRepository = deps.AuthRepository+ s.chatMessageRepository = deps.ChatMessageRepository+ s.userRepository = deps.UserRepository+ return s+}++// SetGetStatus wires (or rewires) the stream-status callback. Exists+// because the composition root has a small cycle: chat needs+// stream.GetStatus; the stream service needs *chat.Service. main.go+// constructs chat first with a nil callback, then fills it in once+// streamSvc exists. Must be called before Start.+func (s *Service) SetGetStatus(fn func() models.Status) {+ s.getStatus = fn+}++// Start initializes persistence, launches the broadcast loop, and+// registers the Prometheus counter. Safe to call once.+func (s *Service) Start() error {+ s.setupPersistence()++ go s.Run()++ log.Traceln("Chat server started with max connection count of", s.maxSocketConnectionLimit)++ s.chatMessagesSentCounter = promauto.NewGauge(prometheus.GaugeOpts{+ Name: "total_chat_message_count",+ Help: "The number of chat messages incremented over time.",+ ConstLabels: map[string]string{+ "version": config.VersionNumber,+ "host": s.configRepository.GetServerURL(),+ },+ })++ return nil+}++// GetClientsForUser will return chat connections that are owned by a specific user.+func (s *Service) GetClientsForUser(userID string) ([]*Client, error) {+ s.mu.Lock()+ defer s.mu.Unlock()++ clients := map[string][]*Client{}++ for _, client := range s.clients {+ clients[client.User.ID] = append(clients[client.User.ID], client)+ }++ if _, exists := clients[userID]; !exists {+ return nil, errors.New("no connections for user found")+ }++ return clients[userID], nil+}++// FindClientByID will return a single connected client by ID.+func (s *Service) FindClientByID(clientID uint) (*Client, bool) {+ client, found := s.clients[clientID]+ return client, found+}++// GetClients will return all the current chat clients connected.+func (s *Service) GetClients() []*Client {+ clients := []*Client{}++ if s == nil {+ return clients+ }++ for _, client := range s.clients {+ clients = append(clients, client)+ }++ sort.Slice(clients, func(i, j int) bool {+ return clients[i].ConnectedAt.Before(clients[j].ConnectedAt)+ })++ return clients+}++// SendSystemMessage sends a message string as a system message to all clients.+func (s *Service) SendSystemMessage(text string, ephemeral bool) error {+ message := events.SystemMessageEvent{+ MessageEvent: events.MessageEvent{+ Body: text,+ },+ ServerName: s.configRepository.GetServerName(),+ }+ message.SetDefaults()+ message.RenderBody()++ if err := s.BroadcastEvent(&message); err != nil {+ log.Errorln("error sending system message", err)+ }++ if !ephemeral {+ s.chatMessageRepository.SaveEvent(message.ID, nil, message.Body, message.GetMessageType(), nil, message.Timestamp, nil, nil, nil, nil)+ }++ return nil+}++// SendFediverseAction sends a message indicating some Fediverse engagement took place.+func (s *Service) SendFediverseAction(eventType string, userAccountName string, image *string, body string, link string) error {+ message := events.FediverseEngagementEvent{+ Event: events.Event{+ Type: eventType,+ },+ MessageEvent: events.MessageEvent{+ Body: body,+ },+ UserAccountName: userAccountName,+ Image: image,+ Link: link,+ ServerName: s.configRepository.GetServerName(),+ }++ message.SetDefaults()++ if err := s.BroadcastEvent(&message); err != nil {+ log.Errorln("error sending system message", err)+ return err+ }++ s.chatMessageRepository.SaveFederatedAction(message)++ return nil+}++// SendSystemAction sends a system action string as an action event to all clients.+func (s *Service) SendSystemAction(text string, ephemeral bool) error {+ message := events.ActionEvent{+ MessageEvent: events.MessageEvent{+ Body: text,+ },+ }++ message.SetDefaults()+ message.RenderBody()++ if err := s.BroadcastEvent(&message); err != nil {+ log.Errorln("error sending system chat action")+ }++ if !ephemeral {+ s.chatMessageRepository.SaveEvent(message.ID, nil, message.Body, message.GetMessageType(), nil, message.Timestamp, nil, nil, nil, nil)+ }++ return nil+}++// SendAllWelcomeMessage sends the chat welcome message to all connected clients.+func (s *Service) SendAllWelcomeMessage() {+ s.sendAllWelcomeMessage()+}++// SendSystemMessageToClient sends a single message to a single connected chat client.+func (s *Service) SendSystemMessageToClient(clientID uint, text string) {+ if client, foundClient := s.FindClientByID(clientID); foundClient {+ s.sendSystemMessageToClient(client, text)+ }+}++// BroadcastEvent sends all connected clients the outbound object provided.+func (s *Service) BroadcastEvent(event events.OutboundEvent) error {+ return s.Broadcast(event.GetBroadcastPayload())+}++// HandleClientConnection handles a single inbound websocket connection.+// Wrapper around the lower-level method so router can bind cleanly.+func (s *Service) HandleWebsocketConnection(w http.ResponseWriter, r *http.Request) {+ s.HandleClientConnection(w, r)+}diff --git a/core/chat/chatclient.go b/services/chat/chatclient.gosimilarity index 93%rename from core/chat/chatclient.gorename to services/chat/chatclient.goindex e15f41f855..c6e440fc64 100644--- a/core/chat/chatclient.go+++ b/services/chat/chatclient.go@@ -11,10 +11,10 @@ import ("golang.org/x/time/rate""github.com/gorilla/websocket"+"github.com/owncast/owncast/config"- "github.com/owncast/owncast/core/chat/events""github.com/owncast/owncast/models"- "github.com/owncast/owncast/persistence/configrepository"+ "github.com/owncast/owncast/services/chat/events""github.com/owncast/owncast/services/geoip")@@ -26,7 +26,7 @@ type Client struct {messageFilter *ChatMessageFilterconn *websocket.ConnUser *models.User `json:"user"`- server *Server+ server *ServiceGeo *geoip.GeoDetails `json:"geo"`// Buffered channel of outbound messages.send chan []byte@@ -133,9 +133,8 @@ func (c *Client) readPump() {}// Check if this message passes the optional language filter- configRepository := configrepository.Get()- if configRepository.GetChatSlurFilterEnabled() && !c.messageFilter.Allow(string(message)) {+ if c.server.configRepository.GetChatSlurFilterEnabled() && !c.messageFilter.Allow(string(message)) {c.sendAction("Sorry, that message contained language that is not allowed in this chat.")continue}@@ -211,11 +210,9 @@ func (c *Client) close() {}func (c *Client) passesRateLimit() bool {- configRepository := configrepository.Get()-// If spam rate limiting is disabled, or the user is a moderator, always// allow the message.- if !configRepository.GetChatSpamProtectionEnabled() || c.User.IsModerator() {+ if !c.server.configRepository.GetChatSpamProtectionEnabled() || c.User.IsModerator() {return true}diff --git a/core/chat/concurrentConnections.go b/services/chat/concurrentConnections.gosimilarity index 100%rename from core/chat/concurrentConnections.gorename to services/chat/concurrentConnections.godiff --git a/core/chat/concurrentConnections_freebsd.go b/services/chat/concurrentConnections_freebsd.gosimilarity index 100%rename from core/chat/concurrentConnections_freebsd.gorename to services/chat/concurrentConnections_freebsd.godiff --git a/core/chat/concurrentConnections_windows.go b/services/chat/concurrentConnections_windows.gosimilarity index 100%rename from core/chat/concurrentConnections_windows.gorename to services/chat/concurrentConnections_windows.godiff --git a/core/chat/events.go b/services/chat/events.gosimilarity index 76%rename from core/chat/events.gorename to services/chat/events.goindex 6b46e93148..2752def2ae 100644--- a/core/chat/events.go+++ b/services/chat/events.go@@ -6,29 +6,24 @@ import ("strings""time"+ log "github.com/sirupsen/logrus"+"github.com/owncast/owncast/config"- "github.com/owncast/owncast/core/chat/events"- "github.com/owncast/owncast/core/webhooks"- "github.com/owncast/owncast/persistence/chatmessagerepository"- "github.com/owncast/owncast/persistence/configrepository"- "github.com/owncast/owncast/persistence/userrepository"+ "github.com/owncast/owncast/services/chat/events""github.com/owncast/owncast/utils"- log "github.com/sirupsen/logrus")-func (s *Server) userNameChanged(eventData chatClientEvent) {+func (s *Service) userNameChanged(eventData chatClientEvent) {var receivedEvent events.NameChangeEventif err := json.Unmarshal(eventData.data, &receivedEvent); err != nil {log.Errorln("error unmarshalling to NameChangeEvent", err)return}- configRepository := configrepository.Get()-proposedUsername := receivedEvent.NewName// Check if name is on the blocklist- blocklist := configRepository.GetForbiddenUsernameList()+ blocklist := s.configRepository.GetForbiddenUsernameList()// Names have a max lengthproposedUsername = utils.MakeSafeStringOfLength(proposedUsername, config.MaxChatDisplayNameLength)@@ -61,10 +56,8 @@ func (s *Server) userNameChanged(eventData chatClientEvent) {}}- userRepository := userrepository.Get()-// Check if the name is not already assigned to a registered user.- if available, err := userRepository.IsDisplayNameAvailable(proposedUsername); err != nil {+ if available, err := s.userRepository.IsDisplayNameAvailable(proposedUsername); err != nil {log.Errorln("error checking if name is available", err)return} else if !available {@@ -77,7 +70,7 @@ func (s *Server) userNameChanged(eventData chatClientEvent) {return}- savedUser := userRepository.GetUserByToken(eventData.client.accessToken)+ savedUser := s.userRepository.GetUserByToken(eventData.client.accessToken)oldName := savedUser.DisplayName// Check that the new name is different from old.@@ -87,7 +80,7 @@ func (s *Server) userNameChanged(eventData chatClientEvent) {}// Save the new name- if err := userRepository.ChangeUsername(eventData.client.User.ID, proposedUsername); err != nil {+ if err := s.userRepository.ChangeUsername(eventData.client.User.ID, proposedUsername); err != nil {log.Errorln("error changing username", err)}@@ -113,15 +106,13 @@ func (s *Server) userNameChanged(eventData chatClientEvent) {// Send chat user name changed webhookreceivedEvent.User = savedUserreceivedEvent.ClientID = eventData.client.Id- webhooks.SendChatEventUsernameChanged(receivedEvent)+ s.webhooks.SendChatEventUsernameChanged(receivedEvent)// Resend the client's user so their username is in sync.eventData.client.sendConnectedClientInfo()}-func (s *Server) userColorChanged(eventData chatClientEvent) {- userRepository := userrepository.Get()-+func (s *Service) userColorChanged(eventData chatClientEvent) {var receivedEvent events.ColorChangeEventif err := json.Unmarshal(eventData.data, &receivedEvent); err != nil {log.Errorln("error unmarshalling to ColorChangeEvent", err)@@ -135,7 +126,7 @@ func (s *Server) userColorChanged(eventData chatClientEvent) {}// Save the new color- if err := userRepository.ChangeUserColor(eventData.client.User.ID, receivedEvent.NewColor); err != nil {+ if err := s.userRepository.ChangeUserColor(eventData.client.User.ID, receivedEvent.NewColor); err != nil {log.Errorln("error changing user display color", err)}@@ -144,9 +135,7 @@ func (s *Server) userColorChanged(eventData chatClientEvent) {eventData.client.sendConnectedClientInfo()}-func (s *Server) userMessageSent(eventData chatClientEvent) {- userRepository := userrepository.Get()-+func (s *Service) userMessageSent(eventData chatClientEvent) {var event events.UserMessageEventif err := json.Unmarshal(eventData.data, &event); err != nil {log.Errorln("error unmarshalling to UserMessageEvent", err)@@ -162,14 +151,14 @@ func (s *Server) userMessageSent(eventData chatClientEvent) {}// Ignore if the stream has been offline- if !getStatus().Online && getStatus().LastDisconnectTime != nil {- disconnectedTime := getStatus().LastDisconnectTime.Time+ if !s.getStatus().Online && s.getStatus().LastDisconnectTime != nil {+ disconnectedTime := s.getStatus().LastDisconnectTime.Timeif time.Since(disconnectedTime) > 5*time.Minute {return}}- event.User = userRepository.GetUserByToken(eventData.client.accessToken)+ event.User = s.userRepository.GetUserByToken(eventData.client.accessToken)// Guard against nil usersif event.User == nil {@@ -183,10 +172,9 @@ func (s *Server) userMessageSent(eventData chatClientEvent) {}// Send chat message sent webhook- webhooks.SendChatEvent(&event)- chatMessagesSentCounter.Inc()- chatMessageRepository := chatmessagerepository.Get()- chatMessageRepository.SaveUserMessage(event)+ s.webhooks.SendChatEvent(&event)+ s.chatMessagesSentCounter.Inc()+ s.chatMessageRepository.SaveUserMessage(event)eventData.client.MessageCount++}diff --git a/core/chat/events/actionEvent.go b/services/chat/events/actionEvent.gosimilarity index 100%rename from core/chat/events/actionEvent.gorename to services/chat/events/actionEvent.godiff --git a/core/chat/events/connectedClientInfo.go b/services/chat/events/connectedClientInfo.gosimilarity index 100%rename from core/chat/events/connectedClientInfo.gorename to services/chat/events/connectedClientInfo.godiff --git a/core/chat/events/events.go b/services/chat/events/events.gosimilarity index 98%rename from core/chat/events/events.gorename to services/chat/events/events.goindex e3eeb2d4e0..29e657b889 100644--- a/core/chat/events/events.go+++ b/services/chat/events/events.go@@ -19,9 +19,10 @@ import ("github.com/yuin/goldmark/util""mvdan.cc/xurls/v2"- "github.com/owncast/owncast/core/data"- "github.com/owncast/owncast/models"log "github.com/sirupsen/logrus"++ "github.com/owncast/owncast/models"+ "github.com/owncast/owncast/services/datastore")// EventPayload is a generic key/value map for sending out to chat clients.@@ -150,7 +151,7 @@ var ()func loadEmoji() {- modTime, err := data.UpdateEmojiList(false)+ modTime, err := datastore.UpdateEmojiList(false)if err != nil {return}@@ -161,7 +162,7 @@ func loadEmoji() {emojiHTML = make(map[string]string)- emojiList := data.GetEmojiList()+ emojiList := datastore.GetEmojiList()emojiArr := make([]emojiDef.Emoji, 0)for i := 0; i < len(emojiList); i++ {diff --git a/core/chat/events/eventtype.go b/services/chat/events/eventtype.gosimilarity index 100%rename from core/chat/events/eventtype.gorename to services/chat/events/eventtype.godiff --git a/core/chat/events/fediverseEngagementEvent.go b/services/chat/events/fediverseEngagementEvent.gosimilarity index 70%rename from core/chat/events/fediverseEngagementEvent.gorename to services/chat/events/fediverseEngagementEvent.goindex cf9d9a0fcf..72940cc208 100644--- a/core/chat/events/fediverseEngagementEvent.go+++ b/services/chat/events/fediverseEngagementEvent.go@@ -1,9 +1,5 @@package events-import (- "github.com/owncast/owncast/persistence/configrepository"-)-// FediverseEngagementEvent is a message displayed in chat on representing an action on the Fediverse.type FediverseEngagementEvent struct {Event@@ -11,12 +7,16 @@ type FediverseEngagementEvent struct {Image *string `json:"image"`Link string `json:"link"`UserAccountName string `json:"title"`+ // ServerName is the configured server display name baked in at+ // construction time. Populated by chat.Service when the event is+ // created so GetBroadcastPayload no longer needs to read from a+ // package-level configRepository. Excluded from JSON because it's a+ // transport detail, not a persisted field.+ ServerName string `json:"-"`}// GetBroadcastPayload will return the object to send to all chat users.func (e *FediverseEngagementEvent) GetBroadcastPayload() EventPayload {- configRepository := configrepository.Get()-return EventPayload{"id": e.ID,payloadKeyTimestamp: e.Timestamp,@@ -26,7 +26,7 @@ func (e *FediverseEngagementEvent) GetBroadcastPayload() EventPayload {"title": e.UserAccountName,"link": e.Link,payloadKeyUser: EventPayload{- "displayName": configRepository.GetServerName(),+ "displayName": e.ServerName,},}}diff --git a/core/chat/events/nameChangeEvent.go b/services/chat/events/nameChangeEvent.gosimilarity index 100%rename from core/chat/events/nameChangeEvent.gorename to services/chat/events/nameChangeEvent.godiff --git a/core/chat/events/setMessageVisibilityEvent.go b/services/chat/events/setMessageVisibilityEvent.gosimilarity index 100%rename from core/chat/events/setMessageVisibilityEvent.gorename to services/chat/events/setMessageVisibilityEvent.godiff --git a/core/chat/events/systemMessageEvent.go b/services/chat/events/systemMessageEvent.gosimilarity index 63%rename from core/chat/events/systemMessageEvent.gorename to services/chat/events/systemMessageEvent.goindex f02749d3ca..86f4532678 100644--- a/core/chat/events/systemMessageEvent.go+++ b/services/chat/events/systemMessageEvent.go@@ -1,26 +1,26 @@package events-import (- "github.com/owncast/owncast/persistence/configrepository"-)-// SystemMessageEvent is a message displayed in chat on behalf of the server.type SystemMessageEvent struct {EventMessageEvent+ // ServerName is the configured server display name baked in at+ // construction time. Populated by chat.Service when the event is+ // created so GetBroadcastPayload no longer needs to read from a+ // package-level configRepository. Excluded from JSON because it's a+ // transport detail, not a persisted field.+ ServerName string `json:"-"`}// GetBroadcastPayload will return the object to send to all chat users.func (e *SystemMessageEvent) GetBroadcastPayload() EventPayload {- configRepository := configrepository.Get()-return EventPayload{"id": e.ID,payloadKeyTimestamp: e.Timestamp,payloadKeyBody: e.Body,payloadKeyType: SystemMessageSent,payloadKeyUser: EventPayload{- "displayName": configRepository.GetServerName(),+ "displayName": e.ServerName,},}}diff --git a/core/chat/events/userDisabledEvent.go b/services/chat/events/userDisabledEvent.gosimilarity index 100%rename from core/chat/events/userDisabledEvent.gorename to services/chat/events/userDisabledEvent.godiff --git a/core/chat/events/userJoinedEvent.go b/services/chat/events/userJoinedEvent.gosimilarity index 100%rename from core/chat/events/userJoinedEvent.gorename to services/chat/events/userJoinedEvent.godiff --git a/core/chat/events/userMessageEvent.go b/services/chat/events/userMessageEvent.gosimilarity index 100%rename from core/chat/events/userMessageEvent.gorename to services/chat/events/userMessageEvent.godiff --git a/core/chat/events/userPartEvent.go b/services/chat/events/userPartEvent.gosimilarity index 100%rename from core/chat/events/userPartEvent.gorename to services/chat/events/userPartEvent.godiff --git a/core/chat/messageFilter.go b/services/chat/messageFilter.gosimilarity index 100%rename from core/chat/messageFilter.gorename to services/chat/messageFilter.godiff --git a/core/chat/messageFilter_test.go b/services/chat/messageFilter_test.gosimilarity index 100%rename from core/chat/messageFilter_test.gorename to services/chat/messageFilter_test.godiff --git a/core/chat/messageRendering_test.go b/services/chat/messageRendering_test.gosimilarity index 98%rename from core/chat/messageRendering_test.gorename to services/chat/messageRendering_test.goindex 382d83cdbd..9c3083570d 100644--- a/core/chat/messageRendering_test.go+++ b/services/chat/messageRendering_test.go@@ -3,7 +3,7 @@ package chatimport ("testing"- "github.com/owncast/owncast/core/chat/events"+ "github.com/owncast/owncast/services/chat/events")// Test a bunch of arbitrary markup and markdown to make sure we get sanitizeddiff --git a/services/chat/messages.go b/services/chat/messages.gonew file mode 100644index 0000000000..d72b39fd8d--- /dev/null+++ b/services/chat/messages.go@@ -0,0 +1,35 @@+package chat++import (+ "errors"++ log "github.com/sirupsen/logrus"++ "github.com/owncast/owncast/services/chat/events"+)++// SetMessagesVisibility sets the visibility of multiple messages by ID.+func (s *Service) SetMessagesVisibility(messageIDs []string, visibility bool) error {+ // Save new message visibility+ if err := s.chatMessageRepository.SetMessageVisibilityForMessageIDs(messageIDs, visibility); err != nil {+ log.Errorln(err)+ return err+ }++ // Send an event letting the chat clients know to hide or show+ // the messages.+ event := events.SetMessageVisibilityEvent{+ MessageIDs: messageIDs,+ Visible: visibility,+ }+ event.Event.SetDefaults()++ payload := event.GetBroadcastPayload()+ if err := s.Broadcast(payload); err != nil {+ return errors.New("error broadcasting message visibility payload " + err.Error())+ }++ s.webhooks.SendChatEventSetMessageVisibility(event)++ return nil+}diff --git a/core/chat/persistence.go b/services/chat/persistence.gosimilarity index 56%rename from core/chat/persistence.gorename to services/chat/persistence.goindex decd6b6738..1bef033202 100644--- a/core/chat/persistence.go+++ b/services/chat/persistence.go@@ -2,24 +2,18 @@ package chatimport ("time"-- "github.com/owncast/owncast/core/data")-var _datastore *data.Datastore-const (maxBacklogHours = 2 // Keep backlog max hours worth of messages)-func setupPersistence() {- _datastore = data.GetDatastore()-+func (s *Service) setupPersistence() {chatDataPruner := time.NewTicker(5 * time.Minute)go func() {- runPruner()+ s.runPruner()for range chatDataPruner.C {- runPruner()+ s.runPruner()}}()}diff --git a/core/chat/pruner.go b/services/chat/pruner.gosimilarity index 84%rename from core/chat/pruner.gorename to services/chat/pruner.goindex a9281b3dfe..b429750014 100644--- a/core/chat/pruner.go+++ b/services/chat/pruner.go@@ -8,14 +8,14 @@ import (// Only keep recent messages so we don't keep more chat data than needed// for privacy and efficiency reasons.-func runPruner() {- _datastore.DbLock.Lock()- defer _datastore.DbLock.Unlock()+func (s *Service) runPruner() {+ s.datastore.DbLock.Lock()+ defer s.datastore.DbLock.Unlock()log.Traceln("Removing chat messages older than", maxBacklogHours, "hours")deleteStatement := `DELETE FROM messages WHERE timestamp <= datetime('now', 'localtime', ?)`- tx, err := _datastore.DB.Begin()+ tx, err := s.datastore.DB.Begin()if err != nil {log.Debugln(err)returndiff --git a/core/chat/server.go b/services/chat/server.gosimilarity index 69%rename from core/chat/server.gorename to services/chat/server.goindex 1403012cce..d47f6edb47 100644--- a/core/chat/server.go+++ b/services/chat/server.go@@ -7,25 +7,25 @@ import ("sync""time"- log "github.com/sirupsen/logrus"-"github.com/gorilla/websocket"+ "github.com/prometheus/client_golang/prometheus"+ log "github.com/sirupsen/logrus""github.com/owncast/owncast/config"- "github.com/owncast/owncast/core/chat/events"- "github.com/owncast/owncast/core/webhooks""github.com/owncast/owncast/models""github.com/owncast/owncast/persistence/authrepository"+ "github.com/owncast/owncast/persistence/chatmessagerepository""github.com/owncast/owncast/persistence/configrepository""github.com/owncast/owncast/persistence/userrepository"+ "github.com/owncast/owncast/services/chat/events"+ "github.com/owncast/owncast/services/datastore""github.com/owncast/owncast/services/geoip"+ "github.com/owncast/owncast/services/webhooks""github.com/owncast/owncast/utils")-var _server *Server--// Server represents an instance of the chat server.-type Server struct {+// Service is an instance of the chat server. Construct via New(Deps).+type Service struct {clients map[uint]*Client// send outbound message payload to all clients@@ -39,6 +39,41 @@ type Server struct {geoipClient *geoip.Client+ // webhooks dispatches chat events (messages, joins, parts,+ // renames, visibility toggles) to configured webhook destinations.+ webhooks *webhooks.Service++ // datastore is the database handle the chat pruner uses to+ // trim aged messages on a recurring timer.+ datastore *datastore.Datastore++ // getStatus returns the current stream status; used by the+ // inbound-message path to make stream-state-aware decisions+ // (welcome messages, recent-disconnect heuristics).+ getStatus func() models.Status++ // configRepository provides server-side chat settings consulted on each+ // inbound message (slur/spam filters, established-users-only mode,+ // auth requirement, welcome message text, etc.).+ configRepository configrepository.ConfigRepository++ // authRepository is consulted on each inbound websocket connection to+ // reject banned IP addresses before upgrading to a chat client.+ authRepository authrepository.AuthRepository++ // chatMessageRepository persists user/system/action/federated chat+ // events and answers history + moderation visibility queries.+ chatMessageRepository chatmessagerepository.ChatMessageRepository++ // userRepository provides access to user records (lookups by ID/token,+ // display-name availability checks, color/name updates) consulted+ // throughout the chat message lifecycle.+ userRepository userrepository.UserRepository++ // chatMessagesSentCounter is the Prometheus counter incremented on+ // each accepted inbound message.+ chatMessagesSentCounter prometheus.Gauge+// a map of user IDs and timers that fire for chat part messages.userPartedTimers map[string]*time.Tickerseq uint@@ -48,17 +83,18 @@ type Server struct {}// NewChat will return a new instance of the chat server.-func NewChat() *Server {+func newServer(webhooksSvc *webhooks.Service) *Service {maximumConcurrentConnectionLimit := getMaximumConcurrentConnectionLimit()setSystemConcurrentConnectionLimit(maximumConcurrentConnectionLimit)- server := &Server{+ server := &Service{clients: map[uint]*Client{},outbound: make(chan []byte),inbound: make(chan chatClientEvent),unregister: make(chan uint),maxSocketConnectionLimit: maximumConcurrentConnectionLimit,geoipClient: geoip.NewClient(),+ webhooks: webhooksSvc,userPartedTimers: map[string]*time.Ticker{},}@@ -66,7 +102,7 @@ func NewChat() *Server {}// Run will start the chat server.-func (s *Server) Run() {+func (s *Service) Run() {for {select {case clientID := <-s.unregister:@@ -84,7 +120,7 @@ func (s *Server) Run() {}// Addclient registers new connection as a User.-func (s *Server) Addclient(conn *websocket.Conn, user *models.User, accessToken string, userAgent string, ipAddress string) *Client {+func (s *Service) Addclient(conn *websocket.Conn, user *models.User, accessToken string, userAgent string, ipAddress string) *Client {client := &Client{server: s,conn: conn,@@ -96,14 +132,12 @@ func (s *Server) Addclient(conn *websocket.Conn, user *models.User, accessTokenConnectedAt: time.Now(),}- configRepository := configrepository.Get()-- shouldSendJoinedMessages := configRepository.GetChatJoinPartMessagesEnabled()+ shouldSendJoinedMessages := s.configRepository.GetChatJoinPartMessagesEnabled()// If there are existing clients connected for this user do not send// a user joined message. Do not put this under a mutex, as// GetClientsForUser already has a lock.- if existingConnectedClients, _ := GetClientsForUser(user.ID); len(existingConnectedClients) > 0 {+ if existingConnectedClients, _ := s.GetClientsForUser(user.ID); len(existingConnectedClients) > 0 {shouldSendJoinedMessages = false}@@ -131,7 +165,7 @@ func (s *Server) Addclient(conn *websocket.Conn, user *models.User, accessTokenclient.sendConnectedClientInfo()- if getStatus().Online {+ if s.getStatus().Online {if shouldSendJoinedMessages {s.sendUserJoinedMessage(client)}@@ -146,7 +180,7 @@ func (s *Server) Addclient(conn *websocket.Conn, user *models.User, accessTokenreturn client}-func (s *Server) sendUserJoinedMessage(c *Client) {+func (s *Service) sendUserJoinedMessage(c *Client) {userJoinedEvent := events.UserJoinedEvent{}userJoinedEvent.SetDefaults()userJoinedEvent.User = c.User@@ -157,16 +191,16 @@ func (s *Server) sendUserJoinedMessage(c *Client) {}// Send chat user joined webhook- webhooks.SendChatEventUserJoined(userJoinedEvent)+ s.webhooks.SendChatEventUserJoined(userJoinedEvent)}-func (s *Server) handleClientDisconnected(c *Client) {+func (s *Service) handleClientDisconnected(c *Client) {if _, ok := s.clients[c.Id]; ok {log.Debugln("Deleting", c.Id)delete(s.clients, c.Id)}- additionalClientCheck, _ := GetClientsForUser(c.User.ID)+ additionalClientCheck, _ := s.GetClientsForUser(c.User.ID)if len(additionalClientCheck) > 0 {// This user is still connected to chat with another client.return@@ -180,7 +214,7 @@ func (s *Server) handleClientDisconnected(c *Client) {}()}-func (s *Server) sendUserPartedMessage(c *Client) {+func (s *Service) sendUserPartedMessage(c *Client) {s.userPartedTimers[c.User.ID].Stop()delete(s.userPartedTimers, c.User.ID)@@ -189,31 +223,26 @@ func (s *Server) sendUserPartedMessage(c *Client) {userPartEvent.User = c.UseruserPartEvent.ClientID = c.Id- configRepository := configrepository.Get()-// If part messages are disabled.- if configRepository.GetChatJoinPartMessagesEnabled() {+ if s.configRepository.GetChatJoinPartMessagesEnabled() {if err := s.Broadcast(userPartEvent.GetBroadcastPayload()); err != nil {log.Errorln("error sending chat part message", err)}}// Send chat user joined webhook- webhooks.SendChatEventUserParted(userPartEvent)+ s.webhooks.SendChatEventUserParted(userPartEvent)}// HandleClientConnection is fired when a single client connects to the websocket.-func (s *Server) HandleClientConnection(w http.ResponseWriter, r *http.Request) {- configRepository := configrepository.Get()- authRepository := authrepository.Get()-- if configRepository.GetChatDisabled() {+func (s *Service) HandleClientConnection(w http.ResponseWriter, r *http.Request) {+ if s.configRepository.GetChatDisabled() {_, _ = w.Write([]byte(events.ChatDisabled))return}ipAddress := utils.GetIPAddressFromRequest(r)// Check if this client's IP address is banned. If so send a rejection.- if blocked, err := authRepository.IsIPAddressBanned(ipAddress); blocked {+ if blocked, err := s.authRepository.IsIPAddressBanned(ipAddress); blocked {log.Debugln("Client ip address has been blocked. Rejecting.")w.WriteHeader(http.StatusForbidden)@@ -248,10 +277,8 @@ func (s *Server) HandleClientConnection(w http.ResponseWriter, r *http.Request)return}- userRepository := userrepository.Get()-// A user is required to use the websocket- user := userRepository.GetUserByToken(accessToken)+ user := s.userRepository.GetUserByToken(accessToken)if user == nil {// Send error that registration is required@@ -278,7 +305,7 @@ func (s *Server) HandleClientConnection(w http.ResponseWriter, r *http.Request)}// Broadcast sends message to all connected clients.-func (s *Server) Broadcast(payload events.EventPayload) error {+func (s *Service) Broadcast(payload events.EventPayload) error {data, err := json.Marshal(payload)if err != nil {return err@@ -303,7 +330,7 @@ func (s *Server) Broadcast(payload events.EventPayload) error {}// Send will send a single payload to a single connected client.-func (s *Server) Send(payload events.EventPayload, client *Client) {+func (s *Service) Send(payload events.EventPayload, client *Client) {data, err := json.Marshal(payload)if err != nil {log.Errorln(err)@@ -314,7 +341,7 @@ func (s *Server) Send(payload events.EventPayload, client *Client) {}// DisconnectClients will forcefully disconnect all clients belonging to a user by ID.-func (s *Server) DisconnectClients(clients []*Client) {+func (s *Service) DisconnectClients(clients []*Client) {for _, client := range clients {log.Traceln("Disconnecting client", client.User.ID, "owned by", client.User.DisplayName)@@ -324,7 +351,7 @@ func (s *Server) DisconnectClients(clients []*Client) {// Send this disabled event specifically to this single connected client// to let them know they've been banned.- _server.Send(event.GetBroadcastPayload(), client)+ s.Send(event.GetBroadcastPayload(), client)// Give the socket time to send out the above message.// Unfortunately I don't know of any way to get a real callback to know when@@ -341,16 +368,14 @@ func (s *Server) DisconnectClients(clients []*Client) {// SendConnectedClientInfoToUser will find all the connected clients assigned to a user// and re-send each the connected client info.-func SendConnectedClientInfoToUser(userID string) error {- clients, err := GetClientsForUser(userID)+func (s *Service) SendConnectedClientInfoToUser(userID string) error {+ clients, err := s.GetClientsForUser(userID)if err != nil {return err}- userRepository := userrepository.Get()-// Get an updated reference to the user.- user := userRepository.GetUserByID(userID)+ user := s.userRepository.GetUserByID(userID)if user == nil {return fmt.Errorf("user not found")}@@ -371,34 +396,32 @@ func SendConnectedClientInfoToUser(userID string) error {// SendActionToUser will send system action text to all connected clients// assigned to a user ID.-func SendActionToUser(userID string, text string) error {- clients, err := GetClientsForUser(userID)+func (s *Service) SendActionToUser(userID string, text string) error {+ clients, err := s.GetClientsForUser(userID)if err != nil {return err}for _, client := range clients {- _server.sendActionToClient(client, text)+ s.sendActionToClient(client, text)}return nil}-func (s *Server) eventReceived(event chatClientEvent) {- configRepository := configrepository.Get()-+func (s *Service) eventReceived(event chatClientEvent) {c := event.clientu := c.User// If established chat user only mode is enabled and the user is not old// enough then reject this event and send them an informative message.- if u != nil && configRepository.GetChatEstbalishedUsersOnlyMode() && time.Since(event.client.User.CreatedAt) < config.GetDefaults().ChatEstablishedUserModeTimeDuration && !u.IsModerator() {+ if u != nil && s.configRepository.GetChatEstbalishedUsersOnlyMode() && time.Since(event.client.User.CreatedAt) < config.GetDefaults().ChatEstablishedUserModeTimeDuration && !u.IsModerator() {s.sendActionToClient(c, "You have not been an established chat participant long enough to take part in chat. Please enjoy the stream and try again later.")return}// Check if authentication is required for chat- if configRepository.GetChatRequireAuthentication() {+ if s.configRepository.GetChatRequireAuthentication() {if u == nil || (!u.Authenticated && !u.IsModerator()) {s.sendActionToClient(c, "Authentication is required to participate in chat.")return@@ -426,23 +449,19 @@ func (s *Server) eventReceived(event chatClientEvent) {}}-func (s *Server) sendWelcomeMessageToClient(c *Client) {- configRepository := configrepository.Get()-+func (s *Service) sendWelcomeMessageToClient(c *Client) {// Add an artificial delay so people notice this message come in.time.Sleep(7 * time.Second)- welcomeMessage := utils.RenderSimpleMarkdown(configRepository.GetServerWelcomeMessage())+ welcomeMessage := utils.RenderSimpleMarkdown(s.configRepository.GetServerWelcomeMessage())if welcomeMessage != "" {s.sendSystemMessageToClient(c, welcomeMessage)}}-func (s *Server) sendAllWelcomeMessage() {- configRepository := configrepository.Get()-- welcomeMessage := utils.RenderSimpleMarkdown(configRepository.GetServerWelcomeMessage())+func (s *Service) sendAllWelcomeMessage() {+ welcomeMessage := utils.RenderSimpleMarkdown(s.configRepository.GetServerWelcomeMessage())if welcomeMessage != "" {clientMessage := events.SystemMessageEvent{@@ -450,25 +469,27 @@ func (s *Server) sendAllWelcomeMessage() {MessageEvent: events.MessageEvent{Body: welcomeMessage,},+ ServerName: s.configRepository.GetServerName(),}clientMessage.SetDefaults()_ = s.Broadcast(clientMessage.GetBroadcastPayload())}}-func (s *Server) sendSystemMessageToClient(c *Client, message string) {+func (s *Service) sendSystemMessageToClient(c *Client, message string) {clientMessage := events.SystemMessageEvent{Event: events.Event{},MessageEvent: events.MessageEvent{Body: message,},+ ServerName: s.configRepository.GetServerName(),}clientMessage.SetDefaults()clientMessage.RenderBody()s.Send(clientMessage.GetBroadcastPayload(), c)}-func (s *Server) sendActionToClient(c *Client, message string) {+func (s *Service) sendActionToClient(c *Client, message string) {clientMessage := events.ActionEvent{MessageEvent: events.MessageEvent{Body: message,diff --git a/core/chat/utils.go b/services/chat/utils.gosimilarity index 100%rename from core/chat/utils.gorename to services/chat/utils.godiff --git a/core/chat/utils_windows.go b/services/chat/utils_windows.gosimilarity index 100%rename from core/chat/utils_windows.gorename to services/chat/utils_windows.godiff --git a/core/data/cache.go b/services/datastore/cache.gosimilarity index 75%rename from core/data/cache.gorename to services/datastore/cache.goindex 2af34ab427..92ecc59805 100644--- a/core/data/cache.go+++ b/services/datastore/cache.go@@ -1,16 +1,13 @@-package data+package datastoreimport ("errors"- "sync")-var _cacheLock = sync.Mutex{}-// GetCachedValue will return a value for key from the cache.func (ds *Datastore) GetCachedValue(key string) ([]byte, error) {- _cacheLock.Lock()- defer _cacheLock.Unlock()+ ds.cacheLock.Lock()+ defer ds.cacheLock.Unlock()// Check for a cached valueif val, ok := ds.cache[key]; ok {@@ -22,8 +19,8 @@ func (ds *Datastore) GetCachedValue(key string) ([]byte, error) {// SetCachedValue will set a value for key in the cache.func (ds *Datastore) SetCachedValue(key string, b []byte) {- _cacheLock.Lock()- defer _cacheLock.Unlock()+ ds.cacheLock.Lock()+ defer ds.cacheLock.Unlock()ds.cache[key] = b}diff --git a/core/data/data.go b/services/datastore/data.gosimilarity index 53%rename from core/data/data.gorename to services/datastore/data.goindex f4ee18e24f..b5679fb5b8 100644--- a/core/data/data.go+++ b/services/datastore/data.go@@ -1,8 +1,10 @@-// This is a centralized place to connect to the database, and hold a reference to it.-// Other packages can share this reference. This package would also be a place to add any kind of-// persistence-related convenience methods or migrations.--package data+// Package datastore is the database root for the rest of the+// application. SetupPersistence opens the SQLite file, runs migrations,+// and returns a constructed *Datastore so main.go can inject it through+// every *repository.New and into the service Deps structs that need+// direct database access. No package-level handle is retained — the+// composition root owns the lifetime.+package datastoreimport ("database/sql"@@ -11,29 +13,19 @@ import ("path/filepath""time"- "github.com/owncast/owncast/config"- "github.com/owncast/owncast/persistence/migrations"- "github.com/owncast/owncast/utils"log "github.com/sirupsen/logrus"-)-var (- _db *sql.DB- _datastore *Datastore+ "github.com/owncast/owncast/persistence/migrations"+ "github.com/owncast/owncast/utils")-// GetDatabase will return the shared instance of the actual database.-func GetDatabase() *sql.DB {- return _db-}--// GetStore will return the shared instance of the read/write datastore.-func GetStore() *Datastore {- return _datastore-}--// SetupPersistence will open the datastore and make it available.-func SetupPersistence(file string) error {+// SetupPersistence opens the datastore file (or an in-memory database+// when file == ":memory:"), runs migrations, starts the periodic backup+// goroutine, and returns the constructed *Datastore. backupDirectory is+// the directory the hourly backup goroutine writes owncastdb.bak into.+// The returned value is the sole handle to the database — main.go+// threads it through every consumer.+func SetupPersistence(file, backupDirectory string) (*Datastore, error) {// Allow support for in-memory databases for tests.var db *sql.DB@@ -57,12 +49,11 @@ func SetupPersistence(file string) error {onDiskDb, err := sql.Open("sqlite3", fmt.Sprintf("file:%s?_cache_size=10000&cache=shared&_journal_mode=WAL", file))if err != nil {- return err+ return nil, err}db = onDiskDbdb.SetMaxOpenConns(1)}- _db = db// Some SQLite optimizations_, _ = db.Exec("pragma journal_mode = WAL")@@ -73,20 +64,20 @@ func SetupPersistence(file string) error {// Bring the schema up to date. The migrations package owns all table// creation and schema changes; existing pre-goose installs are caught up// automatically by its legacy-bridge step.- if err := migrations.Run(db); err != nil {- return fmt.Errorf("running database migrations: %w", err)+ if err := migrations.Run(db, backupDirectory); err != nil {+ return nil, fmt.Errorf("running database migrations: %w", err)}- _datastore = &Datastore{}- _datastore.Setup()+ dataStore := &Datastore{}+ dataStore.Setup(db)dbBackupTicker := time.NewTicker(1 * time.Hour)go func() {- backupFile := filepath.Join(config.BackupDirectory, "owncastdb.bak")+ backupFile := filepath.Join(backupDirectory, "owncastdb.bak")for range dbBackupTicker.C {- utils.Backup(_db, backupFile)+ utils.Backup(db, backupFile)}}()- return nil+ return dataStore, nil}diff --git a/core/data/data_test.go b/services/datastore/data_test.gosimilarity index 95%rename from core/data/data_test.gorename to services/datastore/data_test.goindex 8b3f1f5f21..683fb4f875 100644--- a/core/data/data_test.go+++ b/services/datastore/data_test.go@@ -1,4 +1,4 @@-package data+package datastoreimport ("fmt"@@ -8,13 +8,19 @@ import ("github.com/owncast/owncast/models")+var _datastore *Datastore+func TestMain(m *testing.M) {dbFile, err := os.CreateTemp(os.TempDir(), "owncast-test-db.db")if err != nil {panic(err)}- SetupPersistence(dbFile.Name())+ ds, err := SetupPersistence(dbFile.Name(), os.TempDir())+ if err != nil {+ panic(err)+ }+ _datastore = dsm.Run()}diff --git a/core/data/datastore.go b/services/datastore/datastore.gosimilarity index 90%rename from core/data/datastore.gorename to services/datastore/datastore.goindex 5498bc18f5..f9d8261459 100644--- a/core/data/datastore.go+++ b/services/datastore/datastore.go@@ -1,4 +1,4 @@-package data+package datastoreimport ("bytes"@@ -8,16 +8,18 @@ import (// sqlite requires a blank import._ "github.com/mattn/go-sqlite3"+ log "github.com/sirupsen/logrus"+"github.com/owncast/owncast/db""github.com/owncast/owncast/models"- log "github.com/sirupsen/logrus")// Datastore is the global key/value store for configuration values.type Datastore struct {- DB *sql.DB- cache map[string][]byte- DbLock *sync.Mutex+ DB *sql.DB+ cache map[string][]byte+ cacheLock sync.Mutex+ DbLock *sync.Mutex}// WarmCache pre-caches all configuration values in memory.@@ -107,10 +109,11 @@ func (ds *Datastore) Save(e models.ConfigEntry) error {return nil}-// Setup will perform initial initialization.-func (ds *Datastore) Setup() {+// Setup will perform initial initialization using the provided database+// handle. Called by SetupPersistence with the freshly opened *sql.DB.+func (ds *Datastore) Setup(db *sql.DB) {ds.cache = make(map[string][]byte)- ds.DB = GetDatabase()+ ds.DB = dbds.DbLock = &sync.Mutex{}}@@ -129,11 +132,6 @@ func (ds *Datastore) Reset() {}}-// GetDatastore returns the shared instance of the owncast datastore.-func GetDatastore() *Datastore {- return _datastore-}-// MustExec will execute a SQL statement on a provided database instance.func (ds *Datastore) MustExec(s string) {stmt, err := ds.DB.Prepare(s)diff --git a/core/data/emoji.go b/services/datastore/emoji.gosimilarity index 99%rename from core/data/emoji.gorename to services/datastore/emoji.goindex 45c16cb648..6a28f82b86 100644--- a/core/data/emoji.go+++ b/services/datastore/emoji.go@@ -1,4 +1,4 @@-package data+package datastoreimport ("fmt"@@ -9,12 +9,13 @@ import ("sync""time"+ "github.com/pkg/errors"+ log "github.com/sirupsen/logrus"+"github.com/owncast/owncast/config""github.com/owncast/owncast/static""github.com/owncast/owncast/utils""github.com/owncast/owncast/webserver/handlers/generated"- "github.com/pkg/errors"- log "github.com/sirupsen/logrus")var (diff --git a/core/data/types.go b/services/datastore/types.gosimilarity index 99%rename from core/data/types.gorename to services/datastore/types.goindex 60d399a645..ad8cc64cdb 100644--- a/core/data/types.go+++ b/services/datastore/types.go@@ -1,4 +1,4 @@-package data+package datastoreimport "github.com/owncast/owncast/models"diff --git a/services/notifications/service.go b/services/notifications/service.goindex 2723c31eee..72909bbba0 100644--- a/services/notifications/service.go+++ b/services/notifications/service.go@@ -3,13 +3,14 @@ package notificationsimport ("fmt"- "github.com/owncast/owncast/core/data"+ "github.com/pkg/errors"+ log "github.com/sirupsen/logrus"+"github.com/owncast/owncast/notifications/browser""github.com/owncast/owncast/notifications/discord""github.com/owncast/owncast/persistence/configrepository""github.com/owncast/owncast/persistence/notificationsrepository"- "github.com/pkg/errors"- log "github.com/sirupsen/logrus"+ "github.com/owncast/owncast/services/datastore")// Service defines the interface for notification operations.@@ -26,10 +27,10 @@ type notificationService struct {}// New creates a new instance of the notification service.-func New(datastore *data.Datastore) (Service, error) {+func New(datastore *datastore.Datastore, configRepository configrepository.ConfigRepository) (Service, error) {service := ¬ificationService{- repository: notificationsrepository.New(datastore),- configRepository: configrepository.Get(),+ repository: notificationsrepository.New(datastore, configRepository),+ configRepository: configRepository,}if err := service.setupBrowserPush(datastore); err != nil {@@ -42,7 +43,7 @@ func New(datastore *data.Datastore) (Service, error) {return service, nil}-func (s *notificationService) setupBrowserPush(datastore *data.Datastore) error {+func (s *notificationService) setupBrowserPush(datastore *datastore.Datastore) error {if s.configRepository.GetBrowserPushConfig().Enabled {publicKey, err := s.configRepository.GetBrowserPushPublicKey()if err != nil || publicKey == "" {diff --git a/core/rtmp/broadcaster.go b/services/rtmp/broadcaster.gosimilarity index 88%rename from core/rtmp/broadcaster.gorename to services/rtmp/broadcaster.goindex a2d2129264..7a94e50a05 100644--- a/core/rtmp/broadcaster.go+++ b/services/rtmp/broadcaster.go@@ -4,11 +4,12 @@ import ("time""github.com/nareix/joy5/format/flv/flvio"- "github.com/owncast/owncast/models"log "github.com/sirupsen/logrus"++ "github.com/owncast/owncast/models")-func setCurrentBroadcasterInfo(t flvio.Tag, remoteAddr string) {+func (s *Service) setCurrentBroadcasterInfo(t flvio.Tag, remoteAddr string) {data, err := getInboundDetailsFromMetadata(t.DebugFields())if err != nil {log.Traceln("Unable to parse inbound broadcaster details:", err)@@ -30,5 +31,5 @@ func setCurrentBroadcasterInfo(t flvio.Tag, remoteAddr string) {},}- _setBroadcaster(broadcaster)+ s.setBroadcaster(broadcaster)}diff --git a/core/rtmp/rtmp.go b/services/rtmp/rtmp.gosimilarity index 53%rename from core/rtmp/rtmp.gorename to services/rtmp/rtmp.goindex 09951de82e..bfd9f214b2 100644--- a/core/rtmp/rtmp.go+++ b/services/rtmp/rtmp.go@@ -8,52 +8,35 @@ import ("github.com/nareix/joy5/format/flv""github.com/nareix/joy5/format/flv/flvio"+ "github.com/nareix/joy5/format/rtmp"log "github.com/sirupsen/logrus"- "github.com/nareix/joy5/format/rtmp"- "github.com/owncast/owncast/config""github.com/owncast/owncast/models"- "github.com/owncast/owncast/persistence/configrepository""github.com/owncast/owncast/webserver/handlers/generated")-var _hasInboundRTMPConnection = false--var (- _pipe *io.PipeWriter- _rtmpConnection net.Conn-)--var (- _setStreamAsConnected func(*io.PipeReader)- _setBroadcaster func(models.Broadcaster)-)--// Start starts the rtmp service, listening on specified RTMP port.-func Start(setStreamAsConnected func(*io.PipeReader), setBroadcaster func(models.Broadcaster)) {- _setStreamAsConnected = setStreamAsConnected- _setBroadcaster = setBroadcaster-- configRepository := configrepository.Get()-- port := configRepository.GetRTMPPortNumber()- s := rtmp.NewServer()- var lis net.Listener- var err error- if lis, err = net.Listen("tcp", fmt.Sprintf(":%d", port)); err != nil {+// Start binds the RTMP listener and runs the accept loop. Blocks until+// the listener returns. setStreamAsConnected is invoked once per+// authenticated connection; setBroadcaster is invoked when the inbound+// metadata tag arrives.+func (s *Service) Start(setStreamAsConnected func(*io.PipeReader), setBroadcaster func(models.Broadcaster)) {+ s.setStreamAsConnected = setStreamAsConnected+ s.setBroadcaster = setBroadcaster++ port := s.configRepository.GetRTMPPortNumber()+ srv := rtmp.NewServer()+ lis, err := net.Listen("tcp", fmt.Sprintf(":%d", port))+ if err != nil {log.Fatal(err)}- s.LogEvent = func(c *rtmp.Conn, nc net.Conn, e int) {+ srv.LogEvent = func(c *rtmp.Conn, nc net.Conn, e int) {es := rtmp.EventString[e]log.Traceln("RTMP", nc.LocalAddr(), nc.RemoteAddr(), es)}- s.HandleConn = HandleConn+ srv.HandleConn = s.handleConn- if err != nil {- log.Panicln(err)- }log.Tracef("RTMP server is listening for incoming stream on port: %d", port)for {@@ -62,33 +45,31 @@ func Start(setStreamAsConnected func(*io.PipeReader), setBroadcaster func(modelstime.Sleep(time.Second)continue}- go s.HandleNetConn(nc)+ go srv.HandleNetConn(nc)}}-// HandleConn is fired when an inbound RTMP connection takes place.-func HandleConn(c *rtmp.Conn, nc net.Conn) {+// handleConn is fired when an inbound RTMP connection takes place.+func (s *Service) handleConn(c *rtmp.Conn, nc net.Conn) {c.LogTagEvent = func(isRead bool, t flvio.Tag) {if t.Type == flvio.TAG_AMF0 {log.Tracef("%+v\n", t.DebugFields())- setCurrentBroadcasterInfo(t, nc.RemoteAddr().String())+ s.setCurrentBroadcasterInfo(t, nc.RemoteAddr().String())}}- if _hasInboundRTMPConnection {+ if s.hasInboundConnection {log.Errorln("stream already running; can not overtake an existing stream from", nc.RemoteAddr().String())_ = nc.Close()return}- configRepository := configrepository.Get()-accessGranted := false- validStreamingKeys := configRepository.GetStreamKeys()+ validStreamingKeys := s.configRepository.GetStreamKeys()// If a stream key override was specified then use that instead.- if config.TemporaryStreamKey != "" {- validStreamingKeys = []generated.StreamKey{{Key: &config.TemporaryStreamKey}}+ if s.cfg.TemporaryStreamKey != "" {+ validStreamingKeys = []generated.StreamKey{{Key: &s.cfg.TemporaryStreamKey}}}for _, key := range validStreamingKeys {@@ -105,61 +86,61 @@ func HandleConn(c *rtmp.Conn, nc net.Conn) {}rtmpOut, rtmpIn := io.Pipe()- _pipe = rtmpIn+ s.pipe = rtmpInlog.Infoln("Inbound stream connected from", nc.RemoteAddr().String())- _setStreamAsConnected(rtmpOut)+ s.setStreamAsConnected(rtmpOut)- _hasInboundRTMPConnection = true- _rtmpConnection = nc+ s.hasInboundConnection = true+ s.rtmpConnection = ncw := flv.NewMuxer(rtmpIn)- for _hasInboundRTMPConnection {- // If we don't get a readable packet in 10 seconds give up and disconnect- if err := _rtmpConnection.SetReadDeadline(time.Now().Add(10 * time.Second)); err != nil {+ for s.hasInboundConnection {+ // If we don't get a readable packet in 10 seconds give up and disconnect.+ if err := s.rtmpConnection.SetReadDeadline(time.Now().Add(10 * time.Second)); err != nil {log.Debugln(err)}pkt, err := c.ReadPacket()- // Broadcaster disconnected+ // Broadcaster disconnected.if err == io.EOF {- handleDisconnect(nc)+ s.handleDisconnect(nc)return}// Read timeout. Disconnect.if neterr, ok := err.(net.Error); ok && neterr.Timeout() {log.Debugln("Timeout reading the inbound stream from the broadcaster. Assuming that they disconnected and ending the stream.")- handleDisconnect(nc)+ s.handleDisconnect(nc)return}if err := w.WritePacket(pkt); err != nil {log.Errorln("unable to write rtmp packet", err)- handleDisconnect(nc)+ s.handleDisconnect(nc)return}}}-func handleDisconnect(conn net.Conn) {- if !_hasInboundRTMPConnection {+func (s *Service) handleDisconnect(conn net.Conn) {+ if !s.hasInboundConnection {return}log.Infoln("Inbound stream disconnected.")_ = conn.Close()- _ = _pipe.Close()- _hasInboundRTMPConnection = false+ _ = s.pipe.Close()+ s.hasInboundConnection = false}// Disconnect will force disconnect the current inbound RTMP connection.-func Disconnect() {- if _rtmpConnection == nil {+func (s *Service) Disconnect() {+ if s.rtmpConnection == nil {return}log.Traceln("Inbound stream disconnect requested.")- handleDisconnect(_rtmpConnection)+ s.handleDisconnect(s.rtmpConnection)}diff --git a/services/rtmp/service.go b/services/rtmp/service.gonew file mode 100644index 0000000000..1604110663--- /dev/null+++ b/services/rtmp/service.go@@ -0,0 +1,64 @@+// Package rtmp is the inbound RTMP ingest service. It listens on the+// configured RTMP port, authenticates incoming streams against the+// configured stream keys, and pipes the FLV-muxed bytes to the stream+// service via callbacks supplied to Start.+//+// The stream service holds a *Service and calls Start(...) once at+// startup; admin handlers hold one to force-disconnect via Disconnect().+package rtmp++import (+ "io"+ "net"++ "github.com/owncast/owncast/config"+ "github.com/owncast/owncast/models"+ "github.com/owncast/owncast/persistence/configrepository"+)++// Service owns the RTMP listener and the single in-flight inbound+// connection (RTMP allows one broadcaster at a time). Construct with+// New() and start with Start(...).+type Service struct {+ // hasInboundConnection is set true while an authenticated RTMP source+ // is connected. Used both as a single-broadcaster guard and as the+ // loop condition for the packet pump.+ hasInboundConnection bool++ // pipe is the write end of the FLV bytestream handed to the stream+ // service via setStreamAsConnected. Closed on disconnect.+ pipe *io.PipeWriter++ // rtmpConnection is the live net.Conn of the broadcaster. Held so+ // Disconnect() can force-close it and so the read deadline can be+ // reset between packets.+ rtmpConnection net.Conn++ // setStreamAsConnected is invoked once at authenticated-connect time+ // with the read end of the FLV pipe. Set by Start.+ setStreamAsConnected func(*io.PipeReader)++ // setBroadcaster is invoked when the inbound onMetaData arrives with+ // the parsed broadcaster details. Set by Start.+ setBroadcaster func(models.Broadcaster)++ // configRepository is consulted at listener bind for the RTMP port and at+ // connect time for the list of valid stream keys.+ configRepository configrepository.ConfigRepository++ // cfg supplies the optional temporary stream key override set at+ // startup via the --streamkey CLI flag.+ cfg *config.Config+}++// Deps is the explicit dependency contract for the RTMP service.+type Deps struct {+ ConfigRepository configrepository.ConfigRepository+ Config *config.Config+}++// New constructs an idle RTMP service. Call Start(...) to bind the+// listener and begin accepting connections.+func New(deps Deps) *Service {+ return &Service{configRepository: deps.ConfigRepository, cfg: deps.Config}+}diff --git a/core/rtmp/utils.go b/services/rtmp/utils.gosimilarity index 94%rename from core/rtmp/utils.gorename to services/rtmp/utils.goindex 797a7c4ea2..78aeb45ed2 100644--- a/core/rtmp/utils.go+++ b/services/rtmp/utils.go@@ -9,8 +9,9 @@ import ("strings""github.com/nareix/joy5/format/flv/flvio"- "github.com/owncast/owncast/models"log "github.com/sirupsen/logrus"++ "github.com/owncast/owncast/models")const unknownString = "Unknown"@@ -86,10 +87,10 @@ func secretMatch(configStreamKey string, path string) bool {if !strings.HasPrefix(path, prefix) {log.Debug("RTMP path does not start with " + prefix)- return false // We need the path to begin with $prefix+ return false}- streamingKey := path[len(prefix):] // Remove $prefix+ streamingKey := path[len(prefix):]matches := subtle.ConstantTimeCompare([]byte(streamingKey), []byte(configStreamKey)) == 1return matchesdiff --git a/core/rtmp/utils_test.go b/services/rtmp/utils_test.gosimilarity index 100%rename from core/rtmp/utils_test.gorename to services/rtmp/utils_test.godiff --git a/core/storageproviders/local.go b/services/storage/local.gosimilarity index 86%rename from core/storageproviders/local.gorename to services/storage/local.goindex 2e43f98780..dc07d431bc 100644--- a/core/storageproviders/local.go+++ b/services/storage/local.go@@ -1,28 +1,29 @@-package storageproviders+package storageimport ("os""path/filepath""sort"- "github.com/owncast/owncast/persistence/configrepository"log "github.com/sirupsen/logrus"++ "github.com/owncast/owncast/persistence/configrepository")// LocalStorage represents an instance of the local storage provider for HLS video.type LocalStorage struct {- host string+ host string+ configRepository configrepository.ConfigRepository}// NewLocalStorage returns a new LocalStorage instance.-func NewLocalStorage() *LocalStorage {- return &LocalStorage{}+func NewLocalStorage(configRepository configrepository.ConfigRepository) *LocalStorage {+ return &LocalStorage{configRepository: configRepository}}// Setup configures this storage provider.func (s *LocalStorage) Setup() error {- configRepository := configrepository.Get()- s.host = configRepository.GetVideoServingEndpoint()+ s.host = s.configRepository.GetVideoServingEndpoint()return nil}@@ -63,8 +64,7 @@ func (s *LocalStorage) Save(filePath string, retryCount int) (string, error) {// Cleanup will remove old files from the storage provider.func (s *LocalStorage) Cleanup() error {// Determine how many files we should keep on disk- configRepository := configrepository.Get()- maxNumber := configRepository.GetStreamLatencyLevel().SegmentCount+ maxNumber := s.configRepository.GetStreamLatencyLevel().SegmentCountbuffer := 10return localCleanup(maxNumber + buffer)}diff --git a/core/storageproviders/localCleanup.go b/services/storage/localCleanup.gosimilarity index 97%rename from core/storageproviders/localCleanup.gorename to services/storage/localCleanup.goindex 7e655d4d00..1e42ca95a8 100644--- a/core/storageproviders/localCleanup.go+++ b/services/storage/localCleanup.go@@ -1,12 +1,13 @@-package storageproviders+package storageimport ("os""path/filepath"- "github.com/owncast/owncast/config""github.com/pkg/errors"log "github.com/sirupsen/logrus"++ "github.com/owncast/owncast/config")func localCleanup(maxNumber int) error {diff --git a/services/storage/playlist.go b/services/storage/playlist.gonew file mode 100644index 0000000000..6cda7eb79c--- /dev/null+++ b/services/storage/playlist.go@@ -0,0 +1,21 @@+package storage++import "os"++// writePlaylist writes an HLS playlist to disk. Internal helper for the+// storage providers (local + S3 both rely on rewriting playlist files+// to point at their final serving location).+func writePlaylist(data string, filePath string) error {+ // nolint:gosec+ f, err := os.Create(filePath)+ if err != nil {+ return err+ }+ defer f.Close()++ if _, err := f.WriteString(data); err != nil {+ return err+ }++ return nil+}diff --git a/core/storageproviders/rewriteLocalPlaylist.go b/services/storage/rewriteLocalPlaylist.gosimilarity index 86%rename from core/storageproviders/rewriteLocalPlaylist.gorename to services/storage/rewriteLocalPlaylist.goindex 22ec378207..64aa596d45 100644--- a/core/storageproviders/rewriteLocalPlaylist.go+++ b/services/storage/rewriteLocalPlaylist.go@@ -1,4 +1,4 @@-package storageproviders+package storageimport ("bufio"@@ -6,10 +6,9 @@ import ("path/filepath""github.com/grafov/m3u8"- "github.com/owncast/owncast/config"- "github.com/owncast/owncast/core/playlist"-log "github.com/sirupsen/logrus"++ "github.com/owncast/owncast/config")// rewritePlaylistLocations will take a local playlist and rewrite it to have absolute URLs to a specified location.@@ -36,5 +35,5 @@ func rewritePlaylistLocations(localFilePath, remoteServingEndpoint, hlsPrefix stnewPlaylist := p.String()- return playlist.WritePlaylist(newPlaylist, publicPath)+ return writePlaylist(newPlaylist, publicPath)}diff --git a/core/storageproviders/s3Storage.go b/services/storage/s3Storage.gosimilarity index 92%rename from core/storageproviders/s3Storage.gorename to services/storage/s3Storage.goindex f749c3da90..37b9cd4477 100644--- a/core/storageproviders/s3Storage.go+++ b/services/storage/s3Storage.go@@ -1,4 +1,4 @@-package storageproviders+package storageimport ("context"@@ -13,11 +13,12 @@ import ("sync""time"- "github.com/owncast/owncast/persistence/configrepository"- "github.com/owncast/owncast/utils""github.com/pkg/errors"log "github.com/sirupsen/logrus"+ "github.com/owncast/owncast/persistence/configrepository"+ "github.com/owncast/owncast/utils"+"github.com/aws/aws-sdk-go-v2/aws""github.com/aws/aws-sdk-go-v2/credentials""github.com/aws/aws-sdk-go-v2/service/s3"@@ -48,23 +49,28 @@ type S3Storage struct {lock sync.Mutex+ configRepository configrepository.ConfigRepository++ performanceTracker *utils.PerformanceTracker+s3ForcePathStyle bool}// NewS3Storage returns a new S3Storage instance.-func NewS3Storage() *S3Storage {+func NewS3Storage(configRepository configrepository.ConfigRepository) *S3Storage {return &S3Storage{queuedPlaylistUpdates: make(map[string]string),lock: sync.Mutex{},+ configRepository: configRepository,+ performanceTracker: utils.NewPerformanceTracker(),}}// Setup sets up the s3 storage for saving the video to s3.func (s *S3Storage) Setup() error {log.Trace("Setting up S3 for external storage of video...")- configRepository := configrepository.Get()- s3Config := configRepository.GetS3Config()- customVideoServingEndpoint := configRepository.GetVideoServingEndpoint()+ s3Config := s.configRepository.GetS3Config()+ customVideoServingEndpoint := s.configRepository.GetVideoServingEndpoint()if customVideoServingEndpoint != "" {s.host = customVideoServingEndpoint@@ -91,19 +97,18 @@ func (s *S3Storage) Setup() error {func (s *S3Storage) SegmentWritten(localFilePath string) {index := utils.GetIndexFromFilePath(localFilePath)performanceMonitorKey := "s3upload-" + index- utils.StartPerformanceMonitor(performanceMonitorKey)+ s.performanceTracker.StartPerformanceMonitor(performanceMonitorKey)// Upload the segmentif _, err := s.Save(localFilePath, 0); err != nil {log.Errorln(err)return}- averagePerformance := utils.GetAveragePerformance(performanceMonitorKey)+ averagePerformance := s.performanceTracker.GetAveragePerformance(performanceMonitorKey)// Warn the user about long-running save operations- configRepository := configrepository.Get()if averagePerformance != 0 {- if averagePerformance > float64(configRepository.GetStreamLatencyLevel().SecondsPerSegment)*0.9 {+ if averagePerformance > float64(s.configRepository.GetStreamLatencyLevel().SecondsPerSegment)*0.9 {log.Warnln("Possible slow uploads: average upload S3 save duration", averagePerformance, "s. troubleshoot this issue by visiting https://owncast.online/docs/troubleshooting/")}}@@ -210,8 +215,7 @@ func (s *S3Storage) Cleanup() error {// RemoteCleanup will remove old files from the remote storage provider.func (s *S3Storage) RemoteCleanup() error {// Determine how many files we should keep on S3 storage- configRepository := configrepository.Get()- maxNumber := configRepository.GetStreamLatencyLevel().SegmentCount+ maxNumber := s.configRepository.GetStreamLatencyLevel().SegmentCountbuffer := 20keys, err := s.getDeletableVideoSegmentsWithOffset(maxNumber + buffer)diff --git a/core/offlineState.go b/services/stream/offline.gosimilarity index 82%rename from core/offlineState.gorename to services/stream/offline.goindex 7f6f43a349..0ea3bfdc06 100644--- a/core/offlineState.go+++ b/services/stream/offline.go@@ -1,4 +1,4 @@-package core+package streamimport ("fmt"@@ -6,13 +6,14 @@ import ("path/filepath""github.com/grafov/m3u8"+ log "github.com/sirupsen/logrus"+"github.com/owncast/owncast/config""github.com/owncast/owncast/static""github.com/owncast/owncast/utils"- log "github.com/sirupsen/logrus")-func appendOfflineToVariantPlaylist(index int, playlistFilePath string) {+func (s *Service) appendOfflineToVariantPlaylist(index int, playlistFilePath string) {existingPlaylistContents, err := os.ReadFile(playlistFilePath) // nolint: gosecif err != nil {log.Debugln("unable to read existing playlist file", err)@@ -20,7 +21,7 @@ func appendOfflineToVariantPlaylist(index int, playlistFilePath string) {}tmpFileName := fmt.Sprintf("tmp-stream-%d.m3u8", index)- atomicWriteTmpPlaylistFile, err := os.CreateTemp(config.TempDir, tmpFileName)+ atomicWriteTmpPlaylistFile, err := os.CreateTemp(s.cfg.TempDir, tmpFileName)if err != nil {log.Errorln("error creating tmp playlist file to write to", playlistFilePath, err)return@@ -48,7 +49,7 @@ func appendOfflineToVariantPlaylist(index int, playlistFilePath string) {}}-func makeVariantIndexOffline(index int, offlineFilePath string, offlineFilename string) {+func (s *Service) makeVariantIndexOffline(index int, offlineFilePath string, offlineFilename string) {playlistFilePath := fmt.Sprintf(filepath.Join(config.HLSStoragePath, "%d/stream.m3u8"), index)segmentFilePath := fmt.Sprintf(filepath.Join(config.HLSStoragePath, "%d/%s"), index, offlineFilename)@@ -56,16 +57,16 @@ func makeVariantIndexOffline(index int, offlineFilePath string, offlineFilenamelog.Warnln(err)}- if _, err := _storage.Save(segmentFilePath, 0); err != nil {+ if _, err := s.storage.Save(segmentFilePath, 0); err != nil {log.Warnln(err)}if utils.DoesFileExists(playlistFilePath) {- appendOfflineToVariantPlaylist(index, playlistFilePath)+ s.appendOfflineToVariantPlaylist(index, playlistFilePath)} else {createEmptyOfflinePlaylist(playlistFilePath, offlineFilename)}- if _, err := _storage.Save(playlistFilePath, 0); err != nil {+ if _, err := s.storage.Save(playlistFilePath, 0); err != nil {log.Warnln(err)}}@@ -92,9 +93,9 @@ func createEmptyOfflinePlaylist(playlistFilePath string, offlineFilename string)}}-func saveOfflineClipToDisk(offlineFilename string) (string, error) {+func saveOfflineClipToDisk(tempDir, offlineFilename string) (string, error) {offlineFileData := static.GetOfflineSegment()- offlineTmpFile, err := os.CreateTemp(config.TempDir, offlineFilename)+ offlineTmpFile, err := os.CreateTemp(tempDir, offlineFilename)if err != nil {log.Errorln("unable to create temp file for offline video segment", err)}diff --git a/services/stream/service.go b/services/stream/service.gonew file mode 100644index 0000000000..2d6a73345d--- /dev/null+++ b/services/stream/service.go@@ -0,0 +1,149 @@+// Package stream is the live-streaming lifecycle service: stream connect /+// disconnect handling, viewer stats, status reporting, storage provider+// setup, and the offline content state. It owns the state that used to+// live as package-level globals in the legacy `core` package; that package+// now exists only as a thin backward-compatibility shim that delegates+// here.+package stream++import (+ "context"+ "sync"+ "time"++ "github.com/owncast/owncast/config"+ "github.com/owncast/owncast/models"+ "github.com/owncast/owncast/persistence/configrepository"+ "github.com/owncast/owncast/services/activitypub"+ "github.com/owncast/owncast/services/chat"+ "github.com/owncast/owncast/services/datastore"+ "github.com/owncast/owncast/services/geoip"+ "github.com/owncast/owncast/services/rtmp"+ "github.com/owncast/owncast/services/transcoder"+ "github.com/owncast/owncast/services/webhooks"+ "github.com/owncast/owncast/yp"+)++// activeViewerPurgeTimeout is the silence-window after which a viewer is+// dropped from the active set.+const activeViewerPurgeTimeout = 15 * time.Second++// Service is the stream subsystem. Construct one in main.go with New(),+// register it with the legacy core compat shim via core.Init(svc), then+// call Start(ctx) to bring up the storage, transcoder, RTMP listener and+// associated infrastructure.+type Service struct {+ // stats owns viewer-count, connect timing, etc. statsMu guards the+ // stats fields that are touched from goroutines (viewer-set updates,+ // chat-client removal).+ stats *models.Stats+ statsMu sync.RWMutex++ // storage is the active HLS storage provider (local filesystem or S3).+ storage models.StorageProvider++ // transcoder holds the active ffmpeg child while a stream is online.+ // Replaced when a stream comes up, nil'd when it goes down.+ transcoder *transcoder.Transcoder++ // yp talks to the Owncast directory.+ yp *yp.YP++ // broadcaster carries the metadata of the currently-connected RTMP+ // source. Nil between streams.+ broadcaster *models.Broadcaster++ // currentBroadcast holds the in-flight broadcast settings (latency+ // level, output variants) captured at stream-connect time.+ currentBroadcast *models.CurrentBroadcast++ // offlineCleanupTimer fires once N minutes after a stream goes+ // offline to wipe HLS content. onlineCleanupTicker fires every N+ // minutes while a stream is up to prune old segments.+ offlineCleanupTimer *time.Timer+ onlineCleanupTicker *time.Ticker++ // onlineTimerCancelFunc cancels the delayed live-notification+ // dispatcher when a stream ends before the notification fires.+ onlineTimerCancelFunc context.CancelFunc++ // lastNotified is the last time we sent the live-going-online+ // notification; used to debounce re-notifications when a stream+ // flaps.+ lastNotified *time.Time++ // HLS transcoder plumbing. handler routes finished playlists/segments+ // to the storage provider; fileWriter feeds the transcoder's output+ // into handler.+ handler transcoder.HLSHandler+ fileWriter *transcoder.FileWriterReceiverService++ // thumbnailGen owns the periodic thumbnail+preview snapshotter that+ // runs while a stream is online. Lazily started on stream-connect,+ // stopped on stream-disconnect.+ thumbnailGen *transcoder.ThumbnailGenerator++ // geoIPClient performs the asynchronous viewer-geolocation lookup.+ geoIPClient *geoip.Client++ // rtmp is the inbound RTMP ingest service. Start hands it+ // stream-lifecycle callbacks; admin disconnect goes through it too.+ rtmp *rtmp.Service++ // activitypub is the federation subsystem; the stream service uses+ // it to broadcast go-live notifications to followers when a stream+ // starts.+ activitypub *activitypub.Service++ // webhooks dispatches stream-status events (started/stopped) to+ // user-configured HTTP destinations.+ webhooks *webhooks.Service++ // chat is the websocket chat server; the stream service tells it+ // when a stream starts/ends so it can send the appropriate+ // system-message announcements.+ chat *chat.Service++ // datastore is the database handle the stream service hands to the+ // notifications subsystem when dispatching delayed go-live pushes.+ datastore *datastore.Datastore++ // configRepository provides all server settings used during stream+ // lifecycle (latency level, output variants, stream keys, …).+ configRepository configrepository.ConfigRepository++ // cfg holds runtime configuration values (HLS storage scratch dirs,+ // debug flag) shared with transcoder/thumbnail children spawned by+ // the stream lifecycle.+ cfg *config.Config+}++// Deps is the explicit-dependency contract the service requires at+// construction time.+type Deps struct {+ Rtmp *rtmp.Service+ Activitypub *activitypub.Service+ Webhooks *webhooks.Service+ Chat *chat.Service+ YP *yp.YP+ Datastore *datastore.Datastore+ ConfigRepository configrepository.ConfigRepository+ Config *config.Config+}++// New constructs an idle stream Service. Call Start(ctx) to bring up the+// storage backend, transcoder, RTMP listener, and associated lifecycle.+func New(deps Deps) *Service {+ return &Service{+ geoIPClient: geoip.NewClient(),+ fileWriter: transcoder.NewFileWriterReceiverService(deps.Config),+ rtmp: deps.Rtmp,+ activitypub: deps.Activitypub,+ webhooks: deps.Webhooks,+ chat: deps.Chat,+ yp: deps.YP,+ datastore: deps.Datastore,+ configRepository: deps.ConfigRepository,+ cfg: deps.Config,+ }+}diff --git a/services/stream/stats.go b/services/stream/stats.gonew file mode 100644index 0000000000..05ddb66f51--- /dev/null+++ b/services/stream/stats.go@@ -0,0 +1,146 @@+package stream++import (+ "math"+ "time"++ log "github.com/sirupsen/logrus"++ "github.com/owncast/owncast/models"+)++// setupStats restores stats from the previous session and starts the+// periodic save + viewer-prune goroutines.+func (s *Service) setupStats() error {+ saved := s.getSavedStats()+ s.stats = &saved++ statsSaveTicker := time.NewTicker(1 * time.Minute)+ go func() {+ for range statsSaveTicker.C {+ s.saveStats()+ }+ }()++ viewerCountPruneTicker := time.NewTicker(5 * time.Second)+ go func() {+ for range viewerCountPruneTicker.C {+ s.pruneViewerCount()+ }+ }()++ return nil+}++// IsStreamConnected reports whether the stream is actively delivering+// live HLS content. Returns false during the brief warm-up after an+// RTMP connection where HLS segments aren't ready yet.+func (s *Service) IsStreamConnected() bool {+ if s.stats == nil || !s.stats.StreamConnected {+ return false+ }++ // Kind of a hack. It takes a handful of seconds between an RTMP+ // connection and when HLS data is available. Account for that with+ // an artificial buffer of a few segments.+ timeSinceLastConnected := time.Since(s.stats.LastConnectTime.Time).Seconds()+ waitTime := math.Max(float64(s.configRepository.GetStreamLatencyLevel().SecondsPerSegment)*3.0, 7)+ if timeSinceLastConnected < waitTime {+ return false+ }++ return s.stats.StreamConnected+}++// RemoveChatClient removes a chat client from the active-clients record.+// Currently unused — kept for now during the migration; remove once+// confirmed dead.+func (s *Service) RemoveChatClient(clientID string) {+ log.Trace("Removing the client:", clientID)++ s.statsMu.Lock()+ delete(s.stats.ChatClients, clientID)+ s.statsMu.Unlock()+}++// SetViewerActive marks a viewer as currently watching and updates the+// session/overall peak counters. Silent no-op while no stream is live.+func (s *Service) SetViewerActive(viewer *models.Viewer) {+ if s.stats == nil || !s.stats.StreamConnected {+ return+ }++ s.statsMu.Lock()+ defer s.statsMu.Unlock()++ // Asynchronously, optionally, fetch GeoIP info.+ go func(viewer *models.Viewer) {+ viewer.Geo = s.geoIPClient.GetGeoFromIP(viewer.IPAddress)+ }(viewer)++ if _, exists := s.stats.Viewers[viewer.ClientID]; exists {+ s.stats.Viewers[viewer.ClientID].LastSeen = time.Now()+ } else {+ s.stats.Viewers[viewer.ClientID] = viewer+ }+ s.stats.SessionMaxViewerCount = int(math.Max(float64(len(s.stats.Viewers)), float64(s.stats.SessionMaxViewerCount)))+ s.stats.OverallMaxViewerCount = int(math.Max(float64(s.stats.SessionMaxViewerCount), float64(s.stats.OverallMaxViewerCount)))+}++// GetActiveViewers returns the currently-tracked viewers. The returned+// map is the live one — callers should not modify it.+func (s *Service) GetActiveViewers() map[string]*models.Viewer {+ if s.stats == nil {+ return nil+ }+ return s.stats.Viewers+}++func (s *Service) pruneViewerCount() {+ viewers := make(map[string]*models.Viewer)++ s.statsMu.Lock()+ defer s.statsMu.Unlock()++ for viewerID, viewer := range s.stats.Viewers {+ if time.Since(s.stats.Viewers[viewerID].LastSeen) < activeViewerPurgeTimeout {+ viewers[viewerID] = viewer+ }+ }++ s.stats.Viewers = viewers+}++func (s *Service) saveStats() {+ if err := s.configRepository.SetPeakOverallViewerCount(s.stats.OverallMaxViewerCount); err != nil {+ log.Errorln("error saving viewer count", err)+ }+ if err := s.configRepository.SetPeakSessionViewerCount(s.stats.SessionMaxViewerCount); err != nil {+ log.Errorln("error saving viewer count", err)+ }+ if s.stats.LastDisconnectTime != nil && s.stats.LastDisconnectTime.Valid {+ if err := s.configRepository.SetLastDisconnectTime(s.stats.LastDisconnectTime.Time); err != nil {+ log.Errorln("error saving disconnect time", err)+ }+ }+}++func (s *Service) getSavedStats() models.Stats {+ savedLastDisconnectTime, _ := s.configRepository.GetLastDisconnectTime()++ result := models.Stats{+ ChatClients: make(map[string]models.Client),+ Viewers: make(map[string]*models.Viewer),+ SessionMaxViewerCount: s.configRepository.GetPeakSessionViewerCount(),+ OverallMaxViewerCount: s.configRepository.GetPeakOverallViewerCount(),+ LastDisconnectTime: savedLastDisconnectTime,+ }++ // If the stats were saved > 5min ago then ignore the+ // peak session count value, since the session is over.+ if result.LastDisconnectTime == nil || !result.LastDisconnectTime.Valid || time.Since(result.LastDisconnectTime.Time).Minutes() > 5 {+ result.SessionMaxViewerCount = 0+ }++ return result+}diff --git a/services/stream/status.go b/services/stream/status.gonew file mode 100644index 0000000000..a56ad6a897--- /dev/null+++ b/services/stream/status.go@@ -0,0 +1,48 @@+package stream++import (+ "github.com/owncast/owncast/config"+ "github.com/owncast/owncast/models"+)++// GetStatus returns a snapshot of the current stream state suitable for+// the public/admin status APIs.+func (s *Service) GetStatus() models.Status {+ if s.stats == nil {+ return models.Status{}+ }++ viewerCount := 0+ if s.IsStreamConnected() {+ viewerCount = len(s.stats.Viewers)+ }++ return models.Status{+ Online: s.IsStreamConnected(),+ ViewerCount: viewerCount,+ OverallMaxViewerCount: s.stats.OverallMaxViewerCount,+ SessionMaxViewerCount: s.stats.SessionMaxViewerCount,+ LastDisconnectTime: s.stats.LastDisconnectTime,+ LastConnectTime: s.stats.LastConnectTime,+ VersionNumber: config.VersionNumber,+ StreamTitle: s.configRepository.GetStreamTitle(),+ }+}++// GetCurrentBroadcast returns the in-flight broadcast settings, or nil+// if no stream is currently live.+func (s *Service) GetCurrentBroadcast() *models.CurrentBroadcast {+ return s.currentBroadcast+}++// setBroadcaster records the metadata of the inbound RTMP source. Called+// by the RTMP server's on-connect callback.+func (s *Service) setBroadcaster(broadcaster models.Broadcaster) {+ s.broadcaster = &broadcaster+}++// GetBroadcaster returns the active inbound broadcaster, or nil between+// streams.+func (s *Service) GetBroadcaster() *models.Broadcaster {+ return s.broadcaster+}diff --git a/services/stream/storage.go b/services/stream/storage.gonew file mode 100644index 0000000000..c8835f5e27--- /dev/null+++ b/services/stream/storage.go@@ -0,0 +1,25 @@+package stream++import (+ "github.com/owncast/owncast/services/storage"+)++// setupStorage picks an HLS storage backend based on the S3 config and+// wires it into the HLS handler. Called once from Start().+func (s *Service) setupStorage() error {+ s3Config := s.configRepository.GetS3Config()++ if s3Config.Enabled {+ s.storage = storage.NewS3Storage(s.configRepository)+ } else {+ s.storage = storage.NewLocalStorage(s.configRepository)+ }++ if err := s.storage.Setup(); err != nil {+ return err+ }++ s.handler.Storage = s.storage++ return nil+}diff --git a/services/stream/stream.go b/services/stream/stream.gonew file mode 100644index 0000000000..21ab9a993c--- /dev/null+++ b/services/stream/stream.go@@ -0,0 +1,301 @@+package stream++import (+ "context"+ "io"+ "os"+ "path"+ "path/filepath"+ "time"++ log "github.com/sirupsen/logrus"++ "github.com/owncast/owncast/config"+ "github.com/owncast/owncast/models"+ "github.com/owncast/owncast/services/notifications"+ "github.com/owncast/owncast/services/transcoder"+ "github.com/owncast/owncast/utils"+)++// Start brings up the storage backend, transcoder, RTMP listener, chat,+// webhooks, and the directory/notification subsystems. Must be called+// exactly once after New().+func (s *Service) Start(_ context.Context) error {+ s.resetDirectories()++ if err := s.configRepository.VerifySettings(s.cfg.TemporaryStreamKey); err != nil {+ log.Error(err)+ return err+ }++ if err := s.setupStats(); err != nil {+ log.Error("failed to setup the stats")+ return err+ }++ // The HLS handler takes the written HLS playlists and segments and+ // makes storage decisions. Rather simple right now but will play more+ // useful when recordings come into play.+ s.handler = transcoder.HLSHandler{}++ if err := s.setupStorage(); err != nil {+ log.Errorln("storage error", err)+ }++ s.fileWriter.SetupFileWriterReceiverService(&s.handler)++ if err := s.createInitialOfflineState(); err != nil {+ log.Error("failed to create the initial offline state")+ return err+ }++ if err := s.chat.Start(); err != nil {+ log.Errorln(err)+ }++ // start the rtmp server+ go s.rtmp.Start(s.setStreamAsConnected, s.setBroadcaster)++ rtmpPort := s.configRepository.GetRTMPPortNumber()+ if rtmpPort != 1935 {+ log.Infof("RTMP is accepting inbound streams on port %d.", rtmpPort)+ }++ s.webhooks.Start()++ return nil+}++// Stop releases anything the service is holding. Currently a no-op+// because individual goroutines and ffmpeg children are tied to+// stream-connect/disconnect rather than overall service lifetime, but the+// hook is here for graceful-shutdown plumbing later: process exit+// reclaims the goroutines and ffmpeg child today; future work cancels+// onlineTimerCancelFunc, stops tickers, and closes the transcoder+// cleanly.+func (s *Service) Stop(_ context.Context) {+}++func (s *Service) createInitialOfflineState() error {+ s.transitionToOfflineVideoStreamContent()+ return nil+}++// transitionToOfflineVideoStreamContent overwrites the current stream+// with the offline video stream state only. No live stream HLS segments+// will continue to be referenced.+func (s *Service) transitionToOfflineVideoStreamContent() {+ log.Traceln("Firing transcoder with offline stream state")++ offlineTranscoder := transcoder.NewTranscoder(s.cfg, s.configRepository)+ offlineTranscoder.SetIdentifier("offline")+ offlineTranscoder.SetLatencyLevel(models.GetLatencyLevel(4))+ offlineTranscoder.SetIsEvent(true)++ offlineFilePath, err := saveOfflineClipToDisk(s.cfg.TempDir, "offline-v2.ts")+ if err != nil {+ log.Fatalln("unable to save offline clip:", err)+ }++ offlineTranscoder.SetInput(offlineFilePath)+ go offlineTranscoder.Start(false)++ // Copy the logo to be the thumbnail+ logo := s.configRepository.GetLogoPath()+ dst := filepath.Join(s.cfg.TempDir, "thumbnail.jpg")+ if err = utils.Copy(filepath.Join("data", logo), dst); err != nil {+ log.Warnln(err)+ }++ // Delete the preview Gif+ _ = os.Remove(path.Join(config.DataDirectory, "preview.gif"))+}++func (s *Service) resetDirectories() {+ log.Trace("Resetting file directories to a clean slate.")++ // Wipe hls data directory+ utils.CleanupDirectory(config.HLSStoragePath)++ // Remove the previous thumbnail+ logo := s.configRepository.GetLogoPath()+ if utils.DoesFileExists(logo) {+ err := utils.Copy(path.Join("data", logo), filepath.Join(config.DataDirectory, "thumbnail.jpg"))+ if err != nil {+ log.Warnln(err)+ }+ }+}++// setStreamAsConnected is the RTMP server's on-connect callback.+func (s *Service) setStreamAsConnected(rtmpOut *io.PipeReader) {+ now := utils.NullTime{Time: time.Now(), Valid: true}+ s.stats.StreamConnected = true+ s.stats.LastDisconnectTime = nil+ s.stats.LastConnectTime = &now+ s.stats.SessionMaxViewerCount = 0++ s.currentBroadcast = &models.CurrentBroadcast{+ LatencyLevel: s.configRepository.GetStreamLatencyLevel(),+ OutputSettings: s.configRepository.GetStreamOutputVariants(),+ }++ s.StopOfflineCleanupTimer()+ s.startOnlineCleanupTimer()++ if s.yp != nil {+ go s.yp.Start()+ }++ segmentPath := config.HLSStoragePath++ if err := s.setupStorage(); err != nil {+ log.Fatalln("failed to setup the storage", err)+ }++ go func() {+ s.transcoder = transcoder.NewTranscoder(s.cfg, s.configRepository)+ s.transcoder.TranscoderCompleted = func(error) {+ s.SetStreamAsDisconnected()+ s.transcoder = nil+ s.currentBroadcast = nil+ }+ s.transcoder.SetStdin(rtmpOut)+ s.transcoder.Start(true)+ }()++ go s.webhooks.SendStreamStatusEvent(models.StreamStarted)+ selectedThumbnailVideoQualityIndex, isVideoPassthrough := s.configRepository.FindHighestVideoQualityIndex(s.currentBroadcast.OutputSettings)+ s.thumbnailGen = transcoder.NewThumbnailGenerator(s.cfg, s.configRepository)+ s.thumbnailGen.Start(segmentPath, selectedThumbnailVideoQualityIndex, isVideoPassthrough)++ _ = s.chat.SendSystemAction("Stay tuned, the stream is **starting**!", true)+ s.chat.SendAllWelcomeMessage()++ // Send delayed notification messages.+ s.onlineTimerCancelFunc = s.startLiveStreamNotificationsTimer()+}++// SetStreamAsDisconnected handles cleanup when a live stream ends.+func (s *Service) SetStreamAsDisconnected() {+ _ = s.chat.SendSystemAction("The stream is ending.", true)++ now := utils.NullTime{Time: time.Now(), Valid: true}+ if s.onlineTimerCancelFunc != nil {+ s.onlineTimerCancelFunc()+ }++ s.stats.StreamConnected = false+ s.stats.LastDisconnectTime = &now+ s.stats.LastConnectTime = nil+ s.broadcaster = nil++ offlineFilename := "offline-v2.ts"++ offlineFilePath, err := saveOfflineClipToDisk(s.cfg.TempDir, offlineFilename)+ if err != nil {+ log.Errorln(err)+ return+ }++ if s.thumbnailGen != nil {+ s.thumbnailGen.Stop()+ }+ s.rtmp.Disconnect()++ if s.yp != nil {+ s.yp.Stop()+ }++ // If there is no current broadcast available the previous stream+ // likely failed for some reason. Don't try to append to it. Just+ // transition to offline.+ if s.currentBroadcast == nil {+ s.stopOnlineCleanupTimer()+ s.transitionToOfflineVideoStreamContent()+ log.Errorln("unexpected nil currentBroadcast")+ return+ }++ for index := range s.currentBroadcast.OutputSettings {+ s.makeVariantIndexOffline(index, offlineFilePath, offlineFilename)+ }++ s.StartOfflineCleanupTimer()+ s.stopOnlineCleanupTimer()+ s.saveStats()++ go s.webhooks.SendStreamStatusEvent(models.StreamStopped)+}++// StartOfflineCleanupTimer fires a cleanup after n minutes being+// disconnected.+func (s *Service) StartOfflineCleanupTimer() {+ s.offlineCleanupTimer = time.NewTimer(5 * time.Minute)+ go func() {+ for range s.offlineCleanupTimer.C {+ // Set video to offline state+ s.resetDirectories()+ s.transitionToOfflineVideoStreamContent()+ }+ }()+}++// StopOfflineCleanupTimer stops the previous offline cleanup timer.+func (s *Service) StopOfflineCleanupTimer() {+ if s.offlineCleanupTimer != nil {+ s.offlineCleanupTimer.Stop()+ }+}++func (s *Service) startOnlineCleanupTimer() {+ s.onlineCleanupTicker = time.NewTicker(1 * time.Minute)+ go func() {+ for range s.onlineCleanupTicker.C {+ if err := s.storage.Cleanup(); err != nil {+ log.Errorln(err)+ }+ }+ }()+}++func (s *Service) stopOnlineCleanupTimer() {+ if s.onlineCleanupTicker != nil {+ s.onlineCleanupTicker.Stop()+ }+}++func (s *Service) startLiveStreamNotificationsTimer() context.CancelFunc {+ // Send delayed notification messages.+ c, cancelFunc := context.WithCancel(context.Background())+ s.onlineTimerCancelFunc = cancelFunc+ go func(c context.Context) {+ select {+ case <-time.After(time.Minute * 2.0):+ if s.lastNotified != nil && time.Since(*s.lastNotified) < 10*time.Minute {+ return+ }++ // Send Fediverse message.+ if s.configRepository.GetFederationEnabled() {+ log.Traceln("Sending Federated Go Live message.")+ if err := s.activitypub.SendLive(); err != nil {+ log.Errorln(err)+ }+ }++ // Send notification to those who have registered for them.+ if notificationService, err := notifications.New(s.datastore, s.configRepository); err != nil {+ log.Errorln(err)+ } else {+ notificationService.Notify()+ }++ now := time.Now()+ s.lastNotified = &now+ case <-c.Done():+ }+ }(c)++ return cancelFunc+}diff --git a/core/transcoder/codecs.go b/services/transcoder/codecs.gosimilarity index 100%rename from core/transcoder/codecs.gorename to services/transcoder/codecs.godiff --git a/core/transcoder/fileWriterReceiverService.go b/services/transcoder/fileWriterReceiverService.gosimilarity index 84%rename from core/transcoder/fileWriterReceiverService.gorename to services/transcoder/fileWriterReceiverService.goindex 08c1427cfd..b803fc9591 100644--- a/core/transcoder/fileWriterReceiverService.go+++ b/services/transcoder/fileWriterReceiverService.go@@ -8,9 +8,10 @@ import ("path/filepath""strings"+ log "github.com/sirupsen/logrus"+"github.com/owncast/owncast/config""github.com/owncast/owncast/utils"- log "github.com/sirupsen/logrus")// FileWriterReceiverServiceCallback are to be fired when transcoder responses are written to disk.@@ -25,9 +26,19 @@ type FileWriterReceiverServiceCallback interface {// the transcoder process to be completely isolated and even run remotely in the future, as long// as it can send HTTP requests to this service with the results.type FileWriterReceiverService struct {+ // cfg receives the listener port discovered when the receiver binds+ // (the kernel-assigned ephemeral port). The transcoder later reads+ // the same field when it spins up its ffmpeg child.+ cfg *config.Configcallbacks FileWriterReceiverServiceCallback}+// NewFileWriterReceiverService constructs an idle receiver. Call+// SetupFileWriterReceiverService to bind the listener.+func NewFileWriterReceiverService(cfg *config.Config) *FileWriterReceiverService {+ return &FileWriterReceiverService{cfg: cfg}+}+// SetupFileWriterReceiverService will start listening for transcoder responses.func (s *FileWriterReceiverService) SetupFileWriterReceiverService(callbacks FileWriterReceiverServiceCallback) {s.callbacks = callbacks@@ -43,7 +54,7 @@ func (s *FileWriterReceiverService) SetupFileWriterReceiverService(callbacks Fil}listenerPort := strings.Split(listener.Addr().String(), ":")[1]- config.InternalHLSListenerPort = listenerPort+ s.cfg.InternalHLSListenerPort = listenerPortlog.Traceln("Transcoder response service listening on: " + listenerPort)go func() {//nolint: gosecdiff --git a/core/transcoder/hlsHandler.go b/services/transcoder/hlsHandler.gosimilarity index 100%rename from core/transcoder/hlsHandler.gorename to services/transcoder/hlsHandler.godiff --git a/core/transcoder/thumbnailGenerator.go b/services/transcoder/thumbnailGenerator.gosimilarity index 51%rename from core/transcoder/thumbnailGenerator.gorename to services/transcoder/thumbnailGenerator.goindex 2e8d16afa6..78e188001b 100644--- a/core/transcoder/thumbnailGenerator.go+++ b/services/transcoder/thumbnailGenerator.go@@ -14,46 +14,51 @@ import ("github.com/owncast/owncast/utils")-var _timer *time.Ticker+// ThumbnailGenerator periodically snapshots the most recent HLS segment+// into thumbnail.jpg + preview.gif while a stream is online. One+// instance per active stream, owned by the stream service.+type ThumbnailGenerator struct {+ timer *time.Ticker+ cfg *config.Config+ configRepository configrepository.ConfigRepository+}++// NewThumbnailGenerator returns an idle generator. Call Start to begin.+func NewThumbnailGenerator(cfg *config.Config, configRepository configrepository.ConfigRepository) *ThumbnailGenerator {+ return &ThumbnailGenerator{cfg: cfg, configRepository: configRepository}+}-// StopThumbnailGenerator will stop the periodic generating of a thumbnail from video.-func StopThumbnailGenerator() {- if _timer != nil {- _timer.Stop()+// Stop will stop the periodic generating of a thumbnail from video.+func (g *ThumbnailGenerator) Stop() {+ if g.timer != nil {+ g.timer.Stop()}}-// StartThumbnailGenerator starts generating thumbnails.-func StartThumbnailGenerator(chunkPath string, variantIndex int, isVideoPassthrough bool) {+// Start starts generating thumbnails.+func (g *ThumbnailGenerator) Start(chunkPath string, variantIndex int, isVideoPassthrough bool) {// Every 20 seconds create a thumbnail from the most// recent video segment.- _timer = time.NewTicker(20 * time.Second)- quit := make(chan struct{})+ g.timer = time.NewTicker(20 * time.Second)go func() {- for {- select {- case <-_timer.C:- if err := fireThumbnailGenerator(chunkPath, variantIndex); err != nil {- logMsg := "Unable to generate thumbnail: " + err.Error()- if isVideoPassthrough {- logMsg += ". Video Passthrough is enabled. You should disable it to fix this, and other, streaming errors. https://owncast.online/troubleshoot"- }- log.Errorln("Unable to generate thumbnail:", logMsg)+ for range g.timer.C {+ if err := g.fireThumbnailGenerator(chunkPath, variantIndex); err != nil {+ logMsg := "Unable to generate thumbnail: " + err.Error()+ if isVideoPassthrough {+ logMsg += ". Video Passthrough is enabled. You should disable it to fix this, and other, streaming errors. https://owncast.online/troubleshoot"}- case <-quit:- log.Debug("thumbnail generator has stopped")- _timer.Stop()- return+ log.Errorln("Unable to generate thumbnail:", logMsg)}}+ log.Debug("thumbnail generator has stopped")}()}-func fireThumbnailGenerator(segmentPath string, variantIndex int) error {+func (g *ThumbnailGenerator) fireThumbnailGenerator(segmentPath string, variantIndex int) error {// JPG takes less time to encode than PNG- outputFile := path.Join(config.TempDir, "thumbnail.jpg")- previewGifFile := path.Join(config.TempDir, "preview.gif")+ outputFile := path.Join(g.cfg.TempDir, "thumbnail.jpg")+ previewGifFile := path.Join(g.cfg.TempDir, "preview.gif")framePath := path.Join(segmentPath, strconv.Itoa(variantIndex))files, err := os.ReadDir(framePath)@@ -87,10 +92,9 @@ func fireThumbnailGenerator(segmentPath string, variantIndex int) error {if len(names) == 0 {return nil}- configRepository := configrepository.Get()mostRecentFile := path.Join(framePath, names[0])- ffmpegPath := utils.ValidatedFfmpegPath(configRepository.GetFfMpegPath())- outputFileTemp := path.Join(config.TempDir, "tempthumbnail.jpg")+ ffmpegPath := utils.ValidatedFfmpegPath(g.configRepository.GetFfMpegPath())+ outputFileTemp := path.Join(g.cfg.TempDir, "tempthumbnail.jpg")thumbnailCmdFlags := []string{"-y", // Overwrite file@@ -111,15 +115,14 @@ func fireThumbnailGenerator(segmentPath string, variantIndex int) error {log.Errorln(err)}- makeAnimatedGifPreview(mostRecentFile, previewGifFile)+ g.makeAnimatedGifPreview(mostRecentFile, previewGifFile)return nil}-func makeAnimatedGifPreview(sourceFile string, outputFile string) {- configRepository := configrepository.Get()- ffmpegPath := utils.ValidatedFfmpegPath(configRepository.GetFfMpegPath())- outputFileTemp := path.Join(config.TempDir, "temppreview.gif")+func (g *ThumbnailGenerator) makeAnimatedGifPreview(sourceFile string, outputFile string) {+ ffmpegPath := utils.ValidatedFfmpegPath(g.configRepository.GetFfMpegPath())+ outputFileTemp := path.Join(g.cfg.TempDir, "temppreview.gif")// Filter is pulled from https://engineering.giphy.com/how-to-make-gifs-with-ffmpeg/animatedGifFlags := []string{diff --git a/core/transcoder/transcoder.go b/services/transcoder/transcoder.gosimilarity index 89%rename from core/transcoder/transcoder.gorename to services/transcoder/transcoder.goindex fe71174333..e2e799769c 100644--- a/core/transcoder/transcoder.go+++ b/services/transcoder/transcoder.go@@ -8,6 +8,7 @@ import ("runtime""strconv""strings"+ "sync"log "github.com/sirupsen/logrus""github.com/teris-io/shortid"@@ -22,8 +23,6 @@ import (// ffmpegFlagMap is the ffmpeg stream selection flag.const ffmpegFlagMap = "-map"-var _commandExec *exec.Cmd-type execInfo struct {binPath stringcommand []string@@ -38,8 +37,29 @@ func (e *execInfo) String() string {type Transcoder struct {codec Codec+ // cfg supplies runtime values (the HLS listener port discovered at+ // startup, the debug flag, the log directory) needed when building+ // the ffmpeg command line.+ cfg *config.Config++ // configRepository provides ffmpeg path, latency level, output variants,+ // and codec selection consulted at Start.+ configRepository configrepository.ConfigRepository+stdin *io.PipeReader+ // commandExec holds the live ffmpeg child process while the+ // transcoder is running. Set in Start, killed in Stop.+ commandExec *exec.Cmd++ // logMu guards lastLogMessage. Held briefly while+ // handleTranscoderMessage decides whether to emit a deduped log line+ // from the stderr-scanner goroutine.+ logMu sync.RWMutex+ // lastLogMessage is the most recent stderr line surfaced to the+ // logger; used to suppress immediate repeats.+ lastLogMessage string+TranscoderCompleted func(error)playlistOutputPath stringffmpegPath string@@ -118,7 +138,7 @@ func (v *VideoSize) getString() string {// Stop will stop the transcoder and kill all processing.func (t *Transcoder) Stop() {log.Traceln("Transcoder STOP requested.")- err := _commandExec.Process.Kill()+ err := t.commandExec.Process.Kill()if err != nil {log.Errorln(err)}@@ -126,33 +146,31 @@ func (t *Transcoder) Stop() {// Start will execute the transcoding process with the settings previously set.func (t *Transcoder) Start(shouldLog bool) {- _lastTranscoderLogMessage = ""-flags := t.getFlags()if shouldLog {log.Infof("Processing video using codec %s with %d output qualities configured.", t.codec.DisplayName(), len(t.variants))}- createVariantDirectories()+ t.createVariantDirectories()command := flags.String()- if config.EnableDebugFeatures {+ if t.cfg.EnableDebugFeatures {log.Println(command)}- _commandExec = exec.Command(flags.binPath, flags.command...) // nolint: gosec- _commandExec.Env = flags.environ+ t.commandExec = exec.Command(flags.binPath, flags.command...) // nolint: gosec+ t.commandExec.Env = flags.environif t.stdin != nil {- _commandExec.Stdin = t.stdin+ t.commandExec.Stdin = t.stdin}- stdout, err := _commandExec.StderrPipe()+ stdout, err := t.commandExec.StderrPipe()if err != nil {log.Fatalln(err)}- if err := _commandExec.Start(); err != nil {- log.Errorln("Transcoder error. See", logging.GetTranscoderLogFilePath(), "for full output to debug.")+ if err := t.commandExec.Start(); err != nil {+ log.Errorln("Transcoder error. See", logging.GetTranscoderLogFilePath(t.cfg.LogDirectory), "for full output to debug.")log.Panicln(err, command)}@@ -160,17 +178,17 @@ func (t *Transcoder) Start(shouldLog bool) {scanner := bufio.NewScanner(stdout)for scanner.Scan() {line := scanner.Text()- handleTranscoderMessage(line)+ t.handleTranscoderMessage(line)}}()- err = _commandExec.Wait()+ err = t.commandExec.Wait()if t.TranscoderCompleted != nil {t.TranscoderCompleted(err)}if err != nil {- log.Errorln("transcoding error. look at", logging.GetTranscoderLogFilePath(), "to help debug. your copy of ffmpeg may not support your selected codec of", t.codec.Name(), "https://owncast.online/docs/codecs/")+ log.Errorln("transcoding error. look at", logging.GetTranscoderLogFilePath(t.cfg.LogDirectory), "to help debug. your copy of ffmpeg may not support your selected codec of", t.codec.Name(), "https://owncast.online/docs/codecs/")}}@@ -219,7 +237,7 @@ func (t *Transcoder) getFlags() *execInfo {hlsOptionsString = append(hlsOptionsString, "-hls_flags", strings.Join(hlsOptionFlags, "+"))}- logPath := logging.GetTranscoderLogFilePath()+ logPath := logging.GetTranscoderLogFilePath(t.cfg.LogDirectory)reportEnv := fmt.Sprintf(`FFREPORT=file=%s:level=32`, logPath)if runtime.GOOS == "windows" {logPath = strings.ReplaceAll(logPath, "\\", "/")@@ -311,13 +329,14 @@ func getVariantFromConfigQuality(quality models.StreamOutputVariant, index int)}// NewTranscoder will return a new Transcoder, populated by the config.-func NewTranscoder() *Transcoder {- configRepository := configrepository.Get()+func NewTranscoder(cfg *config.Config, configRepository configrepository.ConfigRepository) *Transcoder {ffmpegPath := utils.ValidatedFfmpegPath(configRepository.GetFfMpegPath())transcoder := new(Transcoder)+ transcoder.cfg = cfg+ transcoder.configRepository = configRepositorytranscoder.ffmpegPath = ffmpegPath- transcoder.internalListenerPort = config.InternalHLSListenerPort+ transcoder.internalListenerPort = cfg.InternalHLSListenerPorttranscoder.currentStreamOutputSettings = configRepository.GetStreamOutputVariants()transcoder.currentLatencyLevel = configRepository.GetStreamLatencyLevel()diff --git a/core/transcoder/transcoder_nvenc_test.go b/services/transcoder/transcoder_nvenc_test.gosimilarity index 95%rename from core/transcoder/transcoder_nvenc_test.gorename to services/transcoder/transcoder_nvenc_test.goindex d0cf9d7b7b..1981804a15 100644--- a/core/transcoder/transcoder_nvenc_test.go+++ b/services/transcoder/transcoder_nvenc_test.go@@ -4,6 +4,7 @@ import ("path/filepath""testing"+ "github.com/owncast/owncast/config""github.com/owncast/owncast/models")@@ -12,6 +13,7 @@ func TestFFmpegNvencCommand(t *testing.T) {codec := NvencCodec{}transcoder := new(Transcoder)+ transcoder.cfg = &config.Config{LogDirectory: "data/logs"}transcoder.ffmpegPath = filepath.Join("fake", "path", "ffmpeg")transcoder.SetInput("fakecontent.flv")transcoder.SetOutputPath("fakeOutput")diff --git a/core/transcoder/transcoder_omx_test.go b/services/transcoder/transcoder_omx_test.gosimilarity index 95%rename from core/transcoder/transcoder_omx_test.gorename to services/transcoder/transcoder_omx_test.goindex 0405a3a7f2..1f547ba161 100644--- a/core/transcoder/transcoder_omx_test.go+++ b/services/transcoder/transcoder_omx_test.go@@ -4,6 +4,7 @@ import ("path/filepath""testing"+ "github.com/owncast/owncast/config""github.com/owncast/owncast/models")@@ -12,6 +13,7 @@ func TestFFmpegOmxCommand(t *testing.T) {codec := OmxCodec{}transcoder := new(Transcoder)+ transcoder.cfg = &config.Config{LogDirectory: "data/logs"}transcoder.ffmpegPath = filepath.Join("fake", "path", "ffmpeg")transcoder.SetInput("fakecontent.flv")transcoder.SetOutputPath("fakeOutput")diff --git a/core/transcoder/transcoder_qsv_test.go b/services/transcoder/transcoder_qsv_test.gosimilarity index 95%rename from core/transcoder/transcoder_qsv_test.gorename to services/transcoder/transcoder_qsv_test.goindex 132c83eded..20fa3a9bee 100644--- a/core/transcoder/transcoder_qsv_test.go+++ b/services/transcoder/transcoder_qsv_test.go@@ -4,6 +4,7 @@ import ("path/filepath""testing"+ "github.com/owncast/owncast/config""github.com/owncast/owncast/models")@@ -12,6 +13,7 @@ func TestFFmpegQuicksyncCommand(t *testing.T) {codec := QuicksyncCodec{}transcoder := new(Transcoder)+ transcoder.cfg = &config.Config{LogDirectory: "data/logs"}transcoder.ffmpegPath = filepath.Join("fake", "path", "ffmpeg")transcoder.SetInput("fakecontent.flv")transcoder.SetOutputPath("fakeOutput")diff --git a/core/transcoder/transcoder_vaapi_test.go b/services/transcoder/transcoder_vaapi_test.gosimilarity index 95%rename from core/transcoder/transcoder_vaapi_test.gorename to services/transcoder/transcoder_vaapi_test.goindex 0772f82c5a..38db9c081a 100644--- a/core/transcoder/transcoder_vaapi_test.go+++ b/services/transcoder/transcoder_vaapi_test.go@@ -4,6 +4,7 @@ import ("path/filepath""testing"+ "github.com/owncast/owncast/config""github.com/owncast/owncast/models")@@ -12,6 +13,7 @@ func TestFFmpegVaapiCommand(t *testing.T) {codec := VaapiCodec{}transcoder := new(Transcoder)+ transcoder.cfg = &config.Config{LogDirectory: "data/logs"}transcoder.ffmpegPath = filepath.Join("fake", "path", "ffmpeg")transcoder.SetInput("fakecontent.flv")transcoder.SetOutputPath("fakeOutput")diff --git a/core/transcoder/transcoder_videotoolbox_test.go b/services/transcoder/transcoder_videotoolbox_test.gosimilarity index 95%rename from core/transcoder/transcoder_videotoolbox_test.gorename to services/transcoder/transcoder_videotoolbox_test.goindex b72b151597..352a63296b 100644--- a/core/transcoder/transcoder_videotoolbox_test.go+++ b/services/transcoder/transcoder_videotoolbox_test.go@@ -4,6 +4,7 @@ import ("path/filepath""testing"+ "github.com/owncast/owncast/config""github.com/owncast/owncast/models")@@ -12,6 +13,7 @@ func TestFFmpegVideoToolboxCommand(t *testing.T) {codec := VideoToolboxCodec{}transcoder := new(Transcoder)+ transcoder.cfg = &config.Config{LogDirectory: "data/logs"}transcoder.ffmpegPath = filepath.Join("fake", "path", "ffmpeg")transcoder.SetInput("fakecontent.flv")transcoder.SetOutputPath("fakeOutput")diff --git a/core/transcoder/transcoder_x264_test.go b/services/transcoder/transcoder_x264_test.gosimilarity index 95%rename from core/transcoder/transcoder_x264_test.gorename to services/transcoder/transcoder_x264_test.goindex 5a58ec3abb..0c5d41e1eb 100644--- a/core/transcoder/transcoder_x264_test.go+++ b/services/transcoder/transcoder_x264_test.go@@ -4,6 +4,7 @@ import ("path/filepath""testing"+ "github.com/owncast/owncast/config""github.com/owncast/owncast/models")@@ -12,6 +13,7 @@ func TestFFmpegx264Command(t *testing.T) {codec := Libx264Codec{}transcoder := new(Transcoder)+ transcoder.cfg = &config.Config{LogDirectory: "data/logs"}transcoder.ffmpegPath = filepath.Join("fake", "path", "ffmpeg")transcoder.SetInput("fakecontent.flv")transcoder.SetOutputPath("fakeOutput")diff --git a/core/transcoder/utils.go b/services/transcoder/utils.gosimilarity index 91%rename from core/transcoder/utils.gorename to services/transcoder/utils.goindex f058293559..95fd69882f 100644--- a/core/transcoder/utils.go+++ b/services/transcoder/utils.go@@ -5,17 +5,11 @@ import ("path""strconv""strings"- "sync"- "github.com/owncast/owncast/config"- "github.com/owncast/owncast/persistence/configrepository"- "github.com/owncast/owncast/utils"log "github.com/sirupsen/logrus"-)-var (- _lastTranscoderLogMessage = ""- l = &sync.RWMutex{}+ "github.com/owncast/owncast/config"+ "github.com/owncast/owncast/utils")var errorMap = map[string]string{@@ -63,11 +57,11 @@ var ignoredErrors = []string{"Failed to allocate a vaapi/nv12 frame from a fixed pool of hardware frames.",}-func handleTranscoderMessage(message string) {+func (t *Transcoder) handleTranscoderMessage(message string) {log.Debugln(message)- l.Lock()- defer l.Unlock()+ t.logMu.Lock()+ defer t.logMu.Unlock()// Ignore certain messages that we don't care about.for _, error := range ignoredErrors {@@ -89,21 +83,20 @@ func handleTranscoderMessage(message string) {}// No good comes from a flood of repeated messages.- if message == _lastTranscoderLogMessage {+ if message == t.lastLogMessage {return}log.Error(message)- _lastTranscoderLogMessage = message+ t.lastLogMessage = message}-func createVariantDirectories() {+func (t *Transcoder) createVariantDirectories() {// Create private hls data dirsutils.CleanupDirectory(config.HLSStoragePath)- configRepository := configrepository.Get()- if len(configRepository.GetStreamOutputVariants()) != 0 {- for index := range configRepository.GetStreamOutputVariants() {+ if len(t.configRepository.GetStreamOutputVariants()) != 0 {+ for index := range t.configRepository.GetStreamOutputVariants() {if err := os.MkdirAll(path.Join(config.HLSStoragePath, strconv.Itoa(index)), 0o750); err != nil {log.Fatalln(err)}diff --git a/core/webhooks/chat.go b/services/webhooks/chat.gosimilarity index 54%rename from core/webhooks/chat.gorename to services/webhooks/chat.goindex 9505061b8a..a3bc8f6624 100644--- a/core/webhooks/chat.go+++ b/services/webhooks/chat.go@@ -1,18 +1,18 @@package webhooksimport (- "github.com/owncast/owncast/core/chat/events""github.com/owncast/owncast/models"+ "github.com/owncast/owncast/services/chat/events")-// SendChatEvent will send a chat event to webhook destinations.-func SendChatEvent(chatEvent *events.UserMessageEvent) {+// SendChatEvent dispatches a chat-message event to webhook destinations.+func (s *Service) SendChatEvent(chatEvent *events.UserMessageEvent) {webhookEvent := WebhookEvent{Type: chatEvent.GetMessageType(),EventData: &WebhookChatMessage{BaseWebhookData: BaseWebhookData{- Status: getStatus(),- ServerURL: getServerURL(),+ Status: s.getStatus(),+ ServerURL: s.serverURL(),},User: chatEvent.User,Body: chatEvent.Body,@@ -24,17 +24,17 @@ func SendChatEvent(chatEvent *events.UserMessageEvent) {},}- SendEventToWebhooks(webhookEvent)+ s.SendEventToWebhooks(webhookEvent)}-// SendChatEventUsernameChanged will send a username changed event to webhook destinations.-func SendChatEventUsernameChanged(event events.NameChangeEvent) {+// SendChatEventUsernameChanged dispatches a username-changed event.+func (s *Service) SendChatEventUsernameChanged(event events.NameChangeEvent) {webhookEvent := WebhookEvent{Type: models.UserNameChanged,EventData: &WebhookNameChangeEventData{BaseWebhookData: BaseWebhookData{- Status: getStatus(),- ServerURL: getServerURL(),+ Status: s.getStatus(),+ ServerURL: s.serverURL(),},ID: event.ID,Timestamp: event.Timestamp,@@ -43,17 +43,17 @@ func SendChatEventUsernameChanged(event events.NameChangeEvent) {},}- SendEventToWebhooks(webhookEvent)+ s.SendEventToWebhooks(webhookEvent)}-// SendChatEventUserJoined sends a webhook notifying that a user has joined.-func SendChatEventUserJoined(event events.UserJoinedEvent) {+// SendChatEventUserJoined dispatches a user-joined event.+func (s *Service) SendChatEventUserJoined(event events.UserJoinedEvent) {webhookEvent := WebhookEvent{Type: models.UserJoined,EventData: &WebhookUserJoinedEventData{BaseWebhookData: BaseWebhookData{- Status: getStatus(),- ServerURL: getServerURL(),+ Status: s.getStatus(),+ ServerURL: s.serverURL(),},ID: event.ID,Timestamp: event.Timestamp,@@ -61,17 +61,17 @@ func SendChatEventUserJoined(event events.UserJoinedEvent) {},}- SendEventToWebhooks(webhookEvent)+ s.SendEventToWebhooks(webhookEvent)}-// SendChatEventUserParted sends a webhook notifying that a user has parted.-func SendChatEventUserParted(event events.UserPartEvent) {+// SendChatEventUserParted dispatches a user-parted event.+func (s *Service) SendChatEventUserParted(event events.UserPartEvent) {webhookEvent := WebhookEvent{Type: events.UserParted,EventData: &WebhookUserPartEventData{BaseWebhookData: BaseWebhookData{- Status: getStatus(),- ServerURL: getServerURL(),+ Status: s.getStatus(),+ ServerURL: s.serverURL(),},ID: event.ID,Timestamp: event.Timestamp,@@ -79,18 +79,17 @@ func SendChatEventUserParted(event events.UserPartEvent) {},}- SendEventToWebhooks(webhookEvent)+ s.SendEventToWebhooks(webhookEvent)}-// SendChatEventSetMessageVisibility sends a webhook notifying that the visibility of one or more-// messages has changed.-func SendChatEventSetMessageVisibility(event events.SetMessageVisibilityEvent) {+// SendChatEventSetMessageVisibility dispatches a message-visibility-changed event.+func (s *Service) SendChatEventSetMessageVisibility(event events.SetMessageVisibilityEvent) {webhookEvent := WebhookEvent{Type: models.VisibiltyToggled,EventData: &WebhookVisibilityToggleEventData{BaseWebhookData: BaseWebhookData{- Status: getStatus(),- ServerURL: getServerURL(),+ Status: s.getStatus(),+ ServerURL: s.serverURL(),},ID: event.ID,Timestamp: event.Timestamp,@@ -100,5 +99,5 @@ func SendChatEventSetMessageVisibility(event events.SetMessageVisibilityEvent) {},}- SendEventToWebhooks(webhookEvent)+ s.SendEventToWebhooks(webhookEvent)}diff --git a/core/webhooks/chat_test.go b/services/webhooks/chat_test.gosimilarity index 93%rename from core/webhooks/chat_test.gorename to services/webhooks/chat_test.goindex 7a1fc3e4ce..d89f940969 100644--- a/core/webhooks/chat_test.go+++ b/services/webhooks/chat_test.go@@ -7,10 +7,10 @@ import ("testing""time"- "github.com/owncast/owncast/core/chat/events""github.com/owncast/owncast/models""github.com/owncast/owncast/persistence/configrepository""github.com/owncast/owncast/persistence/webhookrepository"+ "github.com/owncast/owncast/services/chat/events")func TestSendChatEvent(t *testing.T) {@@ -30,7 +30,7 @@ func TestSendChatEvent(t *testing.T) {}checkPayload(t, models.MessageSent, func() {- SendChatEvent(&events.UserMessageEvent{+ testSvc.SendChatEvent(&events.UserMessageEvent{Event: events.Event{Type: events.MessageSent,ID: "id",@@ -94,7 +94,7 @@ func TestSendChatEventUsernameChanged(t *testing.T) {}checkPayload(t, models.UserNameChanged, func() {- SendChatEventUsernameChanged(events.NameChangeEvent{+ testSvc.SendChatEventUsernameChanged(events.NameChangeEvent{Event: events.Event{Type: events.UserNameChanged,ID: "id",@@ -151,7 +151,7 @@ func TestSendChatEventUserJoined(t *testing.T) {}checkPayload(t, models.UserJoined, func() {- SendChatEventUserJoined(events.UserJoinedEvent{+ testSvc.SendChatEventUserJoined(events.UserJoinedEvent{Event: events.Event{Type: events.UserJoined,ID: "id",@@ -193,7 +193,7 @@ func TestSendChatEventSetMessageVisibility(t *testing.T) {timestamp := time.Unix(72, 6).UTC()checkPayload(t, models.VisibiltyToggled, func() {- SendChatEventSetMessageVisibility(events.SetMessageVisibilityEvent{+ testSvc.SendChatEventSetMessageVisibility(events.SetMessageVisibilityEvent{Event: events.Event{Type: events.VisibiltyUpdate,ID: "id",@@ -229,8 +229,8 @@ func TestSendChatEventSetMessageVisibility(t *testing.T) {// TestWebhookHasServerStatus verifies that all webhook events include server statusfunc TestWebhookHasServerStatus(t *testing.T) {// Set up server configuration- configRepo := configrepository.Get()- configRepo.SetServerURL("http://localhost:8080")+ configRepository := configrepository.New(testDatastore)+ configRepository.SetServerURL("http://localhost:8080")eventChannel := make(chan WebhookEvent)@@ -242,7 +242,7 @@ func TestWebhookHasServerStatus(t *testing.T) {}))defer svr.Close()- webhooksRepo := webhookrepository.Get()+ webhooksRepo := webhookrepository.New(testDatastore)// Subscribe to the webhook.hook, err := webhooksRepo.InsertWebhook(svr.URL, []models.EventType{models.UserJoined})@@ -271,7 +271,7 @@ func TestWebhookHasServerStatus(t *testing.T) {Authenticated: false,}- SendChatEventUserJoined(events.UserJoinedEvent{+ testSvc.SendChatEventUserJoined(events.UserJoinedEvent{Event: events.Event{Type: events.UserJoined,ID: "id",diff --git a/services/webhooks/fediverseEngagement.go b/services/webhooks/fediverseEngagement.gonew file mode 100644index 0000000000..f6ea7aa732--- /dev/null+++ b/services/webhooks/fediverseEngagement.go@@ -0,0 +1,32 @@+package webhooks++import (+ "github.com/owncast/owncast/models"+ "github.com/owncast/owncast/services/activitypub/events"+)++// SendFediverseEngagementFollowEvent dispatches a user-followed event+// to webhook destinations, resolving the actor IRI through the+// followers repository the service was constructed with.+func (s *Service) SendFediverseEngagementFollowEvent(iri string) {+ follower, err := s.followers.GetByIRI(iri)+ if err != nil {+ return+ }+ userFollowedEvent := events.FediverseEngagementFollowEvent{}+ userFollowedEvent.SetDefaults()+ userFollowedEvent.Name = follower.Name+ userFollowedEvent.Username = follower.Username+ userFollowedEvent.Image = follower.Image.String()++ s.sendFediverseEngagementEventFollow(userFollowedEvent)+}++func (s *Service) sendFediverseEngagementEventFollow(event events.FediverseEngagementFollowEvent) {+ webhookEvent := WebhookEvent{+ Type: models.FediverseEngagementFollow,+ EventData: event,+ }++ s.SendEventToWebhooks(webhookEvent)+}diff --git a/core/webhooks/fediverseEngagement_test.go b/services/webhooks/fediverseEngagement_test.gosimilarity index 77%rename from core/webhooks/fediverseEngagement_test.gorename to services/webhooks/fediverseEngagement_test.goindex 9d565fab22..5c72b3206c 100644--- a/core/webhooks/fediverseEngagement_test.go+++ b/services/webhooks/fediverseEngagement_test.go@@ -4,13 +4,13 @@ import ("testing""time"- "github.com/owncast/owncast/activitypub/events""github.com/owncast/owncast/models"+ "github.com/owncast/owncast/services/activitypub/events")func TestSendFediverseEngagementEventFollow(t *testing.T) {checkPayload(t, models.FediverseEngagementFollow, func() {- sendFediverseEngagementEventFollow(events.FediverseEngagementFollowEvent{+ testSvc.sendFediverseEngagementEventFollow(events.FediverseEngagementFollowEvent{Event: events.Event{Timestamp: time.Unix(72, 6).UTC(),ID: "id",diff --git a/services/webhooks/stream.go b/services/webhooks/stream.gonew file mode 100644index 0000000000..a7fe61e2f2--- /dev/null+++ b/services/webhooks/stream.go@@ -0,0 +1,30 @@+package webhooks++import (+ "time"++ "github.com/teris-io/shortid"++ "github.com/owncast/owncast/models"+)++// SendStreamStatusEvent dispatches a stream-status event (started,+// stopped, title-updated, …) to all configured webhook destinations.+func (s *Service) SendStreamStatusEvent(eventType models.EventType) {+ s.sendStreamStatusEvent(eventType, shortid.MustGenerate(), time.Now())+}++func (s *Service) sendStreamStatusEvent(eventType models.EventType, id string, timestamp time.Time) {+ s.SendEventToWebhooks(WebhookEvent{+ Type: eventType,+ EventData: map[string]interface{}{+ "id": id,+ "name": s.configRepository.GetServerName(),+ "summary": s.configRepository.GetServerSummary(),+ "streamTitle": s.configRepository.GetStreamTitle(),+ "status": s.getStatus(),+ "serverURL": s.configRepository.GetServerURL(),+ "timestamp": timestamp,+ },+ })+}diff --git a/core/webhooks/stream_test.go b/services/webhooks/stream_test.gosimilarity index 81%rename from core/webhooks/stream_test.gorename to services/webhooks/stream_test.goindex 3100e08674..bd116b1b36 100644--- a/core/webhooks/stream_test.go+++ b/services/webhooks/stream_test.go@@ -4,20 +4,20 @@ import ("testing""time"- "github.com/owncast/owncast/core/chat/events""github.com/owncast/owncast/models""github.com/owncast/owncast/persistence/configrepository"+ "github.com/owncast/owncast/services/chat/events")func TestSendStreamStatusEvent(t *testing.T) {- configRepository := configrepository.Get()+ configRepository := configrepository.New(testDatastore)configRepository.SetServerName("my server")configRepository.SetServerSummary("my server where I stream")configRepository.SetStreamTitle("my stream")checkPayload(t, models.StreamStarted, func() {- sendStreamStatusEvent(events.StreamStarted, "id", time.Unix(72, 6).UTC())+ testSvc.sendStreamStatusEvent(events.StreamStarted, "id", time.Unix(72, 6).UTC())}, `{"id": "id","name": "my server",diff --git a/core/webhooks/webhooks.go b/services/webhooks/webhooks.gosimilarity index 63%rename from core/webhooks/webhooks.gorename to services/webhooks/webhooks.goindex d42db85330..af6602f03d 100644--- a/core/webhooks/webhooks.go+++ b/services/webhooks/webhooks.go@@ -1,3 +1,8 @@+// Package webhooks dispatches Owncast events (chat messages, stream+// status changes, fediverse engagement, …) to user-configured HTTP+// destinations via a bounded worker pool. Construct a *Service in+// main.go with the stream status callback and the followers repository,+// then call Start to launch the workers.package webhooksimport (@@ -5,8 +10,7 @@ import ("time""github.com/owncast/owncast/models"- "github.com/owncast/owncast/persistence/configrepository"- "github.com/owncast/owncast/persistence/webhookrepository"+ "github.com/owncast/owncast/services/activitypub/persistence/followersrepository")// BaseWebhookData contains common fields shared across all webhook event data.@@ -68,25 +72,33 @@ type WebhookVisibilityToggleEventData struct {MessageIDs []string `json:"ids"`}-// SendEventToWebhooks will send a single webhook event to all webhook destinations.-func SendEventToWebhooks(payload WebhookEvent) {- sendEventToWebhooks(payload, nil)+// SendEventToWebhooks fans an event out to every configured webhook+// destination subscribed to that event type.+func (s *Service) SendEventToWebhooks(payload WebhookEvent) {+ s.sendEventToWebhooks(payload, nil)}-func sendEventToWebhooks(payload WebhookEvent, wg *sync.WaitGroup) {- webhooksRepo := webhookrepository.Get()- webhooks := webhooksRepo.GetWebhooksForEvent(payload.Type)+// sendEventToWebhooks is the dispatch internal that also accepts an+// optional waitgroup so callers (tests, batched senders) can wait for+// all destinations to be drained.+func (s *Service) sendEventToWebhooks(payload WebhookEvent, wg *sync.WaitGroup) {+ webhooks := s.webhookRepository.GetWebhooksForEvent(payload.Type)for _, webhook := range webhooks {- // Use wg to track the number of notifications to be sent.if wg != nil {wg.Add(1)}- addToQueue(webhook, payload, wg)+ s.addToQueue(webhook, payload, wg)}}-func getServerURL() string {- configRepo := configrepository.Get()- return configRepo.GetServerURL()+// serverURL is the helper used in event payloads.+func (s *Service) serverURL() string {+ return s.configRepository.GetServerURL()+}++// Followers exposes the followers repository the service was+// constructed with. Used by the fediverse-engagement event builder.+func (s *Service) Followers() followersrepository.FollowersRepository {+ return s.followers}diff --git a/core/webhooks/webhooks_test.go b/services/webhooks/webhooks_test.gosimilarity index 85%rename from core/webhooks/webhooks_test.gorename to services/webhooks/webhooks_test.goindex 17ddb182ac..28d4302f15 100644--- a/core/webhooks/webhooks_test.go+++ b/services/webhooks/webhooks_test.go@@ -12,12 +12,13 @@ import ("testing""time"- "github.com/owncast/owncast/core/chat/events"- "github.com/owncast/owncast/core/data"+ jsonpatch "gopkg.in/evanphx/json-patch.v5"+"github.com/owncast/owncast/models""github.com/owncast/owncast/persistence/configrepository""github.com/owncast/owncast/persistence/webhookrepository"- jsonpatch "gopkg.in/evanphx/json-patch.v5"+ "github.com/owncast/owncast/services/chat/events"+ "github.com/owncast/owncast/services/datastore")func fakeGetStatus() models.Status {@@ -31,6 +32,14 @@ func fakeGetStatus() models.Status {}}+// testSvc is the *Service used by tests in this package. Constructed+// in TestMain after the in-memory datastore is up so the worker pool+// has somewhere to dispatch.+var (+ testSvc *Service+ testDatastore *datastore.Datastore+)+func TestMain(m *testing.M) {dbFile, err := os.CreateTemp(os.TempDir(), "owncast-test-db.db")if err != nil {@@ -39,17 +48,25 @@ func TestMain(m *testing.M) {dbFile.Close()defer os.Remove(dbFile.Name())- if err := data.SetupPersistence(dbFile.Name()); err != nil {+ ds, err := datastore.SetupPersistence(dbFile.Name(), os.TempDir())+ if err != nil {panic(err)}+ testDatastore = ds// Set up server URL for tests- configRepo := configrepository.Get()- configRepo.SetServerURL("http://localhost:8080")+ configRepository := configrepository.New(testDatastore)+ configRepository.SetServerURL("http://localhost:8080")+ webhookRepository := webhookrepository.New(testDatastore)- SetupWebhooks(fakeGetStatus)+ testSvc = New(Deps{+ GetStatus: fakeGetStatus,+ ConfigRepository: configRepository,+ WebhookRepository: webhookRepository,+ })+ testSvc.Start()- defer close(queue)+ defer close(testSvc.queue)m.Run()}@@ -58,7 +75,7 @@ func TestMain(m *testing.M) {// this test ensures that `SendToWebhooks` without a `WaitGroup` doesn't panic.func TestPublicSend(t *testing.T) {// Send enough events to be sure at least one worker delivers a second event.- eventsCount := webhookWorkerPoolSize + 1+ eventsCount := testSvc.workerPoolSize + 1var wg sync.WaitGroupwg.Add(eventsCount)@@ -68,7 +85,7 @@ func TestPublicSend(t *testing.T) {}))defer svr.Close()- webhooksRepo := webhookrepository.Get()+ webhooksRepo := webhookrepository.New(testDatastore)hook, err := webhooksRepo.InsertWebhook(svr.URL, []models.EventType{models.MessageSent})if err != nil {@@ -85,7 +102,7 @@ func TestPublicSend(t *testing.T) {EventData: struct{}{},Type: models.MessageSent,}- SendEventToWebhooks(wh)+ testSvc.SendEventToWebhooks(wh)}wg.Wait()@@ -115,7 +132,7 @@ func TestRouting(t *testing.T) {}))defer svr.Close()- webhooksRepo := webhookrepository.Get()+ webhooksRepo := webhookrepository.New(testDatastore)for _, eventType := range eventTypes {hook, err := webhooksRepo.InsertWebhook(svr.URL+"/"+eventType, []models.EventType{eventType})@@ -136,7 +153,7 @@ func TestRouting(t *testing.T) {EventData: struct{}{},Type: eventType,}- sendEventToWebhooks(wh, &wg)+ testSvc.sendEventToWebhooks(wh, &wg)}wg.Wait()@@ -158,7 +175,7 @@ func TestMultiple(t *testing.T) {}))defer svr.Close()- webhooksRepo := webhookrepository.Get()+ webhooksRepo := webhookrepository.New(testDatastore)for i := 0; i < times; i++ {hook, err := webhooksRepo.InsertWebhook(fmt.Sprintf("%v/%v", svr.URL, i), []models.EventType{models.MessageSent})@@ -178,7 +195,7 @@ func TestMultiple(t *testing.T) {EventData: struct{}{},Type: models.MessageSent,}- sendEventToWebhooks(wh, &wg)+ testSvc.sendEventToWebhooks(wh, &wg)wg.Wait()@@ -198,7 +215,7 @@ func TestTimestamps(t *testing.T) {}))defer svr.Close()- webhooksRepo := webhookrepository.Get()+ webhooksRepo := webhookrepository.New(testDatastore)for i, eventType := range eventTypes {hook, err := webhooksRepo.InsertWebhook(svr.URL+"/"+eventType, []models.EventType{eventType})@@ -219,7 +236,7 @@ func TestTimestamps(t *testing.T) {EventData: struct{}{},Type: eventTypes[0],}- sendEventToWebhooks(wh, &wg)+ testSvc.sendEventToWebhooks(wh, &wg)wg.Wait()@@ -276,13 +293,13 @@ func TestParallel(t *testing.T) {var wgStart sync.WaitGroupfinished := make(chan int)- wgStart.Add(webhookWorkerPoolSize)+ wgStart.Add(testSvc.workerPoolSize)svr := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {myId := atomic.AddUint32(&calls, 1)// We made it to the pool size + 1 event, so we're done with the test.- if myId == uint32(webhookWorkerPoolSize)+1 {+ if myId == uint32(testSvc.workerPoolSize)+1 {close(finished)return}@@ -299,7 +316,7 @@ func TestParallel(t *testing.T) {}))defer svr.Close()- webhooksRepo := webhookrepository.Get()+ webhooksRepo := webhookrepository.New(testDatastore)hook, err := webhooksRepo.InsertWebhook(svr.URL, []models.EventType{models.MessageSent})if err != nil {@@ -313,12 +330,12 @@ func TestParallel(t *testing.T) {var wgMessages sync.WaitGroup- for i := 0; i < webhookWorkerPoolSize+1; i++ {+ for i := 0; i < testSvc.workerPoolSize+1; i++ {wh := WebhookEvent{EventData: struct{}{},Type: models.MessageSent,}- sendEventToWebhooks(wh, &wgMessages)+ testSvc.sendEventToWebhooks(wh, &wgMessages)}wgMessages.Wait()@@ -336,7 +353,7 @@ func checkPayload(t *testing.T, eventType models.EventType, send func(), expecte}))defer svr.Close()- webhooksRepo := webhookrepository.Get()+ webhooksRepo := webhookrepository.New(testDatastore)// Subscribe to the webhook.hook, err := webhooksRepo.InsertWebhook(svr.URL, []models.EventType{eventType})diff --git a/services/webhooks/workerpool.go b/services/webhooks/workerpool.gonew file mode 100644index 0000000000..57030f8b96--- /dev/null+++ b/services/webhooks/workerpool.go@@ -0,0 +1,137 @@+package webhooks++import (+ "bytes"+ "encoding/json"+ "net/http"+ "runtime"+ "sync"++ log "github.com/sirupsen/logrus"++ "github.com/owncast/owncast/models"+ "github.com/owncast/owncast/persistence/configrepository"+ "github.com/owncast/owncast/persistence/webhookrepository"+ "github.com/owncast/owncast/services/activitypub/persistence/followersrepository"+)++// Job bundles a single webhook destination + payload for a worker.+type Job struct {+ wg *sync.WaitGroup+ payload WebhookEvent+ webhook models.Webhook+}++// Service owns the webhook dispatcher: a bounded worker pool that+// fans events out to configured destinations.+//+// Most events also need the current stream status and follower details+// to build their payloads, so those collaborators are dependencies.+type Service struct {+ workerPoolSize int+ queue chan Job++ // getStatus returns the current stream status for inclusion in+ // outbound event payloads. Supplied by main.go (the stream service).+ getStatus func() models.Status++ // followers is consulted by the fediverse-engagement builder to+ // resolve actor IRIs to display data.+ followers followersrepository.FollowersRepository++ // configRepository provides server metadata included in stream-status+ // event payloads.+ configRepository configrepository.ConfigRepository++ // webhookRepository stores configured webhook destinations and is+ // consulted when dispatching events as well as when marking a+ // destination as used after a successful send.+ webhookRepository webhookrepository.WebhookRepository+}++// Deps lists every collaborator a *Service needs at construction.+type Deps struct {+ GetStatus func() models.Status+ Followers followersrepository.FollowersRepository+ ConfigRepository configrepository.ConfigRepository+ WebhookRepository webhookrepository.WebhookRepository+}++// New constructs an idle webhook Service. Call Start to launch the+// worker pool.+func New(deps Deps) *Service {+ return &Service{+ workerPoolSize: runtime.GOMAXPROCS(0),+ getStatus: deps.GetStatus,+ followers: deps.Followers,+ configRepository: deps.ConfigRepository,+ webhookRepository: deps.WebhookRepository,+ }+}++// SetGetStatus wires the stream-status callback after construction.+// Exists because the composition root has a small cycle: webhooks+// needs stream.GetStatus, but stream needs *webhooks.Service. main.go+// constructs webhooks first with a nil callback, then fills it in once+// streamSvc exists. Must be called before Start.+func (s *Service) SetGetStatus(fn func() models.Status) {+ s.getStatus = fn+}++// Start launches the worker goroutines that drain the queue.+func (s *Service) Start() {+ s.queue = make(chan Job)+ for i := 1; i <= s.workerPoolSize; i++ {+ go s.worker(i)+ }+}++func (s *Service) addToQueue(webhook models.Webhook, payload WebhookEvent, wg *sync.WaitGroup) {+ log.Tracef("Queued Event %s for Webhook %s", payload.Type, webhook.URL)+ s.queue <- Job{wg, payload, webhook}+}++func (s *Service) worker(workerID int) {+ log.Debugf("Started Webhook worker %d", workerID)++ for job := range s.queue {+ log.Debugf("Event %s sent to Webhook %s using worker %d", job.payload.Type, job.webhook.URL, workerID)++ if err := s.sendWebhook(job); err != nil {+ log.Errorf("Event: %s failed to send to webhook: %s Error: %s", job.payload.Type, job.webhook.URL, err)+ }+ log.Tracef("Done with Event %s to Webhook %s using worker %d", job.payload.Type, job.webhook.URL, workerID)+ if job.wg != nil {+ job.wg.Done()+ }+ }+}++func (s *Service) sendWebhook(job Job) error {+ jsonText, err := json.Marshal(job.payload)+ if err != nil {+ return err+ }++ req, err := http.NewRequest("POST", job.webhook.URL, bytes.NewReader(jsonText))+ if err != nil {+ return err+ }++ req.Header.Set("Content-Type", "application/json")++ client := &http.Client{}++ resp, err := client.Do(req)+ if err != nil {+ return err+ }++ defer resp.Body.Close()++ if err := s.webhookRepository.SetWebhookAsUsed(job.webhook); err != nil {+ log.Warnln(err)+ }++ return nil+}diff --git a/test/automated/activitypub/Dockerfile b/test/automated/activitypub/Dockerfileindex f8929a3f1e..11d4d3acca 100644--- a/test/automated/activitypub/Dockerfile+++ b/test/automated/activitypub/Dockerfile@@ -1,4 +1,4 @@-FROM golang:1.25-bookworm+FROM golang:1.26-bookwormRUN apt-get update && apt-get install -y \gcc make \diff --git a/tools/go.sum b/tools/go.sumindex 6097d7eef4..c70545eac7 100644--- a/tools/go.sum+++ b/tools/go.sum@@ -252,8 +252,8 @@ github.com/go-openapi/swag/jsonname v0.25.4 h1:bZH0+MsS03MbnwBXYhuTttMOqk+5KcQ98github.com/go-openapi/swag/jsonname v0.25.4/go.mod h1:GPVEk9CWVhNvWhZgrnvRA6utbAltopbKwDu8mXNUMag=github.com/go-openapi/testify/v2 v2.0.2 h1:X999g3jeLcoY8qctY/c/Z8iBHTbwLz7R2WXd6Ub6wls=github.com/go-openapi/testify/v2 v2.0.2/go.mod h1:HCPmvFFnheKK2BuwSA0TbbdxJ3I16pjwMkYkP4Ywn54=-github.com/go-quicktest/qt v1.101.0 h1:O1K29Txy5P2OK0dGo59b7b0LR6wKfIhttaAhHUyn7eI=-github.com/go-quicktest/qt v1.101.0/go.mod h1:14Bz/f7NwaXPtdYEgzsx46kqSxVwTbzVZsDC26tQJow=+github.com/go-quicktest/qt v1.102.0 h1:HSQxCeh5YZH3EL3W39ixjtyaEhcWSXQHtHnMBzSs474=+github.com/go-quicktest/qt v1.102.0/go.mod h1:p4lGIVX+8Wa6ZPNDvqcxq36XpUDLh42FLetFU7odllI=github.com/go-sql-driver/mysql v1.9.3 h1:U/N249h2WzJ3Ukj8SowVFjdtZKfu9vlLZxjPXV1aweo=github.com/go-sql-driver/mysql v1.9.3/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU=github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=@@ -332,8 +332,7 @@ github.com/golangci/go-printf-func-name v0.1.1 h1:hIYTFJqAGp1iwoIfsNTpoq1xZAaroggithub.com/golangci/go-printf-func-name v0.1.1/go.mod h1:Es64MpWEZbh0UBtTAICOZiB+miW53w/K9Or/4QogJss=github.com/golangci/gofmt v0.0.0-20250106114630-d62b90e6713d h1:viFft9sS/dxoYY0aiOTsLKO2aZQAPT4nlQCsimGcSGE=github.com/golangci/gofmt v0.0.0-20250106114630-d62b90e6713d/go.mod h1:ivJ9QDg0XucIkmwhzCDsqcnxxlDStoTl89jDMIoNxKY=-github.com/golangci/golangci-lint/v2 v2.12.1 h1:Rr07Ps/u+kvQqSO4L026WOSVvOlMU+RZTa/lossFaJA=-github.com/golangci/golangci-lint/v2 v2.12.1/go.mod h1:e/wBh0xvA13ag/OWByUmvjc9oYPtcKGpXycldJbc7t0=+github.com/golangci/golangci-lint/v2 v2.12.2 h1:7+d1uY0bq1MU2UV3R5pW5Q7QWdcoq4naMRXM+gsJKrs=github.com/golangci/golangci-lint/v2 v2.12.2/go.mod h1:opqHHuIcTG2R+4akzWMd4o1BnD9/1LcjICWOujr91U8=github.com/golangci/golines v0.15.0 h1:Qnph25g8Y1c5fdo1X7GaRDGgnMHgnxh4Gk4VfPTtRx0=github.com/golangci/golines v0.15.0/go.mod h1:AZjXd23tbHMpowhtnGlj9KCNsysj72aeZVVHnVcZx10=@@ -604,8 +603,7 @@ github.com/otiai10/mint v1.3.0/go.mod h1:F5AjcsTsWUqX+Na9fpHb52P8pcRX2CI6A3ctIT9github.com/otiai10/mint v1.3.1/go.mod h1:/yxELlJQ0ufhjUwhshSj+wFjZ78CnZ48/1wtmBH1OTc=github.com/pelletier/go-toml v1.9.5 h1:4yBQzkHv+7BHq2PQUZF3Mx0IYxG7LsP222s7Agd3ve8=github.com/pelletier/go-toml v1.9.5/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c=-github.com/pelletier/go-toml/v2 v2.3.0 h1:k59bC/lIZREW0/iVaQR8nDHxVq8OVlIzYCOJf421CaM=-github.com/pelletier/go-toml/v2 v2.3.0/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=+github.com/pelletier/go-toml/v2 v2.3.1 h1:MYEvvGnQjeNkRF1qUuGolNtNExTDwct51yp7olPtrEc=github.com/pelletier/go-toml/v2 v2.3.1/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=github.com/perimeterx/marshmallow v1.1.5 h1:a2LALqQ1BlHM8PZblsDdidgv1mWi1DgC2UmX50IvK2s=github.com/perimeterx/marshmallow v1.1.5/go.mod h1:dsXbUu8CRzfYP5a87xpp0xq9S3u0Vchtcl8we9tYaXw=@@ -670,8 +668,7 @@ github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=github.com/ryancurrah/gomodguard v1.4.1 h1:eWC8eUMNZ/wM/PWuZBv7JxxqT5fiIKSIyTvjb7Elr+g=github.com/ryancurrah/gomodguard v1.4.1/go.mod h1:qnMJwV1hX9m+YJseXEBhd2s90+1Xn6x9dLz11ualI1I=-github.com/ryancurrah/gomodguard/v2 v2.1.0 h1:iIIARHe7Fsp10LY5utfMmYA++hkVuKsMFGDzxnVcijU=-github.com/ryancurrah/gomodguard/v2 v2.1.0/go.mod h1:ryDqr6as4otkNbUp/U0m7zAsxGpwcJ9NtL6mvy9Zzdw=+github.com/ryancurrah/gomodguard/v2 v2.1.3 h1:E7sz3PJwE9Ba1reVxSpF6XLCPJZ74Kfw/LabTNM4GIA=github.com/ryancurrah/gomodguard/v2 v2.1.3/go.mod h1:CQicdLGatWMxLX53JzoBjYlsNZhHbmLv2AVa0s2aivU=github.com/ryanrolds/sqlclosecheck v0.6.0 h1:pEyL9okISdg1F1SEpJNlrEotkTGerv5BMk7U4AG0eVg=github.com/ryanrolds/sqlclosecheck v0.6.0/go.mod h1:xyX16hsDaCMXHrMJ3JMzGf5OpDfHTOTTQrT7HOFUmeU=@@ -764,8 +761,7 @@ github.com/ultraware/whitespace v0.2.0 h1:TYowo2m9Nfj1baEQBjuHzvMRbp19i+RCcRYrSWgithub.com/ultraware/whitespace v0.2.0/go.mod h1:XcP1RLD81eV4BW8UhQlpaR+SDc2givTvyI8a586WjW8=github.com/uudashr/gocognit v1.2.1 h1:CSJynt5txTnORn/DkhiB4mZjwPuifyASC8/6Q0I/QS4=github.com/uudashr/gocognit v1.2.1/go.mod h1:acaubQc6xYlXFEMb9nWX2dYBzJ/bIjEkc1zzvyIZg5Q=-github.com/uudashr/iface v1.4.1 h1:J16Xl1wyNX9ofhpHmQ9h9gk5rnv2A6lX/2+APLTo0zU=-github.com/uudashr/iface v1.4.1/go.mod h1:pbeBPlbuU2qkNDn0mmfrxP2X+wjPMIQAy+r1MBXSXtg=+github.com/uudashr/iface v1.4.2 h1:06Vq5RKVYThBsj0Bnw4oasMjD1r+7CE/bcKOA8dVSvg=github.com/uudashr/iface v1.4.2/go.mod h1:pbeBPlbuU2qkNDn0mmfrxP2X+wjPMIQAy+r1MBXSXtg=github.com/vmware-labs/yaml-jsonpath v0.3.2 h1:/5QKeCBGdsInyDCyVNLbXyilb61MXGi9NP674f9Hobk=github.com/vmware-labs/yaml-jsonpath v0.3.2/go.mod h1:U6whw1z03QyqgWdgXxvVnQ90zN1BWz5V+51Ewf8k+rQ=@@ -1200,8 +1196,7 @@ honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k=honnef.co/go/tools v0.7.0 h1:w6WUp1VbkqPEgLz4rkBzH/CSU6HkoqNLp6GstyTx3lU=honnef.co/go/tools v0.7.0/go.mod h1:pm29oPxeP3P82ISxZDgIYeOaf9ta6Pi0EWvCFoLG2vc=-mvdan.cc/gofumpt v0.9.2 h1:zsEMWL8SVKGHNztrx6uZrXdp7AX8r421Vvp23sz7ik4=-mvdan.cc/gofumpt v0.9.2/go.mod h1:iB7Hn+ai8lPvofHd9ZFGVg2GOr8sBUw1QUWjNbmIL/s=+mvdan.cc/gofumpt v0.10.0 h1:yGGpRS2pBN2OQIi7b21IXknJna7faPkFaVfHLrN6Euo=mvdan.cc/gofumpt v0.10.0/go.mod h1:sU2ElXHzOEmvoPqfutYG7uunlueR4K2T1JFml40SzP4=mvdan.cc/unparam v0.0.0-20251027182757-5beb8c8f8f15 h1:ssMzja7PDPJV8FStj7hq9IKiuiKhgz9ErWw+m68e7DI=mvdan.cc/unparam v0.0.0-20251027182757-5beb8c8f8f15/go.mod h1:4M5MMXl2kW6fivUT6yRGpLLPNfuGtU2Z0cPvFquGDYU=diff --git a/utils/performanceTimer.go b/utils/performanceTimer.goindex 5d30207479..c4f5b4af15 100644--- a/utils/performanceTimer.go+++ b/utils/performanceTimer.go@@ -6,42 +6,56 @@ import ("time")-var l = sync.Mutex{}--// The "start" timestamp of a timing event.-var _pointsInTime = make(map[string]time.Time)+// PerformanceTracker records the start times of named events and+// maintains a small rolling sample of their durations, exposing the+// average. State is held per-instance: construct with NewPerformanceTracker+// and inject into the component that needs it.+type PerformanceTracker struct {+ lock sync.Mutex++ // The "start" timestamp of a timing event.+ pointsInTime map[string]time.Time++ // A collection of timestamp durations for returning the average of.+ durationStorage map[string][]float64+}-// A collection of timestamp durations for returning the average of.-var _durationStorage = make(map[string][]float64)+// NewPerformanceTracker constructs an empty PerformanceTracker.+func NewPerformanceTracker() *PerformanceTracker {+ return &PerformanceTracker{+ pointsInTime: make(map[string]time.Time),+ durationStorage: make(map[string][]float64),+ }+}// StartPerformanceMonitor will keep track of the start time of this event.-func StartPerformanceMonitor(key string) {- l.Lock()- if len(_durationStorage[key]) > 20 {- _durationStorage[key] = removeHighValue(_durationStorage[key])+func (t *PerformanceTracker) StartPerformanceMonitor(key string) {+ t.lock.Lock()+ if len(t.durationStorage[key]) > 20 {+ t.durationStorage[key] = removeHighValue(t.durationStorage[key])}- _pointsInTime[key] = time.Now()- l.Unlock()+ t.pointsInTime[key] = time.Now()+ t.lock.Unlock()}// GetAveragePerformance will return the average durations for the event.-func GetAveragePerformance(key string) float64 {- timestamp := _pointsInTime[key]+func (t *PerformanceTracker) GetAveragePerformance(key string) float64 {+ t.lock.Lock()+ defer t.lock.Unlock()++ timestamp := t.pointsInTime[key]if timestamp.IsZero() {return 0}- l.Lock()- defer l.Unlock()-delta := time.Since(timestamp).Seconds()- _durationStorage[key] = append(_durationStorage[key], delta)- if len(_durationStorage[key]) < 8 {+ t.durationStorage[key] = append(t.durationStorage[key], delta)+ if len(t.durationStorage[key]) < 8 {return 0}- _durationStorage[key] = removeHighValue(_durationStorage[key])+ t.durationStorage[key] = removeHighValue(t.durationStorage[key])- return Avg(_durationStorage[key])+ return Avg(t.durationStorage[key])}func removeHighValue(values []float64) []float64 {diff --git a/webserver/handlers/admin.go b/webserver/handlers/admin.goindex 878544460f..3cf28ff825 100644--- a/webserver/handlers/admin.go+++ b/webserver/handlers/admin.go@@ -3,310 +3,303 @@ package handlersimport ("net/http"- "github.com/owncast/owncast/core/rtmp""github.com/owncast/owncast/webserver/handlers/admin""github.com/owncast/owncast/webserver/handlers/generated""github.com/owncast/owncast/webserver/router/middleware")-func (*ServerInterfaceImpl) StatusAdmin(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.Status)(w, r)+func (s *ServerInterfaceImpl) StatusAdmin(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.Status)(w, r)}-func (*ServerInterfaceImpl) StatusAdminOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.Status)(w, r)+func (s *ServerInterfaceImpl) StatusAdminOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.Status)(w, r)}-func (*ServerInterfaceImpl) DisconnectInboundConnection(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.DisconnectInboundConnection)(w, r)+func (s *ServerInterfaceImpl) DisconnectInboundConnection(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.DisconnectInboundConnection)(w, r)}-func (*ServerInterfaceImpl) DisconnectInboundConnectionOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.DisconnectInboundConnection)(w, r)+func (s *ServerInterfaceImpl) DisconnectInboundConnectionOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.DisconnectInboundConnection)(w, r)}-func (*ServerInterfaceImpl) GetServerConfig(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.GetServerConfig)(w, r)+func (s *ServerInterfaceImpl) GetServerConfig(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.GetServerConfig)(w, r)}-func (*ServerInterfaceImpl) GetServerConfigOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.GetServerConfig)(w, r)+func (s *ServerInterfaceImpl) GetServerConfigOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.GetServerConfig)(w, r)}-func (*ServerInterfaceImpl) GetViewersOverTime(w http.ResponseWriter, r *http.Request, params generated.GetViewersOverTimeParams) {- middleware.RequireAdminAuth(admin.GetViewersOverTime)(w, r)+func (s *ServerInterfaceImpl) GetViewersOverTime(w http.ResponseWriter, r *http.Request, params generated.GetViewersOverTimeParams) {+ s.h.middleware.RequireAdminAuth(s.h.admin.GetViewersOverTime)(w, r)}-func (*ServerInterfaceImpl) GetViewersOverTimeOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.GetViewersOverTime)(w, r)+func (s *ServerInterfaceImpl) GetViewersOverTimeOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.GetViewersOverTime)(w, r)}-func (*ServerInterfaceImpl) GetActiveViewers(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.GetActiveViewers)(w, r)+func (s *ServerInterfaceImpl) GetActiveViewers(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.GetActiveViewers)(w, r)}-func (*ServerInterfaceImpl) GetActiveViewersOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.GetActiveViewers)(w, r)+func (s *ServerInterfaceImpl) GetActiveViewersOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.GetActiveViewers)(w, r)}-func (*ServerInterfaceImpl) GetHardwareStats(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.GetHardwareStats)(w, r)+func (s *ServerInterfaceImpl) GetHardwareStats(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.GetHardwareStats)(w, r)}-func (*ServerInterfaceImpl) GetHardwareStatsOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.GetHardwareStats)(w, r)+func (s *ServerInterfaceImpl) GetHardwareStatsOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.GetHardwareStats)(w, r)}-func (*ServerInterfaceImpl) GetConnectedChatClients(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.GetConnectedChatClients)(w, r)+func (s *ServerInterfaceImpl) GetConnectedChatClients(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.GetConnectedChatClients)(w, r)}-func (*ServerInterfaceImpl) GetConnectedChatClientsOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.GetConnectedChatClients)(w, r)+func (s *ServerInterfaceImpl) GetConnectedChatClientsOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.GetConnectedChatClients)(w, r)}-func (*ServerInterfaceImpl) GetChatMessagesAdmin(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.GetChatMessages)(w, r)+func (s *ServerInterfaceImpl) GetChatMessagesAdmin(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.GetChatMessages)(w, r)}-func (*ServerInterfaceImpl) GetChatMessagesAdminOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.GetChatMessages)(w, r)+func (s *ServerInterfaceImpl) GetChatMessagesAdminOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.GetChatMessages)(w, r)}-func (*ServerInterfaceImpl) UpdateMessageVisibilityAdmin(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.UpdateMessageVisibility)(w, r)+func (s *ServerInterfaceImpl) UpdateMessageVisibilityAdmin(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.UpdateMessageVisibility)(w, r)}-func (*ServerInterfaceImpl) UpdateMessageVisibilityAdminOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.UpdateMessageVisibility)(w, r)+func (s *ServerInterfaceImpl) UpdateMessageVisibilityAdminOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.UpdateMessageVisibility)(w, r)}-func (*ServerInterfaceImpl) UpdateUserEnabledAdmin(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.UpdateUserEnabled)(w, r)+func (s *ServerInterfaceImpl) UpdateUserEnabledAdmin(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.UpdateUserEnabled)(w, r)}-func (*ServerInterfaceImpl) UpdateUserEnabledAdminOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.UpdateUserEnabled)(w, r)+func (s *ServerInterfaceImpl) UpdateUserEnabledAdminOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.UpdateUserEnabled)(w, r)}-func (*ServerInterfaceImpl) GetDisabledUsers(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.GetDisabledUsers)(w, r)+func (s *ServerInterfaceImpl) GetDisabledUsers(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.GetDisabledUsers)(w, r)}-func (*ServerInterfaceImpl) GetDisabledUsersOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.GetDisabledUsers)(w, r)+func (s *ServerInterfaceImpl) GetDisabledUsersOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.GetDisabledUsers)(w, r)}-func (*ServerInterfaceImpl) BanIPAddress(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.BanIPAddress)(w, r)+func (s *ServerInterfaceImpl) BanIPAddress(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.BanIPAddress)(w, r)}-func (*ServerInterfaceImpl) BanIPAddressOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.BanIPAddress)(w, r)+func (s *ServerInterfaceImpl) BanIPAddressOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.BanIPAddress)(w, r)}-func (*ServerInterfaceImpl) UnbanIPAddress(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.UnBanIPAddress)(w, r)+func (s *ServerInterfaceImpl) UnbanIPAddress(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.UnBanIPAddress)(w, r)}-func (*ServerInterfaceImpl) UnbanIPAddressOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.UnBanIPAddress)(w, r)+func (s *ServerInterfaceImpl) UnbanIPAddressOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.UnBanIPAddress)(w, r)}-func (*ServerInterfaceImpl) GetIPAddressBans(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.GetIPAddressBans)(w, r)+func (s *ServerInterfaceImpl) GetIPAddressBans(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.GetIPAddressBans)(w, r)}-func (*ServerInterfaceImpl) GetIPAddressBansOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.GetIPAddressBans)(w, r)+func (s *ServerInterfaceImpl) GetIPAddressBansOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.GetIPAddressBans)(w, r)}-func (*ServerInterfaceImpl) UpdateUserModerator(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.UpdateUserModerator)(w, r)+func (s *ServerInterfaceImpl) UpdateUserModerator(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.UpdateUserModerator)(w, r)}-func (*ServerInterfaceImpl) UpdateUserModeratorOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.UpdateUserModerator)(w, r)+func (s *ServerInterfaceImpl) UpdateUserModeratorOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.UpdateUserModerator)(w, r)}-func (*ServerInterfaceImpl) GetModerators(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.GetModerators)(w, r)+func (s *ServerInterfaceImpl) GetModerators(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.GetModerators)(w, r)}-func (*ServerInterfaceImpl) GetModeratorsOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.GetModerators)(w, r)+func (s *ServerInterfaceImpl) GetModeratorsOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.GetModerators)(w, r)}-func (*ServerInterfaceImpl) GetLogs(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.GetLogs)(w, r)+func (s *ServerInterfaceImpl) GetLogs(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(admin.GetLogs)(w, r)}-func (*ServerInterfaceImpl) GetLogsOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.GetLogs)(w, r)+func (s *ServerInterfaceImpl) GetLogsOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(admin.GetLogs)(w, r)}-func (*ServerInterfaceImpl) GetWarnings(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.GetWarnings)(w, r)+func (s *ServerInterfaceImpl) GetWarnings(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(admin.GetWarnings)(w, r)}-func (*ServerInterfaceImpl) GetWarningsOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.GetWarnings)(w, r)+func (s *ServerInterfaceImpl) GetWarningsOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(admin.GetWarnings)(w, r)}-func (*ServerInterfaceImpl) GetFollowersAdmin(w http.ResponseWriter, r *http.Request, params generated.GetFollowersAdminParams) {- middleware.RequireAdminAuth(middleware.HandlePagination(GetFollowers))(w, r)+func (s *ServerInterfaceImpl) GetFollowersAdmin(w http.ResponseWriter, r *http.Request, params generated.GetFollowersAdminParams) {+ s.h.middleware.RequireAdminAuth(middleware.HandlePagination(s.h.GetFollowers))(w, r)}-func (*ServerInterfaceImpl) GetFollowersAdminOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(middleware.HandlePagination(GetFollowers))(w, r)+func (s *ServerInterfaceImpl) GetFollowersAdminOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(middleware.HandlePagination(s.h.GetFollowers))(w, r)}-func (*ServerInterfaceImpl) GetPendingFollowRequests(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.GetPendingFollowRequests)(w, r)+func (s *ServerInterfaceImpl) GetPendingFollowRequests(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.GetPendingFollowRequests)(w, r)}-func (*ServerInterfaceImpl) GetPendingFollowRequestsOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.GetPendingFollowRequests)(w, r)+func (s *ServerInterfaceImpl) GetPendingFollowRequestsOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.GetPendingFollowRequests)(w, r)}-func (*ServerInterfaceImpl) GetBlockedAndRejectedFollowers(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.GetBlockedAndRejectedFollowers)(w, r)+func (s *ServerInterfaceImpl) GetBlockedAndRejectedFollowers(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.GetBlockedAndRejectedFollowers)(w, r)}-func (*ServerInterfaceImpl) GetBlockedAndRejectedFollowersOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.GetBlockedAndRejectedFollowers)(w, r)+func (s *ServerInterfaceImpl) GetBlockedAndRejectedFollowersOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.GetBlockedAndRejectedFollowers)(w, r)}-func (*ServerInterfaceImpl) ApproveFollower(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.ApproveFollower)(w, r)+func (s *ServerInterfaceImpl) ApproveFollower(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.ApproveFollower)(w, r)}-func (*ServerInterfaceImpl) ApproveFollowerOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.ApproveFollower)(w, r)+func (s *ServerInterfaceImpl) ApproveFollowerOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.ApproveFollower)(w, r)}-func (*ServerInterfaceImpl) UploadCustomEmoji(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.UploadCustomEmoji)(w, r)+func (s *ServerInterfaceImpl) UploadCustomEmoji(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(admin.UploadCustomEmoji)(w, r)}-func (*ServerInterfaceImpl) UploadCustomEmojiOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.UploadCustomEmoji)(w, r)+func (s *ServerInterfaceImpl) UploadCustomEmojiOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(admin.UploadCustomEmoji)(w, r)}-func (*ServerInterfaceImpl) DeleteCustomEmoji(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.DeleteCustomEmoji)(w, r)+func (s *ServerInterfaceImpl) DeleteCustomEmoji(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(admin.DeleteCustomEmoji)(w, r)}-func (*ServerInterfaceImpl) DeleteCustomEmojiOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.DeleteCustomEmoji)(w, r)+func (s *ServerInterfaceImpl) DeleteCustomEmojiOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(admin.DeleteCustomEmoji)(w, r)}-func (*ServerInterfaceImpl) GetWebhooks(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.GetWebhooks)(w, r)+func (s *ServerInterfaceImpl) GetWebhooks(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.GetWebhooks)(w, r)}-func (*ServerInterfaceImpl) GetWebhooksOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.GetWebhooks)(w, r)+func (s *ServerInterfaceImpl) GetWebhooksOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.GetWebhooks)(w, r)}-func (*ServerInterfaceImpl) DeleteWebhook(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.DeleteWebhook)(w, r)+func (s *ServerInterfaceImpl) DeleteWebhook(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.DeleteWebhook)(w, r)}-func (*ServerInterfaceImpl) DeleteWebhookOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.DeleteWebhook)(w, r)+func (s *ServerInterfaceImpl) DeleteWebhookOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.DeleteWebhook)(w, r)}-func (*ServerInterfaceImpl) CreateWebhook(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.CreateWebhook)(w, r)+func (s *ServerInterfaceImpl) CreateWebhook(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.CreateWebhook)(w, r)}-func (*ServerInterfaceImpl) CreateWebhookOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.CreateWebhook)(w, r)+func (s *ServerInterfaceImpl) CreateWebhookOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.CreateWebhook)(w, r)}-func (*ServerInterfaceImpl) GetExternalAPIUsers(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.GetExternalAPIUsers)(w, r)+func (s *ServerInterfaceImpl) GetExternalAPIUsers(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.GetExternalAPIUsers)(w, r)}-func (*ServerInterfaceImpl) GetExternalAPIUsersOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.GetExternalAPIUsers)(w, r)+func (s *ServerInterfaceImpl) GetExternalAPIUsersOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.GetExternalAPIUsers)(w, r)}-func (*ServerInterfaceImpl) DeleteExternalAPIUser(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.DeleteExternalAPIUser)(w, r)+func (s *ServerInterfaceImpl) DeleteExternalAPIUser(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.DeleteExternalAPIUser)(w, r)}-func (*ServerInterfaceImpl) DeleteExternalAPIUserOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.DeleteExternalAPIUser)(w, r)+func (s *ServerInterfaceImpl) DeleteExternalAPIUserOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.DeleteExternalAPIUser)(w, r)}-func (*ServerInterfaceImpl) CreateExternalAPIUser(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.CreateExternalAPIUser)(w, r)+func (s *ServerInterfaceImpl) CreateExternalAPIUser(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.CreateExternalAPIUser)(w, r)}-func (*ServerInterfaceImpl) CreateExternalAPIUserOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.CreateExternalAPIUser)(w, r)+func (s *ServerInterfaceImpl) CreateExternalAPIUserOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.CreateExternalAPIUser)(w, r)}-func (*ServerInterfaceImpl) AutoUpdateOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.AutoUpdateOptions)(w, r)+func (s *ServerInterfaceImpl) AutoUpdateOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(admin.AutoUpdateOptions)(w, r)}-func (*ServerInterfaceImpl) AutoUpdateOptionsOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.AutoUpdateOptions)(w, r)+func (s *ServerInterfaceImpl) AutoUpdateOptionsOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(admin.AutoUpdateOptions)(w, r)}-func (*ServerInterfaceImpl) AutoUpdateStart(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.AutoUpdateStart)(w, r)+func (s *ServerInterfaceImpl) AutoUpdateStart(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(admin.AutoUpdateStart)(w, r)}-func (*ServerInterfaceImpl) AutoUpdateStartOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.AutoUpdateStart)(w, r)+func (s *ServerInterfaceImpl) AutoUpdateStartOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(admin.AutoUpdateStart)(w, r)}-func (*ServerInterfaceImpl) AutoUpdateForceQuit(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.AutoUpdateForceQuit)(w, r)+func (s *ServerInterfaceImpl) AutoUpdateForceQuit(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(admin.AutoUpdateForceQuit)(w, r)}-func (*ServerInterfaceImpl) AutoUpdateForceQuitOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.AutoUpdateForceQuit)(w, r)+func (s *ServerInterfaceImpl) AutoUpdateForceQuitOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(admin.AutoUpdateForceQuit)(w, r)}-func (*ServerInterfaceImpl) ResetYPRegistration(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.ResetYPRegistration)(w, r)+func (s *ServerInterfaceImpl) ResetYPRegistration(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.ResetYPRegistration)(w, r)}-func (*ServerInterfaceImpl) ResetYPRegistrationOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.ResetYPRegistration)(w, r)+func (s *ServerInterfaceImpl) ResetYPRegistrationOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.ResetYPRegistration)(w, r)}-func (*ServerInterfaceImpl) GetVideoPlaybackMetrics(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.GetVideoPlaybackMetrics)(w, r)+func (s *ServerInterfaceImpl) GetVideoPlaybackMetrics(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.GetVideoPlaybackMetrics)(w, r)}-func (*ServerInterfaceImpl) GetVideoPlaybackMetricsOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.GetVideoPlaybackMetrics)(w, r)+func (s *ServerInterfaceImpl) GetVideoPlaybackMetricsOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.GetVideoPlaybackMetrics)(w, r)}-func (*ServerInterfaceImpl) SendFederatedMessage(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SendFederatedMessage)(w, r)+func (s *ServerInterfaceImpl) SendFederatedMessage(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SendFederatedMessage)(w, r)}-func (*ServerInterfaceImpl) SendFederatedMessageOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SendFederatedMessage)(w, r)+func (s *ServerInterfaceImpl) SendFederatedMessageOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SendFederatedMessage)(w, r)}-func (*ServerInterfaceImpl) GetFederatedActions(w http.ResponseWriter, r *http.Request, params generated.GetFederatedActionsParams) {- middleware.RequireAdminAuth(middleware.HandlePagination(admin.GetFederatedActions))(w, r)+func (s *ServerInterfaceImpl) GetFederatedActions(w http.ResponseWriter, r *http.Request, params generated.GetFederatedActionsParams) {+ s.h.middleware.RequireAdminAuth(middleware.HandlePagination(s.h.admin.GetFederatedActions))(w, r)}-func (*ServerInterfaceImpl) GetFederatedActionsOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(middleware.HandlePagination(admin.GetFederatedActions))(w, r)-}--// DisconnectInboundConnection will force-disconnect an inbound stream.-func DisconnectInboundConnection(w http.ResponseWriter, r *http.Request) {- rtmp.Disconnect()- w.WriteHeader(http.StatusOK)+func (s *ServerInterfaceImpl) GetFederatedActionsOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(middleware.HandlePagination(s.h.admin.GetFederatedActions))(w, r)}diff --git a/webserver/handlers/admin/admin.go b/webserver/handlers/admin/admin.gonew file mode 100644index 0000000000..464de5cd7f--- /dev/null+++ b/webserver/handlers/admin/admin.go@@ -0,0 +1,86 @@+package admin++import (+ "github.com/owncast/owncast/config"+ "github.com/owncast/owncast/metrics"+ "github.com/owncast/owncast/persistence/authrepository"+ "github.com/owncast/owncast/persistence/chatmessagerepository"+ "github.com/owncast/owncast/persistence/configrepository"+ "github.com/owncast/owncast/persistence/userrepository"+ "github.com/owncast/owncast/persistence/webhookrepository"+ "github.com/owncast/owncast/services/activitypub"+ "github.com/owncast/owncast/services/activitypub/apmodels"+ apcrypto "github.com/owncast/owncast/services/activitypub/crypto"+ "github.com/owncast/owncast/services/activitypub/persistence/followersrepository"+ "github.com/owncast/owncast/services/chat"+ "github.com/owncast/owncast/services/rtmp"+ "github.com/owncast/owncast/services/stream"+ "github.com/owncast/owncast/services/webhooks"+)++// Admin carries the dependencies of admin HTTP handlers that need+// injected services. Construct one in main() and pass it to the OpenAPI+// shim layer (webserver/handlers.NewHandlers) so the matching+// ServerInterface methods can delegate to it.+//+// Admin handlers without injected dependencies remain free functions in+// this package; they migrate to methods on *Admin as the services they+// need to consume move to services/<domain>/.+type Admin struct {+ stream *stream.Service+ rtmp *rtmp.Service+ activitypub *activitypub.Service+ webhooks *webhooks.Service+ chat *chat.Service+ metrics *metrics.Service+ configRepository configrepository.ConfigRepository+ authRepository authrepository.AuthRepository+ followersRepository followersrepository.FollowersRepository+ webhookRepository webhookrepository.WebhookRepository+ chatMessageRepository chatmessagerepository.ChatMessageRepository+ userRepository userrepository.UserRepository+ apBuilder *apmodels.Builder+ apSigner *apcrypto.Signer+ cfg *config.Config+}++// Deps lists every service a *Admin consumes. New deps appear here as+// more admin handlers migrate.+type Deps struct {+ Stream *stream.Service+ Rtmp *rtmp.Service+ Activitypub *activitypub.Service+ Webhooks *webhooks.Service+ Chat *chat.Service+ Metrics *metrics.Service+ ConfigRepository configrepository.ConfigRepository+ AuthRepository authrepository.AuthRepository+ FollowersRepository followersrepository.FollowersRepository+ WebhookRepository webhookrepository.WebhookRepository+ ChatMessageRepository chatmessagerepository.ChatMessageRepository+ UserRepository userrepository.UserRepository+ APBuilder *apmodels.Builder+ APSigner *apcrypto.Signer+ Config *config.Config+}++// 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,+ }+}diff --git a/webserver/handlers/admin/appearance.go b/webserver/handlers/admin/appearance.goindex d74a23fd4b..6a8765a3b1 100644--- a/webserver/handlers/admin/appearance.go+++ b/webserver/handlers/admin/appearance.go@@ -4,13 +4,12 @@ import ("encoding/json""net/http"- "github.com/owncast/owncast/persistence/configrepository""github.com/owncast/owncast/webserver/handlers/generated"webutils "github.com/owncast/owncast/webserver/utils")// SetCustomColorVariableValues sets the custom color variables.-func SetCustomColorVariableValues(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetCustomColorVariableValues(w http.ResponseWriter, r *http.Request) {if !requirePOST(w, r) {return}@@ -28,8 +27,7 @@ func SetCustomColorVariableValues(w http.ResponseWriter, r *http.Request) {return}- configRepository := configrepository.Get()- if err := configRepository.SetCustomColorVariableValues(*values.Value); err != nil {+ if err := a.configRepository.SetCustomColorVariableValues(*values.Value); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return}diff --git a/webserver/handlers/admin/chat.go b/webserver/handlers/admin/chat.goindex edc1a1a009..bd7f177b42 100644--- a/webserver/handlers/admin/chat.go+++ b/webserver/handlers/admin/chat.go@@ -8,27 +8,23 @@ import ("net/http""strconv"- "github.com/owncast/owncast/core/chat"- "github.com/owncast/owncast/core/chat/events"+ "github.com/pkg/errors"+ log "github.com/sirupsen/logrus"+"github.com/owncast/owncast/models"- "github.com/owncast/owncast/persistence/authrepository"- "github.com/owncast/owncast/persistence/chatmessagerepository"- "github.com/owncast/owncast/persistence/configrepository"- "github.com/owncast/owncast/persistence/userrepository"+ "github.com/owncast/owncast/services/chat/events""github.com/owncast/owncast/utils""github.com/owncast/owncast/webserver/handlers/generated"webutils "github.com/owncast/owncast/webserver/utils"- "github.com/pkg/errors"- log "github.com/sirupsen/logrus")// ExternalUpdateMessageVisibility updates an array of message IDs to have the same visiblity.-func ExternalUpdateMessageVisibility(integration models.ExternalAPIUser, w http.ResponseWriter, r *http.Request) {- UpdateMessageVisibility(w, r)+func (a *Admin) ExternalUpdateMessageVisibility(integration models.ExternalAPIUser, w http.ResponseWriter, r *http.Request) {+ a.UpdateMessageVisibility(w, r)}// UpdateMessageVisibility updates an array of message IDs to have the same visiblity.-func UpdateMessageVisibility(w http.ResponseWriter, r *http.Request) {+func (a *Admin) UpdateMessageVisibility(w http.ResponseWriter, r *http.Request) {if r.Method != http.MethodPost {// nolint:goconstwebutils.WriteSimpleResponse(w, false, r.Method+" not supported")@@ -49,7 +45,7 @@ func UpdateMessageVisibility(w http.ResponseWriter, r *http.Request) {return}- if err := chat.SetMessagesVisibility(*request.IdArray, *request.Visible); err != nil {+ if err := a.chat.SetMessagesVisibility(*request.IdArray, *request.Visible); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return}@@ -58,7 +54,7 @@ func UpdateMessageVisibility(w http.ResponseWriter, r *http.Request) {}// BanIPAddress will manually ban an IP address.-func BanIPAddress(w http.ResponseWriter, r *http.Request) {+func (a *Admin) BanIPAddress(w http.ResponseWriter, r *http.Request) {if !requirePOST(w, r) {return}@@ -69,9 +65,7 @@ func BanIPAddress(w http.ResponseWriter, r *http.Request) {return}- authRepository := authrepository.Get()-- if err := authRepository.BanIPAddress(configValue.Value.(string), "manually added"); err != nil {+ if err := a.authRepository.BanIPAddress(configValue.Value.(string), "manually added"); err != nil {webutils.WriteSimpleResponse(w, false, "error saving IP address ban")return}@@ -80,7 +74,7 @@ func BanIPAddress(w http.ResponseWriter, r *http.Request) {}// UnBanIPAddress will remove an IP address ban.-func UnBanIPAddress(w http.ResponseWriter, r *http.Request) {+func (a *Admin) UnBanIPAddress(w http.ResponseWriter, r *http.Request) {if !requirePOST(w, r) {return}@@ -91,9 +85,7 @@ func UnBanIPAddress(w http.ResponseWriter, r *http.Request) {return}- authRepository := authrepository.Get()-- if err := authRepository.RemoveIPAddressBan(configValue.Value.(string)); err != nil {+ if err := a.authRepository.RemoveIPAddressBan(configValue.Value.(string)); err != nil {webutils.WriteSimpleResponse(w, false, "error removing IP address ban")return}@@ -102,10 +94,8 @@ func UnBanIPAddress(w http.ResponseWriter, r *http.Request) {}// GetIPAddressBans will return all the banned IP addresses.-func GetIPAddressBans(w http.ResponseWriter, r *http.Request) {- authRepository := authrepository.Get()-- bans, err := authRepository.GetIPAddressBans()+func (a *Admin) GetIPAddressBans(w http.ResponseWriter, r *http.Request) {+ bans, err := a.authRepository.GetIPAddressBans()if err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return@@ -115,7 +105,7 @@ func GetIPAddressBans(w http.ResponseWriter, r *http.Request) {}// UpdateUserEnabled enable or disable a single user by ID.-func UpdateUserEnabled(w http.ResponseWriter, r *http.Request) {+func (a *Admin) UpdateUserEnabled(w http.ResponseWriter, r *http.Request) {if r.Method != http.MethodPost {webutils.WriteSimpleResponse(w, false, r.Method+" not supported")return@@ -135,13 +125,13 @@ func UpdateUserEnabled(w http.ResponseWriter, r *http.Request) {return}- if err := updateUserStatus(request); err != nil {+ if err := a.updateUserStatus(request); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return}if !*request.Enabled {- if err := handleUserDisabling(*request.UserId); err != nil {+ if err := a.handleUserDisabling(*request.UserId); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return}@@ -150,22 +140,19 @@ func UpdateUserEnabled(w http.ResponseWriter, r *http.Request) {webutils.WriteSimpleResponse(w, true, fmt.Sprintf("%s enabled: %t", *request.UserId, *request.Enabled))}-func updateUserStatus(request generated.UpdateUserEnabledJSONBody) error {- userRepository := userrepository.Get()- chatMessageRepository := chatmessagerepository.Get()-- if err := userRepository.SetEnabled(*request.UserId, *request.Enabled); err != nil {+func (a *Admin) updateUserStatus(request generated.UpdateUserEnabledJSONBody) error {+ if err := a.userRepository.SetEnabled(*request.UserId, *request.Enabled); err != nil {log.Errorln("error changing user enabled status", err)return err}- messageIDs, err := chatMessageRepository.GetMessageIdsForUserID(*request.UserId)+ messageIDs, err := a.chatMessageRepository.GetMessageIdsForUserID(*request.UserId)if err != nil {return errors.Wrap(err, "error fetching user messages")}if !*request.Enabled && len(messageIDs) > 0 {- if err := chat.SetMessagesVisibility(messageIDs, *request.Enabled); err != nil {+ if err := a.chat.SetMessagesVisibility(messageIDs, *request.Enabled); err != nil {log.Errorln("error changing user messages visibility", err)return err}@@ -173,8 +160,8 @@ func updateUserStatus(request generated.UpdateUserEnabledJSONBody) error {return nil}-func handleUserDisabling(userID string) error {- clients, err := chat.GetClientsForUser(userID)+func (a *Admin) handleUserDisabling(userID string) error {+ clients, err := a.chat.GetClientsForUser(userID)if len(clients) == 0 {return nil}@@ -184,20 +171,18 @@ func handleUserDisabling(userID string) error {return err}- chat.DisconnectClients(clients)- userRepository := userrepository.Get()- disconnectedUser := userRepository.GetUserByID(userID)- _ = chat.SendSystemAction(fmt.Sprintf("**%s** has been removed from chat.", disconnectedUser.DisplayName), true)+ a.chat.DisconnectClients(clients)+ disconnectedUser := a.userRepository.GetUserByID(userID)+ _ = a.chat.SendSystemAction(fmt.Sprintf("**%s** has been removed from chat.", disconnectedUser.DisplayName), true)localIP4Address := "127.0.0.1"localIP6Address := "::1"- authRepository := authrepository.Get()for _, client := range clients {ipAddress := client.IPAddressif ipAddress != localIP4Address && ipAddress != localIP6Address {reason := fmt.Sprintf("Banning of %s", disconnectedUser.DisplayName)- if err := authRepository.BanIPAddress(ipAddress, reason); err != nil {+ if err := a.authRepository.BanIPAddress(ipAddress, reason); err != nil {log.Errorln("error banning IP address: ", err)}}@@ -206,17 +191,15 @@ func handleUserDisabling(userID string) error {}// GetDisabledUsers will return all the disabled users.-func GetDisabledUsers(w http.ResponseWriter, r *http.Request) {+func (a *Admin) GetDisabledUsers(w http.ResponseWriter, r *http.Request) {w.Header().Set("Content-Type", "application/json")- userRepository := userrepository.Get()-- users := userRepository.GetDisabledUsers()+ users := a.userRepository.GetDisabledUsers()webutils.WriteResponse(w, users)}// UpdateUserModerator will set the moderator status for a user ID.-func UpdateUserModerator(w http.ResponseWriter, r *http.Request) {+func (a *Admin) UpdateUserModerator(w http.ResponseWriter, r *http.Request) {if r.Method != http.MethodPost {webutils.WriteSimpleResponse(w, false, r.Method+" not supported")return@@ -230,16 +213,14 @@ func UpdateUserModerator(w http.ResponseWriter, r *http.Request) {return}- userRepository := userrepository.Get()-// Update the user object with new moderation access.- if err := userRepository.SetModerator(*req.UserId, *req.IsModerator); err != nil {+ if err := a.userRepository.SetModerator(*req.UserId, *req.IsModerator); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return}// Update the clients for this user to know about the moderator access change.- if err := chat.SendConnectedClientInfoToUser(*req.UserId); err != nil {+ if err := a.chat.SendConnectedClientInfoToUser(*req.UserId); err != nil {log.Debugln(err)}@@ -247,26 +228,23 @@ func UpdateUserModerator(w http.ResponseWriter, r *http.Request) {}// GetModerators will return a list of moderator users.-func GetModerators(w http.ResponseWriter, r *http.Request) {+func (a *Admin) GetModerators(w http.ResponseWriter, r *http.Request) {w.Header().Set("Content-Type", "application/json")- userRepository := userrepository.Get()-- users := userRepository.GetModeratorUsers()+ users := a.userRepository.GetModeratorUsers()webutils.WriteResponse(w, users)}// GetChatMessages returns all of the chat messages, unfiltered.-func GetChatMessages(w http.ResponseWriter, r *http.Request) {+func (a *Admin) GetChatMessages(w http.ResponseWriter, r *http.Request) {w.Header().Set("Content-Type", "application/json")- chatMessageRepository := chatmessagerepository.Get()- messages := chatMessageRepository.GetChatModerationHistory()+ messages := a.chatMessageRepository.GetChatModerationHistory()webutils.WriteResponse(w, messages)}// SendSystemMessage will send an official "SYSTEM" message to chat on behalf of your server.-func SendSystemMessage(integration models.ExternalAPIUser, w http.ResponseWriter, r *http.Request) {+func (a *Admin) SendSystemMessage(integration models.ExternalAPIUser, w http.ResponseWriter, r *http.Request) {w.Header().Set("Content-Type", "application/json")var message events.SystemMessageEvent@@ -275,7 +253,7 @@ func SendSystemMessage(integration models.ExternalAPIUser, w http.ResponseWriterreturn}- if err := chat.SendSystemMessage(message.Body, false); err != nil {+ if err := a.chat.SendSystemMessage(message.Body, false); err != nil {webutils.BadRequestHandler(w, err)}@@ -283,7 +261,7 @@ func SendSystemMessage(integration models.ExternalAPIUser, w http.ResponseWriter}// SendSystemMessageToConnectedClient will handle incoming requests to send a single message to a single connected client by ID.-func SendSystemMessageToConnectedClient(integration models.ExternalAPIUser, w http.ResponseWriter, r *http.Request) {+func (a *Admin) SendSystemMessageToConnectedClient(integration models.ExternalAPIUser, w http.ResponseWriter, r *http.Request) {w.Header().Set("Content-Type", "application/json")clientIDText, err := utils.GetURLParam(r, "clientId")if err != nil {@@ -309,18 +287,18 @@ func SendSystemMessageToConnectedClient(integration models.ExternalAPIUser, w htreturn}- chat.SendSystemMessageToClient(uint(clientIDNumeric), *message.Body)+ a.chat.SendSystemMessageToClient(uint(clientIDNumeric), *message.Body)webutils.WriteSimpleResponse(w, true, "sent")}// SendUserMessage will send a message to chat on behalf of a user. *Depreciated*.-func SendUserMessage(integration models.ExternalAPIUser, w http.ResponseWriter, r *http.Request) {+func (a *Admin) SendUserMessage(integration models.ExternalAPIUser, w http.ResponseWriter, r *http.Request) {w.Header().Set("Content-Type", "application/json")webutils.BadRequestHandler(w, errors.New("no longer supported. see /api/integrations/chat/send"))}// SendIntegrationChatMessage will send a chat message on behalf of an external chat integration.-func SendIntegrationChatMessage(integration models.ExternalAPIUser, w http.ResponseWriter, r *http.Request) {+func (a *Admin) SendIntegrationChatMessage(integration models.ExternalAPIUser, w http.ResponseWriter, r *http.Request) {w.Header().Set("Content-Type", "application/json")name := integration.DisplayName@@ -352,19 +330,18 @@ func SendIntegrationChatMessage(integration models.ExternalAPIUser, w http.RespoIsBot: true,}- if err := chat.Broadcast(&event); err != nil {+ if err := a.chat.BroadcastEvent(&event); err != nil {webutils.BadRequestHandler(w, err)return}- chatMessageRepository := chatmessagerepository.Get()- chatMessageRepository.SaveUserMessage(event)+ a.chatMessageRepository.SaveUserMessage(event)webutils.WriteSimpleResponse(w, true, "sent")}// SendChatAction will send a generic chat action.-func SendChatAction(integration models.ExternalAPIUser, w http.ResponseWriter, r *http.Request) {+func (a *Admin) SendChatAction(integration models.ExternalAPIUser, w http.ResponseWriter, r *http.Request) {w.Header().Set("Content-Type", "application/json")var message events.SystemActionEvent@@ -376,7 +353,7 @@ func SendChatAction(integration models.ExternalAPIUser, w http.ResponseWriter, rmessage.SetDefaults()message.RenderBody()- if err := chat.SendSystemAction(message.Body, false); err != nil {+ if err := a.chat.SendSystemAction(message.Body, false); err != nil {webutils.BadRequestHandler(w, err)return}@@ -386,7 +363,7 @@ func SendChatAction(integration models.ExternalAPIUser, w http.ResponseWriter, r// SetEnableEstablishedChatUserMode sets the requirement for a chat user// to be "established" for some time before taking part in chat.-func SetEnableEstablishedChatUserMode(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetEnableEstablishedChatUserMode(w http.ResponseWriter, r *http.Request) {if !requirePOST(w, r) {return}@@ -397,8 +374,7 @@ func SetEnableEstablishedChatUserMode(w http.ResponseWriter, r *http.Request) {return}- configRepository := configrepository.Get()- if err := configRepository.SetChatEstablishedUsersOnlyMode(configValue.Value.(bool)); err != nil {+ if err := a.configRepository.SetChatEstablishedUsersOnlyMode(configValue.Value.(bool)); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return}diff --git a/webserver/handlers/admin/config.go b/webserver/handlers/admin/config.goindex 6c2fca5688..e431ab9e49 100644--- a/webserver/handlers/admin/config.go+++ b/webserver/handlers/admin/config.go@@ -11,17 +11,13 @@ import ("reflect""strings"- "github.com/owncast/owncast/activitypub/outbox"- "github.com/owncast/owncast/core"- "github.com/owncast/owncast/core/chat"- "github.com/owncast/owncast/core/webhooks"+ log "github.com/sirupsen/logrus"+ "github.com/teris-io/shortid"+"github.com/owncast/owncast/models"- "github.com/owncast/owncast/persistence/configrepository""github.com/owncast/owncast/utils""github.com/owncast/owncast/webserver/handlers/generated"webutils "github.com/owncast/owncast/webserver/utils"- log "github.com/sirupsen/logrus"- "github.com/teris-io/shortid")// ConfigValue is a container object that holds a value, is encoded, and saved to the database.@@ -30,7 +26,7 @@ type ConfigValue struct {}// SetTags will handle the web config request to set tags.-func SetTags(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetTags(w http.ResponseWriter, r *http.Request) {if !requirePOST(w, r) {return}@@ -45,14 +41,14 @@ func SetTags(w http.ResponseWriter, r *http.Request) {tagStrings = append(tagStrings, strings.TrimLeft(tag.Value.(string), "#"))}- configRepository := configrepository.Get()+ configRepository := a.configRepositoryif err := configRepository.SetServerMetadataTags(tagStrings); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return}// Update Fediverse followers about this change.- if err := outbox.UpdateFollowersWithAccountUpdates(); err != nil {+ if err := a.activitypub.UpdateFollowersWithAccountUpdates(); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return}@@ -61,7 +57,7 @@ func SetTags(w http.ResponseWriter, r *http.Request) {}// SetStreamTitle will handle the web config request to set the current stream title.-func SetStreamTitle(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetStreamTitle(w http.ResponseWriter, r *http.Request) {if !requirePOST(w, r) {return}@@ -72,38 +68,38 @@ func SetStreamTitle(w http.ResponseWriter, r *http.Request) {}value := configValue.Value.(string)- configRepository := configrepository.Get()+ configRepository := a.configRepositoryif err := configRepository.SetStreamTitle(value); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return}if value != "" {- sendSystemChatAction(fmt.Sprintf("Stream title changed to **%s**", value), true)- go webhooks.SendStreamStatusEvent(models.StreamTitleUpdated)+ a.sendSystemChatAction(fmt.Sprintf("Stream title changed to **%s**", value), true)+ go a.webhooks.SendStreamStatusEvent(models.StreamTitleUpdated)}webutils.WriteSimpleResponse(w, true, "changed")}// ExternalSetStreamTitle will change the stream title on behalf of an external integration API request.-func ExternalSetStreamTitle(integration models.ExternalAPIUser, w http.ResponseWriter, r *http.Request) {- SetStreamTitle(w, r)+func (a *Admin) ExternalSetStreamTitle(integration models.ExternalAPIUser, w http.ResponseWriter, r *http.Request) {+ a.SetStreamTitle(w, r)}// ExternalGetStatus will return the status of the server.-func ExternalGetStatus(integration models.ExternalAPIUser, w http.ResponseWriter, r *http.Request) {- status := core.GetStatus()+func (a *Admin) ExternalGetStatus(integration models.ExternalAPIUser, w http.ResponseWriter, r *http.Request) {+ status := a.stream.GetStatus()webutils.WriteResponse(w, status)}-func sendSystemChatAction(messageText string, ephemeral bool) {- if err := chat.SendSystemAction(messageText, ephemeral); err != nil {+func (a *Admin) sendSystemChatAction(messageText string, ephemeral bool) {+ if err := a.chat.SendSystemAction(messageText, ephemeral); err != nil {log.Errorln(err)}}// SetServerName will handle the web config request to set the server's name.-func SetServerName(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetServerName(w http.ResponseWriter, r *http.Request) {if !requirePOST(w, r) {return}@@ -113,14 +109,14 @@ func SetServerName(w http.ResponseWriter, r *http.Request) {return}- configRepository := configrepository.Get()+ configRepository := a.configRepositoryif err := configRepository.SetServerName(configValue.Value.(string)); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return}// Update Fediverse followers about this change.- if err := outbox.UpdateFollowersWithAccountUpdates(); err != nil {+ if err := a.activitypub.UpdateFollowersWithAccountUpdates(); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return}@@ -129,7 +125,7 @@ func SetServerName(w http.ResponseWriter, r *http.Request) {}// SetServerSummary will handle the web config request to set the about/summary text.-func SetServerSummary(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetServerSummary(w http.ResponseWriter, r *http.Request) {if !requirePOST(w, r) {return}@@ -139,14 +135,14 @@ func SetServerSummary(w http.ResponseWriter, r *http.Request) {return}- configRepository := configrepository.Get()+ configRepository := a.configRepositoryif err := configRepository.SetServerSummary(configValue.Value.(string)); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return}// Update Fediverse followers about this change.- if err := outbox.UpdateFollowersWithAccountUpdates(); err != nil {+ if err := a.activitypub.UpdateFollowersWithAccountUpdates(); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return}@@ -155,7 +151,7 @@ func SetServerSummary(w http.ResponseWriter, r *http.Request) {}// SetCustomOfflineMessage will set a message to display when the server is offline.-func SetCustomOfflineMessage(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetCustomOfflineMessage(w http.ResponseWriter, r *http.Request) {if !requirePOST(w, r) {return}@@ -165,7 +161,7 @@ func SetCustomOfflineMessage(w http.ResponseWriter, r *http.Request) {return}- configRepository := configrepository.Get()+ configRepository := a.configRepositoryif err := configRepository.SetCustomOfflineMessage(strings.TrimSpace(configValue.Value.(string))); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return@@ -175,7 +171,7 @@ func SetCustomOfflineMessage(w http.ResponseWriter, r *http.Request) {}// SetServerWelcomeMessage will handle the web config request to set the welcome message text.-func SetServerWelcomeMessage(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetServerWelcomeMessage(w http.ResponseWriter, r *http.Request) {if !requirePOST(w, r) {return}@@ -185,7 +181,7 @@ func SetServerWelcomeMessage(w http.ResponseWriter, r *http.Request) {return}- configRepository := configrepository.Get()+ configRepository := a.configRepositoryif err := configRepository.SetServerWelcomeMessage(strings.TrimSpace(configValue.Value.(string))); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return@@ -195,7 +191,7 @@ func SetServerWelcomeMessage(w http.ResponseWriter, r *http.Request) {}// SetExtraPageContent will handle the web config request to set the page markdown content.-func SetExtraPageContent(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetExtraPageContent(w http.ResponseWriter, r *http.Request) {if !requirePOST(w, r) {return}@@ -205,7 +201,7 @@ func SetExtraPageContent(w http.ResponseWriter, r *http.Request) {return}- configRepository := configrepository.Get()+ configRepository := a.configRepositoryif err := configRepository.SetExtraPageBodyContent(configValue.Value.(string)); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return@@ -215,7 +211,7 @@ func SetExtraPageContent(w http.ResponseWriter, r *http.Request) {}// SetAdminPassword will handle the web config request to set the server admin password.-func SetAdminPassword(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetAdminPassword(w http.ResponseWriter, r *http.Request) {if !requirePOST(w, r) {return}@@ -225,7 +221,7 @@ func SetAdminPassword(w http.ResponseWriter, r *http.Request) {return}- configRepository := configrepository.Get()+ configRepository := a.configRepositoryif err := configRepository.SetAdminPassword(configValue.Value.(string)); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return@@ -235,7 +231,7 @@ func SetAdminPassword(w http.ResponseWriter, r *http.Request) {}// SetLogo will handle a new logo image file being uploaded.-func SetLogo(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetLogo(w http.ResponseWriter, r *http.Request) {if !requirePOST(w, r) {return}@@ -262,7 +258,7 @@ func SetLogo(w http.ResponseWriter, r *http.Request) {return}- configRepository := configrepository.Get()+ configRepository := a.configRepositoryif err := configRepository.SetLogoPath("logo" + extension); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())@@ -274,7 +270,7 @@ func SetLogo(w http.ResponseWriter, r *http.Request) {}// Update Fediverse followers about this change.- if err := outbox.UpdateFollowersWithAccountUpdates(); err != nil {+ if err := a.activitypub.UpdateFollowersWithAccountUpdates(); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return}@@ -283,7 +279,7 @@ func SetLogo(w http.ResponseWriter, r *http.Request) {}// SetFavicon will handle a new favicon image being set via base64 data.-func SetFavicon(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetFavicon(w http.ResponseWriter, r *http.Request) {if !requirePOST(w, r) {return}@@ -328,7 +324,7 @@ func SetFavicon(w http.ResponseWriter, r *http.Request) {return}- configRepository := configrepository.Get()+ configRepository := a.configRepositoryif err := configRepository.SetFaviconPath("favicon" + extension); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())@@ -339,8 +335,8 @@ func SetFavicon(w http.ResponseWriter, r *http.Request) {}// ResetFavicon will reset the favicon to the default by removing the custom one.-func ResetFavicon(w http.ResponseWriter, r *http.Request) {- configRepository := configrepository.Get()+func (a *Admin) ResetFavicon(w http.ResponseWriter, r *http.Request) {+ configRepository := a.configRepository// Get the current favicon path before clearing itcurrentFavicon := configRepository.GetFaviconPath()@@ -371,7 +367,7 @@ func ResetFavicon(w http.ResponseWriter, r *http.Request) {}// SetNSFW will handle the web config request to set the NSFW flag.-func SetNSFW(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetNSFW(w http.ResponseWriter, r *http.Request) {if !requirePOST(w, r) {return}@@ -381,7 +377,7 @@ func SetNSFW(w http.ResponseWriter, r *http.Request) {return}- configRepository := configrepository.Get()+ configRepository := a.configRepositoryif err := configRepository.SetNSFW(configValue.Value.(bool)); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return@@ -391,7 +387,7 @@ func SetNSFW(w http.ResponseWriter, r *http.Request) {}// SetFfmpegPath will handle the web config request to validate and set an updated copy of ffmpg.-func SetFfmpegPath(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetFfmpegPath(w http.ResponseWriter, r *http.Request) {if !requirePOST(w, r) {return}@@ -407,7 +403,7 @@ func SetFfmpegPath(w http.ResponseWriter, r *http.Request) {return}- configRepository := configrepository.Get()+ configRepository := a.configRepositoryif err := configRepository.SetFfmpegPath(configValue.Value.(string)); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return@@ -417,7 +413,7 @@ func SetFfmpegPath(w http.ResponseWriter, r *http.Request) {}// SetWebServerPort will handle the web config request to set the server's HTTP port.-func SetWebServerPort(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetWebServerPort(w http.ResponseWriter, r *http.Request) {if !requirePOST(w, r) {return}@@ -427,7 +423,7 @@ func SetWebServerPort(w http.ResponseWriter, r *http.Request) {return}- configRepository := configrepository.Get()+ configRepository := a.configRepositoryif port, ok := configValue.Value.(float64); ok {if (port < 1) || (port > 65535) {webutils.WriteSimpleResponse(w, false, "Port number must be between 1 and 65535")@@ -446,7 +442,7 @@ func SetWebServerPort(w http.ResponseWriter, r *http.Request) {}// SetWebServerIP will handle the web config request to set the server's HTTP listen address.-func SetWebServerIP(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetWebServerIP(w http.ResponseWriter, r *http.Request) {if !requirePOST(w, r) {return}@@ -456,7 +452,7 @@ func SetWebServerIP(w http.ResponseWriter, r *http.Request) {return}- configRepository := configrepository.Get()+ configRepository := a.configRepositoryif input, ok := configValue.Value.(string); ok {if ip := net.ParseIP(input); ip != nil {if err := configRepository.SetHTTPListenAddress(ip.String()); err != nil {@@ -475,7 +471,7 @@ func SetWebServerIP(w http.ResponseWriter, r *http.Request) {}// SetRTMPServerPort will handle the web config request to set the inbound RTMP port.-func SetRTMPServerPort(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetRTMPServerPort(w http.ResponseWriter, r *http.Request) {if !requirePOST(w, r) {return}@@ -485,7 +481,7 @@ func SetRTMPServerPort(w http.ResponseWriter, r *http.Request) {return}- configRepository := configrepository.Get()+ configRepository := a.configRepositoryif err := configRepository.SetRTMPPortNumber(configValue.Value.(float64)); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return@@ -495,7 +491,7 @@ func SetRTMPServerPort(w http.ResponseWriter, r *http.Request) {}// SetServerURL will handle the web config request to set the full server URL.-func SetServerURL(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetServerURL(w http.ResponseWriter, r *http.Request) {if !requirePOST(w, r) {return}@@ -525,7 +521,7 @@ func SetServerURL(w http.ResponseWriter, r *http.Request) {return}- configRepository := configrepository.Get()+ configRepository := a.configRepository// Trim any trailing slashserverURL := strings.TrimRight(rawValue, "/")@@ -539,7 +535,7 @@ func SetServerURL(w http.ResponseWriter, r *http.Request) {}// SetSocketHostOverride will set the host override for the websocket.-func SetSocketHostOverride(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetSocketHostOverride(w http.ResponseWriter, r *http.Request) {if !requirePOST(w, r) {return}@@ -549,7 +545,7 @@ func SetSocketHostOverride(w http.ResponseWriter, r *http.Request) {return}- configRepository := configrepository.Get()+ configRepository := a.configRepositoryif err := configRepository.SetWebsocketOverrideHost(configValue.Value.(string)); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())@@ -560,7 +556,7 @@ func SetSocketHostOverride(w http.ResponseWriter, r *http.Request) {}// SetDirectoryEnabled will handle the web config request to enable or disable directory registration.-func SetDirectoryEnabled(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetDirectoryEnabled(w http.ResponseWriter, r *http.Request) {if !requirePOST(w, r) {return}@@ -570,7 +566,7 @@ func SetDirectoryEnabled(w http.ResponseWriter, r *http.Request) {return}- configRepository := configrepository.Get()+ configRepository := a.configRepositoryif err := configRepository.SetDirectoryEnabled(configValue.Value.(bool)); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())@@ -580,7 +576,7 @@ func SetDirectoryEnabled(w http.ResponseWriter, r *http.Request) {}// SetStreamLatencyLevel will handle the web config request to set the stream latency level.-func SetStreamLatencyLevel(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetStreamLatencyLevel(w http.ResponseWriter, r *http.Request) {if !requirePOST(w, r) {return}@@ -590,7 +586,7 @@ func SetStreamLatencyLevel(w http.ResponseWriter, r *http.Request) {return}- configRepository := configrepository.Get()+ configRepository := a.configRepositoryif err := configRepository.SetStreamLatencyLevel(configValue.Value.(float64)); err != nil {webutils.WriteSimpleResponse(w, false, "error setting stream latency "+err.Error())@@ -601,7 +597,7 @@ func SetStreamLatencyLevel(w http.ResponseWriter, r *http.Request) {}// SetS3Configuration will handle the web config request to set the storage configuration.-func SetS3Configuration(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetS3Configuration(w http.ResponseWriter, r *http.Request) {if !requirePOST(w, r) {return}@@ -639,7 +635,7 @@ func SetS3Configuration(w http.ResponseWriter, r *http.Request) {}}- configRepository := configrepository.Get()+ configRepository := a.configRepositoryif err := configRepository.SetS3Config(newS3Config.Value); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return@@ -648,7 +644,7 @@ func SetS3Configuration(w http.ResponseWriter, r *http.Request) {}// SetStreamOutputVariants will handle the web config request to set the video output stream variants.-func SetStreamOutputVariants(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetStreamOutputVariants(w http.ResponseWriter, r *http.Request) {if !requirePOST(w, r) {return}@@ -664,7 +660,7 @@ func SetStreamOutputVariants(w http.ResponseWriter, r *http.Request) {return}- configRepository := configrepository.Get()+ configRepository := a.configRepositoryif err := configRepository.SetStreamOutputVariants(videoVariants.Value); err != nil {webutils.WriteSimpleResponse(w, false, "unable to update video config with provided values "+err.Error())return@@ -674,7 +670,7 @@ func SetStreamOutputVariants(w http.ResponseWriter, r *http.Request) {}// SetSocialHandles will handle the web config request to set the external social profile links.-func SetSocialHandles(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetSocialHandles(w http.ResponseWriter, r *http.Request) {if !requirePOST(w, r) {return}@@ -690,14 +686,14 @@ func SetSocialHandles(w http.ResponseWriter, r *http.Request) {return}- configRepository := configrepository.Get()+ configRepository := a.configRepositoryif err := configRepository.SetSocialHandles(socialHandles.Value); err != nil {webutils.WriteSimpleResponse(w, false, "unable to update social handles with provided values")return}// Update Fediverse followers about this change.- if err := outbox.UpdateFollowersWithAccountUpdates(); err != nil {+ if err := a.activitypub.UpdateFollowersWithAccountUpdates(); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return}@@ -706,7 +702,7 @@ func SetSocialHandles(w http.ResponseWriter, r *http.Request) {}// SetChatDisabled will disable chat functionality.-func SetChatDisabled(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetChatDisabled(w http.ResponseWriter, r *http.Request) {if !requirePOST(w, r) {return}@@ -717,7 +713,7 @@ func SetChatDisabled(w http.ResponseWriter, r *http.Request) {return}- configRepository := configrepository.Get()+ configRepository := a.configRepositoryif err := configRepository.SetChatDisabled(configValue.Value.(bool)); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return@@ -727,7 +723,7 @@ func SetChatDisabled(w http.ResponseWriter, r *http.Request) {}// SetVideoCodec will change the codec used for video encoding.-func SetVideoCodec(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetVideoCodec(w http.ResponseWriter, r *http.Request) {if !requirePOST(w, r) {return}@@ -738,7 +734,7 @@ func SetVideoCodec(w http.ResponseWriter, r *http.Request) {return}- configRepository := configrepository.Get()+ configRepository := a.configRepositoryif err := configRepository.SetVideoCodec(configValue.Value.(string)); err != nil {webutils.WriteSimpleResponse(w, false, "unable to update codec")return@@ -748,7 +744,7 @@ func SetVideoCodec(w http.ResponseWriter, r *http.Request) {}// SetExternalActions will set the 3rd party actions for the web interface.-func SetExternalActions(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetExternalActions(w http.ResponseWriter, r *http.Request) {type externalActionsRequest struct {Value []models.ExternalAction `json:"value"`}@@ -760,7 +756,7 @@ func SetExternalActions(w http.ResponseWriter, r *http.Request) {return}- configRepository := configrepository.Get()+ configRepository := a.configRepositoryif err := configRepository.SetExternalActions(actions.Value); err != nil {webutils.WriteSimpleResponse(w, false, "unable to update external actions with provided values")return@@ -770,14 +766,14 @@ func SetExternalActions(w http.ResponseWriter, r *http.Request) {}// SetCustomStyles will set the CSS string we insert into the page.-func SetCustomStyles(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetCustomStyles(w http.ResponseWriter, r *http.Request) {customStyles, success := getValueFromRequest(w, r)if !success {webutils.WriteSimpleResponse(w, false, "unable to update custom styles")return}- configRepository := configrepository.Get()+ configRepository := a.configRepositoryif err := configRepository.SetCustomStyles(customStyles.Value.(string)); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return@@ -787,14 +783,14 @@ func SetCustomStyles(w http.ResponseWriter, r *http.Request) {}// SetCustomJavascript will set the Javascript string we insert into the page.-func SetCustomJavascript(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetCustomJavascript(w http.ResponseWriter, r *http.Request) {customJavascript, success := getValueFromRequest(w, r)if !success {webutils.WriteSimpleResponse(w, false, "unable to update custom javascript")return}- configRepository := configrepository.Get()+ configRepository := a.configRepositoryif err := configRepository.SetCustomJavascript(customJavascript.Value.(string)); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return@@ -804,7 +800,7 @@ func SetCustomJavascript(w http.ResponseWriter, r *http.Request) {}// SetForbiddenUsernameList will set the list of usernames we do not allow to use.-func SetForbiddenUsernameList(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetForbiddenUsernameList(w http.ResponseWriter, r *http.Request) {decoder := json.NewDecoder(r.Body)var request generated.SetForbiddenUsernameListJSONBody@@ -813,7 +809,7 @@ func SetForbiddenUsernameList(w http.ResponseWriter, r *http.Request) {return}- configRepository := configrepository.Get()+ configRepository := a.configRepositoryif err := configRepository.SetForbiddenUsernameList(*request.Value); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return@@ -823,7 +819,7 @@ func SetForbiddenUsernameList(w http.ResponseWriter, r *http.Request) {}// SetSuggestedUsernameList will set the list of suggested usernames that newly registered users are assigned if it isn't inferred otherwise (i.e. through a proxy).-func SetSuggestedUsernameList(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetSuggestedUsernameList(w http.ResponseWriter, r *http.Request) {decoder := json.NewDecoder(r.Body)var request generated.SetSuggestedUsernameListJSONBody@@ -832,7 +828,7 @@ func SetSuggestedUsernameList(w http.ResponseWriter, r *http.Request) {return}- configRepository := configrepository.Get()+ configRepository := a.configRepositoryif err := configRepository.SetSuggestedUsernamesList(*request.Value); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return@@ -842,7 +838,7 @@ func SetSuggestedUsernameList(w http.ResponseWriter, r *http.Request) {}// SetChatJoinMessagesEnabled will enable or disable the chat join messages.-func SetChatJoinMessagesEnabled(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetChatJoinMessagesEnabled(w http.ResponseWriter, r *http.Request) {if !requirePOST(w, r) {return}@@ -853,7 +849,7 @@ func SetChatJoinMessagesEnabled(w http.ResponseWriter, r *http.Request) {return}- configRepository := configrepository.Get()+ configRepository := a.configRepositoryif err := configRepository.SetChatJoinMessagesEnabled(configValue.Value.(bool)); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return@@ -863,7 +859,7 @@ func SetChatJoinMessagesEnabled(w http.ResponseWriter, r *http.Request) {}// SetHideViewerCount will enable or disable hiding the viewer count.-func SetHideViewerCount(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetHideViewerCount(w http.ResponseWriter, r *http.Request) {if !requirePOST(w, r) {return}@@ -874,7 +870,7 @@ func SetHideViewerCount(w http.ResponseWriter, r *http.Request) {return}- configRepository := configrepository.Get()+ configRepository := a.configRepositoryif err := configRepository.SetHideViewerCount(configValue.Value.(bool)); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return@@ -884,7 +880,7 @@ func SetHideViewerCount(w http.ResponseWriter, r *http.Request) {}// SetDisableSearchIndexing will set search indexing support.-func SetDisableSearchIndexing(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetDisableSearchIndexing(w http.ResponseWriter, r *http.Request) {if !requirePOST(w, r) {return}@@ -895,7 +891,7 @@ func SetDisableSearchIndexing(w http.ResponseWriter, r *http.Request) {return}- configRepository := configrepository.Get()+ configRepository := a.configRepositoryif err := configRepository.SetDisableSearchIndexing(configValue.Value.(bool)); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return@@ -905,7 +901,7 @@ func SetDisableSearchIndexing(w http.ResponseWriter, r *http.Request) {}// SetVideoServingEndpoint will save the video serving endpoint.-func SetVideoServingEndpoint(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetVideoServingEndpoint(w http.ResponseWriter, r *http.Request) {endpoint, success := getValueFromRequest(w, r)if !success {webutils.WriteSimpleResponse(w, false, "unable to update custom video serving endpoint")@@ -918,7 +914,7 @@ func SetVideoServingEndpoint(w http.ResponseWriter, r *http.Request) {return}- configRepository := configrepository.Get()+ configRepository := a.configRepositoryif err := configRepository.SetVideoServingEndpoint(value); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return@@ -928,7 +924,7 @@ func SetVideoServingEndpoint(w http.ResponseWriter, r *http.Request) {}// SetChatSpamProtectionEnabled will enable or disable the chat spam protection.-func SetChatSpamProtectionEnabled(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetChatSpamProtectionEnabled(w http.ResponseWriter, r *http.Request) {if !requirePOST(w, r) {return}@@ -938,7 +934,7 @@ func SetChatSpamProtectionEnabled(w http.ResponseWriter, r *http.Request) {return}- configRepository := configrepository.Get()+ configRepository := a.configRepositoryif err := configRepository.SetChatSpamProtectionEnabled(configValue.Value.(bool)); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return@@ -947,7 +943,7 @@ func SetChatSpamProtectionEnabled(w http.ResponseWriter, r *http.Request) {}// SetChatSlurFilterEnabled will enable or disable the chat slur filter.-func SetChatSlurFilterEnabled(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetChatSlurFilterEnabled(w http.ResponseWriter, r *http.Request) {if !requirePOST(w, r) {return}@@ -957,7 +953,7 @@ func SetChatSlurFilterEnabled(w http.ResponseWriter, r *http.Request) {return}- configRepository := configrepository.Get()+ configRepository := a.configRepositoryif err := configRepository.SetChatSlurFilterEnabled(configValue.Value.(bool)); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return@@ -966,7 +962,7 @@ func SetChatSlurFilterEnabled(w http.ResponseWriter, r *http.Request) {}// SetChatRequireAuthentication will enable or disable requiring authentication for chat.-func SetChatRequireAuthentication(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetChatRequireAuthentication(w http.ResponseWriter, r *http.Request) {if !requirePOST(w, r) {return}@@ -976,7 +972,7 @@ func SetChatRequireAuthentication(w http.ResponseWriter, r *http.Request) {return}- configRepository := configrepository.Get()+ configRepository := a.configRepositoryif err := configRepository.SetChatRequireAuthentication(configValue.Value.(bool)); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return@@ -1025,7 +1021,7 @@ func getValuesFromRequest(w http.ResponseWriter, r *http.Request) ([]ConfigValue}// SetStreamKeys will set the valid stream keys.-func SetStreamKeys(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetStreamKeys(w http.ResponseWriter, r *http.Request) {if !requirePOST(w, r) {return}@@ -1049,7 +1045,7 @@ func SetStreamKeys(w http.ResponseWriter, r *http.Request) {}}- configRepository := configrepository.Get()+ configRepository := a.configRepositoryif err := configRepository.SetStreamKeys(*streamKeys.Value); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())returndiff --git a/webserver/handlers/admin/config_favicon_test.go b/webserver/handlers/admin/config_favicon_test.goindex 7a23953052..ea1eb5fd18 100644--- a/webserver/handlers/admin/config_favicon_test.go+++ b/webserver/handlers/admin/config_favicon_test.go@@ -11,9 +11,17 @@ import ("strings""testing"- "github.com/owncast/owncast/core/data""github.com/owncast/owncast/models""github.com/owncast/owncast/persistence/configrepository"+ "github.com/owncast/owncast/services/datastore"+)++// testAdmin is the *Admin used by tests in this package. Only the+// configRepository handle is needed by favicon tests; expand if other+// handler tests land that need additional deps.+var (+ testAdmin *Admin+ testDatastore *datastore.Datastore)func TestMain(m *testing.M) {@@ -23,15 +31,19 @@ func TestMain(m *testing.M) {}dbFile.Close()- if err := data.SetupPersistence(dbFile.Name()); err != nil {+ ds, err := datastore.SetupPersistence(dbFile.Name(), os.TempDir())+ if err != nil {panic(err)}+ testDatastore = ds// Ensure data directory exists for file operations.if err := os.MkdirAll("data", 0o755); err != nil {panic(err)}+ testAdmin = &Admin{configRepository: configrepository.New(testDatastore)}+code := m.Run()os.Remove(dbFile.Name())os.Exit(code)@@ -79,7 +91,7 @@ func cleanupFaviconFiles(t *testing.T) {for _, ext := range []string{".png", ".ico"} {os.Remove(filepath.Join("data", "favicon"+ext))}- configRepository := configrepository.Get()+ configRepository := configrepository.New(testDatastore)configRepository.SetFaviconPath("")}@@ -91,7 +103,7 @@ func TestSetFaviconPNG(t *testing.T) {req.Header.Set("Content-Type", "application/json")w := httptest.NewRecorder()- SetFavicon(w, req)+ testAdmin.SetFavicon(w, req)resp := parseResponse(t, w)if !resp.Success {@@ -107,7 +119,7 @@ func TestSetFaviconPNG(t *testing.T) {}// Verify config was updated.- configRepository := configrepository.Get()+ configRepository := configrepository.New(testDatastore)if path := configRepository.GetFaviconPath(); path != "favicon.png" {t.Errorf("expected favicon path 'favicon.png', got %q", path)}@@ -121,7 +133,7 @@ func TestSetFaviconICO(t *testing.T) {req.Header.Set("Content-Type", "application/json")w := httptest.NewRecorder()- SetFavicon(w, req)+ testAdmin.SetFavicon(w, req)resp := parseResponse(t, w)if !resp.Success {@@ -134,7 +146,7 @@ func TestSetFaviconICO(t *testing.T) {}// Verify config was updated.- configRepository := configrepository.Get()+ configRepository := configrepository.New(testDatastore)if path := configRepository.GetFaviconPath(); path != "favicon.ico" {t.Errorf("expected favicon path 'favicon.ico', got %q", path)}@@ -148,7 +160,7 @@ func TestSetFaviconRejectsJPEG(t *testing.T) {req.Header.Set("Content-Type", "application/json")w := httptest.NewRecorder()- SetFavicon(w, req)+ testAdmin.SetFavicon(w, req)if w.Code != http.StatusBadRequest {t.Errorf("expected status 400, got %d", w.Code)@@ -174,7 +186,7 @@ func TestSetFaviconRejectsOversized(t *testing.T) {req.Header.Set("Content-Type", "application/json")w := httptest.NewRecorder()- SetFavicon(w, req)+ testAdmin.SetFavicon(w, req)if w.Code != http.StatusBadRequest {t.Errorf("expected status 400, got %d", w.Code)@@ -196,7 +208,7 @@ func TestSetFaviconRejectsEmptyBody(t *testing.T) {req.Header.Set("Content-Type", "application/json")w := httptest.NewRecorder()- SetFavicon(w, req)+ testAdmin.SetFavicon(w, req)if w.Code != http.StatusBadRequest {t.Errorf("expected status 400, got %d", w.Code)@@ -207,7 +219,7 @@ func TestSetFaviconRejectsGETMethod(t *testing.T) {req := httptest.NewRequest(http.MethodGet, "/api/admin/config/favicon", nil)w := httptest.NewRecorder()- SetFavicon(w, req)+ testAdmin.SetFavicon(w, req)if w.Code != http.StatusBadRequest {t.Errorf("expected status 400 for GET request, got %d", w.Code)@@ -223,7 +235,7 @@ func TestResetFavicon(t *testing.T) {t.Fatal(err)}- configRepository := configrepository.Get()+ configRepository := configrepository.New(testDatastore)if err := configRepository.SetFaviconPath("favicon.png"); err != nil {t.Fatal(err)}@@ -231,7 +243,7 @@ func TestResetFavicon(t *testing.T) {req := httptest.NewRequest(http.MethodDelete, "/api/admin/config/favicon", nil)w := httptest.NewRecorder()- ResetFavicon(w, req)+ testAdmin.ResetFavicon(w, req)resp := parseResponse(t, w)if !resp.Success {@@ -254,13 +266,13 @@ func TestResetFavicon(t *testing.T) {func TestResetFaviconWhenNoneSet(t *testing.T) {// Reset when no custom favicon is set should still succeed.- configRepository := configrepository.Get()+ configRepository := configrepository.New(testDatastore)configRepository.SetFaviconPath("")req := httptest.NewRequest(http.MethodDelete, "/api/admin/config/favicon", nil)w := httptest.NewRecorder()- ResetFavicon(w, req)+ testAdmin.ResetFavicon(w, req)resp := parseResponse(t, w)if !resp.Success {diff --git a/webserver/handlers/admin/connectedClients.go b/webserver/handlers/admin/connectedClients.goindex a4e8811b74..a64409aaf1 100644--- a/webserver/handlers/admin/connectedClients.go+++ b/webserver/handlers/admin/connectedClients.go@@ -4,14 +4,13 @@ import ("encoding/json""net/http"- "github.com/owncast/owncast/core/chat""github.com/owncast/owncast/models"webutils "github.com/owncast/owncast/webserver/utils")// GetConnectedChatClients returns currently connected clients.-func GetConnectedChatClients(w http.ResponseWriter, r *http.Request) {- clients := chat.GetClients()+func (a *Admin) GetConnectedChatClients(w http.ResponseWriter, r *http.Request) {+ clients := a.chat.GetClients()w.Header().Set("Content-Type", "application/json")if err := json.NewEncoder(w).Encode(clients); err != nil {@@ -20,6 +19,6 @@ func GetConnectedChatClients(w http.ResponseWriter, r *http.Request) {}// ExternalGetConnectedChatClients returns currently connected clients.-func ExternalGetConnectedChatClients(integration models.ExternalAPIUser, w http.ResponseWriter, r *http.Request) {- GetConnectedChatClients(w, r)+func (a *Admin) ExternalGetConnectedChatClients(integration models.ExternalAPIUser, w http.ResponseWriter, r *http.Request) {+ a.GetConnectedChatClients(w, r)}diff --git a/webserver/handlers/admin/disconnect.go b/webserver/handlers/admin/disconnect.goindex 66a3deea27..1b77925726 100644--- a/webserver/handlers/admin/disconnect.go+++ b/webserver/handlers/admin/disconnect.go@@ -3,19 +3,16 @@ package adminimport ("net/http"- "github.com/owncast/owncast/core"webutils "github.com/owncast/owncast/webserver/utils"-- "github.com/owncast/owncast/core/rtmp")// DisconnectInboundConnection will force-disconnect an inbound stream.-func DisconnectInboundConnection(w http.ResponseWriter, r *http.Request) {- if !core.GetStatus().Online {+func (a *Admin) DisconnectInboundConnection(w http.ResponseWriter, r *http.Request) {+ if !a.stream.GetStatus().Online {webutils.WriteSimpleResponse(w, false, "no inbound stream connected")return}- rtmp.Disconnect()+ a.rtmp.Disconnect()webutils.WriteSimpleResponse(w, true, "inbound stream disconnected")}diff --git a/webserver/handlers/admin/externalAPIUsers.go b/webserver/handlers/admin/externalAPIUsers.goindex 5038ad4626..e6324c476d 100644--- a/webserver/handlers/admin/externalAPIUsers.go+++ b/webserver/handlers/admin/externalAPIUsers.go@@ -8,14 +8,13 @@ import ("github.com/owncast/owncast/config""github.com/owncast/owncast/models"- "github.com/owncast/owncast/persistence/userrepository""github.com/owncast/owncast/utils""github.com/owncast/owncast/webserver/handlers/generated"webutils "github.com/owncast/owncast/webserver/utils")// CreateExternalAPIUser will generate a 3rd party access token.-func CreateExternalAPIUser(w http.ResponseWriter, r *http.Request) {+func (a *Admin) CreateExternalAPIUser(w http.ResponseWriter, r *http.Request) {decoder := json.NewDecoder(r.Body)var request generated.CreateExternalAPIUserJSONBodyif err := decoder.Decode(&request); err != nil {@@ -23,8 +22,6 @@ func CreateExternalAPIUser(w http.ResponseWriter, r *http.Request) {return}- userRepository := userrepository.Get()-if request.Scopes == nil {webutils.BadRequestHandler(w, errors.New("scopes field is required"))return@@ -36,7 +33,7 @@ func CreateExternalAPIUser(w http.ResponseWriter, r *http.Request) {}// Verify all the scopes provided are valid- if !userRepository.HasValidScopes(*request.Scopes) {+ if !a.userRepository.HasValidScopes(*request.Scopes) {webutils.BadRequestHandler(w, errors.New("one or more invalid scopes provided"))return}@@ -49,7 +46,7 @@ func CreateExternalAPIUser(w http.ResponseWriter, r *http.Request) {color := utils.GenerateRandomDisplayColor(config.MaxUserColor)- if err := userRepository.InsertExternalAPIUser(token, *request.Name, color, *request.Scopes); err != nil {+ if err := a.userRepository.InsertExternalAPIUser(token, *request.Name, color, *request.Scopes); err != nil {webutils.InternalErrorHandler(w, err)return}@@ -66,12 +63,10 @@ func CreateExternalAPIUser(w http.ResponseWriter, r *http.Request) {}// GetExternalAPIUsers will return all 3rd party access tokens.-func GetExternalAPIUsers(w http.ResponseWriter, r *http.Request) {+func (a *Admin) GetExternalAPIUsers(w http.ResponseWriter, r *http.Request) {w.Header().Set("Content-Type", "application/json")- userRepository := userrepository.Get()-- tokens, err := userRepository.GetExternalAPIUser()+ tokens, err := a.userRepository.GetExternalAPIUser()if err != nil {webutils.InternalErrorHandler(w, err)return@@ -80,7 +75,7 @@ func GetExternalAPIUsers(w http.ResponseWriter, r *http.Request) {}// DeleteExternalAPIUser will return a single 3rd party access token.-func DeleteExternalAPIUser(w http.ResponseWriter, r *http.Request) {+func (a *Admin) DeleteExternalAPIUser(w http.ResponseWriter, r *http.Request) {w.Header().Set("Content-Type", "application/json")if r.Method != http.MethodPost {@@ -105,9 +100,7 @@ func DeleteExternalAPIUser(w http.ResponseWriter, r *http.Request) {return}- userRepository := userrepository.Get()-- if err := userRepository.DeleteExternalAPIUser(*request.Token); err != nil {+ if err := a.userRepository.DeleteExternalAPIUser(*request.Token); err != nil {webutils.InternalErrorHandler(w, err)return}diff --git a/webserver/handlers/admin/federation.go b/webserver/handlers/admin/federation.goindex 8c2c4aaa7c..0881f24df8 100644--- a/webserver/handlers/admin/federation.go+++ b/webserver/handlers/admin/federation.go@@ -3,22 +3,16 @@ package adminimport ("net/http"- "github.com/owncast/owncast/activitypub"- "github.com/owncast/owncast/activitypub/outbox"- "github.com/owncast/owncast/activitypub/persistence"- "github.com/owncast/owncast/persistence/configrepository"webutils "github.com/owncast/owncast/webserver/utils")// SendFederatedMessage will send a manual message to the fediverse.-func SendFederatedMessage(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SendFederatedMessage(w http.ResponseWriter, r *http.Request) {if !requirePOST(w, r) {return}- configRepository := configrepository.Get()-- if !configRepository.GetFederationEnabled() {+ if !a.configRepository.GetFederationEnabled() {webutils.WriteSimpleResponse(w, false, "Federation is disabled")return}@@ -34,7 +28,7 @@ func SendFederatedMessage(w http.ResponseWriter, r *http.Request) {return}- if err := activitypub.SendPublicFederatedMessage(message); err != nil {+ if err := a.activitypub.SendPublicFederatedMessage(message); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return}@@ -43,7 +37,7 @@ func SendFederatedMessage(w http.ResponseWriter, r *http.Request) {}// SetFederationEnabled will set if Federation features are enabled.-func SetFederationEnabled(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetFederationEnabled(w http.ResponseWriter, r *http.Request) {if !requirePOST(w, r) {return}@@ -53,9 +47,7 @@ func SetFederationEnabled(w http.ResponseWriter, r *http.Request) {return}- configRepository := configrepository.Get()-- if err := configRepository.SetFederationEnabled(configValue.Value.(bool)); err != nil {+ if err := a.configRepository.SetFederationEnabled(configValue.Value.(bool)); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return}@@ -63,7 +55,7 @@ func SetFederationEnabled(w http.ResponseWriter, r *http.Request) {}// SetFederationActivityPrivate will set if Federation features are private to followers.-func SetFederationActivityPrivate(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetFederationActivityPrivate(w http.ResponseWriter, r *http.Request) {if !requirePOST(w, r) {return}@@ -73,15 +65,13 @@ func SetFederationActivityPrivate(w http.ResponseWriter, r *http.Request) {return}- configRepository := configrepository.Get()-- if err := configRepository.SetFederationIsPrivate(configValue.Value.(bool)); err != nil {+ if err := a.configRepository.SetFederationIsPrivate(configValue.Value.(bool)); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return}// Update Fediverse followers about this change.- if err := outbox.UpdateFollowersWithAccountUpdates(); err != nil {+ if err := a.activitypub.UpdateFollowersWithAccountUpdates(); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return}@@ -90,7 +80,7 @@ func SetFederationActivityPrivate(w http.ResponseWriter, r *http.Request) {}// SetFederationShowEngagement will set if Fedivese engagement shows in chat.-func SetFederationShowEngagement(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetFederationShowEngagement(w http.ResponseWriter, r *http.Request) {if !requirePOST(w, r) {return}@@ -100,8 +90,7 @@ func SetFederationShowEngagement(w http.ResponseWriter, r *http.Request) {return}- configRepository := configrepository.Get()- if err := configRepository.SetFederationShowEngagement(configValue.Value.(bool)); err != nil {+ if err := a.configRepository.SetFederationShowEngagement(configValue.Value.(bool)); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return}@@ -109,7 +98,7 @@ func SetFederationShowEngagement(w http.ResponseWriter, r *http.Request) {}// SetFederationUsername will set the local actor username used for federation activities.-func SetFederationUsername(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetFederationUsername(w http.ResponseWriter, r *http.Request) {if !requirePOST(w, r) {return}@@ -119,8 +108,7 @@ func SetFederationUsername(w http.ResponseWriter, r *http.Request) {return}- configRepository := configrepository.Get()- if err := configRepository.SetFederationUsername(configValue.Value.(string)); err != nil {+ if err := a.configRepository.SetFederationUsername(configValue.Value.(string)); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return}@@ -129,7 +117,7 @@ func SetFederationUsername(w http.ResponseWriter, r *http.Request) {}// SetFederationGoLiveMessage will set the federated message sent when the streamer goes live.-func SetFederationGoLiveMessage(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetFederationGoLiveMessage(w http.ResponseWriter, r *http.Request) {if !requirePOST(w, r) {return}@@ -139,8 +127,7 @@ func SetFederationGoLiveMessage(w http.ResponseWriter, r *http.Request) {return}- configRepository := configrepository.Get()- if err := configRepository.SetFederationGoLiveMessage(configValue.Value.(string)); err != nil {+ if err := a.configRepository.SetFederationGoLiveMessage(configValue.Value.(string)); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return}@@ -149,7 +136,7 @@ func SetFederationGoLiveMessage(w http.ResponseWriter, r *http.Request) {}// SetFederationBlockDomains saves a list of domains to block on the Fediverse.-func SetFederationBlockDomains(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetFederationBlockDomains(w http.ResponseWriter, r *http.Request) {if !requirePOST(w, r) {return}@@ -165,8 +152,7 @@ func SetFederationBlockDomains(w http.ResponseWriter, r *http.Request) {domainStrings = append(domainStrings, domain.Value.(string))}- configRepository := configrepository.Get()- if err := configRepository.SetBlockedFederatedDomains(domainStrings); err != nil {+ if err := a.configRepository.SetBlockedFederatedDomains(domainStrings); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return}@@ -176,10 +162,10 @@ func SetFederationBlockDomains(w http.ResponseWriter, r *http.Request) {// GetFederatedActions will return the saved list of accepted inbound// federated activities.-func GetFederatedActions(page int, pageSize int, w http.ResponseWriter, r *http.Request) {+func (a *Admin) GetFederatedActions(page int, pageSize int, w http.ResponseWriter, r *http.Request) {offset := pageSize * page- activities, total, err := persistence.GetInboundActivities(pageSize, offset)+ activities, total, err := a.activitypub.GetInboundActivities(pageSize, offset)if err != nil {webutils.WriteSimpleResponse(w, false, err.Error())returndiff --git a/webserver/handlers/admin/followers.go b/webserver/handlers/admin/followers.goindex e44c4f5411..bc8c70d244 100644--- a/webserver/handlers/admin/followers.go+++ b/webserver/handlers/admin/followers.go@@ -4,16 +4,13 @@ import ("encoding/json""net/http"- "github.com/owncast/owncast/activitypub/persistence/followersrepository"- "github.com/owncast/owncast/activitypub/requests"- "github.com/owncast/owncast/core/webhooks"- "github.com/owncast/owncast/persistence/configrepository"+ "github.com/owncast/owncast/services/activitypub/requests""github.com/owncast/owncast/webserver/handlers/generated"webutils "github.com/owncast/owncast/webserver/utils")// ApproveFollower will approve a federated follow request.-func ApproveFollower(w http.ResponseWriter, r *http.Request) {+func (a *Admin) ApproveFollower(w http.ResponseWriter, r *http.Request) {if !requirePOST(w, r) {return}@@ -30,35 +27,32 @@ func ApproveFollower(w http.ResponseWriter, r *http.Request) {return}- followersRepo := followersrepository.Get()-if *approval.Approved {// Approve a follower- if err := followersRepo.ApprovePreviousRequest(*approval.ActorIRI); err != nil {+ if err := a.followersRepository.ApprovePreviousRequest(*approval.ActorIRI); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return}// Fire fediverse engagement follow event.- go webhooks.SendFediverseEngagementFollowEvent(*approval.ActorIRI)+ go a.webhooks.SendFediverseEngagementFollowEvent(*approval.ActorIRI)- configRepository := configrepository.Get()- localAccountName := configRepository.GetDefaultFederationUsername()+ localAccountName := a.configRepository.GetDefaultFederationUsername()- followRequest, err := followersRepo.GetByIRI(*approval.ActorIRI)+ followRequest, err := a.followersRepository.GetByIRI(*approval.ActorIRI)if err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return}// Send the approval to the follow requestor.- if err := requests.SendFollowAccept(followRequest.Inbox, followRequest.RequestObject, localAccountName); err != nil {+ if err := requests.SendFollowAccept(a.activitypub.Workerpool(), followRequest.Inbox, followRequest.RequestObject, localAccountName, a.apBuilder, a.apSigner); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return}} else {// Remove/block a follower- if err := followersRepo.BlockOrReject(*approval.ActorIRI); err != nil {+ if err := a.followersRepository.BlockOrReject(*approval.ActorIRI); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return}@@ -68,9 +62,8 @@ func ApproveFollower(w http.ResponseWriter, r *http.Request) {}// GetPendingFollowRequests will return a list of pending follow requests.-func GetPendingFollowRequests(w http.ResponseWriter, r *http.Request) {- followersRepo := followersrepository.Get()- requests, err := followersRepo.GetPendingFollowRequests()+func (a *Admin) GetPendingFollowRequests(w http.ResponseWriter, r *http.Request) {+ requests, err := a.followersRepository.GetPendingFollowRequests()if err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return@@ -80,9 +73,8 @@ func GetPendingFollowRequests(w http.ResponseWriter, r *http.Request) {}// GetBlockedAndRejectedFollowers will return blocked and rejected followers.-func GetBlockedAndRejectedFollowers(w http.ResponseWriter, r *http.Request) {- followersRepo := followersrepository.Get()- rejections, err := followersRepo.GetBlockedAndRejected()+func (a *Admin) GetBlockedAndRejectedFollowers(w http.ResponseWriter, r *http.Request) {+ rejections, err := a.followersRepository.GetBlockedAndRejected()if err != nil {webutils.WriteSimpleResponse(w, false, err.Error())returndiff --git a/webserver/handlers/admin/hardware.go b/webserver/handlers/admin/hardware.goindex fc036bc3f8..9728ea09a9 100644--- a/webserver/handlers/admin/hardware.go+++ b/webserver/handlers/admin/hardware.go@@ -4,13 +4,12 @@ import ("encoding/json""net/http"- "github.com/owncast/owncast/metrics"log "github.com/sirupsen/logrus")// GetHardwareStats will return hardware utilization over time.-func GetHardwareStats(w http.ResponseWriter, r *http.Request) {- m := metrics.GetMetrics()+func (a *Admin) GetHardwareStats(w http.ResponseWriter, r *http.Request) {+ m := a.metrics.GetMetrics()w.Header().Set("Content-Type", "application/json")err := json.NewEncoder(w).Encode(m)diff --git a/webserver/handlers/admin/logs.go b/webserver/handlers/admin/logs.goindex bfacfe2900..043386ebda 100644--- a/webserver/handlers/admin/logs.go+++ b/webserver/handlers/admin/logs.go@@ -5,8 +5,9 @@ import ("net/http""time"- "github.com/owncast/owncast/logging"log "github.com/sirupsen/logrus"++ "github.com/owncast/owncast/logging")// GetLogs will return all logs.diff --git a/webserver/handlers/admin/notifications.go b/webserver/handlers/admin/notifications.goindex 6ba8931272..81c2c377fa 100644--- a/webserver/handlers/admin/notifications.go+++ b/webserver/handlers/admin/notifications.go@@ -5,12 +5,11 @@ import ("net/http""github.com/owncast/owncast/models"- "github.com/owncast/owncast/persistence/configrepository"webutils "github.com/owncast/owncast/webserver/utils")// SetDiscordNotificationConfiguration will set the discord notification configuration.-func SetDiscordNotificationConfiguration(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetDiscordNotificationConfiguration(w http.ResponseWriter, r *http.Request) {if !requirePOST(w, r) {return}@@ -19,8 +18,6 @@ func SetDiscordNotificationConfiguration(w http.ResponseWriter, r *http.Request)Value models.DiscordConfiguration `json:"value"`}- configRepository := configrepository.Get()-decoder := json.NewDecoder(r.Body)var config requestif err := decoder.Decode(&config); err != nil {@@ -28,7 +25,7 @@ func SetDiscordNotificationConfiguration(w http.ResponseWriter, r *http.Request)return}- if err := configRepository.SetDiscordConfig(config.Value); err != nil {+ if err := a.configRepository.SetDiscordConfig(config.Value); err != nil {webutils.WriteSimpleResponse(w, false, "unable to update discord config with provided values")return}@@ -37,7 +34,7 @@ func SetDiscordNotificationConfiguration(w http.ResponseWriter, r *http.Request)}// SetBrowserNotificationConfiguration will set the browser notification configuration.-func SetBrowserNotificationConfiguration(w http.ResponseWriter, r *http.Request) {+func (a *Admin) SetBrowserNotificationConfiguration(w http.ResponseWriter, r *http.Request) {if !requirePOST(w, r) {return}@@ -46,7 +43,6 @@ func SetBrowserNotificationConfiguration(w http.ResponseWriter, r *http.Request)Value models.BrowserNotificationConfiguration `json:"value"`}- configRepository := configrepository.Get()decoder := json.NewDecoder(r.Body)var config requestif err := decoder.Decode(&config); err != nil {@@ -54,7 +50,7 @@ func SetBrowserNotificationConfiguration(w http.ResponseWriter, r *http.Request)return}- if err := configRepository.SetBrowserPushConfig(config.Value); err != nil {+ if err := a.configRepository.SetBrowserPushConfig(config.Value); err != nil {webutils.WriteSimpleResponse(w, false, "unable to update browser push config with provided values")return}diff --git a/webserver/handlers/admin/serverConfig.go b/webserver/handlers/admin/serverConfig.goindex fdf76290b6..5300402755 100644--- a/webserver/handlers/admin/serverConfig.go+++ b/webserver/handlers/admin/serverConfig.go@@ -4,19 +4,18 @@ import ("encoding/json""net/http"- "github.com/owncast/owncast/config"- "github.com/owncast/owncast/core/transcoder"+ log "github.com/sirupsen/logrus"+"github.com/owncast/owncast/models"- "github.com/owncast/owncast/persistence/configrepository"+ "github.com/owncast/owncast/services/transcoder""github.com/owncast/owncast/utils""github.com/owncast/owncast/webserver/handlers/generated""github.com/owncast/owncast/webserver/router/middleware"- log "github.com/sirupsen/logrus")// GetServerConfig gets the config details of the server.-func GetServerConfig(w http.ResponseWriter, r *http.Request) {- configRepository := configrepository.Get()+func (a *Admin) GetServerConfig(w http.ResponseWriter, r *http.Request) {+ configRepository := a.configRepositoryffmpeg := utils.ValidatedFfmpegPath(configRepository.GetFfMpegPath())usernameBlocklist := configRepository.GetForbiddenUsernameList()usernameSuggestions := configRepository.GetSuggestedUsernamesList()@@ -55,9 +54,9 @@ func GetServerConfig(w http.ResponseWriter, r *http.Request) {FFmpegPath: ffmpeg,AdminPassword: configRepository.GetAdminPassword(),StreamKeys: configRepository.GetStreamKeys(),- StreamKeyOverridden: config.TemporaryStreamKey != "",- WebServerPort: config.WebServerPort,- WebServerIP: config.WebServerIP,+ StreamKeyOverridden: a.cfg.TemporaryStreamKey != "",+ WebServerPort: a.cfg.WebServerPort,+ WebServerIP: a.cfg.WebServerIP,RTMPServerPort: configRepository.GetRTMPPortNumber(),ChatDisabled: configRepository.GetChatDisabled(),ChatJoinMessagesEnabled: configRepository.GetChatJoinPartMessagesEnabled(),diff --git a/webserver/handlers/admin/status.go b/webserver/handlers/admin/status.goindex e8cf205a9c..acfa76cfa9 100644--- a/webserver/handlers/admin/status.go+++ b/webserver/handlers/admin/status.go@@ -4,22 +4,18 @@ import ("encoding/json""net/http"- "github.com/owncast/owncast/core"- "github.com/owncast/owncast/metrics"+ log "github.com/sirupsen/logrus"+"github.com/owncast/owncast/models"- "github.com/owncast/owncast/persistence/configrepository""github.com/owncast/owncast/webserver/router/middleware"- log "github.com/sirupsen/logrus")// Status gets the details of the inbound broadcaster.-func Status(w http.ResponseWriter, r *http.Request) {- configRepository := configrepository.Get()-- broadcaster := core.GetBroadcaster()- status := core.GetStatus()- currentBroadcast := core.GetCurrentBroadcast()- health := metrics.GetStreamHealthOverview()+func (a *Admin) Status(w http.ResponseWriter, r *http.Request) {+ broadcaster := a.stream.GetBroadcaster()+ status := a.stream.GetStatus()+ currentBroadcast := a.stream.GetCurrentBroadcast()+ health := a.metrics.GetStreamHealthOverview()response := adminStatusResponse{Broadcaster: broadcaster,CurrentBroadcast: currentBroadcast,@@ -29,7 +25,7 @@ func Status(w http.ResponseWriter, r *http.Request) {OverallPeakViewerCount: status.OverallMaxViewerCount,SessionPeakViewerCount: status.SessionMaxViewerCount,VersionNumber: status.VersionNumber,- StreamTitle: configRepository.GetStreamTitle(),+ StreamTitle: a.configRepository.GetStreamTitle(),}w.Header().Set("Content-Type", "application/json")diff --git a/webserver/handlers/admin/update.go b/webserver/handlers/admin/update.goindex d690a83010..a70c2062fe 100644--- a/webserver/handlers/admin/update.go+++ b/webserver/handlers/admin/update.go@@ -9,9 +9,10 @@ import ("strconv""strings"+ log "github.com/sirupsen/logrus"+"github.com/owncast/owncast/config"webutils "github.com/owncast/owncast/webserver/utils"- log "github.com/sirupsen/logrus")/*diff --git a/webserver/handlers/admin/video.go b/webserver/handlers/admin/video.goindex 18521fe113..6cfeac6417 100644--- a/webserver/handlers/admin/video.go+++ b/webserver/handlers/admin/video.go@@ -4,14 +4,13 @@ import ("encoding/json""net/http"- "github.com/owncast/owncast/core"- "github.com/owncast/owncast/metrics"- "github.com/owncast/owncast/persistence/configrepository"log "github.com/sirupsen/logrus"++ "github.com/owncast/owncast/metrics")// GetVideoPlaybackMetrics returns video playback metrics.-func GetVideoPlaybackMetrics(w http.ResponseWriter, r *http.Request) {+func (a *Admin) GetVideoPlaybackMetrics(w http.ResponseWriter, r *http.Request) {type response struct {Errors []metrics.TimestampedValue `json:"errors"`QualityVariantChanges []metrics.TimestampedValue `json:"qualityVariantChanges"`@@ -34,34 +33,33 @@ func GetVideoPlaybackMetrics(w http.ResponseWriter, r *http.Request) {availableBitrates := []int{}var segmentLength int- if core.GetCurrentBroadcast() != nil {- segmentLength = core.GetCurrentBroadcast().LatencyLevel.SecondsPerSegment- for _, variants := range core.GetCurrentBroadcast().OutputSettings {+ if broadcast := a.stream.GetCurrentBroadcast(); broadcast != nil {+ segmentLength = broadcast.LatencyLevel.SecondsPerSegment+ for _, variants := range broadcast.OutputSettings {availableBitrates = append(availableBitrates, variants.VideoBitrate)}} else {- configRepository := configrepository.Get()- segmentLength = configRepository.GetStreamLatencyLevel().SecondsPerSegment- for _, variants := range configRepository.GetStreamOutputVariants() {+ segmentLength = a.configRepository.GetStreamLatencyLevel().SecondsPerSegment+ for _, variants := range a.configRepository.GetStreamOutputVariants() {availableBitrates = append(availableBitrates, variants.VideoBitrate)}}- errors := metrics.GetPlaybackErrorCountOverTime()- medianLatency := metrics.GetMedianLatencyOverTime()- minimumLatency := metrics.GetMinimumLatencyOverTime()- maximumLatency := metrics.GetMaximumLatencyOverTime()+ errors := a.metrics.GetPlaybackErrorCountOverTime()+ medianLatency := a.metrics.GetMedianLatencyOverTime()+ minimumLatency := a.metrics.GetMinimumLatencyOverTime()+ maximumLatency := a.metrics.GetMaximumLatencyOverTime()- medianDurations := metrics.GetMedianDownloadDurationsOverTime()- maximumDurations := metrics.GetMaximumDownloadDurationsOverTime()- minimumDurations := metrics.GetMinimumDownloadDurationsOverTime()+ medianDurations := a.metrics.GetMedianDownloadDurationsOverTime()+ maximumDurations := a.metrics.GetMaximumDownloadDurationsOverTime()+ minimumDurations := a.metrics.GetMinimumDownloadDurationsOverTime()- minPlayerBitrate := metrics.GetSlowestDownloadRateOverTime()- medianPlayerBitrate := metrics.GetMedianDownloadRateOverTime()- maxPlayerBitrate := metrics.GetMaxDownloadRateOverTime()- qualityVariantChanges := metrics.GetQualityVariantChangesOverTime()+ minPlayerBitrate := a.metrics.GetSlowestDownloadRateOverTime()+ medianPlayerBitrate := a.metrics.GetMedianDownloadRateOverTime()+ maxPlayerBitrate := a.metrics.GetMaxDownloadRateOverTime()+ qualityVariantChanges := a.metrics.GetQualityVariantChangesOverTime()- representation := metrics.GetPlaybackMetricsRepresentation()+ representation := a.metrics.GetPlaybackMetricsRepresentation()resp := response{AvailableBitrates: availableBitrates,diff --git a/webserver/handlers/admin/viewers.go b/webserver/handlers/admin/viewers.goindex b89dd715e9..61632428cb 100644--- a/webserver/handlers/admin/viewers.go+++ b/webserver/handlers/admin/viewers.go@@ -6,15 +6,14 @@ import ("strconv""time"- "github.com/owncast/owncast/core"- "github.com/owncast/owncast/metrics"+ log "github.com/sirupsen/logrus"+"github.com/owncast/owncast/models"webutils "github.com/owncast/owncast/webserver/utils"- log "github.com/sirupsen/logrus")// GetViewersOverTime will return the number of viewers at points in time.-func GetViewersOverTime(w http.ResponseWriter, r *http.Request) {+func (a *Admin) GetViewersOverTime(w http.ResponseWriter, r *http.Request) {windowStartAtStr := r.URL.Query().Get("windowStart")windowStartAtUnix, err := strconv.Atoi(windowStartAtStr)if err != nil {@@ -25,7 +24,7 @@ func GetViewersOverTime(w http.ResponseWriter, r *http.Request) {windowStartAt := time.Unix(int64(windowStartAtUnix), 0)windowEnd := time.Now()- viewersOverTime := metrics.GetViewersOverTime(windowStartAt, windowEnd)+ viewersOverTime := a.metrics.GetViewersOverTime(windowStartAt, windowEnd)w.Header().Set("Content-Type", "application/json")err = json.NewEncoder(w).Encode(viewersOverTime)if err != nil {@@ -34,8 +33,8 @@ func GetViewersOverTime(w http.ResponseWriter, r *http.Request) {}// GetActiveViewers returns currently connected clients.-func GetActiveViewers(w http.ResponseWriter, r *http.Request) {- c := core.GetActiveViewers()+func (a *Admin) GetActiveViewers(w http.ResponseWriter, r *http.Request) {+ c := a.stream.GetActiveViewers()viewers := make([]models.Viewer, 0, len(c))for _, v := range c {viewers = append(viewers, *v)@@ -49,6 +48,6 @@ func GetActiveViewers(w http.ResponseWriter, r *http.Request) {}// ExternalGetActiveViewers returns currently connected clients.-func ExternalGetActiveViewers(integration models.ExternalAPIUser, w http.ResponseWriter, r *http.Request) {- GetConnectedChatClients(w, r)+func (a *Admin) ExternalGetActiveViewers(integration models.ExternalAPIUser, w http.ResponseWriter, r *http.Request) {+ a.GetConnectedChatClients(w, r)}diff --git a/webserver/handlers/admin/webhooks.go b/webserver/handlers/admin/webhooks.goindex 39b381f737..d65ade20d1 100644--- a/webserver/handlers/admin/webhooks.go+++ b/webserver/handlers/admin/webhooks.go@@ -7,7 +7,6 @@ import ("time""github.com/owncast/owncast/models"- "github.com/owncast/owncast/persistence/webhookrepository""github.com/owncast/owncast/webserver/handlers/generated"webutils "github.com/owncast/owncast/webserver/utils")@@ -18,7 +17,7 @@ type createWebhookRequest struct {}// CreateWebhook will add a single webhook.-func CreateWebhook(w http.ResponseWriter, r *http.Request) {+func (a *Admin) CreateWebhook(w http.ResponseWriter, r *http.Request) {decoder := json.NewDecoder(r.Body)var request createWebhookRequestif err := decoder.Decode(&request); err != nil {@@ -32,8 +31,7 @@ func CreateWebhook(w http.ResponseWriter, r *http.Request) {return}- webhooksrepo := webhookrepository.Get()- newWebhookID, err := webhooksrepo.InsertWebhook(request.URL, request.Events)+ newWebhookID, err := a.webhookRepository.InsertWebhook(request.URL, request.Events)if err != nil {webutils.InternalErrorHandler(w, err)return@@ -49,9 +47,8 @@ func CreateWebhook(w http.ResponseWriter, r *http.Request) {}// GetWebhooks will return all webhooks.-func GetWebhooks(w http.ResponseWriter, r *http.Request) {- webhooksrepo := webhookrepository.Get()- webhooks, err := webhooksrepo.GetWebhooks()+func (a *Admin) GetWebhooks(w http.ResponseWriter, r *http.Request) {+ webhooks, err := a.webhookRepository.GetWebhooks()if err != nil {webutils.InternalErrorHandler(w, err)return@@ -61,7 +58,7 @@ func GetWebhooks(w http.ResponseWriter, r *http.Request) {}// DeleteWebhook will delete a single webhook.-func DeleteWebhook(w http.ResponseWriter, r *http.Request) {+func (a *Admin) DeleteWebhook(w http.ResponseWriter, r *http.Request) {if r.Method != http.MethodPost {webutils.WriteSimpleResponse(w, false, r.Method+" not supported")return@@ -74,8 +71,7 @@ func DeleteWebhook(w http.ResponseWriter, r *http.Request) {return}- webhooksrepo := webhookrepository.Get()- if err := webhooksrepo.DeleteWebhook(*request.Id); err != nil {+ if err := a.webhookRepository.DeleteWebhook(*request.Id); err != nil {webutils.InternalErrorHandler(w, err)return}diff --git a/webserver/handlers/admin/yp.go b/webserver/handlers/admin/yp.goindex 75b622922b..3e4798b647 100644--- a/webserver/handlers/admin/yp.go+++ b/webserver/handlers/admin/yp.go@@ -3,16 +3,15 @@ package adminimport ("net/http"- "github.com/owncast/owncast/persistence/configrepository"- webutils "github.com/owncast/owncast/webserver/utils"log "github.com/sirupsen/logrus"++ webutils "github.com/owncast/owncast/webserver/utils")// ResetYPRegistration will clear the YP protocol registration key.-func ResetYPRegistration(w http.ResponseWriter, r *http.Request) {+func (a *Admin) ResetYPRegistration(w http.ResponseWriter, r *http.Request) {log.Traceln("Resetting YP registration key")- configRepository := configrepository.Get()- if err := configRepository.SetDirectoryRegistrationKey(""); err != nil {+ if err := a.configRepository.SetDirectoryRegistrationKey(""); err != nil {log.Errorln(err)webutils.WriteSimpleResponse(w, false, err.Error())returndiff --git a/webserver/handlers/auth.go b/webserver/handlers/auth.goindex c69e9d8e1d..34f6461a27 100644--- a/webserver/handlers/auth.go+++ b/webserver/handlers/auth.go@@ -3,32 +3,29 @@ package handlersimport ("net/http"- "github.com/owncast/owncast/webserver/handlers/auth/fediverse"- "github.com/owncast/owncast/webserver/handlers/auth/indieauth""github.com/owncast/owncast/webserver/handlers/generated"- "github.com/owncast/owncast/webserver/router/middleware")-func (*ServerInterfaceImpl) StartIndieAuthFlow(w http.ResponseWriter, r *http.Request, params generated.StartIndieAuthFlowParams) {- middleware.RequireUserAccessToken(indieauth.StartAuthFlow)(w, r)+func (s *ServerInterfaceImpl) StartIndieAuthFlow(w http.ResponseWriter, r *http.Request, params generated.StartIndieAuthFlowParams) {+ s.h.middleware.RequireUserAccessToken(s.h.indieauth.StartAuthFlow)(w, r)}-func (*ServerInterfaceImpl) HandleIndieAuthRedirect(w http.ResponseWriter, r *http.Request, params generated.HandleIndieAuthRedirectParams) {- indieauth.HandleRedirect(w, r)+func (s *ServerInterfaceImpl) HandleIndieAuthRedirect(w http.ResponseWriter, r *http.Request, params generated.HandleIndieAuthRedirectParams) {+ s.h.indieauth.HandleRedirect(w, r)}-func (*ServerInterfaceImpl) HandleIndieAuthEndpointGet(w http.ResponseWriter, r *http.Request, params generated.HandleIndieAuthEndpointGetParams) {- middleware.RequireAdminAuth(indieauth.HandleAuthEndpointGet)(w, r)+func (s *ServerInterfaceImpl) HandleIndieAuthEndpointGet(w http.ResponseWriter, r *http.Request, params generated.HandleIndieAuthEndpointGetParams) {+ s.h.middleware.RequireAdminAuth(s.h.indieauth.HandleAuthEndpointGet)(w, r)}-func (*ServerInterfaceImpl) HandleIndieAuthEndpointPost(w http.ResponseWriter, r *http.Request) {- indieauth.HandleAuthEndpointPost(w, r)+func (s *ServerInterfaceImpl) HandleIndieAuthEndpointPost(w http.ResponseWriter, r *http.Request) {+ s.h.indieauth.HandleAuthEndpointPost(w, r)}-func (*ServerInterfaceImpl) RegisterFediverseOTPRequest(w http.ResponseWriter, r *http.Request, params generated.RegisterFediverseOTPRequestParams) {- middleware.RequireUserAccessToken(fediverse.RegisterFediverseOTPRequest)(w, r)+func (s *ServerInterfaceImpl) RegisterFediverseOTPRequest(w http.ResponseWriter, r *http.Request, params generated.RegisterFediverseOTPRequestParams) {+ s.h.middleware.RequireUserAccessToken(s.h.fediverse.RegisterFediverseOTPRequest)(w, r)}-func (*ServerInterfaceImpl) VerifyFediverseOTPRequest(w http.ResponseWriter, r *http.Request) {- fediverse.VerifyFediverseOTPRequest(w, r)+func (s *ServerInterfaceImpl) VerifyFediverseOTPRequest(w http.ResponseWriter, r *http.Request) {+ s.h.fediverse.VerifyFediverseOTPRequest(w, r)}diff --git a/webserver/handlers/auth/fediverse/fediverse.go b/webserver/handlers/auth/fediverse/fediverse.goindex 7f427b2815..14836e1da7 100644--- a/webserver/handlers/auth/fediverse/fediverse.go+++ b/webserver/handlers/auth/fediverse/fediverse.go@@ -5,19 +5,53 @@ import ("fmt""net/http"- "github.com/owncast/owncast/activitypub"+ log "github.com/sirupsen/logrus"+fediverseauth "github.com/owncast/owncast/auth/fediverse"- "github.com/owncast/owncast/core/chat""github.com/owncast/owncast/models""github.com/owncast/owncast/persistence/configrepository""github.com/owncast/owncast/persistence/userrepository"+ "github.com/owncast/owncast/services/activitypub"+ "github.com/owncast/owncast/services/chat""github.com/owncast/owncast/webserver/handlers/generated"webutils "github.com/owncast/owncast/webserver/utils"- log "github.com/sirupsen/logrus")+// Handler bundles the dependencies the fediverse auth handlers need:+// the activitypub service (to send OTP codes via direct federated+// message), the chat service (to broadcast a system action when an+// authenticated user re-logs in under a different display name), and+// the fediverse auth service that owns the in-memory OTP state.+type Handler struct {+ activitypub *activitypub.Service+ chat *chat.Service+ fediverseAuth *fediverseauth.Service+ configRepository configrepository.ConfigRepository+ userRepository userrepository.UserRepository+}++// Deps lists the dependencies of the fediverse auth Handler.+type Deps struct {+ Activitypub *activitypub.Service+ Chat *chat.Service+ FediverseAuth *fediverseauth.Service+ ConfigRepository configrepository.ConfigRepository+ UserRepository userrepository.UserRepository+}++// New constructs the Handler.+func New(deps Deps) *Handler {+ return &Handler{+ activitypub: deps.Activitypub,+ chat: deps.Chat,+ fediverseAuth: deps.FediverseAuth,+ configRepository: deps.ConfigRepository,+ userRepository: deps.UserRepository,+ }+}+// RegisterFediverseOTPRequest registers a new OTP request for the given access token.-func RegisterFediverseOTPRequest(u models.User, w http.ResponseWriter, r *http.Request) {+func (h *Handler) RegisterFediverseOTPRequest(u models.User, w http.ResponseWriter, r *http.Request) {type request struct {FediverseAccount string `json:"account"`}@@ -29,7 +63,7 @@ func RegisterFediverseOTPRequest(u models.User, w http.ResponseWriter, r *http.R}accessToken := r.URL.Query().Get("accessToken")- reg, success, err := fediverseauth.RegisterFediverseOTP(accessToken, u.ID, u.DisplayName, req.FediverseAccount)+ reg, success, err := h.fediverseAuth.RegisterFediverseOTP(accessToken, u.ID, u.DisplayName, req.FediverseAccount)if err != nil {webutils.WriteSimpleResponse(w, false, "Could not register auth request: "+err.Error())return@@ -40,9 +74,8 @@ func RegisterFediverseOTPRequest(u models.User, w http.ResponseWriter, r *http.Rreturn}- configRepository := configrepository.Get()- msg := fmt.Sprintf("<p>One-time code from %s: %s. If you did not request this message please ignore or block.</p>", configRepository.GetServerName(), reg.Code)- if err := activitypub.SendDirectFederatedMessage(msg, reg.Account); err != nil {+ msg := fmt.Sprintf("<p>One-time code from %s: %s. If you did not request this message please ignore or block.</p>", h.configRepository.GetServerName(), reg.Code)+ if err := h.activitypub.SendDirectFederatedMessage(msg, reg.Account); err != nil {webutils.WriteSimpleResponse(w, false, "Could not send code to fediverse: "+err.Error())return}@@ -51,7 +84,7 @@ func RegisterFediverseOTPRequest(u models.User, w http.ResponseWriter, r *http.R}// VerifyFediverseOTPRequest verifies the given OTP code for the given access token.-func VerifyFediverseOTPRequest(w http.ResponseWriter, r *http.Request) {+func (h *Handler) VerifyFediverseOTPRequest(w http.ResponseWriter, r *http.Request) {var req generated.VerifyFediverseOTPRequestJSONBodydecoder := json.NewDecoder(r.Body)@@ -66,29 +99,27 @@ func VerifyFediverseOTPRequest(w http.ResponseWriter, r *http.Request) {}accessToken := r.URL.Query().Get("accessToken")- valid, authRegistration := fediverseauth.ValidateFediverseOTP(accessToken, *req.Code)+ valid, authRegistration := h.fediverseAuth.ValidateFediverseOTP(accessToken, *req.Code)if !valid {w.WriteHeader(http.StatusForbidden)return}- userRepository := userrepository.Get()-// Check if a user with this auth already exists, if so, log them in.- if u := userRepository.GetUserByAuth(authRegistration.Account, models.Fediverse); u != nil {+ if u := h.userRepository.GetUserByAuth(authRegistration.Account, models.Fediverse); u != nil {// Handle existing auth.log.Debugln("user with provided fedvierse identity already exists, logging them in")// Update the current user's access token to point to the existing user id.userID := u.ID- if err := userRepository.SetAccessTokenToOwner(accessToken, userID); err != nil {+ if err := h.userRepository.SetAccessTokenToOwner(accessToken, userID); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return}if authRegistration.UserDisplayName != u.DisplayName {loginMessage := fmt.Sprintf("**%s** is now authenticated as **%s**", authRegistration.UserDisplayName, u.DisplayName)- if err := chat.SendSystemAction(loginMessage, true); err != nil {+ if err := h.chat.SendSystemAction(loginMessage, true); err != nil {log.Errorln(err)}}@@ -100,14 +131,14 @@ func VerifyFediverseOTPRequest(w http.ResponseWriter, r *http.Request) {// Otherwise, save this as new auth.log.Debug("fediverse account does not already exist, saving it as a new one for the current user")- if err := userRepository.AddAuth(authRegistration.UserID, authRegistration.Account, models.Fediverse); err != nil {+ if err := h.userRepository.AddAuth(authRegistration.UserID, authRegistration.Account, models.Fediverse); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return}// Update the current user's authenticated flag so we can show it in// the chat UI.- if err := userRepository.SetUserAsAuthenticated(authRegistration.UserID); err != nil {+ if err := h.userRepository.SetUserAsAuthenticated(authRegistration.UserID); err != nil {log.Errorln(err)}diff --git a/webserver/handlers/auth/indieauth/client.go b/webserver/handlers/auth/indieauth/client.goindex d52bf8a5eb..275d95329b 100644--- a/webserver/handlers/auth/indieauth/client.go+++ b/webserver/handlers/auth/indieauth/client.go@@ -6,16 +6,44 @@ import ("io""net/http"+ log "github.com/sirupsen/logrus"+ia "github.com/owncast/owncast/auth/indieauth"- "github.com/owncast/owncast/core/chat""github.com/owncast/owncast/models""github.com/owncast/owncast/persistence/userrepository"+ "github.com/owncast/owncast/services/chat"+ "github.com/owncast/owncast/webserver/router/middleware"webutils "github.com/owncast/owncast/webserver/utils"- log "github.com/sirupsen/logrus")+// Handler bundles the dependencies the IndieAuth handlers need.+type Handler struct {+ chat *chat.Service+ userRepository userrepository.UserRepository+ indieAuth *ia.Service+ middleware *middleware.Middleware+}++// Deps lists the dependencies of the IndieAuth Handler.+type Deps struct {+ Chat *chat.Service+ UserRepository userrepository.UserRepository+ IndieAuth *ia.Service+ Middleware *middleware.Middleware+}++// New constructs the Handler.+func New(deps Deps) *Handler {+ return &Handler{+ chat: deps.Chat,+ userRepository: deps.UserRepository,+ indieAuth: deps.IndieAuth,+ middleware: deps.Middleware,+ }+}+// StartAuthFlow will begin the IndieAuth flow for the current user.-func StartAuthFlow(u models.User, w http.ResponseWriter, r *http.Request) {+func (h *Handler) StartAuthFlow(u models.User, w http.ResponseWriter, r *http.Request) {type request struct {AuthHost string `json:"authHost"`}@@ -38,7 +66,7 @@ func StartAuthFlow(u models.User, w http.ResponseWriter, r *http.Request) {accessToken := r.URL.Query().Get("accessToken")- redirectURL, err := ia.StartAuthFlow(authRequest.AuthHost, u.ID, accessToken, u.DisplayName)+ redirectURL, err := h.indieAuth.StartAuthFlow(authRequest.AuthHost, u.ID, accessToken, u.DisplayName)if err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return@@ -52,10 +80,10 @@ func StartAuthFlow(u models.User, w http.ResponseWriter, r *http.Request) {// HandleRedirect will handle the redirect from an IndieAuth server to// continue the auth flow.-func HandleRedirect(w http.ResponseWriter, r *http.Request) {+func (h *Handler) HandleRedirect(w http.ResponseWriter, r *http.Request) {state := r.URL.Query().Get("state")code := r.URL.Query().Get("code")- request, response, err := ia.HandleCallbackCode(code, state)+ request, response, err := h.indieAuth.HandleCallbackCode(code, state)if err != nil {log.Debugln(err)msg := `Unable to complete authentication. <a href="/">Go back.</a><hr/>`@@ -63,24 +91,22 @@ func HandleRedirect(w http.ResponseWriter, r *http.Request) {return}- userRepository := userrepository.Get()-// Check if a user with this auth already exists, if so, log them in.- if u := userRepository.GetUserByAuth(response.Me, models.IndieAuth); u != nil {+ if u := h.userRepository.GetUserByAuth(response.Me, models.IndieAuth); u != nil {// Handle existing auth.log.Debugln("user with provided indieauth already exists, logging them in")// Update the current user's access token to point to the existing user id.accessToken := request.CurrentAccessTokenuserID := u.ID- if err := userRepository.SetAccessTokenToOwner(accessToken, userID); err != nil {+ if err := h.userRepository.SetAccessTokenToOwner(accessToken, userID); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return}if request.DisplayName != u.DisplayName {loginMessage := fmt.Sprintf("**%s** is now authenticated as **%s**", request.DisplayName, u.DisplayName)- if err := chat.SendSystemAction(loginMessage, true); err != nil {+ if err := h.chat.SendSystemAction(loginMessage, true); err != nil {log.Errorln(err)}}@@ -92,14 +118,14 @@ func HandleRedirect(w http.ResponseWriter, r *http.Request) {// Otherwise, save this as new auth.log.Debug("indieauth token does not already exist, saving it as a new one for the current user")- if err := userRepository.AddAuth(request.UserID, response.Me, models.IndieAuth); err != nil {+ if err := h.userRepository.AddAuth(request.UserID, response.Me, models.IndieAuth); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return}// Update the current user's authenticated flag so we can show it in// the chat UI.- if err := userRepository.SetUserAsAuthenticated(request.UserID); err != nil {+ if err := h.userRepository.SetUserAsAuthenticated(request.UserID); err != nil {log.Errorln(err)}diff --git a/webserver/handlers/auth/indieauth/server.go b/webserver/handlers/auth/indieauth/server.goindex 574dcc3e5b..140d24b257 100644--- a/webserver/handlers/auth/indieauth/server.go+++ b/webserver/handlers/auth/indieauth/server.go@@ -5,34 +5,33 @@ import ("net/url"ia "github.com/owncast/owncast/auth/indieauth"- "github.com/owncast/owncast/webserver/router/middleware"webutils "github.com/owncast/owncast/webserver/utils")// HandleAuthEndpoint will handle the IndieAuth auth endpoint.-func HandleAuthEndpoint(w http.ResponseWriter, r *http.Request) {+func (h *Handler) HandleAuthEndpoint(w http.ResponseWriter, r *http.Request) {switch r.Method {case http.MethodGet:// Require the GET request for IndieAuth to be behind admin login.- f := middleware.RequireAdminAuth(HandleAuthEndpointGet)+ f := h.middleware.RequireAdminAuth(h.HandleAuthEndpointGet)f(w, r)returncase http.MethodPost:- HandleAuthEndpointPost(w, r)+ h.HandleAuthEndpointPost(w, r)default:w.WriteHeader(http.StatusMethodNotAllowed)return}}-func HandleAuthEndpointGet(w http.ResponseWriter, r *http.Request) {+func (h *Handler) HandleAuthEndpointGet(w http.ResponseWriter, r *http.Request) {clientID := r.URL.Query().Get("client_id")redirectURI := r.URL.Query().Get("redirect_uri")codeChallenge := r.URL.Query().Get("code_challenge")state := r.URL.Query().Get("state")me := r.URL.Query().Get("me")- request, err := ia.StartServerAuth(clientID, redirectURI, codeChallenge, state, me)+ request, err := h.indieAuth.StartServerAuth(clientID, redirectURI, codeChallenge, state, me)if err != nil {_ = webutils.WriteString(w, err.Error(), http.StatusInternalServerError)return@@ -63,7 +62,7 @@ func HandleAuthEndpointGet(w http.ResponseWriter, r *http.Request) {http.Redirect(w, r, u.String(), http.StatusTemporaryRedirect) //nolint:gosec // G710: redirect_uri validated against client_id in StartServerAuth}-func HandleAuthEndpointPost(w http.ResponseWriter, r *http.Request) {+func (h *Handler) HandleAuthEndpointPost(w http.ResponseWriter, r *http.Request) {r.Body = http.MaxBytesReader(w, r.Body, 1<<20)if err := r.ParseForm(); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())@@ -77,7 +76,7 @@ func HandleAuthEndpointPost(w http.ResponseWriter, r *http.Request) {// If the server auth flow cannot be completed then return with specific// "invalid_client" error.- response, err := ia.CompleteServerAuth(code, redirectURI, clientID, codeVerifier)+ response, err := h.indieAuth.CompleteServerAuth(code, redirectURI, clientID, codeVerifier)if err != nil {webutils.WriteResponse(w, ia.Response{Error: "invalid_client",diff --git a/webserver/handlers/chat.go b/webserver/handlers/chat.goindex 7758aebcc8..561aebe994 100644--- a/webserver/handlers/chat.go+++ b/webserver/handlers/chat.go@@ -4,37 +4,34 @@ import ("encoding/json""net/http"+ log "github.com/sirupsen/logrus"+"github.com/owncast/owncast/config""github.com/owncast/owncast/models"- "github.com/owncast/owncast/persistence/chatmessagerepository"- "github.com/owncast/owncast/persistence/configrepository"- "github.com/owncast/owncast/persistence/userrepository""github.com/owncast/owncast/utils""github.com/owncast/owncast/webserver/handlers/generated""github.com/owncast/owncast/webserver/router/middleware"webutils "github.com/owncast/owncast/webserver/utils"- log "github.com/sirupsen/logrus")// ExternalGetChatMessages gets all of the chat messages.-func ExternalGetChatMessages(integration models.ExternalAPIUser, w http.ResponseWriter, r *http.Request) {+func (h *Handlers) ExternalGetChatMessages(integration models.ExternalAPIUser, w http.ResponseWriter, r *http.Request) {middleware.EnableCors(w)- getChatMessages(w, r)+ h.getChatMessages(w, r)}// GetChatMessages gets all of the chat messages.-func GetChatMessages(u models.User, w http.ResponseWriter, r *http.Request) {+func (h *Handlers) GetChatMessages(u models.User, w http.ResponseWriter, r *http.Request) {middleware.EnableCors(w)- getChatMessages(w, r)+ h.getChatMessages(w, r)}-func getChatMessages(w http.ResponseWriter, r *http.Request) {+func (h *Handlers) getChatMessages(w http.ResponseWriter, r *http.Request) {w.Header().Set("Content-Type", "application/json")switch r.Method {case http.MethodGet:- chatMessageRepository := chatmessagerepository.Get()- messages := chatMessageRepository.GetChatHistory()+ messages := h.chatMessageRepository.GetChatHistory()if err := json.NewEncoder(w).Encode(messages); err != nil {log.Debugln(err)@@ -48,11 +45,9 @@ func getChatMessages(w http.ResponseWriter, r *http.Request) {}// RegisterAnonymousChatUser will register a new user.-func RegisterAnonymousChatUser(w http.ResponseWriter, r *http.Request) {+func (h *Handlers) RegisterAnonymousChatUser(w http.ResponseWriter, r *http.Request) {middleware.EnableCors(w)- userRepository := userrepository.Get()-if r.Method == http.MethodOptions {// All OPTIONS requests should have a wildcard CORS header.w.Header().Set("Access-Control-Allow-Origin", "*")@@ -83,11 +78,11 @@ func RegisterAnonymousChatUser(w http.ResponseWriter, r *http.Request) {proposedNewDisplayName = *request.DisplayName}if proposedNewDisplayName == "" {- proposedNewDisplayName = generateDisplayName()+ proposedNewDisplayName = h.generateDisplayName()}proposedNewDisplayName = utils.MakeSafeStringOfLength(proposedNewDisplayName, config.MaxChatDisplayNameLength)- newUser, accessToken, err := userRepository.CreateAnonymousUser(proposedNewDisplayName)+ newUser, accessToken, err := h.userRepository.CreateAnonymousUser(proposedNewDisplayName)if err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return@@ -105,9 +100,8 @@ func RegisterAnonymousChatUser(w http.ResponseWriter, r *http.Request) {webutils.WriteResponse(w, response)}-func generateDisplayName() string {- configRepository := configrepository.Get()- suggestedUsernamesList := configRepository.GetSuggestedUsernamesList()+func (h *Handlers) generateDisplayName() string {+ suggestedUsernamesList := h.configRepository.GetSuggestedUsernamesList()minSuggestedUsernamePoolLength := 10if len(suggestedUsernamesList) >= minSuggestedUsernamePoolLength {diff --git a/webserver/handlers/config.go b/webserver/handlers/config.goindex 87450f5b53..d594199e46 100644--- a/webserver/handlers/config.go+++ b/webserver/handlers/config.go@@ -6,14 +6,13 @@ import ("net/http""net/url"- "github.com/owncast/owncast/activitypub"+ log "github.com/sirupsen/logrus"+"github.com/owncast/owncast/config""github.com/owncast/owncast/models"- "github.com/owncast/owncast/persistence/configrepository""github.com/owncast/owncast/utils""github.com/owncast/owncast/webserver/router/middleware"webutils "github.com/owncast/owncast/webserver/utils"- log "github.com/sirupsen/logrus")type webConfigResponse struct {@@ -61,20 +60,20 @@ type authenticationConfigResponse struct {}// GetWebConfig gets the status of the server.-func GetWebConfig(w http.ResponseWriter, r *http.Request) {+func (h *Handlers) GetWebConfig(w http.ResponseWriter, r *http.Request) {middleware.EnableCors(w)middleware.DisableCache(w)w.Header().Set("Content-Type", "application/json")- configuration := getConfigResponse()+ configuration := h.getConfigResponse()if err := json.NewEncoder(w).Encode(configuration); err != nil {webutils.BadRequestHandler(w, err)}}-func getConfigResponse() webConfigResponse {- configRepository := configrepository.Get()+func (h *Handlers) getConfigResponse() webConfigResponse {+ configRepository := h.configRepositorypageContent := utils.RenderPageContentMarkdown(configRepository.GetExtraPageBodyContent())offlineMessage := utils.RenderSimpleMarkdown(configRepository.GetCustomOfflineMessage())socialHandles := configRepository.GetSocialHandles()@@ -91,7 +90,7 @@ func getConfigResponse() webConfigResponse {var federationResponse federationConfigResponsefederationEnabled := configRepository.GetFederationEnabled()- followerCount, _ := activitypub.GetFollowerCount()+ followerCount, _ := h.activitypub.GetFollowerCount()if federationEnabled {serverURLString := configRepository.GetServerURL()serverURL, _ := url.Parse(serverURLString)diff --git a/webserver/handlers/configInterface.go b/webserver/handlers/configInterface.goindex 4bb51cbf08..8465c68334 100644--- a/webserver/handlers/configInterface.go+++ b/webserver/handlers/configInterface.go@@ -2,387 +2,384 @@ package handlersimport ("net/http"-- "github.com/owncast/owncast/webserver/handlers/admin"- "github.com/owncast/owncast/webserver/router/middleware")-func (*ServerInterfaceImpl) SetAdminPassword(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetAdminPassword)(w, r)+func (s *ServerInterfaceImpl) SetAdminPassword(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetAdminPassword)(w, r)}-func (*ServerInterfaceImpl) SetAdminPasswordOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetAdminPassword)(w, r)+func (s *ServerInterfaceImpl) SetAdminPasswordOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetAdminPassword)(w, r)}-func (*ServerInterfaceImpl) SetStreamKeys(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetStreamKeys)(w, r)+func (s *ServerInterfaceImpl) SetStreamKeys(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetStreamKeys)(w, r)}-func (*ServerInterfaceImpl) SetStreamKeysOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetStreamKeys)(w, r)+func (s *ServerInterfaceImpl) SetStreamKeysOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetStreamKeys)(w, r)}-func (*ServerInterfaceImpl) SetExtraPageContent(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetExtraPageContent)(w, r)+func (s *ServerInterfaceImpl) SetExtraPageContent(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetExtraPageContent)(w, r)}-func (*ServerInterfaceImpl) SetExtraPageContentOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetExtraPageContent)(w, r)+func (s *ServerInterfaceImpl) SetExtraPageContentOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetExtraPageContent)(w, r)}-func (*ServerInterfaceImpl) SetStreamTitle(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetStreamTitle)(w, r)+func (s *ServerInterfaceImpl) SetStreamTitle(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetStreamTitle)(w, r)}-func (*ServerInterfaceImpl) SetStreamTitleOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetStreamTitle)(w, r)+func (s *ServerInterfaceImpl) SetStreamTitleOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetStreamTitle)(w, r)}-func (*ServerInterfaceImpl) SetServerName(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetServerName)(w, r)+func (s *ServerInterfaceImpl) SetServerName(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetServerName)(w, r)}-func (*ServerInterfaceImpl) SetServerNameOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetServerName)(w, r)+func (s *ServerInterfaceImpl) SetServerNameOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetServerName)(w, r)}-func (*ServerInterfaceImpl) SetServerSummary(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetServerSummary)(w, r)+func (s *ServerInterfaceImpl) SetServerSummary(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetServerSummary)(w, r)}-func (*ServerInterfaceImpl) SetServerSummaryOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetServerSummary)(w, r)+func (s *ServerInterfaceImpl) SetServerSummaryOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetServerSummary)(w, r)}-func (*ServerInterfaceImpl) SetCustomOfflineMessage(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetCustomOfflineMessage)(w, r)+func (s *ServerInterfaceImpl) SetCustomOfflineMessage(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetCustomOfflineMessage)(w, r)}-func (*ServerInterfaceImpl) SetCustomOfflineMessageOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetCustomOfflineMessage)(w, r)+func (s *ServerInterfaceImpl) SetCustomOfflineMessageOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetCustomOfflineMessage)(w, r)}-func (*ServerInterfaceImpl) SetServerWelcomeMessage(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetServerWelcomeMessage)(w, r)+func (s *ServerInterfaceImpl) SetServerWelcomeMessage(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetServerWelcomeMessage)(w, r)}-func (*ServerInterfaceImpl) SetServerWelcomeMessageOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetServerWelcomeMessage)(w, r)+func (s *ServerInterfaceImpl) SetServerWelcomeMessageOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetServerWelcomeMessage)(w, r)}-func (*ServerInterfaceImpl) SetChatDisabled(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetChatDisabled)(w, r)+func (s *ServerInterfaceImpl) SetChatDisabled(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetChatDisabled)(w, r)}-func (*ServerInterfaceImpl) SetChatDisabledOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetChatDisabled)(w, r)+func (s *ServerInterfaceImpl) SetChatDisabledOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetChatDisabled)(w, r)}-func (*ServerInterfaceImpl) SetChatJoinMessagesEnabled(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetChatJoinMessagesEnabled)(w, r)+func (s *ServerInterfaceImpl) SetChatJoinMessagesEnabled(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetChatJoinMessagesEnabled)(w, r)}-func (*ServerInterfaceImpl) SetChatJoinMessagesEnabledOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetChatJoinMessagesEnabled)(w, r)+func (s *ServerInterfaceImpl) SetChatJoinMessagesEnabledOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetChatJoinMessagesEnabled)(w, r)}-func (*ServerInterfaceImpl) SetEnableEstablishedChatUserMode(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetEnableEstablishedChatUserMode)(w, r)+func (s *ServerInterfaceImpl) SetEnableEstablishedChatUserMode(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetEnableEstablishedChatUserMode)(w, r)}-func (*ServerInterfaceImpl) SetEnableEstablishedChatUserModeOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetEnableEstablishedChatUserMode)(w, r)+func (s *ServerInterfaceImpl) SetEnableEstablishedChatUserModeOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetEnableEstablishedChatUserMode)(w, r)}-func (*ServerInterfaceImpl) SetForbiddenUsernameList(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetForbiddenUsernameList)(w, r)+func (s *ServerInterfaceImpl) SetForbiddenUsernameList(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetForbiddenUsernameList)(w, r)}-func (*ServerInterfaceImpl) SetForbiddenUsernameListOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetForbiddenUsernameList)(w, r)+func (s *ServerInterfaceImpl) SetForbiddenUsernameListOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetForbiddenUsernameList)(w, r)}-func (*ServerInterfaceImpl) SetSuggestedUsernameList(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetSuggestedUsernameList)(w, r)+func (s *ServerInterfaceImpl) SetSuggestedUsernameList(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetSuggestedUsernameList)(w, r)}-func (*ServerInterfaceImpl) SetSuggestedUsernameListOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetSuggestedUsernameList)(w, r)+func (s *ServerInterfaceImpl) SetSuggestedUsernameListOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetSuggestedUsernameList)(w, r)}-func (*ServerInterfaceImpl) SetChatSpamProtectionEnabled(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetChatSpamProtectionEnabled)(w, r)+func (s *ServerInterfaceImpl) SetChatSpamProtectionEnabled(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetChatSpamProtectionEnabled)(w, r)}-func (*ServerInterfaceImpl) SetChatSpamProtectionEnabledOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetChatSpamProtectionEnabled)(w, r)+func (s *ServerInterfaceImpl) SetChatSpamProtectionEnabledOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetChatSpamProtectionEnabled)(w, r)}-func (*ServerInterfaceImpl) SetChatSlurFilterEnabled(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetChatSlurFilterEnabled)(w, r)+func (s *ServerInterfaceImpl) SetChatSlurFilterEnabled(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetChatSlurFilterEnabled)(w, r)}-func (*ServerInterfaceImpl) SetChatSlurFilterEnabledOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetChatSlurFilterEnabled)(w, r)+func (s *ServerInterfaceImpl) SetChatSlurFilterEnabledOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetChatSlurFilterEnabled)(w, r)}-func (*ServerInterfaceImpl) SetChatRequireAuthentication(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetChatRequireAuthentication)(w, r)+func (s *ServerInterfaceImpl) SetChatRequireAuthentication(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetChatRequireAuthentication)(w, r)}-func (*ServerInterfaceImpl) SetChatRequireAuthenticationOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetChatRequireAuthentication)(w, r)+func (s *ServerInterfaceImpl) SetChatRequireAuthenticationOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetChatRequireAuthentication)(w, r)}-func (*ServerInterfaceImpl) SetVideoCodec(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetVideoCodec)(w, r)+func (s *ServerInterfaceImpl) SetVideoCodec(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetVideoCodec)(w, r)}-func (*ServerInterfaceImpl) SetVideoCodecOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetVideoCodec)(w, r)+func (s *ServerInterfaceImpl) SetVideoCodecOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetVideoCodec)(w, r)}-func (*ServerInterfaceImpl) SetStreamLatencyLevel(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetStreamLatencyLevel)(w, r)+func (s *ServerInterfaceImpl) SetStreamLatencyLevel(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetStreamLatencyLevel)(w, r)}-func (*ServerInterfaceImpl) SetStreamLatencyLevelOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetStreamLatencyLevel)(w, r)+func (s *ServerInterfaceImpl) SetStreamLatencyLevelOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetStreamLatencyLevel)(w, r)}-func (*ServerInterfaceImpl) SetStreamOutputVariants(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetStreamOutputVariants)(w, r)+func (s *ServerInterfaceImpl) SetStreamOutputVariants(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetStreamOutputVariants)(w, r)}-func (*ServerInterfaceImpl) SetStreamOutputVariantsOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetStreamOutputVariants)(w, r)+func (s *ServerInterfaceImpl) SetStreamOutputVariantsOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetStreamOutputVariants)(w, r)}-func (*ServerInterfaceImpl) SetCustomColorVariableValues(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetCustomColorVariableValues)(w, r)+func (s *ServerInterfaceImpl) SetCustomColorVariableValues(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetCustomColorVariableValues)(w, r)}-func (*ServerInterfaceImpl) SetCustomColorVariableValuesOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetCustomColorVariableValues)(w, r)+func (s *ServerInterfaceImpl) SetCustomColorVariableValuesOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetCustomColorVariableValues)(w, r)}-func (*ServerInterfaceImpl) SetLogo(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetLogo)(w, r)+func (s *ServerInterfaceImpl) SetLogo(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetLogo)(w, r)}-func (*ServerInterfaceImpl) SetLogoOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetLogo)(w, r)+func (s *ServerInterfaceImpl) SetLogoOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetLogo)(w, r)}-func (*ServerInterfaceImpl) SetFavicon(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetFavicon)(w, r)+func (s *ServerInterfaceImpl) SetFavicon(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetFavicon)(w, r)}-func (*ServerInterfaceImpl) SetFaviconOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetFavicon)(w, r)+func (s *ServerInterfaceImpl) SetFaviconOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetFavicon)(w, r)}-func (*ServerInterfaceImpl) ResetFavicon(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.ResetFavicon)(w, r)+func (s *ServerInterfaceImpl) ResetFavicon(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.ResetFavicon)(w, r)}-func (*ServerInterfaceImpl) SetTags(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetTags)(w, r)+func (s *ServerInterfaceImpl) SetTags(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetTags)(w, r)}-func (*ServerInterfaceImpl) SetTagsOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetTags)(w, r)+func (s *ServerInterfaceImpl) SetTagsOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetTags)(w, r)}-func (*ServerInterfaceImpl) SetFfmpegPath(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetFfmpegPath)(w, r)+func (s *ServerInterfaceImpl) SetFfmpegPath(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetFfmpegPath)(w, r)}-func (*ServerInterfaceImpl) SetFfmpegPathOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetFfmpegPath)(w, r)+func (s *ServerInterfaceImpl) SetFfmpegPathOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetFfmpegPath)(w, r)}-func (*ServerInterfaceImpl) SetWebServerPort(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetWebServerPort)(w, r)+func (s *ServerInterfaceImpl) SetWebServerPort(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetWebServerPort)(w, r)}-func (*ServerInterfaceImpl) SetWebServerPortOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetWebServerPort)(w, r)+func (s *ServerInterfaceImpl) SetWebServerPortOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetWebServerPort)(w, r)}-func (*ServerInterfaceImpl) SetWebServerIP(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetWebServerIP)(w, r)+func (s *ServerInterfaceImpl) SetWebServerIP(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetWebServerIP)(w, r)}-func (*ServerInterfaceImpl) SetWebServerIPOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetWebServerIP)(w, r)+func (s *ServerInterfaceImpl) SetWebServerIPOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetWebServerIP)(w, r)}-func (*ServerInterfaceImpl) SetRTMPServerPort(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetRTMPServerPort)(w, r)+func (s *ServerInterfaceImpl) SetRTMPServerPort(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetRTMPServerPort)(w, r)}-func (*ServerInterfaceImpl) SetRTMPServerPortOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetRTMPServerPort)(w, r)+func (s *ServerInterfaceImpl) SetRTMPServerPortOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetRTMPServerPort)(w, r)}-func (*ServerInterfaceImpl) SetSocketHostOverride(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetSocketHostOverride)(w, r)+func (s *ServerInterfaceImpl) SetSocketHostOverride(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetSocketHostOverride)(w, r)}-func (*ServerInterfaceImpl) SetSocketHostOverrideOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetSocketHostOverride)(w, r)+func (s *ServerInterfaceImpl) SetSocketHostOverrideOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetSocketHostOverride)(w, r)}-func (*ServerInterfaceImpl) SetVideoServingEndpoint(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetVideoServingEndpoint)(w, r)+func (s *ServerInterfaceImpl) SetVideoServingEndpoint(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetVideoServingEndpoint)(w, r)}-func (*ServerInterfaceImpl) SetVideoServingEndpointOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetVideoServingEndpoint)(w, r)+func (s *ServerInterfaceImpl) SetVideoServingEndpointOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetVideoServingEndpoint)(w, r)}-func (*ServerInterfaceImpl) SetNSFW(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetNSFW)(w, r)+func (s *ServerInterfaceImpl) SetNSFW(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetNSFW)(w, r)}-func (*ServerInterfaceImpl) SetNSFWOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetNSFW)(w, r)+func (s *ServerInterfaceImpl) SetNSFWOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetNSFW)(w, r)}-func (*ServerInterfaceImpl) SetDirectoryEnabled(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetDirectoryEnabled)(w, r)+func (s *ServerInterfaceImpl) SetDirectoryEnabled(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetDirectoryEnabled)(w, r)}-func (*ServerInterfaceImpl) SetDirectoryEnabledOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetDirectoryEnabled)(w, r)+func (s *ServerInterfaceImpl) SetDirectoryEnabledOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetDirectoryEnabled)(w, r)}-func (*ServerInterfaceImpl) SetSocialHandles(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetSocialHandles)(w, r)+func (s *ServerInterfaceImpl) SetSocialHandles(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetSocialHandles)(w, r)}-func (*ServerInterfaceImpl) SetSocialHandlesOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetSocialHandles)(w, r)+func (s *ServerInterfaceImpl) SetSocialHandlesOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetSocialHandles)(w, r)}-func (*ServerInterfaceImpl) SetS3Configuration(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetS3Configuration)(w, r)+func (s *ServerInterfaceImpl) SetS3Configuration(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetS3Configuration)(w, r)}-func (*ServerInterfaceImpl) SetS3ConfigurationOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetS3Configuration)(w, r)+func (s *ServerInterfaceImpl) SetS3ConfigurationOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetS3Configuration)(w, r)}-func (*ServerInterfaceImpl) SetServerURL(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetServerURL)(w, r)+func (s *ServerInterfaceImpl) SetServerURL(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetServerURL)(w, r)}-func (*ServerInterfaceImpl) SetServerURLOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetServerURL)(w, r)+func (s *ServerInterfaceImpl) SetServerURLOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetServerURL)(w, r)}-func (*ServerInterfaceImpl) SetExternalActions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetExternalActions)(w, r)+func (s *ServerInterfaceImpl) SetExternalActions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetExternalActions)(w, r)}-func (*ServerInterfaceImpl) SetExternalActionsOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetExternalActions)(w, r)+func (s *ServerInterfaceImpl) SetExternalActionsOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetExternalActions)(w, r)}-func (*ServerInterfaceImpl) SetCustomStyles(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetCustomStyles)(w, r)+func (s *ServerInterfaceImpl) SetCustomStyles(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetCustomStyles)(w, r)}-func (*ServerInterfaceImpl) SetCustomStylesOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetCustomStyles)(w, r)+func (s *ServerInterfaceImpl) SetCustomStylesOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetCustomStyles)(w, r)}-func (*ServerInterfaceImpl) SetCustomJavascript(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetCustomJavascript)(w, r)+func (s *ServerInterfaceImpl) SetCustomJavascript(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetCustomJavascript)(w, r)}-func (*ServerInterfaceImpl) SetCustomJavascriptOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetCustomJavascript)(w, r)+func (s *ServerInterfaceImpl) SetCustomJavascriptOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetCustomJavascript)(w, r)}-func (*ServerInterfaceImpl) SetHideViewerCount(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetHideViewerCount)(w, r)+func (s *ServerInterfaceImpl) SetHideViewerCount(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetHideViewerCount)(w, r)}-func (*ServerInterfaceImpl) SetHideViewerCountOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetHideViewerCount)(w, r)+func (s *ServerInterfaceImpl) SetHideViewerCountOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetHideViewerCount)(w, r)}-func (*ServerInterfaceImpl) SetDisableSearchIndexing(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetDisableSearchIndexing)(w, r)+func (s *ServerInterfaceImpl) SetDisableSearchIndexing(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetDisableSearchIndexing)(w, r)}-func (*ServerInterfaceImpl) SetDisableSearchIndexingOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetDisableSearchIndexing)(w, r)+func (s *ServerInterfaceImpl) SetDisableSearchIndexingOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetDisableSearchIndexing)(w, r)}-func (*ServerInterfaceImpl) SetFederationEnabled(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetFederationEnabled)(w, r)+func (s *ServerInterfaceImpl) SetFederationEnabled(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetFederationEnabled)(w, r)}-func (*ServerInterfaceImpl) SetFederationEnabledOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetFederationEnabled)(w, r)+func (s *ServerInterfaceImpl) SetFederationEnabledOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetFederationEnabled)(w, r)}-func (*ServerInterfaceImpl) SetFederationActivityPrivate(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetFederationActivityPrivate)(w, r)+func (s *ServerInterfaceImpl) SetFederationActivityPrivate(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetFederationActivityPrivate)(w, r)}-func (*ServerInterfaceImpl) SetFederationActivityPrivateOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetFederationActivityPrivate)(w, r)+func (s *ServerInterfaceImpl) SetFederationActivityPrivateOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetFederationActivityPrivate)(w, r)}-func (*ServerInterfaceImpl) SetFederationShowEngagement(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetFederationShowEngagement)(w, r)+func (s *ServerInterfaceImpl) SetFederationShowEngagement(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetFederationShowEngagement)(w, r)}-func (*ServerInterfaceImpl) SetFederationShowEngagementOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetFederationShowEngagement)(w, r)+func (s *ServerInterfaceImpl) SetFederationShowEngagementOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetFederationShowEngagement)(w, r)}-func (*ServerInterfaceImpl) SetFederationUsername(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetFederationUsername)(w, r)+func (s *ServerInterfaceImpl) SetFederationUsername(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetFederationUsername)(w, r)}-func (*ServerInterfaceImpl) SetFederationUsernameOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetFederationUsername)(w, r)+func (s *ServerInterfaceImpl) SetFederationUsernameOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetFederationUsername)(w, r)}-func (*ServerInterfaceImpl) SetFederationGoLiveMessage(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetFederationGoLiveMessage)(w, r)+func (s *ServerInterfaceImpl) SetFederationGoLiveMessage(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetFederationGoLiveMessage)(w, r)}-func (*ServerInterfaceImpl) SetFederationGoLiveMessageOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetFederationGoLiveMessage)(w, r)+func (s *ServerInterfaceImpl) SetFederationGoLiveMessageOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetFederationGoLiveMessage)(w, r)}-func (*ServerInterfaceImpl) SetFederationBlockDomains(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetFederationBlockDomains)(w, r)+func (s *ServerInterfaceImpl) SetFederationBlockDomains(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetFederationBlockDomains)(w, r)}-func (*ServerInterfaceImpl) SetFederationBlockDomainsOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetFederationBlockDomains)(w, r)+func (s *ServerInterfaceImpl) SetFederationBlockDomainsOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetFederationBlockDomains)(w, r)}-func (*ServerInterfaceImpl) SetDiscordNotificationConfiguration(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetDiscordNotificationConfiguration)(w, r)+func (s *ServerInterfaceImpl) SetDiscordNotificationConfiguration(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetDiscordNotificationConfiguration)(w, r)}-func (*ServerInterfaceImpl) SetDiscordNotificationConfigurationOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetDiscordNotificationConfiguration)(w, r)+func (s *ServerInterfaceImpl) SetDiscordNotificationConfigurationOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetDiscordNotificationConfiguration)(w, r)}-func (*ServerInterfaceImpl) SetBrowserNotificationConfiguration(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetBrowserNotificationConfiguration)(w, r)+func (s *ServerInterfaceImpl) SetBrowserNotificationConfiguration(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetBrowserNotificationConfiguration)(w, r)}-func (*ServerInterfaceImpl) SetBrowserNotificationConfigurationOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireAdminAuth(admin.SetBrowserNotificationConfiguration)(w, r)+func (s *ServerInterfaceImpl) SetBrowserNotificationConfigurationOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(s.h.admin.SetBrowserNotificationConfiguration)(w, r)}diff --git a/webserver/handlers/customJavascript.go b/webserver/handlers/customJavascript.goindex d350de9f5f..882233fedd 100644--- a/webserver/handlers/customJavascript.go+++ b/webserver/handlers/customJavascript.go@@ -2,15 +2,10 @@ package handlersimport ("net/http"-- "github.com/owncast/owncast/persistence/configrepository")// ServeCustomJavascript will serve optional custom Javascript.-func ServeCustomJavascript(w http.ResponseWriter, r *http.Request) {+func (h *Handlers) ServeCustomJavascript(w http.ResponseWriter, r *http.Request) {w.Header().Set("Content-Type", "text/javascript; charset=utf-8")-- configRepository := configrepository.Get()- js := configRepository.GetCustomJavascript()- _, _ = w.Write([]byte(js))+ _, _ = w.Write([]byte(h.configRepository.GetCustomJavascript()))}diff --git a/webserver/handlers/emoji.go b/webserver/handlers/emoji.goindex a6e661ab50..37ae0dd0f4 100644--- a/webserver/handlers/emoji.go+++ b/webserver/handlers/emoji.go@@ -7,14 +7,14 @@ import ("strings""github.com/owncast/owncast/config"- "github.com/owncast/owncast/core/data"+ "github.com/owncast/owncast/services/datastore""github.com/owncast/owncast/webserver/router/middleware"webutils "github.com/owncast/owncast/webserver/utils")// GetCustomEmojiList returns a list of emoji via the API.func GetCustomEmojiList(w http.ResponseWriter, r *http.Request) {- emojiList := data.GetEmojiList()+ emojiList := datastore.GetEmojiList()middleware.SetCachingHeaders(w, r)if err := json.NewEncoder(w).Encode(emojiList); err != nil {diff --git a/webserver/handlers/favicon.go b/webserver/handlers/favicon.goindex f98d9256a0..b5de7bac30 100644--- a/webserver/handlers/favicon.go+++ b/webserver/handlers/favicon.go@@ -6,17 +6,16 @@ import ("path/filepath""strconv"+ log "github.com/sirupsen/logrus"+"github.com/owncast/owncast/config"- "github.com/owncast/owncast/persistence/configrepository""github.com/owncast/owncast/static""github.com/owncast/owncast/utils"- log "github.com/sirupsen/logrus")// GetFavicon will return the favicon image as a response.-func GetFavicon(w http.ResponseWriter, r *http.Request) {- configRepository := configrepository.Get()- faviconFilename := configRepository.GetFaviconPath()+func (h *Handlers) GetFavicon(w http.ResponseWriter, r *http.Request) {+ faviconFilename := h.configRepository.GetFaviconPath()if faviconFilename == "" {returnDefaultFavicon(w)returndiff --git a/webserver/handlers/followers.go b/webserver/handlers/followers.goindex d2e8c6c113..d83f9a6e15 100644--- a/webserver/handlers/followers.go+++ b/webserver/handlers/followers.go@@ -3,14 +3,12 @@ package handlersimport ("net/http"- "github.com/owncast/owncast/activitypub/persistence/followersrepository"webutils "github.com/owncast/owncast/webserver/utils")// GetFollowers will handle an API request to fetch the list of followers (non-activitypub response).-func GetFollowers(offset int, limit int, w http.ResponseWriter, r *http.Request) {- followersRepo := followersrepository.Get()- followers, total, err := followersRepo.GetFollowers(limit, offset)+func (h *Handlers) GetFollowers(offset int, limit int, w http.ResponseWriter, r *http.Request) {+ followers, total, err := h.followersRepository.GetFollowers(limit, offset)if err != nil {webutils.WriteSimpleResponse(w, false, "unable to fetch followers")returndiff --git a/webserver/handlers/handler.go b/webserver/handlers/handler.goindex 832b5ca88f..91ebd3eddd 100644--- a/webserver/handlers/handler.go+++ b/webserver/handlers/handler.go@@ -3,86 +3,93 @@ package handlersimport ("net/http"- "github.com/owncast/owncast/webserver/handlers/admin""github.com/owncast/owncast/webserver/handlers/generated""github.com/owncast/owncast/webserver/router/middleware"-- "github.com/owncast/owncast/yp")-type ServerInterfaceImpl struct{}+// ServerInterfaceImpl is the OpenAPI-generated ServerInterface+// implementation. It holds the dependency-bearing handler sets and+// delegates each generated method to either a free function in this+// package or a method on one of those sets.+//+// As more handlers migrate to needing injected services, their+// delegations here switch from `pkg.X(w, r)` to `s.h.X(w, r)` or+// `s.h.admin.X(w, r)`.+type ServerInterfaceImpl struct {+ h *Handlers+}// ensure ServerInterfaceImpl implements ServerInterface.var _ generated.ServerInterface = &ServerInterfaceImpl{}-func New() *ServerInterfaceImpl {- return &ServerInterfaceImpl{}+func New(h *Handlers) *ServerInterfaceImpl {+ return &ServerInterfaceImpl{h: h}}func (s *ServerInterfaceImpl) Handler() http.Handler {return generated.Handler(s)}-func (*ServerInterfaceImpl) GetStatus(w http.ResponseWriter, r *http.Request) {- GetStatus(w, r)+func (s *ServerInterfaceImpl) GetStatus(w http.ResponseWriter, r *http.Request) {+ s.h.GetStatus(w, r)}func (*ServerInterfaceImpl) GetCustomEmojiList(w http.ResponseWriter, r *http.Request) {GetCustomEmojiList(w, r)}-func (*ServerInterfaceImpl) GetChatMessages(w http.ResponseWriter, r *http.Request, params generated.GetChatMessagesParams) {- middleware.RequireUserAccessToken(GetChatMessages)(w, r)+func (s *ServerInterfaceImpl) GetChatMessages(w http.ResponseWriter, r *http.Request, params generated.GetChatMessagesParams) {+ s.h.middleware.RequireUserAccessToken(s.h.GetChatMessages)(w, r)}-func (*ServerInterfaceImpl) RegisterAnonymousChatUser(w http.ResponseWriter, r *http.Request, params generated.RegisterAnonymousChatUserParams) {- RegisterAnonymousChatUser(w, r)+func (s *ServerInterfaceImpl) RegisterAnonymousChatUser(w http.ResponseWriter, r *http.Request, params generated.RegisterAnonymousChatUserParams) {+ s.h.RegisterAnonymousChatUser(w, r)}-func (*ServerInterfaceImpl) RegisterAnonymousChatUserOptions(w http.ResponseWriter, r *http.Request) {- RegisterAnonymousChatUser(w, r)+func (s *ServerInterfaceImpl) RegisterAnonymousChatUserOptions(w http.ResponseWriter, r *http.Request) {+ s.h.RegisterAnonymousChatUser(w, r)}-func (*ServerInterfaceImpl) UpdateMessageVisibility(w http.ResponseWriter, r *http.Request, params generated.UpdateMessageVisibilityParams) {- middleware.RequireUserModerationScopeAccesstoken(admin.UpdateMessageVisibility)(w, r)+func (s *ServerInterfaceImpl) UpdateMessageVisibility(w http.ResponseWriter, r *http.Request, params generated.UpdateMessageVisibilityParams) {+ s.h.middleware.RequireUserModerationScopeAccesstoken(s.h.admin.UpdateMessageVisibility)(w, r)}-func (*ServerInterfaceImpl) UpdateUserEnabled(w http.ResponseWriter, r *http.Request, params generated.UpdateUserEnabledParams) {- middleware.RequireUserModerationScopeAccesstoken(admin.UpdateUserEnabled)(w, r)+func (s *ServerInterfaceImpl) UpdateUserEnabled(w http.ResponseWriter, r *http.Request, params generated.UpdateUserEnabledParams) {+ s.h.middleware.RequireUserModerationScopeAccesstoken(s.h.admin.UpdateUserEnabled)(w, r)}-func (*ServerInterfaceImpl) GetWebConfig(w http.ResponseWriter, r *http.Request) {- GetWebConfig(w, r)+func (s *ServerInterfaceImpl) GetWebConfig(w http.ResponseWriter, r *http.Request) {+ s.h.GetWebConfig(w, r)}-func (*ServerInterfaceImpl) GetYPResponse(w http.ResponseWriter, r *http.Request) {- yp.GetYPResponse(w, r)+func (s *ServerInterfaceImpl) GetYPResponse(w http.ResponseWriter, r *http.Request) {+ s.h.yp.GetYPResponse(w, r)}func (*ServerInterfaceImpl) GetAllSocialPlatforms(w http.ResponseWriter, r *http.Request) {GetAllSocialPlatforms(w, r)}-func (*ServerInterfaceImpl) GetVideoStreamOutputVariants(w http.ResponseWriter, r *http.Request) {- GetVideoStreamOutputVariants(w, r)+func (s *ServerInterfaceImpl) GetVideoStreamOutputVariants(w http.ResponseWriter, r *http.Request) {+ s.h.GetVideoStreamOutputVariants(w, r)}-func (*ServerInterfaceImpl) Ping(w http.ResponseWriter, r *http.Request) {- Ping(w, r)+func (s *ServerInterfaceImpl) Ping(w http.ResponseWriter, r *http.Request) {+ s.h.Ping(w, r)}-func (*ServerInterfaceImpl) RemoteFollow(w http.ResponseWriter, r *http.Request) {- RemoteFollow(w, r)+func (s *ServerInterfaceImpl) RemoteFollow(w http.ResponseWriter, r *http.Request) {+ s.h.RemoteFollow(w, r)}-func (*ServerInterfaceImpl) GetFollowers(w http.ResponseWriter, r *http.Request, params generated.GetFollowersParams) {- middleware.HandlePagination(GetFollowers)(w, r)+func (s *ServerInterfaceImpl) GetFollowers(w http.ResponseWriter, r *http.Request, params generated.GetFollowersParams) {+ middleware.HandlePagination(s.h.GetFollowers)(w, r)}-func (*ServerInterfaceImpl) ReportPlaybackMetrics(w http.ResponseWriter, r *http.Request) {- ReportPlaybackMetrics(w, r)+func (s *ServerInterfaceImpl) ReportPlaybackMetrics(w http.ResponseWriter, r *http.Request) {+ s.h.ReportPlaybackMetrics(w, r)}-func (*ServerInterfaceImpl) RegisterForLiveNotifications(w http.ResponseWriter, r *http.Request, params generated.RegisterForLiveNotificationsParams) {- middleware.RequireUserAccessToken(RegisterForLiveNotifications)(w, r)+func (s *ServerInterfaceImpl) RegisterForLiveNotifications(w http.ResponseWriter, r *http.Request, params generated.RegisterForLiveNotificationsParams) {+ s.h.middleware.RequireUserAccessToken(s.h.RegisterForLiveNotifications)(w, r)}diff --git a/webserver/handlers/handlers.go b/webserver/handlers/handlers.gonew file mode 100644index 0000000000..f580774c4c--- /dev/null+++ b/webserver/handlers/handlers.go@@ -0,0 +1,124 @@+package handlers++import (+ "net/http"+ "sync"++ "github.com/jellydator/ttlcache/v3"++ "github.com/owncast/owncast/config"+ "github.com/owncast/owncast/metrics"+ "github.com/owncast/owncast/persistence/chatmessagerepository"+ "github.com/owncast/owncast/persistence/configrepository"+ "github.com/owncast/owncast/persistence/notificationsrepository"+ "github.com/owncast/owncast/persistence/userrepository"+ "github.com/owncast/owncast/services/activitypub"+ "github.com/owncast/owncast/services/activitypub/apmodels"+ "github.com/owncast/owncast/services/activitypub/persistence/followersrepository"+ "github.com/owncast/owncast/services/cache"+ "github.com/owncast/owncast/services/chat"+ "github.com/owncast/owncast/services/stream"+ "github.com/owncast/owncast/webserver/handlers/admin"+ "github.com/owncast/owncast/webserver/handlers/auth/fediverse"+ "github.com/owncast/owncast/webserver/handlers/auth/indieauth"+ "github.com/owncast/owncast/webserver/handlers/moderation"+ "github.com/owncast/owncast/webserver/router/middleware"+ "github.com/owncast/owncast/yp"+)++// Handlers carries the dependencies of HTTP handlers that need injected+// services. Construct one in main() with NewHandlers and pass it to the+// router; methods on *Handlers are registered as routes.+//+// Handlers that don't yet need dependencies remain free functions in this+// package; they migrate to methods as the services they depend on move to+// services/<domain>/ and stop being callable via package-level singletons.+type Handlers struct {+ cache *cache.Container+ stream *stream.Service+ chat *chat.Service+ admin *admin.Admin+ activitypub *activitypub.Service+ fediverse *fediverse.Handler+ indieauth *indieauth.Handler+ moderation *moderation.Handler+ middleware *middleware.Middleware+ yp *yp.YP+ metrics *metrics.Service+ configRepository configrepository.ConfigRepository+ followersRepository followersrepository.FollowersRepository+ chatMessageRepository chatmessagerepository.ChatMessageRepository+ userRepository userrepository.UserRepository+ notificationsRepository notificationsrepository.NotificationsRepository+ apBuilder *apmodels.Builder+ cfg *config.Config++ // previewThumbCache caches thumbnail/preview bytes for a short window+ // so frequent polling from chat clients doesn't re-read the file+ // every request.+ previewThumbCache *ttlcache.Cache[string, []byte]++ // hasWarnedSVGLogo gates the one-time warning logged when an+ // external site requests an SVG logo via /logo/external.+ hasWarnedSVGLogoLock sync.Mutex+ hasWarnedSVGLogo bool+}++// Deps lists every service a *Handlers consumes. New deps appear here as+// more handlers migrate.+type Deps struct {+ Cache *cache.Container+ Stream *stream.Service+ Chat *chat.Service+ Admin *admin.Admin+ Activitypub *activitypub.Service+ Fediverse *fediverse.Handler+ IndieAuth *indieauth.Handler+ Moderation *moderation.Handler+ Middleware *middleware.Middleware+ YP *yp.YP+ Metrics *metrics.Service+ ConfigRepository configrepository.ConfigRepository+ FollowersRepository followersrepository.FollowersRepository+ ChatMessageRepository chatmessagerepository.ChatMessageRepository+ UserRepository userrepository.UserRepository+ NotificationsRepository notificationsrepository.NotificationsRepository+ APBuilder *apmodels.Builder+ Config *config.Config+}++// HandleWebsocketConnection routes the /ws websocket upgrade to the+// chat service. Lives here so the router can bind a method on+// *Handlers instead of reaching into chat directly.+func (h *Handlers) HandleWebsocketConnection(w http.ResponseWriter, r *http.Request) {+ h.chat.HandleWebsocketConnection(w, r)+}++// NewHandlers constructs the dependency-bearing handler set.+func NewHandlers(deps Deps) *Handlers {+ return &Handlers{+ cache: deps.Cache,+ stream: deps.Stream,+ chat: deps.Chat,+ admin: deps.Admin,+ activitypub: deps.Activitypub,+ fediverse: deps.Fediverse,+ indieauth: deps.IndieAuth,+ moderation: deps.Moderation,+ middleware: deps.Middleware,+ yp: deps.YP,+ metrics: deps.Metrics,+ configRepository: deps.ConfigRepository,+ followersRepository: deps.FollowersRepository,+ chatMessageRepository: deps.ChatMessageRepository,+ userRepository: deps.UserRepository,+ notificationsRepository: deps.NotificationsRepository,+ apBuilder: deps.APBuilder,+ cfg: deps.Config,+ previewThumbCache: ttlcache.New(+ ttlcache.WithTTL[string, []byte](15),+ ttlcache.WithCapacity[string, []byte](1),+ ttlcache.WithDisableTouchOnHit[string, []byte](),+ ),+ }+}diff --git a/webserver/handlers/handlers_test.go b/webserver/handlers/handlers_test.goindex b36cd6867d..83d1eceb85 100644--- a/webserver/handlers/handlers_test.go+++ b/webserver/handlers/handlers_test.go@@ -9,8 +9,16 @@ import ("path/filepath""testing"- "github.com/owncast/owncast/core/data""github.com/owncast/owncast/persistence/configrepository"+ "github.com/owncast/owncast/services/datastore"+)++// testHandlers is the *Handlers used by tests in this package, holding+// only the configRepository handle. Expand if other handler tests land+// that need additional deps.+var (+ testHandlers *Handlers+ testDatastore *datastore.Datastore)func TestMain(m *testing.M) {@@ -20,9 +28,13 @@ func TestMain(m *testing.M) {}dbFile.Close()- if err := data.SetupPersistence(dbFile.Name()); err != nil {+ ds, err := datastore.SetupPersistence(dbFile.Name(), os.TempDir())+ if err != nil {panic(err)}+ testDatastore = ds++ testHandlers = &Handlers{configRepository: configrepository.New(testDatastore)}code := m.Run()os.Remove(dbFile.Name())@@ -45,13 +57,13 @@ func makeBase64DataURL(contentType string, data []byte) string {func TestGetFaviconDefault(t *testing.T) {// With no custom favicon set, should return the default.- configRepository := configrepository.Get()+ configRepository := configrepository.New(testDatastore)_ = configRepository.SetFaviconPath("")req := httptest.NewRequest(http.MethodGet, "/favicon.ico", nil)w := httptest.NewRecorder()- GetFavicon(w, req)+ testHandlers.GetFavicon(w, req)resp := w.Result()if resp.StatusCode != http.StatusOK {@@ -73,7 +85,7 @@ func TestGetFaviconCustomPNG(t *testing.T) {t.Fatal(err)}- configRepository := configrepository.Get()+ configRepository := configrepository.New(testDatastore)if err := configRepository.SetFaviconPath("favicon.png"); err != nil {t.Fatal(err)}@@ -82,7 +94,7 @@ func TestGetFaviconCustomPNG(t *testing.T) {req := httptest.NewRequest(http.MethodGet, "/favicon.ico", nil)w := httptest.NewRecorder()- GetFavicon(w, req)+ testHandlers.GetFavicon(w, req)resp := w.Result()if resp.StatusCode != http.StatusOK {@@ -105,7 +117,7 @@ func TestGetFaviconCustomICO(t *testing.T) {t.Fatal(err)}- configRepository := configrepository.Get()+ configRepository := configrepository.New(testDatastore)if err := configRepository.SetFaviconPath("favicon.ico"); err != nil {t.Fatal(err)}@@ -114,7 +126,7 @@ func TestGetFaviconCustomICO(t *testing.T) {req := httptest.NewRequest(http.MethodGet, "/favicon.ico", nil)w := httptest.NewRecorder()- GetFavicon(w, req)+ testHandlers.GetFavicon(w, req)resp := w.Result()if resp.StatusCode != http.StatusOK {@@ -127,7 +139,7 @@ func TestGetFaviconCustomICO(t *testing.T) {func TestGetFaviconMissingFileFallsBackToDefault(t *testing.T) {// Point config at a file that doesn't exist; should fall back to default.- configRepository := configrepository.Get()+ configRepository := configrepository.New(testDatastore)if err := configRepository.SetFaviconPath("favicon-nonexistent.png"); err != nil {t.Fatal(err)}@@ -136,7 +148,7 @@ func TestGetFaviconMissingFileFallsBackToDefault(t *testing.T) {req := httptest.NewRequest(http.MethodGet, "/favicon.ico", nil)w := httptest.NewRecorder()- GetFavicon(w, req)+ testHandlers.GetFavicon(w, req)resp := w.Result()if resp.StatusCode != http.StatusOK {diff --git a/webserver/handlers/hls.go b/webserver/handlers/hls.goindex 73ff20f7b3..815480d3a4 100644--- a/webserver/handlers/hls.go+++ b/webserver/handlers/hls.go@@ -8,15 +8,13 @@ import ("strings""github.com/owncast/owncast/config"- "github.com/owncast/owncast/core""github.com/owncast/owncast/models"- "github.com/owncast/owncast/persistence/configrepository""github.com/owncast/owncast/utils""github.com/owncast/owncast/webserver/router/middleware")// HandleHLSRequest will manage all requests to HLS content.-func HandleHLSRequest(w http.ResponseWriter, r *http.Request) {+func (h *Handlers) HandleHLSRequest(w http.ResponseWriter, r *http.Request) {// Sanity check to limit requests to HLS file types.if filepath.Ext(r.URL.Path) != ".m3u8" && filepath.Ext(r.URL.Path) != ".ts" {w.WriteHeader(http.StatusNotFound)@@ -27,10 +25,25 @@ func HandleHLSRequest(w http.ResponseWriter, r *http.Request) {relativePath := strings.Replace(requestedPath, "/hls/", "", 1)fullPath := filepath.Join(config.HLSStoragePath, relativePath)+ // Defense-in-depth path-traversal guard. http.ServeFile already rejects+ // URL.Path entries containing "..", but we resolve both paths to+ // absolute form and confirm the request stays inside HLSStoragePath+ // rather than relying on that stdlib detail. HLS asset names never+ // contain ".." in practice.+ absBase, err := filepath.Abs(config.HLSStoragePath)+ if err != nil {+ w.WriteHeader(http.StatusInternalServerError)+ return+ }+ absFull, err := filepath.Abs(fullPath)+ if err != nil || (absFull != absBase && !strings.HasPrefix(absFull, absBase+string(filepath.Separator))) {+ w.WriteHeader(http.StatusNotFound)+ return+ }+// If using external storage then only allow requests for the// master playlist at stream.m3u8, no variants or segments.- configRepository := configrepository.Get()- if configRepository.GetS3Config().Enabled && relativePath != "stream.m3u8" {+ if h.configRepository.GetS3Config().Enabled && relativePath != "stream.m3u8" {w.WriteHeader(http.StatusNotFound)return}@@ -45,17 +58,12 @@ func HandleHLSRequest(w http.ResponseWriter, r *http.Request) {// Use this as an opportunity to mark this viewer as active.viewer := models.GenerateViewerFromRequest(r)- core.SetViewerActive(&viewer)+ h.stream.SetViewerActive(&viewer)} else {cacheTime := utils.GetCacheDurationSecondsForPath(relativePath)w.Header().Set("Cache-Control", "public, max-age="+strconv.Itoa(cacheTime))}middleware.EnableCors(w)- // fullPath is built from r.URL.Path, which is normalized and cleaned by the- // http.ServeMux that routes to this handler (stripping ".." traversal- // segments), and is further constrained to .m3u8/.ts files under- // config.HLSStoragePath via the extension check above and filepath.Join.- //nolint:gosec // G703: requested path is normalized and confined to HLSStoragePath.- http.ServeFile(w, r, fullPath)+ http.ServeFile(w, r, fullPath) //nolint:gosec // G703: fullPath was verified to be inside HLSStoragePath above}diff --git a/webserver/handlers/images.go b/webserver/handlers/images.goindex ecf721df8b..bcb2afd0eb 100644--- a/webserver/handlers/images.go+++ b/webserver/handlers/images.go@@ -5,48 +5,39 @@ import ("path/filepath""time"- "github.com/jellydator/ttlcache/v3"- "github.com/owncast/owncast/config""github.com/owncast/owncast/utils")const (contentTypeJPEG = "image/jpeg"contentTypeGIF = "image/gif"-)--// thumbnailFilename is the filename of the generated stream thumbnail image.-const thumbnailFilename = "thumbnail.jpg"-var previewThumbCache = ttlcache.New(- ttlcache.WithTTL[string, []byte](15),- ttlcache.WithCapacity[string, []byte](1),- ttlcache.WithDisableTouchOnHit[string, []byte](),+ thumbnailFilename = "thumbnail.jpg")// GetThumbnail will return the thumbnail image as a response.-func GetThumbnail(w http.ResponseWriter, r *http.Request) {+func (h *Handlers) GetThumbnail(w http.ResponseWriter, r *http.Request) {imageFilename := thumbnailFilename- imagePath := filepath.Join(config.TempDir, imageFilename)+ imagePath := filepath.Join(h.cfg.TempDir, imageFilename)httpCacheTime := utils.GetCacheDurationSecondsForPath(imagePath)inMemoryCacheTime := time.Duration(15) * time.Secondvar imageBytes []bytevar err error- if previewThumbCache.Get(imagePath) != nil {- ci := previewThumbCache.Get(imagePath)+ if h.previewThumbCache.Get(imagePath) != nil {+ ci := h.previewThumbCache.Get(imagePath)imageBytes = ci.Value()} else if utils.DoesFileExists(imagePath) {imageBytes, err = getImage(imagePath)- previewThumbCache.Set(imagePath, imageBytes, inMemoryCacheTime)+ h.previewThumbCache.Set(imagePath, imageBytes, inMemoryCacheTime)} else {- GetLogo(w, r)+ h.GetLogo(w, r)return}if err != nil {- GetLogo(w, r)+ h.GetLogo(w, r)return}@@ -54,28 +45,28 @@ func GetThumbnail(w http.ResponseWriter, r *http.Request) {}// GetPreview will return the preview gif as a response.-func GetPreview(w http.ResponseWriter, r *http.Request) {+func (h *Handlers) GetPreview(w http.ResponseWriter, r *http.Request) {imageFilename := "preview.gif"- imagePath := filepath.Join(config.TempDir, imageFilename)+ imagePath := filepath.Join(h.cfg.TempDir, imageFilename)httpCacheTime := utils.GetCacheDurationSecondsForPath(imagePath)inMemoryCacheTime := time.Duration(15) * time.Secondvar imageBytes []bytevar err error- if previewThumbCache.Get(imagePath) != nil {- ci := previewThumbCache.Get(imagePath)+ if h.previewThumbCache.Get(imagePath) != nil {+ ci := h.previewThumbCache.Get(imagePath)imageBytes = ci.Value()} else if utils.DoesFileExists(imagePath) {imageBytes, err = getImage(imagePath)- previewThumbCache.Set(imagePath, imageBytes, inMemoryCacheTime)+ h.previewThumbCache.Set(imagePath, imageBytes, inMemoryCacheTime)} else {- GetLogo(w, r)+ h.GetLogo(w, r)return}if err != nil {- GetLogo(w, r)+ h.GetLogo(w, r)return}diff --git a/webserver/handlers/index.go b/webserver/handlers/index.goindex 503360292e..53c399efc1 100644--- a/webserver/handlers/index.go+++ b/webserver/handlers/index.go@@ -11,21 +11,17 @@ import ("strings""time"+ log "github.com/sirupsen/logrus"+"github.com/owncast/owncast/config"- "github.com/owncast/owncast/core"- "github.com/owncast/owncast/core/cache""github.com/owncast/owncast/models"- "github.com/owncast/owncast/persistence/configrepository""github.com/owncast/owncast/static""github.com/owncast/owncast/utils""github.com/owncast/owncast/webserver/router/middleware"- log "github.com/sirupsen/logrus")-var gc = cache.GetGlobalCache()-// IndexHandler handles the default index route.-func IndexHandler(w http.ResponseWriter, r *http.Request) {+func (h *Handlers) IndexHandler(w http.ResponseWriter, r *http.Request) {middleware.EnableCors(w)isIndexRequest := r.URL.Path == "/" || filepath.Base(r.URL.Path) == "index.html" || filepath.Base(r.URL.Path) == ""@@ -38,7 +34,7 @@ func IndexHandler(w http.ResponseWriter, r *http.Request) {// For search engine bots and social scrapers return a special// server-rendered page.if utils.IsUserAgentABot(r.UserAgent()) && isIndexRequest {- handleScraperMetadataPage(w, r)+ h.handleScraperMetadataPage(w, r)return}@@ -51,14 +47,14 @@ func IndexHandler(w http.ResponseWriter, r *http.Request) {middleware.SetHeaders(w, fmt.Sprintf("nonce-%s", nonceRandom))if isIndexRequest {- renderIndexHtml(w, nonceRandom)+ h.renderIndexHtml(w, nonceRandom)return}serveWeb(w, r)}-func renderIndexHtml(w http.ResponseWriter, nonce string) {+func (h *Handlers) renderIndexHtml(w http.ResponseWriter, nonce string) {type serverSideContent struct {Name stringSummary string@@ -73,21 +69,21 @@ func renderIndexHtml(w http.ResponseWriter, nonce string) {Nonce string}- status := getStatusResponse()+ status := h.getStatusResponse()sb, err := json.Marshal(status)if err != nil {http.Error(w, err.Error(), http.StatusInternalServerError)return}- config := getConfigResponse()+ config := h.getConfigResponse()cb, err := json.Marshal(config)if err != nil {http.Error(w, err.Error(), http.StatusInternalServerError)return}- configRepository := configrepository.Get()+ configRepository := h.configRepositorycontent := serverSideContent{Name: configRepository.GetServerName(),Summary: configRepository.GetServerSummary(),@@ -134,12 +130,12 @@ type MetadataPage struct {// Return a basic HTML page with server-rendered metadata from the config// to give to Opengraph clients and web scrapers (bots, web crawlers, etc).-func handleScraperMetadataPage(w http.ResponseWriter, r *http.Request) {+func (h *Handlers) handleScraperMetadataPage(w http.ResponseWriter, r *http.Request) {cacheKey := "bot-scraper-html"cacheHtmlExpiration := time.Duration(60) * time.Second- c := gc.GetOrCreateCache(cacheKey, cacheHtmlExpiration)+ c := h.cache.GetOrCreate(cacheKey, cacheHtmlExpiration)- cachedHtml := c.GetValueForKey(cacheKey)+ cachedHtml := c.Get(cacheKey)if cachedHtml != nil {w.Header().Set("Content-Type", "text/html")_, _ = w.Write(cachedHtml)@@ -154,7 +150,7 @@ func handleScraperMetadataPage(w http.ResponseWriter, r *http.Request) {}scheme := "http"- configRepository := configrepository.Get()+ configRepository := h.configRepositoryif siteURL := configRepository.GetServerURL(); siteURL != "" {if parsed, err := url.Parse(siteURL); err == nil && parsed.Scheme != "" {scheme = parsed.Scheme@@ -170,12 +166,12 @@ func handleScraperMetadataPage(w http.ResponseWriter, r *http.Request) {log.Errorln(err)}- status := core.GetStatus()+ status := h.stream.GetStatus()// If the thumbnail does not exist or we're offline then just use the logo imagevar thumbnailURL stringif status.Online && utils.DoesFileExists(filepath.Join(config.DataDirectory, "tmp", thumbnailFilename)) {- thumbnail, err := url.Parse(fmt.Sprintf("%s://%s%s", scheme, r.Host, "/thumbnail.jpg"))+ thumbnail, err := url.Parse(fmt.Sprintf("%s://%s/%s", scheme, r.Host, thumbnailFilename))if err != nil {log.Errorln(err)thumbnailURL = imageURL.String()diff --git a/webserver/handlers/integrations.go b/webserver/handlers/integrations.goindex be587ddfc8..11ef7f6c40 100644--- a/webserver/handlers/integrations.go+++ b/webserver/handlers/integrations.go@@ -3,126 +3,124 @@ package handlersimport ("net/http"- "github.com/owncast/owncast/models"- "github.com/owncast/owncast/webserver/handlers/admin"- "github.com/owncast/owncast/webserver/handlers/moderation"- "github.com/owncast/owncast/webserver/router/middleware""github.com/prometheus/client_golang/prometheus/promhttp"++ "github.com/owncast/owncast/models")-func (*ServerInterfaceImpl) SendSystemMessage(w http.ResponseWriter, r *http.Request) {- middleware.RequireExternalAPIAccessToken(models.ScopeCanSendSystemMessages, admin.SendSystemMessage)(w, r)+func (s *ServerInterfaceImpl) SendSystemMessage(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireExternalAPIAccessToken(models.ScopeCanSendSystemMessages, s.h.admin.SendSystemMessage)(w, r)}-func (*ServerInterfaceImpl) SendSystemMessageOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireExternalAPIAccessToken(models.ScopeCanSendSystemMessages, admin.SendSystemMessage)(w, r)+func (s *ServerInterfaceImpl) SendSystemMessageOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireExternalAPIAccessToken(models.ScopeCanSendSystemMessages, s.h.admin.SendSystemMessage)(w, r)}-func (*ServerInterfaceImpl) SendSystemMessageToConnectedClient(w http.ResponseWriter, r *http.Request, clientId int) {- middleware.RequireExternalAPIAccessToken(models.ScopeCanSendSystemMessages, admin.SendSystemMessageToConnectedClient)(w, r)+func (s *ServerInterfaceImpl) SendSystemMessageToConnectedClient(w http.ResponseWriter, r *http.Request, clientId int) {+ s.h.middleware.RequireExternalAPIAccessToken(models.ScopeCanSendSystemMessages, s.h.admin.SendSystemMessageToConnectedClient)(w, r)}-func (*ServerInterfaceImpl) SendSystemMessageToConnectedClientOptions(w http.ResponseWriter, r *http.Request, clientId int) {- middleware.RequireExternalAPIAccessToken(models.ScopeCanSendSystemMessages, admin.SendSystemMessageToConnectedClient)(w, r)+func (s *ServerInterfaceImpl) SendSystemMessageToConnectedClientOptions(w http.ResponseWriter, r *http.Request, clientId int) {+ s.h.middleware.RequireExternalAPIAccessToken(models.ScopeCanSendSystemMessages, s.h.admin.SendSystemMessageToConnectedClient)(w, r)}// Deprecated.-func (*ServerInterfaceImpl) SendUserMessage(w http.ResponseWriter, r *http.Request) {- middleware.RequireExternalAPIAccessToken(models.ScopeCanSendChatMessages, admin.SendUserMessage)(w, r)+func (s *ServerInterfaceImpl) SendUserMessage(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireExternalAPIAccessToken(models.ScopeCanSendChatMessages, s.h.admin.SendUserMessage)(w, r)}// Deprecated.-func (*ServerInterfaceImpl) SendUserMessageOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireExternalAPIAccessToken(models.ScopeCanSendChatMessages, admin.SendUserMessage)(w, r)+func (s *ServerInterfaceImpl) SendUserMessageOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireExternalAPIAccessToken(models.ScopeCanSendChatMessages, s.h.admin.SendUserMessage)(w, r)}-func (*ServerInterfaceImpl) SendIntegrationChatMessage(w http.ResponseWriter, r *http.Request) {- middleware.RequireExternalAPIAccessToken(models.ScopeCanSendChatMessages, admin.SendIntegrationChatMessage)(w, r)+func (s *ServerInterfaceImpl) SendIntegrationChatMessage(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireExternalAPIAccessToken(models.ScopeCanSendChatMessages, s.h.admin.SendIntegrationChatMessage)(w, r)}-func (*ServerInterfaceImpl) SendIntegrationChatMessageOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireExternalAPIAccessToken(models.ScopeCanSendChatMessages, admin.SendIntegrationChatMessage)(w, r)+func (s *ServerInterfaceImpl) SendIntegrationChatMessageOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireExternalAPIAccessToken(models.ScopeCanSendChatMessages, s.h.admin.SendIntegrationChatMessage)(w, r)}-func (*ServerInterfaceImpl) SendChatAction(w http.ResponseWriter, r *http.Request) {- middleware.RequireExternalAPIAccessToken(models.ScopeCanSendSystemMessages, admin.SendChatAction)(w, r)+func (s *ServerInterfaceImpl) SendChatAction(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireExternalAPIAccessToken(models.ScopeCanSendSystemMessages, s.h.admin.SendChatAction)(w, r)}-func (*ServerInterfaceImpl) SendChatActionOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireExternalAPIAccessToken(models.ScopeCanSendSystemMessages, admin.SendChatAction)(w, r)+func (s *ServerInterfaceImpl) SendChatActionOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireExternalAPIAccessToken(models.ScopeCanSendSystemMessages, s.h.admin.SendChatAction)(w, r)}-func (*ServerInterfaceImpl) ExternalUpdateMessageVisibility(w http.ResponseWriter, r *http.Request) {- middleware.RequireExternalAPIAccessToken(models.ScopeHasAdminAccess, admin.ExternalUpdateMessageVisibility)(w, r)+func (s *ServerInterfaceImpl) ExternalUpdateMessageVisibility(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireExternalAPIAccessToken(models.ScopeHasAdminAccess, s.h.admin.ExternalUpdateMessageVisibility)(w, r)}-func (*ServerInterfaceImpl) ExternalUpdateMessageVisibilityOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireExternalAPIAccessToken(models.ScopeHasAdminAccess, admin.ExternalUpdateMessageVisibility)(w, r)+func (s *ServerInterfaceImpl) ExternalUpdateMessageVisibilityOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireExternalAPIAccessToken(models.ScopeHasAdminAccess, s.h.admin.ExternalUpdateMessageVisibility)(w, r)}-func (*ServerInterfaceImpl) ExternalSetStreamTitle(w http.ResponseWriter, r *http.Request) {- middleware.RequireExternalAPIAccessToken(models.ScopeHasAdminAccess, admin.ExternalSetStreamTitle)(w, r)+func (s *ServerInterfaceImpl) ExternalSetStreamTitle(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireExternalAPIAccessToken(models.ScopeHasAdminAccess, s.h.admin.ExternalSetStreamTitle)(w, r)}-func (*ServerInterfaceImpl) ExternalSetStreamTitleOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireExternalAPIAccessToken(models.ScopeHasAdminAccess, admin.ExternalSetStreamTitle)(w, r)+func (s *ServerInterfaceImpl) ExternalSetStreamTitleOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireExternalAPIAccessToken(models.ScopeHasAdminAccess, s.h.admin.ExternalSetStreamTitle)(w, r)}-func (*ServerInterfaceImpl) ExternalGetUserDetails(w http.ResponseWriter, r *http.Request, userId string) {- middleware.RequireExternalAPIAccessToken(models.ScopeHasAdminAccess, moderation.ExternalGetUserDetails)(w, r)+func (s *ServerInterfaceImpl) ExternalGetUserDetails(w http.ResponseWriter, r *http.Request, userId string) {+ s.h.middleware.RequireExternalAPIAccessToken(models.ScopeHasAdminAccess, s.h.moderation.ExternalGetUserDetails)(w, r)}-func (*ServerInterfaceImpl) ExternalGetChatMessages(w http.ResponseWriter, r *http.Request) {- middleware.RequireExternalAPIAccessToken(models.ScopeHasAdminAccess, ExternalGetChatMessages)(w, r)+func (s *ServerInterfaceImpl) ExternalGetChatMessages(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireExternalAPIAccessToken(models.ScopeHasAdminAccess, s.h.ExternalGetChatMessages)(w, r)}-func (*ServerInterfaceImpl) ExternalGetChatMessagesOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireExternalAPIAccessToken(models.ScopeHasAdminAccess, ExternalGetChatMessages)(w, r)+func (s *ServerInterfaceImpl) ExternalGetChatMessagesOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireExternalAPIAccessToken(models.ScopeHasAdminAccess, s.h.ExternalGetChatMessages)(w, r)}-func (*ServerInterfaceImpl) ExternalGetConnectedChatClients(w http.ResponseWriter, r *http.Request) {- middleware.RequireExternalAPIAccessToken(models.ScopeHasAdminAccess, admin.ExternalGetConnectedChatClients)(w, r)+func (s *ServerInterfaceImpl) ExternalGetConnectedChatClients(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireExternalAPIAccessToken(models.ScopeHasAdminAccess, s.h.admin.ExternalGetConnectedChatClients)(w, r)}-func (*ServerInterfaceImpl) ExternalGetConnectedChatClientsOptions(w http.ResponseWriter, r *http.Request) {- middleware.RequireExternalAPIAccessToken(models.ScopeHasAdminAccess, admin.ExternalGetConnectedChatClients)(w, r)+func (s *ServerInterfaceImpl) ExternalGetConnectedChatClientsOptions(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireExternalAPIAccessToken(models.ScopeHasAdminAccess, s.h.admin.ExternalGetConnectedChatClients)(w, r)}-func (*ServerInterfaceImpl) ExternalGetStatus(w http.ResponseWriter, r *http.Request) {- middleware.RequireExternalAPIAccessToken(models.ScopeHasAdminAccess, admin.ExternalGetStatus)(w, r)+func (s *ServerInterfaceImpl) ExternalGetStatus(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireExternalAPIAccessToken(models.ScopeHasAdminAccess, s.h.admin.ExternalGetStatus)(w, r)}-func (*ServerInterfaceImpl) GetPrometheusAPI(w http.ResponseWriter, r *http.Request) {+func (s *ServerInterfaceImpl) GetPrometheusAPI(w http.ResponseWriter, r *http.Request) {// might need to bring this out of the codegen- middleware.RequireAdminAuth(func(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(func(w http.ResponseWriter, r *http.Request) {promhttp.Handler().ServeHTTP(w, r)})(w, r)}-func (*ServerInterfaceImpl) PostPrometheusAPI(w http.ResponseWriter, r *http.Request) {+func (s *ServerInterfaceImpl) PostPrometheusAPI(w http.ResponseWriter, r *http.Request) {// might need to bring this out of the codegen- middleware.RequireAdminAuth(func(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(func(w http.ResponseWriter, r *http.Request) {promhttp.Handler().ServeHTTP(w, r)})(w, r)}-func (*ServerInterfaceImpl) PutPrometheusAPI(w http.ResponseWriter, r *http.Request) {+func (s *ServerInterfaceImpl) PutPrometheusAPI(w http.ResponseWriter, r *http.Request) {// might need to bring this out of the codegen- middleware.RequireAdminAuth(func(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(func(w http.ResponseWriter, r *http.Request) {promhttp.Handler().ServeHTTP(w, r)})(w, r)}-func (*ServerInterfaceImpl) DeletePrometheusAPI(w http.ResponseWriter, r *http.Request) {+func (s *ServerInterfaceImpl) DeletePrometheusAPI(w http.ResponseWriter, r *http.Request) {// might need to bring this out of the codegen- middleware.RequireAdminAuth(func(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(func(w http.ResponseWriter, r *http.Request) {promhttp.Handler().ServeHTTP(w, r)})(w, r)}-func (*ServerInterfaceImpl) OptionsPrometheusAPI(w http.ResponseWriter, r *http.Request) {+func (s *ServerInterfaceImpl) OptionsPrometheusAPI(w http.ResponseWriter, r *http.Request) {// might need to bring this out of the codegen- middleware.RequireAdminAuth(func(w http.ResponseWriter, r *http.Request) {+ s.h.middleware.RequireAdminAuth(func(w http.ResponseWriter, r *http.Request) {promhttp.Handler().ServeHTTP(w, r)})(w, r)}diff --git a/webserver/handlers/logo.go b/webserver/handlers/logo.goindex 01c0a800b5..f96238ef6f 100644--- a/webserver/handlers/logo.go+++ b/webserver/handlers/logo.go@@ -6,19 +6,16 @@ import ("path/filepath""strconv"+ log "github.com/sirupsen/logrus"+"github.com/owncast/owncast/config"- "github.com/owncast/owncast/persistence/configrepository""github.com/owncast/owncast/static""github.com/owncast/owncast/utils"- log "github.com/sirupsen/logrus")-var _hasWarnedSVGLogo = false-// GetLogo will return the logo image as a response.-func GetLogo(w http.ResponseWriter, r *http.Request) {- configRepository := configrepository.Get()- imageFilename := configRepository.GetLogoPath()+func (h *Handlers) GetLogo(w http.ResponseWriter, r *http.Request) {+ imageFilename := h.configRepository.GetLogoPath()if imageFilename == "" {returnDefault(w)return@@ -47,14 +44,13 @@ func GetLogo(w http.ResponseWriter, r *http.Request) {// and in that case will return a default placeholder.// Used for sharing to external social networks that generally// don't support SVG.-func GetCompatibleLogo(w http.ResponseWriter, r *http.Request) {- configRepository := configrepository.Get()- imageFilename := configRepository.GetLogoPath()+func (h *Handlers) GetCompatibleLogo(w http.ResponseWriter, r *http.Request) {+ imageFilename := h.configRepository.GetLogoPath()// If the logo image is not a SVG then we can return it// without any problems.if imageFilename != "" && filepath.Ext(imageFilename) != ".svg" {- GetLogo(w, r)+ h.GetLogo(w, r)return}@@ -70,9 +66,11 @@ func GetCompatibleLogo(w http.ResponseWriter, r *http.Request) {cacheTime := utils.GetCacheDurationSecondsForPath(imagePath)writeBytesAsImage(imageBytes, contentType, w, cacheTime)- if !_hasWarnedSVGLogo {+ h.hasWarnedSVGLogoLock.Lock()+ defer h.hasWarnedSVGLogoLock.Unlock()+ if !h.hasWarnedSVGLogo {log.Warnf("an external site requested your logo. because many social networks do not support SVGs we returned a placeholder instead. change your current logo to a png or jpeg to be most compatible with external social networking sites.")- _hasWarnedSVGLogo = true+ h.hasWarnedSVGLogo = true}}diff --git a/webserver/handlers/moderation.go b/webserver/handlers/moderation.goindex 55d9f07e7a..2d05507bf7 100644--- a/webserver/handlers/moderation.go+++ b/webserver/handlers/moderation.go@@ -4,10 +4,8 @@ import ("net/http""github.com/owncast/owncast/webserver/handlers/generated"- "github.com/owncast/owncast/webserver/handlers/moderation"- "github.com/owncast/owncast/webserver/router/middleware")-func (*ServerInterfaceImpl) GetUserDetails(w http.ResponseWriter, r *http.Request, userId string, params generated.GetUserDetailsParams) {- middleware.RequireUserModerationScopeAccesstoken(moderation.GetUserDetails)(w, r)+func (s *ServerInterfaceImpl) GetUserDetails(w http.ResponseWriter, r *http.Request, userId string, params generated.GetUserDetailsParams) {+ s.h.middleware.RequireUserModerationScopeAccesstoken(s.h.moderation.GetUserDetails)(w, r)}diff --git a/webserver/handlers/moderation/moderation.go b/webserver/handlers/moderation/moderation.goindex 5a5843ed3e..6d66832c43 100644--- a/webserver/handlers/moderation/moderation.go+++ b/webserver/handlers/moderation/moderation.go@@ -6,17 +6,41 @@ import ("strings""time"- "github.com/owncast/owncast/core/chat"- "github.com/owncast/owncast/core/chat/events"+ log "github.com/sirupsen/logrus"+"github.com/owncast/owncast/models""github.com/owncast/owncast/persistence/chatmessagerepository""github.com/owncast/owncast/persistence/userrepository"+ "github.com/owncast/owncast/services/chat"+ "github.com/owncast/owncast/services/chat/events""github.com/owncast/owncast/webserver/utils"- log "github.com/sirupsen/logrus")+// Handler bundles the dependencies the moderation handlers need.+type Handler struct {+ chat *chat.Service+ chatMessageRepository chatmessagerepository.ChatMessageRepository+ userRepository userrepository.UserRepository+}++// Deps lists the dependencies of the moderation Handler.+type Deps struct {+ Chat *chat.Service+ ChatMessageRepository chatmessagerepository.ChatMessageRepository+ UserRepository userrepository.UserRepository+}++// New constructs the Handler.+func New(deps Deps) *Handler {+ return &Handler{+ chat: deps.Chat,+ chatMessageRepository: deps.ChatMessageRepository,+ userRepository: deps.UserRepository,+ }+}+// GetUserDetails returns the details of a chat user for moderators.-func GetUserDetails(w http.ResponseWriter, r *http.Request) {+func (h *Handler) GetUserDetails(w http.ResponseWriter, r *http.Request) {type connectedClient struct {ConnectedAt time.Time `json:"connectedAt"`UserAgent string `json:"userAgent"`@@ -34,16 +58,14 @@ func GetUserDetails(w http.ResponseWriter, r *http.Request) {pathComponents := strings.Split(r.URL.Path, "/")uid := pathComponents[len(pathComponents)-1]- userRepository := userrepository.Get()-- u := userRepository.GetUserByID(uid)+ u := h.userRepository.GetUserByID(uid)if u == nil {w.WriteHeader(http.StatusNotFound)return}- c, _ := chat.GetClientsForUser(uid)+ c, _ := h.chat.GetClientsForUser(uid)clients := make([]connectedClient, len(c))for i, c := range c {client := connectedClient{@@ -59,8 +81,7 @@ func GetUserDetails(w http.ResponseWriter, r *http.Request) {clients[i] = client}- chatMessagesRepository := chatmessagerepository.Get()- messages, err := chatMessagesRepository.GetMessagesFromUser(uid)+ messages, err := h.chatMessageRepository.GetMessagesFromUser(uid)if err != nil {log.Errorln(err)}@@ -77,6 +98,8 @@ func GetUserDetails(w http.ResponseWriter, r *http.Request) {}}-func ExternalGetUserDetails(integration models.ExternalAPIUser, w http.ResponseWriter, r *http.Request) {- GetUserDetails(w, r)+// ExternalGetUserDetails is the externally-authenticated entry point that+// delegates to GetUserDetails.+func (h *Handler) ExternalGetUserDetails(integration models.ExternalAPIUser, w http.ResponseWriter, r *http.Request) {+ h.GetUserDetails(w, r)}diff --git a/webserver/handlers/notifications.go b/webserver/handlers/notifications.goindex 070aa2d43e..706e9160fb 100644--- a/webserver/handlers/notifications.go+++ b/webserver/handlers/notifications.go@@ -4,16 +4,17 @@ import ("encoding/json""net/http"+ log "github.com/sirupsen/logrus"+"github.com/owncast/owncast/models"notificationsrepo "github.com/owncast/owncast/persistence/notificationsrepository""github.com/owncast/owncast/utils"webutils "github.com/owncast/owncast/webserver/utils"- log "github.com/sirupsen/logrus")// RegisterForLiveNotifications will register a channel + destination to be// notified when a stream goes live.-func RegisterForLiveNotifications(u models.User, w http.ResponseWriter, r *http.Request) {+func (h *Handlers) RegisterForLiveNotifications(u models.User, w http.ResponseWriter, r *http.Request) {if r.Method != http.MethodPost {webutils.WriteSimpleResponse(w, false, r.Method+" not supported")return@@ -42,7 +43,7 @@ func RegisterForLiveNotifications(u models.User, w http.ResponseWriter, r *http.return}- if err := notificationsrepo.Get().AddNotification(req.Channel, req.Destination); err != nil {+ if err := h.notificationsRepository.AddNotification(req.Channel, req.Destination); err != nil {log.Errorln(err)webutils.WriteSimpleResponse(w, false, "unable to save notification")returndiff --git a/webserver/handlers/ping.go b/webserver/handlers/ping.goindex 36da32df71..7aed0b0b11 100644--- a/webserver/handlers/ping.go+++ b/webserver/handlers/ping.go@@ -3,13 +3,12 @@ package handlersimport ("net/http"- "github.com/owncast/owncast/core""github.com/owncast/owncast/models")// Ping is fired by a client to show they are still an active viewer.-func Ping(w http.ResponseWriter, r *http.Request) {+func (h *Handlers) Ping(w http.ResponseWriter, r *http.Request) {viewer := models.GenerateViewerFromRequest(r)- core.SetViewerActive(&viewer)+ h.stream.SetViewerActive(&viewer)w.WriteHeader(http.StatusOK)}diff --git a/webserver/handlers/playbackMetrics.go b/webserver/handlers/playbackMetrics.goindex 22ba77e2f8..665ba4f288 100644--- a/webserver/handlers/playbackMetrics.go+++ b/webserver/handlers/playbackMetrics.go@@ -4,16 +4,16 @@ import ("encoding/json""net/http"- "github.com/owncast/owncast/metrics"+ log "github.com/sirupsen/logrus"+"github.com/owncast/owncast/utils""github.com/owncast/owncast/webserver/handlers/generated"webutils "github.com/owncast/owncast/webserver/utils"- log "github.com/sirupsen/logrus")// ReportPlaybackMetrics will accept playback metrics from a client and save// them for future video health reporting.-func ReportPlaybackMetrics(w http.ResponseWriter, r *http.Request) {+func (h *Handlers) ReportPlaybackMetrics(w http.ResponseWriter, r *http.Request) {if r.Method != http.MethodPost {webutils.WriteSimpleResponse(w, false, r.Method+" not supported")return@@ -33,23 +33,23 @@ func ReportPlaybackMetrics(w http.ResponseWriter, r *http.Request) {webutils.WriteSimpleResponse(w, false, "errors field is required")return}- metrics.RegisterPlaybackErrorCount(clientID, *request.Errors)+ h.metrics.RegisterPlaybackErrorCount(clientID, *request.Errors)if request.Bandwidth != nil && *request.Bandwidth != 0.0 {- metrics.RegisterPlayerBandwidth(clientID, *request.Bandwidth)+ h.metrics.RegisterPlayerBandwidth(clientID, *request.Bandwidth)}if request.Latency != nil && *request.Latency != 0.0 {- metrics.RegisterPlayerLatency(clientID, *request.Latency)+ h.metrics.RegisterPlayerLatency(clientID, *request.Latency)}if request.DownloadDuration != nil && *request.DownloadDuration != 0.0 {- metrics.RegisterPlayerSegmentDownloadDuration(clientID, *request.DownloadDuration)+ h.metrics.RegisterPlayerSegmentDownloadDuration(clientID, *request.DownloadDuration)}if request.QualityVariantChanges == nil {webutils.WriteSimpleResponse(w, false, "qualityVariantChanges field is required")return}- metrics.RegisterQualityVariantChangesCount(clientID, *request.QualityVariantChanges)+ h.metrics.RegisterQualityVariantChangesCount(clientID, *request.QualityVariantChanges)}diff --git a/webserver/handlers/remoteFollow.go b/webserver/handlers/remoteFollow.goindex a0fb419751..f6b3ee6035 100644--- a/webserver/handlers/remoteFollow.go+++ b/webserver/handlers/remoteFollow.go@@ -5,15 +5,13 @@ import ("net/http""strings"- "github.com/owncast/owncast/activitypub/apmodels"- "github.com/owncast/owncast/activitypub/webfinger"- "github.com/owncast/owncast/persistence/configrepository"+ "github.com/owncast/owncast/services/activitypub/webfinger""github.com/owncast/owncast/webserver/handlers/generated"webutils "github.com/owncast/owncast/webserver/utils")// RemoteFollow handles a request to begin the remote follow redirect flow.-func RemoteFollow(w http.ResponseWriter, r *http.Request) {+func (h *Handlers) RemoteFollow(w http.ResponseWriter, r *http.Request) {type followResponse struct {RedirectURL string `json:"redirectUrl"`}@@ -35,8 +33,7 @@ func RemoteFollow(w http.ResponseWriter, r *http.Request) {return}- configRepository := configrepository.Get()- localActorPath := apmodels.MakeLocalIRIForAccount(configRepository.GetDefaultFederationUsername())+ localActorPath := h.apBuilder.MakeLocalIRIForAccount(h.configRepository.GetDefaultFederationUsername())var template stringlinks, err := webfinger.GetWebfingerLinks(*request.Account)if err != nil {diff --git a/webserver/handlers/robots.go b/webserver/handlers/robots.goindex 95d1155fd6..5654621b32 100644--- a/webserver/handlers/robots.go+++ b/webserver/handlers/robots.go@@ -3,12 +3,10 @@ package handlersimport ("net/http""strings"-- "github.com/owncast/owncast/persistence/configrepository")// GetRobotsDotTxt returns the contents of our robots.txt.-func GetRobotsDotTxt(w http.ResponseWriter, r *http.Request) {+func (h *Handlers) GetRobotsDotTxt(w http.ResponseWriter, r *http.Request) {w.Header().Set("Content-Type", "text/plain")contents := []string{"User-agent: *",@@ -16,8 +14,7 @@ func GetRobotsDotTxt(w http.ResponseWriter, r *http.Request) {"Disallow: /api",}- configRepository := configrepository.Get()- if configRepository.GetDisableSearchIndexing() {+ if h.configRepository.GetDisableSearchIndexing() {contents = append(contents, "Disallow: /")}diff --git a/webserver/handlers/status.go b/webserver/handlers/status.goindex 037bd07f0f..7908a2b2f1 100644--- a/webserver/handlers/status.go+++ b/webserver/handlers/status.go@@ -5,16 +5,14 @@ import ("net/http""time"- "github.com/owncast/owncast/core"- "github.com/owncast/owncast/persistence/configrepository""github.com/owncast/owncast/utils""github.com/owncast/owncast/webserver/router/middleware"webutils "github.com/owncast/owncast/webserver/utils")// GetStatus gets the status of the server.-func GetStatus(w http.ResponseWriter, r *http.Request) {- response := getStatusResponse()+func (h *Handlers) GetStatus(w http.ResponseWriter, r *http.Request) {+ response := h.getStatusResponse()w.Header().Set("Content-Type", "application/json")middleware.DisableCache(w)@@ -24,8 +22,8 @@ func GetStatus(w http.ResponseWriter, r *http.Request) {}}-func getStatusResponse() webStatusResponse {- status := core.GetStatus()+func (h *Handlers) getStatusResponse() webStatusResponse {+ status := h.stream.GetStatus()response := webStatusResponse{Online: status.Online,ServerTime: time.Now(),@@ -34,8 +32,7 @@ func getStatusResponse() webStatusResponse {VersionNumber: status.VersionNumber,StreamTitle: status.StreamTitle,}- configRepository := configrepository.Get()- if !configRepository.GetHideViewerCount() {+ if !h.configRepository.GetHideViewerCount() {response.ViewerCount = status.ViewerCount}return responsediff --git a/webserver/handlers/video.go b/webserver/handlers/video.goindex fdfe0db4a2..5881206eab 100644--- a/webserver/handlers/video.go+++ b/webserver/handlers/video.go@@ -4,7 +4,6 @@ import ("net/http""sort"- "github.com/owncast/owncast/persistence/configrepository"webutils "github.com/owncast/owncast/webserver/utils")@@ -21,9 +20,8 @@ type variantsResponse struct {}// GetVideoStreamOutputVariants will return the video variants available.-func GetVideoStreamOutputVariants(w http.ResponseWriter, r *http.Request) {- configRepository := configrepository.Get()- outputVariants := configRepository.GetStreamOutputVariants()+func (h *Handlers) GetVideoStreamOutputVariants(w http.ResponseWriter, r *http.Request) {+ outputVariants := h.configRepository.GetStreamOutputVariants()streamSortVariants := make([]variantsSort, len(outputVariants))for i, variant := range outputVariants {diff --git a/webserver/router/middleware/activityPub.go b/webserver/router/middleware/activityPub.goindex 2558619e28..c86871611f 100644--- a/webserver/router/middleware/activityPub.go+++ b/webserver/router/middleware/activityPub.go@@ -4,16 +4,14 @@ import ("net/http""strings"- "github.com/owncast/owncast/persistence/configrepository""github.com/owncast/owncast/utils")// RequireActivityPubOrRedirect will validate the requested content types and// redirect to the main Owncast page if it doesn't match.-func RequireActivityPubOrRedirect(handler http.HandlerFunc) http.HandlerFunc {- configRepository := configrepository.Get()+func (m *Middleware) RequireActivityPubOrRedirect(handler http.HandlerFunc) http.HandlerFunc {return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- if !configRepository.GetFederationEnabled() {+ if !m.configRepository.GetFederationEnabled() {w.WriteHeader(http.StatusMethodNotAllowed)return}diff --git a/webserver/router/middleware/auth.go b/webserver/router/middleware/auth.goindex 7da4a8f59f..3e91d749d9 100644--- a/webserver/router/middleware/auth.go+++ b/webserver/router/middleware/auth.go@@ -5,12 +5,10 @@ import ("net/http""strings"+ log "github.com/sirupsen/logrus"+"github.com/owncast/owncast/models"- "github.com/owncast/owncast/persistence/authrepository"- "github.com/owncast/owncast/persistence/configrepository"- "github.com/owncast/owncast/persistence/userrepository""github.com/owncast/owncast/utils"- log "github.com/sirupsen/logrus")// ExternalAccessTokenHandlerFunc is a function that is called after validing access.@@ -21,11 +19,10 @@ type UserAccessTokenHandlerFunc func(models.User, http.ResponseWriter, *http.Req// RequireAdminAuth wraps a handler requiring HTTP basic auth for it using the given// the stream key as the password and and a hardcoded "admin" for username.-func RequireAdminAuth(handler http.HandlerFunc) http.HandlerFunc {- configRepository := configrepository.Get()+func (m *Middleware) RequireAdminAuth(handler http.HandlerFunc) http.HandlerFunc {return func(w http.ResponseWriter, r *http.Request) {username := "admin"- password := configRepository.GetAdminPassword()+ password := m.configRepository.GetAdminPassword()realm := "Owncast Authenticated Request"// Alow CORS only for localhost:3000 to support Owncast development.@@ -61,7 +58,7 @@ func accessDenied(w http.ResponseWriter) {}// RequireExternalAPIAccessToken will validate a 3rd party access token.-func RequireExternalAPIAccessToken(scope string, handler ExternalAccessTokenHandlerFunc) http.HandlerFunc {+func (m *Middleware) RequireExternalAPIAccessToken(scope string, handler ExternalAccessTokenHandlerFunc) http.HandlerFunc {return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {// We should accept 3rd party preflight OPTIONS requests.if r.Method == "OPTIONS" {@@ -83,9 +80,7 @@ func RequireExternalAPIAccessToken(scope string, handler ExternalAccessTokenHandreturn}- userRepository := userrepository.Get()-- integration, err := userRepository.GetExternalAPIUserForAccessTokenAndScope(token, scope)+ integration, err := m.userRepository.GetExternalAPIUserForAccessTokenAndScope(token, scope)if integration == nil || err != nil {accessDenied(w)return@@ -96,7 +91,7 @@ func RequireExternalAPIAccessToken(scope string, handler ExternalAccessTokenHandhandler(*integration, w, r)- if err := userRepository.SetExternalAPIUserAccessTokenAsUsed(token); err != nil {+ if err := m.userRepository.SetExternalAPIUserAccessTokenAsUsed(token); err != nil {log.Debugln("token not found when updating last_used timestamp")}})@@ -104,8 +99,7 @@ func RequireExternalAPIAccessToken(scope string, handler ExternalAccessTokenHand// RequireUserAccessToken will validate a provided user's access token and make sure the associated user is enabled.// Not to be used for validating 3rd party access.-func RequireUserAccessToken(handler UserAccessTokenHandlerFunc) http.HandlerFunc {- authRepository := authrepository.Get()+func (m *Middleware) RequireUserAccessToken(handler UserAccessTokenHandlerFunc) http.HandlerFunc {return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {accessToken := r.URL.Query().Get("accessToken")if accessToken == "" {@@ -115,7 +109,7 @@ func RequireUserAccessToken(handler UserAccessTokenHandlerFunc) http.HandlerFuncipAddress := utils.GetIPAddressFromRequest(r)// Check if this client's IP address is banned.- if blocked, err := authRepository.IsIPAddressBanned(ipAddress); blocked {+ if blocked, err := m.authRepository.IsIPAddressBanned(ipAddress); blocked {log.Debugln("Client ip address has been blocked. Rejecting.")accessDenied(w)return@@ -123,10 +117,8 @@ func RequireUserAccessToken(handler UserAccessTokenHandlerFunc) http.HandlerFunclog.Errorln("error determining if IP address is blocked: ", err)}- userRepository := userrepository.Get()-// A user is required to use the websocket- user := userRepository.GetUserByToken(accessToken)+ user := m.userRepository.GetUserByToken(accessToken)if user == nil || !user.IsEnabled() {accessDenied(w)return@@ -138,7 +130,7 @@ func RequireUserAccessToken(handler UserAccessTokenHandlerFunc) http.HandlerFunc// RequireUserModerationScopeAccesstoken will validate a provided user's access token and make sure the associated user is enabled// and has "MODERATOR" scope assigned to the user.-func RequireUserModerationScopeAccesstoken(handler http.HandlerFunc) http.HandlerFunc {+func (m *Middleware) RequireUserModerationScopeAccesstoken(handler http.HandlerFunc) http.HandlerFunc {return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {accessToken := r.URL.Query().Get("accessToken")if accessToken == "" {@@ -146,10 +138,8 @@ func RequireUserModerationScopeAccesstoken(handler http.HandlerFunc) http.Handlereturn}- userRepository := userrepository.Get()-// A user is required to use the websocket- user := userRepository.GetUserByToken(accessToken)+ user := m.userRepository.GetUserByToken(accessToken)if user == nil || !user.IsEnabled() || !user.IsModerator() {accessDenied(w)returndiff --git a/webserver/router/middleware/middleware.go b/webserver/router/middleware/middleware.gonew file mode 100644index 0000000000..10a49aeab4--- /dev/null+++ b/webserver/router/middleware/middleware.go@@ -0,0 +1,33 @@+package middleware++import (+ "github.com/owncast/owncast/persistence/authrepository"+ "github.com/owncast/owncast/persistence/configrepository"+ "github.com/owncast/owncast/persistence/userrepository"+)++// Middleware bundles the dependencies needed by the HTTP middleware+// helpers in this package (admin basic-auth, external-API token auth,+// user-access-token auth, federation gating, etc.). Construct once in+// main() and inject into the components that wire HTTP routes.+type Middleware struct {+ configRepository configrepository.ConfigRepository+ authRepository authrepository.AuthRepository+ userRepository userrepository.UserRepository+}++// Deps lists the services *Middleware consumes.+type Deps struct {+ ConfigRepository configrepository.ConfigRepository+ AuthRepository authrepository.AuthRepository+ UserRepository userrepository.UserRepository+}++// New constructs a *Middleware.+func New(deps Deps) *Middleware {+ return &Middleware{+ configRepository: deps.ConfigRepository,+ authRepository: deps.AuthRepository,+ userRepository: deps.UserRepository,+ }+}diff --git a/webserver/router/router.go b/webserver/router/router.goindex 3750dafc9a..41b3c9b308 100644--- a/webserver/router/router.go+++ b/webserver/router/router.go@@ -11,17 +11,22 @@ import (chiMW "github.com/go-chi/chi/v5/middleware"log "github.com/sirupsen/logrus"- "github.com/owncast/owncast/activitypub"- aphandlers "github.com/owncast/owncast/activitypub/controllers""github.com/owncast/owncast/config"- "github.com/owncast/owncast/core/chat"- "github.com/owncast/owncast/core/data"+ apcontrollers "github.com/owncast/owncast/services/activitypub/controllers""github.com/owncast/owncast/webserver/handlers""github.com/owncast/owncast/webserver/router/middleware")// Start starts the router for the http, ws, and rtmp.-func Start(enableVerboseLogging bool) error {+//+// cfg supplies the bound port + IP for the public web server. h carries+// dependency-injected handler methods. Free-function handlers (the+// majority during the migration) are referenced directly by package+// path; methods on *handlers.Handlers are registered via the h receiver.+// mw carries the methodified HTTP middleware (admin basic-auth, federation+// content-type gating). apc carries the methodified ActivityPub HTTP+// handler set.+func Start(cfg *config.Config, enableVerboseLogging bool, h *handlers.Handlers, mw *middleware.Middleware, apc *apcontrollers.Controllers) error {// @behlers New Routerr := chi.NewRouter()@@ -31,35 +36,32 @@ func Start(enableVerboseLogging bool) error {}r.Use(chiMW.Recoverer)- addStaticFileEndpoints(r)+ addStaticFileEndpoints(r, h, apc)// websocket- r.HandleFunc("/ws", chat.HandleClientConnection)+ r.HandleFunc("/ws", h.HandleWebsocketConnection)// serve filesfs := http.FileServer(http.Dir(config.PublicFilesPath))r.Handle("/public/*", http.StripPrefix("/public/", fs))// Return HLS video- r.HandleFunc("/hls/*", handlers.HandleHLSRequest)+ r.HandleFunc("/hls/*", h.HandleHLSRequest)// The admin web app.- r.HandleFunc("/admin/*", middleware.RequireAdminAuth(handlers.IndexHandler))+ r.HandleFunc("/admin/*", mw.RequireAdminAuth(h.IndexHandler))// Single ActivityPub Actor- r.HandleFunc("/federation/user/*", middleware.RequireActivityPubOrRedirect(aphandlers.ActorHandler))+ r.HandleFunc("/federation/user/*", mw.RequireActivityPubOrRedirect(apc.ActorHandler))// Single AP object- r.HandleFunc("/federation/*", middleware.RequireActivityPubOrRedirect(aphandlers.ObjectHandler))+ r.HandleFunc("/federation/*", mw.RequireActivityPubOrRedirect(apc.ObjectHandler))// The primary web app.- r.HandleFunc("/*", handlers.IndexHandler)+ r.HandleFunc("/*", h.IndexHandler)// mount the api- r.Mount("/api/", handlers.New().Handler())-- // ActivityPub has its own router- activitypub.Start(data.GetDatastore())+ r.Mount("/api/", handlers.New(h).Handler())// Create a custom mux handler to intercept the /debug/vars endpoint.// This is a hack because Prometheus enables this endpoint by default@@ -80,8 +82,8 @@ func Start(enableVerboseLogging bool) error {}})- port := config.WebServerPort- ip := config.WebServerIP+ port := cfg.WebServerPort+ ip := cfg.WebServerIP// Allow cleartext (unencrypted) HTTP/2 in addition to HTTP/1, replacing the// previously used and now-deprecated golang.org/x/net/http2/h2c wrapper.@@ -107,20 +109,20 @@ func Start(enableVerboseLogging bool) error {return server.ListenAndServe()}-func addStaticFileEndpoints(r chi.Router) {+func addStaticFileEndpoints(r chi.Router, h *handlers.Handlers, apc *apcontrollers.Controllers) {// Images- r.HandleFunc("/thumbnail.jpg", handlers.GetThumbnail)- r.HandleFunc("/preview.gif", handlers.GetPreview)- r.HandleFunc("/logo", handlers.GetLogo)- r.HandleFunc("/favicon.ico", handlers.GetFavicon)+ r.HandleFunc("/thumbnail.jpg", h.GetThumbnail)+ r.HandleFunc("/preview.gif", h.GetPreview)+ r.HandleFunc("/logo", h.GetLogo)+ r.HandleFunc("/favicon.ico", h.GetFavicon)// return a logo that's compatible with external social networks- r.HandleFunc("/logo/external", handlers.GetCompatibleLogo)+ r.HandleFunc("/logo/external", h.GetCompatibleLogo)// Custom Javascript- r.HandleFunc("/customjavascript", handlers.ServeCustomJavascript)+ r.HandleFunc("/customjavascript", h.ServeCustomJavascript)// robots.txt- r.HandleFunc("/robots.txt", handlers.GetRobotsDotTxt)+ r.HandleFunc("/robots.txt", h.GetRobotsDotTxt)// Return a single emoji image.emojiDir := config.EmojiDir@@ -130,20 +132,20 @@ func addStaticFileEndpoints(r chi.Router) {r.HandleFunc(emojiDir, handlers.GetCustomEmojiImage)// WebFinger- r.HandleFunc("/.well-known/webfinger", aphandlers.WebfingerHandler)+ r.HandleFunc("/.well-known/webfinger", apc.WebfingerHandler)// Host Metadata- r.HandleFunc("/.well-known/host-meta", aphandlers.HostMetaController)+ r.HandleFunc("/.well-known/host-meta", apc.HostMetaController)// Nodeinfo v1- r.HandleFunc("/.well-known/nodeinfo", aphandlers.NodeInfoController)+ r.HandleFunc("/.well-known/nodeinfo", apc.NodeInfoController)// x-nodeinfo v2- r.HandleFunc("/.well-known/x-nodeinfo2", aphandlers.XNodeInfo2Controller)+ r.HandleFunc("/.well-known/x-nodeinfo2", apc.XNodeInfo2Controller)// Nodeinfo v2- r.HandleFunc("/nodeinfo/2.0", aphandlers.NodeInfoV2Controller)+ r.HandleFunc("/nodeinfo/2.0", apc.NodeInfoV2Controller)// Instance details- r.HandleFunc("/api/v1/instance", aphandlers.InstanceV1Controller)+ r.HandleFunc("/api/v1/instance", apc.InstanceV1Controller)}diff --git a/webserver/utils/responses.go b/webserver/utils/responses.goindex 368ca756ed..216bc35d47 100644--- a/webserver/utils/responses.go+++ b/webserver/utils/responses.go@@ -4,9 +4,10 @@ import ("encoding/json""net/http"+ log "github.com/sirupsen/logrus"+"github.com/owncast/owncast/models""github.com/owncast/owncast/webserver/router/middleware"- log "github.com/sirupsen/logrus")type J map[string]interface{}diff --git a/yp/api.go b/yp/api.goindex cfffb9e4e8..0f520fa5d9 100644--- a/yp/api.go+++ b/yp/api.go@@ -4,10 +4,10 @@ import ("encoding/json""net/http"+ log "github.com/sirupsen/logrus"+"github.com/owncast/owncast/models"- "github.com/owncast/owncast/persistence/configrepository""github.com/owncast/owncast/utils"- log "github.com/sirupsen/logrus")type ypDetailsResponse struct {@@ -27,30 +27,29 @@ type ypDetailsResponse struct {}// GetYPResponse gets the status of the server for YP purposes.-func GetYPResponse(w http.ResponseWriter, r *http.Request) {- configRepository := configrepository.Get()- if !configRepository.GetDirectoryEnabled() {+func (yp *YP) GetYPResponse(w http.ResponseWriter, r *http.Request) {+ if !yp.configRepository.GetDirectoryEnabled() {w.WriteHeader(http.StatusNotFound)return}- status := getStatus()+ status := yp.getStatus()- streamTitle := configRepository.GetStreamTitle()+ streamTitle := yp.configRepository.GetStreamTitle()response := ypDetailsResponse{- Name: configRepository.GetServerName(),- Description: configRepository.GetServerSummary(),+ Name: yp.configRepository.GetServerName(),+ Description: yp.configRepository.GetServerSummary(),StreamTitle: streamTitle,Logo: "/logo",- NSFW: configRepository.GetNSFW(),- Tags: configRepository.GetServerMetadataTags(),+ NSFW: yp.configRepository.GetNSFW(),+ Tags: yp.configRepository.GetServerMetadataTags(),Online: status.Online,ViewerCount: status.ViewerCount,OverallMaxViewerCount: status.OverallMaxViewerCount,SessionMaxViewerCount: status.SessionMaxViewerCount,LastConnectTime: status.LastConnectTime,- Social: configRepository.GetSocialHandles(),+ Social: yp.configRepository.GetSocialHandles(),}w.Header().Set("Content-Type", "application/json")diff --git a/yp/yp.go b/yp/yp.goindex 1221ed908a..8cb2687686 100644--- a/yp/yp.go+++ b/yp/yp.go@@ -1,3 +1,6 @@+// Package yp is the Owncast directory listing service. Construct via+// New(Deps) and call Start when a stream goes live to begin pinging the+// directory.package ypimport (@@ -17,14 +20,28 @@ import (const pingInterval = 4 * time.Minute-var (- getStatus func() models.Status- _inErrorState = false-)-// YP is a service for handling listing in the Owncast directory.type YP struct {timer *time.Ticker++ // getStatus returns the current stream status; consulted on each+ // ping cycle to skip pings while offline.+ getStatus func() models.Status++ // configRepository provides directory-listing settings (enabled flag,+ // server URL/name, registration key, etc.) read on each ping and on+ // every YP API response.+ configRepository configrepository.ConfigRepository++ // inErrorState tracks whether we've already logged an error for the+ // current configuration to avoid spamming the log on repeated pings.+ inErrorState bool+}++// Deps lists the explicit dependencies for the YP service.+type Deps struct {+ GetStatus func() models.Status+ ConfigRepository configrepository.ConfigRepository}type ypPingResponse struct {@@ -39,10 +56,21 @@ type ypPingRequest struct {URL string `json:"url"`}-// NewYP creates a new instance of the YP service handler.-func NewYP(getStatusFunc func() models.Status) *YP {- getStatus = getStatusFunc- return &YP{}+// New constructs a new instance of the YP service handler.+func New(deps Deps) *YP {+ return &YP{+ getStatus: deps.GetStatus,+ configRepository: deps.ConfigRepository,+ }+}++// SetGetStatus wires (or rewires) the stream-status callback. Exists+// because yp must be constructed before stream (stream takes yp via+// Deps), but yp needs stream.GetStatus to skip pings while offline.+// main.go constructs yp first with a nil callback, then fills it in once+// streamSvc exists. Must be called before Start.+func (yp *YP) SetGetStatus(fn func() models.Status) {+ yp.getStatus = fn}// Start is run when a live stream begins to start pinging YP.@@ -61,35 +89,33 @@ func (yp *YP) Stop() {}func (yp *YP) ping() {- configRepository := configrepository.Get()-- if !configRepository.GetDirectoryEnabled() {+ if !yp.configRepository.GetDirectoryEnabled() {return}// Hack: Don't allow ping'ing when offline.// It shouldn't even be trying to, but on some instances the ping timer isn't stopping.- if !getStatus().Online {+ if !yp.getStatus().Online {return}- myInstanceURL := configRepository.GetServerURL()+ myInstanceURL := yp.configRepository.GetServerURL()if myInstanceURL == "" {log.Warnln("Server URL not set in the configuration. Directory access is disabled until this is set.")return}isValidInstanceURL := isURL(myInstanceURL)if myInstanceURL == "" || !isValidInstanceURL {- if !_inErrorState {+ if !yp.inErrorState {log.Warnln("YP Error: unable to use", myInstanceURL, "as a public instance URL. Fix this value in your configuration.")}- _inErrorState = true+ yp.inErrorState = truereturn}- key := configRepository.GetDirectoryRegistrationKey()+ key := yp.configRepository.GetDirectoryRegistrationKey()- log.Traceln("Pinging YP as: ", configRepository.GetServerName(), "with key", key)+ log.Traceln("Pinging YP as: ", yp.configRepository.GetServerName(), "with key", key)request := ypPingRequest{Key: key,@@ -121,17 +147,17 @@ func (yp *YP) ping() {}if !pingResponse.Success {- if !_inErrorState {+ if !yp.inErrorState {log.Warnln("YP Ping error returned from service:", pingResponse.Error)}- _inErrorState = true+ yp.inErrorState = truereturn}- _inErrorState = false+ yp.inErrorState = falseif pingResponse.Key != key {- if err := configRepository.SetDirectoryRegistrationKey(key); err != nil {+ if err := yp.configRepository.SetDirectoryRegistrationKey(key); err != nil {log.Errorln("unable to save directory key:", err)}}