はじまりの大地

このコミットが含まれているのは:
2024-07-15 09:14:04 +09:00
コミット 6632905f32
3501個のファイルの変更1439465行の追加0行の削除
+112
ファイルの表示
@@ -0,0 +1,112 @@
import express from 'express'
import { blacklistVideo, unblacklistVideo } from '@server/lib/video-blacklist.js'
import { HttpStatusCode, UserRight, VideoBlacklistCreate } from '@peertube/peertube-models'
import { logger } from '../../../helpers/logger.js'
import { getFormattedObjects } from '../../../helpers/utils.js'
import { sequelizeTypescript } from '../../../initializers/database.js'
import {
asyncMiddleware,
authenticate,
blacklistSortValidator,
ensureUserHasRight,
openapiOperationDoc,
paginationValidator,
setBlacklistSort,
setDefaultPagination,
videosBlacklistAddValidator,
videosBlacklistFiltersValidator,
videosBlacklistRemoveValidator,
videosBlacklistUpdateValidator
} from '../../../middlewares/index.js'
import { VideoBlacklistModel } from '../../../models/video/video-blacklist.js'
const blacklistRouter = express.Router()
blacklistRouter.post('/:videoId/blacklist',
openapiOperationDoc({ operationId: 'addVideoBlock' }),
authenticate,
ensureUserHasRight(UserRight.MANAGE_VIDEO_BLACKLIST),
asyncMiddleware(videosBlacklistAddValidator),
asyncMiddleware(addVideoToBlacklistController)
)
blacklistRouter.get('/blacklist',
openapiOperationDoc({ operationId: 'getVideoBlocks' }),
authenticate,
ensureUserHasRight(UserRight.MANAGE_VIDEO_BLACKLIST),
paginationValidator,
blacklistSortValidator,
setBlacklistSort,
setDefaultPagination,
videosBlacklistFiltersValidator,
asyncMiddleware(listBlacklist)
)
blacklistRouter.put('/:videoId/blacklist',
authenticate,
ensureUserHasRight(UserRight.MANAGE_VIDEO_BLACKLIST),
asyncMiddleware(videosBlacklistUpdateValidator),
asyncMiddleware(updateVideoBlacklistController)
)
blacklistRouter.delete('/:videoId/blacklist',
openapiOperationDoc({ operationId: 'delVideoBlock' }),
authenticate,
ensureUserHasRight(UserRight.MANAGE_VIDEO_BLACKLIST),
asyncMiddleware(videosBlacklistRemoveValidator),
asyncMiddleware(removeVideoFromBlacklistController)
)
// ---------------------------------------------------------------------------
export {
blacklistRouter
}
// ---------------------------------------------------------------------------
async function addVideoToBlacklistController (req: express.Request, res: express.Response) {
const videoInstance = res.locals.videoAll
const body: VideoBlacklistCreate = req.body
await blacklistVideo(videoInstance, body)
logger.info('Video %s blacklisted.', videoInstance.uuid)
return res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
}
async function updateVideoBlacklistController (req: express.Request, res: express.Response) {
const videoBlacklist = res.locals.videoBlacklist
if (req.body.reason !== undefined) videoBlacklist.reason = req.body.reason
await sequelizeTypescript.transaction(t => {
return videoBlacklist.save({ transaction: t })
})
return res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
}
async function listBlacklist (req: express.Request, res: express.Response) {
const resultList = await VideoBlacklistModel.listForApi({
start: req.query.start,
count: req.query.count,
sort: req.query.sort,
search: req.query.search,
type: req.query.type
})
return res.json(getFormattedObjects(resultList.data, resultList.total))
}
async function removeVideoFromBlacklistController (req: express.Request, res: express.Response) {
const videoBlacklist = res.locals.videoBlacklist
const video = res.locals.videoAll
await unblacklistVideo(videoBlacklist, video)
logger.info('Video %s removed from blacklist.', video.uuid)
return res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
}
+116
ファイルの表示
@@ -0,0 +1,116 @@
import { HttpStatusCode, VideoCaptionGenerate } from '@peertube/peertube-models'
import { Hooks } from '@server/lib/plugins/hooks.js'
import { createLocalCaption, createTranscriptionTaskIfNeeded } from '@server/lib/video-captions.js'
import { VideoJobInfoModel } from '@server/models/video/video-job-info.js'
import express from 'express'
import { createReqFiles } from '../../../helpers/express-utils.js'
import { logger, loggerTagsFactory } from '../../../helpers/logger.js'
import { getFormattedObjects } from '../../../helpers/utils.js'
import { MIMETYPES } from '../../../initializers/constants.js'
import { sequelizeTypescript } from '../../../initializers/database.js'
import { federateVideoIfNeeded } from '../../../lib/activitypub/videos/index.js'
import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate } from '../../../middlewares/index.js'
import {
addVideoCaptionValidator,
deleteVideoCaptionValidator,
generateVideoCaptionValidator,
listVideoCaptionsValidator
} from '../../../middlewares/validators/index.js'
import { VideoCaptionModel } from '../../../models/video/video-caption.js'
const lTags = loggerTagsFactory('api', 'video-caption')
const reqVideoCaptionAdd = createReqFiles([ 'captionfile' ], MIMETYPES.VIDEO_CAPTIONS.MIMETYPE_EXT)
const videoCaptionsRouter = express.Router()
videoCaptionsRouter.post('/:videoId/captions/generate',
authenticate,
asyncMiddleware(generateVideoCaptionValidator),
asyncMiddleware(createGenerateVideoCaption)
)
videoCaptionsRouter.get('/:videoId/captions',
asyncMiddleware(listVideoCaptionsValidator),
asyncMiddleware(listVideoCaptions)
)
videoCaptionsRouter.put('/:videoId/captions/:captionLanguage',
authenticate,
reqVideoCaptionAdd,
asyncMiddleware(addVideoCaptionValidator),
asyncRetryTransactionMiddleware(createVideoCaption)
)
videoCaptionsRouter.delete('/:videoId/captions/:captionLanguage',
authenticate,
asyncMiddleware(deleteVideoCaptionValidator),
asyncRetryTransactionMiddleware(deleteVideoCaption)
)
// ---------------------------------------------------------------------------
export {
videoCaptionsRouter
}
// ---------------------------------------------------------------------------
async function createGenerateVideoCaption (req: express.Request, res: express.Response) {
const video = res.locals.videoAll
const body = req.body as VideoCaptionGenerate
if (body.forceTranscription === true) {
await VideoJobInfoModel.abortAllTasks(video.uuid, 'pendingTranscription')
}
await createTranscriptionTaskIfNeeded(video)
return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
}
async function listVideoCaptions (req: express.Request, res: express.Response) {
const data = await VideoCaptionModel.listVideoCaptions(res.locals.onlyVideo.id)
return res.json(getFormattedObjects(data, data.length))
}
async function createVideoCaption (req: express.Request, res: express.Response) {
const videoCaptionPhysicalFile: Express.Multer.File = req.files['captionfile'][0]
const video = res.locals.videoAll
const captionLanguage = req.params.captionLanguage
const videoCaption = await createLocalCaption({
video,
language: captionLanguage,
path: videoCaptionPhysicalFile.path,
automaticallyGenerated: false
})
await sequelizeTypescript.transaction(async t => {
await federateVideoIfNeeded(video, false, t)
})
Hooks.runAction('action:api.video-caption.created', { caption: videoCaption, req, res })
return res.status(HttpStatusCode.NO_CONTENT_204).end()
}
async function deleteVideoCaption (req: express.Request, res: express.Response) {
const video = res.locals.videoAll
const videoCaption = res.locals.videoCaption
await sequelizeTypescript.transaction(async t => {
await videoCaption.destroy({ transaction: t })
// Send video update
await federateVideoIfNeeded(video, false, t)
})
logger.info('Video caption %s of video %s deleted.', videoCaption.language, video.uuid, lTags(video.uuid))
Hooks.runAction('action:api.video-caption.deleted', { caption: videoCaption, req, res })
return res.type('json').status(HttpStatusCode.NO_CONTENT_204).end()
}
+51
ファイルの表示
@@ -0,0 +1,51 @@
import express from 'express'
import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate } from '../../../middlewares/index.js'
import { updateVideoChaptersValidator, videosCustomGetValidator } from '../../../middlewares/validators/index.js'
import { VideoChapterModel } from '@server/models/video/video-chapter.js'
import { HttpStatusCode, VideoChapterUpdate } from '@peertube/peertube-models'
import { sequelizeTypescript } from '@server/initializers/database.js'
import { retryTransactionWrapper } from '@server/helpers/database-utils.js'
import { federateVideoIfNeeded } from '@server/lib/activitypub/videos/federate.js'
import { replaceChapters } from '@server/lib/video-chapters.js'
const videoChaptersRouter = express.Router()
videoChaptersRouter.get('/:id/chapters',
asyncMiddleware(videosCustomGetValidator('only-video-and-blacklist')),
asyncMiddleware(listVideoChapters)
)
videoChaptersRouter.put('/:videoId/chapters',
authenticate,
asyncMiddleware(updateVideoChaptersValidator),
asyncRetryTransactionMiddleware(replaceVideoChapters)
)
// ---------------------------------------------------------------------------
export {
videoChaptersRouter
}
// ---------------------------------------------------------------------------
async function listVideoChapters (req: express.Request, res: express.Response) {
const chapters = await VideoChapterModel.listChaptersOfVideo(res.locals.onlyVideo.id)
return res.json({ chapters: chapters.map(c => c.toFormattedJSON()) })
}
async function replaceVideoChapters (req: express.Request, res: express.Response) {
const body = req.body as VideoChapterUpdate
const video = res.locals.videoAll
await retryTransactionWrapper(() => {
return sequelizeTypescript.transaction(async t => {
await replaceChapters({ video, chapters: body.chapters, transaction: t })
await federateVideoIfNeeded(video, false, t)
})
})
return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
}
+248
ファイルの表示
@@ -0,0 +1,248 @@
import { pick } from '@peertube/peertube-core-utils'
import {
HttpStatusCode,
ResultList,
ThreadsResultList,
UserRight,
VideoCommentCreate,
VideoCommentPolicy,
VideoCommentThreads
} from '@peertube/peertube-models'
import { getServerActor } from '@server/models/application/application.js'
import { MCommentFormattable } from '@server/types/models/index.js'
import express from 'express'
import { CommentAuditView, auditLoggerFactory, getAuditIdFromRes } from '../../../helpers/audit-logger.js'
import { getFormattedObjects } from '../../../helpers/utils.js'
import { Notifier } from '../../../lib/notifier/index.js'
import { Hooks } from '../../../lib/plugins/hooks.js'
import { approveComment, buildFormattedCommentTree, createLocalVideoComment, removeComment } from '../../../lib/video-comment.js'
import {
asyncMiddleware,
asyncRetryTransactionMiddleware,
authenticate,
ensureUserHasRight,
optionalAuthenticate,
paginationValidator,
setDefaultPagination,
setDefaultSort
} from '../../../middlewares/index.js'
import {
addVideoCommentReplyValidator,
addVideoCommentThreadValidator,
approveVideoCommentValidator,
listAllVideoCommentsForAdminValidator,
listVideoCommentThreadsValidator,
listVideoThreadCommentsValidator,
removeVideoCommentValidator,
videoCommentThreadsSortValidator,
videoCommentsValidator
} from '../../../middlewares/validators/index.js'
import { VideoCommentModel } from '../../../models/video/video-comment.js'
const auditLogger = auditLoggerFactory('comments')
const videoCommentRouter = express.Router()
videoCommentRouter.get('/:videoId/comment-threads',
paginationValidator,
videoCommentThreadsSortValidator,
setDefaultSort,
setDefaultPagination,
asyncMiddleware(listVideoCommentThreadsValidator),
optionalAuthenticate,
asyncMiddleware(listVideoThreads)
)
videoCommentRouter.get('/:videoId/comment-threads/:threadId',
asyncMiddleware(listVideoThreadCommentsValidator),
optionalAuthenticate,
asyncMiddleware(listVideoThreadComments)
)
videoCommentRouter.post('/:videoId/comment-threads',
authenticate,
asyncMiddleware(addVideoCommentThreadValidator),
asyncRetryTransactionMiddleware(addVideoCommentThread)
)
videoCommentRouter.post('/:videoId/comments/:commentId',
authenticate,
asyncMiddleware(addVideoCommentReplyValidator),
asyncRetryTransactionMiddleware(addVideoCommentReply)
)
videoCommentRouter.delete('/:videoId/comments/:commentId',
authenticate,
asyncMiddleware(removeVideoCommentValidator),
asyncRetryTransactionMiddleware(removeVideoComment)
)
videoCommentRouter.post('/:videoId/comments/:commentId/approve',
authenticate,
asyncMiddleware(approveVideoCommentValidator),
asyncMiddleware(approveVideoComment)
)
videoCommentRouter.get('/comments',
authenticate,
ensureUserHasRight(UserRight.SEE_ALL_COMMENTS),
paginationValidator,
videoCommentsValidator,
setDefaultSort,
setDefaultPagination,
asyncMiddleware(listAllVideoCommentsForAdminValidator),
asyncMiddleware(listComments)
)
// ---------------------------------------------------------------------------
export {
videoCommentRouter
}
// ---------------------------------------------------------------------------
async function listComments (req: express.Request, res: express.Response) {
const options = {
...pick(req.query, [
'start',
'count',
'sort',
'isLocal',
'onLocalVideo',
'search',
'searchAccount',
'searchVideo',
'autoTagOneOf'
]),
videoId: res.locals.onlyImmutableVideo?.id,
videoChannelOwnerId: res.locals.videoChannel?.id,
autoTagOfAccountId: (await getServerActor()).Account.id,
heldForReview: undefined
}
const resultList = await VideoCommentModel.listCommentsForApi(options)
return res.json({
total: resultList.total,
data: resultList.data.map(c => c.toFormattedForAdminOrUserJSON())
})
}
async function listVideoThreads (req: express.Request, res: express.Response) {
const video = res.locals.onlyVideo
const user = res.locals.oauth ? res.locals.oauth.token.User : undefined
let resultList: ThreadsResultList<MCommentFormattable>
if (video.commentsPolicy !== VideoCommentPolicy.DISABLED) {
const apiOptions = await Hooks.wrapObject({
video,
start: req.query.start,
count: req.query.count,
sort: req.query.sort,
user
}, 'filter:api.video-threads.list.params')
resultList = await Hooks.wrapPromiseFun(
VideoCommentModel.listThreadsForApi.bind(VideoCommentModel),
apiOptions,
'filter:api.video-threads.list.result'
)
} else {
resultList = {
total: 0,
totalNotDeletedComments: 0,
data: []
}
}
return res.json({
...getFormattedObjects(resultList.data, resultList.total),
totalNotDeletedComments: resultList.totalNotDeletedComments
} as VideoCommentThreads)
}
async function listVideoThreadComments (req: express.Request, res: express.Response) {
const video = res.locals.onlyVideo
const user = res.locals.oauth ? res.locals.oauth.token.User : undefined
let resultList: ResultList<MCommentFormattable>
if (video.commentsPolicy !== VideoCommentPolicy.DISABLED) {
const apiOptions = await Hooks.wrapObject({
video,
threadId: res.locals.videoCommentThread.id,
user
}, 'filter:api.video-thread-comments.list.params')
resultList = await Hooks.wrapPromiseFun(
VideoCommentModel.listThreadCommentsForApi.bind(VideoCommentModel),
apiOptions,
'filter:api.video-thread-comments.list.result'
)
} else {
resultList = {
total: 0,
data: []
}
}
if (resultList.data.length === 0) {
return res.fail({
status: HttpStatusCode.NOT_FOUND_404,
message: 'No comments were found'
})
}
return res.json(buildFormattedCommentTree(resultList))
}
async function addVideoCommentThread (req: express.Request, res: express.Response) {
const videoCommentInfo: VideoCommentCreate = req.body
const comment = await createLocalVideoComment({
text: videoCommentInfo.text,
inReplyToComment: null,
video: res.locals.videoAll,
user: res.locals.oauth.token.User
})
Notifier.Instance.notifyOnNewComment(comment)
auditLogger.create(getAuditIdFromRes(res), new CommentAuditView(comment.toFormattedJSON()))
Hooks.runAction('action:api.video-thread.created', { comment, req, res })
return res.json({ comment: comment.toFormattedJSON() })
}
async function addVideoCommentReply (req: express.Request, res: express.Response) {
const videoCommentInfo: VideoCommentCreate = req.body
const comment = await createLocalVideoComment({
text: videoCommentInfo.text,
inReplyToComment: res.locals.videoCommentFull,
video: res.locals.videoAll,
user: res.locals.oauth.token.User
})
Notifier.Instance.notifyOnNewComment(comment)
auditLogger.create(getAuditIdFromRes(res), new CommentAuditView(comment.toFormattedJSON()))
Hooks.runAction('action:api.video-comment-reply.created', { comment, req, res })
return res.json({ comment: comment.toFormattedJSON() })
}
async function removeVideoComment (req: express.Request, res: express.Response) {
const comment = res.locals.videoCommentFull
await removeComment(comment, req, res)
auditLogger.delete(getAuditIdFromRes(res), new CommentAuditView(comment.toFormattedJSON()))
return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
}
async function approveVideoComment (req: express.Request, res: express.Response) {
await approveComment(res.locals.videoCommentFull)
return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
}
+122
ファイルの表示
@@ -0,0 +1,122 @@
import express from 'express'
import validator from 'validator'
import { logger, loggerTagsFactory } from '@server/helpers/logger.js'
import { federateVideoIfNeeded } from '@server/lib/activitypub/videos/index.js'
import { updatePlaylistAfterFileChange } from '@server/lib/hls.js'
import { removeAllWebVideoFiles, removeHLSFile, removeHLSPlaylist, removeWebVideoFile } from '@server/lib/video-file.js'
import { VideoFileModel } from '@server/models/video/video-file.js'
import { HttpStatusCode, UserRight } from '@peertube/peertube-models'
import {
asyncMiddleware,
authenticate,
ensureUserHasRight,
videoFileMetadataGetValidator,
videoFilesDeleteHLSFileValidator,
videoFilesDeleteHLSValidator,
videoFilesDeleteWebVideoFileValidator,
videoFilesDeleteWebVideoValidator,
videosGetValidator
} from '../../../middlewares/index.js'
const lTags = loggerTagsFactory('api', 'video')
const filesRouter = express.Router()
filesRouter.get('/:id/metadata/:videoFileId',
asyncMiddleware(videosGetValidator),
asyncMiddleware(videoFileMetadataGetValidator),
asyncMiddleware(getVideoFileMetadata)
)
filesRouter.delete('/:id/hls',
authenticate,
ensureUserHasRight(UserRight.MANAGE_VIDEO_FILES),
asyncMiddleware(videoFilesDeleteHLSValidator),
asyncMiddleware(removeHLSPlaylistController)
)
filesRouter.delete('/:id/hls/:videoFileId',
authenticate,
ensureUserHasRight(UserRight.MANAGE_VIDEO_FILES),
asyncMiddleware(videoFilesDeleteHLSFileValidator),
asyncMiddleware(removeHLSFileController)
)
filesRouter.delete(
[ '/:id/webtorrent', '/:id/web-videos' ], // TODO: remove webtorrent in V7
authenticate,
ensureUserHasRight(UserRight.MANAGE_VIDEO_FILES),
asyncMiddleware(videoFilesDeleteWebVideoValidator),
asyncMiddleware(removeAllWebVideoFilesController)
)
filesRouter.delete(
[ '/:id/webtorrent/:videoFileId', '/:id/web-videos/:videoFileId' ], // TODO: remove webtorrent in V7
authenticate,
ensureUserHasRight(UserRight.MANAGE_VIDEO_FILES),
asyncMiddleware(videoFilesDeleteWebVideoFileValidator),
asyncMiddleware(removeWebVideoFileController)
)
// ---------------------------------------------------------------------------
export {
filesRouter
}
// ---------------------------------------------------------------------------
async function getVideoFileMetadata (req: express.Request, res: express.Response) {
const videoFile = await VideoFileModel.loadWithMetadata(validator.default.toInt(req.params.videoFileId))
return res.json(videoFile.metadata)
}
// ---------------------------------------------------------------------------
async function removeHLSPlaylistController (req: express.Request, res: express.Response) {
const video = res.locals.videoAll
logger.info('Deleting HLS playlist of %s.', video.url, lTags(video.uuid))
await removeHLSPlaylist(video)
await federateVideoIfNeeded(video, false, undefined)
return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
}
async function removeHLSFileController (req: express.Request, res: express.Response) {
const video = res.locals.videoAll
const videoFileId = +req.params.videoFileId
logger.info('Deleting HLS file %d of %s.', videoFileId, video.url, lTags(video.uuid))
const playlist = await removeHLSFile(video, videoFileId)
if (playlist) await updatePlaylistAfterFileChange(video, playlist)
await federateVideoIfNeeded(video, false, undefined)
return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
}
// ---------------------------------------------------------------------------
async function removeAllWebVideoFilesController (req: express.Request, res: express.Response) {
const video = res.locals.videoAll
logger.info('Deleting Web Video files of %s.', video.url, lTags(video.uuid))
await removeAllWebVideoFiles(video)
await federateVideoIfNeeded(video, false, undefined)
return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
}
async function removeWebVideoFileController (req: express.Request, res: express.Response) {
const video = res.locals.videoAll
const videoFileId = +req.params.videoFileId
logger.info('Deleting Web Video file %d of %s.', videoFileId, video.url, lTags(video.uuid))
await removeWebVideoFile(video, videoFileId)
await federateVideoIfNeeded(video, false, undefined)
return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
}
+272
ファイルの表示
@@ -0,0 +1,272 @@
import express from 'express'
import { move } from 'fs-extra/esm'
import { readFile } from 'fs/promises'
import { decode } from 'magnet-uri'
import parseTorrent, { Instance } from 'parse-torrent'
import { join } from 'path'
import { buildVideoFromImport, buildYoutubeDLImport, insertFromImportIntoDB, YoutubeDlImportError } from '@server/lib/video-pre-import.js'
import { MThumbnail, MVideoThumbnail } from '@server/types/models/index.js'
import {
HttpStatusCode,
ServerErrorCode,
ThumbnailType,
VideoImportCreate,
VideoImportPayload,
VideoImportState
} from '@peertube/peertube-models'
import { auditLoggerFactory, getAuditIdFromRes, VideoImportAuditView } from '../../../helpers/audit-logger.js'
import { isArray } from '../../../helpers/custom-validators/misc.js'
import { cleanUpReqFiles, createReqFiles } from '../../../helpers/express-utils.js'
import { logger } from '../../../helpers/logger.js'
import { getSecureTorrentName } from '../../../helpers/utils.js'
import { CONFIG } from '../../../initializers/config.js'
import { MIMETYPES } from '../../../initializers/constants.js'
import { JobQueue } from '../../../lib/job-queue/job-queue.js'
import { updateLocalVideoMiniatureFromExisting } from '../../../lib/thumbnail.js'
import {
asyncMiddleware,
asyncRetryTransactionMiddleware,
authenticate,
videoImportAddValidator,
videoImportCancelValidator,
videoImportDeleteValidator
} from '../../../middlewares/index.js'
const auditLogger = auditLoggerFactory('video-imports')
const videoImportsRouter = express.Router()
const reqVideoFileImport = createReqFiles(
[ 'thumbnailfile', 'previewfile', 'torrentfile' ],
{ ...MIMETYPES.TORRENT.MIMETYPE_EXT, ...MIMETYPES.IMAGE.MIMETYPE_EXT }
)
videoImportsRouter.post('/imports',
authenticate,
reqVideoFileImport,
asyncMiddleware(videoImportAddValidator),
asyncRetryTransactionMiddleware(handleVideoImport)
)
videoImportsRouter.post('/imports/:id/cancel',
authenticate,
asyncMiddleware(videoImportCancelValidator),
asyncRetryTransactionMiddleware(cancelVideoImport)
)
videoImportsRouter.delete('/imports/:id',
authenticate,
asyncMiddleware(videoImportDeleteValidator),
asyncRetryTransactionMiddleware(deleteVideoImport)
)
// ---------------------------------------------------------------------------
export {
videoImportsRouter
}
// ---------------------------------------------------------------------------
async function deleteVideoImport (req: express.Request, res: express.Response) {
const videoImport = res.locals.videoImport
await videoImport.destroy()
return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
}
async function cancelVideoImport (req: express.Request, res: express.Response) {
const videoImport = res.locals.videoImport
videoImport.state = VideoImportState.CANCELLED
await videoImport.save()
return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
}
function handleVideoImport (req: express.Request, res: express.Response) {
if (req.body.targetUrl) return handleYoutubeDlImport(req, res)
const file = req.files?.['torrentfile']?.[0]
if (req.body.magnetUri || file) return handleTorrentImport(req, res, file)
}
async function handleTorrentImport (req: express.Request, res: express.Response, torrentfile: Express.Multer.File) {
const body: VideoImportCreate = req.body
const user = res.locals.oauth.token.User
let videoName: string
let torrentName: string
let magnetUri: string
if (torrentfile) {
const result = await processTorrentOrAbortRequest(req, res, torrentfile)
if (!result) return
videoName = result.name
torrentName = result.torrentName
} else {
const result = processMagnetURI(body)
magnetUri = result.magnetUri
videoName = result.name
}
const video = await buildVideoFromImport({
channelId: res.locals.videoChannel.id,
importData: { name: videoName },
importDataOverride: body,
importType: 'torrent'
})
const thumbnailModel = await processThumbnail(req, video)
const previewModel = await processPreview(req, video)
const videoImport = await insertFromImportIntoDB({
video,
thumbnailModel,
previewModel,
videoChannel: res.locals.videoChannel,
tags: body.tags || undefined,
user,
videoPasswords: body.videoPasswords,
videoImportAttributes: {
magnetUri,
torrentName,
state: VideoImportState.PENDING,
userId: user.id
}
})
const payload: VideoImportPayload = {
type: torrentfile
? 'torrent-file'
: 'magnet-uri',
videoImportId: videoImport.id,
preventException: false,
generateTranscription: body.generateTranscription
}
await JobQueue.Instance.createJob({ type: 'video-import', payload })
auditLogger.create(getAuditIdFromRes(res), new VideoImportAuditView(videoImport.toFormattedJSON()))
return res.json(videoImport.toFormattedJSON()).end()
}
function statusFromYtDlImportError (err: YoutubeDlImportError): number {
switch (err.code) {
case YoutubeDlImportError.CODE.NOT_ONLY_UNICAST_URL:
return HttpStatusCode.FORBIDDEN_403
case YoutubeDlImportError.CODE.FETCH_ERROR:
return HttpStatusCode.BAD_REQUEST_400
default:
return HttpStatusCode.INTERNAL_SERVER_ERROR_500
}
}
async function handleYoutubeDlImport (req: express.Request, res: express.Response) {
const body: VideoImportCreate = req.body
const targetUrl = body.targetUrl
const user = res.locals.oauth.token.User
try {
const { job, videoImport } = await buildYoutubeDLImport({
targetUrl,
channel: res.locals.videoChannel,
importDataOverride: body,
thumbnailFilePath: req.files?.['thumbnailfile']?.[0].path,
previewFilePath: req.files?.['previewfile']?.[0].path,
user
})
await JobQueue.Instance.createJob(job)
auditLogger.create(getAuditIdFromRes(res), new VideoImportAuditView(videoImport.toFormattedJSON()))
return res.json(videoImport.toFormattedJSON()).end()
} catch (err) {
logger.error('An error occurred while importing the video %s. ', targetUrl, { err })
return res.fail({
message: err.message,
status: statusFromYtDlImportError(err),
data: {
targetUrl
}
})
}
}
async function processThumbnail (req: express.Request, video: MVideoThumbnail) {
const thumbnailField = req.files ? req.files['thumbnailfile'] : undefined
if (thumbnailField) {
const thumbnailPhysicalFile = thumbnailField[0]
return updateLocalVideoMiniatureFromExisting({
inputPath: thumbnailPhysicalFile.path,
video,
type: ThumbnailType.MINIATURE,
automaticallyGenerated: false
})
}
return undefined
}
async function processPreview (req: express.Request, video: MVideoThumbnail): Promise<MThumbnail> {
const previewField = req.files ? req.files['previewfile'] : undefined
if (previewField) {
const previewPhysicalFile = previewField[0]
return updateLocalVideoMiniatureFromExisting({
inputPath: previewPhysicalFile.path,
video,
type: ThumbnailType.PREVIEW,
automaticallyGenerated: false
})
}
return undefined
}
async function processTorrentOrAbortRequest (req: express.Request, res: express.Response, torrentfile: Express.Multer.File) {
const torrentName = torrentfile.originalname
// Rename the torrent to a secured name
const newTorrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, getSecureTorrentName(torrentName))
await move(torrentfile.path, newTorrentPath, { overwrite: true })
torrentfile.path = newTorrentPath
const buf = await readFile(torrentfile.path)
// FIXME: typings: parseTorrent now returns an async result
const parsedTorrent = await (parseTorrent(buf) as unknown as Promise<Instance>)
if (parsedTorrent.files.length !== 1) {
cleanUpReqFiles(req)
res.fail({
type: ServerErrorCode.INCORRECT_FILES_IN_TORRENT,
message: 'Torrents with only 1 file are supported.'
})
return undefined
}
return {
name: extractNameFromArray(parsedTorrent.name),
torrentName
}
}
function processMagnetURI (body: VideoImportCreate) {
const magnetUri = body.magnetUri
const parsed = decode(magnetUri)
return {
name: extractNameFromArray(parsed.name),
magnetUri
}
}
function extractNameFromArray (name: string | string[]) {
return isArray(name) ? name[0] : name
}
+232
ファイルの表示
@@ -0,0 +1,232 @@
import express from 'express'
import { HttpStatusCode } from '@peertube/peertube-models'
import { pickCommonVideoQuery } from '@server/helpers/query.js'
import { doJSONRequest } from '@server/helpers/requests.js'
import { openapiOperationDoc } from '@server/middlewares/doc.js'
import { getServerActor } from '@server/models/application/application.js'
import { MVideoAccountLight } from '@server/types/models/index.js'
import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger.js'
import { buildNSFWFilter, getCountVideos } from '../../../helpers/express-utils.js'
import { logger } from '../../../helpers/logger.js'
import { getFormattedObjects } from '../../../helpers/utils.js'
import { REMOTE_SCHEME, VIDEO_CATEGORIES, VIDEO_LANGUAGES, VIDEO_LICENCES, VIDEO_PRIVACIES } from '../../../initializers/constants.js'
import { sequelizeTypescript } from '../../../initializers/database.js'
import { JobQueue } from '../../../lib/job-queue/index.js'
import { Hooks } from '../../../lib/plugins/hooks.js'
import {
apiRateLimiter,
asyncMiddleware,
asyncRetryTransactionMiddleware,
authenticate,
checkVideoFollowConstraints,
commonVideosFiltersValidator,
optionalAuthenticate,
paginationValidator,
setDefaultPagination,
setDefaultVideosSort,
videosCustomGetValidator,
videosGetValidator,
videosRemoveValidator,
videosSortValidator
} from '../../../middlewares/index.js'
import { guessAdditionalAttributesFromQuery } from '../../../models/video/formatter/index.js'
import { VideoModel } from '../../../models/video/video.js'
import { blacklistRouter } from './blacklist.js'
import { videoCaptionsRouter } from './captions.js'
import { videoCommentRouter } from './comment.js'
import { filesRouter } from './files.js'
import { videoImportsRouter } from './import.js'
import { liveRouter } from './live.js'
import { ownershipVideoRouter } from './ownership.js'
import { videoPasswordRouter } from './passwords.js'
import { rateVideoRouter } from './rate.js'
import { videoSourceRouter } from './source.js'
import { statsRouter } from './stats.js'
import { storyboardRouter } from './storyboard.js'
import { studioRouter } from './studio.js'
import { tokenRouter } from './token.js'
import { transcodingRouter } from './transcoding.js'
import { updateRouter } from './update.js'
import { uploadRouter } from './upload.js'
import { viewRouter } from './view.js'
import { videoChaptersRouter } from './chapters.js'
const auditLogger = auditLoggerFactory('videos')
const videosRouter = express.Router()
videosRouter.use(apiRateLimiter)
videosRouter.use('/', blacklistRouter)
videosRouter.use('/', statsRouter)
videosRouter.use('/', rateVideoRouter)
videosRouter.use('/', videoCommentRouter)
videosRouter.use('/', studioRouter)
videosRouter.use('/', videoCaptionsRouter)
videosRouter.use('/', videoImportsRouter)
videosRouter.use('/', ownershipVideoRouter)
videosRouter.use('/', viewRouter)
videosRouter.use('/', liveRouter)
videosRouter.use('/', uploadRouter)
videosRouter.use('/', updateRouter)
videosRouter.use('/', filesRouter)
videosRouter.use('/', transcodingRouter)
videosRouter.use('/', tokenRouter)
videosRouter.use('/', videoPasswordRouter)
videosRouter.use('/', storyboardRouter)
videosRouter.use('/', videoSourceRouter)
videosRouter.use('/', videoChaptersRouter)
videosRouter.get('/categories',
openapiOperationDoc({ operationId: 'getCategories' }),
listVideoCategories
)
videosRouter.get('/licences',
openapiOperationDoc({ operationId: 'getLicences' }),
listVideoLicences
)
videosRouter.get('/languages',
openapiOperationDoc({ operationId: 'getLanguages' }),
listVideoLanguages
)
videosRouter.get('/privacies',
openapiOperationDoc({ operationId: 'getPrivacies' }),
listVideoPrivacies
)
videosRouter.get('/',
openapiOperationDoc({ operationId: 'getVideos' }),
paginationValidator,
videosSortValidator,
setDefaultVideosSort,
setDefaultPagination,
optionalAuthenticate,
commonVideosFiltersValidator,
asyncMiddleware(listVideos)
)
// TODO: remove, deprecated in 5.0 now we send the complete description in VideoDetails
videosRouter.get('/:id/description',
openapiOperationDoc({ operationId: 'getVideoDesc' }),
asyncMiddleware(videosGetValidator),
asyncMiddleware(getVideoDescription)
)
videosRouter.get('/:id',
openapiOperationDoc({ operationId: 'getVideo' }),
optionalAuthenticate,
asyncMiddleware(videosCustomGetValidator('for-api')),
asyncMiddleware(checkVideoFollowConstraints),
asyncMiddleware(getVideo)
)
videosRouter.delete('/:id',
openapiOperationDoc({ operationId: 'delVideo' }),
authenticate,
asyncMiddleware(videosRemoveValidator),
asyncRetryTransactionMiddleware(removeVideo)
)
// ---------------------------------------------------------------------------
export {
videosRouter
}
// ---------------------------------------------------------------------------
function listVideoCategories (_req: express.Request, res: express.Response) {
res.json(VIDEO_CATEGORIES)
}
function listVideoLicences (_req: express.Request, res: express.Response) {
res.json(VIDEO_LICENCES)
}
function listVideoLanguages (_req: express.Request, res: express.Response) {
res.json(VIDEO_LANGUAGES)
}
function listVideoPrivacies (_req: express.Request, res: express.Response) {
res.json(VIDEO_PRIVACIES)
}
async function getVideo (req: express.Request, res: express.Response) {
const videoId = res.locals.videoAPI.id
const userId = res.locals.oauth?.token.User.id
const video = await Hooks.wrapObject(res.locals.videoAPI, 'filter:api.video.get.result', { req, id: videoId, userId })
// Filter may return null/undefined value to forbid video access
if (!video) return res.sendStatus(HttpStatusCode.NOT_FOUND_404)
if (video.isOutdated()) {
JobQueue.Instance.createJobAsync({ type: 'activitypub-refresher', payload: { type: 'video', url: video.url } })
}
return res.json(video.toFormattedDetailsJSON())
}
async function getVideoDescription (req: express.Request, res: express.Response) {
const videoInstance = res.locals.videoAll
const description = videoInstance.isOwned()
? videoInstance.description
: await fetchRemoteVideoDescription(videoInstance)
return res.json({ description })
}
async function listVideos (req: express.Request, res: express.Response) {
const serverActor = await getServerActor()
const query = pickCommonVideoQuery(req.query)
const countVideos = getCountVideos(req)
const apiOptions = await Hooks.wrapObject({
...query,
displayOnlyForFollower: {
actorId: serverActor.id,
orLocalVideos: true
},
nsfw: buildNSFWFilter(res, query.nsfw),
user: res.locals.oauth ? res.locals.oauth.token.User : undefined,
countVideos
}, 'filter:api.videos.list.params')
const resultList = await Hooks.wrapPromiseFun(
VideoModel.listForApi.bind(VideoModel),
apiOptions,
'filter:api.videos.list.result'
)
return res.json(getFormattedObjects(resultList.data, resultList.total, guessAdditionalAttributesFromQuery(query)))
}
async function removeVideo (req: express.Request, res: express.Response) {
const videoInstance = res.locals.videoAll
await sequelizeTypescript.transaction(async t => {
await videoInstance.destroy({ transaction: t })
})
auditLogger.delete(getAuditIdFromRes(res), new VideoAuditView(videoInstance.toFormattedDetailsJSON()))
logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
Hooks.runAction('action:api.video.deleted', { video: videoInstance, req, res })
return res.type('json')
.status(HttpStatusCode.NO_CONTENT_204)
.end()
}
// ---------------------------------------------------------------------------
// FIXME: Should not exist, we rely on specific API
async function fetchRemoteVideoDescription (video: MVideoAccountLight) {
const host = video.VideoChannel.Account.Actor.Server.host
const path = video.getDescriptionAPIPath()
const url = REMOTE_SCHEME.HTTP + '://' + host + path
const { body } = await doJSONRequest<any>(url)
return body.description || ''
}
+207
ファイルの表示
@@ -0,0 +1,207 @@
import express from 'express'
import {
HttpStatusCode,
LiveVideoCreate,
LiveVideoUpdate,
ThumbnailType,
UserRight,
VideoState
} from '@peertube/peertube-models'
import { exists } from '@server/helpers/custom-validators/misc.js'
import { createReqFiles } from '@server/helpers/express-utils.js'
import { getFormattedObjects } from '@server/helpers/utils.js'
import { ASSETS_PATH, MIMETYPES } from '@server/initializers/constants.js'
import { federateVideoIfNeeded } from '@server/lib/activitypub/videos/index.js'
import { Hooks } from '@server/lib/plugins/hooks.js'
import {
videoLiveAddValidator,
videoLiveFindReplaySessionValidator,
videoLiveGetValidator,
videoLiveListSessionsValidator,
videoLiveUpdateValidator
} from '@server/middlewares/validators/videos/video-live.js'
import { VideoLiveReplaySettingModel } from '@server/models/video/video-live-replay-setting.js'
import { VideoLiveSessionModel } from '@server/models/video/video-live-session.js'
import { MVideoLive } from '@server/types/models/index.js'
import { uuidToShort } from '@peertube/peertube-node-utils'
import { logger, loggerTagsFactory } from '../../../helpers/logger.js'
import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate, optionalAuthenticate } from '../../../middlewares/index.js'
import { LocalVideoCreator } from '@server/lib/local-video-creator.js'
import { pick } from '@peertube/peertube-core-utils'
const lTags = loggerTagsFactory('api', 'live')
const liveRouter = express.Router()
const reqVideoFileLive = createReqFiles([ 'thumbnailfile', 'previewfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT)
liveRouter.post('/live',
authenticate,
reqVideoFileLive,
asyncMiddleware(videoLiveAddValidator),
asyncRetryTransactionMiddleware(addLiveVideo)
)
liveRouter.get('/live/:videoId/sessions',
authenticate,
asyncMiddleware(videoLiveGetValidator),
videoLiveListSessionsValidator,
asyncMiddleware(getLiveVideoSessions)
)
liveRouter.get('/live/:videoId',
optionalAuthenticate,
asyncMiddleware(videoLiveGetValidator),
getLiveVideo
)
liveRouter.put('/live/:videoId',
authenticate,
asyncMiddleware(videoLiveGetValidator),
videoLiveUpdateValidator,
asyncRetryTransactionMiddleware(updateLiveVideo)
)
liveRouter.get('/:videoId/live-session',
asyncMiddleware(videoLiveFindReplaySessionValidator),
getLiveReplaySession
)
// ---------------------------------------------------------------------------
export {
liveRouter
}
// ---------------------------------------------------------------------------
function getLiveVideo (req: express.Request, res: express.Response) {
const videoLive = res.locals.videoLive
return res.json(videoLive.toFormattedJSON(canSeePrivateLiveInformation(res)))
}
function getLiveReplaySession (req: express.Request, res: express.Response) {
const session = res.locals.videoLiveSession
return res.json(session.toFormattedJSON())
}
async function getLiveVideoSessions (req: express.Request, res: express.Response) {
const videoLive = res.locals.videoLive
const data = await VideoLiveSessionModel.listSessionsOfLiveForAPI({ videoId: videoLive.videoId })
return res.json(getFormattedObjects(data, data.length))
}
function canSeePrivateLiveInformation (res: express.Response) {
const user = res.locals.oauth?.token.User
if (!user) return false
if (user.hasRight(UserRight.GET_ANY_LIVE)) return true
const video = res.locals.videoAll
return video.VideoChannel.Account.userId === user.id
}
async function updateLiveVideo (req: express.Request, res: express.Response) {
const body: LiveVideoUpdate = req.body
const video = res.locals.videoAll
const videoLive = res.locals.videoLive
const newReplaySettingModel = await updateReplaySettings(videoLive, body)
if (newReplaySettingModel) videoLive.replaySettingId = newReplaySettingModel.id
else videoLive.replaySettingId = null
if (exists(body.permanentLive)) videoLive.permanentLive = body.permanentLive
if (exists(body.latencyMode)) videoLive.latencyMode = body.latencyMode
video.VideoLive = await videoLive.save()
await federateVideoIfNeeded(video, false)
return res.status(HttpStatusCode.NO_CONTENT_204).end()
}
async function updateReplaySettings (videoLive: MVideoLive, body: LiveVideoUpdate) {
if (exists(body.saveReplay)) videoLive.saveReplay = body.saveReplay
// The live replay is not saved anymore, destroy the old model if it existed
if (!videoLive.saveReplay) {
if (videoLive.replaySettingId) {
await VideoLiveReplaySettingModel.removeSettings(videoLive.replaySettingId)
}
return undefined
}
const settingModel = videoLive.replaySettingId
? await VideoLiveReplaySettingModel.load(videoLive.replaySettingId)
: new VideoLiveReplaySettingModel()
if (exists(body.replaySettings.privacy)) settingModel.privacy = body.replaySettings.privacy
return settingModel.save()
}
async function addLiveVideo (req: express.Request, res: express.Response) {
const videoInfo: LiveVideoCreate = req.body
const thumbnails = [ { type: ThumbnailType.MINIATURE, field: 'thumbnailfile' }, { type: ThumbnailType.PREVIEW, field: 'previewfile' } ]
.map(({ type, field }) => {
if (req.files?.[field]?.[0]) {
return {
path: req.files[field][0].path,
type,
automaticallyGenerated: false,
keepOriginal: false
}
}
return {
path: ASSETS_PATH.DEFAULT_LIVE_BACKGROUND,
type,
automaticallyGenerated: true,
keepOriginal: true
}
})
const localVideoCreator = new LocalVideoCreator({
channel: res.locals.videoChannel,
chapters: undefined,
fallbackChapters: {
fromDescription: false,
finalFallback: undefined
},
liveAttributes: pick(videoInfo, [ 'saveReplay', 'permanentLive', 'latencyMode', 'replaySettings' ]),
videoAttributeResultHook: 'filter:api.video.live.video-attribute.result',
lTags,
videoAttributes: {
...videoInfo,
duration: 0,
state: VideoState.WAITING_FOR_LIVE,
isLive: true,
inputFilename: null
},
videoFile: undefined,
user: res.locals.oauth.token.User,
thumbnails
})
const { video } = await localVideoCreator.create()
logger.info('Video live %s with uuid %s created.', videoInfo.name, video.uuid, lTags())
Hooks.runAction('action:api.live-video.created', { video, req, res })
return res.json({
video: {
id: video.id,
shortUUID: uuidToShort(video.uuid),
uuid: video.uuid
}
})
}
+138
ファイルの表示
@@ -0,0 +1,138 @@
import { HttpStatusCode, VideoChangeOwnershipStatus } from '@peertube/peertube-models'
import { canVideoBeFederated } from '@server/lib/activitypub/videos/federate.js'
import { MVideoFullLight } from '@server/types/models/index.js'
import express from 'express'
import { logger } from '../../../helpers/logger.js'
import { getFormattedObjects } from '../../../helpers/utils.js'
import { sequelizeTypescript } from '../../../initializers/database.js'
import { sendUpdateVideo } from '../../../lib/activitypub/send/index.js'
import { changeVideoChannelShare } from '../../../lib/activitypub/share.js'
import {
asyncMiddleware,
asyncRetryTransactionMiddleware,
authenticate,
paginationValidator,
setDefaultPagination,
videosAcceptChangeOwnershipValidator,
videosChangeOwnershipValidator,
videosTerminateChangeOwnershipValidator
} from '../../../middlewares/index.js'
import { VideoChangeOwnershipModel } from '../../../models/video/video-change-ownership.js'
import { VideoChannelModel } from '../../../models/video/video-channel.js'
import { VideoModel } from '../../../models/video/video.js'
const ownershipVideoRouter = express.Router()
ownershipVideoRouter.post('/:videoId/give-ownership',
authenticate,
asyncMiddleware(videosChangeOwnershipValidator),
asyncRetryTransactionMiddleware(giveVideoOwnership)
)
ownershipVideoRouter.get('/ownership',
authenticate,
paginationValidator,
setDefaultPagination,
asyncRetryTransactionMiddleware(listVideoOwnership)
)
ownershipVideoRouter.post('/ownership/:id/accept',
authenticate,
asyncMiddleware(videosTerminateChangeOwnershipValidator),
asyncMiddleware(videosAcceptChangeOwnershipValidator),
asyncRetryTransactionMiddleware(acceptOwnership)
)
ownershipVideoRouter.post('/ownership/:id/refuse',
authenticate,
asyncMiddleware(videosTerminateChangeOwnershipValidator),
asyncRetryTransactionMiddleware(refuseOwnership)
)
// ---------------------------------------------------------------------------
export {
ownershipVideoRouter
}
// ---------------------------------------------------------------------------
async function giveVideoOwnership (req: express.Request, res: express.Response) {
const videoInstance = res.locals.videoAll
const initiatorAccountId = res.locals.oauth.token.User.Account.id
const nextOwner = res.locals.nextOwner
await sequelizeTypescript.transaction(t => {
return VideoChangeOwnershipModel.findOrCreate({
where: {
initiatorAccountId,
nextOwnerAccountId: nextOwner.id,
videoId: videoInstance.id,
status: VideoChangeOwnershipStatus.WAITING
},
defaults: {
initiatorAccountId,
nextOwnerAccountId: nextOwner.id,
videoId: videoInstance.id,
status: VideoChangeOwnershipStatus.WAITING
},
transaction: t
})
})
logger.info('Ownership change for video %s created.', videoInstance.name)
return res.type('json')
.status(HttpStatusCode.NO_CONTENT_204)
.end()
}
async function listVideoOwnership (req: express.Request, res: express.Response) {
const currentAccountId = res.locals.oauth.token.User.Account.id
const resultList = await VideoChangeOwnershipModel.listForApi(
currentAccountId,
req.query.start || 0,
req.query.count || 10,
req.query.sort || 'createdAt'
)
return res.json(getFormattedObjects(resultList.data, resultList.total))
}
function acceptOwnership (req: express.Request, res: express.Response) {
return sequelizeTypescript.transaction(async t => {
const videoChangeOwnership = res.locals.videoChangeOwnership
const channel = res.locals.videoChannel
// We need more attributes for federation
const targetVideo = await VideoModel.loadFull(videoChangeOwnership.Video.id, t)
const oldVideoChannel = await VideoChannelModel.loadAndPopulateAccount(targetVideo.channelId, t)
targetVideo.channelId = channel.id
const targetVideoUpdated = await targetVideo.save({ transaction: t }) as MVideoFullLight
targetVideoUpdated.VideoChannel = channel
if (canVideoBeFederated(targetVideoUpdated)) {
await changeVideoChannelShare(targetVideoUpdated, oldVideoChannel, t)
await sendUpdateVideo(targetVideoUpdated, t, oldVideoChannel.Account.Actor)
}
videoChangeOwnership.status = VideoChangeOwnershipStatus.ACCEPTED
await videoChangeOwnership.save({ transaction: t })
return res.status(HttpStatusCode.NO_CONTENT_204).end()
})
}
function refuseOwnership (req: express.Request, res: express.Response) {
return sequelizeTypescript.transaction(async t => {
const videoChangeOwnership = res.locals.videoChangeOwnership
videoChangeOwnership.status = VideoChangeOwnershipStatus.REFUSED
await videoChangeOwnership.save({ transaction: t })
return res.status(HttpStatusCode.NO_CONTENT_204).end()
})
}
+104
ファイルの表示
@@ -0,0 +1,104 @@
import express from 'express'
import { Transaction } from 'sequelize'
import { HttpStatusCode } from '@peertube/peertube-models'
import { logger, loggerTagsFactory } from '@server/helpers/logger.js'
import { getVideoWithAttributes } from '@server/helpers/video.js'
import { VideoPasswordModel } from '@server/models/video/video-password.js'
import { getFormattedObjects } from '../../../helpers/utils.js'
import {
asyncMiddleware,
asyncRetryTransactionMiddleware,
authenticate,
setDefaultPagination,
setDefaultSort
} from '../../../middlewares/index.js'
import {
listVideoPasswordValidator,
paginationValidator,
removeVideoPasswordValidator,
updateVideoPasswordListValidator,
videoPasswordsSortValidator
} from '../../../middlewares/validators/index.js'
const lTags = loggerTagsFactory('api', 'video')
const videoPasswordRouter = express.Router()
videoPasswordRouter.get('/:videoId/passwords',
authenticate,
paginationValidator,
videoPasswordsSortValidator,
setDefaultSort,
setDefaultPagination,
asyncMiddleware(listVideoPasswordValidator),
asyncMiddleware(listVideoPasswords)
)
videoPasswordRouter.put('/:videoId/passwords',
authenticate,
asyncMiddleware(updateVideoPasswordListValidator),
asyncMiddleware(updateVideoPasswordList)
)
videoPasswordRouter.delete('/:videoId/passwords/:passwordId',
authenticate,
asyncMiddleware(removeVideoPasswordValidator),
asyncRetryTransactionMiddleware(removeVideoPassword)
)
// ---------------------------------------------------------------------------
export {
videoPasswordRouter
}
// ---------------------------------------------------------------------------
async function listVideoPasswords (req: express.Request, res: express.Response) {
const options = {
videoId: res.locals.videoAll.id,
start: req.query.start,
count: req.query.count,
sort: req.query.sort
}
const resultList = await VideoPasswordModel.listPasswords(options)
return res.json(getFormattedObjects(resultList.data, resultList.total))
}
async function updateVideoPasswordList (req: express.Request, res: express.Response) {
const videoInstance = getVideoWithAttributes(res)
const videoId = videoInstance.id
const passwordArray = req.body.passwords as string[]
await VideoPasswordModel.sequelize.transaction(async (t: Transaction) => {
await VideoPasswordModel.deleteAllPasswords(videoId, t)
await VideoPasswordModel.addPasswords(passwordArray, videoId, t)
})
logger.info(
`Video passwords for video with name %s and uuid %s have been updated`,
videoInstance.name,
videoInstance.uuid,
lTags(videoInstance.uuid)
)
return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
}
async function removeVideoPassword (req: express.Request, res: express.Response) {
const videoInstance = getVideoWithAttributes(res)
const password = res.locals.videoPassword
await VideoPasswordModel.deletePassword(password.id)
logger.info(
'Password with id %d of video named %s and uuid %s has been deleted.',
password.id,
videoInstance.name,
videoInstance.uuid,
lTags(videoInstance.uuid)
)
return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
}
+36
ファイルの表示
@@ -0,0 +1,36 @@
import express from 'express'
import { HttpStatusCode, UserVideoRateUpdate } from '@peertube/peertube-models'
import { logger } from '../../../helpers/logger.js'
import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate, videoUpdateRateValidator } from '../../../middlewares/index.js'
import { userRateVideo } from '@server/lib/rate.js'
const rateVideoRouter = express.Router()
rateVideoRouter.put('/:id/rate',
authenticate,
asyncMiddleware(videoUpdateRateValidator),
asyncRetryTransactionMiddleware(rateVideo)
)
// ---------------------------------------------------------------------------
export {
rateVideoRouter
}
// ---------------------------------------------------------------------------
async function rateVideo (req: express.Request, res: express.Response) {
const user = res.locals.oauth.token.User
const video = res.locals.videoAll
await userRateVideo({
account: user.Account,
rateType: (req.body as UserVideoRateUpdate).rating,
video
})
logger.info('Account video rate for video %s of account %s updated.', video.name, user.username)
return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
}
+216
ファイルの表示
@@ -0,0 +1,216 @@
import { buildAspectRatio } from '@peertube/peertube-core-utils'
import { HttpStatusCode, UserRight, VideoState } from '@peertube/peertube-models'
import { sequelizeTypescript } from '@server/initializers/database.js'
import { CreateJobArgument, CreateJobOptions, JobQueue } from '@server/lib/job-queue/index.js'
import { Hooks } from '@server/lib/plugins/hooks.js'
import { regenerateMiniaturesIfNeeded } from '@server/lib/thumbnail.js'
import { setupUploadResumableRoutes } from '@server/lib/uploadx.js'
import { autoBlacklistVideoIfNeeded } from '@server/lib/video-blacklist.js'
import { buildNewFile, createVideoSource } from '@server/lib/video-file.js'
import { buildMoveJob, buildStoryboardJobIfNeeded } from '@server/lib/video-jobs.js'
import { VideoPathManager } from '@server/lib/video-path-manager.js'
import { buildNextVideoState } from '@server/lib/video-state.js'
import { openapiOperationDoc } from '@server/middlewares/doc.js'
import { VideoModel } from '@server/models/video/video.js'
import { MStreamingPlaylistFiles, MVideo, MVideoFile, MVideoFullLight } from '@server/types/models/index.js'
import express from 'express'
import { move } from 'fs-extra/esm'
import { logger, loggerTagsFactory } from '../../../helpers/logger.js'
import {
asyncMiddleware,
authenticate,
ensureUserHasRight,
replaceVideoSourceResumableInitValidator,
replaceVideoSourceResumableValidator,
videoSourceGetLatestValidator
} from '../../../middlewares/index.js'
const lTags = loggerTagsFactory('api', 'video')
const videoSourceRouter = express.Router()
videoSourceRouter.get('/:id/source',
openapiOperationDoc({ operationId: 'getVideoSource' }),
authenticate,
asyncMiddleware(videoSourceGetLatestValidator),
getVideoLatestSource
)
videoSourceRouter.delete('/:id/source/file',
openapiOperationDoc({ operationId: 'deleteVideoSourceFile' }),
authenticate,
ensureUserHasRight(UserRight.MANAGE_VIDEO_FILES),
asyncMiddleware(videoSourceGetLatestValidator),
asyncMiddleware(deleteVideoLatestSourceFile)
)
setupUploadResumableRoutes({
routePath: '/:id/source/replace-resumable',
router: videoSourceRouter,
uploadInitAfterMiddlewares: [ asyncMiddleware(replaceVideoSourceResumableInitValidator) ],
uploadedMiddlewares: [ asyncMiddleware(replaceVideoSourceResumableValidator) ],
uploadedController: asyncMiddleware(replaceVideoSourceResumable)
})
// ---------------------------------------------------------------------------
export {
videoSourceRouter
}
// ---------------------------------------------------------------------------
async function deleteVideoLatestSourceFile (req: express.Request, res: express.Response) {
const videoSource = res.locals.videoSource
const video = res.locals.videoAll
await video.removeOriginalFile(videoSource)
videoSource.keptOriginalFilename = null
videoSource.storage = null
await videoSource.save()
return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
}
function getVideoLatestSource (req: express.Request, res: express.Response) {
return res.json(res.locals.videoSource.toFormattedJSON())
}
async function replaceVideoSourceResumable (req: express.Request, res: express.Response) {
const videoPhysicalFile = res.locals.updateVideoFileResumable
const user = res.locals.oauth.token.User
const videoFile = await buildNewFile({ path: videoPhysicalFile.path, mode: 'web-video', ffprobe: res.locals.ffprobe })
const originalFilename = videoPhysicalFile.originalname
const videoFileMutexReleaser = await VideoPathManager.Instance.lockFiles(res.locals.videoAll.uuid)
try {
const destination = VideoPathManager.Instance.getFSVideoFileOutputPath(res.locals.videoAll, videoFile)
await move(videoPhysicalFile.path, destination)
let oldWebVideoFiles: MVideoFile[] = []
let oldStreamingPlaylists: MStreamingPlaylistFiles[] = []
const inputFileUpdatedAt = new Date()
const video = await sequelizeTypescript.transaction(async transaction => {
const video = await VideoModel.loadFull(res.locals.videoAll.id, transaction)
oldWebVideoFiles = video.VideoFiles
oldStreamingPlaylists = video.VideoStreamingPlaylists
for (const file of video.VideoFiles) {
await file.destroy({ transaction })
}
for (const playlist of oldStreamingPlaylists) {
await playlist.destroy({ transaction })
}
videoFile.videoId = video.id
await videoFile.save({ transaction })
video.VideoFiles = [ videoFile ]
video.VideoStreamingPlaylists = []
video.state = buildNextVideoState()
video.duration = videoPhysicalFile.duration
video.inputFileUpdatedAt = inputFileUpdatedAt
video.aspectRatio = buildAspectRatio({ width: videoFile.width, height: videoFile.height })
await video.save({ transaction })
await autoBlacklistVideoIfNeeded({
video,
user,
isRemote: false,
isNew: false,
isNewFile: true,
transaction
})
return video
})
await removeOldFiles({ video, files: oldWebVideoFiles, playlists: oldStreamingPlaylists })
const source = await createVideoSource({
inputFilename: originalFilename,
inputProbe: res.locals.ffprobe,
inputPath: destination,
video,
createdAt: inputFileUpdatedAt
})
await regenerateMiniaturesIfNeeded(video, res.locals.ffprobe)
await video.VideoChannel.setAsUpdated()
await addVideoJobsAfterUpload(video, video.getMaxQualityFile())
logger.info('Replaced video file of video %s with uuid %s.', video.name, video.uuid, lTags(video.uuid))
Hooks.runAction('action:api.video.file-updated', { video, req, res })
return res.json(source.toFormattedJSON())
} finally {
videoFileMutexReleaser()
}
}
async function addVideoJobsAfterUpload (video: MVideoFullLight, videoFile: MVideoFile) {
const jobs: (CreateJobArgument & CreateJobOptions)[] = [
{
type: 'manage-video-torrent' as 'manage-video-torrent',
payload: {
videoId: video.id,
videoFileId: videoFile.id,
action: 'create'
}
},
buildStoryboardJobIfNeeded({ video, federate: false }),
{
type: 'federate-video' as 'federate-video',
payload: {
videoUUID: video.uuid,
isNewVideoForFederation: false
}
}
]
if (video.state === VideoState.TO_MOVE_TO_EXTERNAL_STORAGE) {
jobs.push(await buildMoveJob({ video, isNewVideo: false, previousVideoState: undefined, type: 'move-to-object-storage' }))
}
if (video.state === VideoState.TO_TRANSCODE) {
jobs.push({
type: 'transcoding-job-builder' as 'transcoding-job-builder',
payload: {
videoUUID: video.uuid,
optimizeJob: {
isNewVideo: false
}
}
})
}
return JobQueue.Instance.createSequentialJobFlow(...jobs)
}
async function removeOldFiles (options: {
video: MVideo
files: MVideoFile[]
playlists: MStreamingPlaylistFiles[]
}) {
const { video, files, playlists } = options
for (const file of files) {
await video.removeWebVideoFile(file)
}
for (const playlist of playlists) {
await video.removeStreamingPlaylistFiles(playlist)
}
}
+75
ファイルの表示
@@ -0,0 +1,75 @@
import express from 'express'
import { LocalVideoViewerModel } from '@server/models/view/local-video-viewer.js'
import { VideoStatsOverallQuery, VideoStatsTimeserieMetric, VideoStatsTimeserieQuery } from '@peertube/peertube-models'
import {
asyncMiddleware,
authenticate,
videoOverallStatsValidator,
videoRetentionStatsValidator,
videoTimeserieStatsValidator
} from '../../../middlewares/index.js'
const statsRouter = express.Router()
statsRouter.get('/:videoId/stats/overall',
authenticate,
asyncMiddleware(videoOverallStatsValidator),
asyncMiddleware(getOverallStats)
)
statsRouter.get('/:videoId/stats/timeseries/:metric',
authenticate,
asyncMiddleware(videoTimeserieStatsValidator),
asyncMiddleware(getTimeserieStats)
)
statsRouter.get('/:videoId/stats/retention',
authenticate,
asyncMiddleware(videoRetentionStatsValidator),
asyncMiddleware(getRetentionStats)
)
// ---------------------------------------------------------------------------
export {
statsRouter
}
// ---------------------------------------------------------------------------
async function getOverallStats (req: express.Request, res: express.Response) {
const video = res.locals.videoAll
const query = req.query as VideoStatsOverallQuery
const stats = await LocalVideoViewerModel.getOverallStats({
video,
startDate: query.startDate,
endDate: query.endDate
})
return res.json(stats)
}
async function getRetentionStats (req: express.Request, res: express.Response) {
const video = res.locals.videoAll
const stats = await LocalVideoViewerModel.getRetentionStats(video)
return res.json(stats)
}
async function getTimeserieStats (req: express.Request, res: express.Response) {
const video = res.locals.videoAll
const metric = req.params.metric as VideoStatsTimeserieMetric
const query = req.query as VideoStatsTimeserieQuery
const stats = await LocalVideoViewerModel.getTimeserieStats({
video,
metric,
startDate: query.startDate ?? video.createdAt.toISOString(),
endDate: query.endDate ?? new Date().toISOString()
})
return res.json(stats)
}
+29
ファイルの表示
@@ -0,0 +1,29 @@
import express from 'express'
import { getVideoWithAttributes } from '@server/helpers/video.js'
import { StoryboardModel } from '@server/models/video/storyboard.js'
import { asyncMiddleware, videosGetValidator } from '../../../middlewares/index.js'
const storyboardRouter = express.Router()
storyboardRouter.get('/:id/storyboards',
asyncMiddleware(videosGetValidator),
asyncMiddleware(listStoryboards)
)
// ---------------------------------------------------------------------------
export {
storyboardRouter
}
// ---------------------------------------------------------------------------
async function listStoryboards (req: express.Request, res: express.Response) {
const video = getVideoWithAttributes(res)
const storyboards = await StoryboardModel.listStoryboardsOf(video)
return res.json({
storyboards: storyboards.map(s => s.toFormattedJSON())
})
}
+143
ファイルの表示
@@ -0,0 +1,143 @@
import Bluebird from 'bluebird'
import express from 'express'
import { move } from 'fs-extra/esm'
import { basename } from 'path'
import { createAnyReqFiles } from '@server/helpers/express-utils.js'
import { MIMETYPES, VIDEO_FILTERS } from '@server/initializers/constants.js'
import { buildTaskFileFieldname, createVideoStudioJob, getStudioTaskFilePath, getTaskFileFromReq } from '@server/lib/video-studio.js'
import {
HttpStatusCode,
VideoState,
VideoStudioCreateEdition,
VideoStudioTask,
VideoStudioTaskCut,
VideoStudioTaskIntro,
VideoStudioTaskOutro,
VideoStudioTaskPayload,
VideoStudioTaskWatermark
} from '@peertube/peertube-models'
import { asyncMiddleware, authenticate, videoStudioAddEditionValidator } from '../../../middlewares/index.js'
const studioRouter = express.Router()
const tasksFiles = createAnyReqFiles(
MIMETYPES.VIDEO.MIMETYPE_EXT,
(req: express.Request, file: Express.Multer.File, cb: (err: Error, result?: boolean) => void) => {
const body = req.body as VideoStudioCreateEdition
// Fetch array element
const matches = file.fieldname.match(/tasks\[(\d+)\]/)
if (!matches) return cb(new Error('Cannot find array element indice for ' + file.fieldname))
const indice = parseInt(matches[1])
const task = body.tasks[indice]
if (!task) return cb(new Error('Cannot find array element of indice ' + indice + ' for ' + file.fieldname))
if (
[ 'add-intro', 'add-outro', 'add-watermark' ].includes(task.name) &&
file.fieldname === buildTaskFileFieldname(indice)
) {
return cb(null, true)
}
return cb(null, false)
}
)
studioRouter.post('/:videoId/studio/edit',
authenticate,
tasksFiles,
asyncMiddleware(videoStudioAddEditionValidator),
asyncMiddleware(createEditionTasks)
)
// ---------------------------------------------------------------------------
export {
studioRouter
}
// ---------------------------------------------------------------------------
async function createEditionTasks (req: express.Request, res: express.Response) {
const files = req.files as Express.Multer.File[]
const body = req.body as VideoStudioCreateEdition
const video = res.locals.videoAll
video.state = VideoState.TO_EDIT
await video.save()
const payload = {
videoUUID: video.uuid,
tasks: await Bluebird.mapSeries(body.tasks, (t, i) => buildTaskPayload(t, i, files))
}
await createVideoStudioJob({
user: res.locals.oauth.token.User,
payload,
video
})
return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
}
const taskPayloadBuilders: {
[id in VideoStudioTask['name']]: (
task: VideoStudioTask,
indice?: number,
files?: Express.Multer.File[]
) => Promise<VideoStudioTaskPayload>
} = {
'add-intro': buildIntroOutroTask,
'add-outro': buildIntroOutroTask,
'cut': buildCutTask,
'add-watermark': buildWatermarkTask
}
function buildTaskPayload (task: VideoStudioTask, indice: number, files: Express.Multer.File[]): Promise<VideoStudioTaskPayload> {
return taskPayloadBuilders[task.name](task, indice, files)
}
async function buildIntroOutroTask (task: VideoStudioTaskIntro | VideoStudioTaskOutro, indice: number, files: Express.Multer.File[]) {
const destination = await moveStudioFileToPersistentTMP(getTaskFileFromReq(files, indice).path)
return {
name: task.name,
options: {
file: destination
}
}
}
function buildCutTask (task: VideoStudioTaskCut) {
return Promise.resolve({
name: task.name,
options: {
start: task.options.start,
end: task.options.end
}
})
}
async function buildWatermarkTask (task: VideoStudioTaskWatermark, indice: number, files: Express.Multer.File[]) {
const destination = await moveStudioFileToPersistentTMP(getTaskFileFromReq(files, indice).path)
return {
name: task.name,
options: {
file: destination,
watermarkSizeRatio: VIDEO_FILTERS.WATERMARK.SIZE_RATIO,
horitonzalMarginRatio: VIDEO_FILTERS.WATERMARK.HORIZONTAL_MARGIN_RATIO,
verticalMarginRatio: VIDEO_FILTERS.WATERMARK.VERTICAL_MARGIN_RATIO
}
}
}
async function moveStudioFileToPersistentTMP (file: string) {
const destination = getStudioTaskFilePath(basename(file))
await move(file, destination)
return destination
}
+33
ファイルの表示
@@ -0,0 +1,33 @@
import express from 'express'
import { VideoTokensManager } from '@server/lib/video-tokens-manager.js'
import { VideoPrivacy, VideoToken } from '@peertube/peertube-models'
import { asyncMiddleware, optionalAuthenticate, videoFileTokenValidator, videosCustomGetValidator } from '../../../middlewares/index.js'
const tokenRouter = express.Router()
tokenRouter.post('/:id/token',
optionalAuthenticate,
asyncMiddleware(videosCustomGetValidator('only-video-and-blacklist')),
videoFileTokenValidator,
generateToken
)
// ---------------------------------------------------------------------------
export {
tokenRouter
}
// ---------------------------------------------------------------------------
function generateToken (req: express.Request, res: express.Response) {
const video = res.locals.onlyVideo
const files = video.privacy === VideoPrivacy.PASSWORD_PROTECTED
? VideoTokensManager.Instance.createForPasswordProtectedVideo({ videoUUID: video.uuid })
: VideoTokensManager.Instance.createForAuthUser({ videoUUID: video.uuid, user: res.locals.oauth.token.User })
return res.json({
files
} as VideoToken)
}
+60
ファイルの表示
@@ -0,0 +1,60 @@
import express from 'express'
import { logger, loggerTagsFactory } from '@server/helpers/logger.js'
import { Hooks } from '@server/lib/plugins/hooks.js'
import { createTranscodingJobs } from '@server/lib/transcoding/create-transcoding-job.js'
import { computeResolutionsToTranscode } from '@server/lib/transcoding/transcoding-resolutions.js'
import { VideoJobInfoModel } from '@server/models/video/video-job-info.js'
import { HttpStatusCode, UserRight, VideoState, VideoTranscodingCreate } from '@peertube/peertube-models'
import { asyncMiddleware, authenticate, createTranscodingValidator, ensureUserHasRight } from '../../../middlewares/index.js'
const lTags = loggerTagsFactory('api', 'video')
const transcodingRouter = express.Router()
transcodingRouter.post('/:videoId/transcoding',
authenticate,
ensureUserHasRight(UserRight.RUN_VIDEO_TRANSCODING),
asyncMiddleware(createTranscodingValidator),
asyncMiddleware(createTranscoding)
)
// ---------------------------------------------------------------------------
export {
transcodingRouter
}
// ---------------------------------------------------------------------------
async function createTranscoding (req: express.Request, res: express.Response) {
const video = res.locals.videoAll
logger.info('Creating %s transcoding job for %s.', req.body.transcodingType, video.url, lTags())
const body: VideoTranscodingCreate = req.body
await VideoJobInfoModel.abortAllTasks(video.uuid, 'pendingTranscode')
const { resolution: maxResolution, hasAudio } = await video.probeMaxQualityFile()
const resolutions = await Hooks.wrapObject(
computeResolutionsToTranscode({ input: maxResolution, type: 'vod', includeInput: true, strictLower: false, hasAudio }),
'filter:transcoding.manual.resolutions-to-transcode.result',
body
)
if (resolutions.length === 0) {
return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
}
video.state = VideoState.TO_TRANSCODE
await video.save()
await createTranscodingJobs({
video,
resolutions,
transcodingType: body.transcodingType,
isNewVideo: false,
user: null // Don't specify priority since these transcoding jobs are fired by the admin
})
return res.sendStatus(HttpStatusCode.NO_CONTENT_204)
}
+271
ファイルの表示
@@ -0,0 +1,271 @@
import { forceNumber } from '@peertube/peertube-core-utils'
import { HttpStatusCode, ThumbnailType, VideoCommentPolicy, VideoPrivacy, VideoPrivacyType, VideoUpdate } from '@peertube/peertube-models'
import { exists } from '@server/helpers/custom-validators/misc.js'
import { changeVideoChannelShare } from '@server/lib/activitypub/share.js'
import { isNewVideoPrivacyForFederation, isPrivacyForFederation } from '@server/lib/activitypub/videos/federate.js'
import { AutomaticTagger } from '@server/lib/automatic-tags/automatic-tagger.js'
import { setAndSaveVideoAutomaticTags } from '@server/lib/automatic-tags/automatic-tags.js'
import { updateLocalVideoMiniatureFromExisting } from '@server/lib/thumbnail.js'
import { replaceChaptersFromDescriptionIfNeeded } from '@server/lib/video-chapters.js'
import { addVideoJobsAfterUpdate } from '@server/lib/video-jobs.js'
import { VideoPathManager } from '@server/lib/video-path-manager.js'
import { setVideoPrivacy } from '@server/lib/video-privacy.js'
import { setVideoTags } from '@server/lib/video.js'
import { openapiOperationDoc } from '@server/middlewares/doc.js'
import { VideoPasswordModel } from '@server/models/video/video-password.js'
import { FilteredModelAttributes } from '@server/types/index.js'
import { MVideoFullLight, MVideoThumbnail } from '@server/types/models/index.js'
import express, { UploadFiles } from 'express'
import { Transaction } from 'sequelize'
import { VideoAuditView, auditLoggerFactory, getAuditIdFromRes } from '../../../helpers/audit-logger.js'
import { resetSequelizeInstance } from '../../../helpers/database-utils.js'
import { createReqFiles } from '../../../helpers/express-utils.js'
import { logger, loggerTagsFactory } from '../../../helpers/logger.js'
import { MIMETYPES } from '../../../initializers/constants.js'
import { sequelizeTypescript } from '../../../initializers/database.js'
import { Hooks } from '../../../lib/plugins/hooks.js'
import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist.js'
import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate, videosUpdateValidator } from '../../../middlewares/index.js'
import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update.js'
import { VideoModel } from '../../../models/video/video.js'
const lTags = loggerTagsFactory('api', 'video')
const auditLogger = auditLoggerFactory('videos')
const updateRouter = express.Router()
const reqVideoFileUpdate = createReqFiles([ 'thumbnailfile', 'previewfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT)
updateRouter.put('/:id',
openapiOperationDoc({ operationId: 'putVideo' }),
authenticate,
reqVideoFileUpdate,
asyncMiddleware(videosUpdateValidator),
asyncRetryTransactionMiddleware(updateVideo)
)
// ---------------------------------------------------------------------------
export {
updateRouter
}
// ---------------------------------------------------------------------------
async function updateVideo (req: express.Request, res: express.Response) {
const videoFromReq = res.locals.videoAll
const oldVideoAuditView = new VideoAuditView(videoFromReq.toFormattedDetailsJSON())
const videoInfoToUpdate: VideoUpdate = req.body
const hadPrivacyForFederation = isPrivacyForFederation(videoFromReq.privacy)
const oldPrivacy = videoFromReq.privacy
const thumbnails = await buildVideoThumbnailsFromReq(videoFromReq, req.files)
const videoFileLockReleaser = await VideoPathManager.Instance.lockFiles(videoFromReq.uuid)
try {
const { videoInstanceUpdated, isNewVideoForFederation } = await sequelizeTypescript.transaction(async t => {
// Refresh video since thumbnails to prevent concurrent updates
const video = await VideoModel.loadFull(videoFromReq.id, t)
const oldName = video.name
const oldDescription = video.description
const oldVideoChannel = video.VideoChannel
const keysToUpdate: (keyof VideoUpdate & FilteredModelAttributes<VideoModel>)[] = [
'name',
'category',
'licence',
'language',
'nsfw',
'waitTranscoding',
'support',
'description',
'downloadEnabled'
]
for (const key of keysToUpdate) {
if (videoInfoToUpdate[key] !== undefined) video.set(key, videoInfoToUpdate[key])
}
// Special treatment for comments policy to support deprecated commentsEnabled attribute
if (videoInfoToUpdate.commentsPolicy !== undefined) {
video.commentsPolicy = videoInfoToUpdate.commentsPolicy
} else if (videoInfoToUpdate.commentsEnabled === true) {
video.commentsPolicy = VideoCommentPolicy.ENABLED
} else if (videoInfoToUpdate.commentsEnabled === false) {
video.commentsPolicy = VideoCommentPolicy.DISABLED
}
if (videoInfoToUpdate.originallyPublishedAt !== undefined) {
video.originallyPublishedAt = videoInfoToUpdate.originallyPublishedAt
? new Date(videoInfoToUpdate.originallyPublishedAt)
: null
}
// Privacy update?
let isNewVideoForFederation = false
if (videoInfoToUpdate.privacy !== undefined) {
isNewVideoForFederation = await updateVideoPrivacy({
videoInstance: video,
videoInfoToUpdate,
hadPrivacyForFederation,
transaction: t
})
}
// Force updatedAt attribute change
if (!video.changed()) {
await video.setAsRefreshed(t)
}
const videoInstanceUpdated = await video.save({ transaction: t }) as MVideoFullLight
// Thumbnail & preview updates?
for (const thumbnail of thumbnails) {
await videoInstanceUpdated.addAndSaveThumbnail(thumbnail, t)
}
// Video tags update?
if (videoInfoToUpdate.tags !== undefined) {
await setVideoTags({ video: videoInstanceUpdated, tags: videoInfoToUpdate.tags, transaction: t })
}
// Video channel update?
if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
videoInstanceUpdated.VideoChannel = res.locals.videoChannel
if (hadPrivacyForFederation === true) {
await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
}
}
// Schedule an update in the future?
await updateSchedule(videoInstanceUpdated, videoInfoToUpdate, t)
if (oldDescription !== video.description) {
await replaceChaptersFromDescriptionIfNeeded({
newDescription: videoInstanceUpdated.description,
transaction: t,
video,
oldDescription
})
}
if (oldName !== video.name || oldDescription !== video.description) {
const automaticTags = await new AutomaticTagger().buildVideoAutomaticTags({ video, transaction: t })
await setAndSaveVideoAutomaticTags({ video, automaticTags, transaction: t })
}
await autoBlacklistVideoIfNeeded({
video: videoInstanceUpdated,
user: res.locals.oauth.token.User,
isRemote: false,
isNew: false,
isNewFile: false,
transaction: t
})
auditLogger.update(
getAuditIdFromRes(res),
new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
oldVideoAuditView
)
logger.info('Video with name %s and uuid %s updated.', video.name, video.uuid, lTags(video.uuid))
return { videoInstanceUpdated, isNewVideoForFederation }
})
Hooks.runAction('action:api.video.updated', { video: videoInstanceUpdated, body: req.body, req, res })
await addVideoJobsAfterUpdate({
video: videoInstanceUpdated,
nameChanged: !!videoInfoToUpdate.name,
oldPrivacy,
isNewVideoForFederation
})
} catch (err) {
// If the transaction is retried, sequelize will think the object has not changed
// So we need to restore the previous fields
await resetSequelizeInstance(videoFromReq)
throw err
} finally {
videoFileLockReleaser()
}
return res.type('json')
.status(HttpStatusCode.NO_CONTENT_204)
.end()
}
// Return a boolean indicating if the video is considered as "new" for remote instances in the federation
async function updateVideoPrivacy (options: {
videoInstance: MVideoFullLight
videoInfoToUpdate: VideoUpdate
hadPrivacyForFederation: boolean
transaction: Transaction
}) {
const { videoInstance, videoInfoToUpdate, hadPrivacyForFederation, transaction } = options
const isNewVideoForFederation = isNewVideoPrivacyForFederation(videoInstance.privacy, videoInfoToUpdate.privacy)
const newPrivacy = forceNumber(videoInfoToUpdate.privacy) as VideoPrivacyType
setVideoPrivacy(videoInstance, newPrivacy)
// Delete passwords if video is not anymore password protected
if (videoInstance.privacy === VideoPrivacy.PASSWORD_PROTECTED && newPrivacy !== VideoPrivacy.PASSWORD_PROTECTED) {
await VideoPasswordModel.deleteAllPasswords(videoInstance.id, transaction)
}
if (newPrivacy === VideoPrivacy.PASSWORD_PROTECTED && exists(videoInfoToUpdate.videoPasswords)) {
await VideoPasswordModel.deleteAllPasswords(videoInstance.id, transaction)
await VideoPasswordModel.addPasswords(videoInfoToUpdate.videoPasswords, videoInstance.id, transaction)
}
// Unfederate the video if the new privacy is not compatible with federation
if (hadPrivacyForFederation && !isPrivacyForFederation(videoInstance.privacy)) {
await VideoModel.sendDelete(videoInstance, { transaction })
}
return isNewVideoForFederation
}
function updateSchedule (videoInstance: MVideoFullLight, videoInfoToUpdate: VideoUpdate, transaction: Transaction) {
if (videoInfoToUpdate.scheduleUpdate) {
return ScheduleVideoUpdateModel.upsert({
videoId: videoInstance.id,
updateAt: new Date(videoInfoToUpdate.scheduleUpdate.updateAt),
privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
}, { transaction })
} else if (videoInfoToUpdate.scheduleUpdate === null) {
return ScheduleVideoUpdateModel.deleteByVideoId(videoInstance.id, transaction)
}
}
async function buildVideoThumbnailsFromReq (video: MVideoThumbnail, files: UploadFiles) {
const promises = [
{
type: ThumbnailType.MINIATURE,
fieldName: 'thumbnailfile'
},
{
type: ThumbnailType.PREVIEW,
fieldName: 'previewfile'
}
].map(p => {
const fields = files?.[p.fieldName]
if (!fields) return undefined
return updateLocalVideoMiniatureFromExisting({
inputPath: fields[0].path,
video,
type: p.type,
automaticallyGenerated: false
})
})
const thumbnailsOrUndefined = await Promise.all(promises)
return thumbnailsOrUndefined.filter(t => !!t)
}
+180
ファイルの表示
@@ -0,0 +1,180 @@
import { ffprobePromise, getChaptersFromContainer } from '@peertube/peertube-ffmpeg'
import { ThumbnailType, VideoCreate } from '@peertube/peertube-models'
import { uuidToShort } from '@peertube/peertube-node-utils'
import { getResumableUploadPath } from '@server/helpers/upload.js'
import { LocalVideoCreator } from '@server/lib/local-video-creator.js'
import { Redis } from '@server/lib/redis.js'
import { setupUploadResumableRoutes, uploadx } from '@server/lib/uploadx.js'
import { buildNextVideoState } from '@server/lib/video-state.js'
import { openapiOperationDoc } from '@server/middlewares/doc.js'
import express from 'express'
import { VideoAuditView, auditLoggerFactory, getAuditIdFromRes } from '../../../helpers/audit-logger.js'
import { createReqFiles } from '../../../helpers/express-utils.js'
import { logger, loggerTagsFactory } from '../../../helpers/logger.js'
import { CONSTRAINTS_FIELDS, MIMETYPES } from '../../../initializers/constants.js'
import { Hooks } from '../../../lib/plugins/hooks.js'
import {
asyncMiddleware,
asyncRetryTransactionMiddleware,
authenticate,
setReqTimeout,
videosAddLegacyValidator,
videosAddResumableInitValidator,
videosAddResumableValidator
} from '../../../middlewares/index.js'
const lTags = loggerTagsFactory('api', 'video')
const auditLogger = auditLoggerFactory('videos')
const uploadRouter = express.Router()
const reqVideoFileAdd = createReqFiles(
[ 'videofile', 'thumbnailfile', 'previewfile' ],
{ ...MIMETYPES.VIDEO.MIMETYPE_EXT, ...MIMETYPES.IMAGE.MIMETYPE_EXT }
)
const reqVideoFileAddResumable = createReqFiles(
[ 'thumbnailfile', 'previewfile' ],
MIMETYPES.IMAGE.MIMETYPE_EXT,
getResumableUploadPath()
)
uploadRouter.post('/upload',
openapiOperationDoc({ operationId: 'uploadLegacy' }),
authenticate,
setReqTimeout(1000 * 60 * 10), // Uploading the video could be long
reqVideoFileAdd,
asyncMiddleware(videosAddLegacyValidator),
asyncRetryTransactionMiddleware(addVideoLegacy)
)
setupUploadResumableRoutes({
routePath: '/upload-resumable',
router: uploadRouter,
uploadInitBeforeMiddlewares: [
openapiOperationDoc({ operationId: 'uploadResumableInit' }),
reqVideoFileAddResumable
],
uploadInitAfterMiddlewares: [ asyncMiddleware(videosAddResumableInitValidator) ],
uploadDeleteMiddlewares: [ asyncMiddleware(deleteUploadResumableCache) ],
uploadedMiddlewares: [
openapiOperationDoc({ operationId: 'uploadResumable' }),
asyncMiddleware(videosAddResumableValidator)
],
uploadedController: asyncMiddleware(addVideoResumable)
})
// ---------------------------------------------------------------------------
export {
uploadRouter
}
// ---------------------------------------------------------------------------
async function addVideoLegacy (req: express.Request, res: express.Response) {
const videoPhysicalFile = req.files['videofile'][0]
const videoInfo: VideoCreate = req.body
const files = req.files
const response = await addVideo({ req, res, videoPhysicalFile, videoInfo, files })
return res.json(response)
}
async function addVideoResumable (req: express.Request, res: express.Response) {
const videoPhysicalFile = res.locals.uploadVideoFileResumable
const videoInfo = videoPhysicalFile.metadata
const files = { previewfile: videoInfo.previewfile, thumbnailfile: videoInfo.thumbnailfile }
const response = await addVideo({ req, res, videoPhysicalFile, videoInfo, files })
await Redis.Instance.deleteUploadSession(req.query.upload_id)
await uploadx.storage.delete(res.locals.uploadVideoFileResumable)
return res.json(response)
}
async function addVideo (options: {
req: express.Request
res: express.Response
videoPhysicalFile: express.VideoLegacyUploadFile
videoInfo: VideoCreate
files: express.UploadFiles
}) {
const { req, res, videoPhysicalFile, videoInfo, files } = options
const ffprobe = await ffprobePromise(videoPhysicalFile.path)
const containerChapters = await getChaptersFromContainer({
path: videoPhysicalFile.path,
maxTitleLength: CONSTRAINTS_FIELDS.VIDEO_CHAPTERS.TITLE.max,
ffprobe
})
logger.debug(`Got ${containerChapters.length} chapters from video "${videoInfo.name}" container`, { containerChapters, ...lTags() })
const thumbnails = [ { type: ThumbnailType.MINIATURE, field: 'thumbnailfile' }, { type: ThumbnailType.PREVIEW, field: 'previewfile' } ]
.filter(({ field }) => !!files?.[field]?.[0])
.map(({ type, field }) => ({
path: files[field][0].path,
type,
automaticallyGenerated: false,
keepOriginal: false
}))
const localVideoCreator = new LocalVideoCreator({
lTags,
videoFile: {
path: videoPhysicalFile.path,
probe: res.locals.ffprobe
},
user: res.locals.oauth.token.User,
channel: res.locals.videoChannel,
chapters: undefined,
fallbackChapters: {
fromDescription: true,
finalFallback: containerChapters
},
videoAttributes: {
...videoInfo,
duration: videoPhysicalFile.duration,
inputFilename: videoPhysicalFile.originalname,
state: buildNextVideoState(),
isLive: false
},
liveAttributes: undefined,
videoAttributeResultHook: 'filter:api.video.upload.video-attribute.result',
thumbnails
})
const { video } = await localVideoCreator.create()
auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(video.toFormattedDetailsJSON()))
logger.info('Video with name %s and uuid %s created.', videoInfo.name, video.uuid, lTags(video.uuid))
Hooks.runAction('action:api.video.uploaded', { video, req, res })
return {
video: {
id: video.id,
shortUUID: uuidToShort(video.uuid),
uuid: video.uuid
}
}
}
async function deleteUploadResumableCache (req: express.Request, res: express.Response, next: express.NextFunction) {
await Redis.Instance.deleteUploadSession(req.query.upload_id)
return next()
}
+67
ファイルの表示
@@ -0,0 +1,67 @@
import express from 'express'
import { HttpStatusCode, VideoView } from '@peertube/peertube-models'
import { Hooks } from '@server/lib/plugins/hooks.js'
import { VideoViewsManager } from '@server/lib/views/video-views-manager.js'
import { MVideoId } from '@server/types/models/index.js'
import {
asyncMiddleware,
methodsValidator,
openapiOperationDoc,
optionalAuthenticate,
videoViewValidator
} from '../../../middlewares/index.js'
import { UserVideoHistoryModel } from '../../../models/user/user-video-history.js'
const viewRouter = express.Router()
viewRouter.all(
[ '/:videoId/views', '/:videoId/watching' ],
openapiOperationDoc({ operationId: 'addView' }),
methodsValidator([ 'PUT', 'POST' ]),
optionalAuthenticate,
asyncMiddleware(videoViewValidator),
asyncMiddleware(viewVideo)
)
// ---------------------------------------------------------------------------
export {
viewRouter
}
// ---------------------------------------------------------------------------
async function viewVideo (req: express.Request, res: express.Response) {
const video = res.locals.onlyImmutableVideo
const body = req.body as VideoView
const ip = req.ip
const { successView } = await VideoViewsManager.Instance.processLocalView({
video,
ip,
currentTime: body.currentTime,
viewEvent: body.viewEvent,
sessionId: body.sessionId
})
if (successView) {
Hooks.runAction('action:api.video.viewed', { video, ip, req, res })
}
await updateUserHistoryIfNeeded(body, video, res)
return res.status(HttpStatusCode.NO_CONTENT_204).end()
}
async function updateUserHistoryIfNeeded (body: VideoView, video: MVideoId, res: express.Response) {
const user = res.locals.oauth?.token.User
if (!user) return
if (user.videosHistoryEnabled !== true) return
await UserVideoHistoryModel.upsert({
videoId: video.id,
userId: user.id,
currentTime: body.currentTime
})
}