Init commit

This commit is contained in:
ShreejitPanchal
2026-05-19 19:56:02 +08:00
commit 6601501eff
4047 changed files with 2185372 additions and 0 deletions

View File

@@ -0,0 +1,95 @@
import { HttpStatusCode } from '@peertube/peertube-models'
import express from 'express'
import { logger } from '../../helpers/logger.js'
import { ACCEPT_HEADERS } from '../../initializers/constants.js'
import { VideoHtml } from './shared/video-html.js'
import { PlaylistHtml } from './shared/playlist-html.js'
import { ActorHtml } from './shared/actor-html.js'
import { PageHtml } from './shared/page-html.js'
class ClientHtml {
static invalidateCache () {
PageHtml.invalidateCache()
}
static getDefaultHTMLPage (req: express.Request, res: express.Response, paramLang?: string) {
return PageHtml.getDefaultHTML(req, res, paramLang)
}
// ---------------------------------------------------------------------------
static getWatchHTMLPage (videoId: string, req: express.Request, res: express.Response) {
return VideoHtml.getWatchVideoHTML(videoId, req, res)
}
static getVideoEmbedHTML (videoId: string) {
return VideoHtml.getEmbedVideoHTML(videoId)
}
// ---------------------------------------------------------------------------
static getWatchPlaylistHTMLPage (videoPlaylistId: string, req: express.Request, res: express.Response) {
return PlaylistHtml.getWatchPlaylistHTML(videoPlaylistId, req, res)
}
static getVideoPlaylistEmbedHTML (playlistId: string) {
return PlaylistHtml.getEmbedPlaylistHTML(playlistId)
}
// ---------------------------------------------------------------------------
static getAccountHTMLPage (handle: string, req: express.Request, res: express.Response) {
return ActorHtml.getAccountHTMLPage(handle, req, res)
}
static getVideoChannelHTMLPage (handle: string, req: express.Request, res: express.Response) {
return ActorHtml.getVideoChannelHTMLPage(handle, req, res)
}
static getActorHTMLPage (handle: string, req: express.Request, res: express.Response) {
return ActorHtml.getActorHTMLPage(handle, req, res)
}
}
function sendHTML (html: string, res: express.Response, localizedHTML = false) {
res.set('Content-Type', 'text/html; charset=UTF-8')
res.set('Cache-Control', 'max-age=0, no-cache, must-revalidate')
if (localizedHTML) {
res.set('Vary', 'Accept-Language')
}
return res.send(html)
}
async function serveIndexHTML (req: express.Request, res: express.Response) {
if (req.accepts(ACCEPT_HEADERS) === 'html' || !req.headers.accept) {
try {
await generateHTMLPage(req, res, req.params.language)
return
} catch (err) {
logger.error('Cannot generate HTML page.', { err })
return res.status(HttpStatusCode.INTERNAL_SERVER_ERROR_500).end()
}
}
return res.status(HttpStatusCode.NOT_ACCEPTABLE_406).end()
}
// ---------------------------------------------------------------------------
export {
ClientHtml,
sendHTML,
serveIndexHTML
}
// ---------------------------------------------------------------------------
// Private
// ---------------------------------------------------------------------------
async function generateHTMLPage (req: express.Request, res: express.Response, paramLang?: string) {
const html = await ClientHtml.getDefaultHTMLPage(req, res, paramLang)
return sendHTML(html, res, true)
}

View File

@@ -0,0 +1,119 @@
import { escapeHTML, maxBy } from '@peertube/peertube-core-utils'
import { HttpStatusCode } from '@peertube/peertube-models'
import { getChannelRSSFeeds, getDefaultRSSFeeds } from '@server/lib/rss.js'
import { AccountModel } from '@server/models/account/account.js'
import { ActorImageModel } from '@server/models/actor/actor-image.js'
import { VideoChannelModel } from '@server/models/video/video-channel.js'
import { MAccountDefault, MChannelDefault } from '@server/types/models/index.js'
import express from 'express'
import { CONFIG } from '../../../initializers/config.js'
import { PageHtml } from './page-html.js'
import { TagsHtml, TagsOptions } from './tags-html.js'
export class ActorHtml {
static async getAccountHTMLPage (handle: string, req: express.Request, res: express.Response) {
const accountModelPromise = AccountModel.loadByHandle(handle)
return this.getAccountOrChannelHTMLPage({
loader: () => accountModelPromise,
getRSSFeeds: () => getDefaultRSSFeeds(req),
req,
res
})
}
static async getVideoChannelHTMLPage (handle: string, req: express.Request, res: express.Response) {
const videoChannel = await VideoChannelModel.loadByHandleAndPopulateAccount(handle)
return this.getAccountOrChannelHTMLPage({
loader: () => Promise.resolve(videoChannel),
getRSSFeeds: () => getChannelRSSFeeds(videoChannel, req),
req,
res
})
}
static async getActorHTMLPage (handle: string, req: express.Request, res: express.Response) {
const [ account, channel ] = await Promise.all([
AccountModel.loadByHandle(handle),
VideoChannelModel.loadByHandleAndPopulateAccount(handle)
])
return this.getAccountOrChannelHTMLPage({
loader: () => Promise.resolve(account || channel),
getRSSFeeds: () =>
account
? getDefaultRSSFeeds(req)
: getChannelRSSFeeds(channel, req),
req,
res
})
}
// ---------------------------------------------------------------------------
private static async getAccountOrChannelHTMLPage (options: {
loader: () => Promise<MAccountDefault | MChannelDefault>
getRSSFeeds: (entity: MAccountDefault | MChannelDefault) => TagsOptions['rssFeeds']
req: express.Request
res: express.Response
}) {
const { loader, getRSSFeeds, req, res } = options
const [ html, entity ] = await Promise.all([
PageHtml.getIndexHTML(req, res),
loader()
])
// Let Angular application handle errors
if (!entity) {
res.status(HttpStatusCode.NOT_FOUND_404)
return PageHtml.getIndexHTML(req, res)
}
const escapedTruncatedDescription = TagsHtml.buildEscapedTruncatedDescription(entity.description)
let customHTML = TagsHtml.addTitleTag(html, entity.getDisplayName())
customHTML = TagsHtml.addDescriptionTag(customHTML, escapedTruncatedDescription)
const url = entity.getClientUrl()
const siteName = CONFIG.INSTANCE.NAME
const title = entity.getDisplayName()
const avatar = maxBy(entity.Actor.Avatars, 'width')
const image = {
url: ActorImageModel.getImageUrl(avatar),
width: avatar?.width,
height: avatar?.height
}
const ogType = 'website'
const twitterCard = 'summary'
const schemaType = 'ProfilePage'
customHTML = await TagsHtml.addTags(customHTML, {
url,
escapedTitle: escapeHTML(title),
escapedSiteName: escapeHTML(siteName),
escapedTruncatedDescription,
relMe: TagsHtml.findRelMe(entity.description),
image,
ogType,
twitterCard,
schemaType,
jsonldProfile: {
createdAt: entity.createdAt,
updatedAt: entity.updatedAt
},
forbidIndexation: !entity.Actor.isLocal(),
embedIndexation: false,
rssFeeds: getRSSFeeds(entity)
}, {})
return customHTML
}
}

View File

@@ -0,0 +1,16 @@
import { MVideoPlaylist } from '@server/types/models/video/video-playlist.js'
import { MVideo } from '@server/types/models/video/video.js'
import { TagsHtml } from './tags-html.js'
export function buildEmptyEmbedHTML (options: {
html: string
playlist?: MVideoPlaylist
video?: MVideo
}) {
const { html, playlist, video } = options
let htmlResult = TagsHtml.addTitleTag(html)
htmlResult = TagsHtml.addDescriptionTag(htmlResult)
return TagsHtml.addTags(htmlResult, { forbidIndexation: true, embedIndexation: true }, { playlist, video })
}

View File

@@ -0,0 +1,5 @@
export * from './actor-html.js'
export * from './tags-html.js'
export * from './page-html.js'
export * from './playlist-html.js'
export * from './video-html.js'

View File

@@ -0,0 +1,181 @@
import { AVAILABLE_LOCALES, buildFileLocale, escapeHTML, getDefaultLocale, is18nLocale } from '@peertube/peertube-core-utils'
import { HTMLServerConfig } from '@peertube/peertube-models'
import { isTestOrDevInstance, root, sha256 } from '@peertube/peertube-node-utils'
import { setClientLanguageCookie } from '@server/helpers/i18n.js'
import { CONFIG } from '@server/initializers/config.js'
import { getDefaultRSSFeeds } from '@server/lib/rss.js'
import { getServerActor } from '@server/models/application/application.js'
import express from 'express'
import { pathExists } from 'fs-extra/esm'
import { readFile } from 'fs/promises'
import { join } from 'path'
import { logger } from '../../../helpers/logger.js'
import { CUSTOM_HTML_TAG_COMMENTS, FILES_CONTENT_HASH, PLUGIN_GLOBAL_CSS_PATH, WEBSERVER } from '../../../initializers/constants.js'
import { ServerConfigManager } from '../../server-config-manager.js'
import { TagsHtml } from './tags-html.js'
export class PageHtml {
private static htmlCache: { [path: string]: string } = {}
static invalidateCache () {
logger.info('Cleaning HTML cache.')
this.htmlCache = {}
}
static async getDefaultHTML (req: express.Request, res: express.Response, paramLang?: string) {
const html = await this.getIndexHTML(req, res, paramLang)
const serverActor = await getServerActor()
const openGraphImage = ServerConfigManager.Instance.getDefaultOpenGraph(serverActor)
let customHTML = TagsHtml.addTitleTag(html)
customHTML = TagsHtml.addDescriptionTag(customHTML)
const url = req.originalUrl === '/'
? WEBSERVER.URL
: WEBSERVER.URL + req.originalUrl
customHTML = await TagsHtml.addTags(customHTML, {
url,
escapedSiteName: escapeHTML(CONFIG.INSTANCE.NAME),
escapedTitle: escapeHTML(CONFIG.INSTANCE.NAME),
escapedTruncatedDescription: escapeHTML(CONFIG.INSTANCE.SHORT_DESCRIPTION),
relMe: url === WEBSERVER.URL
? TagsHtml.findRelMe(CONFIG.INSTANCE.DESCRIPTION)
: undefined,
image: openGraphImage
? { url: openGraphImage.fileUrl, width: openGraphImage.width, height: openGraphImage.height }
: undefined,
ogType: 'website',
twitterCard: 'summary_large_image',
forbidIndexation: false,
embedIndexation: false,
rssFeeds: getDefaultRSSFeeds(req)
}, {})
return customHTML
}
static async getEmbedHTML () {
const path = this.getEmbedHTMLPath()
// Disable HTML cache in dev mode because Vite can regenerate JS files
if (!isTestOrDevInstance() && this.htmlCache[path]) {
return this.htmlCache[path]
}
const buffer = await readFile(path)
const serverConfig = await ServerConfigManager.Instance.getHTMLServerConfig()
let html = buffer.toString()
html = await this.addAsyncPluginCSS(html)
html = this.addCustomCSS(html)
html = this.addServerConfig(html, serverConfig)
this.htmlCache[path] = html
return html
}
// ---------------------------------------------------------------------------
static async getIndexHTML (req: express.Request, res: express.Response, paramLang?: string) {
const path = this.getIndexHTMLPath(req, res, paramLang)
if (this.htmlCache[path]) return this.htmlCache[path]
const buffer = await readFile(path)
const serverConfig = await ServerConfigManager.Instance.getHTMLServerConfig()
let html = buffer.toString()
html = this.addManifestContentHash(html)
html = this.addCustomCSS(html)
html = this.addServerConfig(html, serverConfig)
html = await this.addAsyncPluginCSS(html)
this.htmlCache[path] = html
return html
}
// ---------------------------------------------------------------------------
// Private
// ---------------------------------------------------------------------------
private static getEmbedHTMLPath () {
return join(root(), 'client', 'dist', 'standalone', 'videos', 'embed.html')
}
private static getIndexHTMLPath (req: express.Request, res: express.Response, paramLang: string) {
let lang: string
// Check param lang validity
if (paramLang && is18nLocale(paramLang)) {
lang = paramLang
// Save locale in cookies
setClientLanguageCookie(res, lang)
} else if (req.cookies.clientLanguage && is18nLocale(req.cookies.clientLanguage)) {
lang = req.cookies.clientLanguage
} else {
lang = req.acceptsLanguages(AVAILABLE_LOCALES) || getDefaultLocale()
}
logger.debug(
'Serving %s HTML language',
buildFileLocale(lang),
{ cookie: req.cookies?.clientLanguage, paramLang, acceptLanguage: req.headers['accept-language'] }
)
return join(root(), 'client', 'dist', buildFileLocale(lang), 'index.html')
}
// ---------------------------------------------------------------------------
static addCustomCSS (htmlStringPage: string) {
const styleTag = `<style class="custom-css-style">${CONFIG.INSTANCE.CUSTOMIZATIONS.CSS}</style>`
return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.CUSTOM_CSS, styleTag)
}
static addServerConfig (htmlStringPage: string, serverConfig: HTMLServerConfig) {
// Stringify the JSON object, and then stringify the string object so we can inject it into the HTML
const serverConfigString = JSON.stringify(JSON.stringify(serverConfig))
const configScriptTag = `<script type="application/javascript">window.PeerTubeServerConfig = ${serverConfigString}</script>`
return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.SERVER_CONFIG, configScriptTag)
}
static async addAsyncPluginCSS (htmlStringPage: string) {
if (!await pathExists(PLUGIN_GLOBAL_CSS_PATH)) {
logger.info('Plugin Global CSS file is not available (generation may still be in progress), ignoring it.')
return htmlStringPage
}
let globalCSSContent: Buffer
try {
globalCSSContent = await readFile(PLUGIN_GLOBAL_CSS_PATH)
} catch (err) {
logger.error('Error retrieving the Plugin Global CSS file, ignoring it.', { err })
return htmlStringPage
}
if (globalCSSContent.byteLength === 0) return htmlStringPage
const fileHash = sha256(globalCSSContent)
const linkTag = `<link rel="stylesheet" href="/plugins/global.css?hash=${fileHash}" />`
return htmlStringPage.replace('</head>', linkTag + '</head>')
}
private static addManifestContentHash (htmlStringPage: string) {
return htmlStringPage.replace('[manifestContentHash]', FILES_CONTENT_HASH.MANIFEST)
}
}

View File

@@ -0,0 +1,156 @@
import { addQueryParams, escapeHTML } from '@peertube/peertube-core-utils'
import { HttpStatusCode, VideoPlaylistPrivacy } from '@peertube/peertube-models'
import { Memoize } from '@server/helpers/memoize.js'
import { getDefaultRSSFeeds } from '@server/lib/rss.js'
import { VideoPlaylistModel } from '@server/models/video/video-playlist.js'
import { MVideoPlaylist, MVideoPlaylistFull } from '@server/types/models/index.js'
import express from 'express'
import validator from 'validator'
import { CONFIG } from '../../../initializers/config.js'
import { MEMOIZE_TTL, WEBSERVER } from '../../../initializers/constants.js'
import { buildEmptyEmbedHTML } from './common.js'
import { PageHtml } from './page-html.js'
import { TagsHtml } from './tags-html.js'
export class PlaylistHtml {
static async getWatchPlaylistHTML (videoPlaylistId: string, req: express.Request, res: express.Response) {
// Let Angular application handle errors
if (!validator.default.isInt(videoPlaylistId) && !validator.default.isUUID(videoPlaylistId, 4)) {
res.status(HttpStatusCode.NOT_FOUND_404)
return PageHtml.getIndexHTML(req, res)
}
const [ html, videoPlaylist ] = await Promise.all([
PageHtml.getIndexHTML(req, res),
VideoPlaylistModel.loadWithAccountAndChannel(videoPlaylistId, null)
])
// Let Angular application handle errors
if (!videoPlaylist || videoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) {
res.status(HttpStatusCode.NOT_FOUND_404)
return html
}
return this.buildPlaylistHTML({
req,
html,
playlist: videoPlaylist,
addOG: true,
addTwitterCard: true,
isEmbed: false,
currentQuery: req.query
})
}
@Memoize({ maxAge: MEMOIZE_TTL.EMBED_HTML })
static async getEmbedPlaylistHTML (playlistId: string) {
const playlistPromise: Promise<MVideoPlaylistFull> = validator.default.isInt(playlistId) || validator.default.isUUID(playlistId, 4)
? VideoPlaylistModel.loadWithAccountAndChannel(playlistId, null)
: Promise.resolve(undefined)
const [ html, playlist ] = await Promise.all([ PageHtml.getEmbedHTML(), playlistPromise ])
if (!playlist || playlist.privacy === VideoPlaylistPrivacy.PRIVATE) {
return buildEmptyEmbedHTML({ html, playlist })
}
return this.buildPlaylistHTML({
req: null,
html,
playlist,
addOG: false,
addTwitterCard: false,
isEmbed: true,
// TODO: Implement it so we can send query params to oembed service
currentQuery: {}
})
}
// ---------------------------------------------------------------------------
// Private
// ---------------------------------------------------------------------------
private static buildPlaylistHTML (options: {
req: express.Request
html: string
playlist: MVideoPlaylistFull
addOG: boolean
addTwitterCard: boolean
isEmbed: boolean
currentQuery: Record<string, string>
}) {
const { req, html, playlist, addOG, addTwitterCard, isEmbed, currentQuery = {} } = options
const escapedTruncatedDescription = TagsHtml.buildEscapedTruncatedDescription(playlist.description)
let htmlResult = TagsHtml.addTitleTag(html, playlist.name)
htmlResult = TagsHtml.addDescriptionTag(htmlResult, escapedTruncatedDescription)
return TagsHtml.addTags(htmlResult, {
url: WEBSERVER.URL + playlist.getWatchStaticPath(),
escapedSiteName: escapeHTML(CONFIG.INSTANCE.NAME),
escapedTitle: escapeHTML(playlist.name),
escapedTruncatedDescription,
forbidIndexation: isEmbed
? playlist.privacy !== VideoPlaylistPrivacy.PUBLIC && playlist.privacy !== VideoPlaylistPrivacy.UNLISTED
: !playlist.isLocal() || playlist.privacy !== VideoPlaylistPrivacy.PUBLIC,
embedIndexation: isEmbed,
image: playlist.hasThumbnail()
? { url: playlist.getThumbnailUrl(), width: playlist.Thumbnail.width, height: playlist.Thumbnail.height }
: undefined,
list: { numberOfItems: playlist.get('videosLength') as number },
schemaType: 'ItemList',
ogType: addOG
? 'video' as 'video'
: undefined,
twitterCard: addTwitterCard
? 'player'
: undefined,
videoOrPlaylist: {
embedUrl: WEBSERVER.URL + playlist.getEmbedStaticPath(),
oembedUrl: this.getOEmbedUrl(playlist, currentQuery),
createdAt: playlist.createdAt.toISOString(),
updatedAt: playlist.updatedAt.toISOString(),
channel: playlist.VideoChannel
? {
displayName: playlist.VideoChannel.name,
url: playlist.VideoChannel.getClientUrl(false)
}
: undefined
},
rssFeeds: req
? getDefaultRSSFeeds(req)
: []
}, { playlist })
}
private static getOEmbedUrl (playlist: MVideoPlaylist, currentQuery: Record<string, string>) {
const base = WEBSERVER.URL + playlist.getWatchStaticPath()
const additionalQuery: Record<string, string> = {}
const allowedParams = new Set([ 'playlistPosition' ])
for (const [ key, value ] of Object.entries(currentQuery)) {
if (allowedParams.has(key)) additionalQuery[key] = value
}
return addQueryParams(base, additionalQuery)
}
}

View File

@@ -0,0 +1,410 @@
import { escapeAttribute, escapeHTML } from '@peertube/peertube-core-utils'
import { mdToPlainText } from '@server/helpers/markdown.js'
import { getActivityStreamDuration } from '@server/lib/activitypub/activity.js'
import { ServerConfigManager } from '@server/lib/server-config-manager.js'
import { getServerActor } from '@server/models/application/application.js'
import truncate from 'lodash-es/truncate.js'
import { parse } from 'node-html-parser'
import { CONFIG } from '../../../initializers/config.js'
import { CUSTOM_HTML_TAG_COMMENTS, EMBED_SIZE, WEBSERVER } from '../../../initializers/constants.js'
import { MVideo, MVideoPlaylist } from '../../../types/models/index.js'
import { Hooks } from '../../plugins/hooks.js'
type JsonldSchema = {
'@context': 'http://schema.org'
'@type': string
name: string
description: string
image: string
url: string
embedUrl?: string
uploadDate?: string
thumbnailUrl?: string
numberOfItems?: number
duration?: string
inLanguage?: string
interactionStatistic?: {
'@type': 'InteractionCounter'
interactionType: string
userInteractionCount: number
}[]
keywords?: string[]
author?: {
'@type': 'Organization'
name: string
url: string
}
contentRating?: 'Mature' | 'General Audience'
datePublished?: string
dateModified?: string
caption?: {
'@type': 'MediaObject'
'contentUrl': string
'encodingFormat': string
'inLanguage': string
'name': string
}[]
}
export type TagsOptions = {
forbidIndexation: boolean
embedIndexation: boolean
url?: string
ogType?: string
twitterCard?: 'player' | 'summary' | 'summary_large_image'
schemaType?: string
jsonldProfile?: {
createdAt: Date
updatedAt: Date
}
list?: {
numberOfItems: number
}
escapedSiteName?: string
escapedTitle?: string
escapedTruncatedDescription?: string
relMe?: string[]
image?: {
url: string
width: number
height: number
}
videoOrPlaylist?: {
embedUrl: string
oembedUrl: string
updatedAt: string
createdAt: string
channel?: {
displayName: string
url: string
}
}
video?: {
duration: number
language: string
tags: string[]
views: number
likes: number
dislikes: number
nsfw: boolean
publishedAt: string
captions: {
label: string
mediaType: string
language: string
url: string
}[]
}
rssFeeds?: {
title: string
url: string
}[]
}
type HookContext = {
video?: MVideo
playlist?: MVideoPlaylist
}
export class TagsHtml {
static addTitleTag (htmlStringPage: string, title?: string) {
let text = title || CONFIG.INSTANCE.NAME
if (title) text += ` - ${CONFIG.INSTANCE.NAME}`
const titleTag = `<title>${escapeHTML(text)}</title>`
return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.TITLE, titleTag)
}
static addDescriptionTag (htmlStringPage: string, escapedTruncatedDescription?: string) {
const content = escapedTruncatedDescription || escapeHTML(CONFIG.INSTANCE.SHORT_DESCRIPTION)
const descriptionTag = `<meta name="description" content="${escapeAttribute(content)}" />`
return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.DESCRIPTION, descriptionTag)
}
static findRelMe (content: string) {
if (!content) return undefined
const html = parse(content)
return html.querySelectorAll('a[rel=me]').map(e => e.getAttribute('href'))
}
// ---------------------------------------------------------------------------
static async addTags (htmlStringPage: string, tagsValues: TagsOptions, context: HookContext) {
const { url, escapedTitle, videoOrPlaylist, forbidIndexation, embedIndexation, relMe, rssFeeds } = tagsValues
const serverActor = await getServerActor()
let tagsStr = ''
// Global meta tags
const metaTags = {
...this.generateOpenGraphMetaTagsOptions(tagsValues),
...this.generateStandardMetaTagsOptions(tagsValues),
...this.generateTwitterCardMetaTagsOptions(tagsValues)
}
for (const tagName of Object.keys(metaTags)) {
const tagValue = metaTags[tagName]
if (!tagValue) continue
tagsStr += `<meta property="${tagName}" content="${escapeAttribute(tagValue)}" />`
}
// OEmbed
if (videoOrPlaylist?.oembedUrl) {
const href = WEBSERVER.URL + '/services/oembed?url=' + encodeURIComponent(videoOrPlaylist.oembedUrl)
tagsStr += `<link rel="alternate" type="application/json+oembed" href="${href}" title="${escapeAttribute(escapedTitle)}" />`
}
// Schema.org
const schemaTags = await this.generateSchemaTagsOptions(tagsValues, context)
if (schemaTags) {
tagsStr += `<script type="application/ld+json">${JSON.stringify(schemaTags)}</script>`
}
// Rel Me
if (Array.isArray(relMe)) {
for (const relMeLink of relMe) {
tagsStr += `<link href="${escapeAttribute(relMeLink)}" rel="me">`
}
}
// SEO
if (forbidIndexation === true) {
tagsStr += `<meta name="robots" content="noindex" />`
} else if (embedIndexation) {
tagsStr += `<meta name="robots" content="noindex, indexifembedded" />`
} else if (url) { // SEO, use origin URL
tagsStr += `<link rel="canonical" href="${url}" />`
}
// RSS
for (const rssLink of (rssFeeds || [])) {
tagsStr += `<link rel="alternate" type="application/rss+xml" title="${escapeAttribute(rssLink.title)}" href="${rssLink.url}" />`
}
// Favicon
const favicon = ServerConfigManager.Instance.getFavicon(serverActor)
tagsStr += `<link rel="icon" type="image/png" href="${escapeAttribute(favicon.fileUrl)}" />`
// Apple Touch Icon
const iconHref = ServerConfigManager.Instance.getLogoUrl(serverActor, 192)
tagsStr += `<link rel="apple-touch-icon" href="${iconHref}" />`
return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.META_TAGS, tagsStr)
}
// ---------------------------------------------------------------------------
static generateOpenGraphMetaTagsOptions (tags: TagsOptions) {
if (!tags.ogType) return {}
const metaTags = {
'og:type': tags.ogType,
'og:site_name': tags.escapedSiteName,
'og:title': tags.escapedTitle
}
if (tags.image?.url) {
metaTags['og:image'] = tags.image.url
}
if (tags.image?.width && tags.image?.height) {
metaTags['og:image:width'] = tags.image.width
metaTags['og:image:height'] = tags.image.height
}
metaTags['og:url'] = tags.url
metaTags['og:description'] = tags.escapedTruncatedDescription
if (tags.videoOrPlaylist) {
metaTags['og:video:url'] = tags.videoOrPlaylist.embedUrl
metaTags['og:video:secure_url'] = tags.videoOrPlaylist.embedUrl
metaTags['og:video:type'] = 'text/html'
metaTags['og:video:width'] = EMBED_SIZE.width
metaTags['og:video:height'] = EMBED_SIZE.height
}
return metaTags
}
static generateStandardMetaTagsOptions (tags: TagsOptions) {
return {
name: tags.escapedTitle,
description: tags.escapedTruncatedDescription,
image: tags.image?.url
}
}
static generateTwitterCardMetaTagsOptions (tags: TagsOptions) {
if (!tags.twitterCard) return {}
const metaTags = {
'twitter:card': tags.twitterCard,
'twitter:site': CONFIG.SERVICES.TWITTER.USERNAME,
'twitter:title': tags.escapedTitle,
'twitter:description': tags.escapedTruncatedDescription
}
if (tags.image?.url) {
metaTags['twitter:image:url'] = tags.image.url
}
if (tags.image?.width && tags.image?.height) {
metaTags['twitter:image:width'] = tags.image.width
metaTags['twitter:image:height'] = tags.image.height
}
if (tags.twitterCard === 'player' && tags.videoOrPlaylist) {
metaTags['twitter:player'] = tags.videoOrPlaylist.embedUrl
metaTags['twitter:player:width'] = EMBED_SIZE.width
metaTags['twitter:player:height'] = EMBED_SIZE.height
}
return metaTags
}
static generateSchemaTagsOptions (tags: TagsOptions, context: HookContext) {
if (!tags.schemaType) return
if (tags.schemaType === 'ProfilePage') {
if (!tags.jsonldProfile) throw new Error('Missing `jsonldProfile` with ProfilePage schema type')
const profilePageSchema = {
'@context': 'http://schema.org',
'@type': tags.schemaType,
'dateCreated': tags.jsonldProfile.createdAt.toISOString(),
'dateModified': tags.jsonldProfile.updatedAt.toISOString(),
'mainEntity': {
'@id': '#main-author',
'@type': 'Person',
'name': tags.escapedTitle,
'description': tags.escapedTruncatedDescription,
'image': tags.image?.url
}
}
return Hooks.wrapObject(profilePageSchema, 'filter:html.client.json-ld.result', context)
}
const schema: JsonldSchema = {
'@context': 'http://schema.org',
'@type': tags.schemaType,
'name': tags.escapedTitle,
'description': tags.escapedTruncatedDescription,
'image': tags.image?.url,
'url': tags.url
}
if (tags.list) {
schema['numberOfItems'] = tags.list.numberOfItems
schema['thumbnailUrl'] = tags.image?.url
}
if (tags.videoOrPlaylist) {
const videoOrPlaylist = tags.videoOrPlaylist
const video = tags.video
schema['publisher'] = {
'@type': 'Organization',
'name': CONFIG.INSTANCE.NAME,
'url': WEBSERVER.URL
}
schema['embedUrl'] = videoOrPlaylist.embedUrl
schema['uploadDate'] = videoOrPlaylist.createdAt
schema['thumbnailUrl'] = tags.image?.url
schema['dateModified'] = videoOrPlaylist.updatedAt
if (videoOrPlaylist.channel) {
schema['author'] = {
'@type': 'Organization',
'name': videoOrPlaylist.channel.displayName,
'url': videoOrPlaylist.channel.url
}
}
if (video) {
schema['datePublished'] = video.publishedAt
schema['interactionStatistic'] = [
{
'@type': 'InteractionCounter',
'interactionType': 'http://schema.org/WatchAction',
'userInteractionCount': video.views
},
{
'@type': 'InteractionCounter',
'interactionType': 'http://schema.org/LikeAction',
'userInteractionCount': video.likes
},
{
'@type': 'InteractionCounter',
'interactionType': 'http://schema.org/DislikeAction',
'userInteractionCount': video.dislikes
}
]
if (video.duration) schema['duration'] = getActivityStreamDuration(video.duration)
if (video.language) schema['inLanguage'] = video.language
if (video.tags.length !== 0) schema['keywords'] = video.tags
if (video.captions.length !== 0) {
schema['caption'] = video.captions.map(c => ({
'@type': 'MediaObject',
'contentUrl': c.url,
'encodingFormat': c.mediaType,
'inLanguage': c.language,
'name': c.label
}))
}
if (video.nsfw) schema['contentRating'] = 'Mature'
else schema['contentRating'] = 'General Audience'
}
}
return Hooks.wrapObject(schema, 'filter:html.client.json-ld.result', context)
}
// ---------------------------------------------------------------------------
static buildEscapedTruncatedDescription (description: string) {
return truncate(mdToPlainText(description), { length: 200 })
}
}

View File

@@ -0,0 +1,178 @@
import { addQueryParams, escapeHTML } from '@peertube/peertube-core-utils'
import { HttpStatusCode, VideoPrivacy } from '@peertube/peertube-models'
import { Memoize } from '@server/helpers/memoize.js'
import { getVideoRSSFeeds } from '@server/lib/rss.js'
import { VideoCaptionModel } from '@server/models/video/video-caption.js'
import express from 'express'
import validator from 'validator'
import { CONFIG } from '../../../initializers/config.js'
import { MEMOIZE_TTL, WEBSERVER } from '../../../initializers/constants.js'
import { VideoModel } from '../../../models/video/video.js'
import { MVideo, MVideoSeo } from '../../../types/models/index.js'
import { isVideoInPrivateDirectory } from '../../video-privacy.js'
import { buildEmptyEmbedHTML } from './common.js'
import { PageHtml } from './page-html.js'
import { TagsHtml } from './tags-html.js'
export class VideoHtml {
static async getWatchVideoHTML (videoId: string, req: express.Request, res: express.Response) {
// Let Angular application handle errors
if (!validator.default.isInt(videoId) && !validator.default.isUUID(videoId, 4)) {
res.status(HttpStatusCode.NOT_FOUND_404)
return PageHtml.getIndexHTML(req, res)
}
const [ html, video ] = await Promise.all([
PageHtml.getIndexHTML(req, res),
VideoModel.loadForSEO(videoId)
])
if (video?.privacy === VideoPrivacy.PASSWORD_PROTECTED) {
return html
}
// Let Angular application handle errors
if (!video || isVideoInPrivateDirectory(video.privacy) || video.VideoBlacklist) {
res.status(HttpStatusCode.NOT_FOUND_404)
return html
}
return this.buildVideoHTML({
req,
html,
video,
currentQuery: req.query,
addOG: true,
addTwitterCard: true,
isEmbed: false
})
}
@Memoize({ maxAge: MEMOIZE_TTL.EMBED_HTML })
static async getEmbedVideoHTML (videoId: string) {
const videoPromise: Promise<MVideoSeo> = validator.default.isInt(videoId) || validator.default.isUUID(videoId, 4)
? VideoModel.loadForSEO(videoId)
: Promise.resolve(undefined)
const [ html, video ] = await Promise.all([ PageHtml.getEmbedHTML(), videoPromise ])
if (!video || isVideoInPrivateDirectory(video.privacy) || video.VideoBlacklist) {
return buildEmptyEmbedHTML({ html, video })
}
return this.buildVideoHTML({
req: null,
html,
video,
addOG: false,
addTwitterCard: false,
isEmbed: true,
// TODO: Implement it so we can send query params to oembed service
currentQuery: {}
})
}
// ---------------------------------------------------------------------------
// Private
// ---------------------------------------------------------------------------
private static buildVideoHTML (options: {
req: express.Request
html: string
video: MVideoSeo
addOG: boolean
addTwitterCard: boolean
isEmbed: boolean
currentQuery: Record<string, string>
}) {
const { req, html, video, addOG, addTwitterCard, isEmbed, currentQuery = {} } = options
const escapedTruncatedDescription = TagsHtml.buildEscapedTruncatedDescription(video.description)
let customHTML = TagsHtml.addTitleTag(html, video.name)
customHTML = TagsHtml.addDescriptionTag(customHTML, escapedTruncatedDescription)
const preview = video.getPreview()
return TagsHtml.addTags(customHTML, {
url: WEBSERVER.URL + video.getWatchStaticPath(),
escapedSiteName: escapeHTML(CONFIG.INSTANCE.NAME),
escapedTitle: escapeHTML(video.name),
escapedTruncatedDescription,
forbidIndexation: isEmbed
? video.privacy !== VideoPrivacy.PUBLIC && video.privacy !== VideoPrivacy.UNLISTED
: video.remote || video.privacy !== VideoPrivacy.PUBLIC,
embedIndexation: isEmbed,
image: preview
? { url: WEBSERVER.URL + video.getPreviewStaticPath(), width: preview.width, height: preview.height }
: undefined,
videoOrPlaylist: {
embedUrl: WEBSERVER.URL + video.getEmbedStaticPath(),
oembedUrl: this.getOEmbedUrl(video, currentQuery),
channel: {
displayName: video.VideoChannel.name,
url: video.VideoChannel.getClientUrl(false)
},
createdAt: video.createdAt.toISOString(),
updatedAt: video.updatedAt.toISOString()
},
video: {
publishedAt: video.publishedAt.toISOString(),
duration: video.duration,
views: video.views,
language: video.language,
dislikes: video.dislikes,
likes: video.likes,
nsfw: video.nsfw,
tags: video.Tags.map(t => t.name),
captions: video.VideoCaptions.map(c => ({
label: VideoCaptionModel.getLanguageLabel(c.language),
mediaType: 'text/vtt',
language: c.language,
url: c.getFileUrl(video)
}))
},
ogType: addOG
? 'video' as 'video'
: undefined,
twitterCard: addTwitterCard
? 'player'
: undefined,
schemaType: 'VideoObject',
rssFeeds: req
? getVideoRSSFeeds(video, req)
: []
}, { video })
}
private static getOEmbedUrl (video: MVideo, currentQuery: Record<string, string>) {
const base = WEBSERVER.URL + video.getWatchStaticPath()
const additionalQuery: Record<string, string> = {}
const allowedParams = new Set([ 'start' ])
for (const [ key, value ] of Object.entries(currentQuery)) {
if (allowedParams.has(key)) additionalQuery[key] = value
}
return addQueryParams(base, additionalQuery)
}
}