Take control over your live stream video by running it yourself. Streaming + chat out of the box.
HTML activitypubbroadcastingchatdecentralizedfederationfediversegolanghacktoberfesthlslivelivestreamowncastrtmpself-hostedstreaming-videovideo
feat(ap): reflect a featured server's live status immediately
Gabe Kangas34953d86f4d9
diff --git a/services/activitypub/inbox/accept.go b/services/activitypub/inbox/accept.goindex f603bb2d35..353b3e60dc 100644--- a/services/activitypub/inbox/accept.go+++ b/services/activitypub/inbox/accept.go@@ -9,6 +9,7 @@ import ("github.com/go-fed/activity/streams/vocab"log "github.com/sirupsen/logrus"+ "github.com/owncast/owncast/config""github.com/owncast/owncast/persistence/federatedserversrepository""github.com/owncast/owncast/services/activitypub/apmodels")@@ -32,18 +33,16 @@ func (s *Service) handleAcceptInboxRequest(c context.Context, activity vocab.Actreturn nil}+ // The Accept may carry the remote server's current Owncast stream status+ // so we can reflect its live state immediately on acceptance.+ metadata := apmodels.ParseOwncastMetadata(activity.GetUnknownProperties())+for iter := objectProp.Begin(); iter != objectProp.End(); iter = iter.Next() {if iter.IsActivityStreamsFollow() {- s.markFederatedServerAccepted(actorIRI)+ s.markFederatedServerAccepted(actorIRI, metadata)}}- unknownProps := activity.GetUnknownProperties()- metadata := apmodels.ParseOwncastMetadata(unknownProps)- if metadata.IsOwncastServer {- log.Debugf("Accept activity from %s contains Owncast metadata", actorIRI)- }-return nil}@@ -51,7 +50,7 @@ func (s *Service) handleAcceptInboxRequest(c context.Context, activity vocab.Act// an Accept-of-Follow: it transitions our pending follow record for the// remote Owncast server into the accepted state and tops up the cached// metadata from the resolved actor.-func (s *Service) markFederatedServerAccepted(actorIRI string) {+func (s *Service) markFederatedServerAccepted(actorIRI string, metadata *apmodels.OwncastMetadata) {log.Debugf("Received Accept for Follow request from %s", actorIRI)parsedIRI, err := url.Parse(actorIRI)@@ -95,5 +94,14 @@ func (s *Service) markFederatedServerAccepted(actorIRI string) {}}+ // If the Accept reports the remote stream is already live, reflect that now+ // so a server featured while already streaming doesn't appear offline until+ // its next periodic ping.+ if metadata != nil && metadata.StreamStatus == config.APStreamStatusLive {+ if err := repo.UpdateServerStatus(serverURL, true, buildStreamUpdateFromMetadata(metadata)); err != nil {+ log.Errorf("Failed to set initial online status for %s: %v", serverURL, err)+ }+ }+log.Infof("Follow request to %s has been accepted", serverURL)}diff --git a/services/activitypub/inbox/follow.go b/services/activitypub/inbox/follow.goindex b7f0708d1f..4b7be3a032 100644--- a/services/activitypub/inbox/follow.go+++ b/services/activitypub/inbox/follow.go@@ -59,7 +59,10 @@ func (s *Service) handleFollowInboxRequest(c context.Context, activity vocab.ActactorReference := activity.GetActivityStreamsActor()if approved {- if err := requests.SendFollowAccept(s.workerpool, follow.Inbox, activity, localAccountName, s.builder, s.signer); err != nil {+ // Only non-featured (fan) follows reach the auto-accept path here;+ // featured follows always require manual approval, so live status in+ // this Accept isn't needed and is reported as not-live.+ if err := requests.SendFollowAccept(s.workerpool, follow.Inbox, activity, localAccountName, s.builder, s.signer, s.configRepository, false); err != nil {log.Errorln("unable to send follow accept", err)return err}diff --git a/services/activitypub/outbox/follow.go b/services/activitypub/outbox/follow.goindex deeb20d30a..607bff0c14 100644--- a/services/activitypub/outbox/follow.go+++ b/services/activitypub/outbox/follow.go@@ -52,6 +52,106 @@ func (s *Service) SendFollowRequestToOwncastServerURL(targetServerURL string, isreturn s.SendFollowToAccount(targetActorAccount, isStreamConnected)}+// SendUnfollowRequestToOwncastServerURL sends an Undo of our Follow to the+// given Owncast server so it stops treating us as a follower. Used when an+// admin unfeatures a server. Best-effort: the local record is removed+// regardless, so callers should treat a returned error as non-fatal.+func (s *Service) SendUnfollowRequestToOwncastServerURL(targetServerURL string) error {+ if !s.configRepository.GetFederationEnabled() {+ return nil+ }++ parsedURL, err := url.Parse(targetServerURL)+ if err != nil {+ return fmt.Errorf("failed to parse target URL: %w", err)+ }++ nodeinfo, err := utils.FetchNodeInfo(targetServerURL)+ if err != nil {+ return fmt.Errorf("failed to fetch nodeinfo from %s: %w", targetServerURL, err)+ }++ targetUsername, err := utils.ExtractFederationUsername(nodeinfo)+ if err != nil {+ return fmt.Errorf("failed to extract federation username: %w", err)+ }++ account := fmt.Sprintf("%s@%s", targetUsername, parsedURL.Host)+ links, err := webfinger.GetWebfingerLinks(account)+ if err != nil {+ return fmt.Errorf("failed to get webfinger links for %s: %w", account, err)+ }++ user := apmodels.MakeWebFingerRequestResponseFromData(links)+ if user.Self == "" {+ return fmt.Errorf("no actor IRI found in webfinger response for %s", account)+ }++ actor, err := s.resolver.GetResolvedActorFromIRI(user.Self)+ if err != nil {+ return fmt.Errorf("failed to resolve actor from IRI %s: %w", user.Self, err)+ }++ if !strings.EqualFold(actor.ActorIri.Host, parsedURL.Host) {+ return fmt.Errorf("resolved actor host %q does not match server host %q", actor.ActorIri.Host, parsedURL.Host)+ }+ if actor.Inbox == nil {+ return fmt.Errorf("no inbox found for actor %s", actor.ActorIri.String())+ }++ return s.sendUndoFollow(actor.ActorIri, actor.Inbox)+}++// sendUndoFollow builds and queues an Undo of a Follow whose actor is this+// server and whose object is the given remote actor.+func (s *Service) sendUndoFollow(targetActorIRI, inbox *url.URL) error {+ localUsername := s.configRepository.GetFederationUsername()+ localActorIRI := s.builder.MakeLocalIRIForAccount(localUsername)++ undoID := shortid.MustGenerate()+ undoIRI := s.builder.MakeLocalIRIForResource(fmt.Sprintf("undo/%s", undoID))++ // Reconstruct the Follow being undone (actor = us, object = remote actor).+ follow := streams.NewActivityStreamsFollow()+ followActor := streams.NewActivityStreamsActorProperty()+ followActor.AppendIRI(localActorIRI)+ follow.SetActivityStreamsActor(followActor)+ followObject := streams.NewActivityStreamsObjectProperty()+ followObject.AppendIRI(targetActorIRI)+ follow.SetActivityStreamsObject(followObject)++ undo := streams.NewActivityStreamsUndo()+ undoIDProperty := streams.NewJSONLDIdProperty()+ undoIDProperty.SetIRI(undoIRI)+ undo.SetJSONLDId(undoIDProperty)++ undoActor := streams.NewActivityStreamsActorProperty()+ undoActor.AppendIRI(localActorIRI)+ undo.SetActivityStreamsActor(undoActor)++ undoObject := streams.NewActivityStreamsObjectProperty()+ undoObject.AppendActivityStreamsFollow(follow)+ undo.SetActivityStreamsObject(undoObject)++ undoTo := streams.NewActivityStreamsToProperty()+ undoTo.AppendIRI(targetActorIRI)+ undo.SetActivityStreamsTo(undoTo)++ jsonData, err := apmodels.Serialize(undo)+ if err != nil {+ return fmt.Errorf("failed to serialize undo activity: %w", err)+ }++ req, err := s.signer.CreateSignedRequest(jsonData, inbox, localActorIRI)+ if err != nil {+ return fmt.Errorf("failed to create signed request: %w", err)+ }++ s.workerpool.AddToOutboundQueue(req)+ log.Infof("Sent unfollow (Undo) to %s", targetActorIRI.String())+ return nil+}+// SendFollowToAccount sends a Follow activity to a fediverse account// expressed in webfinger form (user@host).func (s *Service) SendFollowToAccount(targetActorAccount string, isStreamConnected bool) error {diff --git a/services/activitypub/requests/acceptFollow.go b/services/activitypub/requests/acceptFollow.goindex 7ff17c24f9..9d130f0203 100644--- a/services/activitypub/requests/acceptFollow.go+++ b/services/activitypub/requests/acceptFollow.go@@ -8,6 +8,7 @@ import ("github.com/go-fed/activity/streams/vocab""github.com/pkg/errors"+ "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/workerpool"@@ -18,8 +19,10 @@ import (// 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 {+// provided workerpool. The Accept carries this server's current Owncast+// stream status so a newly accepted featured-streams follower reflects our+// live state immediately rather than waiting for the next periodic ping.+func SendFollowAccept(wp *workerpool.Service, inbox *url.URL, originalFollowActivity vocab.ActivityStreamsFollow, fromLocalAccountName string, builder *apmodels.Builder, signer *crypto.Signer, configRepository configrepository.ConfigRepository, streamActive bool) 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())@@ -28,7 +31,7 @@ func SendFollowAccept(wp *workerpool.Service, inbox *url.URL, originalFollowActireturn errors.Errorf("rejecting internal/loopback inbox URL for SSRF protection: %s", inbox.String())}- followAccept := makeAcceptFollow(originalFollowActivity, fromLocalAccountName, builder)+ followAccept := makeAcceptFollow(originalFollowActivity, fromLocalAccountName, builder, configRepository, streamActive)localAccountIRI := builder.MakeLocalIRIForAccount(fromLocalAccountName)var jsonmap map[string]interface{}@@ -44,7 +47,7 @@ func SendFollowAccept(wp *workerpool.Service, inbox *url.URL, originalFollowActireturn nil}-func makeAcceptFollow(originalFollowActivity vocab.ActivityStreamsFollow, fromAccountName string, builder *apmodels.Builder) vocab.ActivityStreamsAccept {+func makeAcceptFollow(originalFollowActivity vocab.ActivityStreamsFollow, fromAccountName string, builder *apmodels.Builder, configRepository configrepository.ConfigRepository, streamActive bool) vocab.ActivityStreamsAccept {acceptIDString := shortid.MustGenerate()acceptID := builder.MakeLocalIRIForResource(acceptIDString)actorID := builder.MakeLocalIRIForAccount(fromAccountName)@@ -61,5 +64,9 @@ func makeAcceptFollow(originalFollowActivity vocab.ActivityStreamsFollow, fromAcobject.AppendActivityStreamsFollow(originalFollowActivity)accept.SetActivityStreamsObject(object)+ // Attach our current stream status/metadata so a featured-streams follower+ // can show our live state the moment the follow is accepted.+ apmodels.SetOwncastMetadata(accept.GetUnknownProperties(), configRepository, streamActive)+return accept}diff --git a/test/automated/activitypub/test-featured-streams.sh b/test/automated/activitypub/test-featured-streams.shindex d2cb2642cd..a3a938fdd4 100755--- a/test/automated/activitypub/test-featured-streams.sh+++ b/test/automated/activitypub/test-featured-streams.sh@@ -366,6 +366,19 @@ server_object() {echo "$1" | jq -c --arg iri "$2" '.servers[]? | select(.iri == $iri)' 2>/dev/null}+# server_id JSON IRI -> prints the numeric id of the server with that iri+server_id() {+ echo "$1" | jq -r --arg iri "$2" '.servers[]? | select(.iri == $iri) | .id' 2>/dev/null+}++# remove_featured_server WEB_PORT ID -> unfeatures (and unfollows) a server+remove_featured_server() {+ local web_port=$1 id=$2 auth+ auth=$(get_admin_auth)+ curl -s -X DELETE "http://localhost:${web_port}/api/admin/federation/servers/${id}" \+ -H "Authorization: Basic ${auth}"+}+# server_field JSON IRI FIELD -> prints the value of FIELD (or empty).# Note: we deliberately avoid `// empty` here because jq treats a literal# false as "absent", which would turn isOnline=false into an empty string and@@ -777,6 +790,114 @@ test_featuring_server_hidden_from_followers() {return 0}+test_feature_while_already_live() {+ log_test "TEST 9: Featuring a server that is already live shows it live promptly"++ if [[ "${CI}" != "true" ]]; then+ echo ""+ read -p "Run the 'feature while already live' test (starts a stream)? [Y/n] " -n 1 -r+ echo ""+ if [[ "${REPLY}" =~ ^[Nn]$ ]]; then+ log_warn "TEST 9 SKIPPED: declined to start a test stream"+ return 0+ fi+ fi++ local instance1_actor="${OWNCAST_URL}/federation/user/${OWNCAST_FED_USERNAME}"++ # Unfeature instance 2 first, so instance 1 is NOT a follower when instance+ # 2 goes live (otherwise instance 2's immediate go-live ping would reach+ # instance 1 and mask what we're testing). The unfeature sends an Undo so+ # instance 2 drops instance 1 as a follower, enabling a clean re-follow.+ local id+ id=$(server_id "$(get_featured_servers "${OWNCAST_PORT}" admin)" "${OWNCAST2_URL}")+ if [[ -z "${id}" || "${id}" == "null" ]]; then+ log_error "TEST 9 FAILED: could not find instance 2's id to unfeature"+ return 1+ fi+ log_info "Unfeaturing instance 2 (id ${id}); waiting for the Undo to propagate..."+ remove_featured_server "${OWNCAST_PORT}" "${id}" > /dev/null+ sleep 12++ # Start instance 2 streaming while instance 1 is not following it.+ local expected_title="Already Live Test"+ local auth+ auth=$(get_admin_auth)+ curl -s -X POST "http://localhost:${OWNCAST2_PORT}/api/admin/config/streamtitle" \+ -H "Authorization: Basic ${auth}" -H "Content-Type: application/json" \+ -d "{\"value\": \"${expected_title}\"}" > /dev/null++ log_info "Starting test stream into instance 2..."+ "${REPO_ROOT}/test/ocTestStream.sh" "rtmp://127.0.0.1:${OWNCAST2_RTMP_PORT}/live/${STREAM_KEY}" \+ > "${TEMP_DIR}/teststream-live.log" 2>&1 &+ TEST_STREAM_PID=$!++ local waited=0+ while [[ ${waited} -lt 90 ]]; do+ if [[ "$(curl -s "http://localhost:${OWNCAST2_PORT}/api/status" | jq -r '.online // false' 2>/dev/null)" == "true" ]]; then+ break+ fi+ if ! kill -0 "${TEST_STREAM_PID}" 2>/dev/null; then+ log_error "TEST 9 FAILED: test stream exited early. ffmpeg log:"+ cat "${TEMP_DIR}/teststream-live.log"+ TEST_STREAM_PID=""+ return 1+ fi+ sleep 3+ waited=$((waited + 3))+ done+ if [[ "$(curl -s "http://localhost:${OWNCAST2_PORT}/api/status" | jq -r '.online // false' 2>/dev/null)" != "true" ]]; then+ log_error "TEST 9 FAILED: instance 2 did not go live"+ stop_test_stream+ return 1+ fi++ # Re-feature instance 2 while it is already live, then approve.+ local response success+ response=$(add_featured_server "${OWNCAST_PORT}" "${OWNCAST2_URL}")+ success=$(echo "${response}" | jq -r '.success // false' 2>/dev/null)+ if [[ "${success}" != "true" ]]; then+ log_error "TEST 9 FAILED: re-feature add not accepted: $(echo "${response}" | jq -r '.message // ""')"+ stop_test_stream+ return 1+ fi+ log_info "Approving the re-feature request on instance 2..."+ approve_featured_request "${OWNCAST2_PORT}" "${instance1_actor}" > /dev/null+ if ! wait_for_follow_status "${OWNCAST_PORT}" "${OWNCAST2_URL}" "accepted" 40; then+ log_error "TEST 9 FAILED: re-feature follow not accepted (the unfeature Undo may not have cleared the prior follower)"+ stop_test_stream+ return 1+ fi++ # Instance 1 must show instance 2 live promptly -- this can only come from+ # the Accept's carried status, since instance 1 just started following and+ # the next periodic ping is minutes away.+ local online="" json+ waited=0+ while [[ ${waited} -lt 30 ]]; do+ json=$(get_featured_servers "${OWNCAST_PORT}" admin)+ online=$(server_field "${json}" "${OWNCAST2_URL}" isOnline)+ if [[ "${online}" == "true" ]]; then+ break+ fi+ sleep 3+ waited=$((waited + 3))+ done++ if [[ "${online}" != "true" ]]; then+ log_error "TEST 9 FAILED: instance 2 not shown live on instance 1 within 30s of acceptance"+ log_error "Server record: $(server_object "${json}" "${OWNCAST2_URL}")"+ stop_test_stream+ return 1+ fi++ local title+ title=$(server_field "$(get_featured_servers "${OWNCAST_PORT}" admin)" "${OWNCAST2_URL}" streamTitle)+ stop_test_stream+ log_test "TEST 9 PASSED: featured-while-live shown online ~${waited}s after accept (title='${title}')"+ return 0+}+# ==========================# Results# ==========================@@ -867,6 +988,8 @@ main() {echo ""if test_featuring_server_hidden_from_followers; then passed=$((passed + 1)); else failed=$((failed + 1)); fiecho ""+ if test_feature_while_already_live; then passed=$((passed + 1)); else failed=$((failed + 1)); fi+ echo ""print_results "${passed}" "${failed}"diff --git a/webserver/handlers/admin/federatedservers.go b/webserver/handlers/admin/federatedservers.goindex 0050b0c155..d9e0780fd6 100644--- a/webserver/handlers/admin/federatedservers.go+++ b/webserver/handlers/admin/federatedservers.go@@ -155,12 +155,32 @@ func (a *Admin) RemoveFederatedServer(w http.ResponseWriter, r *http.Request, idreturn}+ // Look up the server's IRI before deleting so we can tell it to drop us+ // as a follower.+ var iri string+ if servers, err := repo.GetFederatedServers(); err == nil {+ for _, srv := range servers {+ if srv.ID == int64(id) {+ iri = srv.IRI+ break+ }+ }+ }+if err := repo.RemoveFederatedServer(int64(id)); err != nil {log.Errorf("Failed to remove federated server with ID %d: %v", id, err)webutils.WriteSimpleResponse(w, false, "Failed to remove federated server: "+err.Error())return}+ // Send an Undo of our Follow so the remote stops treating us as a follower.+ // Best-effort: the local removal already succeeded.+ if iri != "" {+ if err := a.activitypub.Outbox().SendUnfollowRequestToOwncastServerURL(iri); err != nil {+ log.Warnf("Unfeatured %s but failed to send unfollow: %v", iri, err)+ }+ }+log.Infof("Removed federated server with ID: %d", id)webutils.WriteSimpleResponse(w, true, "Federated server removed successfully")}diff --git a/webserver/handlers/admin/followers.go b/webserver/handlers/admin/followers.goindex f59fbfc7d2..e3067a0400 100644--- a/webserver/handlers/admin/followers.go+++ b/webserver/handlers/admin/followers.go@@ -48,8 +48,11 @@ func (a *Admin) ApproveFollower(w http.ResponseWriter, r *http.Request) {go a.webhooks.SendFediverseEngagementFollowEvent(*approval.ActorIRI)}- // Send the approval to the follow requestor.- if err := requests.SendFollowAccept(a.activitypub.Workerpool(), followRequest.Inbox, followRequest.RequestObject, localAccountName, a.apBuilder, a.apSigner); err != nil {+ // Send the approval to the follow requestor, including our current+ // stream status so a featured-streams follower approved while we are+ // already live shows us live immediately.+ streamActive := a.stream.GetStatus().Online+ if err := requests.SendFollowAccept(a.activitypub.Workerpool(), followRequest.Inbox, followRequest.RequestObject, localAccountName, a.apBuilder, a.apSigner, a.configRepository, streamActive); err != nil {webutils.WriteSimpleResponse(w, false, err.Error())return}