Skip to content

ActivityPub-federated video streaming platform using P2P directly in your web browser

6.7 KB
Raw Blame
import { addQueryParams, escapeHTML } from '@peertube/peertube-core-utils'
import { HttpStatusCode, VideoPrivacy, VideoResolution } 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 (!this.canBuildVideoTags(video, videoId)) {
      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 (!this.canBuildVideoTags(video, videoId)) {
      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 canBuildVideoTags (video: MVideoSeo, videoId: string) {
    if (!video || isVideoInPrivateDirectory(video.privacy) || video.VideoBlacklist) return false

    // Unlisted videos can only be fetched using their UUID
    if (video.privacy === VideoPrivacy.UNLISTED && !validator.default.isUUID(videoId, 4)) return false

    return true
  }

  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 thumbnail = video.getBestThumbnail('16:9')

    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: thumbnail
        ? { url: WEBSERVER.URL + thumbnail.getFileStaticPath(), width: thumbnail.width, height: thumbnail.height }
        : undefined,

      videoOrPlaylist: {
        embedUrl: video.getEmbedStaticUrl(),
        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,

        contentUrl: this.getContentUrl(video),
        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.getLocalFileUrl()
        }))
      },

      ogType: addOG
        ? 'video'
        : undefined,

      twitterCard: addTwitterCard
        ? 'player'
        : undefined,

      schemaType: 'VideoObject',

      rssFeeds: req
        ? getVideoRSSFeeds(video, req)
        : []
    }, { video })
  }

  // Crawlers prefer a URL they can fetch and probe themselves over the embed page
  private static getContentUrl (video: MVideoSeo) {
    const webVideoFile = this.getSEOWebVideoFile(video)
    if (webVideoFile) return webVideoFile.getFileUrl(video)

    // HLS only video: fallback on the master playlist
    return video.getHLSPlaylist()?.getMasterPlaylistUrl(video)
  }

  // Prefer 720p: crawlers get enough to probe the video without us serving them our biggest file
  private static getSEOWebVideoFile (video: MVideoSeo) {
    const files = (video.VideoFiles || []).filter(f => f.resolution !== VideoResolution.H_NOVIDEO)
    if (files.length === 0) return undefined

    return files.sort((a, b) => {
      const distance = Math.abs(a.resolution - 720) - Math.abs(b.resolution - 720)
      if (distance !== 0) return distance

      // prefer smaller file
      return a.resolution - b.resolution
    })[0]
  }

  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)
  }
}