Skip to content

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

Add `withFile` plugin helper

Chocobozzz13b3ca19916c
diff --git a/packages/tests/fixtures/peertube-plugin-test-four/main.js b/packages/tests/fixtures/peertube-plugin-test-four/main.js
index 1fe272431b..01b1651f1a 100644
--- a/packages/tests/fixtures/peertube-plugin-test-four/main.js
+++ b/packages/tests/fixtures/peertube-plugin-test-four/main.js
@@ -142,6 +142,30 @@ async function register ({
return res.json(result)
})
+ router.get('/with-file/:videoId/:fileId', async (req, res) => {
+ const { existsSync } = require('fs')
+
+ try {
+ const result = await peertubeHelpers.videos.withFile(
+ { videoId: req.params.videoId, videoFileId: parseInt(req.params.fileId) },
+ async path => {
+ const probe = await peertubeHelpers.videos.ffprobe(path)
+
+ return {
+ path,
+ streamsLength: probe.streams.length,
+ existsDuringCallback: existsSync(path)
+ }
+ }
+ )
+
+ return res.json({ ...result, existsAfterCallback: existsSync(result.path) })
+ } catch (err) {
+ logger.error('Error in with-file.', { err })
+ return res.sendStatus(404)
+ }
+ })
+
router.post('/send-notification', async (req, res) => {
peertubeHelpers.socket.sendNotification(req.body.userId, {
type: 1,
diff --git a/packages/tests/src/plugins/plugin-helpers.ts b/packages/tests/src/plugins/plugin-helpers.ts
index 817dfc21b7..63dac2e63a 100644
--- a/packages/tests/src/plugins/plugin-helpers.ts
+++ b/packages/tests/src/plugins/plugin-helpers.ts
@@ -1,14 +1,17 @@
/* oxlint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/require-await */
import { HttpStatusCode, VideoPrivacy } from '@peertube/peertube-models'
+import { areMockObjectStorageTestsDisabled } from '@peertube/peertube-node-utils'
import {
cleanupTests,
ConfigCommand,
createMultipleServers,
+ createSingleServer,
doubleFollow,
makeGetRequest,
makePostBodyRequest,
makeRawRequest,
+ ObjectStorageCommand,
PeerTubeServer,
PluginsCommand,
setAccessTokensToServers,
@@ -363,6 +366,48 @@ describe('Test plugin helpers', function () {
}
})
+ it('Should provide a locked video file to the plugin (local storage)', async function () {
+ const { body: filesBody } = await makeGetRequest({
+ url: servers[0].url,
+ path: '/plugins/test-four/router/video-files/' + videoUUID,
+ expectedStatus: HttpStatusCode.OK_200
+ })
+
+ for (const file of [ ...filesBody.webVideo.videoFiles, ...filesBody.hls.videoFiles ]) {
+ const { body } = await makeGetRequest({
+ url: servers[0].url,
+ path: `/plugins/test-four/router/with-file/${videoUUID}/${file.id}`,
+ expectedStatus: HttpStatusCode.OK_200
+ })
+
+ expect(body.path).to.equal(file.path)
+ expect(body.streamsLength).to.equal(2)
+ expect(body.existsDuringCallback).to.be.true
+
+ // Local storage files are not cleaned up after the plugin used them
+ expect(body.existsAfterCallback).to.be.true
+ expect(await pathExists(body.path)).to.be.true
+ }
+ })
+
+ it('Should return 404 when the video file does not belong to the video', async function () {
+ const { uuid: otherUUID } = await servers[0].videos.quickUpload({ name: 'other video' })
+ await waitJobs(servers)
+
+ const { body: filesBody } = await makeGetRequest({
+ url: servers[0].url,
+ path: '/plugins/test-four/router/video-files/' + videoUUID,
+ expectedStatus: HttpStatusCode.OK_200
+ })
+ const fileId = filesBody.webVideo.videoFiles[0].id
+
+ await makeGetRequest({
+ url: servers[0].url,
+ path: `/plugins/test-four/router/with-file/${otherUUID}/${fileId}`,
+ expectedStatus: HttpStatusCode.NOT_FOUND_404
+ })
+ })
+
it('Should probe a file', async function () {
const { body } = await makeGetRequest({
url: servers[0].url,
@@ -437,3 +482,64 @@ describe('Test plugin helpers', function () {
await cleanupTests(servers)
})
})
+
+describe('Test plugin helpers videos.withFile with object storage', function () {
+ if (areMockObjectStorageTestsDisabled()) return
+
+ let server: PeerTubeServer
+ let videoUUID: string
+
+ const objectStorage = new ObjectStorageCommand()
+
+ before(async function () {
+ this.timeout(240000)
+
+ await objectStorage.prepareDefaultMockBuckets()
+
+ server = await createSingleServer(1, objectStorage.getDefaultMockConfig())
+ await setAccessTokensToServers([ server ])
+
+ await server.plugins.install({ path: PluginsCommand.getPluginTestPath('-four') })
+
+ await server.config.enableTranscoding({ webVideo: true, hls: true, resolutions: 'max' })
+
+ const res = await server.videos.quickUpload({ name: 'video1' })
+ videoUUID = res.uuid
+
+ await waitJobs([ server ])
+ })
+
+ it('Should provide a locked video file to the plugin, cleaning it up afterwards', async function () {
+ const { body: filesBody } = await makeGetRequest({
+ url: server.url,
+ path: '/plugins/test-four/router/video-files/' + videoUUID,
+ expectedStatus: HttpStatusCode.OK_200
+ })
+
+ // Object storage files do not have a local FS path
+ expect(filesBody.webVideo.videoFiles[0].path).to.be.null
+ expect(filesBody.hls.videoFiles[0].path).to.be.null
+
+ for (const file of [ ...filesBody.webVideo.videoFiles, ...filesBody.hls.videoFiles ]) {
+ const { body } = await makeGetRequest({
+ url: server.url,
+ path: `/plugins/test-four/router/with-file/${videoUUID}/${file.id}`,
+ expectedStatus: HttpStatusCode.OK_200
+ })
+
+ expect(body.path).to.be.a('string')
+ expect(body.streamsLength).to.equal(2)
+ expect(body.existsDuringCallback).to.be.true
+
+ // The file was downloaded from object storage to a tmp destination that must be cleaned up afterwards
+ expect(body.existsAfterCallback).to.be.false
+ expect(await pathExists(body.path)).to.be.false
+ }
+ })
+
+ after(async function () {
+ await objectStorage.cleanupMock()
+
+ await cleanupTests([ server ])
+ })
+})
diff --git a/packages/tests/src/shared/videos.ts b/packages/tests/src/shared/videos.ts
index 1c9b669712..cbe7e2699e 100644
--- a/packages/tests/src/shared/videos.ts
+++ b/packages/tests/src/shared/videos.ts
@@ -350,11 +350,13 @@ export async function checkVideoFilesWereRemoved (options: {
const existingFiles = await readdir(directoryPath)
for (const existingFile of existingFiles) {
for (const shouldNotExist of directories[directory]) {
- // Allow 500ms more for the file to be removed, because sometimes the file is still being removed when we check it
- await wait(1000)
+ if (existingFile === shouldNotExist) {
+ // Allow 1000ms more for the file to be removed, because sometimes the file is still being removed when we check it
+ await wait(1000)
- if (await pathExists(join(directoryPath, existingFile))) {
- expect(existingFile, `File ${existingFile} should not exist in ${directoryPath}`).to.not.equal(shouldNotExist)
+ if (await pathExists(join(directoryPath, existingFile))) {
+ expect(existingFile, `File ${existingFile} should not exist in ${directoryPath}`).to.not.equal(shouldNotExist)
+ }
}
}
}
diff --git a/server/core/lib/plugins/plugin-helpers-builder.ts b/server/core/lib/plugins/plugin-helpers-builder.ts
index eb35038561..6079231a44 100644
--- a/server/core/lib/plugins/plugin-helpers-builder.ts
+++ b/server/core/lib/plugins/plugin-helpers-builder.ts
@@ -1,5 +1,6 @@
import { ffprobePromise } from '@peertube/peertube-ffmpeg'
import { FileStorage, VideoBlacklistCreate } from '@peertube/peertube-models'
+import { Awaitable } from '@peertube/peertube-typescript-utils'
import { toCompleteUUID } from '@server/helpers/custom-validators/misc.js'
import { buildWinstonLogger, createLogger } from '@server/helpers/logger.js'
import { CONFIG } from '@server/initializers/config.js'
@@ -14,6 +15,7 @@ import { ServerBlocklistModel } from '@server/models/blocklist/server-blocklist.
import { ServerModel } from '@server/models/server/server.js'
import { UserModel } from '@server/models/user/user.js'
import { VideoBlacklistModel } from '@server/models/video/video-blacklist.js'
+import { VideoFileModel } from '@server/models/video/video-file.js'
import { VideoModel } from '@server/models/video/video.js'
import { MPlugin, MVideo, UserNotificationModelForApi } from '@server/types/models/index.js'
import { PeerTubeHelpers } from '@server/types/plugins/index.js'
@@ -115,11 +117,35 @@ function buildVideosHelpers (npmName: string) {
return ffprobePromise(path)
},
+ withFile: async <T>(
+ options: {
+ videoId: number | string
+ videoFileId: number
+ },
+ cb: (path: string) => Awaitable<T>
+ ) => {
+ const videoFile = await VideoFileModel.loadWithVideoOrPlaylist(options.videoFileId, toCompleteUUID(options.videoId))
+ if (!videoFile) throw new Error('Video file not found')
+
+ const video = videoFile.getVideo()
+
+ return logger.withContext([ npmName, video.uuid ], async () => {
+ const releaser = await VideoPathManager.Instance.lockFiles(video.uuid)
+
+ try {
+ return await VideoPathManager.Instance.makeAvailableVideoFile(videoFile, cb)
+ } finally {
+ releaser()
+ }
+ })
+ },
+
getFiles: async (id: number | string) => {
const video = await VideoModel.loadFull(id)
if (!video) return undefined
const webVideoFiles = (video.VideoFiles || []).map(f => ({
+ id: f.id,
path: f.storage === FileStorage.FILE_SYSTEM
? VideoPathManager.Instance.getFSVideoFileOutputPath(video, f)
: null,
@@ -135,6 +161,7 @@ function buildVideosHelpers (npmName: string) {
const hlsVideoFiles = hls
? (video.getHLSPlaylist().VideoFiles || []).map(f => {
return {
+ id: f.id,
path: f.storage === FileStorage.FILE_SYSTEM
? VideoPathManager.Instance.getFSVideoFileOutputPath(hls, f)
: null,
diff --git a/server/core/models/video/video-file.ts b/server/core/models/video/video-file.ts
index 15d1db3660..de76bc2eb0 100644
--- a/server/core/models/video/video-file.ts
+++ b/server/core/models/video/video-file.ts
@@ -310,7 +310,7 @@ export class VideoFileModel extends SequelizeModel<VideoFileModel> {
return VideoFileModel.scope(ScopeNames.WITH_VIDEO).findByPk<MVideoFileVideo>(id, { transaction })
}
- static loadWithVideoOrPlaylist (id: number, videoIdOrUUID: number | string) {
+ static loadWithVideoOrPlaylist (id: number, videoIdOrUUID: number | string): Promise<MVideoFileVideo | MVideoFileStreamingPlaylistVideo> {
const whereVideo = validator.default.isUUID(videoIdOrUUID + '')
? { uuid: videoIdOrUUID }
: { id: videoIdOrUUID }
diff --git a/server/core/types/plugins/register-server-option.model.ts b/server/core/types/plugins/register-server-option.model.ts
index 4127270ef7..59e705342a 100644
--- a/server/core/types/plugins/register-server-option.model.ts
+++ b/server/core/types/plugins/register-server-option.model.ts
@@ -72,9 +72,21 @@ export type PeerTubeHelpers = {
ffprobe: (path: string) => Promise<any>
+ // PeerTube >= 8.3
+ // Make a video file available on disk (downloading it from remote storage if needed) so it can be analyzed
+ // The video files of the video are locked until the promise returned by `cb` is resolved/rejected
+ withFile: <T>(
+ options: {
+ videoId: number | string
+ videoFileId: number
+ },
+ cb: (path: string) => Promise<T> | T
+ ) => Promise<T>
+
getFiles: (id: number | string) => Promise<{
webVideo: {
videoFiles: {
+ id: number
path: string // Could be null if using remote storage
url: string
resolution: number
@@ -85,6 +97,7 @@ export type PeerTubeHelpers = {
hls: {
videoFiles: {
+ id: number
path: string // Could be null if using remote storage
url: string
resolution: number