diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 093a2495ede..35c91bf85bc 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -45,6 +45,7 @@ jobs: PGUSER: peertube PGHOST: localhost NODE_PENDING_JOB_WAIT: 250 + ENABLE_OBJECT_STORAGE_TESTS: true steps: - uses: actions/checkout@v2 diff --git a/config/default.yaml b/config/default.yaml index 2227abbd522..3865ab5cf19 100644 --- a/config/default.yaml +++ b/config/default.yaml @@ -99,16 +99,18 @@ object_storage: enabled: false # Without protocol, will default to HTTPS - endpoint: 's3.amazonaws.com' + endpoint: '' # 's3.amazonaws.com' or 's3.fr-par.scw.cloud' for example region: 'us-east-1' credentials: - access_key_id: 'access-key' - secret_access_key: 'secret-access-key' + # You can also use AWS_ACCESS_KEY_ID env variable + access_key_id: '' + # You can also use AWS_SECRET_ACCESS_KEY env variable + secret_access_key: '' # Maximum amount to upload in one request to object storage - max_upload_part: 2MB + max_upload_part: 2GB streaming_playlists: bucket_name: 'streaming-playlists' diff --git a/config/production.yaml.example b/config/production.yaml.example index 514ab99a47c..94238fad00f 100644 --- a/config/production.yaml.example +++ b/config/production.yaml.example @@ -93,6 +93,39 @@ storage: # If not, peertube will fallback to the default file client_overrides: '/var/www/peertube/storage/client-overrides/' +object_storage: + enabled: false + + # Without protocol, will default to HTTPS + endpoint: '' # 's3.amazonaws.com' or 's3.fr-par.scw.cloud' for example + + region: 'us-east-1' + + credentials: + # You can also use AWS_ACCESS_KEY_ID env variable + access_key_id: '' + # You can also use AWS_SECRET_ACCESS_KEY env variable + secret_access_key: '' + + # Maximum amount to upload in one request to object storage + max_upload_part: 2GB + + streaming_playlists: + bucket_name: 'streaming-playlists' + + # Allows setting all buckets to the same value but with a different prefix + prefix: '' # Example: 'streaming-playlists:' + + # Base url for object URL generation, scheme and host will be replaced by this URL + # Useful when you want to use a CDN/external proxy + base_url: '' # Example: 'https://mirror.example.com' + + # Same settings but for webtorrent videos + videos: + bucket_name: 'videos' + prefix: '' + base_url: '' + log: level: 'info' # 'debug' | 'info' | 'warn' | 'error' rotation: diff --git a/scripts/create-transcoding-job.ts b/scripts/create-transcoding-job.ts index ba885d97583..0bb9bfeab8d 100755 --- a/scripts/create-transcoding-job.ts +++ b/scripts/create-transcoding-job.ts @@ -6,7 +6,7 @@ import { VideoModel } from '../server/models/video/video' import { initDatabaseModels } from '../server/initializers/database' import { JobQueue } from '../server/lib/job-queue' import { computeResolutionsToTranscode } from '@server/helpers/ffprobe-utils' -import { VideoTranscodingPayload } from '@shared/models' +import { VideoState, VideoTranscodingPayload } from '@shared/models' import { CONFIG } from '@server/initializers/config' import { isUUIDValid } from '@server/helpers/custom-validators/misc' import { addTranscodingJob } from '@server/lib/video' @@ -48,7 +48,7 @@ async function run () { if (!video) throw new Error('Video not found.') const dataInput: VideoTranscodingPayload[] = [] - const { resolution } = await video.getMaxQualityResolution() + const resolution = video.getMaxQualityFile().resolution // Generate HLS files if (options.generateHls || CONFIG.TRANSCODING.WEBTORRENT.ENABLED === false) { @@ -63,6 +63,7 @@ async function run () { resolution, isPortraitMode: false, copyCodecs: false, + isNewVideo: false, isMaxQuality: false }) } @@ -88,7 +89,10 @@ async function run () { } } - await JobQueue.Instance.init() + JobQueue.Instance.init() + + video.state = VideoState.TO_TRANSCODE + await video.save() for (const d of dataInput) { await addTranscodingJob(d, {}) diff --git a/scripts/optimize-old-videos.ts b/scripts/optimize-old-videos.ts index 81594d72c0e..245e4cf284f 100644 --- a/scripts/optimize-old-videos.ts +++ b/scripts/optimize-old-videos.ts @@ -1,19 +1,19 @@ +import { registerTSPaths } from '../server/helpers/register-ts-paths' +registerTSPaths() + import { copy, move, remove } from 'fs-extra' import { basename, dirname } from 'path' import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent' import { CONFIG } from '@server/initializers/config' import { processMoveToObjectStorage } from '@server/lib/job-queue/handlers/move-to-object-storage' -import { getVideoFilePath, getVideoFilePathMakeAvailable } from '@server/lib/video-paths' +import { VideoPathManager } from '@server/lib/video-path-manager' import { getMaxBitrate } from '@shared/core-utils' import { MoveObjectStoragePayload } from '@shared/models' import { getDurationFromVideoFile, getVideoFileBitrate, getVideoFileFPS, getVideoFileResolution } from '../server/helpers/ffprobe-utils' -import { registerTSPaths } from '../server/helpers/register-ts-paths' import { initDatabaseModels } from '../server/initializers/database' import { optimizeOriginalVideofile } from '../server/lib/transcoding/video-transcoding' import { VideoModel } from '../server/models/video/video' -registerTSPaths() - run() .then(() => process.exit(0)) .catch(err => { @@ -42,43 +42,45 @@ async function run () { currentVideoId = video.id for (const file of video.VideoFiles) { - currentFilePath = await getVideoFilePathMakeAvailable(video, file) - - const [ videoBitrate, fps, dataResolution ] = await Promise.all([ - getVideoFileBitrate(currentFilePath), - getVideoFileFPS(currentFilePath), - getVideoFileResolution(currentFilePath) - ]) - - const maxBitrate = getMaxBitrate({ ...dataResolution, fps }) - const isMaxBitrateExceeded = videoBitrate > maxBitrate - if (isMaxBitrateExceeded) { - console.log( - 'Optimizing video file %s with bitrate %s kbps (max: %s kbps)', - basename(currentFilePath), videoBitrate / 1000, maxBitrate / 1000 - ) - - const backupFile = `${currentFilePath}_backup` - await copy(currentFilePath, backupFile) - - await optimizeOriginalVideofile(video, file) - // Update file path, the video filename changed - currentFilePath = getVideoFilePath(video, file) - - const originalDuration = await getDurationFromVideoFile(backupFile) - const newDuration = await getDurationFromVideoFile(currentFilePath) - - if (originalDuration === newDuration) { - console.log('Finished optimizing %s', basename(currentFilePath)) - await remove(backupFile) - continue + await VideoPathManager.Instance.makeAvailableVideoFile(video, file, async path => { + currentFilePath = path + + const [ videoBitrate, fps, dataResolution ] = await Promise.all([ + getVideoFileBitrate(currentFilePath), + getVideoFileFPS(currentFilePath), + getVideoFileResolution(currentFilePath) + ]) + + const maxBitrate = getMaxBitrate({ ...dataResolution, fps }) + const isMaxBitrateExceeded = videoBitrate > maxBitrate + if (isMaxBitrateExceeded) { + console.log( + 'Optimizing video file %s with bitrate %s kbps (max: %s kbps)', + basename(currentFilePath), videoBitrate / 1000, maxBitrate / 1000 + ) + + const backupFile = `${currentFilePath}_backup` + await copy(currentFilePath, backupFile) + + await optimizeOriginalVideofile(video, file) + // Update file path, the video filename changed + currentFilePath = VideoPathManager.Instance.getFSVideoFileOutputPath(video, file) + + const originalDuration = await getDurationFromVideoFile(backupFile) + const newDuration = await getDurationFromVideoFile(currentFilePath) + + if (originalDuration === newDuration) { + console.log('Finished optimizing %s', basename(currentFilePath)) + await remove(backupFile) + return + } + + console.log('Failed to optimize %s, restoring original', basename(currentFilePath)) + await move(backupFile, currentFilePath, { overwrite: true }) + await createTorrentAndSetInfoHash(video, file) + await file.save() } - - console.log('Failed to optimize %s, restoring original', basename(currentFilePath)) - await move(backupFile, currentFilePath, { overwrite: true }) - await createTorrentAndSetInfoHash(video, file) - await file.save() - } + }) } if (CONFIG.OBJECT_STORAGE.ENABLED === true) { diff --git a/server/controllers/api/videos/upload.ts b/server/controllers/api/videos/upload.ts index 22de0d66230..5c740c0410e 100644 --- a/server/controllers/api/videos/upload.ts +++ b/server/controllers/api/videos/upload.ts @@ -1,10 +1,12 @@ import * as express from 'express' import { move } from 'fs-extra' +import { basename } from 'path' import { getLowercaseExtension } from '@server/helpers/core-utils' import { deleteResumableUploadMetaFile, getResumableUploadPath } from '@server/helpers/upload' import { uuidToShort } from '@server/helpers/uuid' import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent' import { getLocalVideoActivityPubUrl } from '@server/lib/activitypub/url' +import { generateWebTorrentVideoFilename } from '@server/lib/paths' import { addMoveToObjectStorageJob, addOptimizeOrMergeAudioJob, @@ -12,7 +14,7 @@ import { buildVideoThumbnailsFromReq, setVideoTags } from '@server/lib/video' -import { generateWebTorrentVideoFilename, getVideoFilePath } from '@server/lib/video-paths' +import { VideoPathManager } from '@server/lib/video-path-manager' import { buildNextVideoState } from '@server/lib/video-state' import { openapiOperationDoc } from '@server/middlewares/doc' import { MVideo, MVideoFile, MVideoFullLight } from '@server/types/models' @@ -153,13 +155,13 @@ async function addVideo (options: { video.VideoChannel = videoChannel video.url = getLocalVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object - const videoFile = await buildNewFile(video, videoPhysicalFile) + const videoFile = await buildNewFile(videoPhysicalFile) // Move physical file - const destination = getVideoFilePath(video, videoFile) + const destination = VideoPathManager.Instance.getFSVideoFileOutputPath(video, videoFile) await move(videoPhysicalFile.path, destination) // This is important in case if there is another attempt in the retry process - videoPhysicalFile.filename = getVideoFilePath(video, videoFile) + videoPhysicalFile.filename = basename(destination) videoPhysicalFile.path = destination const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({ @@ -235,7 +237,7 @@ async function addVideo (options: { }) } -async function buildNewFile (video: MVideo, videoPhysicalFile: express.VideoUploadFile) { +async function buildNewFile (videoPhysicalFile: express.VideoUploadFile) { const videoFile = new VideoFileModel({ extname: getLowercaseExtension(videoPhysicalFile.filename), size: videoPhysicalFile.size, diff --git a/server/controllers/download.ts b/server/controllers/download.ts index 65aa53420e7..ffe40d57e3c 100644 --- a/server/controllers/download.ts +++ b/server/controllers/download.ts @@ -3,7 +3,7 @@ import * as express from 'express' import { logger } from '@server/helpers/logger' import { VideosTorrentCache } from '@server/lib/files-cache/videos-torrent-cache' import { Hooks } from '@server/lib/plugins/hooks' -import { getVideoFilePath } from '@server/lib/video-paths' +import { VideoPathManager } from '@server/lib/video-path-manager' import { MStreamingPlaylist, MVideo, MVideoFile, MVideoFullLight } from '@server/types/models' import { HttpStatusCode, VideoStorage, VideoStreamingPlaylistType } from '@shared/models' import { STATIC_DOWNLOAD_PATHS } from '../initializers/constants' @@ -85,7 +85,11 @@ async function downloadVideoFile (req: express.Request, res: express.Response) { return res.redirect(videoFile.getObjectStorageUrl()) } - return res.download(getVideoFilePath(video, videoFile), `${video.name}-${videoFile.resolution}p${videoFile.extname}`) + await VideoPathManager.Instance.makeAvailableVideoFile(video, videoFile, path => { + const filename = `${video.name}-${videoFile.resolution}p${videoFile.extname}` + + return res.download(path, filename) + }) } async function downloadHLSVideoFile (req: express.Request, res: express.Response) { @@ -115,8 +119,11 @@ async function downloadHLSVideoFile (req: express.Request, res: express.Response return res.redirect(videoFile.getObjectStorageUrl()) } - const filename = `${video.name}-${videoFile.resolution}p-${streamingPlaylist.getStringType()}${videoFile.extname}` - return res.download(getVideoFilePath(streamingPlaylist, videoFile), filename) + await VideoPathManager.Instance.makeAvailableVideoFile(streamingPlaylist, videoFile, path => { + const filename = `${video.name}-${videoFile.resolution}p-${streamingPlaylist.getStringType()}${videoFile.extname}` + + return res.download(path, filename) + }) } function getVideoFile (req: express.Request, files: MVideoFile[]) { diff --git a/server/helpers/webtorrent.ts b/server/helpers/webtorrent.ts index ecf63e93e74..c8437630445 100644 --- a/server/helpers/webtorrent.ts +++ b/server/helpers/webtorrent.ts @@ -6,7 +6,8 @@ import { dirname, join } from 'path' import * as WebTorrent from 'webtorrent' import { isArray } from '@server/helpers/custom-validators/misc' import { WEBSERVER } from '@server/initializers/constants' -import { generateTorrentFileName, getVideoFilePath } from '@server/lib/video-paths' +import { generateTorrentFileName } from '@server/lib/paths' +import { VideoPathManager } from '@server/lib/video-path-manager' import { MVideo } from '@server/types/models/video/video' import { MVideoFile, MVideoFileRedundanciesOpt } from '@server/types/models/video/video-file' import { MStreamingPlaylistVideo } from '@server/types/models/video/video-streaming-playlist' @@ -78,7 +79,7 @@ async function downloadWebTorrentVideo (target: { magnetUri: string, torrentName }) } -async function createTorrentAndSetInfoHash ( +function createTorrentAndSetInfoHash ( videoOrPlaylist: MVideo | MStreamingPlaylistVideo, videoFile: MVideoFile ) { @@ -95,22 +96,24 @@ async function createTorrentAndSetInfoHash ( urlList: [ videoFile.getFileUrl(video) ] } - const torrent = await createTorrentPromise(getVideoFilePath(videoOrPlaylist, videoFile), options) + return VideoPathManager.Instance.makeAvailableVideoFile(videoOrPlaylist, videoFile, async videoPath => { + const torrent = await createTorrentPromise(videoPath, options) - const torrentFilename = generateTorrentFileName(videoOrPlaylist, videoFile.resolution) - const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, torrentFilename) - logger.info('Creating torrent %s.', torrentPath) + const torrentFilename = generateTorrentFileName(videoOrPlaylist, videoFile.resolution) + const torrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, torrentFilename) + logger.info('Creating torrent %s.', torrentPath) - await writeFile(torrentPath, torrent) + await writeFile(torrentPath, torrent) - // Remove old torrent file if it existed - if (videoFile.hasTorrent()) { - await remove(join(CONFIG.STORAGE.TORRENTS_DIR, videoFile.torrentFilename)) - } + // Remove old torrent file if it existed + if (videoFile.hasTorrent()) { + await remove(join(CONFIG.STORAGE.TORRENTS_DIR, videoFile.torrentFilename)) + } - const parsedTorrent = parseTorrent(torrent) - videoFile.infoHash = parsedTorrent.infoHash - videoFile.torrentFilename = torrentFilename + const parsedTorrent = parseTorrent(torrent) + videoFile.infoHash = parsedTorrent.infoHash + videoFile.torrentFilename = torrentFilename + }) } function generateMagnetUri ( diff --git a/server/initializers/migrations/0065-video-file-size.ts b/server/initializers/migrations/0065-video-file-size.ts index 1aeb27f2dce..ac952a98cc5 100644 --- a/server/initializers/migrations/0065-video-file-size.ts +++ b/server/initializers/migrations/0065-video-file-size.ts @@ -1,7 +1,4 @@ import * as Sequelize from 'sequelize' -import { stat } from 'fs-extra' -import { VideoModel } from '../../models/video/video' -import { getVideoFilePath } from '@server/lib/video-paths' function up (utils: { transaction: Sequelize.Transaction @@ -9,30 +6,7 @@ function up (utils: { sequelize: Sequelize.Sequelize db: any }): Promise { - return utils.db.Video.listOwnedAndPopulateAuthorAndTags() - .then((videos: VideoModel[]) => { - const tasks: Promise[] = [] - - videos.forEach(video => { - video.VideoFiles.forEach(videoFile => { - const p = new Promise((res, rej) => { - stat(getVideoFilePath(video, videoFile), (err, stats) => { - if (err) return rej(err) - - videoFile.size = stats.size - videoFile.save().then(res).catch(rej) - }) - }) - - tasks.push(p) - }) - }) - - return tasks - }) - .then((tasks: Promise[]) => { - return Promise.all(tasks) - }) + throw new Error('Removed, please upgrade from a previous version first.') } function down (options) { diff --git a/server/initializers/migrations/0660-object-storage.ts b/server/initializers/migrations/0660-object-storage.ts index 1cc265bfbb3..c815c71c65d 100644 --- a/server/initializers/migrations/0660-object-storage.ts +++ b/server/initializers/migrations/0660-object-storage.ts @@ -12,7 +12,7 @@ async function up (utils: { CREATE TABLE IF NOT EXISTS "videoJobInfo" ( "id" serial, "pendingMove" INTEGER NOT NULL, - "pendingTranscoding" INTEGER NOT NULL, + "pendingTranscode" INTEGER NOT NULL, "videoId" serial UNIQUE NOT NULL REFERENCES "video" ("id") ON DELETE CASCADE ON UPDATE CASCADE, "createdAt" timestamp WITH time zone NOT NULL, "updatedAt" timestamp WITH time zone NOT NULL, @@ -28,7 +28,7 @@ async function up (utils: { } { await utils.sequelize.query( - `UPDATE "videoFile" SET "storage" = ${VideoStorage.LOCAL}` + `UPDATE "videoFile" SET "storage" = ${VideoStorage.FILE_SYSTEM}` ) } { @@ -40,7 +40,7 @@ async function up (utils: { } { await utils.sequelize.query( - `UPDATE "videoStreamingPlaylist" SET "storage" = ${VideoStorage.LOCAL}` + `UPDATE "videoStreamingPlaylist" SET "storage" = ${VideoStorage.FILE_SYSTEM}` ) } { diff --git a/server/lib/activitypub/videos/shared/object-to-model-attributes.ts b/server/lib/activitypub/videos/shared/object-to-model-attributes.ts index 1fa16295d44..bd9ed45a9d7 100644 --- a/server/lib/activitypub/videos/shared/object-to-model-attributes.ts +++ b/server/lib/activitypub/videos/shared/object-to-model-attributes.ts @@ -6,7 +6,7 @@ import { isVideoFileInfoHashValid } from '@server/helpers/custom-validators/vide import { logger } from '@server/helpers/logger' import { getExtFromMimetype } from '@server/helpers/video' import { ACTIVITY_PUB, MIMETYPES, P2P_MEDIA_LOADER_PEER_VERSION, PREVIEWS_SIZE, THUMBNAILS_SIZE } from '@server/initializers/constants' -import { generateTorrentFileName } from '@server/lib/video-paths' +import { generateTorrentFileName } from '@server/lib/paths' import { VideoCaptionModel } from '@server/models/video/video-caption' import { VideoFileModel } from '@server/models/video/video-file' import { VideoStreamingPlaylistModel } from '@server/models/video/video-streaming-playlist' diff --git a/server/lib/hls.ts b/server/lib/hls.ts index 0e77ab9fa0d..0828a2d0fda 100644 --- a/server/lib/hls.ts +++ b/server/lib/hls.ts @@ -1,4 +1,4 @@ -import { close, ensureDir, move, open, outputJSON, pathExists, read, readFile, remove, stat, writeFile } from 'fs-extra' +import { close, ensureDir, move, open, outputJSON, read, readFile, remove, stat, writeFile } from 'fs-extra' import { flatten, uniq } from 'lodash' import { basename, dirname, join } from 'path' import { MStreamingPlaylistFilesVideo, MVideoWithFile } from '@server/types/models' @@ -8,11 +8,12 @@ import { logger } from '../helpers/logger' import { doRequest, doRequestAndSaveToFile } from '../helpers/requests' import { generateRandomString } from '../helpers/utils' import { CONFIG } from '../initializers/config' -import { HLS_STREAMING_PLAYLIST_DIRECTORY, P2P_MEDIA_LOADER_PEER_VERSION } from '../initializers/constants' +import { P2P_MEDIA_LOADER_PEER_VERSION } from '../initializers/constants' import { sequelizeTypescript } from '../initializers/database' import { VideoFileModel } from '../models/video/video-file' import { VideoStreamingPlaylistModel } from '../models/video/video-streaming-playlist' -import { getHlsResolutionPlaylistFilename, getVideoFilePath } from './video-paths' +import { getHlsResolutionPlaylistFilename } from './paths' +import { VideoPathManager } from './video-path-manager' async function updateStreamingPlaylistsInfohashesIfNeeded () { const playlistsToUpdate = await VideoStreamingPlaylistModel.listByIncorrectPeerVersion() @@ -31,75 +32,66 @@ async function updateStreamingPlaylistsInfohashesIfNeeded () { } async function updateMasterHLSPlaylist (video: MVideoWithFile, playlist: MStreamingPlaylistFilesVideo) { - const directory = join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid) - const masterPlaylists: string[] = [ '#EXTM3U', '#EXT-X-VERSION:3' ] - const masterPlaylistPath = join(directory, playlist.playlistFilename) - for (const file of playlist.VideoFiles) { const playlistFilename = getHlsResolutionPlaylistFilename(file.filename) - // If we did not generated a playlist for this resolution, skip - const filePlaylistPath = join(directory, playlistFilename) - if (await pathExists(filePlaylistPath) === false) continue - - const videoFilePath = getVideoFilePath(playlist, file) + await VideoPathManager.Instance.makeAvailableVideoFile(playlist, file, async videoFilePath => { + const size = await getVideoStreamSize(videoFilePath) - const size = await getVideoStreamSize(videoFilePath) + const bandwidth = 'BANDWIDTH=' + video.getBandwidthBits(file) + const resolution = `RESOLUTION=${size.width}x${size.height}` - const bandwidth = 'BANDWIDTH=' + video.getBandwidthBits(file) - const resolution = `RESOLUTION=${size.width}x${size.height}` + let line = `#EXT-X-STREAM-INF:${bandwidth},${resolution}` + if (file.fps) line += ',FRAME-RATE=' + file.fps - let line = `#EXT-X-STREAM-INF:${bandwidth},${resolution}` - if (file.fps) line += ',FRAME-RATE=' + file.fps + const codecs = await Promise.all([ + getVideoStreamCodec(videoFilePath), + getAudioStreamCodec(videoFilePath) + ]) - const codecs = await Promise.all([ - getVideoStreamCodec(videoFilePath), - getAudioStreamCodec(videoFilePath) - ]) + line += `,CODECS="${codecs.filter(c => !!c).join(',')}"` - line += `,CODECS="${codecs.filter(c => !!c).join(',')}"` - - masterPlaylists.push(line) - masterPlaylists.push(playlistFilename) + masterPlaylists.push(line) + masterPlaylists.push(playlistFilename) + }) } - await writeFile(masterPlaylistPath, masterPlaylists.join('\n') + '\n') + await VideoPathManager.Instance.makeAvailablePlaylistFile(playlist, playlist.playlistFilename, masterPlaylistPath => { + return writeFile(masterPlaylistPath, masterPlaylists.join('\n') + '\n') + }) } async function updateSha256VODSegments (video: MVideoWithFile, playlist: MStreamingPlaylistFilesVideo) { const json: { [filename: string]: { [range: string]: string } } = {} - const playlistDirectory = join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid) - // For all the resolutions available for this video for (const file of playlist.VideoFiles) { const rangeHashes: { [range: string]: string } = {} - const videoPath = getVideoFilePath(playlist, file) - const resolutionPlaylistPath = join(playlistDirectory, getHlsResolutionPlaylistFilename(file.filename)) - - // Maybe the playlist is not generated for this resolution yet - if (!await pathExists(resolutionPlaylistPath)) continue + await VideoPathManager.Instance.makeAvailableVideoFile(playlist, file, videoPath => { - const playlistContent = await readFile(resolutionPlaylistPath) - const ranges = getRangesFromPlaylist(playlistContent.toString()) + return VideoPathManager.Instance.makeAvailableResolutionPlaylistFile(playlist, file, async resolutionPlaylistPath => { + const playlistContent = await readFile(resolutionPlaylistPath) + const ranges = getRangesFromPlaylist(playlistContent.toString()) - const fd = await open(videoPath, 'r') - for (const range of ranges) { - const buf = Buffer.alloc(range.length) - await read(fd, buf, 0, range.length, range.offset) + const fd = await open(videoPath, 'r') + for (const range of ranges) { + const buf = Buffer.alloc(range.length) + await read(fd, buf, 0, range.length, range.offset) - rangeHashes[`${range.offset}-${range.offset + range.length - 1}`] = sha256(buf) - } - await close(fd) + rangeHashes[`${range.offset}-${range.offset + range.length - 1}`] = sha256(buf) + } + await close(fd) - const videoFilename = file.filename - json[videoFilename] = rangeHashes + const videoFilename = file.filename + json[videoFilename] = rangeHashes + }) + }) } - const outputPath = join(playlistDirectory, playlist.segmentsSha256Filename) + const outputPath = VideoPathManager.Instance.getFSHLSOutputPath(video, playlist.segmentsSha256Filename) await outputJSON(outputPath, json) } diff --git a/server/lib/job-queue/handlers/move-to-object-storage.ts b/server/lib/job-queue/handlers/move-to-object-storage.ts index 2b1dca3d18e..a0c58d21143 100644 --- a/server/lib/job-queue/handlers/move-to-object-storage.ts +++ b/server/lib/job-queue/handlers/move-to-object-storage.ts @@ -4,13 +4,12 @@ import { join } from 'path' import { logger } from '@server/helpers/logger' import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent' import { CONFIG } from '@server/initializers/config' -import { HLS_STREAMING_PLAYLIST_DIRECTORY } from '@server/initializers/constants' import { storeHLSFile, storeWebTorrentFile } from '@server/lib/object-storage' -import { getHLSDirectory, getHlsResolutionPlaylistFilename } from '@server/lib/video-paths' +import { getHLSDirectory, getHlsResolutionPlaylistFilename } from '@server/lib/paths' import { moveToNextState } from '@server/lib/video-state' import { VideoModel } from '@server/models/video/video' import { VideoJobInfoModel } from '@server/models/video/video-job-info' -import { MVideoFile, MVideoWithAllFiles } from '@server/types/models' +import { MStreamingPlaylistVideo, MVideo, MVideoFile, MVideoWithAllFiles } from '@server/types/models' import { MoveObjectStoragePayload, VideoStorage } from '../../../../shared' export async function processMoveToObjectStorage (job: Bull.Job) { @@ -28,14 +27,14 @@ export async function processMoveToObjectStorage (job: Bull.Job) { await moveWebTorrentFiles(video) } - if (CONFIG.TRANSCODING.HLS.ENABLED && video.VideoStreamingPlaylists) { + if (video.VideoStreamingPlaylists) { await moveHLSFiles(video) } const pendingMove = await VideoJobInfoModel.decrease(video.uuid, 'pendingMove') if (pendingMove === 0) { logger.info('Running cleanup after moving files to object storage (video %s in job %d)', video.uuid, job.id) - await doAfterLastJob(video) + await doAfterLastJob(video, payload.isNewVideo) } return payload.videoUUID @@ -45,12 +44,12 @@ export async function processMoveToObjectStorage (job: Bull.Job) { async function moveWebTorrentFiles (video: MVideoWithAllFiles) { for (const file of video.VideoFiles) { - if (file.storage !== VideoStorage.LOCAL) continue + if (file.storage !== VideoStorage.FILE_SYSTEM) continue const fileUrl = await storeWebTorrentFile(file.filename) const oldPath = join(CONFIG.STORAGE.VIDEOS_DIR, file.filename) - await onFileMoved({ video, file, fileUrl, oldPath }) + await onFileMoved({ videoOrPlaylist: video, file, fileUrl, oldPath }) } } @@ -58,7 +57,7 @@ async function moveHLSFiles (video: MVideoWithAllFiles) { for (const playlist of video.VideoStreamingPlaylists) { for (const file of playlist.VideoFiles) { - if (file.storage !== VideoStorage.LOCAL) continue + if (file.storage !== VideoStorage.FILE_SYSTEM) continue // Resolution playlist const playlistFilename = getHlsResolutionPlaylistFilename(file.filename) @@ -69,13 +68,15 @@ async function moveHLSFiles (video: MVideoWithAllFiles) { const oldPath = join(getHLSDirectory(video), file.filename) - await onFileMoved({ video, file, fileUrl, oldPath }) + await onFileMoved({ videoOrPlaylist: Object.assign(playlist, { Video: video }), file, fileUrl, oldPath }) } } } -async function doAfterLastJob (video: MVideoWithAllFiles) { +async function doAfterLastJob (video: MVideoWithAllFiles, isNewVideo: boolean) { for (const playlist of video.VideoStreamingPlaylists) { + if (playlist.storage === VideoStorage.OBJECT_STORAGE) continue + // Master playlist playlist.playlistUrl = await storeHLSFile(playlist, video, playlist.playlistFilename) // Sha256 segments file @@ -88,24 +89,24 @@ async function doAfterLastJob (video: MVideoWithAllFiles) { // Remove empty hls video directory if (video.VideoStreamingPlaylists) { - await remove(join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid)) + await remove(getHLSDirectory(video)) } - await moveToNextState(video) + await moveToNextState(video, isNewVideo) } async function onFileMoved (options: { - video: MVideoWithAllFiles + videoOrPlaylist: MVideo | MStreamingPlaylistVideo file: MVideoFile fileUrl: string oldPath: string }) { - const { video, file, fileUrl, oldPath } = options + const { videoOrPlaylist, file, fileUrl, oldPath } = options file.fileUrl = fileUrl file.storage = VideoStorage.OBJECT_STORAGE - await createTorrentAndSetInfoHash(video, file) + await createTorrentAndSetInfoHash(videoOrPlaylist, file) await file.save() logger.debug('Removing %s because it\'s now on object storage', oldPath) diff --git a/server/lib/job-queue/handlers/video-file-import.ts b/server/lib/job-queue/handlers/video-file-import.ts index 2f4abf73064..e8ee1f7596a 100644 --- a/server/lib/job-queue/handlers/video-file-import.ts +++ b/server/lib/job-queue/handlers/video-file-import.ts @@ -2,15 +2,19 @@ import * as Bull from 'bull' import { copy, stat } from 'fs-extra' import { getLowercaseExtension } from '@server/helpers/core-utils' import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent' -import { generateWebTorrentVideoFilename, getVideoFilePath } from '@server/lib/video-paths' +import { CONFIG } from '@server/initializers/config' +import { federateVideoIfNeeded } from '@server/lib/activitypub/videos' +import { generateWebTorrentVideoFilename } from '@server/lib/paths' +import { addMoveToObjectStorageJob } from '@server/lib/video' +import { VideoPathManager } from '@server/lib/video-path-manager' import { UserModel } from '@server/models/user/user' import { MVideoFullLight } from '@server/types/models' -import { VideoFileImportPayload } from '@shared/models' +import { VideoFileImportPayload, VideoStorage } from '@shared/models' import { getVideoFileFPS, getVideoFileResolution } from '../../../helpers/ffprobe-utils' import { logger } from '../../../helpers/logger' import { VideoModel } from '../../../models/video/video' import { VideoFileModel } from '../../../models/video/video-file' -import { onNewWebTorrentFileResolution } from './video-transcoding' +import { createHlsJobIfEnabled } from './video-transcoding' async function processVideoFileImport (job: Bull.Job) { const payload = job.data as VideoFileImportPayload @@ -29,15 +33,19 @@ async function processVideoFileImport (job: Bull.Job) { const user = await UserModel.loadByChannelActorId(video.VideoChannel.actorId) - const newResolutionPayload = { - type: 'new-resolution-to-webtorrent' as 'new-resolution-to-webtorrent', + await createHlsJobIfEnabled(user, { videoUUID: video.uuid, resolution: data.resolution, isPortraitMode: data.isPortraitMode, - copyCodecs: false, - isNewVideo: false + copyCodecs: true, + isMaxQuality: false + }) + + if (CONFIG.OBJECT_STORAGE.ENABLED) { + await addMoveToObjectStorageJob(video) + } else { + await federateVideoIfNeeded(video, false) } - await onNewWebTorrentFileResolution(video, user, newResolutionPayload) return video } @@ -72,12 +80,13 @@ async function updateVideoFile (video: MVideoFullLight, inputFilePath: string) { resolution, extname: fileExt, filename: generateWebTorrentVideoFilename(resolution, fileExt), + storage: VideoStorage.FILE_SYSTEM, size, fps, videoId: video.id }) - const outputPath = getVideoFilePath(video, newVideoFile) + const outputPath = VideoPathManager.Instance.getFSVideoFileOutputPath(video, newVideoFile) await copy(inputFilePath, outputPath) video.VideoFiles.push(newVideoFile) diff --git a/server/lib/job-queue/handlers/video-import.ts b/server/lib/job-queue/handlers/video-import.ts index fec553f2b1e..a5fa204f55a 100644 --- a/server/lib/job-queue/handlers/video-import.ts +++ b/server/lib/job-queue/handlers/video-import.ts @@ -4,11 +4,13 @@ import { getLowercaseExtension } from '@server/helpers/core-utils' import { retryTransactionWrapper } from '@server/helpers/database-utils' import { YoutubeDL } from '@server/helpers/youtube-dl' import { isPostImportVideoAccepted } from '@server/lib/moderation' +import { generateWebTorrentVideoFilename } from '@server/lib/paths' import { Hooks } from '@server/lib/plugins/hooks' import { ServerConfigManager } from '@server/lib/server-config-manager' import { isAbleToUploadVideo } from '@server/lib/user' -import { addOptimizeOrMergeAudioJob } from '@server/lib/video' -import { generateWebTorrentVideoFilename, getVideoFilePath } from '@server/lib/video-paths' +import { addMoveToObjectStorageJob, addOptimizeOrMergeAudioJob } from '@server/lib/video' +import { VideoPathManager } from '@server/lib/video-path-manager' +import { buildNextVideoState } from '@server/lib/video-state' import { ThumbnailModel } from '@server/models/video/thumbnail' import { MVideoImportDefault, MVideoImportDefaultFiles, MVideoImportVideo } from '@server/types/models/video/video-import' import { @@ -25,7 +27,6 @@ import { getDurationFromVideoFile, getVideoFileFPS, getVideoFileResolution } fro import { logger } from '../../../helpers/logger' import { getSecureTorrentName } from '../../../helpers/utils' import { createTorrentAndSetInfoHash, downloadWebTorrentVideo } from '../../../helpers/webtorrent' -import { CONFIG } from '../../../initializers/config' import { VIDEO_IMPORT_TIMEOUT } from '../../../initializers/constants' import { sequelizeTypescript } from '../../../initializers/database' import { VideoModel } from '../../../models/video/video' @@ -100,7 +101,6 @@ type ProcessFileOptions = { } async function processFile (downloader: () => Promise, videoImport: MVideoImportDefault, options: ProcessFileOptions) { let tempVideoPath: string - let videoDestFile: string let videoFile: VideoFileModel try { @@ -159,7 +159,7 @@ async function processFile (downloader: () => Promise, videoImport: MVid const videoImportWithFiles: MVideoImportDefaultFiles = Object.assign(videoImport, { Video: videoWithFiles }) // Move file - videoDestFile = getVideoFilePath(videoImportWithFiles.Video, videoFile) + const videoDestFile = VideoPathManager.Instance.getFSVideoFileOutputPath(videoImportWithFiles.Video, videoFile) await move(tempVideoPath, videoDestFile) tempVideoPath = null // This path is not used anymore @@ -204,7 +204,7 @@ async function processFile (downloader: () => Promise, videoImport: MVid // Update video DB object video.duration = duration - video.state = CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED + video.state = buildNextVideoState(video.state) await video.save({ transaction: t }) if (thumbnailModel) await video.addAndSaveThumbnail(thumbnailModel, t) @@ -245,6 +245,10 @@ async function processFile (downloader: () => Promise, videoImport: MVid Notifier.Instance.notifyOnNewVideoIfNeeded(video) } + if (video.state === VideoState.TO_MOVE_TO_EXTERNAL_STORAGE) { + return addMoveToObjectStorageJob(videoImportUpdated.Video) + } + // Create transcoding jobs? if (video.state === VideoState.TO_TRANSCODE) { await addOptimizeOrMergeAudioJob(videoImportUpdated.Video, videoFile, videoImport.User) diff --git a/server/lib/job-queue/handlers/video-live-ending.ts b/server/lib/job-queue/handlers/video-live-ending.ts index 38523c75245..9ccf724c2dc 100644 --- a/server/lib/job-queue/handlers/video-live-ending.ts +++ b/server/lib/job-queue/handlers/video-live-ending.ts @@ -4,9 +4,10 @@ import { join } from 'path' import { ffprobePromise, getAudioStream, getDurationFromVideoFile, getVideoFileResolution } from '@server/helpers/ffprobe-utils' import { VIDEO_LIVE } from '@server/initializers/constants' import { buildConcatenatedName, cleanupLive, LiveSegmentShaStore } from '@server/lib/live' +import { generateHLSMasterPlaylistFilename, generateHlsSha256SegmentsFilename, getLiveDirectory } from '@server/lib/paths' import { generateVideoMiniature } from '@server/lib/thumbnail' import { generateHlsPlaylistResolutionFromTS } from '@server/lib/transcoding/video-transcoding' -import { generateHLSMasterPlaylistFilename, generateHlsSha256SegmentsFilename, getHLSDirectory } from '@server/lib/video-paths' +import { VideoPathManager } from '@server/lib/video-path-manager' import { moveToNextState } from '@server/lib/video-state' import { VideoModel } from '@server/models/video/video' import { VideoFileModel } from '@server/models/video/video-file' @@ -55,16 +56,15 @@ export { // --------------------------------------------------------------------------- async function saveLive (video: MVideo, live: MVideoLive, streamingPlaylist: MStreamingPlaylist) { - const hlsDirectory = getHLSDirectory(video, false) - const replayDirectory = join(hlsDirectory, VIDEO_LIVE.REPLAY_DIRECTORY) + const replayDirectory = VideoPathManager.Instance.getFSHLSOutputPath(video, VIDEO_LIVE.REPLAY_DIRECTORY) - const rootFiles = await readdir(hlsDirectory) + const rootFiles = await readdir(getLiveDirectory(video)) const playlistFiles = rootFiles.filter(file => { return file.endsWith('.m3u8') && file !== streamingPlaylist.playlistFilename }) - await cleanupLiveFiles(hlsDirectory) + await cleanupTMPLiveFiles(getLiveDirectory(video)) await live.destroy() @@ -136,7 +136,7 @@ async function saveLive (video: MVideo, live: MVideoLive, streamingPlaylist: MSt await moveToNextState(videoWithFiles, false) } -async function cleanupLiveFiles (hlsDirectory: string) { +async function cleanupTMPLiveFiles (hlsDirectory: string) { if (!await pathExists(hlsDirectory)) return const files = await readdir(hlsDirectory) diff --git a/server/lib/job-queue/handlers/video-transcoding.ts b/server/lib/job-queue/handlers/video-transcoding.ts index 6070c1899fd..b3149dde896 100644 --- a/server/lib/job-queue/handlers/video-transcoding.ts +++ b/server/lib/job-queue/handlers/video-transcoding.ts @@ -1,7 +1,7 @@ import * as Bull from 'bull' import { TranscodeOptionsType } from '@server/helpers/ffmpeg-utils' import { addTranscodingJob, getTranscodingJobPriority } from '@server/lib/video' -import { getVideoFilePath } from '@server/lib/video-paths' +import { VideoPathManager } from '@server/lib/video-path-manager' import { moveToNextState } from '@server/lib/video-state' import { UserModel } from '@server/models/user/user' import { VideoJobInfoModel } from '@server/models/video/video-job-info' @@ -68,15 +68,16 @@ async function handleHLSJob (job: Bull.Job, payload: HLSTranscodingPayload, vide : video.getMaxQualityFile() const videoOrStreamingPlaylist = videoFileInput.getVideoOrStreamingPlaylist() - const videoInputPath = getVideoFilePath(videoOrStreamingPlaylist, videoFileInput) - await generateHlsPlaylistResolution({ - video, - videoInputPath, - resolution: payload.resolution, - copyCodecs: payload.copyCodecs, - isPortraitMode: payload.isPortraitMode || false, - job + await VideoPathManager.Instance.makeAvailableVideoFile(videoOrStreamingPlaylist, videoFileInput, videoInputPath => { + return generateHlsPlaylistResolution({ + video, + videoInputPath, + resolution: payload.resolution, + copyCodecs: payload.copyCodecs, + isPortraitMode: payload.isPortraitMode || false, + job + }) }) await retryTransactionWrapper(onHlsPlaylistGeneration, video, user, payload) @@ -120,11 +121,18 @@ async function onHlsPlaylistGeneration (video: MVideoFullLight, user: MUser, pay video.VideoFiles = [] // Create HLS new resolution jobs - await createLowerResolutionsJobs(video, user, payload.resolution, payload.isPortraitMode, 'hls') + await createLowerResolutionsJobs({ + video, + user, + videoFileResolution: payload.resolution, + isPortraitMode: payload.isPortraitMode, + isNewVideo: payload.isNewVideo ?? true, + type: 'hls' + }) } - await VideoJobInfoModel.decrease(video.uuid, 'pendingTranscoding') - await moveToNextState(video) + await VideoJobInfoModel.decrease(video.uuid, 'pendingTranscode') + await moveToNextState(video, payload.isNewVideo) } async function onVideoFileOptimizer ( @@ -154,12 +162,20 @@ async function onVideoFileOptimizer ( isMaxQuality: true } const hasHls = await createHlsJobIfEnabled(user, originalFileHLSPayload) - const hasNewResolutions = await createLowerResolutionsJobs(videoDatabase, user, resolution, isPortraitMode, 'webtorrent') - await VideoJobInfoModel.decrease(videoDatabase.uuid, 'pendingTranscoding') + const hasNewResolutions = await createLowerResolutionsJobs({ + video: videoDatabase, + user, + videoFileResolution: resolution, + isPortraitMode, + type: 'webtorrent', + isNewVideo: payload.isNewVideo ?? true + }) + + await VideoJobInfoModel.decrease(videoDatabase.uuid, 'pendingTranscode') // Move to next state if there are no other resolutions to generate if (!hasHls && !hasNewResolutions) { - await moveToNextState(videoDatabase) + await moveToNextState(videoDatabase, payload.isNewVideo) } } @@ -169,28 +185,20 @@ async function onNewWebTorrentFileResolution ( payload: NewResolutionTranscodingPayload | MergeAudioTranscodingPayload ) { await createHlsJobIfEnabled(user, { ...payload, copyCodecs: true, isMaxQuality: false }) - await VideoJobInfoModel.decrease(video.uuid, 'pendingTranscoding') + await VideoJobInfoModel.decrease(video.uuid, 'pendingTranscode') - await moveToNextState(video) + await moveToNextState(video, payload.isNewVideo) } -// --------------------------------------------------------------------------- - -export { - processVideoTranscoding, - onNewWebTorrentFileResolution -} - -// --------------------------------------------------------------------------- - async function createHlsJobIfEnabled (user: MUserId, payload: { videoUUID: string resolution: number isPortraitMode?: boolean copyCodecs: boolean isMaxQuality: boolean + isNewVideo?: boolean }) { - if (!payload || CONFIG.TRANSCODING.HLS.ENABLED !== true) return false + if (!payload || CONFIG.TRANSCODING.ENABLED !== true || CONFIG.TRANSCODING.HLS.ENABLED !== true) return false const jobOptions = { priority: await getTranscodingJobPriority(user) @@ -202,7 +210,8 @@ async function createHlsJobIfEnabled (user: MUserId, payload: { resolution: payload.resolution, isPortraitMode: payload.isPortraitMode, copyCodecs: payload.copyCodecs, - isMaxQuality: payload.isMaxQuality + isMaxQuality: payload.isMaxQuality, + isNewVideo: payload.isNewVideo } await addTranscodingJob(hlsTranscodingPayload, jobOptions) @@ -210,13 +219,26 @@ async function createHlsJobIfEnabled (user: MUserId, payload: { return true } -async function createLowerResolutionsJobs ( - video: MVideoFullLight, - user: MUserId, - videoFileResolution: number, - isPortraitMode: boolean, +// --------------------------------------------------------------------------- + +export { + processVideoTranscoding, + createHlsJobIfEnabled, + onNewWebTorrentFileResolution +} + +// --------------------------------------------------------------------------- + +async function createLowerResolutionsJobs (options: { + video: MVideoFullLight + user: MUserId + videoFileResolution: number + isPortraitMode: boolean + isNewVideo: boolean type: 'hls' | 'webtorrent' -) { +}) { + const { video, user, videoFileResolution, isPortraitMode, isNewVideo, type } = options + // Create transcoding jobs if there are enabled resolutions const resolutionsEnabled = computeResolutionsToTranscode(videoFileResolution, 'vod') const resolutionCreated: number[] = [] @@ -230,7 +252,8 @@ async function createLowerResolutionsJobs ( type: 'new-resolution-to-webtorrent', videoUUID: video.uuid, resolution, - isPortraitMode + isPortraitMode, + isNewVideo } } @@ -241,7 +264,8 @@ async function createLowerResolutionsJobs ( resolution, isPortraitMode, copyCodecs: false, - isMaxQuality: false + isMaxQuality: false, + isNewVideo } } diff --git a/server/lib/live/live-manager.ts b/server/lib/live/live-manager.ts index 2a429fb3378..d7dc841d929 100644 --- a/server/lib/live/live-manager.ts +++ b/server/lib/live/live-manager.ts @@ -20,7 +20,7 @@ import { VideoState, VideoStreamingPlaylistType } from '@shared/models' import { federateVideoIfNeeded } from '../activitypub/videos' import { JobQueue } from '../job-queue' import { PeerTubeSocket } from '../peertube-socket' -import { generateHLSMasterPlaylistFilename, generateHlsSha256SegmentsFilename } from '../video-paths' +import { generateHLSMasterPlaylistFilename, generateHlsSha256SegmentsFilename } from '../paths' import { LiveQuotaStore } from './live-quota-store' import { LiveSegmentShaStore } from './live-segment-sha-store' import { cleanupLive } from './live-utils' diff --git a/server/lib/live/live-utils.ts b/server/lib/live/live-utils.ts index e4526c7a574..3bf723b9816 100644 --- a/server/lib/live/live-utils.ts +++ b/server/lib/live/live-utils.ts @@ -1,7 +1,7 @@ import { remove } from 'fs-extra' import { basename } from 'path' import { MStreamingPlaylist, MVideo } from '@server/types/models' -import { getHLSDirectory } from '../video-paths' +import { getLiveDirectory } from '../paths' function buildConcatenatedName (segmentOrPlaylistPath: string) { const num = basename(segmentOrPlaylistPath).match(/^(\d+)(-|\.)/) @@ -10,7 +10,7 @@ function buildConcatenatedName (segmentOrPlaylistPath: string) { } async function cleanupLive (video: MVideo, streamingPlaylist: MStreamingPlaylist) { - const hlsDirectory = getHLSDirectory(video) + const hlsDirectory = getLiveDirectory(video) await remove(hlsDirectory) diff --git a/server/lib/live/shared/muxing-session.ts b/server/lib/live/shared/muxing-session.ts index a80abc843e3..9b5b6c4fc99 100644 --- a/server/lib/live/shared/muxing-session.ts +++ b/server/lib/live/shared/muxing-session.ts @@ -11,9 +11,9 @@ import { CONFIG } from '@server/initializers/config' import { MEMOIZE_TTL, VIDEO_LIVE } from '@server/initializers/constants' import { VideoFileModel } from '@server/models/video/video-file' import { MStreamingPlaylistVideo, MUserId, MVideoLiveVideo } from '@server/types/models' +import { getLiveDirectory } from '../../paths' import { VideoTranscodingProfilesManager } from '../../transcoding/video-transcoding-profiles' import { isAbleToUploadVideo } from '../../user' -import { getHLSDirectory } from '../../video-paths' import { LiveQuotaStore } from '../live-quota-store' import { LiveSegmentShaStore } from '../live-segment-sha-store' import { buildConcatenatedName } from '../live-utils' @@ -282,7 +282,7 @@ class MuxingSession extends EventEmitter { } private async prepareDirectories () { - const outPath = getHLSDirectory(this.videoLive.Video) + const outPath = getLiveDirectory(this.videoLive.Video) await ensureDir(outPath) const replayDirectory = join(outPath, VIDEO_LIVE.REPLAY_DIRECTORY) diff --git a/server/lib/object-storage/keys.ts b/server/lib/object-storage/keys.ts index 998139964d7..51947477513 100644 --- a/server/lib/object-storage/keys.ts +++ b/server/lib/object-storage/keys.ts @@ -1,12 +1,12 @@ import { join } from 'path' import { MStreamingPlaylist, MVideoUUID } from '@server/types/models' -function generateHLSObjectStorageKey (playlist: MStreamingPlaylist, video: MVideoUUID, filename?: string) { - const base = playlist.getStringType() + '_' + video.uuid - - if (!filename) return base +function generateHLSObjectStorageKey (playlist: MStreamingPlaylist, video: MVideoUUID, filename: string) { + return join(generateHLSObjectBaseStorageKey(playlist, video), filename) +} - return join(base, filename) +function generateHLSObjectBaseStorageKey (playlist: MStreamingPlaylist, video: MVideoUUID) { + return playlist.getStringType() + '_' + video.uuid } function generateWebTorrentObjectStorageKey (filename: string) { @@ -15,5 +15,6 @@ function generateWebTorrentObjectStorageKey (filename: string) { export { generateHLSObjectStorageKey, + generateHLSObjectBaseStorageKey, generateWebTorrentObjectStorageKey } diff --git a/server/lib/object-storage/shared/client.ts b/server/lib/object-storage/shared/client.ts index 7a306410a5c..c9a61459336 100644 --- a/server/lib/object-storage/shared/client.ts +++ b/server/lib/object-storage/shared/client.ts @@ -3,11 +3,14 @@ import { logger } from '@server/helpers/logger' import { CONFIG } from '@server/initializers/config' import { lTags } from './logger' -const endpointConfig = CONFIG.OBJECT_STORAGE.ENDPOINT -const endpoint = endpointConfig.startsWith('http://') || endpointConfig.startsWith('https://') - ? CONFIG.OBJECT_STORAGE.ENDPOINT - : 'https://' + CONFIG.OBJECT_STORAGE.ENDPOINT -const endpointParsed = new URL(endpoint) +let endpointParsed: URL +function getEndpointParsed () { + if (endpointParsed) return endpointParsed + + endpointParsed = new URL(getEndpoint()) + + return endpointParsed +} let s3Client: S3Client function getClient () { @@ -16,21 +19,38 @@ function getClient () { const OBJECT_STORAGE = CONFIG.OBJECT_STORAGE s3Client = new S3Client({ - endpoint, + endpoint: getEndpoint(), region: OBJECT_STORAGE.REGION, - credentials: { - accessKeyId: OBJECT_STORAGE.CREDENTIALS.ACCESS_KEY_ID, - secretAccessKey: OBJECT_STORAGE.CREDENTIALS.SECRET_ACCESS_KEY - } + credentials: OBJECT_STORAGE.CREDENTIALS.ACCESS_KEY_ID + ? { + accessKeyId: OBJECT_STORAGE.CREDENTIALS.ACCESS_KEY_ID, + secretAccessKey: OBJECT_STORAGE.CREDENTIALS.SECRET_ACCESS_KEY + } + : undefined }) - logger.info('Initialized S3 client %s with region %s.', endpoint, OBJECT_STORAGE.REGION, lTags()) + logger.info('Initialized S3 client %s with region %s.', getEndpoint(), OBJECT_STORAGE.REGION, lTags()) return s3Client } +// --------------------------------------------------------------------------- + export { - endpoint, - endpointParsed, + getEndpointParsed, getClient } + +// --------------------------------------------------------------------------- + +let endpoint: string +function getEndpoint () { + if (endpoint) return endpoint + + const endpointConfig = CONFIG.OBJECT_STORAGE.ENDPOINT + endpoint = endpointConfig.startsWith('http://') || endpointConfig.startsWith('https://') + ? CONFIG.OBJECT_STORAGE.ENDPOINT + : 'https://' + CONFIG.OBJECT_STORAGE.ENDPOINT + + return endpoint +} diff --git a/server/lib/object-storage/shared/object-storage-helpers.ts b/server/lib/object-storage/shared/object-storage-helpers.ts index 513c4afcb00..e2321690740 100644 --- a/server/lib/object-storage/shared/object-storage-helpers.ts +++ b/server/lib/object-storage/shared/object-storage-helpers.ts @@ -98,17 +98,24 @@ async function removePrefix (prefix: string, bucketInfo: BucketInfo) { if (listedObjects.IsTruncated) await removePrefix(prefix, bucketInfo) } -async function makeAvailable (options: { filename: string, at: string }, bucketInfo: BucketInfo) { - await ensureDir(dirname(options.at)) +async function makeAvailable (options: { + key: string + destination: string + bucketInfo: BucketInfo +}) { + const { key, destination, bucketInfo } = options + + await ensureDir(dirname(options.destination)) const command = new GetObjectCommand({ Bucket: bucketInfo.BUCKET_NAME, - Key: buildKey(options.filename, bucketInfo) + Key: buildKey(key, bucketInfo) }) const response = await getClient().send(command) - const file = createWriteStream(options.at) + const file = createWriteStream(destination) await pipelinePromise(response.Body as Readable, file) + file.close() } @@ -176,6 +183,7 @@ async function multiPartUpload (options: { partNumber, bucketInfo.PREFIX, objectStorageKey, bucketInfo.BUCKET_NAME, lTags() ) + // FIXME: Remove when https://github.com/aws/aws-sdk-js-v3/pull/2637 is released // The s3 sdk needs to know the length of the http body beforehand, but doesn't support // streams with start and end set, so it just tries to stat the file in stream.path. // This fails for us because we only want to send part of the file. The stream type diff --git a/server/lib/object-storage/urls.ts b/server/lib/object-storage/urls.ts index a9d8516ec0f..2a889190b9f 100644 --- a/server/lib/object-storage/urls.ts +++ b/server/lib/object-storage/urls.ts @@ -1,5 +1,5 @@ import { CONFIG } from '@server/initializers/config' -import { BucketInfo, buildKey, endpointParsed } from './shared' +import { BucketInfo, buildKey, getEndpointParsed } from './shared' function getPrivateUrl (config: BucketInfo, keyWithoutPrefix: string) { return getBaseUrl(config) + buildKey(keyWithoutPrefix, config) @@ -31,7 +31,7 @@ export { function getBaseUrl (bucketInfo: BucketInfo, baseUrl?: string) { if (baseUrl) return baseUrl - return `${endpointParsed.protocol}//${bucketInfo.BUCKET_NAME}.${endpointParsed.host}/` + return `${getEndpointParsed().protocol}//${bucketInfo.BUCKET_NAME}.${getEndpointParsed().host}/` } const regex = new RegExp('https?://[^/]+') diff --git a/server/lib/object-storage/videos.ts b/server/lib/object-storage/videos.ts index 6e5535db0c3..15b8f58d5e0 100644 --- a/server/lib/object-storage/videos.ts +++ b/server/lib/object-storage/videos.ts @@ -1,9 +1,10 @@ import { join } from 'path' +import { logger } from '@server/helpers/logger' import { CONFIG } from '@server/initializers/config' import { MStreamingPlaylist, MVideoFile, MVideoUUID } from '@server/types/models' -import { getHLSDirectory } from '../video-paths' -import { generateHLSObjectStorageKey, generateWebTorrentObjectStorageKey } from './keys' -import { removeObject, removePrefix, storeObject } from './shared' +import { getHLSDirectory } from '../paths' +import { generateHLSObjectBaseStorageKey, generateHLSObjectStorageKey, generateWebTorrentObjectStorageKey } from './keys' +import { lTags, makeAvailable, removeObject, removePrefix, storeObject } from './shared' function storeHLSFile (playlist: MStreamingPlaylist, video: MVideoUUID, filename: string) { const baseHlsDirectory = getHLSDirectory(video) @@ -24,16 +25,48 @@ function storeWebTorrentFile (filename: string) { } function removeHLSObjectStorage (playlist: MStreamingPlaylist, video: MVideoUUID) { - return removePrefix(generateHLSObjectStorageKey(playlist, video), CONFIG.OBJECT_STORAGE.STREAMING_PLAYLISTS) + return removePrefix(generateHLSObjectBaseStorageKey(playlist, video), CONFIG.OBJECT_STORAGE.STREAMING_PLAYLISTS) } function removeWebTorrentObjectStorage (videoFile: MVideoFile) { return removeObject(generateWebTorrentObjectStorageKey(videoFile.filename), CONFIG.OBJECT_STORAGE.VIDEOS) } +async function makeHLSFileAvailable (playlist: MStreamingPlaylist, video: MVideoUUID, filename: string, destination: string) { + const key = generateHLSObjectStorageKey(playlist, video, filename) + + logger.info('Fetching HLS file %s from object storage to %s.', key, destination, lTags()) + + await makeAvailable({ + key, + destination, + bucketInfo: CONFIG.OBJECT_STORAGE.STREAMING_PLAYLISTS + }) + + return destination +} + +async function makeWebTorrentFileAvailable (filename: string, destination: string) { + const key = generateWebTorrentObjectStorageKey(filename) + + logger.info('Fetching WebTorrent file %s from object storage to %s.', key, destination, lTags()) + + await makeAvailable({ + key, + destination, + bucketInfo: CONFIG.OBJECT_STORAGE.VIDEOS + }) + + return destination +} + export { storeWebTorrentFile, storeHLSFile, + removeHLSObjectStorage, - removeWebTorrentObjectStorage + removeWebTorrentObjectStorage, + + makeWebTorrentFileAvailable, + makeHLSFileAvailable } diff --git a/server/lib/paths.ts b/server/lib/paths.ts new file mode 100644 index 00000000000..434e637c6f9 --- /dev/null +++ b/server/lib/paths.ts @@ -0,0 +1,82 @@ +import { join } from 'path' +import { buildUUID } from '@server/helpers/uuid' +import { CONFIG } from '@server/initializers/config' +import { HLS_REDUNDANCY_DIRECTORY, HLS_STREAMING_PLAYLIST_DIRECTORY } from '@server/initializers/constants' +import { isStreamingPlaylist, MStreamingPlaylistVideo, MVideo, MVideoFile, MVideoUUID } from '@server/types/models' +import { removeFragmentedMP4Ext } from '@shared/core-utils' + +// ################## Video file name ################## + +function generateWebTorrentVideoFilename (resolution: number, extname: string) { + return buildUUID() + '-' + resolution + extname +} + +function generateHLSVideoFilename (resolution: number) { + return `${buildUUID()}-${resolution}-fragmented.mp4` +} + +// ################## Streaming playlist ################## + +function getLiveDirectory (video: MVideoUUID) { + return getHLSDirectory(video) +} + +function getHLSDirectory (video: MVideoUUID) { + return join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid) +} + +function getHLSRedundancyDirectory (video: MVideoUUID) { + return join(HLS_REDUNDANCY_DIRECTORY, video.uuid) +} + +function getHlsResolutionPlaylistFilename (videoFilename: string) { + // Video file name already contain resolution + return removeFragmentedMP4Ext(videoFilename) + '.m3u8' +} + +function generateHLSMasterPlaylistFilename (isLive = false) { + if (isLive) return 'master.m3u8' + + return buildUUID() + '-master.m3u8' +} + +function generateHlsSha256SegmentsFilename (isLive = false) { + if (isLive) return 'segments-sha256.json' + + return buildUUID() + '-segments-sha256.json' +} + +// ################## Torrents ################## + +function generateTorrentFileName (videoOrPlaylist: MVideo | MStreamingPlaylistVideo, resolution: number) { + const extension = '.torrent' + const uuid = buildUUID() + + if (isStreamingPlaylist(videoOrPlaylist)) { + return `${uuid}-${resolution}-${videoOrPlaylist.getStringType()}${extension}` + } + + return uuid + '-' + resolution + extension +} + +function getFSTorrentFilePath (videoFile: MVideoFile) { + return join(CONFIG.STORAGE.TORRENTS_DIR, videoFile.torrentFilename) +} + +// --------------------------------------------------------------------------- + +export { + generateHLSVideoFilename, + generateWebTorrentVideoFilename, + + generateTorrentFileName, + getFSTorrentFilePath, + + getHLSDirectory, + getLiveDirectory, + getHLSRedundancyDirectory, + + generateHLSMasterPlaylistFilename, + generateHlsSha256SegmentsFilename, + getHlsResolutionPlaylistFilename +} diff --git a/server/lib/schedulers/videos-redundancy-scheduler.ts b/server/lib/schedulers/videos-redundancy-scheduler.ts index 137ae53a039..ebfd015b5eb 100644 --- a/server/lib/schedulers/videos-redundancy-scheduler.ts +++ b/server/lib/schedulers/videos-redundancy-scheduler.ts @@ -24,7 +24,7 @@ import { getLocalVideoCacheFileActivityPubUrl, getLocalVideoCacheStreamingPlayli import { getOrCreateAPVideo } from '../activitypub/videos' import { downloadPlaylistSegments } from '../hls' import { removeVideoRedundancy } from '../redundancy' -import { generateHLSRedundancyUrl, generateWebTorrentRedundancyUrl } from '../video-paths' +import { generateHLSRedundancyUrl, generateWebTorrentRedundancyUrl } from '../video-urls' import { AbstractScheduler } from './abstract-scheduler' type CandidateToDuplicate = { diff --git a/server/lib/thumbnail.ts b/server/lib/thumbnail.ts index c085239880d..d2384f53cf1 100644 --- a/server/lib/thumbnail.ts +++ b/server/lib/thumbnail.ts @@ -1,5 +1,4 @@ import { join } from 'path' - import { ThumbnailType } from '../../shared/models/videos/thumbnail.type' import { generateImageFromVideoFile } from '../helpers/ffmpeg-utils' import { generateImageFilename, processImage } from '../helpers/image-utils' @@ -10,7 +9,7 @@ import { ThumbnailModel } from '../models/video/thumbnail' import { MVideoFile, MVideoThumbnail, MVideoUUID } from '../types/models' import { MThumbnail } from '../types/models/video/thumbnail' import { MVideoPlaylistThumbnail } from '../types/models/video/video-playlist' -import { getVideoFilePath } from './video-paths' +import { VideoPathManager } from './video-path-manager' type ImageSize = { height?: number, width?: number } @@ -116,21 +115,22 @@ function generateVideoMiniature (options: { }) { const { video, videoFile, type } = options - const input = getVideoFilePath(video, videoFile) + return VideoPathManager.Instance.makeAvailableVideoFile(video, videoFile, input => { + const { filename, basePath, height, width, existingThumbnail, outputPath } = buildMetadataFromVideo(video, type) - const { filename, basePath, height, width, existingThumbnail, outputPath } = buildMetadataFromVideo(video, type) - const thumbnailCreator = videoFile.isAudio() - ? () => processImage(ASSETS_PATH.DEFAULT_AUDIO_BACKGROUND, outputPath, { width, height }, true) - : () => generateImageFromVideoFile(input, basePath, filename, { height, width }) + const thumbnailCreator = videoFile.isAudio() + ? () => processImage(ASSETS_PATH.DEFAULT_AUDIO_BACKGROUND, outputPath, { width, height }, true) + : () => generateImageFromVideoFile(input, basePath, filename, { height, width }) - return updateThumbnailFromFunction({ - thumbnailCreator, - filename, - height, - width, - type, - automaticallyGenerated: true, - existingThumbnail + return updateThumbnailFromFunction({ + thumbnailCreator, + filename, + height, + width, + type, + automaticallyGenerated: true, + existingThumbnail + }) }) } diff --git a/server/lib/transcoding/video-transcoding.ts b/server/lib/transcoding/video-transcoding.ts index 7330bc3d6bd..ee228c01114 100644 --- a/server/lib/transcoding/video-transcoding.ts +++ b/server/lib/transcoding/video-transcoding.ts @@ -4,13 +4,13 @@ import { basename, extname as extnameUtil, join } from 'path' import { toEven } from '@server/helpers/core-utils' import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent' import { MStreamingPlaylistFilesVideo, MVideoFile, MVideoFullLight } from '@server/types/models' -import { VideoResolution } from '../../../shared/models/videos' +import { VideoResolution, VideoStorage } from '../../../shared/models/videos' import { VideoStreamingPlaylistType } from '../../../shared/models/videos/video-streaming-playlist.type' import { transcode, TranscodeOptions, TranscodeOptionsType } from '../../helpers/ffmpeg-utils' import { canDoQuickTranscode, getDurationFromVideoFile, getMetadataFromFile, getVideoFileFPS } from '../../helpers/ffprobe-utils' import { logger } from '../../helpers/logger' import { CONFIG } from '../../initializers/config' -import { HLS_STREAMING_PLAYLIST_DIRECTORY, P2P_MEDIA_LOADER_PEER_VERSION } from '../../initializers/constants' +import { P2P_MEDIA_LOADER_PEER_VERSION } from '../../initializers/constants' import { VideoFileModel } from '../../models/video/video-file' import { VideoStreamingPlaylistModel } from '../../models/video/video-streaming-playlist' import { updateMasterHLSPlaylist, updateSha256VODSegments } from '../hls' @@ -19,9 +19,9 @@ import { generateHlsSha256SegmentsFilename, generateHLSVideoFilename, generateWebTorrentVideoFilename, - getHlsResolutionPlaylistFilename, - getVideoFilePath -} from '../video-paths' + getHlsResolutionPlaylistFilename +} from '../paths' +import { VideoPathManager } from '../video-path-manager' import { VideoTranscodingProfilesManager } from './video-transcoding-profiles' /** @@ -32,159 +32,162 @@ import { VideoTranscodingProfilesManager } from './video-transcoding-profiles' */ // Optimize the original video file and replace it. The resolution is not changed. -async function optimizeOriginalVideofile (video: MVideoFullLight, inputVideoFile: MVideoFile, job?: Job) { +function optimizeOriginalVideofile (video: MVideoFullLight, inputVideoFile: MVideoFile, job?: Job) { const transcodeDirectory = CONFIG.STORAGE.TMP_DIR const newExtname = '.mp4' - const videoInputPath = getVideoFilePath(video, inputVideoFile) - const videoTranscodedPath = join(transcodeDirectory, video.id + '-transcoded' + newExtname) + return VideoPathManager.Instance.makeAvailableVideoFile(video, inputVideoFile, async videoInputPath => { + const videoTranscodedPath = join(transcodeDirectory, video.id + '-transcoded' + newExtname) - const transcodeType: TranscodeOptionsType = await canDoQuickTranscode(videoInputPath) - ? 'quick-transcode' - : 'video' + const transcodeType: TranscodeOptionsType = await canDoQuickTranscode(videoInputPath) + ? 'quick-transcode' + : 'video' - const resolution = toEven(inputVideoFile.resolution) + const resolution = toEven(inputVideoFile.resolution) - const transcodeOptions: TranscodeOptions = { - type: transcodeType, + const transcodeOptions: TranscodeOptions = { + type: transcodeType, - inputPath: videoInputPath, - outputPath: videoTranscodedPath, + inputPath: videoInputPath, + outputPath: videoTranscodedPath, - availableEncoders: VideoTranscodingProfilesManager.Instance.getAvailableEncoders(), - profile: CONFIG.TRANSCODING.PROFILE, + availableEncoders: VideoTranscodingProfilesManager.Instance.getAvailableEncoders(), + profile: CONFIG.TRANSCODING.PROFILE, - resolution, + resolution, - job - } + job + } - // Could be very long! - await transcode(transcodeOptions) + // Could be very long! + await transcode(transcodeOptions) - try { - await remove(videoInputPath) + try { + await remove(videoInputPath) - // Important to do this before getVideoFilename() to take in account the new filename - inputVideoFile.extname = newExtname - inputVideoFile.filename = generateWebTorrentVideoFilename(resolution, newExtname) + // Important to do this before getVideoFilename() to take in account the new filename + inputVideoFile.extname = newExtname + inputVideoFile.filename = generateWebTorrentVideoFilename(resolution, newExtname) + inputVideoFile.storage = VideoStorage.FILE_SYSTEM - const videoOutputPath = getVideoFilePath(video, inputVideoFile) + const videoOutputPath = VideoPathManager.Instance.getFSVideoFileOutputPath(video, inputVideoFile) - const { videoFile } = await onWebTorrentVideoFileTranscoding(video, inputVideoFile, videoTranscodedPath, videoOutputPath) + const { videoFile } = await onWebTorrentVideoFileTranscoding(video, inputVideoFile, videoTranscodedPath, videoOutputPath) - return { transcodeType, videoFile } - } catch (err) { - // Auto destruction... - video.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err })) + return { transcodeType, videoFile } + } catch (err) { + // Auto destruction... + video.destroy().catch(err => logger.error('Cannot destruct video after transcoding failure.', { err })) - throw err - } + throw err + } + }) } -// Transcode the original video file to a lower resolution. -async function transcodeNewWebTorrentResolution (video: MVideoFullLight, resolution: VideoResolution, isPortrait: boolean, job: Job) { +// Transcode the original video file to a lower resolution +// We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed +function transcodeNewWebTorrentResolution (video: MVideoFullLight, resolution: VideoResolution, isPortrait: boolean, job: Job) { const transcodeDirectory = CONFIG.STORAGE.TMP_DIR const extname = '.mp4' - // We are sure it's x264 in mp4 because optimizeOriginalVideofile was already executed - const videoInputPath = getVideoFilePath(video, video.getMaxQualityFile()) + return VideoPathManager.Instance.makeAvailableVideoFile(video, video.getMaxQualityFile(), async videoInputPath => { + const newVideoFile = new VideoFileModel({ + resolution, + extname, + filename: generateWebTorrentVideoFilename(resolution, extname), + size: 0, + videoId: video.id + }) - const newVideoFile = new VideoFileModel({ - resolution, - extname, - filename: generateWebTorrentVideoFilename(resolution, extname), - size: 0, - videoId: video.id - }) + const videoOutputPath = VideoPathManager.Instance.getFSVideoFileOutputPath(video, newVideoFile) + const videoTranscodedPath = join(transcodeDirectory, newVideoFile.filename) - const videoOutputPath = getVideoFilePath(video, newVideoFile) - const videoTranscodedPath = join(transcodeDirectory, newVideoFile.filename) + const transcodeOptions = resolution === VideoResolution.H_NOVIDEO + ? { + type: 'only-audio' as 'only-audio', - const transcodeOptions = resolution === VideoResolution.H_NOVIDEO - ? { - type: 'only-audio' as 'only-audio', + inputPath: videoInputPath, + outputPath: videoTranscodedPath, - inputPath: videoInputPath, - outputPath: videoTranscodedPath, + availableEncoders: VideoTranscodingProfilesManager.Instance.getAvailableEncoders(), + profile: CONFIG.TRANSCODING.PROFILE, - availableEncoders: VideoTranscodingProfilesManager.Instance.getAvailableEncoders(), - profile: CONFIG.TRANSCODING.PROFILE, + resolution, - resolution, + job + } + : { + type: 'video' as 'video', + inputPath: videoInputPath, + outputPath: videoTranscodedPath, - job - } - : { - type: 'video' as 'video', - inputPath: videoInputPath, - outputPath: videoTranscodedPath, + availableEncoders: VideoTranscodingProfilesManager.Instance.getAvailableEncoders(), + profile: CONFIG.TRANSCODING.PROFILE, - availableEncoders: VideoTranscodingProfilesManager.Instance.getAvailableEncoders(), - profile: CONFIG.TRANSCODING.PROFILE, + resolution, + isPortraitMode: isPortrait, - resolution, - isPortraitMode: isPortrait, + job + } - job - } - - await transcode(transcodeOptions) + await transcode(transcodeOptions) - return onWebTorrentVideoFileTranscoding(video, newVideoFile, videoTranscodedPath, videoOutputPath) + return onWebTorrentVideoFileTranscoding(video, newVideoFile, videoTranscodedPath, videoOutputPath) + }) } // Merge an image with an audio file to create a video -async function mergeAudioVideofile (video: MVideoFullLight, resolution: VideoResolution, job: Job) { +function mergeAudioVideofile (video: MVideoFullLight, resolution: VideoResolution, job: Job) { const transcodeDirectory = CONFIG.STORAGE.TMP_DIR const newExtname = '.mp4' const inputVideoFile = video.getMinQualityFile() - const audioInputPath = getVideoFilePath(video, inputVideoFile) - const videoTranscodedPath = join(transcodeDirectory, video.id + '-transcoded' + newExtname) + return VideoPathManager.Instance.makeAvailableVideoFile(video, inputVideoFile, async audioInputPath => { + const videoTranscodedPath = join(transcodeDirectory, video.id + '-transcoded' + newExtname) - // If the user updates the video preview during transcoding - const previewPath = video.getPreview().getPath() - const tmpPreviewPath = join(CONFIG.STORAGE.TMP_DIR, basename(previewPath)) - await copyFile(previewPath, tmpPreviewPath) + // If the user updates the video preview during transcoding + const previewPath = video.getPreview().getPath() + const tmpPreviewPath = join(CONFIG.STORAGE.TMP_DIR, basename(previewPath)) + await copyFile(previewPath, tmpPreviewPath) - const transcodeOptions = { - type: 'merge-audio' as 'merge-audio', + const transcodeOptions = { + type: 'merge-audio' as 'merge-audio', - inputPath: tmpPreviewPath, - outputPath: videoTranscodedPath, + inputPath: tmpPreviewPath, + outputPath: videoTranscodedPath, - availableEncoders: VideoTranscodingProfilesManager.Instance.getAvailableEncoders(), - profile: CONFIG.TRANSCODING.PROFILE, + availableEncoders: VideoTranscodingProfilesManager.Instance.getAvailableEncoders(), + profile: CONFIG.TRANSCODING.PROFILE, - audioPath: audioInputPath, - resolution, + audioPath: audioInputPath, + resolution, - job - } + job + } - try { - await transcode(transcodeOptions) + try { + await transcode(transcodeOptions) - await remove(audioInputPath) - await remove(tmpPreviewPath) - } catch (err) { - await remove(tmpPreviewPath) - throw err - } + await remove(audioInputPath) + await remove(tmpPreviewPath) + } catch (err) { + await remove(tmpPreviewPath) + throw err + } - // Important to do this before getVideoFilename() to take in account the new file extension - inputVideoFile.extname = newExtname - inputVideoFile.filename = generateWebTorrentVideoFilename(inputVideoFile.resolution, newExtname) + // Important to do this before getVideoFilename() to take in account the new file extension + inputVideoFile.extname = newExtname + inputVideoFile.filename = generateWebTorrentVideoFilename(inputVideoFile.resolution, newExtname) - const videoOutputPath = getVideoFilePath(video, inputVideoFile) - // ffmpeg generated a new video file, so update the video duration - // See https://trac.ffmpeg.org/ticket/5456 - video.duration = await getDurationFromVideoFile(videoTranscodedPath) - await video.save() + const videoOutputPath = VideoPathManager.Instance.getFSVideoFileOutputPath(video, inputVideoFile) + // ffmpeg generated a new video file, so update the video duration + // See https://trac.ffmpeg.org/ticket/5456 + video.duration = await getDurationFromVideoFile(videoTranscodedPath) + await video.save() - return onWebTorrentVideoFileTranscoding(video, inputVideoFile, videoTranscodedPath, videoOutputPath) + return onWebTorrentVideoFileTranscoding(video, inputVideoFile, videoTranscodedPath, videoOutputPath) + }) } // Concat TS segments from a live video to a fragmented mp4 HLS playlist @@ -335,14 +338,13 @@ async function generateHlsPlaylistCommon (options: { videoStreamingPlaylistId: playlist.id }) - const videoFilePath = getVideoFilePath(playlist, newVideoFile) + const videoFilePath = VideoPathManager.Instance.getFSVideoFileOutputPath(playlist, newVideoFile) // Move files from tmp transcoded directory to the appropriate place - const baseHlsDirectory = join(HLS_STREAMING_PLAYLIST_DIRECTORY, video.uuid) - await ensureDir(baseHlsDirectory) + await ensureDir(VideoPathManager.Instance.getFSHLSOutputPath(video)) // Move playlist file - const resolutionPlaylistPath = join(baseHlsDirectory, resolutionPlaylistFilename) + const resolutionPlaylistPath = VideoPathManager.Instance.getFSHLSOutputPath(video, resolutionPlaylistFilename) await move(resolutionPlaylistFileTranscodePath, resolutionPlaylistPath, { overwrite: true }) // Move video file await move(join(videoTranscodedBasePath, videoFilename), videoFilePath, { overwrite: true }) diff --git a/server/lib/video-path-manager.ts b/server/lib/video-path-manager.ts new file mode 100644 index 00000000000..4c5d0c89d17 --- /dev/null +++ b/server/lib/video-path-manager.ts @@ -0,0 +1,139 @@ +import { remove } from 'fs-extra' +import { extname, join } from 'path' +import { buildUUID } from '@server/helpers/uuid' +import { extractVideo } from '@server/helpers/video' +import { CONFIG } from '@server/initializers/config' +import { MStreamingPlaylistVideo, MVideo, MVideoFile, MVideoUUID } from '@server/types/models' +import { VideoStorage } from '@shared/models' +import { makeHLSFileAvailable, makeWebTorrentFileAvailable } from './object-storage' +import { getHLSDirectory, getHLSRedundancyDirectory, getHlsResolutionPlaylistFilename } from './paths' + +type MakeAvailableCB = (path: string) => Promise | T + +class VideoPathManager { + + private static instance: VideoPathManager + + private constructor () {} + + getFSHLSOutputPath (video: MVideoUUID, filename?: string) { + const base = getHLSDirectory(video) + if (!filename) return base + + return join(base, filename) + } + + getFSRedundancyVideoFilePath (videoOrPlaylist: MVideo | MStreamingPlaylistVideo, videoFile: MVideoFile) { + if (videoFile.isHLS()) { + const video = extractVideo(videoOrPlaylist) + + return join(getHLSRedundancyDirectory(video), videoFile.filename) + } + + return join(CONFIG.STORAGE.REDUNDANCY_DIR, videoFile.filename) + } + + getFSVideoFileOutputPath (videoOrPlaylist: MVideo | MStreamingPlaylistVideo, videoFile: MVideoFile) { + if (videoFile.isHLS()) { + const video = extractVideo(videoOrPlaylist) + + return join(getHLSDirectory(video), videoFile.filename) + } + + return join(CONFIG.STORAGE.VIDEOS_DIR, videoFile.filename) + } + + async makeAvailableVideoFile (videoOrPlaylist: MVideo | MStreamingPlaylistVideo, videoFile: MVideoFile, cb: MakeAvailableCB) { + if (videoFile.storage === VideoStorage.FILE_SYSTEM) { + return this.makeAvailableFactory( + () => this.getFSVideoFileOutputPath(videoOrPlaylist, videoFile), + false, + cb + ) + } + + const destination = this.buildTMPDestination(videoFile.filename) + + if (videoFile.isHLS()) { + const video = extractVideo(videoOrPlaylist) + + return this.makeAvailableFactory( + () => makeHLSFileAvailable(videoOrPlaylist as MStreamingPlaylistVideo, video, videoFile.filename, destination), + true, + cb + ) + } + + return this.makeAvailableFactory( + () => makeWebTorrentFileAvailable(videoFile.filename, destination), + true, + cb + ) + } + + async makeAvailableResolutionPlaylistFile (playlist: MStreamingPlaylistVideo, videoFile: MVideoFile, cb: MakeAvailableCB) { + const filename = getHlsResolutionPlaylistFilename(videoFile.filename) + + if (videoFile.storage === VideoStorage.FILE_SYSTEM) { + return this.makeAvailableFactory( + () => join(getHLSDirectory(playlist.Video), filename), + false, + cb + ) + } + + return this.makeAvailableFactory( + () => makeHLSFileAvailable(playlist, playlist.Video, filename, this.buildTMPDestination(filename)), + true, + cb + ) + } + + async makeAvailablePlaylistFile (playlist: MStreamingPlaylistVideo, filename: string, cb: MakeAvailableCB) { + if (playlist.storage === VideoStorage.FILE_SYSTEM) { + return this.makeAvailableFactory( + () => join(getHLSDirectory(playlist.Video), filename), + false, + cb + ) + } + + return this.makeAvailableFactory( + () => makeHLSFileAvailable(playlist, playlist.Video, filename, this.buildTMPDestination(filename)), + true, + cb + ) + } + + private async makeAvailableFactory (method: () => Promise | string, clean: boolean, cb: MakeAvailableCB) { + let result: T + + const destination = await method() + + try { + result = await cb(destination) + } catch (err) { + if (destination && clean) await remove(destination) + throw err + } + + if (clean) await remove(destination) + + return result + } + + private buildTMPDestination (filename: string) { + return join(CONFIG.STORAGE.TMP_DIR, buildUUID() + extname(filename)) + + } + + static get Instance () { + return this.instance || (this.instance = new this()) + } +} + +// --------------------------------------------------------------------------- + +export { + VideoPathManager +} diff --git a/server/lib/video-paths.ts b/server/lib/video-paths.ts deleted file mode 100644 index 3bff6c0bd55..00000000000 --- a/server/lib/video-paths.ts +++ /dev/null @@ -1,144 +0,0 @@ -import { stat } from 'fs-extra' -import { join } from 'path' -import { buildUUID } from '@server/helpers/uuid' -import { extractVideo } from '@server/helpers/video' -import { CONFIG } from '@server/initializers/config' -import { HLS_REDUNDANCY_DIRECTORY, HLS_STREAMING_PLAYLIST_DIRECTORY, STATIC_PATHS, WEBSERVER } from '@server/initializers/constants' -import { isStreamingPlaylist, MStreamingPlaylist, MStreamingPlaylistVideo, MVideo, MVideoFile, MVideoUUID } from '@server/types/models' -import { removeFragmentedMP4Ext } from '@shared/core-utils' -import { makeAvailable } from './object-storage/shared/object-storage-helpers' - -// ################## Video file name ################## - -function generateWebTorrentVideoFilename (resolution: number, extname: string) { - return buildUUID() + '-' + resolution + extname -} - -function generateHLSVideoFilename (resolution: number) { - return `${buildUUID()}-${resolution}-fragmented.mp4` -} - -function getVideoFilePath (videoOrPlaylist: MVideo | MStreamingPlaylistVideo, videoFile: MVideoFile, isRedundancy = false) { - if (videoFile.isHLS()) { - const video = extractVideo(videoOrPlaylist) - - return join(getHLSDirectory(video), videoFile.filename) - } - - const baseDir = isRedundancy - ? CONFIG.STORAGE.REDUNDANCY_DIR - : CONFIG.STORAGE.VIDEOS_DIR - - return join(baseDir, videoFile.filename) -} - -async function getVideoFilePathMakeAvailable ( - videoOrPlaylist: MVideo | MStreamingPlaylistVideo, - videoFile: MVideoFile -) { - const path = getVideoFilePath(videoOrPlaylist, videoFile) - try { - await stat(path) - return path - } catch { - // Continue if path not available - } - - if (videoFile.isHLS()) { - const video = extractVideo(videoOrPlaylist) - await makeAvailable( - { filename: join((videoOrPlaylist as MStreamingPlaylistVideo).getStringType(), video.uuid, videoFile.filename), at: path }, - CONFIG.OBJECT_STORAGE.STREAMING_PLAYLISTS - ) - return path - } - - await makeAvailable({ filename: videoFile.filename, at: path }, CONFIG.OBJECT_STORAGE.VIDEOS) - return path -} - -// ################## Redundancy ################## - -function generateHLSRedundancyUrl (video: MVideo, playlist: MStreamingPlaylist) { - // Base URL used by our HLS player - return WEBSERVER.URL + STATIC_PATHS.REDUNDANCY + playlist.getStringType() + '/' + video.uuid -} - -function generateWebTorrentRedundancyUrl (file: MVideoFile) { - return WEBSERVER.URL + STATIC_PATHS.REDUNDANCY + file.filename -} - -// ################## Streaming playlist ################## - -function getHLSDirectory (video: MVideoUUID, isRedundancy = false) { - const baseDir = isRedundancy - ? HLS_REDUNDANCY_DIRECTORY - : HLS_STREAMING_PLAYLIST_DIRECTORY - - return join(baseDir, video.uuid) -} - -function getHlsResolutionPlaylistFilename (videoFilename: string) { - // Video file name already contain resolution - return removeFragmentedMP4Ext(videoFilename) + '.m3u8' -} - -function generateHLSMasterPlaylistFilename (isLive = false) { - if (isLive) return 'master.m3u8' - - return buildUUID() + '-master.m3u8' -} - -function generateHlsSha256SegmentsFilename (isLive = false) { - if (isLive) return 'segments-sha256.json' - - return buildUUID() + '-segments-sha256.json' -} - -// ################## Torrents ################## - -function generateTorrentFileName (videoOrPlaylist: MVideo | MStreamingPlaylistVideo, resolution: number) { - const extension = '.torrent' - const uuid = buildUUID() - - if (isStreamingPlaylist(videoOrPlaylist)) { - return `${uuid}-${resolution}-${videoOrPlaylist.getStringType()}${extension}` - } - - return uuid + '-' + resolution + extension -} - -function getTorrentFilePath (videoFile: MVideoFile) { - return join(CONFIG.STORAGE.TORRENTS_DIR, videoFile.torrentFilename) -} - -// ################## Meta data ################## - -function getLocalVideoFileMetadataUrl (video: MVideoUUID, videoFile: MVideoFile) { - const path = '/api/v1/videos/' - - return WEBSERVER.URL + path + video.uuid + '/metadata/' + videoFile.id -} - -// --------------------------------------------------------------------------- - -export { - generateHLSVideoFilename, - generateWebTorrentVideoFilename, - - getVideoFilePath, - getVideoFilePathMakeAvailable, - - generateTorrentFileName, - getTorrentFilePath, - - getHLSDirectory, - generateHLSMasterPlaylistFilename, - generateHlsSha256SegmentsFilename, - getHlsResolutionPlaylistFilename, - - getLocalVideoFileMetadataUrl, - - generateWebTorrentRedundancyUrl, - generateHLSRedundancyUrl -} diff --git a/server/lib/video-state.ts b/server/lib/video-state.ts index ee28f7e4884..0613d94bfa2 100644 --- a/server/lib/video-state.ts +++ b/server/lib/video-state.ts @@ -52,7 +52,7 @@ function moveToNextState (video: MVideoUUID, isNewVideo = true) { } if (newState === VideoState.TO_MOVE_TO_EXTERNAL_STORAGE) { - return moveToExternalStorageState(videoDatabase, t) + return moveToExternalStorageState(videoDatabase, isNewVideo, t) } }) } @@ -83,17 +83,17 @@ async function moveToPublishedState (video: MVideoFullLight, isNewVideo: boolean } } -async function moveToExternalStorageState (video: MVideoFullLight, transaction: Transaction) { +async function moveToExternalStorageState (video: MVideoFullLight, isNewVideo: boolean, transaction: Transaction) { const videoJobInfo = await VideoJobInfoModel.load(video.id, transaction) - const pendingTranscoding = videoJobInfo?.pendingTranscoding || 0 + const pendingTranscode = videoJobInfo?.pendingTranscode || 0 // We want to wait all transcoding jobs before moving the video on an external storage - if (pendingTranscoding !== 0) return + if (pendingTranscode !== 0) return await video.setNewState(VideoState.TO_MOVE_TO_EXTERNAL_STORAGE, transaction) logger.info('Creating external storage move job for video %s.', video.uuid, { tags: [ video.uuid ] }) - addMoveToObjectStorageJob(video) + addMoveToObjectStorageJob(video, isNewVideo) .catch(err => logger.error('Cannot add move to object storage job', { err })) } diff --git a/server/lib/video-urls.ts b/server/lib/video-urls.ts new file mode 100644 index 00000000000..64c2c9bf94a --- /dev/null +++ b/server/lib/video-urls.ts @@ -0,0 +1,31 @@ + +import { STATIC_PATHS, WEBSERVER } from '@server/initializers/constants' +import { MStreamingPlaylist, MVideo, MVideoFile, MVideoUUID } from '@server/types/models' + +// ################## Redundancy ################## + +function generateHLSRedundancyUrl (video: MVideo, playlist: MStreamingPlaylist) { + // Base URL used by our HLS player + return WEBSERVER.URL + STATIC_PATHS.REDUNDANCY + playlist.getStringType() + '/' + video.uuid +} + +function generateWebTorrentRedundancyUrl (file: MVideoFile) { + return WEBSERVER.URL + STATIC_PATHS.REDUNDANCY + file.filename +} + +// ################## Meta data ################## + +function getLocalVideoFileMetadataUrl (video: MVideoUUID, videoFile: MVideoFile) { + const path = '/api/v1/videos/' + + return WEBSERVER.URL + path + video.uuid + '/metadata/' + videoFile.id +} + +// --------------------------------------------------------------------------- + +export { + getLocalVideoFileMetadataUrl, + + generateWebTorrentRedundancyUrl, + generateHLSRedundancyUrl +} diff --git a/server/lib/video.ts b/server/lib/video.ts index 30575125444..0a2b93cc029 100644 --- a/server/lib/video.ts +++ b/server/lib/video.ts @@ -106,15 +106,15 @@ async function addOptimizeOrMergeAudioJob (video: MVideoUUID, videoFile: MVideoF } async function addTranscodingJob (payload: VideoTranscodingPayload, options: CreateJobOptions) { - await VideoJobInfoModel.increaseOrCreate(payload.videoUUID, 'pendingTranscoding') + await VideoJobInfoModel.increaseOrCreate(payload.videoUUID, 'pendingTranscode') return JobQueue.Instance.createJobWithPromise({ type: 'video-transcoding', payload: payload }, options) } -async function addMoveToObjectStorageJob (video: MVideoUUID) { +async function addMoveToObjectStorageJob (video: MVideoUUID, isNewVideo = true) { await VideoJobInfoModel.increaseOrCreate(video.uuid, 'pendingMove') - const dataInput = { videoUUID: video.uuid } + const dataInput = { videoUUID: video.uuid, isNewVideo } return JobQueue.Instance.createJobWithPromise({ type: 'move-to-object-storage', payload: dataInput }) } diff --git a/server/models/video/formatter/video-format-utils.ts b/server/models/video/formatter/video-format-utils.ts index 8a54de3b031..b3c4f390d1e 100644 --- a/server/models/video/formatter/video-format-utils.ts +++ b/server/models/video/formatter/video-format-utils.ts @@ -1,6 +1,6 @@ import { uuidToShort } from '@server/helpers/uuid' import { generateMagnetUri } from '@server/helpers/webtorrent' -import { getLocalVideoFileMetadataUrl } from '@server/lib/video-paths' +import { getLocalVideoFileMetadataUrl } from '@server/lib/video-urls' import { VideoFile } from '@shared/models/videos/video-file.model' import { ActivityTagObject, ActivityUrlObject, VideoObject } from '../../../../shared/models/activitypub/objects' import { Video, VideoDetails } from '../../../../shared/models/videos' diff --git a/server/models/video/video-file.ts b/server/models/video/video-file.ts index ccfbc817d4e..627c957635b 100644 --- a/server/models/video/video-file.ts +++ b/server/models/video/video-file.ts @@ -24,7 +24,7 @@ import { buildRemoteVideoBaseUrl } from '@server/helpers/activitypub' import { logger } from '@server/helpers/logger' import { extractVideo } from '@server/helpers/video' import { getHLSPublicFileUrl, getWebTorrentPublicFileUrl } from '@server/lib/object-storage' -import { getTorrentFilePath } from '@server/lib/video-paths' +import { getFSTorrentFilePath } from '@server/lib/paths' import { MStreamingPlaylistVideo, MVideo, MVideoWithHost } from '@server/types/models' import { AttributesOnly } from '@shared/core-utils' import { VideoStorage } from '@shared/models' @@ -217,7 +217,7 @@ export class VideoFileModel extends Model videoId: number @AllowNull(false) - @Default(VideoStorage.LOCAL) + @Default(VideoStorage.FILE_SYSTEM) @Column storage: VideoStorage @@ -280,7 +280,7 @@ export class VideoFileModel extends Model static async doesOwnedWebTorrentVideoFileExist (filename: string) { const query = 'SELECT 1 FROM "videoFile" INNER JOIN "video" ON "video"."id" = "videoFile"."videoId" AND "video"."remote" IS FALSE ' + - `WHERE "filename" = $filename AND "storage" = ${VideoStorage.LOCAL} LIMIT 1` + `WHERE "filename" = $filename AND "storage" = ${VideoStorage.FILE_SYSTEM} LIMIT 1` return doesExist(query, { filename }) } @@ -521,7 +521,7 @@ export class VideoFileModel extends Model removeTorrent () { if (!this.torrentFilename) return null - const torrentPath = getTorrentFilePath(this) + const torrentPath = getFSTorrentFilePath(this) return remove(torrentPath) .catch(err => logger.warn('Cannot delete torrent %s.', torrentPath, { err })) } diff --git a/server/models/video/video-job-info.ts b/server/models/video/video-job-info.ts index 766695b22b1..7c1fe67345b 100644 --- a/server/models/video/video-job-info.ts +++ b/server/models/video/video-job-info.ts @@ -34,7 +34,7 @@ export class VideoJobInfoModel extends Model VideoModel) @Unique @@ -57,7 +57,7 @@ export class VideoJobInfoModel extends Model { + static async increaseOrCreate (videoUUID: string, column: 'pendingMove' | 'pendingTranscode'): Promise { const options = { type: QueryTypes.SELECT as QueryTypes.SELECT, bind: { videoUUID } } const [ { pendingMove } ] = await VideoJobInfoModel.sequelize.query<{ pendingMove: number }>(` @@ -79,7 +79,7 @@ export class VideoJobInfoModel extends Model { + static async decrease (videoUUID: string, column: 'pendingMove' | 'pendingTranscode'): Promise { const options = { type: QueryTypes.SELECT as QueryTypes.SELECT, bind: { videoUUID } } const [ { pendingMove } ] = await VideoJobInfoModel.sequelize.query<{ pendingMove: number }>(` diff --git a/server/models/video/video-streaming-playlist.ts b/server/models/video/video-streaming-playlist.ts index 66277d396c7..3e9fd97c72e 100644 --- a/server/models/video/video-streaming-playlist.ts +++ b/server/models/video/video-streaming-playlist.ts @@ -97,7 +97,7 @@ export class VideoStreamingPlaylistModel extends Model>> { return peertubeTruncate(this.description, { length: maxLength }) } - async getMaxQualityResolution () { + getMaxQualityResolution () { const file = this.getMaxQualityFile() const videoOrPlaylist = file.getVideoOrStreamingPlaylist() - const originalFilePath = await getVideoFilePathMakeAvailable(videoOrPlaylist, file) - return getVideoFileResolution(originalFilePath) + return VideoPathManager.Instance.makeAvailableVideoFile(videoOrPlaylist, file, originalFilePath => { + return getVideoFileResolution(originalFilePath) + }) } getDescriptionAPIPath () { @@ -1684,7 +1686,9 @@ export class VideoModel extends Model>> { } removeFileAndTorrent (videoFile: MVideoFile, isRedundancy = false) { - const filePath = getVideoFilePath(this, videoFile, isRedundancy) + const filePath = isRedundancy + ? VideoPathManager.Instance.getFSRedundancyVideoFilePath(this, videoFile) + : VideoPathManager.Instance.getFSVideoFileOutputPath(this, videoFile) const promises: Promise[] = [ remove(filePath) ] if (!isRedundancy) promises.push(videoFile.removeTorrent()) @@ -1697,7 +1701,9 @@ export class VideoModel extends Model>> { } async removeStreamingPlaylistFiles (streamingPlaylist: MStreamingPlaylist, isRedundancy = false) { - const directoryPath = getHLSDirectory(this, isRedundancy) + const directoryPath = isRedundancy + ? getHLSRedundancyDirectory(this) + : getHLSDirectory(this) await remove(directoryPath) diff --git a/server/tests/api/live/live-save-replay.ts b/server/tests/api/live/live-save-replay.ts index 8f1fb78a5c3..6c4ea90ca88 100644 --- a/server/tests/api/live/live-save-replay.ts +++ b/server/tests/api/live/live-save-replay.ts @@ -15,7 +15,9 @@ import { stopFfmpeg, testFfmpegStreamError, wait, - waitJobs + waitJobs, + waitUntilLivePublishedOnAllServers, + waitUntilLiveSavedOnAllServers } from '@shared/extra-utils' import { HttpStatusCode, LiveVideoCreate, VideoPrivacy, VideoState } from '@shared/models' @@ -66,18 +68,6 @@ describe('Save replay setting', function () { } } - async function waitUntilLivePublishedOnAllServers (videoId: string) { - for (const server of servers) { - await server.live.waitUntilPublished({ videoId }) - } - } - - async function waitUntilLiveSavedOnAllServers (videoId: string) { - for (const server of servers) { - await server.live.waitUntilSaved({ videoId }) - } - } - before(async function () { this.timeout(120000) @@ -127,7 +117,7 @@ describe('Save replay setting', function () { ffmpegCommand = await servers[0].live.sendRTMPStreamInVideo({ videoId: liveVideoUUID }) - await waitUntilLivePublishedOnAllServers(liveVideoUUID) + await waitUntilLivePublishedOnAllServers(servers, liveVideoUUID) await waitJobs(servers) @@ -160,7 +150,7 @@ describe('Save replay setting', function () { ffmpegCommand = await servers[0].live.sendRTMPStreamInVideo({ videoId: liveVideoUUID }) - await waitUntilLivePublishedOnAllServers(liveVideoUUID) + await waitUntilLivePublishedOnAllServers(servers, liveVideoUUID) await waitJobs(servers) await checkVideosExist(liveVideoUUID, true, HttpStatusCode.OK_200) @@ -189,7 +179,7 @@ describe('Save replay setting', function () { ffmpegCommand = await servers[0].live.sendRTMPStreamInVideo({ videoId: liveVideoUUID }) - await waitUntilLivePublishedOnAllServers(liveVideoUUID) + await waitUntilLivePublishedOnAllServers(servers, liveVideoUUID) await waitJobs(servers) await checkVideosExist(liveVideoUUID, true, HttpStatusCode.OK_200) @@ -224,7 +214,7 @@ describe('Save replay setting', function () { this.timeout(20000) ffmpegCommand = await servers[0].live.sendRTMPStreamInVideo({ videoId: liveVideoUUID }) - await waitUntilLivePublishedOnAllServers(liveVideoUUID) + await waitUntilLivePublishedOnAllServers(servers, liveVideoUUID) await waitJobs(servers) @@ -237,7 +227,7 @@ describe('Save replay setting', function () { await stopFfmpeg(ffmpegCommand) - await waitUntilLiveSavedOnAllServers(liveVideoUUID) + await waitUntilLiveSavedOnAllServers(servers, liveVideoUUID) await waitJobs(servers) // Live has been transcoded @@ -268,7 +258,7 @@ describe('Save replay setting', function () { liveVideoUUID = await createLiveWrapper(true) ffmpegCommand = await servers[0].live.sendRTMPStreamInVideo({ videoId: liveVideoUUID }) - await waitUntilLivePublishedOnAllServers(liveVideoUUID) + await waitUntilLivePublishedOnAllServers(servers, liveVideoUUID) await waitJobs(servers) await checkVideosExist(liveVideoUUID, true, HttpStatusCode.OK_200) @@ -296,7 +286,7 @@ describe('Save replay setting', function () { liveVideoUUID = await createLiveWrapper(true) ffmpegCommand = await servers[0].live.sendRTMPStreamInVideo({ videoId: liveVideoUUID }) - await waitUntilLivePublishedOnAllServers(liveVideoUUID) + await waitUntilLivePublishedOnAllServers(servers, liveVideoUUID) await waitJobs(servers) await checkVideosExist(liveVideoUUID, true, HttpStatusCode.OK_200) diff --git a/server/tests/api/object-storage/index.ts b/server/tests/api/object-storage/index.ts index e29a9b7670f..f319d6ef58d 100644 --- a/server/tests/api/object-storage/index.ts +++ b/server/tests/api/object-storage/index.ts @@ -1 +1,3 @@ +export * from './live' +export * from './video-imports' export * from './videos' diff --git a/server/tests/api/object-storage/live.ts b/server/tests/api/object-storage/live.ts new file mode 100644 index 00000000000..d3e6777f293 --- /dev/null +++ b/server/tests/api/object-storage/live.ts @@ -0,0 +1,136 @@ +/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ + +import 'mocha' +import * as chai from 'chai' +import { FfmpegCommand } from 'fluent-ffmpeg' +import { + areObjectStorageTestsDisabled, + createMultipleServers, + doubleFollow, + expectStartWith, + killallServers, + makeRawRequest, + ObjectStorageCommand, + PeerTubeServer, + setAccessTokensToServers, + setDefaultVideoChannel, + stopFfmpeg, + waitJobs, + waitUntilLivePublishedOnAllServers, + waitUntilLiveSavedOnAllServers +} from '@shared/extra-utils' +import { HttpStatusCode, LiveVideoCreate, VideoFile, VideoPrivacy } from '@shared/models' + +const expect = chai.expect + +async function createLive (server: PeerTubeServer) { + const attributes: LiveVideoCreate = { + channelId: server.store.channel.id, + privacy: VideoPrivacy.PUBLIC, + name: 'my super live', + saveReplay: true + } + + const { uuid } = await server.live.create({ fields: attributes }) + + return uuid +} + +async function checkFiles (files: VideoFile[]) { + for (const file of files) { + expectStartWith(file.fileUrl, ObjectStorageCommand.getPlaylistBaseUrl()) + + await makeRawRequest(file.fileUrl, HttpStatusCode.OK_200) + } +} + +describe('Object storage for lives', function () { + if (areObjectStorageTestsDisabled()) return + + let ffmpegCommand: FfmpegCommand + let servers: PeerTubeServer[] + let videoUUID: string + + before(async function () { + this.timeout(120000) + + await ObjectStorageCommand.prepareDefaultBuckets() + + servers = await createMultipleServers(2, ObjectStorageCommand.getDefaultConfig()) + + await setAccessTokensToServers(servers) + await setDefaultVideoChannel(servers) + await doubleFollow(servers[0], servers[1]) + + await servers[0].config.enableTranscoding() + }) + + describe('Without live transcoding', async function () { + + before(async function () { + await servers[0].config.enableLive({ transcoding: false }) + + videoUUID = await createLive(servers[0]) + }) + + it('Should create a live and save the replay on object storage', async function () { + this.timeout(220000) + + ffmpegCommand = await servers[0].live.sendRTMPStreamInVideo({ videoId: videoUUID }) + await waitUntilLivePublishedOnAllServers(servers, videoUUID) + + await stopFfmpeg(ffmpegCommand) + + await waitUntilLiveSavedOnAllServers(servers, videoUUID) + await waitJobs(servers) + + for (const server of servers) { + const video = await server.videos.get({ id: videoUUID }) + + expect(video.files).to.have.lengthOf(0) + expect(video.streamingPlaylists).to.have.lengthOf(1) + + const files = video.streamingPlaylists[0].files + + await checkFiles(files) + } + }) + }) + + describe('With live transcoding', async function () { + + before(async function () { + await servers[0].config.enableLive({ transcoding: true }) + + videoUUID = await createLive(servers[0]) + }) + + it('Should import a video and have sent it to object storage', async function () { + this.timeout(240000) + + ffmpegCommand = await servers[0].live.sendRTMPStreamInVideo({ videoId: videoUUID }) + await waitUntilLivePublishedOnAllServers(servers, videoUUID) + + await stopFfmpeg(ffmpegCommand) + + await waitUntilLiveSavedOnAllServers(servers, videoUUID) + await waitJobs(servers) + + for (const server of servers) { + const video = await server.videos.get({ id: videoUUID }) + + expect(video.files).to.have.lengthOf(0) + expect(video.streamingPlaylists).to.have.lengthOf(1) + + const files = video.streamingPlaylists[0].files + expect(files).to.have.lengthOf(4) + + await checkFiles(files) + } + }) + }) + + after(async function () { + await killallServers(servers) + }) +}) diff --git a/server/tests/api/object-storage/video-imports.ts b/server/tests/api/object-storage/video-imports.ts new file mode 100644 index 00000000000..efc01f55041 --- /dev/null +++ b/server/tests/api/object-storage/video-imports.ts @@ -0,0 +1,112 @@ +/* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */ + +import 'mocha' +import * as chai from 'chai' +import { + areObjectStorageTestsDisabled, + createSingleServer, + expectStartWith, + FIXTURE_URLS, + killallServers, + makeRawRequest, + ObjectStorageCommand, + PeerTubeServer, + setAccessTokensToServers, + setDefaultVideoChannel, + waitJobs +} from '@shared/extra-utils' +import { HttpStatusCode, VideoPrivacy } from '@shared/models' + +const expect = chai.expect + +async function importVideo (server: PeerTubeServer) { + const attributes = { + name: 'import 2', + privacy: VideoPrivacy.PUBLIC, + channelId: server.store.channel.id, + targetUrl: FIXTURE_URLS.goodVideo720 + } + + const { video: { uuid } } = await server.imports.importVideo({ attributes }) + + return uuid +} + +describe('Object storage for video import', function () { + if (areObjectStorageTestsDisabled()) return + + let server: PeerTubeServer + + before(async function () { + this.timeout(120000) + + await ObjectStorageCommand.prepareDefaultBuckets() + + server = await createSingleServer(1, ObjectStorageCommand.getDefaultConfig()) + + await setAccessTokensToServers([ server ]) + await setDefaultVideoChannel([ server ]) + + await server.config.enableImports() + }) + + describe('Without transcoding', async function () { + + before(async function () { + await server.config.disableTranscoding() + }) + + it('Should import a video and have sent it to object storage', async function () { + this.timeout(120000) + + const uuid = await importVideo(server) + await waitJobs(server) + + const video = await server.videos.get({ id: uuid }) + + expect(video.files).to.have.lengthOf(1) + expect(video.streamingPlaylists).to.have.lengthOf(0) + + const fileUrl = video.files[0].fileUrl + expectStartWith(fileUrl, ObjectStorageCommand.getWebTorrentBaseUrl()) + + await makeRawRequest(fileUrl, HttpStatusCode.OK_200) + }) + }) + + describe('With transcoding', async function () { + + before(async function () { + await server.config.enableTranscoding() + }) + + it('Should import a video and have sent it to object storage', async function () { + this.timeout(120000) + + const uuid = await importVideo(server) + await waitJobs(server) + + const video = await server.videos.get({ id: uuid }) + + expect(video.files).to.have.lengthOf(4) + expect(video.streamingPlaylists).to.have.lengthOf(1) + expect(video.streamingPlaylists[0].files).to.have.lengthOf(4) + + for (const file of video.files) { + expectStartWith(file.fileUrl, ObjectStorageCommand.getWebTorrentBaseUrl()) + + await makeRawRequest(file.fileUrl, HttpStatusCode.OK_200) + } + + for (const file of video.streamingPlaylists[0].files) { + expectStartWith(file.fileUrl, ObjectStorageCommand.getPlaylistBaseUrl()) + + await makeRawRequest(file.fileUrl, HttpStatusCode.OK_200) + } + }) + }) + + after(async function () { + await killallServers([ server ]) + }) +}) diff --git a/server/tests/api/object-storage/videos.ts b/server/tests/api/object-storage/videos.ts index 847b7283d4d..3958bd3d7aa 100644 --- a/server/tests/api/object-storage/videos.ts +++ b/server/tests/api/object-storage/videos.ts @@ -2,13 +2,19 @@ import 'mocha' import * as chai from 'chai' +import { merge } from 'lodash' import { + areObjectStorageTestsDisabled, + checkTmpIsEmpty, cleanupTests, createMultipleServers, + createSingleServer, doubleFollow, expectStartWith, + killallServers, makeRawRequest, MockObjectStorage, + ObjectStorageCommand, PeerTubeServer, setAccessTokensToServers, waitJobs, @@ -21,17 +27,15 @@ const expect = chai.expect async function checkFiles (options: { video: VideoDetails - mockObjectStorage: MockObjectStorage + baseMockUrl?: string playlistBucket: string playlistPrefix?: string - baseMockUrl?: string webtorrentBucket: string webtorrentPrefix?: string }) { const { - mockObjectStorage, video, playlistBucket, webtorrentBucket, @@ -45,7 +49,7 @@ async function checkFiles (options: { for (const file of video.files) { const baseUrl = baseMockUrl ? `${baseMockUrl}/${webtorrentBucket}/` - : `http://${webtorrentBucket}.${mockObjectStorage.getEndpointHost()}/` + : `http://${webtorrentBucket}.${ObjectStorageCommand.getEndpointHost()}/` const prefix = webtorrentPrefix || '' const start = baseUrl + prefix @@ -66,7 +70,7 @@ async function checkFiles (options: { const baseUrl = baseMockUrl ? `${baseMockUrl}/${playlistBucket}/` - : `http://${playlistBucket}.${mockObjectStorage.getEndpointHost()}/` + : `http://${playlistBucket}.${ObjectStorageCommand.getEndpointHost()}/` const prefix = playlistPrefix || '' const start = baseUrl + prefix @@ -75,6 +79,7 @@ async function checkFiles (options: { expectStartWith(hls.segmentsSha256Url, start) await makeRawRequest(hls.playlistUrl, HttpStatusCode.OK_200) + const resSha = await makeRawRequest(hls.segmentsSha256Url, HttpStatusCode.OK_200) expect(JSON.stringify(resSha.body)).to.not.throw @@ -130,16 +135,16 @@ function runTestSuite (options: { const port = await mockObjectStorage.initialize() baseMockUrl = options.useMockBaseUrl ? `http://localhost:${port}` : undefined - await mockObjectStorage.createBucket(options.playlistBucket) - await mockObjectStorage.createBucket(options.webtorrentBucket) + await ObjectStorageCommand.createBucket(options.playlistBucket) + await ObjectStorageCommand.createBucket(options.webtorrentBucket) const config = { object_storage: { enabled: true, - endpoint: 'http://' + mockObjectStorage.getEndpointHost(), - region: mockObjectStorage.getRegion(), + endpoint: 'http://' + ObjectStorageCommand.getEndpointHost(), + region: ObjectStorageCommand.getRegion(), - credentials: mockObjectStorage.getCrendentialsConfig(), + credentials: ObjectStorageCommand.getCredentialsConfig(), max_upload_part: options.maxUploadPart || '2MB', @@ -185,7 +190,7 @@ function runTestSuite (options: { for (const server of servers) { const video = await server.videos.get({ id: uuid }) - const files = await checkFiles({ ...options, mockObjectStorage, video, baseMockUrl }) + const files = await checkFiles({ ...options, video, baseMockUrl }) deletedUrls = deletedUrls.concat(files) } @@ -201,7 +206,7 @@ function runTestSuite (options: { for (const server of servers) { const video = await server.videos.get({ id: uuid }) - const files = await checkFiles({ ...options, mockObjectStorage, video, baseMockUrl }) + const files = await checkFiles({ ...options, video, baseMockUrl }) deletedUrls = deletedUrls.concat(files) } @@ -224,6 +229,12 @@ function runTestSuite (options: { } }) + it('Should have an empty tmp directory', async function () { + for (const server of servers) { + await checkTmpIsEmpty(server) + } + }) + after(async function () { mockObjectStorage.terminate() @@ -231,7 +242,114 @@ function runTestSuite (options: { }) } -describe('Object storage', function () { +describe('Object storage for videos', function () { + if (areObjectStorageTestsDisabled()) return + + describe('Test config', function () { + let server: PeerTubeServer + + const baseConfig = { + object_storage: { + enabled: true, + endpoint: 'http://' + ObjectStorageCommand.getEndpointHost(), + region: ObjectStorageCommand.getRegion(), + + credentials: ObjectStorageCommand.getCredentialsConfig(), + + streaming_playlists: { + bucket_name: ObjectStorageCommand.DEFAULT_PLAYLIST_BUCKET + }, + + videos: { + bucket_name: ObjectStorageCommand.DEFAULT_WEBTORRENT_BUCKET + } + } + } + + const badCredentials = { + access_key_id: 'AKIAIOSFODNN7EXAMPLE', + secret_access_key: 'aJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY' + } + + it('Should fail with same bucket names without prefix', function (done) { + const config = merge({}, baseConfig, { + object_storage: { + streaming_playlists: { + bucket_name: 'aaa' + }, + + videos: { + bucket_name: 'aaa' + } + } + }) + + createSingleServer(1, config) + .then(() => done(new Error('Did not throw'))) + .catch(() => done()) + }) + + it('Should fail with bad credentials', async function () { + this.timeout(60000) + + await ObjectStorageCommand.prepareDefaultBuckets() + + const config = merge({}, baseConfig, { + object_storage: { + credentials: badCredentials + } + }) + + server = await createSingleServer(1, config) + await setAccessTokensToServers([ server ]) + + const { uuid } = await server.videos.quickUpload({ name: 'video' }) + + await waitJobs([ server ], true) + const video = await server.videos.get({ id: uuid }) + + expectStartWith(video.files[0].fileUrl, server.url) + + await killallServers([ server ]) + }) + + it('Should succeed with credentials from env', async function () { + this.timeout(60000) + + await ObjectStorageCommand.prepareDefaultBuckets() + + const config = merge({}, baseConfig, { + object_storage: { + credentials: { + access_key_id: '', + secret_access_key: '' + } + } + }) + + const goodCredentials = ObjectStorageCommand.getCredentialsConfig() + + server = await createSingleServer(1, config, { + env: { + AWS_ACCESS_KEY_ID: goodCredentials.access_key_id, + AWS_SECRET_ACCESS_KEY: goodCredentials.secret_access_key + } + }) + + await setAccessTokensToServers([ server ]) + + const { uuid } = await server.videos.quickUpload({ name: 'video' }) + + await waitJobs([ server ], true) + const video = await server.videos.get({ id: uuid }) + + expectStartWith(video.files[0].fileUrl, ObjectStorageCommand.getWebTorrentBaseUrl()) + }) + + after(async function () { + await killallServers([ server ]) + }) + }) describe('Test simple object storage', function () { runTestSuite({ diff --git a/server/tests/api/redundancy/redundancy.ts b/server/tests/api/redundancy/redundancy.ts index e1a12f5f8c5..3400b1d9adc 100644 --- a/server/tests/api/redundancy/redundancy.ts +++ b/server/tests/api/redundancy/redundancy.ts @@ -207,14 +207,14 @@ async function check1PlaylistRedundancies (videoUUID?: string) { expect(redundancy.baseUrl).to.equal(servers[0].url + '/static/redundancy/hls/' + videoUUID) } - const baseUrlPlaylist = servers[1].url + '/static/streaming-playlists/hls' - const baseUrlSegment = servers[0].url + '/static/redundancy/hls' + const baseUrlPlaylist = servers[1].url + '/static/streaming-playlists/hls/' + videoUUID + const baseUrlSegment = servers[0].url + '/static/redundancy/hls/' + videoUUID const video = await servers[0].videos.get({ id: videoUUID }) const hlsPlaylist = video.streamingPlaylists[0] for (const resolution of [ 240, 360, 480, 720 ]) { - await checkSegmentHash({ server: servers[1], baseUrlPlaylist, baseUrlSegment, videoUUID, resolution, hlsPlaylist }) + await checkSegmentHash({ server: servers[1], baseUrlPlaylist, baseUrlSegment, resolution, hlsPlaylist }) } const { hlsFilenames } = await ensureSameFilenames(videoUUID) diff --git a/server/tests/api/videos/video-hls.ts b/server/tests/api/videos/video-hls.ts index 961f0e617fc..2c829f53289 100644 --- a/server/tests/api/videos/video-hls.ts +++ b/server/tests/api/videos/video-hls.ts @@ -5,6 +5,7 @@ import * as chai from 'chai' import { basename, join } from 'path' import { removeFragmentedMP4Ext, uuidRegex } from '@shared/core-utils' import { + areObjectStorageTestsDisabled, checkDirectoryIsEmpty, checkResolutionsInMasterPlaylist, checkSegmentHash, @@ -12,7 +13,9 @@ import { cleanupTests, createMultipleServers, doubleFollow, + expectStartWith, makeRawRequest, + ObjectStorageCommand, PeerTubeServer, setAccessTokensToServers, waitJobs, @@ -23,8 +26,19 @@ import { DEFAULT_AUDIO_RESOLUTION } from '../../../initializers/constants' const expect = chai.expect -async function checkHlsPlaylist (servers: PeerTubeServer[], videoUUID: string, hlsOnly: boolean, resolutions = [ 240, 360, 480, 720 ]) { - for (const server of servers) { +async function checkHlsPlaylist (options: { + servers: PeerTubeServer[] + videoUUID: string + hlsOnly: boolean + + resolutions?: number[] + objectStorageBaseUrl: string +}) { + const { videoUUID, hlsOnly, objectStorageBaseUrl } = options + + const resolutions = options.resolutions ?? [ 240, 360, 480, 720 ] + + for (const server of options.servers) { const videoDetails = await server.videos.get({ id: videoUUID }) const baseUrl = `http://${videoDetails.account.host}` @@ -48,9 +62,15 @@ async function checkHlsPlaylist (servers: PeerTubeServer[], videoUUID: string, h expect(file.torrentUrl).to.match( new RegExp(`http://${server.host}/lazy-static/torrents/${uuidRegex}-${file.resolution.id}-hls.torrent`) ) - expect(file.fileUrl).to.match( - new RegExp(`${baseUrl}/static/streaming-playlists/hls/${videoDetails.uuid}/${uuidRegex}-${file.resolution.id}-fragmented.mp4`) - ) + + if (objectStorageBaseUrl) { + expectStartWith(file.fileUrl, objectStorageBaseUrl) + } else { + expect(file.fileUrl).to.match( + new RegExp(`${baseUrl}/static/streaming-playlists/hls/${videoDetails.uuid}/${uuidRegex}-${file.resolution.id}-fragmented.mp4`) + ) + } + expect(file.resolution.label).to.equal(resolution + 'p') await makeRawRequest(file.torrentUrl, HttpStatusCode.OK_200) @@ -80,9 +100,11 @@ async function checkHlsPlaylist (servers: PeerTubeServer[], videoUUID: string, h const file = hlsFiles.find(f => f.resolution.id === resolution) const playlistName = removeFragmentedMP4Ext(basename(file.fileUrl)) + '.m3u8' - const subPlaylist = await server.streamingPlaylists.get({ - url: `${baseUrl}/static/streaming-playlists/hls/${videoUUID}/${playlistName}` - }) + const url = objectStorageBaseUrl + ? `${objectStorageBaseUrl}hls_${videoUUID}/${playlistName}` + : `${baseUrl}/static/streaming-playlists/hls/${videoUUID}/${playlistName}` + + const subPlaylist = await server.streamingPlaylists.get({ url }) expect(subPlaylist).to.match(new RegExp(`${uuidRegex}-${resolution}-fragmented.mp4`)) expect(subPlaylist).to.contain(basename(file.fileUrl)) @@ -90,14 +112,15 @@ async function checkHlsPlaylist (servers: PeerTubeServer[], videoUUID: string, h } { - const baseUrlAndPath = baseUrl + '/static/streaming-playlists/hls' + const baseUrlAndPath = objectStorageBaseUrl + ? objectStorageBaseUrl + 'hls_' + videoUUID + : baseUrl + '/static/streaming-playlists/hls/' + videoUUID for (const resolution of resolutions) { await checkSegmentHash({ server, baseUrlPlaylist: baseUrlAndPath, baseUrlSegment: baseUrlAndPath, - videoUUID, resolution, hlsPlaylist }) @@ -111,7 +134,7 @@ describe('Test HLS videos', function () { let videoUUID = '' let videoAudioUUID = '' - function runTestSuite (hlsOnly: boolean) { + function runTestSuite (hlsOnly: boolean, objectStorageBaseUrl?: string) { it('Should upload a video and transcode it to HLS', async function () { this.timeout(120000) @@ -121,7 +144,7 @@ describe('Test HLS videos', function () { await waitJobs(servers) - await checkHlsPlaylist(servers, videoUUID, hlsOnly) + await checkHlsPlaylist({ servers, videoUUID, hlsOnly, objectStorageBaseUrl }) }) it('Should upload an audio file and transcode it to HLS', async function () { @@ -132,7 +155,13 @@ describe('Test HLS videos', function () { await waitJobs(servers) - await checkHlsPlaylist(servers, videoAudioUUID, hlsOnly, [ DEFAULT_AUDIO_RESOLUTION, 360, 240 ]) + await checkHlsPlaylist({ + servers, + videoUUID: videoAudioUUID, + hlsOnly, + resolutions: [ DEFAULT_AUDIO_RESOLUTION, 360, 240 ], + objectStorageBaseUrl + }) }) it('Should update the video', async function () { @@ -142,7 +171,7 @@ describe('Test HLS videos', function () { await waitJobs(servers) - await checkHlsPlaylist(servers, videoUUID, hlsOnly) + await checkHlsPlaylist({ servers, videoUUID, hlsOnly, objectStorageBaseUrl }) }) it('Should delete videos', async function () { @@ -229,6 +258,22 @@ describe('Test HLS videos', function () { runTestSuite(true) }) + describe('With object storage enabled', function () { + if (areObjectStorageTestsDisabled()) return + + before(async function () { + this.timeout(120000) + + const configOverride = ObjectStorageCommand.getDefaultConfig() + await ObjectStorageCommand.prepareDefaultBuckets() + + await servers[0].kill() + await servers[0].run(configOverride) + }) + + runTestSuite(true, ObjectStorageCommand.getPlaylistBaseUrl()) + }) + after(async function () { await cleanupTests(servers) }) diff --git a/server/tests/cli/create-import-video-file-job.ts b/server/tests/cli/create-import-video-file-job.ts index bddcff5e705..9f1b57a2e04 100644 --- a/server/tests/cli/create-import-video-file-job.ts +++ b/server/tests/cli/create-import-video-file-job.ts @@ -2,8 +2,19 @@ import 'mocha' import * as chai from 'chai' -import { cleanupTests, createMultipleServers, doubleFollow, PeerTubeServer, setAccessTokensToServers, waitJobs } from '@shared/extra-utils' -import { VideoFile } from '@shared/models' +import { + areObjectStorageTestsDisabled, + cleanupTests, + createMultipleServers, + doubleFollow, + expectStartWith, + makeRawRequest, + ObjectStorageCommand, + PeerTubeServer, + setAccessTokensToServers, + waitJobs +} from '@shared/extra-utils' +import { HttpStatusCode, VideoDetails, VideoFile } from '@shared/models' const expect = chai.expect @@ -17,22 +28,35 @@ function assertVideoProperties (video: VideoFile, resolution: number, extname: s if (size) expect(video.size).to.equal(size) } -describe('Test create import video jobs', function () { - this.timeout(60000) +async function checkFiles (video: VideoDetails, objectStorage: boolean) { + for (const file of video.files) { + if (objectStorage) expectStartWith(file.fileUrl, ObjectStorageCommand.getWebTorrentBaseUrl()) - let servers: PeerTubeServer[] = [] + await makeRawRequest(file.fileUrl, HttpStatusCode.OK_200) + } +} + +function runTests (objectStorage: boolean) { let video1UUID: string let video2UUID: string + let servers: PeerTubeServer[] = [] + before(async function () { this.timeout(90000) + const config = objectStorage + ? ObjectStorageCommand.getDefaultConfig() + : {} + // Run server 2 to have transcoding enabled - servers = await createMultipleServers(2) + servers = await createMultipleServers(2, config) await setAccessTokensToServers(servers) await doubleFollow(servers[0], servers[1]) + if (objectStorage) await ObjectStorageCommand.prepareDefaultBuckets() + // Upload two videos for our needs { const { uuid } = await servers[0].videos.upload({ attributes: { name: 'video1' } }) @@ -44,7 +68,6 @@ describe('Test create import video jobs', function () { video2UUID = uuid } - // Transcoding await waitJobs(servers) }) @@ -65,6 +88,8 @@ describe('Test create import video jobs', function () { const [ originalVideo, transcodedVideo ] = videoDetails.files assertVideoProperties(originalVideo, 720, 'webm', 218910) assertVideoProperties(transcodedVideo, 480, 'webm', 69217) + + await checkFiles(videoDetails, objectStorage) } }) @@ -87,6 +112,8 @@ describe('Test create import video jobs', function () { assertVideoProperties(transcodedVideo420, 480, 'mp4') assertVideoProperties(transcodedVideo320, 360, 'mp4') assertVideoProperties(transcodedVideo240, 240, 'mp4') + + await checkFiles(videoDetails, objectStorage) } }) @@ -107,10 +134,25 @@ describe('Test create import video jobs', function () { const [ video720, video480 ] = videoDetails.files assertVideoProperties(video720, 720, 'webm', 942961) assertVideoProperties(video480, 480, 'webm', 69217) + + await checkFiles(videoDetails, objectStorage) } }) after(async function () { await cleanupTests(servers) }) +} + +describe('Test create import video jobs', function () { + + describe('On filesystem', function () { + runTests(false) + }) + + describe('On object storage', function () { + if (areObjectStorageTestsDisabled()) return + + runTests(true) + }) }) diff --git a/server/tests/cli/create-transcoding-job.ts b/server/tests/cli/create-transcoding-job.ts index df787ccdcab..3313a492fdf 100644 --- a/server/tests/cli/create-transcoding-job.ts +++ b/server/tests/cli/create-transcoding-job.ts @@ -2,10 +2,15 @@ import 'mocha' import * as chai from 'chai' +import { HttpStatusCode, VideoFile } from '@shared/models' import { + areObjectStorageTestsDisabled, cleanupTests, createMultipleServers, doubleFollow, + expectStartWith, + makeRawRequest, + ObjectStorageCommand, PeerTubeServer, setAccessTokensToServers, waitJobs @@ -13,39 +18,39 @@ import { const expect = chai.expect -describe('Test create transcoding jobs', function () { - let servers: PeerTubeServer[] = [] - const videosUUID: string[] = [] +async function checkFilesInObjectStorage (files: VideoFile[], type: 'webtorrent' | 'playlist') { + for (const file of files) { + const shouldStartWith = type === 'webtorrent' + ? ObjectStorageCommand.getWebTorrentBaseUrl() + : ObjectStorageCommand.getPlaylistBaseUrl() - const config = { - transcoding: { - enabled: false, - resolutions: { - '240p': true, - '360p': true, - '480p': true, - '720p': true, - '1080p': true, - '1440p': true, - '2160p': true - }, - hls: { - enabled: false - } - } + expectStartWith(file.fileUrl, shouldStartWith) + + await makeRawRequest(file.fileUrl, HttpStatusCode.OK_200) } +} + +function runTests (objectStorage: boolean) { + let servers: PeerTubeServer[] = [] + const videosUUID: string[] = [] before(async function () { this.timeout(60000) + const config = objectStorage + ? ObjectStorageCommand.getDefaultConfig() + : {} + // Run server 2 to have transcoding enabled - servers = await createMultipleServers(2) + servers = await createMultipleServers(2, config) await setAccessTokensToServers(servers) - await servers[0].config.updateCustomSubConfig({ newConfig: config }) + await servers[0].config.disableTranscoding() await doubleFollow(servers[0], servers[1]) + if (objectStorage) await ObjectStorageCommand.prepareDefaultBuckets() + for (let i = 1; i <= 5; i++) { const { uuid } = await servers[0].videos.upload({ attributes: { name: 'video' + i } }) videosUUID.push(uuid) @@ -81,27 +86,29 @@ describe('Test create transcoding jobs', function () { let infoHashes: { [id: number]: string } for (const video of data) { - const videoDetail = await server.videos.get({ id: video.uuid }) + const videoDetails = await server.videos.get({ id: video.uuid }) if (video.uuid === videosUUID[1]) { - expect(videoDetail.files).to.have.lengthOf(4) - expect(videoDetail.streamingPlaylists).to.have.lengthOf(0) + expect(videoDetails.files).to.have.lengthOf(4) + expect(videoDetails.streamingPlaylists).to.have.lengthOf(0) + + if (objectStorage) await checkFilesInObjectStorage(videoDetails.files, 'webtorrent') if (!infoHashes) { infoHashes = {} - for (const file of videoDetail.files) { + for (const file of videoDetails.files) { infoHashes[file.resolution.id.toString()] = file.magnetUri } } else { for (const resolution of Object.keys(infoHashes)) { - const file = videoDetail.files.find(f => f.resolution.id.toString() === resolution) + const file = videoDetails.files.find(f => f.resolution.id.toString() === resolution) expect(file.magnetUri).to.equal(infoHashes[resolution]) } } } else { - expect(videoDetail.files).to.have.lengthOf(1) - expect(videoDetail.streamingPlaylists).to.have.lengthOf(0) + expect(videoDetails.files).to.have.lengthOf(1) + expect(videoDetails.streamingPlaylists).to.have.lengthOf(0) } } } @@ -125,6 +132,8 @@ describe('Test create transcoding jobs', function () { expect(videoDetails.files[1].resolution.id).to.equal(480) expect(videoDetails.streamingPlaylists).to.have.lengthOf(0) + + if (objectStorage) await checkFilesInObjectStorage(videoDetails.files, 'webtorrent') } }) @@ -139,11 +148,15 @@ describe('Test create transcoding jobs', function () { const videoDetails = await server.videos.get({ id: videosUUID[2] }) expect(videoDetails.files).to.have.lengthOf(1) + if (objectStorage) await checkFilesInObjectStorage(videoDetails.files, 'webtorrent') + expect(videoDetails.streamingPlaylists).to.have.lengthOf(1) const files = videoDetails.streamingPlaylists[0].files expect(files).to.have.lengthOf(1) expect(files[0].resolution.id).to.equal(480) + + if (objectStorage) await checkFilesInObjectStorage(files, 'playlist') } }) @@ -160,6 +173,8 @@ describe('Test create transcoding jobs', function () { const files = videoDetails.streamingPlaylists[0].files expect(files).to.have.lengthOf(1) expect(files[0].resolution.id).to.equal(480) + + if (objectStorage) await checkFilesInObjectStorage(files, 'playlist') } }) @@ -178,15 +193,15 @@ describe('Test create transcoding jobs', function () { const files = videoDetails.streamingPlaylists[0].files expect(files).to.have.lengthOf(4) + + if (objectStorage) await checkFilesInObjectStorage(files, 'playlist') } }) it('Should optimize the video file and generate HLS videos if enabled in config', async function () { this.timeout(120000) - config.transcoding.hls.enabled = true - await servers[0].config.updateCustomSubConfig({ newConfig: config }) - + await servers[0].config.enableTranscoding() await servers[0].cli.execWithEnv(`npm run create-transcoding-job -- -v ${videosUUID[4]}`) await waitJobs(servers) @@ -197,10 +212,28 @@ describe('Test create transcoding jobs', function () { expect(videoDetails.files).to.have.lengthOf(4) expect(videoDetails.streamingPlaylists).to.have.lengthOf(1) expect(videoDetails.streamingPlaylists[0].files).to.have.lengthOf(4) + + if (objectStorage) { + await checkFilesInObjectStorage(videoDetails.files, 'webtorrent') + await checkFilesInObjectStorage(videoDetails.streamingPlaylists[0].files, 'playlist') + } } }) after(async function () { await cleanupTests(servers) }) +} + +describe('Test create transcoding jobs', function () { + + describe('On filesystem', function () { + runTests(false) + }) + + describe('On object storage', function () { + if (areObjectStorageTestsDisabled()) return + + runTests(true) + }) }) diff --git a/server/tests/helpers/request.ts b/server/tests/helpers/request.ts index 7f7873df349..c9a2eb8310e 100644 --- a/server/tests/helpers/request.ts +++ b/server/tests/helpers/request.ts @@ -13,7 +13,7 @@ describe('Request helpers', function () { it('Should throw an error when the bytes limit is exceeded for request', async function () { try { - await doRequest(FIXTURE_URLS.video4K, { bodyKBLimit: 3 }) + await doRequest(FIXTURE_URLS.file4K, { bodyKBLimit: 3 }) } catch { return } @@ -23,7 +23,7 @@ describe('Request helpers', function () { it('Should throw an error when the bytes limit is exceeded for request and save file', async function () { try { - await doRequestAndSaveToFile(FIXTURE_URLS.video4K, destPath1, { bodyKBLimit: 3 }) + await doRequestAndSaveToFile(FIXTURE_URLS.file4K, destPath1, { bodyKBLimit: 3 }) } catch { await wait(500) @@ -35,8 +35,8 @@ describe('Request helpers', function () { }) it('Should succeed if the file is below the limit', async function () { - await doRequest(FIXTURE_URLS.video4K, { bodyKBLimit: 5 }) - await doRequestAndSaveToFile(FIXTURE_URLS.video4K, destPath2, { bodyKBLimit: 5 }) + await doRequest(FIXTURE_URLS.file4K, { bodyKBLimit: 5 }) + await doRequestAndSaveToFile(FIXTURE_URLS.file4K, destPath2, { bodyKBLimit: 5 }) expect(await pathExists(destPath2)).to.be.true }) diff --git a/shared/extra-utils/miscs/tests.ts b/shared/extra-utils/miscs/tests.ts index 3dfb2487edf..dd86041fef9 100644 --- a/shared/extra-utils/miscs/tests.ts +++ b/shared/extra-utils/miscs/tests.ts @@ -28,7 +28,9 @@ const FIXTURE_URLS = { badVideo: 'https://download.cpy.re/peertube/bad_video.mp4', goodVideo: 'https://download.cpy.re/peertube/good_video.mp4', - video4K: 'https://download.cpy.re/peertube/4k_file.txt' + goodVideo720: 'https://download.cpy.re/peertube/good_video_720.mp4', + + file4K: 'https://download.cpy.re/peertube/4k_file.txt' } function parallelTests () { @@ -42,7 +44,15 @@ function isGithubCI () { function areHttpImportTestsDisabled () { const disabled = process.env.DISABLE_HTTP_IMPORT_TESTS === 'true' - if (disabled) console.log('Import tests are disabled') + if (disabled) console.log('DISABLE_HTTP_IMPORT_TESTS env set to "true" so import tests are disabled') + + return disabled +} + +function areObjectStorageTestsDisabled () { + const disabled = process.env.ENABLE_OBJECT_STORAGE_TESTS !== 'true' + + if (disabled) console.log('ENABLE_OBJECT_STORAGE_TESTS env is not set to "true" so object storage tests are disabled') return disabled } @@ -89,6 +99,7 @@ export { buildAbsoluteFixturePath, getFileSize, buildRequestStub, + areObjectStorageTestsDisabled, wait, root } diff --git a/shared/extra-utils/mock-servers/mock-object-storage.ts b/shared/extra-utils/mock-servers/mock-object-storage.ts index a6a52d87863..19ea7c87c03 100644 --- a/shared/extra-utils/mock-servers/mock-object-storage.ts +++ b/shared/extra-utils/mock-servers/mock-object-storage.ts @@ -3,8 +3,7 @@ import got, { RequestError } from 'got' import { Server } from 'http' import { pipeline } from 'stream' import { randomInt } from '@shared/core-utils' -import { HttpStatusCode } from '@shared/models' -import { makePostBodyRequest } from '../requests' +import { ObjectStorageCommand } from '../server' export class MockObjectStorage { private server: Server @@ -14,7 +13,7 @@ export class MockObjectStorage { const app = express() app.get('/:bucketName/:path(*)', (req: express.Request, res: express.Response, next: express.NextFunction) => { - const url = `http://${req.params.bucketName}.${this.getEndpointHost()}/${req.params.path}` + const url = `http://${req.params.bucketName}.${ObjectStorageCommand.getEndpointHost()}/${req.params.path}` if (process.env.DEBUG) { console.log('Receiving request on mocked server %s.', req.url) @@ -37,41 +36,6 @@ export class MockObjectStorage { }) } - getCrendentialsConfig () { - return { - access_key_id: 'AKIAIOSFODNN7EXAMPLE', - secret_access_key: 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY' - } - } - - getEndpointHost () { - return 'localhost:9444' - } - - getRegion () { - return 'us-east-1' - } - - async createBucket (name: string) { - await makePostBodyRequest({ - url: this.getEndpointHost(), - path: '/ui/' + name + '?delete', - expectedStatus: HttpStatusCode.TEMPORARY_REDIRECT_307 - }) - - await makePostBodyRequest({ - url: this.getEndpointHost(), - path: '/ui/' + name + '?create', - expectedStatus: HttpStatusCode.TEMPORARY_REDIRECT_307 - }) - - await makePostBodyRequest({ - url: this.getEndpointHost(), - path: '/ui/' + name + '?make-public', - expectedStatus: HttpStatusCode.TEMPORARY_REDIRECT_307 - }) - } - terminate () { if (this.server) this.server.close() } diff --git a/shared/extra-utils/requests/requests.ts b/shared/extra-utils/requests/requests.ts index 70f7902222d..e3ecd1af246 100644 --- a/shared/extra-utils/requests/requests.ts +++ b/shared/extra-utils/requests/requests.ts @@ -121,6 +121,20 @@ function unwrapText (test: request.Test): Promise { return test.then(res => res.text) } +function unwrapBodyOrDecodeToJSON (test: request.Test): Promise { + return test.then(res => { + if (res.body instanceof Buffer) { + return JSON.parse(new TextDecoder().decode(res.body)) + } + + return res.body + }) +} + +function unwrapTextOrDecode (test: request.Test): Promise { + return test.then(res => res.text || new TextDecoder().decode(res.body)) +} + // --------------------------------------------------------------------------- export { @@ -134,6 +148,8 @@ export { makeRawRequest, makeActivityPubGetRequest, unwrapBody, + unwrapTextOrDecode, + unwrapBodyOrDecodeToJSON, unwrapText } diff --git a/shared/extra-utils/server/config-command.ts b/shared/extra-utils/server/config-command.ts index 11148aa4665..51d04fa6389 100644 --- a/shared/extra-utils/server/config-command.ts +++ b/shared/extra-utils/server/config-command.ts @@ -18,6 +18,70 @@ export class ConfigCommand extends AbstractCommand { } } + enableImports () { + return this.updateExistingSubConfig({ + newConfig: { + import: { + videos: { + http: { + enabled: true + }, + + torrent: { + enabled: true + } + } + } + } + }) + } + + enableLive (options: { + allowReplay?: boolean + transcoding?: boolean + } = {}) { + return this.updateExistingSubConfig({ + newConfig: { + live: { + enabled: true, + allowReplay: options.allowReplay ?? true, + transcoding: { + enabled: options.transcoding ?? true, + resolutions: ConfigCommand.getCustomConfigResolutions(true) + } + } + } + }) + } + + disableTranscoding () { + return this.updateExistingSubConfig({ + newConfig: { + transcoding: { + enabled: false + } + } + }) + } + + enableTranscoding (webtorrent = true, hls = true) { + return this.updateExistingSubConfig({ + newConfig: { + transcoding: { + enabled: true, + resolutions: ConfigCommand.getCustomConfigResolutions(true), + + webtorrent: { + enabled: webtorrent + }, + hls: { + enabled: hls + } + } + } + }) + } + getConfig (options: OverrideCommandOptions = {}) { const path = '/api/v1/config' @@ -81,6 +145,14 @@ export class ConfigCommand extends AbstractCommand { }) } + async updateExistingSubConfig (options: OverrideCommandOptions & { + newConfig: DeepPartial + }) { + const existing = await this.getCustomConfig(options) + + return this.updateCustomConfig({ ...options, newCustomConfig: merge({}, existing, options.newConfig) }) + } + updateCustomSubConfig (options: OverrideCommandOptions & { newConfig: DeepPartial }) { diff --git a/shared/extra-utils/server/index.ts b/shared/extra-utils/server/index.ts index 9055dfc573a..92ff7a0f9b3 100644 --- a/shared/extra-utils/server/index.ts +++ b/shared/extra-utils/server/index.ts @@ -6,6 +6,7 @@ export * from './follows-command' export * from './follows' export * from './jobs' export * from './jobs-command' +export * from './object-storage-command' export * from './plugins-command' export * from './plugins' export * from './redundancy-command' diff --git a/shared/extra-utils/server/jobs-command.ts b/shared/extra-utils/server/jobs-command.ts index c4eb12dc252..91771c17600 100644 --- a/shared/extra-utils/server/jobs-command.ts +++ b/shared/extra-utils/server/jobs-command.ts @@ -5,6 +5,16 @@ import { AbstractCommand, OverrideCommandOptions } from '../shared' export class JobsCommand extends AbstractCommand { + async getLatest (options: OverrideCommandOptions & { + jobType: JobType + }) { + const { data } = await this.getJobsList({ ...options, start: 0, count: 1, sort: '-createdAt' }) + + if (data.length === 0) return undefined + + return data[0] + } + getJobsList (options: OverrideCommandOptions & { state?: JobState jobType?: JobType diff --git a/shared/extra-utils/server/jobs.ts b/shared/extra-utils/server/jobs.ts index 64a0353eba5..27104bfdfbf 100644 --- a/shared/extra-utils/server/jobs.ts +++ b/shared/extra-utils/server/jobs.ts @@ -3,7 +3,7 @@ import { JobState } from '../../models' import { wait } from '../miscs' import { PeerTubeServer } from './server' -async function waitJobs (serversArg: PeerTubeServer[] | PeerTubeServer) { +async function waitJobs (serversArg: PeerTubeServer[] | PeerTubeServer, skipDelayed = false) { const pendingJobWait = process.env.NODE_PENDING_JOB_WAIT ? parseInt(process.env.NODE_PENDING_JOB_WAIT, 10) : 250 @@ -13,7 +13,9 @@ async function waitJobs (serversArg: PeerTubeServer[] | PeerTubeServer) { if (Array.isArray(serversArg) === false) servers = [ serversArg as PeerTubeServer ] else servers = serversArg as PeerTubeServer[] - const states: JobState[] = [ 'waiting', 'active', 'delayed' ] + const states: JobState[] = [ 'waiting', 'active' ] + if (!skipDelayed) states.push('delayed') + const repeatableJobs = [ 'videos-views', 'activitypub-cleaner' ] let pendingRequests: boolean diff --git a/shared/extra-utils/server/object-storage-command.ts b/shared/extra-utils/server/object-storage-command.ts new file mode 100644 index 00000000000..b4de8f4cbbb --- /dev/null +++ b/shared/extra-utils/server/object-storage-command.ts @@ -0,0 +1,77 @@ + +import { HttpStatusCode } from '@shared/models' +import { makePostBodyRequest } from '../requests' +import { AbstractCommand } from '../shared' + +export class ObjectStorageCommand extends AbstractCommand { + static readonly DEFAULT_PLAYLIST_BUCKET = 'streaming-playlists' + static readonly DEFAULT_WEBTORRENT_BUCKET = 'videos' + + static getDefaultConfig () { + return { + object_storage: { + enabled: true, + endpoint: 'http://' + this.getEndpointHost(), + region: this.getRegion(), + + credentials: this.getCredentialsConfig(), + + streaming_playlists: { + bucket_name: this.DEFAULT_PLAYLIST_BUCKET + }, + + videos: { + bucket_name: this.DEFAULT_WEBTORRENT_BUCKET + } + } + } + } + + static getCredentialsConfig () { + return { + access_key_id: 'AKIAIOSFODNN7EXAMPLE', + secret_access_key: 'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY' + } + } + + static getEndpointHost () { + return 'localhost:9444' + } + + static getRegion () { + return 'us-east-1' + } + + static getWebTorrentBaseUrl () { + return `http://${this.DEFAULT_WEBTORRENT_BUCKET}.${this.getEndpointHost()}/` + } + + static getPlaylistBaseUrl () { + return `http://${this.DEFAULT_PLAYLIST_BUCKET}.${this.getEndpointHost()}/` + } + + static async prepareDefaultBuckets () { + await this.createBucket(this.DEFAULT_PLAYLIST_BUCKET) + await this.createBucket(this.DEFAULT_WEBTORRENT_BUCKET) + } + + static async createBucket (name: string) { + await makePostBodyRequest({ + url: this.getEndpointHost(), + path: '/ui/' + name + '?delete', + expectedStatus: HttpStatusCode.TEMPORARY_REDIRECT_307 + }) + + await makePostBodyRequest({ + url: this.getEndpointHost(), + path: '/ui/' + name + '?create', + expectedStatus: HttpStatusCode.TEMPORARY_REDIRECT_307 + }) + + await makePostBodyRequest({ + url: this.getEndpointHost(), + path: '/ui/' + name + '?make-public', + expectedStatus: HttpStatusCode.TEMPORARY_REDIRECT_307 + }) + } +} diff --git a/shared/extra-utils/server/server.ts b/shared/extra-utils/server/server.ts index 3c335b8e448..bc5e1cd5fa1 100644 --- a/shared/extra-utils/server/server.ts +++ b/shared/extra-utils/server/server.ts @@ -38,11 +38,13 @@ import { PluginsCommand } from './plugins-command' import { RedundancyCommand } from './redundancy-command' import { ServersCommand } from './servers-command' import { StatsCommand } from './stats-command' +import { ObjectStorageCommand } from './object-storage-command' export type RunServerOptions = { hideLogs?: boolean nodeArgs?: string[] peertubeArgs?: string[] + env?: { [ id: string ]: string } } export class PeerTubeServer { @@ -121,6 +123,7 @@ export class PeerTubeServer { servers?: ServersCommand login?: LoginCommand users?: UsersCommand + objectStorage?: ObjectStorageCommand videos?: VideosCommand constructor (options: { serverNumber: number } | { url: string }) { @@ -202,6 +205,10 @@ export class PeerTubeServer { env['NODE_APP_INSTANCE'] = this.internalServerNumber.toString() env['NODE_CONFIG'] = JSON.stringify(configOverride) + if (options.env) { + Object.assign(env, options.env) + } + const forkOptions = { silent: true, env, @@ -209,10 +216,17 @@ export class PeerTubeServer { execArgv: options.nodeArgs || [] } - return new Promise(res => { + return new Promise((res, rej) => { const self = this this.app = fork(join(root(), 'dist', 'server.js'), options.peertubeArgs || [], forkOptions) + + const onExit = function () { + return rej(new Error('Process exited')) + } + + this.app.on('exit', onExit) + this.app.stdout.on('data', function onStdout (data) { let dontContinue = false @@ -241,6 +255,7 @@ export class PeerTubeServer { console.log(data.toString()) } else { self.app.stdout.removeListener('data', onStdout) + self.app.removeListener('exit', onExit) } process.on('exit', () => { @@ -365,5 +380,6 @@ export class PeerTubeServer { this.login = new LoginCommand(this) this.users = new UsersCommand(this) this.videos = new VideosCommand(this) + this.objectStorage = new ObjectStorageCommand(this) } } diff --git a/shared/extra-utils/videos/live.ts b/shared/extra-utils/videos/live.ts index 9a6df07a87f..29f99ed6d0b 100644 --- a/shared/extra-utils/videos/live.ts +++ b/shared/extra-utils/videos/live.ts @@ -89,6 +89,12 @@ async function waitUntilLivePublishedOnAllServers (servers: PeerTubeServer[], vi } } +async function waitUntilLiveSavedOnAllServers (servers: PeerTubeServer[], videoId: string) { + for (const server of servers) { + await server.live.waitUntilSaved({ videoId }) + } +} + async function checkLiveCleanupAfterSave (server: PeerTubeServer, videoUUID: string, resolutions: number[] = []) { const basePath = server.servers.buildDirectory('streaming-playlists') const hlsPath = join(basePath, 'hls', videoUUID) @@ -126,5 +132,6 @@ export { testFfmpegStreamError, stopFfmpeg, waitUntilLivePublishedOnAllServers, + waitUntilLiveSavedOnAllServers, checkLiveCleanupAfterSave } diff --git a/shared/extra-utils/videos/streaming-playlists-command.ts b/shared/extra-utils/videos/streaming-playlists-command.ts index 9662685da1a..5d40d35cb9e 100644 --- a/shared/extra-utils/videos/streaming-playlists-command.ts +++ b/shared/extra-utils/videos/streaming-playlists-command.ts @@ -1,5 +1,5 @@ import { HttpStatusCode } from '@shared/models' -import { unwrapBody, unwrapText } from '../requests' +import { unwrapBody, unwrapTextOrDecode, unwrapBodyOrDecodeToJSON } from '../requests' import { AbstractCommand, OverrideCommandOptions } from '../shared' export class StreamingPlaylistsCommand extends AbstractCommand { @@ -7,7 +7,7 @@ export class StreamingPlaylistsCommand extends AbstractCommand { get (options: OverrideCommandOptions & { url: string }) { - return unwrapText(this.getRawRequest({ + return unwrapTextOrDecode(this.getRawRequest({ ...options, url: options.url, @@ -33,7 +33,7 @@ export class StreamingPlaylistsCommand extends AbstractCommand { getSegmentSha256 (options: OverrideCommandOptions & { url: string }) { - return unwrapBody<{ [ id: string ]: string }>(this.getRawRequest({ + return unwrapBodyOrDecodeToJSON<{ [ id: string ]: string }>(this.getRawRequest({ ...options, url: options.url, diff --git a/shared/extra-utils/videos/streaming-playlists.ts b/shared/extra-utils/videos/streaming-playlists.ts index a224b8f5f67..6671e3fa6bc 100644 --- a/shared/extra-utils/videos/streaming-playlists.ts +++ b/shared/extra-utils/videos/streaming-playlists.ts @@ -9,17 +9,16 @@ async function checkSegmentHash (options: { server: PeerTubeServer baseUrlPlaylist: string baseUrlSegment: string - videoUUID: string resolution: number hlsPlaylist: VideoStreamingPlaylist }) { - const { server, baseUrlPlaylist, baseUrlSegment, videoUUID, resolution, hlsPlaylist } = options + const { server, baseUrlPlaylist, baseUrlSegment, resolution, hlsPlaylist } = options const command = server.streamingPlaylists const file = hlsPlaylist.files.find(f => f.resolution.id === resolution) const videoName = basename(file.fileUrl) - const playlist = await command.get({ url: `${baseUrlPlaylist}/${videoUUID}/${removeFragmentedMP4Ext(videoName)}.m3u8` }) + const playlist = await command.get({ url: `${baseUrlPlaylist}/${removeFragmentedMP4Ext(videoName)}.m3u8` }) const matches = /#EXT-X-BYTERANGE:(\d+)@(\d+)/.exec(playlist) @@ -28,7 +27,7 @@ async function checkSegmentHash (options: { const range = `${offset}-${offset + length - 1}` const segmentBody = await command.getSegment({ - url: `${baseUrlSegment}/${videoUUID}/${videoName}`, + url: `${baseUrlSegment}/${videoName}`, expectedStatus: HttpStatusCode.PARTIAL_CONTENT_206, range: `bytes=${range}` }) diff --git a/shared/models/server/job.model.ts b/shared/models/server/job.model.ts index 973cacef3b8..ff96283a4f5 100644 --- a/shared/models/server/job.model.ts +++ b/shared/models/server/job.model.ts @@ -140,4 +140,5 @@ export interface ActorKeysPayload { export interface MoveObjectStoragePayload { videoUUID: string + isNewVideo: boolean } diff --git a/shared/models/videos/video-storage.enum.ts b/shared/models/videos/video-storage.enum.ts index d9f52ff931b..7c6690db2a6 100644 --- a/shared/models/videos/video-storage.enum.ts +++ b/shared/models/videos/video-storage.enum.ts @@ -1,4 +1,4 @@ export const enum VideoStorage { - LOCAL, + FILE_SYSTEM, OBJECT_STORAGE, } diff --git a/support/docker/production/config/custom-environment-variables.yaml b/support/docker/production/config/custom-environment-variables.yaml index ce0f89d7b8a..1b474582a94 100644 --- a/support/docker/production/config/custom-environment-variables.yaml +++ b/support/docker/production/config/custom-environment-variables.yaml @@ -45,6 +45,29 @@ smtp: __format: "json" from_address: "PEERTUBE_SMTP_FROM" +object_storage: + enabled: + __name: "PEERTUBE_OBJECT_STORAGE_ENABLED" + __format: "json" + + endpoint: "PEERTUBE_OBJECT_STORAGE_ENDPOINT" + + region: "PEERTUBE_OBJECT_STORAGE_REGION" + + max_upload_part: + __name: "PEERTUBE_OBJECT_STORAGE_MAX_UPLOAD_PART" + __format: "json" + + streaming_playlists: + bucket_name: "PEERTUBE_OBJECT_STORAGE_STREAMING_PLAYLISTS_BUCKET_NAME" + prefix: "PEERTUBE_OBJECT_STORAGE_STREAMING_PLAYLISTS_PREFIX" + base_url: "PEERTUBE_OBJECT_STORAGE_STREAMING_PLAYLISTS_BASE_URL" + + videos: + bucket_name: "PEERTUBE_OBJECT_STORAGE_VIDEOS_BUCKET_NAME" + prefix: "PEERTUBE_OBJECT_STORAGE_VIDEOS_PREFIX" + base_url: "PEERTUBE_OBJECT_STORAGE_VIDEOS_BASE_URL" + log: level: "PEERTUBE_LOG_LEVEL" log_ping_requests: