Skip to content

Take control over your live stream video by running it yourself. Streaming + chat out of the box.

8.2 KB
Raw Blame
package controllers

import (
	"fmt"
	"net/http"
	"net/url"

	log "github.com/sirupsen/logrus"

	"github.com/owncast/owncast/config"
	"github.com/owncast/owncast/services/activitypub/requests"
)

const (
	// softwareName is the name of this server software reported in node info responses.
	softwareName = "owncast"
	// protocolActivityPub is the federation protocol name reported in node info responses.
	protocolActivityPub = "activitypub"
)

// NodeInfoController returns the V1 node info response.
func (c *Controllers) NodeInfoController(w http.ResponseWriter, r *http.Request) {
	type links struct {
		Rel  string `json:"rel"`
		Href string `json:"href"`
	}

	type response struct {
		Links []links `json:"links"`
	}

	if !c.configRepository.GetFederationEnabled() {
		w.WriteHeader(http.StatusMethodNotAllowed)
		return
	}

	v2, err := c.builder.GetCanonicalServerURL()
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	v2.Path = "nodeinfo/2.0"

	res := response{
		Links: []links{
			{
				Rel:  "http://nodeinfo.diaspora.software/ns/schema/2.0",
				Href: v2.String(),
			},
		},
	}
	if err := c.writeResponse(res, w); err != nil {
		log.Errorln(err)
	}
}

// NodeInfoV2Controller returns the V2 node info response.
func (c *Controllers) NodeInfoV2Controller(w http.ResponseWriter, r *http.Request) {
	type federation struct {
		Username        string `json:"username"`
		FeaturedStreams int    `json:"featured_streams"`
	}
	type metadata struct {
		ChatEnabled bool       `json:"chat_enabled"`
		Federation  federation `json:"federation"`
	}
	type services struct {
		Outbound []string `json:"outbound"`
		Inbound  []string `json:"inbound"`
	}
	type software struct {
		Name    string `json:"name"`
		Version string `json:"version"`
	}
	type users struct {
		Total          int `json:"total"`
		ActiveMonth    int `json:"activeMonth"`
		ActiveHalfyear int `json:"activeHalfyear"`
	}
	type usage struct {
		Users      users `json:"users"`
		LocalPosts int   `json:"localPosts"`
	}
	type response struct {
		Version           string   `json:"version"`
		Services          services `json:"services"`
		Software          software `json:"software"`
		Protocols         []string `json:"protocols"`
		Usage             usage    `json:"usage"`
		OpenRegistrations bool     `json:"openRegistrations"`
		Metadata          metadata `json:"metadata"`
	}

	if !c.configRepository.GetFederationEnabled() {
		w.WriteHeader(http.StatusMethodNotAllowed)
		return
	}

	localPostCount, _ := c.persistence.GetLocalPostCount()

	res := response{
		Version: "2.0",
		Services: services{
			Inbound:  []string{},
			Outbound: []string{},
		},
		Software: software{
			Name:    softwareName,
			Version: config.VersionNumber,
		},
		Usage: usage{
			Users: users{
				Total:          1,
				ActiveMonth:    1,
				ActiveHalfyear: 1,
			},
			LocalPosts: int(localPostCount),
		},
		OpenRegistrations: false,
		Protocols:         []string{protocolActivityPub},
		Metadata: metadata{
			ChatEnabled: !c.configRepository.GetChatDisabled(),
			Federation: federation{
				Username:        c.configRepository.GetFederationUsername(),
				FeaturedStreams: 1,
			},
		},
	}

	if err := c.writeResponse(res, w); err != nil {
		log.Errorln(err)
	}
}

// XNodeInfo2Controller returns the x-nodeinfo2.
func (c *Controllers) XNodeInfo2Controller(w http.ResponseWriter, r *http.Request) {
	type Organization struct {
		Name    string `json:"name"`
		Contact string `json:"contact"`
	}
	type Server struct {
		BaseURL  string `json:"baseUrl"`
		Version  string `json:"version"`
		Name     string `json:"name"`
		Software string `json:"software"`
	}
	type Services struct {
		Outbound []string `json:"outbound"`
		Inbound  []string `json:"inbound"`
	}
	type Users struct {
		ActiveWeek     int `json:"activeWeek"`
		Total          int `json:"total"`
		ActiveMonth    int `json:"activeMonth"`
		ActiveHalfyear int `json:"activeHalfyear"`
	}
	type Usage struct {
		Users         Users `json:"users"`
		LocalPosts    int   `json:"localPosts"`
		LocalComments int   `json:"localComments"`
	}
	type response struct {
		Server            Server       `json:"server"`
		Organization      Organization `json:"organization"`
		Version           string       `json:"version"`
		Services          Services     `json:"services"`
		Protocols         []string     `json:"protocols"`
		Usage             Usage        `json:"usage"`
		OpenRegistrations bool         `json:"openRegistrations"`
	}

	if !c.configRepository.GetFederationEnabled() {
		w.WriteHeader(http.StatusMethodNotAllowed)
		return
	}

	serverURL := c.configRepository.GetServerURL()
	if serverURL == "" {
		w.WriteHeader(http.StatusNotFound)
		return
	}

	localPostCount, _ := c.persistence.GetLocalPostCount()

	res := &response{
		Organization: Organization{
			Name:    c.configRepository.GetServerName(),
			Contact: serverURL,
		},
		Server: Server{
			BaseURL:  serverURL,
			Version:  config.VersionNumber,
			Name:     softwareName,
			Software: softwareName,
		},
		Services: Services{
			Inbound:  []string{protocolActivityPub},
			Outbound: []string{protocolActivityPub},
		},
		Protocols: []string{protocolActivityPub},
		Version:   config.VersionNumber,
		Usage: Usage{
			Users: Users{
				ActiveWeek:     1,
				Total:          1,
				ActiveMonth:    1,
				ActiveHalfyear: 1,
			},

			LocalPosts:    int(localPostCount),
			LocalComments: 0,
		},
	}

	if err := c.writeResponse(res, w); err != nil {
		log.Errorln(err)
	}
}

// InstanceV1Controller returns the v1 instance details.
func (c *Controllers) InstanceV1Controller(w http.ResponseWriter, r *http.Request) {
	type Stats struct {
		UserCount   int `json:"user_count"`
		StatusCount int `json:"status_count"`
		DomainCount int `json:"domain_count"`
	}
	type response struct {
		URI              string   `json:"uri"`
		Title            string   `json:"title"`
		ShortDescription string   `json:"short_description"`
		Description      string   `json:"description"`
		Version          string   `json:"version"`
		Thumbnail        string   `json:"thumbnail"`
		Languages        []string `json:"languages"`
		Stats            Stats    `json:"stats"`
		Registrations    bool     `json:"registrations"`
		ApprovalRequired bool     `json:"approval_required"`
		InvitesEnabled   bool     `json:"invites_enabled"`
	}

	if !c.configRepository.GetFederationEnabled() {
		w.WriteHeader(http.StatusMethodNotAllowed)
		return
	}

	serverURL := c.configRepository.GetServerURL()
	if serverURL == "" {
		w.WriteHeader(http.StatusNotFound)
		return
	}

	thumbnail, err := url.Parse(serverURL)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	thumbnail.Path = "/logo/external"
	localPostCount, _ := c.persistence.GetLocalPostCount()

	res := response{
		URI:              serverURL,
		Title:            c.configRepository.GetServerName(),
		ShortDescription: c.configRepository.GetServerSummary(),
		Description:      c.configRepository.GetServerSummary(),
		Version:          config.GetReleaseString(),
		Stats: Stats{
			UserCount:   1,
			StatusCount: int(localPostCount),
			DomainCount: 0,
		},
		Thumbnail:        thumbnail.String(),
		Registrations:    false,
		ApprovalRequired: false,
		InvitesEnabled:   false,
	}

	if err := c.writeResponse(res, w); err != nil {
		log.Errorln(err)
	}
}

func (c *Controllers) writeResponse(payload interface{}, w http.ResponseWriter) error {
	accountName := c.configRepository.GetDefaultFederationUsername()
	actorIRI := c.builder.MakeLocalIRIForAccount(accountName)
	publicKey := c.signer.GetPublicKey(actorIRI)

	return requests.WritePayloadResponse(payload, w, publicKey, c.signer)
}

// HostMetaController points to webfinger.
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 := c.builder.GetCanonicalServerURL()
	if err != nil {
		w.WriteHeader(http.StatusNotFound)
		return
	}

	res := fmt.Sprintf(`<?xml version="1.0" encoding="UTF-8"?>
	<XRD xmlns="http://docs.oasis-open.org/ns/xri/xrd-1.0">
		<Link rel="lrdd" type="application/json" template="%s/.well-known/webfinger?resource={uri}"/>
	</XRD>`, serverURL.String())

	if _, err := w.Write([]byte(res)); err != nil {
		log.Errorln(err)
	}
}