mirror of
https://github.com/Chocobozzz/PeerTube.git
synced 2025-10-04 18:29:27 +02:00
Fix SEO and refactor HTML pages generation
* Split methods in multiple classes * Add JSONLD tags in embed too * Index embeds but use a canonical URL tag (targeting the watch page) * Remote objects don't include a canonical URL tag anymore. Instead we forbid indexation * Canonical URLs now use the official short URL (/w/, /w/p, /a, /c etc.)
This commit is contained in:
parent
e731f4b724
commit
f90db24233
23 changed files with 1876 additions and 1213 deletions
91
server/core/lib/html/shared/actor-html.ts
Normal file
91
server/core/lib/html/shared/actor-html.ts
Normal file
|
@ -0,0 +1,91 @@
|
|||
import { escapeHTML } from '@peertube/peertube-core-utils'
|
||||
import { HttpStatusCode } from '@peertube/peertube-models'
|
||||
import express from 'express'
|
||||
import { CONFIG } from '../../../initializers/config.js'
|
||||
import { AccountModel } from '@server/models/account/account.js'
|
||||
import { VideoChannelModel } from '@server/models/video/video-channel.js'
|
||||
import { MAccountHost, MChannelHost } from '@server/types/models/index.js'
|
||||
import { getBiggestActorImage } from '@server/lib/actor-image.js'
|
||||
import { ActorImageModel } from '@server/models/actor/actor-image.js'
|
||||
import { TagsHtml } from './tags-html.js'
|
||||
import { PageHtml } from './page-html.js'
|
||||
|
||||
export class ActorHtml {
|
||||
|
||||
static async getAccountHTMLPage (nameWithHost: string, req: express.Request, res: express.Response) {
|
||||
const accountModelPromise = AccountModel.loadByNameWithHost(nameWithHost)
|
||||
|
||||
return this.getAccountOrChannelHTMLPage(() => accountModelPromise, req, res)
|
||||
}
|
||||
|
||||
static async getVideoChannelHTMLPage (nameWithHost: string, req: express.Request, res: express.Response) {
|
||||
const videoChannelModelPromise = VideoChannelModel.loadByNameWithHostAndPopulateAccount(nameWithHost)
|
||||
|
||||
return this.getAccountOrChannelHTMLPage(() => videoChannelModelPromise, req, res)
|
||||
}
|
||||
|
||||
static async getActorHTMLPage (nameWithHost: string, req: express.Request, res: express.Response) {
|
||||
const [ account, channel ] = await Promise.all([
|
||||
AccountModel.loadByNameWithHost(nameWithHost),
|
||||
VideoChannelModel.loadByNameWithHostAndPopulateAccount(nameWithHost)
|
||||
])
|
||||
|
||||
return this.getAccountOrChannelHTMLPage(() => Promise.resolve(account || channel), req, res)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
private static async getAccountOrChannelHTMLPage (
|
||||
loader: () => Promise<MAccountHost | MChannelHost>,
|
||||
req: express.Request,
|
||||
res: express.Response
|
||||
) {
|
||||
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 = getBiggestActorImage(entity.Actor.Avatars)
|
||||
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,
|
||||
image,
|
||||
ogType,
|
||||
twitterCard,
|
||||
schemaType,
|
||||
|
||||
indexationPolicy: entity.Actor.isOwned()
|
||||
? 'always'
|
||||
: 'never'
|
||||
}, {})
|
||||
|
||||
return customHTML
|
||||
}
|
||||
}
|
18
server/core/lib/html/shared/common-embed-html.ts
Normal file
18
server/core/lib/html/shared/common-embed-html.ts
Normal file
|
@ -0,0 +1,18 @@
|
|||
import { MVideo, MVideoPlaylist } from '../../../types/models/index.js'
|
||||
import { TagsHtml } from './tags-html.js'
|
||||
|
||||
export class CommonEmbedHtml {
|
||||
|
||||
static 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, { indexationPolicy: 'never' }, { playlist, video })
|
||||
}
|
||||
}
|
5
server/core/lib/html/shared/index.ts
Normal file
5
server/core/lib/html/shared/index.ts
Normal 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'
|
166
server/core/lib/html/shared/page-html.ts
Normal file
166
server/core/lib/html/shared/page-html.ts
Normal file
|
@ -0,0 +1,166 @@
|
|||
import { buildFileLocale, getDefaultLocale, is18nLocale, POSSIBLE_LOCALES } from '@peertube/peertube-core-utils'
|
||||
import { isTestOrDevInstance, root, sha256 } from '@peertube/peertube-node-utils'
|
||||
import express from 'express'
|
||||
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'
|
||||
import { pathExists } from 'fs-extra/esm'
|
||||
import { HTMLServerConfig } from '@peertube/peertube-models'
|
||||
import { CONFIG } from '@server/initializers/config.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 = paramLang
|
||||
? await this.getIndexHTML(req, res, paramLang)
|
||||
: await this.getIndexHTML(req, res)
|
||||
|
||||
let customHTML = TagsHtml.addTitleTag(html)
|
||||
customHTML = TagsHtml.addDescriptionTag(customHTML)
|
||||
|
||||
return customHTML
|
||||
}
|
||||
|
||||
static async getEmbedHTML () {
|
||||
const path = this.getEmbedHTMLPath()
|
||||
|
||||
// Disable HTML cache in dev mode because webpack 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.addFaviconContentHash(html)
|
||||
html = this.addLogoContentHash(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
|
||||
res.cookie('clientLanguage', lang, {
|
||||
secure: WEBSERVER.SCHEME === 'https',
|
||||
sameSite: 'none',
|
||||
maxAge: 1000 * 3600 * 24 * 90 // 3 months
|
||||
})
|
||||
|
||||
} else if (req.cookies.clientLanguage && is18nLocale(req.cookies.clientLanguage)) {
|
||||
lang = req.cookies.clientLanguage
|
||||
} else {
|
||||
lang = req.acceptsLanguages(POSSIBLE_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)
|
||||
}
|
||||
|
||||
private static addFaviconContentHash (htmlStringPage: string) {
|
||||
return htmlStringPage.replace('[faviconContentHash]', FILES_CONTENT_HASH.FAVICON)
|
||||
}
|
||||
|
||||
private static addLogoContentHash (htmlStringPage: string) {
|
||||
return htmlStringPage.replace('[logoContentHash]', FILES_CONTENT_HASH.LOGO)
|
||||
}
|
||||
}
|
126
server/core/lib/html/shared/playlist-html.ts
Normal file
126
server/core/lib/html/shared/playlist-html.ts
Normal file
|
@ -0,0 +1,126 @@
|
|||
import { escapeHTML } from '@peertube/peertube-core-utils'
|
||||
import { HttpStatusCode, VideoPlaylistPrivacy } from '@peertube/peertube-models'
|
||||
import { toCompleteUUID } from '@server/helpers/custom-validators/misc.js'
|
||||
import express from 'express'
|
||||
import validator from 'validator'
|
||||
import { CONFIG } from '../../../initializers/config.js'
|
||||
import { MEMOIZE_TTL, WEBSERVER } from '../../../initializers/constants.js'
|
||||
import { Memoize } from '@server/helpers/memoize.js'
|
||||
import { VideoPlaylistModel } from '@server/models/video/video-playlist.js'
|
||||
import { MVideoPlaylistFull } from '@server/types/models/index.js'
|
||||
import { TagsHtml } from './tags-html.js'
|
||||
import { PageHtml } from './page-html.js'
|
||||
import { CommonEmbedHtml } from './common-embed-html.js'
|
||||
|
||||
export class PlaylistHtml {
|
||||
|
||||
static async getWatchPlaylistHTML (videoPlaylistIdArg: string, req: express.Request, res: express.Response) {
|
||||
const videoPlaylistId = toCompleteUUID(videoPlaylistIdArg)
|
||||
|
||||
// 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({
|
||||
html,
|
||||
playlist: videoPlaylist,
|
||||
addEmbedInfo: true,
|
||||
addOG: true,
|
||||
addTwitterCard: true
|
||||
})
|
||||
}
|
||||
|
||||
@Memoize({ maxAge: MEMOIZE_TTL.EMBED_HTML })
|
||||
static async getEmbedPlaylistHTML (playlistIdArg: string) {
|
||||
const playlistId = toCompleteUUID(playlistIdArg)
|
||||
|
||||
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 CommonEmbedHtml.buildEmptyEmbedHTML({ html, playlist })
|
||||
}
|
||||
|
||||
return this.buildPlaylistHTML({
|
||||
html,
|
||||
playlist,
|
||||
addEmbedInfo: false,
|
||||
addOG: false,
|
||||
addTwitterCard: false
|
||||
})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Private
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
private static buildPlaylistHTML (options: {
|
||||
html: string
|
||||
playlist: MVideoPlaylistFull
|
||||
|
||||
addOG: boolean
|
||||
addTwitterCard: boolean
|
||||
addEmbedInfo: boolean
|
||||
}) {
|
||||
const { html, playlist, addEmbedInfo, addOG, addTwitterCard } = options
|
||||
const escapedTruncatedDescription = TagsHtml.buildEscapedTruncatedDescription(playlist.description)
|
||||
|
||||
let htmlResult = TagsHtml.addTitleTag(html, playlist.name)
|
||||
htmlResult = TagsHtml.addDescriptionTag(htmlResult, escapedTruncatedDescription)
|
||||
|
||||
const list = { numberOfItems: playlist.get('videosLength') as number }
|
||||
const schemaType = 'ItemList'
|
||||
|
||||
let twitterCard: 'player' | 'summary'
|
||||
if (addTwitterCard) {
|
||||
twitterCard = CONFIG.SERVICES.TWITTER.WHITELISTED
|
||||
? 'player'
|
||||
: 'summary'
|
||||
}
|
||||
|
||||
const ogType = addOG
|
||||
? 'video' as 'video'
|
||||
: undefined
|
||||
|
||||
const embed = addEmbedInfo
|
||||
? { url: WEBSERVER.URL + playlist.getEmbedStaticPath(), createdAt: playlist.createdAt.toISOString() }
|
||||
: undefined
|
||||
|
||||
return TagsHtml.addTags(htmlResult, {
|
||||
url: WEBSERVER.URL + playlist.getWatchStaticPath(),
|
||||
|
||||
escapedSiteName: escapeHTML(CONFIG.INSTANCE.NAME),
|
||||
escapedTitle: escapeHTML(playlist.name),
|
||||
escapedTruncatedDescription,
|
||||
|
||||
indexationPolicy: !playlist.isOwned() || playlist.privacy !== VideoPlaylistPrivacy.PUBLIC
|
||||
? 'never'
|
||||
: 'always',
|
||||
|
||||
image: { url: playlist.getThumbnailUrl() },
|
||||
|
||||
list,
|
||||
|
||||
schemaType,
|
||||
ogType,
|
||||
twitterCard,
|
||||
embed
|
||||
}, { playlist })
|
||||
}
|
||||
}
|
230
server/core/lib/html/shared/tags-html.ts
Normal file
230
server/core/lib/html/shared/tags-html.ts
Normal file
|
@ -0,0 +1,230 @@
|
|||
import { escapeHTML } from '@peertube/peertube-core-utils'
|
||||
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'
|
||||
import truncate from 'lodash-es/truncate.js'
|
||||
import { mdToOneLinePlainText } from '@server/helpers/markdown.js'
|
||||
|
||||
type Tags = {
|
||||
indexationPolicy: 'always' | 'never'
|
||||
|
||||
url?: string
|
||||
|
||||
schemaType?: string
|
||||
ogType?: string
|
||||
twitterCard?: 'player' | 'summary' | 'summary_large_image'
|
||||
|
||||
list?: {
|
||||
numberOfItems: number
|
||||
}
|
||||
|
||||
escapedSiteName?: string
|
||||
escapedTitle?: string
|
||||
escapedTruncatedDescription?: string
|
||||
|
||||
image?: {
|
||||
url: string
|
||||
width?: number
|
||||
height?: number
|
||||
}
|
||||
|
||||
embed?: {
|
||||
url: string
|
||||
createdAt: string
|
||||
duration?: string
|
||||
views?: number
|
||||
}
|
||||
}
|
||||
|
||||
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="${content}" />`
|
||||
|
||||
return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.DESCRIPTION, descriptionTag)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static async addTags (htmlStringPage: string, tagsValues: Tags, context: HookContext) {
|
||||
const openGraphMetaTags = this.generateOpenGraphMetaTagsOptions(tagsValues)
|
||||
const standardMetaTags = this.generateStandardMetaTagsOptions(tagsValues)
|
||||
const twitterCardMetaTags = this.generateTwitterCardMetaTagsOptions(tagsValues)
|
||||
const schemaTags = await this.generateSchemaTagsOptions(tagsValues, context)
|
||||
|
||||
const { url, escapedTitle, embed, indexationPolicy } = tagsValues
|
||||
|
||||
const oembedLinkTags: { type: string, href: string, escapedTitle: string }[] = []
|
||||
|
||||
if (embed) {
|
||||
oembedLinkTags.push({
|
||||
type: 'application/json+oembed',
|
||||
href: WEBSERVER.URL + '/services/oembed?url=' + encodeURIComponent(url),
|
||||
escapedTitle
|
||||
})
|
||||
}
|
||||
|
||||
let tagsStr = ''
|
||||
|
||||
// Opengraph
|
||||
Object.keys(openGraphMetaTags).forEach(tagName => {
|
||||
const tagValue = openGraphMetaTags[tagName]
|
||||
if (!tagValue) return
|
||||
|
||||
tagsStr += `<meta property="${tagName}" content="${tagValue}" />`
|
||||
})
|
||||
|
||||
// Standard
|
||||
Object.keys(standardMetaTags).forEach(tagName => {
|
||||
const tagValue = standardMetaTags[tagName]
|
||||
if (!tagValue) return
|
||||
|
||||
tagsStr += `<meta property="${tagName}" content="${tagValue}" />`
|
||||
})
|
||||
|
||||
// Twitter card
|
||||
Object.keys(twitterCardMetaTags).forEach(tagName => {
|
||||
const tagValue = twitterCardMetaTags[tagName]
|
||||
if (!tagValue) return
|
||||
|
||||
tagsStr += `<meta property="${tagName}" content="${tagValue}" />`
|
||||
})
|
||||
|
||||
// OEmbed
|
||||
for (const oembedLinkTag of oembedLinkTags) {
|
||||
tagsStr += `<link rel="alternate" type="${oembedLinkTag.type}" href="${oembedLinkTag.href}" title="${oembedLinkTag.escapedTitle}" />`
|
||||
}
|
||||
|
||||
// Schema.org
|
||||
if (schemaTags) {
|
||||
tagsStr += `<script type="application/ld+json">${JSON.stringify(schemaTags)}</script>`
|
||||
}
|
||||
|
||||
// SEO, use origin URL
|
||||
if (indexationPolicy !== 'never' && url) {
|
||||
tagsStr += `<link rel="canonical" href="${url}" />`
|
||||
}
|
||||
|
||||
if (indexationPolicy === 'never') {
|
||||
tagsStr += `<meta name="robots" content="noindex" />`
|
||||
}
|
||||
|
||||
return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.META_TAGS, tagsStr)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static generateOpenGraphMetaTagsOptions (tags: Tags) {
|
||||
if (!tags.ogType) return {}
|
||||
|
||||
const metaTags = {
|
||||
'og:type': tags.ogType,
|
||||
'og:site_name': tags.escapedSiteName,
|
||||
'og:title': tags.escapedTitle,
|
||||
'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.embed) {
|
||||
metaTags['og:video:url'] = tags.embed.url
|
||||
metaTags['og:video:secure_url'] = tags.embed.url
|
||||
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: Tags) {
|
||||
return {
|
||||
name: tags.escapedTitle,
|
||||
description: tags.escapedTruncatedDescription,
|
||||
image: tags.image?.url
|
||||
}
|
||||
}
|
||||
|
||||
static generateTwitterCardMetaTagsOptions (tags: Tags) {
|
||||
if (!tags.twitterCard) return {}
|
||||
|
||||
const metaTags = {
|
||||
'twitter:card': tags.twitterCard,
|
||||
'twitter:site': CONFIG.SERVICES.TWITTER.USERNAME,
|
||||
'twitter:title': tags.escapedTitle,
|
||||
'twitter:description': tags.escapedTruncatedDescription,
|
||||
'twitter:image': 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') {
|
||||
metaTags['twitter:player'] = tags.embed.url
|
||||
metaTags['twitter:player:width'] = EMBED_SIZE.width
|
||||
metaTags['twitter:player:height'] = EMBED_SIZE.height
|
||||
}
|
||||
|
||||
return metaTags
|
||||
}
|
||||
|
||||
static generateSchemaTagsOptions (tags: Tags, context: HookContext) {
|
||||
if (!tags.schemaType) return
|
||||
|
||||
const schema = {
|
||||
'@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.embed) {
|
||||
schema['embedUrl'] = tags.embed.url
|
||||
schema['uploadDate'] = tags.embed.createdAt
|
||||
|
||||
if (tags.embed.duration) schema['duration'] = tags.embed.duration
|
||||
|
||||
schema['thumbnailUrl'] = tags.image.url
|
||||
schema['contentUrl'] = tags.url
|
||||
}
|
||||
|
||||
return Hooks.wrapObject(schema, 'filter:html.client.json-ld.result', context)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
static buildEscapedTruncatedDescription (description: string) {
|
||||
return truncate(mdToOneLinePlainText(description), { length: 200 })
|
||||
}
|
||||
}
|
130
server/core/lib/html/shared/video-html.ts
Normal file
130
server/core/lib/html/shared/video-html.ts
Normal file
|
@ -0,0 +1,130 @@
|
|||
import { escapeHTML } from '@peertube/peertube-core-utils'
|
||||
import { HttpStatusCode, VideoPrivacy } from '@peertube/peertube-models'
|
||||
import { toCompleteUUID } from '@server/helpers/custom-validators/misc.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 } from '../../../types/models/index.js'
|
||||
import { getActivityStreamDuration } from '../../activitypub/activity.js'
|
||||
import { isVideoInPrivateDirectory } from '../../video-privacy.js'
|
||||
import { Memoize } from '@server/helpers/memoize.js'
|
||||
import { MVideoThumbnailBlacklist } from 'server/dist/core/types/models/index.js'
|
||||
import { TagsHtml } from './tags-html.js'
|
||||
import { PageHtml } from './page-html.js'
|
||||
import { CommonEmbedHtml } from './common-embed-html.js'
|
||||
|
||||
export class VideoHtml {
|
||||
|
||||
static async getWatchVideoHTML (videoIdArg: string, req: express.Request, res: express.Response) {
|
||||
const videoId = toCompleteUUID(videoIdArg)
|
||||
|
||||
// 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.loadWithBlacklist(videoId)
|
||||
])
|
||||
|
||||
// Let Angular application handle errors
|
||||
if (!video || isVideoInPrivateDirectory(video.privacy) || video.VideoBlacklist) {
|
||||
res.status(HttpStatusCode.NOT_FOUND_404)
|
||||
return html
|
||||
}
|
||||
|
||||
return this.buildVideoHTML({
|
||||
html,
|
||||
video,
|
||||
addEmbedInfo: true,
|
||||
addOG: true,
|
||||
addTwitterCard: true
|
||||
})
|
||||
}
|
||||
|
||||
@Memoize({ maxAge: MEMOIZE_TTL.EMBED_HTML })
|
||||
static async getEmbedVideoHTML (videoIdArg: string) {
|
||||
const videoId = toCompleteUUID(videoIdArg)
|
||||
|
||||
const videoPromise: Promise<MVideoThumbnailBlacklist> = validator.default.isInt(videoId) || validator.default.isUUID(videoId, 4)
|
||||
? VideoModel.loadWithBlacklist(videoId)
|
||||
: Promise.resolve(undefined)
|
||||
|
||||
const [ html, video ] = await Promise.all([ PageHtml.getEmbedHTML(), videoPromise ])
|
||||
|
||||
if (!video || isVideoInPrivateDirectory(video.privacy) || video.VideoBlacklist) {
|
||||
return CommonEmbedHtml.buildEmptyEmbedHTML({ html, video })
|
||||
}
|
||||
|
||||
return this.buildVideoHTML({
|
||||
html,
|
||||
video,
|
||||
addEmbedInfo: false,
|
||||
addOG: false,
|
||||
addTwitterCard: false
|
||||
})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Private
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
private static buildVideoHTML (options: {
|
||||
html: string
|
||||
video: MVideo
|
||||
|
||||
addOG: boolean
|
||||
addTwitterCard: boolean
|
||||
addEmbedInfo: boolean
|
||||
}) {
|
||||
const { html, video, addEmbedInfo, addOG, addTwitterCard } = options
|
||||
const escapedTruncatedDescription = TagsHtml.buildEscapedTruncatedDescription(video.description)
|
||||
|
||||
let customHTML = TagsHtml.addTitleTag(html, video.name)
|
||||
customHTML = TagsHtml.addDescriptionTag(customHTML, escapedTruncatedDescription)
|
||||
|
||||
const embed = addEmbedInfo
|
||||
? {
|
||||
url: WEBSERVER.URL + video.getEmbedStaticPath(),
|
||||
createdAt: video.createdAt.toISOString(),
|
||||
duration: getActivityStreamDuration(video.duration),
|
||||
views: video.views
|
||||
}
|
||||
: undefined
|
||||
|
||||
const ogType = addOG
|
||||
? 'video' as 'video'
|
||||
: undefined
|
||||
|
||||
let twitterCard: 'player' | 'summary_large_image'
|
||||
if (addTwitterCard) {
|
||||
twitterCard = CONFIG.SERVICES.TWITTER.WHITELISTED
|
||||
? 'player'
|
||||
: 'summary_large_image'
|
||||
}
|
||||
|
||||
const schemaType = 'VideoObject'
|
||||
|
||||
return TagsHtml.addTags(customHTML, {
|
||||
url: WEBSERVER.URL + video.getWatchStaticPath(),
|
||||
escapedSiteName: escapeHTML(CONFIG.INSTANCE.NAME),
|
||||
escapedTitle: escapeHTML(video.name),
|
||||
escapedTruncatedDescription,
|
||||
|
||||
indexationPolicy: video.remote || video.privacy !== VideoPrivacy.PUBLIC
|
||||
? 'never'
|
||||
: 'always',
|
||||
|
||||
image: { url: WEBSERVER.URL + video.getPreviewStaticPath() },
|
||||
|
||||
embed,
|
||||
ogType,
|
||||
twitterCard,
|
||||
schemaType
|
||||
}, { video })
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue