tools

package
v1.17.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 7, 2026 License: MIT Imports: 33 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	PageNotFoundErrMsg     = "This page does not exist."
	CourseNotFoundErrMsg   = "We couldn't find the course you were looking for."
	StreamNotFoundErrMsg   = "We couldn't find the stream you were looking for."
	ForbiddenGenericErrMsg = "You don't have permissions to access this resource. " +
		"Please reach out if this seems wrong :)"
	ForbiddenStreamAccess = "You don't have permissions to access this stream. " +
		"Please make sure to use the correct login."
	ForbiddenCourseAccess = "You don't have permissions to access this course. " +
		"Please make sure to use the correct login."
)
View Source
const (
	CSVSep = ","
	CSVLb  = "\n\r"
)
View Source
const AccessTokenTTL = time.Minute * 15

AccessTokenTTL is how long a bearer access token stays valid. Clients hold them in memory and re-mint from the session cookie, so they are far shorter-lived.

View Source
const SessionTTL = time.Hour * 24 * 7

SessionTTL is how long a browser session cookie stays valid.

Variables

View Source
var (
	ErrUnbalancedTags = errors.New("unbalanced tags")
	TagExpr           = regexp.MustCompile("<(/?)([A-Za-z0-9]+).*?>")
	EntityExpr        = regexp.MustCompile("&#?[A-Za-z0-9]+;")
)
View Source
var CookieSecure = false

CookieSecure sets whether to use secure cookies or not, defaults to false in dev mode, true in production

View Source
var ErrMeiliNotConfigured = errors.New("meilisearch is not configured")
View Source
var VersionTag = "development"

VersionTag is the build's version, set from main via ldflags, "development" when unstamped. Here rather than in web so the v2 API need not import the frontend it is replacing.

Functions

func AdminOfCourse

func AdminOfCourse(next http.Handler) http.Handler

AdminOfCourse checks if the user is an admin of the course or admin. If not, answers Forbidden.

func Cookie(r *http.Request, name string) (string, error)

Cookie returns the unescaped value of the named cookie.

func CourseListContains

func CourseListContains(courses []model.Course, courseId uint) bool

CourseListContains checks whether courses contain a course with a given courseId

func CreateAccessToken added in v1.7.10

func CreateAccessToken(user uint, samlSubjectID *string) (string, error)

CreateAccessToken mints a short-lived `Authorization: Bearer` credential for the v2 API, signed with the same key and claims as a session cookie.

func DownloadFileName added in v1.11.1

func DownloadFileName(courseSlug string, s *model.Stream, version string) string

DownloadFileName returns a human-friendly file name for downloads of s, like "eidi_Graphs-and-Trees_2025-10-14_COMB.mp4". Streams usually have no name, which gives "eidi_2025-10-14_COMB.mp4". version (COMB, CAM or PRES) is part of the name so that the camera and presentation downloads of one lecture don't overwrite each other. Anything that could break a Content-Disposition header or a path on the user's disk is replaced, and the parts are bounded in length. It returns "" when there is nothing to name the file after, and the edge falls back to the stream id.

func GetCacheItem

func GetCacheItem(key string) (interface{}, bool)

GetCacheItem returns the value of the key if it exists in the cache. (nil, err) otherwise

func InitBranding

func InitBranding()

InitBranding initializes the global branding configuration variable `BrandingCfg`. If the config file doesn't exist it will be set to the result of `getDefaultBranding()`.

func InitCronService

func InitCronService()

InitCronService creates an instance of CronService

func LoadConfig

func LoadConfig()

func LoggedIn

func LoggedIn(next http.Handler) http.Handler

LoggedIn is a middleware that checks if the user is logged in and redirects to the login page if not

func MaskEmail

func MaskEmail(email string) (masked string, err error)

func MaskLogin

func MaskLogin(login string) (masked string)

MaskLogin masks lrzIds by replacing digits with *

func RenderErrorPage

func RenderErrorPage(w http.ResponseWriter, r *http.Request, status int, message string)

RenderErrorPage answers with the given status and message. A page request gets the SPA shell, which renders the error; under /api/ the caller is a script, which gets the message as plain text.

func SearchCourses

func SearchCourses(q string, filter string) *meilisearch.SearchResponse

func SendAccountInvite added in v1.8.0

func SendAccountInvite(ctx context.Context, daoWrapper dao.DaoWrapper, email string) error

SendAccountInvite queues the mail inviting someone to set a password on a new account. The register link is single-use, so calling this twice invalidates the first mail's.

func SetCacheItem

func SetCacheItem(key string, value interface{}, ttl time.Duration)

SetCacheItem adds the key and value to the cache with the given expiration time.

func SetCookie added in v1.15.0

func SetCookie(w http.ResponseWriter, name, value string, maxAge int, secure bool)

SetCookie sets an HttpOnly cookie for the whole site. The value is query-escaped and Cookie unescapes it, as the cookies of the gin era were, so a cookie set before the migration still reads back (redirURL holds a path with slashes and a query).

func SetErrorPageRenderer added in v1.10.0

func SetErrorPageRenderer(f func(w http.ResponseWriter, r *http.Request, status int, message string))

SetErrorPageRenderer sets how RenderErrorPage answers a request for a page.

func SetJWTKeyForTest added in v1.10.0

func SetJWTKeyForTest(k *rsa.PrivateKey) (restore func())

SetJWTKeyForTest installs the key playlists and tokens are signed with, for tests of code that signs without booting the configuration. It returns what undoes it.

func SetSignedPlaylists

func SetSignedPlaylists(s *model.Stream, user *model.User, allowDownloading bool) error

SetSignedPlaylists adds a signed jwt to all available playlist urls that indicates that the user is allowed to consume the playlist. The method assumes that the user has been pre-authorized and doesn't check for permissions. Downloads signed through it are not named after a course, use SetSignedPlaylistsForCourse where downloads may be allowed.

func SetSignedPlaylistsForCourse added in v1.11.1

func SetSignedPlaylistsForCourse(s *model.Stream, user *model.User, courseSlug string, allowDownloading bool) error

SetSignedPlaylistsForCourse is SetSignedPlaylists that also names downloads after the course (courseSlug), as the stream doesn't know it. The slug is only used when allowDownloading is set.

func StartSession

func StartSession(w http.ResponseWriter, data *SessionData)

func Truncate

func Truncate(input string, length int) string

Truncate strips an input that can contain html to length.

func TruncateHtml

func TruncateHtml(buf []byte, maxlen int, ellipsis string) ([]byte, error)

TruncateHtml will truncate a given byte slice to a maximum of maxlen visible characters and optionally append ellipsis. HTML tags are automatically closed generating valid truncated HTML. Based on: https://github.com/mborgerson/GoTruncateHtml

func WithTUMLiveContext added in v1.15.0

func WithTUMLiveContext(r *http.Request, c TUMLiveContext) *http.Request

WithTUMLiveContext returns r carrying c, replacing any context an earlier middleware set. InitContext sets the first one; InitCourse and InitStream replace it with the course and stream they found.

func WriteData added in v1.15.0

func WriteData(w http.ResponseWriter, status int, contentType string, body []byte)

WriteData answers with body as the given content type.

func WriteJSON added in v1.15.0

func WriteJSON(w http.ResponseWriter, status int, v any)

WriteJSON answers with v as JSON. Marshalled up front, so a value that cannot be encoded is a 500 rather than a truncated body behind a 200.

func WriteText added in v1.15.0

func WriteText(w http.ResponseWriter, status int, text string)

WriteText answers with a plain-text body.

Types

type Branding

type Branding struct {
	Title       string `yaml:"title"`
	Description string `yaml:"description"`
}
var BrandingCfg Branding

type Config

type Config struct {
	Mail MailConfig `yaml:"mail"`
	Db   struct {
		User     string `yaml:"user"`
		Password string `yaml:"password"`
		Database string `yaml:"database"`
		Host     string `yaml:"host"`
		Port     uint   `yaml:"port"`
		// MaxOpenConns caps the pool. Zero keeps the default of 80, kept below
		// the server's max_connections so a burst queues instead of failing.
		MaxOpenConns int `yaml:"maxOpenConns"`
	} `yaml:"db"`
	Campus struct {
		Base        string   `yaml:"base"`
		Tokens      []string `yaml:"tokens"`
		CampusProxy *struct {
			Host   string `yaml:"host"`
			Scheme string `yaml:"scheme"`
		} `yaml:"campusProxy"`
		RelevantOrgs *[]string `yaml:"relevantOrgs"`
	} `yaml:"campus"`
	Ldap struct {
		URL         string `yaml:"url"`
		User        string `yaml:"user"`
		Password    string `yaml:"password"`
		BaseDn      string `yaml:"baseDn"`
		UserDn      string `yaml:"userDn"`
		UseForLogin bool   `yaml:"useForLogin"`
	} `yaml:"ldap"`
	Saml *struct {
		IdpMetadataURL string   `yaml:"idpMetadataURL"`
		Cert           string   `yaml:"cert"`
		Privkey        string   `yaml:"privkey"`
		EntityID       string   `yaml:"entityID"`
		RootURLs       []string `yaml:"rootURL"`
		IdpName        string   `yaml:"idpName"`
		IdpColor       string   `yaml:"idpColor"`
	} `yaml:"saml"`
	Paths struct {
		Static string `yaml:"static"`
		Mass   string `yaml:"mass"`
		// Vod is the directory the edge serves as /vod/ (the runner's STORAGE_PATH), mounted
		// into this server for reaping the media of deleted streams. Optional: empty
		// disables reaping.
		Vod      string `yaml:"vod"`
		Branding string `yaml:"branding"`
	} `yaml:"paths"`
	Auths struct {
		SmpUser     string `yaml:"smpUser"` // todo, do we need this? Should this be in the lecture_halls table?
		SmpPassword string `yaml:"smpPassword"`
		PwrCrtlAuth string `yaml:"pwrCrtlAuth"`
		CamAuth     string `yaml:"camAuth"`
		CamAuthSony string `yaml:"camAuthSony"`
	} `yaml:"auths"`
	Alerts *struct {
		Matrix *struct {
			Username    string `yaml:"username"`
			Password    string `yaml:"password"`
			Homeserver  string `yaml:"homeserver"`
			LogRoomID   string `yaml:"logRoomID"`
			AlertRoomID string `yaml:"alertRoomId"`
		} `yaml:"matrix"`
	} `yaml:"alerts"`
	// RunnerTLS switches the gRPC link to the runners to mutual TLS. Leave it out in
	// development. The certificate must carry the name the runners dial (GOCAST_SERVER).
	RunnerTLS    mtls.Files `yaml:"runnerTLS"`
	VoiceService *struct {
		Host      string `yaml:"host"`
		Port      string `yaml:"port"`
		AuthToken string `yaml:"authToken"`
	}
	IngestBase string  `yaml:"ingestBase"`
	WebUrl     string  `yaml:"webUrl"`
	JWTKey     *string `yaml:"jwtKey"`
	Meili      *struct {
		Host   string `yaml:"host"`
		ApiKey string `yaml:"apiKey"`
	} `yaml:"meili"`
	// MetricsPort is the port the Prometheus endpoint listens on, separate from the
	// web port so the metrics are not exposed to the internet. Empty disables it.
	MetricsPort      string   `yaml:"metricsPort"`
	VodURLTemplate   string   `yaml:"vodURLTemplate"`
	CanonicalURL     string   `yaml:"canonicalURL"`
	WikiURL          string   `yaml:"wikiURL"`
	RtmpProxyURL     string   `yaml:"rtmpProxyURL"`
	RtmpProxyService string   `yaml:"rtmpProxyService"`
	AllowedReactions []string `yaml:"allowedReactions"`
}
var (
	Cfg Config
	Loc *time.Location
)

func (Config) GetJWTKey

func (Config) GetJWTKey() *rsa.PrivateKey

func (Config) GetMeiliClient

func (c Config) GetMeiliClient() (meilisearch.ServiceManager, error)

type CronService

type CronService struct {
	// contains filtered or unexported fields
}
var Cron *CronService

Cron is the global CronService

func (*CronService) AddFunc

func (c *CronService) AddFunc(name string, fn func(), spec string) error

AddFunc creates a cronJob fn running at the interval specified by spec. The job can be referenced by name.

func (*CronService) ListCronJobs

func (c *CronService) ListCronJobs() []string

ListCronJobs returns a []string with the names of all cronjobs

func (*CronService) Run

func (c *CronService) Run()

Run starts the CronService

func (*CronService) RunJob

func (c *CronService) RunJob(name string)

RunJob executes the cronJob identified by name even when it's not due. Invalid names are ignored silently.

type ExportDataEntry

type ExportDataEntry struct {
	Name  string
	XName string
	YName string
	Data  []dao.Stat
}

type ExportStatsContainer

type ExportStatsContainer struct {
	// contains filtered or unexported fields
}

func (ExportStatsContainer) AddDataEntry

func (ExportStatsContainer) ExportCsv

func (e ExportStatsContainer) ExportCsv() string

func (ExportStatsContainer) ExportJson

func (e ExportStatsContainer) ExportJson() []map[string]any

type JWTClaims

type JWTClaims struct {
	*jwt.RegisteredClaims
	UserID        uint
	SamlSubjectID *string // identifier of the SAML session (if any)
}

JWTClaims are the claims contained in a session

type JWTPlaylistClaims

type JWTPlaylistClaims struct {
	jwt.RegisteredClaims
	UserID   uint
	Playlist string
	Download bool
	StreamID string
	CourseID string
	// FileName is what a download is saved as. The edge has no database, so the
	// human-friendly name has to travel in the token. Only set when downloads are
	// allowed, since nothing else reads it; also empty for tokens issued before it
	// existed, where the edge falls back to the stream id.
	FileName string `json:",omitempty"`
}

type MailConfig

type MailConfig struct {
	Sender    string `yaml:"sender"`
	Server    string `yaml:"server"`
	SMIMECert string `yaml:"SMIMECert"`
	SMIMEKey  string `yaml:"SMIMEKey"`
	// SMIMEKeyPassword unlocks an encrypted SMIMEKey; leave empty for an unencrypted one.
	SMIMEKeyPassword  string `yaml:"SMIMEKeyPassword"`
	MaxMailsPerMinute int    `yaml:"maxMailsPerMinute"`
}

type Mailer

type Mailer struct {
	Dao               dao.DaoWrapper
	MaxMailsPerMinute int
}

func NewMailer

func NewMailer(dao dao.DaoWrapper, maxMailsPerMinute int) *Mailer

func (*Mailer) Run

func (m *Mailer) Run()

type MeiliCourse

type MeiliCourse struct {
	ID           uint   `json:"ID"`
	Name         string `json:"name"`
	Slug         string `json:"slug"`
	Year         int    `json:"year"`
	TeachingTerm string `json:"semester"`
	Visibility   string `json:"visibility"`
}

type MeiliExporter

type MeiliExporter struct {
	// contains filtered or unexported fields
}

func NewMeiliExporter

func NewMeiliExporter(d dao.DaoWrapper) *MeiliExporter

func (*MeiliExporter) Export

func (m *MeiliExporter) Export()

Export exports all relevant search data to MeiliSearch Instance

func (*MeiliExporter) SetIndexSettings

func (m *MeiliExporter) SetIndexSettings()

type MeiliSearchInterface

type MeiliSearchInterface interface {
	SearchSubtitles(q string, streamID uint) *meilisearch.SearchResponse
	Search(q string, limit int64, searchType int, courseFilter string, streamFilter string, subtitleFilter string) *meilisearch.MultiSearchResponse
}

func NewMeiliSearchFunctions

func NewMeiliSearchFunctions() MeiliSearchInterface

type MeiliStream

type MeiliStream struct {
	ID           uint   `json:"ID"`
	Name         string `json:"name"`
	Description  string `json:"description"`
	CourseName   string `json:"courseName"`
	Year         int    `json:"year"`
	TeachingTerm string `json:"semester"`
	CourseID     uint   `json:"courseID"`
	Private      uint   `json:"private"`
	Visibility   string `json:"visibility"` // corresponds to the visibility of the course
}

type MeiliSubtitles

type MeiliSubtitles struct {
	ID        string `json:"ID"` // meili id: streamID + timestamp
	StreamID  uint   `json:"streamID"`
	Timestamp int64  `json:"timestamp"`
	TextPrev  string `json:"textPrev"` // the previous subtitle line
	Text      string `json:"text"`
	TextNext  string `json:"textNext"` // the next subtitle line
}

type Middleware added in v1.15.0

type Middleware func(http.Handler) http.Handler

Middleware wraps a handler. It ends a request by not calling next, which is all "aborting" means here.

func InitContext

func InitContext(daoWrapper dao.DaoWrapper) Middleware

InitContext puts the signed-in user, if any, on the request as its TUMLiveContext. Every route behind it can rely on the context existing; a missing or broken session is an empty context, not an error.

func InitCourse

func InitCourse(wrapper dao.DaoWrapper) Middleware

InitCourse loads the course named by the route's courseID, or year, teachingTerm and slug, and refuses a caller who may not see it.

func InitStream

func InitStream(wrapper dao.DaoWrapper) Middleware

InitStream loads the stream named by the route's streamID, and refuses a caller who may not watch it.

func RequirePermission added in v1.7.10

func RequirePermission(p model.Permission) Middleware

RequirePermission answers Forbidden unless the caller holds the permission. A route group states the capability it needs rather than the role that has it, so moving a capability between roles is a change to model.rolePermissions alone.

type RequestError

type RequestError struct {
	Status        int
	CustomMessage string
	Err           error
}

func (RequestError) Error

func (r RequestError) Error() string

func (RequestError) ToResponse

func (r RequestError) ToResponse() map[string]any

type Router added in v1.15.0

type Router struct {
	// contains filtered or unexported fields
}

Router is an http.ServeMux with middleware groups, which is all of gin the site used. Patterns are ServeMux's: "GET /w/{slug}/{streamID}", read back with r.PathValue.

Middleware applies to the routes registered after it, in the order it was added, and a group starts from a copy of its parent's: the same rules as gin's, so moving a route between groups changes what runs in front of it exactly as it did.

func NewRouter added in v1.15.0

func NewRouter() *Router

func (*Router) Group added in v1.15.0

func (r *Router) Group(mw ...Middleware) *Router

Group returns a router on the same mux whose routes also run the given middleware. Middleware added to the group later does not reach the parent's routes.

func (*Router) Handle added in v1.15.0

func (r *Router) Handle(pattern string, h http.Handler)

Handle registers h behind the router's middleware. Like ServeMux it panics when the pattern conflicts with an earlier one, at startup rather than on a request.

func (*Router) HandleFunc added in v1.15.0

func (r *Router) HandleFunc(pattern string, h http.HandlerFunc)

func (*Router) NotFound added in v1.15.0

func (r *Router) NotFound(h http.Handler)

NotFound serves h, behind the router's middleware, for every request no other pattern takes. A path that only differs from a route by a trailing slash is redirected to the route first, as gin did: 301 for GET, 307 for the rest so a form post is not turned into a GET.

func (*Router) ServeHTTP added in v1.15.0

func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)

func (*Router) Use added in v1.15.0

func (r *Router) Use(mw ...Middleware)

Use adds middleware for the routes registered from now on.

type SessionData

type SessionData struct {
	Userid        uint
	SamlSubjectID *string
}

type TUMLiveContext

type TUMLiveContext struct {
	User          *model.User
	Course        *model.Course
	Stream        *model.Stream
	SamlSubjectID *string
}

func GetTUMLiveContext added in v1.15.0

func GetTUMLiveContext(r *http.Request) (TUMLiveContext, bool)

GetTUMLiveContext returns the context InitContext set on r. It is missing on the static paths InitContext skips and wherever a route was registered without it.

func (*TUMLiveContext) UserIsAdmin

func (c *TUMLiveContext) UserIsAdmin() bool

type TestEnvPolicy added in v1.11.1

type TestEnvPolicy struct {
	Enabled bool
	// contains filtered or unexported fields
}

TestEnvPolicy restricts what a server booted against a copy of the production database may do to the outside world. The zero value is production: everything allowed.

var TestEnv TestEnvPolicy

TestEnv is the process-wide policy, set once at boot from the command line.

func NewTestEnvPolicy added in v1.11.1

func NewTestEnvPolicy(enabled bool, streamCourses string) (TestEnvPolicy, error)

NewTestEnvPolicy builds the policy from the --test-env and --stream-courses flags. Course IDs without --test-env are rejected rather than ignored: a stray flag in a production unit file would otherwise look like it restricts streaming and silently not.

func (TestEnvPolicy) AllowsStream added in v1.11.1

func (p TestEnvPolicy) AllowsStream(courseID uint) bool

AllowsStream reports whether a stream of the given course may be started.

func (TestEnvPolicy) StreamCourseIDs added in v1.11.1

func (p TestEnvPolicy) StreamCourseIDs() []uint

StreamCourseIDs returns the allowlisted course IDs, for the boot log.

Directories

Path Synopsis
Package mediareap works out which files on disk belong only to soft-deleted streams, so an admin can see them listed and then reap them.
Package mediareap works out which files on disk belong only to soft-deleted streams, so an admin can see them listed and then reap them.
Package safepath builds filesystem paths from untrusted input, such as user-supplied course names, without letting that input escape the directory it is supposed to live in.
Package safepath builds filesystem paths from untrusted input, such as user-supplied course names, without letting that input escape the directory it is supposed to live in.
Package timing provides time calculation functions used in TUM Live
Package timing provides time calculation functions used in TUM Live

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL