PeerTube/server/models/video/formatter/video-format-utils.ts

522 lines
14 KiB
TypeScript
Raw Normal View History

import { generateMagnetUri } from '@server/helpers/webtorrent'
Add support for saving video files to object storage (#4290) * Add support for saving video files to object storage * Add support for custom url generation on s3 stored files Uses two config keys to support url generation that doesn't directly go to (compatible s3). Can be used to generate urls to any cache server or CDN. * Upload files to s3 concurrently and delete originals afterwards * Only publish after move to object storage is complete * Use base url instead of url template * Fix mistyped config field * Add rudenmentary way to download before transcode * Implement Chocobozzz suggestions https://github.com/Chocobozzz/PeerTube/pull/4290#issuecomment-891670478 The remarks in question: Try to use objectStorage prefix instead of s3 prefix for your function/variables/config names Prefer to use a tree for the config: s3.streaming_playlists_bucket -> object_storage.streaming_playlists.bucket Use uppercase for config: S3.STREAMING_PLAYLISTS_BUCKETINFO.bucket -> OBJECT_STORAGE.STREAMING_PLAYLISTS.BUCKET (maybe BUCKET_NAME instead of BUCKET) I suggest to rename moveJobsRunning to pendingMovingJobs (or better, create a dedicated videoJobInfo table with a pendingMove & videoId columns so we could also use this table to track pending transcoding jobs) https://github.com/Chocobozzz/PeerTube/pull/4290/files#diff-3e26d41ca4bda1de8e1747af70ca2af642abcc1e9e0bfb94239ff2165acfbde5R19 uses a string instead of an integer I think we should store the origin object storage URL in fileUrl, without base_url injection. Instead, inject the base_url at "runtime" so admins can easily change this configuration without running a script to update DB URLs * Import correct function * Support multipart upload * Remove import of node 15.0 module stream/promises * Extend maximum upload job length Using the same value as for redundancy downloading seems logical * Use dynamic part size for really large uploads Also adds very small part size for local testing * Fix decreasePendingMove query * Resolve various PR comments * Move to object storage after optimize * Make upload size configurable and increase default * Prune webtorrent files that are stored in object storage * Move files after transcoding jobs * Fix federation * Add video path manager * Support move to external storage job in client * Fix live object storage tests Co-authored-by: Chocobozzz <me@florianbigard.com>
2021-08-17 01:26:20 -05:00
import { getLocalVideoFileMetadataUrl } from '@server/lib/video-urls'
import { VideoViews } from '@server/lib/video-views'
import { uuidToShort } from '@shared/extra-utils'
2021-11-18 07:35:08 -06:00
import { VideoFile, VideosCommonQueryAfterSanitize } from '@shared/models'
2021-06-10 01:53:32 -05:00
import { ActivityTagObject, ActivityUrlObject, VideoObject } from '../../../../shared/models/activitypub/objects'
import { Video, VideoDetails, VideoInclude } from '../../../../shared/models/videos'
2021-06-10 01:53:32 -05:00
import { VideoStreamingPlaylist } from '../../../../shared/models/videos/video-streaming-playlist.model'
import { isArray } from '../../../helpers/custom-validators/misc'
2021-06-11 07:36:07 -05:00
import {
MIMETYPES,
VIDEO_CATEGORIES,
VIDEO_LANGUAGES,
VIDEO_LICENCES,
VIDEO_PRIVACIES,
VIDEO_STATES,
WEBSERVER
} from '../../../initializers/constants'
import {
2020-11-20 04:21:08 -06:00
getLocalVideoCommentsActivityPubUrl,
getLocalVideoDislikesActivityPubUrl,
getLocalVideoLikesActivityPubUrl,
getLocalVideoSharesActivityPubUrl
2021-06-10 01:53:32 -05:00
} from '../../../lib/activitypub/url'
import {
MServer,
MStreamingPlaylistRedundanciesOpt,
2021-02-18 04:28:00 -06:00
MVideo,
MVideoAP,
MVideoFile,
MVideoFormattable,
2021-02-18 04:28:00 -06:00
MVideoFormattableDetails
2021-06-10 01:53:32 -05:00
} from '../../../types/models'
import { MVideoFileRedundanciesOpt } from '../../../types/models/video/video-file'
import { VideoCaptionModel } from '../video-caption'
export type VideoFormattingJSONOptions = {
completeDescription?: boolean
additionalAttributes?: {
2020-01-31 09:56:52 -06:00
state?: boolean
waitTranscoding?: boolean
scheduledUpdate?: boolean
blacklistInfo?: boolean
files?: boolean
blockedOwner?: boolean
}
}
2020-01-31 09:56:52 -06:00
function guessAdditionalAttributesFromQuery (query: VideosCommonQueryAfterSanitize): VideoFormattingJSONOptions {
if (!query || !query.include) return {}
return {
additionalAttributes: {
state: !!(query.include & VideoInclude.NOT_PUBLISHED_STATE),
waitTranscoding: !!(query.include & VideoInclude.NOT_PUBLISHED_STATE),
scheduledUpdate: !!(query.include & VideoInclude.NOT_PUBLISHED_STATE),
blacklistInfo: !!(query.include & VideoInclude.BLACKLISTED),
files: !!(query.include & VideoInclude.FILES),
blockedOwner: !!(query.include & VideoInclude.BLOCKED_OWNER)
}
}
}
function videoModelToFormattedJSON (video: MVideoFormattable, options: VideoFormattingJSONOptions = {}): Video {
2018-10-05 04:15:06 -05:00
const userHistory = isArray(video.UserVideoHistories) ? video.UserVideoHistories[0] : undefined
const videoObject: Video = {
id: video.id,
uuid: video.uuid,
shortUUID: uuidToShort(video.uuid),
url: video.url,
name: video.name,
category: {
id: video.category,
2021-06-11 07:36:07 -05:00
label: getCategoryLabel(video.category)
},
licence: {
id: video.licence,
2021-06-11 07:36:07 -05:00
label: getLicenceLabel(video.licence)
},
language: {
id: video.language,
2021-06-11 07:36:07 -05:00
label: getLanguageLabel(video.language)
},
privacy: {
id: video.privacy,
2021-06-11 07:36:07 -05:00
label: getPrivacyLabel(video.privacy)
},
nsfw: video.nsfw,
2020-08-24 09:11:37 -05:00
description: options && options.completeDescription === true
? video.description
: video.getTruncatedDescription(),
isLocal: video.isOwned(),
duration: video.duration,
views: video.views,
likes: video.likes,
dislikes: video.dislikes,
2019-04-23 02:50:57 -05:00
thumbnailPath: video.getMiniatureStaticPath(),
previewPath: video.getPreviewStaticPath(),
embedPath: video.getEmbedStaticPath(),
createdAt: video.createdAt,
updatedAt: video.updatedAt,
publishedAt: video.publishedAt,
2019-01-12 07:41:45 -06:00
originallyPublishedAt: video.originallyPublishedAt,
2019-02-26 03:55:40 -06:00
isLive: video.isLive,
2019-02-26 03:55:40 -06:00
account: video.VideoChannel.Account.toFormattedSummaryJSON(),
channel: video.VideoChannel.toFormattedSummaryJSON(),
2018-10-05 04:15:06 -05:00
2021-02-03 02:33:05 -06:00
userHistory: userHistory
? { currentTime: userHistory.currentTime }
: undefined,
// Can be added by external plugins
pluginData: (video as any).pluginData
}
if (video.isLive) {
videoObject.viewers = VideoViews.Instance.getViewers(video)
}
const add = options.additionalAttributes
if (add?.state === true) {
videoObject.state = {
id: video.state,
label: getStateLabel(video.state)
}
}
if (add?.waitTranscoding === true) {
videoObject.waitTranscoding = video.waitTranscoding
}
if (add?.scheduledUpdate === true && video.ScheduleVideoUpdate) {
videoObject.scheduledUpdate = {
updateAt: video.ScheduleVideoUpdate.updateAt,
privacy: video.ScheduleVideoUpdate.privacy || undefined
}
}
if (add?.blacklistInfo === true) {
videoObject.blacklisted = !!video.VideoBlacklist
videoObject.blacklistedReason = video.VideoBlacklist ? video.VideoBlacklist.reason : null
}
if (add?.blockedOwner === true) {
videoObject.blockedOwner = video.VideoChannel.Account.isBlocked()
const server = video.VideoChannel.Account.Actor.Server as MServer
videoObject.blockedServer = !!(server?.isBlocked())
}
if (add?.files === true) {
videoObject.streamingPlaylists = streamingPlaylistsModelToFormattedJSON(video, video.VideoStreamingPlaylists)
videoObject.files = videoFilesModelToFormattedJSON(video, video.VideoFiles)
}
return videoObject
}
2019-08-20 12:05:31 -05:00
function videoModelToFormattedDetailsJSON (video: MVideoFormattableDetails): VideoDetails {
const videoJSON = video.toFormattedJSON({
additionalAttributes: {
scheduledUpdate: true,
blacklistInfo: true,
files: true
}
}) as Video & Required<Pick<Video, 'files' | 'streamingPlaylists'>>
const tags = video.Tags ? video.Tags.map(t => t.name) : []
2019-01-29 01:37:25 -06:00
const detailsJSON = {
support: video.support,
descriptionPath: video.getDescriptionAPIPath(),
channel: video.VideoChannel.toFormattedJSON(),
account: video.VideoChannel.Account.toFormattedJSON(),
tags,
commentsEnabled: video.commentsEnabled,
downloadEnabled: video.downloadEnabled,
waitTranscoding: video.waitTranscoding,
state: {
id: video.state,
2021-06-11 07:36:07 -05:00
label: getStateLabel(video.state)
},
2019-01-29 01:37:25 -06:00
trackerUrls: video.getTrackerUrls()
}
return Object.assign(videoJSON, detailsJSON)
}
function streamingPlaylistsModelToFormattedJSON (
video: MVideoFormattable,
playlists: MStreamingPlaylistRedundanciesOpt[]
): VideoStreamingPlaylist[] {
2019-01-29 01:37:25 -06:00
if (isArray(playlists) === false) return []
return playlists
.map(playlist => {
const redundancies = isArray(playlist.RedundancyVideos)
? playlist.RedundancyVideos.map(r => ({ baseUrl: r.fileUrl }))
: []
2021-02-18 03:15:11 -06:00
const files = videoFilesModelToFormattedJSON(video, playlist.VideoFiles)
2019-01-29 01:37:25 -06:00
return {
id: playlist.id,
type: playlist.type,
2021-07-23 04:20:00 -05:00
playlistUrl: playlist.getMasterPlaylistUrl(video),
segmentsSha256Url: playlist.getSha256SegmentsUrl(video),
redundancies,
files
}
2019-01-29 01:37:25 -06:00
})
}
2020-06-04 08:03:30 -05:00
function sortByResolutionDesc (fileA: MVideoFile, fileB: MVideoFile) {
if (fileA.resolution < fileB.resolution) return 1
if (fileA.resolution === fileB.resolution) return 0
return -1
}
function videoFilesModelToFormattedJSON (
video: MVideoFormattable,
2021-02-18 04:22:35 -06:00
videoFiles: MVideoFileRedundanciesOpt[],
includeMagnet = true
): VideoFile[] {
2021-02-18 04:22:35 -06:00
const trackerUrls = includeMagnet
? video.getTrackerUrls()
: []
2021-02-18 03:15:11 -06:00
2021-07-29 10:18:09 -05:00
return (videoFiles || [])
2020-11-04 08:31:32 -06:00
.filter(f => !f.isLive())
2020-06-04 08:03:30 -05:00
.sort(sortByResolutionDesc)
.map(videoFile => {
return {
resolution: {
id: videoFile.resolution,
label: videoFile.resolution === 0 ? 'Audio' : `${videoFile.resolution}p`
},
magnetUri: includeMagnet && videoFile.hasTorrent()
2021-02-18 04:22:35 -06:00
? generateMagnetUri(video, videoFile, trackerUrls)
: undefined,
size: videoFile.size,
fps: videoFile.fps,
torrentUrl: videoFile.getTorrentUrl(),
torrentDownloadUrl: videoFile.getTorrentDownloadUrl(),
fileUrl: videoFile.getFileUrl(video),
fileDownloadUrl: videoFile.getFileDownloadUrl(video),
metadataUrl: videoFile.metadataUrl ?? getLocalVideoFileMetadataUrl(video, videoFile)
} as VideoFile
})
}
function addVideoFilesInAPAcc (
acc: ActivityUrlObject[] | ActivityTagObject[],
2021-02-18 04:28:00 -06:00
video: MVideo,
files: MVideoFile[]
) {
2021-02-18 03:15:11 -06:00
const trackerUrls = video.getTrackerUrls()
2021-07-29 10:18:09 -05:00
const sortedFiles = (files || [])
2020-11-04 08:31:32 -06:00
.filter(f => !f.isLive())
.sort(sortByResolutionDesc)
2020-06-04 08:03:30 -05:00
for (const file of sortedFiles) {
acc.push({
type: 'Link',
2020-01-31 09:56:52 -06:00
mediaType: MIMETYPES.VIDEO.EXT_MIMETYPE[file.extname] as any,
href: file.getFileUrl(video),
height: file.resolution,
size: file.size,
fps: file.fps
})
acc.push({
type: 'Link',
rel: [ 'metadata', MIMETYPES.VIDEO.EXT_MIMETYPE[file.extname] ],
mediaType: 'application/json' as 'application/json',
href: getLocalVideoFileMetadataUrl(video, file),
height: file.resolution,
fps: file.fps
})
if (file.hasTorrent()) {
acc.push({
type: 'Link',
mediaType: 'application/x-bittorrent' as 'application/x-bittorrent',
href: file.getTorrentUrl(),
height: file.resolution
})
acc.push({
type: 'Link',
mediaType: 'application/x-bittorrent;x-scheme-handler/magnet' as 'application/x-bittorrent;x-scheme-handler/magnet',
href: generateMagnetUri(video, file, trackerUrls),
height: file.resolution
})
}
}
}
2020-09-17 06:59:02 -05:00
function videoModelToActivityPubObject (video: MVideoAP): VideoObject {
if (!video.Tags) video.Tags = []
const tag = video.Tags.map(t => ({
type: 'Hashtag' as 'Hashtag',
name: t.name
}))
let language
if (video.language) {
language = {
identifier: video.language,
2021-06-11 07:36:07 -05:00
name: getLanguageLabel(video.language)
}
}
let category
if (video.category) {
category = {
identifier: video.category + '',
2021-06-11 07:36:07 -05:00
name: getCategoryLabel(video.category)
}
}
let licence
if (video.licence) {
licence = {
identifier: video.licence + '',
2021-06-11 07:36:07 -05:00
name: getLicenceLabel(video.licence)
}
}
2020-02-04 02:19:56 -06:00
const url: ActivityUrlObject[] = [
// HTML url should be the first element in the array so Mastodon correctly displays the embed
{
type: 'Link',
mediaType: 'text/html',
href: WEBSERVER.URL + '/videos/watch/' + video.uuid
}
]
2021-02-18 03:15:11 -06:00
addVideoFilesInAPAcc(url, video, video.VideoFiles || [])
2019-01-29 01:37:25 -06:00
for (const playlist of (video.VideoStreamingPlaylists || [])) {
2020-01-31 09:56:52 -06:00
const tag = playlist.p2pMediaLoaderInfohashes
.map(i => ({ type: 'Infohash' as 'Infohash', name: i })) as ActivityTagObject[]
2019-01-29 01:37:25 -06:00
tag.push({
type: 'Link',
name: 'sha256',
mediaType: 'application/json' as 'application/json',
2021-07-23 04:20:00 -05:00
href: playlist.getSha256SegmentsUrl(video)
2019-01-29 01:37:25 -06:00
})
2021-02-18 03:15:11 -06:00
addVideoFilesInAPAcc(tag, video, playlist.VideoFiles || [])
2019-01-29 01:37:25 -06:00
url.push({
type: 'Link',
mediaType: 'application/x-mpegURL' as 'application/x-mpegURL',
2021-07-23 04:20:00 -05:00
href: playlist.getMasterPlaylistUrl(video),
2019-01-29 01:37:25 -06:00
tag
})
}
2021-02-18 03:15:11 -06:00
for (const trackerUrl of video.getTrackerUrls()) {
const rel2 = trackerUrl.startsWith('http')
? 'http'
: 'websocket'
url.push({
type: 'Link',
name: `tracker-${rel2}`,
rel: [ 'tracker', rel2 ],
href: trackerUrl
})
}
const subtitleLanguage = []
for (const caption of video.VideoCaptions) {
subtitleLanguage.push({
identifier: caption.language,
name: VideoCaptionModel.getLanguageLabel(caption.language),
url: caption.getFileUrl(video)
})
}
2020-06-04 08:22:08 -05:00
const icons = [ video.getMiniature(), video.getPreview() ]
2019-04-23 02:50:57 -05:00
return {
type: 'Video' as 'Video',
id: video.url,
name: video.name,
duration: getActivityStreamDuration(video.duration),
uuid: video.uuid,
tag,
category,
licence,
language,
views: video.views,
sensitive: video.nsfw,
waitTranscoding: video.waitTranscoding,
2020-12-03 07:10:54 -06:00
state: video.state,
commentsEnabled: video.commentsEnabled,
downloadEnabled: video.downloadEnabled,
published: video.publishedAt.toISOString(),
2020-11-02 08:43:44 -06:00
originallyPublishedAt: video.originallyPublishedAt
? video.originallyPublishedAt.toISOString()
: null,
updated: video.updatedAt.toISOString(),
2022-03-04 06:40:02 -06:00
mediaType: 'text/markdown',
content: video.description,
support: video.support,
2022-03-04 06:40:02 -06:00
subtitleLanguage,
2022-03-04 06:40:02 -06:00
2020-06-04 08:22:08 -05:00
icon: icons.map(i => ({
type: 'Image',
2020-06-04 08:22:08 -05:00
url: i.getFileUrl(video),
mediaType: 'image/jpeg',
2020-06-04 08:22:08 -05:00
width: i.width,
height: i.height
})),
2022-03-04 06:40:02 -06:00
url,
2022-03-04 06:40:02 -06:00
2020-11-20 04:21:08 -06:00
likes: getLocalVideoLikesActivityPubUrl(video),
dislikes: getLocalVideoDislikesActivityPubUrl(video),
shares: getLocalVideoSharesActivityPubUrl(video),
comments: getLocalVideoCommentsActivityPubUrl(video),
2022-03-04 06:40:02 -06:00
attributedTo: [
{
type: 'Person',
id: video.VideoChannel.Account.Actor.url
},
{
type: 'Group',
id: video.VideoChannel.Actor.url
}
2022-03-04 06:40:02 -06:00
],
...buildLiveAPAttributes(video)
}
}
function getActivityStreamDuration (duration: number) {
// https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
return 'PT' + duration + 'S'
}
2021-06-11 07:36:07 -05:00
function getCategoryLabel (id: number) {
return VIDEO_CATEGORIES[id] || 'Misc'
}
function getLicenceLabel (id: number) {
return VIDEO_LICENCES[id] || 'Unknown'
}
function getLanguageLabel (id: string) {
return VIDEO_LANGUAGES[id] || 'Unknown'
}
function getPrivacyLabel (id: number) {
return VIDEO_PRIVACIES[id] || 'Unknown'
}
function getStateLabel (id: number) {
return VIDEO_STATES[id] || 'Unknown'
}
export {
videoModelToFormattedJSON,
videoModelToFormattedDetailsJSON,
videoFilesModelToFormattedJSON,
videoModelToActivityPubObject,
2021-06-11 07:36:07 -05:00
getActivityStreamDuration,
guessAdditionalAttributesFromQuery,
2021-06-11 07:36:07 -05:00
getCategoryLabel,
getLicenceLabel,
getLanguageLabel,
getPrivacyLabel,
getStateLabel
}
2022-03-04 06:40:02 -06:00
// ---------------------------------------------------------------------------
function buildLiveAPAttributes (video: MVideoAP) {
if (!video.isLive) {
return {
isLiveBroadcast: false,
liveSaveReplay: null,
permanentLive: null,
latencyMode: null
}
}
return {
isLiveBroadcast: true,
liveSaveReplay: video.VideoLive.saveReplay,
permanentLive: video.VideoLive.permanentLive,
latencyMode: video.VideoLive.latencyMode
}
}