From e024fd6a7494b37251da1d59470324305cdb4129 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Fri, 7 May 2021 17:14:39 +0200 Subject: Update channel updatedAt when uploading a video --- server/controllers/api/videos/index.ts | 3 +++ 1 file changed, 3 insertions(+) (limited to 'server/controllers/api/videos') diff --git a/server/controllers/api/videos/index.ts b/server/controllers/api/videos/index.ts index 6ec6478e4..fbdb0f776 100644 --- a/server/controllers/api/videos/index.ts +++ b/server/controllers/api/videos/index.ts @@ -248,6 +248,9 @@ async function addVideo (req: express.Request, res: express.Response) { }, { transaction: t }) } + // Channel has a new content, set as updated + await videoCreated.VideoChannel.setAsUpdated(t) + await autoBlacklistVideoIfNeeded({ video, user: res.locals.oauth.token.User, -- cgit v1.2.3 From f6d6e7f861189a4446f406efb775a29688764b48 Mon Sep 17 00:00:00 2001 From: kontrollanten <6680299+kontrollanten@users.noreply.github.com> Date: Mon, 10 May 2021 11:13:41 +0200 Subject: Resumable video uploads (#3933) * WIP: resumable video uploads relates to #324 * fix review comments * video upload: error handling * fix audio upload * fixes after self review * Update server/controllers/api/videos/index.ts Co-authored-by: Rigel Kent * Update server/middlewares/validators/videos/videos.ts Co-authored-by: Rigel Kent * Update server/controllers/api/videos/index.ts Co-authored-by: Rigel Kent * update after code review * refactor upload route - restore multipart upload route - move resumable to dedicated upload-resumable route - move checks to middleware - do not leak internal fs structure in response * fix yarn.lock upon rebase * factorize addVideo for reuse in both endpoints * add resumable upload API to openapi spec * add initial test and test helper for resumable upload * typings for videoAddResumable middleware * avoid including aws and google packages via node-uploadx, by only including uploadx/core * rename ex-isAudioBg to more explicit name mentioning it is a preview file for audio * add video-upload-tmp-folder-cleaner job * stronger typing of video upload middleware * reduce dependency to @uploadx/core * add audio upload test * refactor resumable uploads cleanup from job to scheduler * refactor resumable uploads scheduler to compare to last execution time * make resumable upload validator to always cleanup on failure * move legacy upload request building outside of uploadVideo test helper * filter upload-resumable middlewares down to POST, PUT, DELETE also begin to type metadata * merge add duration functions * stronger typings and documentation for uploadx behaviour, move init validator up * refactor(client/video-edit): options > uploadxOptions * refactor(client/video-edit): remove obsolete else * scheduler/remove-dangling-resum: rename tag * refactor(server/video): add UploadVideoFiles type * refactor(mw/validators): restructure eslint disable * refactor(mw/validators/videos): rename import * refactor(client/vid-upload): rename html elem id * refactor(sched/remove-dangl): move fn to method * refactor(mw/async): add method typing * refactor(mw/vali/video): double quote > single * refactor(server/upload-resum): express use > all * proper http methud enum server/middlewares/async.ts * properly type http methods * factorize common video upload validation steps * add check for maximum partially uploaded file size * fix audioBg use * fix extname(filename) in addVideo * document parameters for uploadx's resumable protocol * clear META files in scheduler * last audio refactor before cramming preview in the initial POST form data * refactor as mulitpart/form-data initial post request this allows preview/thumbnail uploads alongside the initial request, and cleans up the upload form * Add more tests for resumable uploads * Refactor remove dangling resumable uploads * Prepare changelog * Add more resumable upload tests * Remove user quota check for resumable uploads * Fix upload error handler * Update nginx template for upload-resumable * Cleanup comment * Remove unused express methods * Prefer to use got instead of raw http * Don't retry on error 500 Co-authored-by: Rigel Kent Co-authored-by: Rigel Kent Co-authored-by: Chocobozzz --- server/controllers/api/videos/index.ts | 105 ++++++++++++++++++++++++++------- 1 file changed, 85 insertions(+), 20 deletions(-) (limited to 'server/controllers/api/videos') diff --git a/server/controllers/api/videos/index.ts b/server/controllers/api/videos/index.ts index fbdb0f776..c32626d30 100644 --- a/server/controllers/api/videos/index.ts +++ b/server/controllers/api/videos/index.ts @@ -2,6 +2,7 @@ import * as express from 'express' import { move } from 'fs-extra' import { extname } from 'path' import toInt from 'validator/lib/toInt' +import { deleteResumableUploadMetaFile, getResumableUploadPath } from '@server/helpers/upload' import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent' import { changeVideoChannelShare } from '@server/lib/activitypub/share' import { getLocalVideoActivityPubUrl } from '@server/lib/activitypub/url' @@ -10,8 +11,9 @@ import { addOptimizeOrMergeAudioJob, buildLocalVideoFromReq, buildVideoThumbnail import { generateVideoFilename, getVideoFilePath } from '@server/lib/video-paths' import { getServerActor } from '@server/models/application/application' import { MVideo, MVideoFile, MVideoFullLight } from '@server/types/models' +import { uploadx } from '@uploadx/core' import { VideoCreate, VideosCommonQuery, VideoState, VideoUpdate } from '../../../../shared' -import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs' import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger' import { resetSequelizeInstance, retryTransactionWrapper } from '../../../helpers/database-utils' import { buildNSFWFilter, createReqFiles, getCountVideos } from '../../../helpers/express-utils' @@ -47,7 +49,9 @@ import { setDefaultPagination, setDefaultVideosSort, videoFileMetadataGetValidator, - videosAddValidator, + videosAddLegacyValidator, + videosAddResumableInitValidator, + videosAddResumableValidator, videosCustomGetValidator, videosGetValidator, videosRemoveValidator, @@ -69,6 +73,7 @@ import { watchingRouter } from './watching' const lTags = loggerTagsFactory('api', 'video') const auditLogger = auditLoggerFactory('videos') const videosRouter = express.Router() +const uploadxMiddleware = uploadx.upload({ directory: getResumableUploadPath() }) const reqVideoFileAdd = createReqFiles( [ 'videofile', 'thumbnailfile', 'previewfile' ], @@ -79,6 +84,16 @@ const reqVideoFileAdd = createReqFiles( previewfile: CONFIG.STORAGE.TMP_DIR } ) + +const reqVideoFileAddResumable = createReqFiles( + [ 'thumbnailfile', 'previewfile' ], + MIMETYPES.IMAGE.MIMETYPE_EXT, + { + thumbnailfile: getResumableUploadPath(), + previewfile: getResumableUploadPath() + } +) + const reqVideoFileUpdate = createReqFiles( [ 'thumbnailfile', 'previewfile' ], MIMETYPES.IMAGE.MIMETYPE_EXT, @@ -111,18 +126,39 @@ videosRouter.get('/', commonVideosFiltersValidator, asyncMiddleware(listVideos) ) + +videosRouter.post('/upload', + authenticate, + reqVideoFileAdd, + asyncMiddleware(videosAddLegacyValidator), + asyncRetryTransactionMiddleware(addVideoLegacy) +) + +videosRouter.post('/upload-resumable', + authenticate, + reqVideoFileAddResumable, + asyncMiddleware(videosAddResumableInitValidator), + uploadxMiddleware +) + +videosRouter.delete('/upload-resumable', + authenticate, + uploadxMiddleware +) + +videosRouter.put('/upload-resumable', + authenticate, + uploadxMiddleware, // uploadx doesn't use call next() before the file upload completes + asyncMiddleware(videosAddResumableValidator), + asyncMiddleware(addVideoResumable) +) + videosRouter.put('/:id', authenticate, reqVideoFileUpdate, asyncMiddleware(videosUpdateValidator), asyncRetryTransactionMiddleware(updateVideo) ) -videosRouter.post('/upload', - authenticate, - reqVideoFileAdd, - asyncMiddleware(videosAddValidator), - asyncRetryTransactionMiddleware(addVideo) -) videosRouter.get('/:id/description', asyncMiddleware(videosGetValidator), @@ -157,23 +193,23 @@ export { // --------------------------------------------------------------------------- -function listVideoCategories (req: express.Request, res: express.Response) { +function listVideoCategories (_req: express.Request, res: express.Response) { res.json(VIDEO_CATEGORIES) } -function listVideoLicences (req: express.Request, res: express.Response) { +function listVideoLicences (_req: express.Request, res: express.Response) { res.json(VIDEO_LICENCES) } -function listVideoLanguages (req: express.Request, res: express.Response) { +function listVideoLanguages (_req: express.Request, res: express.Response) { res.json(VIDEO_LANGUAGES) } -function listVideoPrivacies (req: express.Request, res: express.Response) { +function listVideoPrivacies (_req: express.Request, res: express.Response) { res.json(VIDEO_PRIVACIES) } -async function addVideo (req: express.Request, res: express.Response) { +async function addVideoLegacy (req: express.Request, res: express.Response) { // Uploading the video could be long // Set timeout to 10 minutes, as Express's default is 2 minutes req.setTimeout(1000 * 60 * 10, () => { @@ -183,13 +219,42 @@ async function addVideo (req: express.Request, res: express.Response) { const videoPhysicalFile = req.files['videofile'][0] const videoInfo: VideoCreate = req.body + const files = req.files + + return addVideo({ res, videoPhysicalFile, videoInfo, files }) +} + +async function addVideoResumable (_req: express.Request, res: express.Response) { + const videoPhysicalFile = res.locals.videoFileResumable + const videoInfo = videoPhysicalFile.metadata + const files = { previewfile: videoInfo.previewfile } + + // Don't need the meta file anymore + await deleteResumableUploadMetaFile(videoPhysicalFile.path) + + return addVideo({ res, videoPhysicalFile, videoInfo, files }) +} - const videoData = buildLocalVideoFromReq(videoInfo, res.locals.videoChannel.id) - videoData.state = CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED - videoData.duration = videoPhysicalFile['duration'] // duration was added by a previous middleware +async function addVideo (options: { + res: express.Response + videoPhysicalFile: express.VideoUploadFile + videoInfo: VideoCreate + files: express.UploadFiles +}) { + const { res, videoPhysicalFile, videoInfo, files } = options + const videoChannel = res.locals.videoChannel + const user = res.locals.oauth.token.User + + const videoData = buildLocalVideoFromReq(videoInfo, videoChannel.id) + + videoData.state = CONFIG.TRANSCODING.ENABLED + ? VideoState.TO_TRANSCODE + : VideoState.PUBLISHED + + videoData.duration = videoPhysicalFile.duration // duration was added by a previous middleware const video = new VideoModel(videoData) as MVideoFullLight - video.VideoChannel = res.locals.videoChannel + video.VideoChannel = videoChannel video.url = getLocalVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object const videoFile = new VideoFileModel({ @@ -217,7 +282,7 @@ async function addVideo (req: express.Request, res: express.Response) { const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({ video, - files: req.files, + files, fallback: type => generateVideoMiniature({ video, videoFile, type }) }) @@ -253,7 +318,7 @@ async function addVideo (req: express.Request, res: express.Response) { await autoBlacklistVideoIfNeeded({ video, - user: res.locals.oauth.token.User, + user, isRemote: false, isNew: true, transaction: t @@ -282,7 +347,7 @@ async function addVideo (req: express.Request, res: express.Response) { .catch(err => logger.error('Cannot federate or notify video creation %s', video.url, { err, ...lTags(video.uuid) })) if (video.state === VideoState.TO_TRANSCODE) { - await addOptimizeOrMergeAudioJob(videoCreated, videoFile, res.locals.oauth.token.User) + await addOptimizeOrMergeAudioJob(videoCreated, videoFile, user) } Hooks.runAction('action:api.video.uploaded', { video: videoCreated }) -- cgit v1.2.3 From 1bcb03a100d172903b877d6a0e4ed11d63b14f3d Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Tue, 11 May 2021 10:54:05 +0200 Subject: Use a class for youtube-dl --- server/controllers/api/videos/import.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) (limited to 'server/controllers/api/videos') diff --git a/server/controllers/api/videos/import.ts b/server/controllers/api/videos/import.ts index 3b9b887e2..37fd42b90 100644 --- a/server/controllers/api/videos/import.ts +++ b/server/controllers/api/videos/import.ts @@ -3,6 +3,7 @@ import { move, readFile } from 'fs-extra' import * as magnetUtil from 'magnet-uri' import * as parseTorrent from 'parse-torrent' import { join } from 'path' +import { getEnabledResolutions } from '@server/lib/config' import { setVideoTags } from '@server/lib/video' import { MChannelAccountDefault, @@ -24,7 +25,7 @@ import { isArray } from '../../../helpers/custom-validators/misc' import { createReqFiles } from '../../../helpers/express-utils' import { logger } from '../../../helpers/logger' import { getSecureTorrentName } from '../../../helpers/utils' -import { getYoutubeDLInfo, getYoutubeDLSubs, YoutubeDLInfo } from '../../../helpers/youtube-dl' +import { YoutubeDL, YoutubeDLInfo } from '../../../helpers/youtube-dl' import { CONFIG } from '../../../initializers/config' import { MIMETYPES } from '../../../initializers/constants' import { sequelizeTypescript } from '../../../initializers/database' @@ -139,10 +140,12 @@ async function addYoutubeDLImport (req: express.Request, res: express.Response) const targetUrl = body.targetUrl const user = res.locals.oauth.token.User + const youtubeDL = new YoutubeDL(targetUrl, getEnabledResolutions('vod')) + // Get video infos let youtubeDLInfo: YoutubeDLInfo try { - youtubeDLInfo = await getYoutubeDLInfo(targetUrl) + youtubeDLInfo = await youtubeDL.getYoutubeDLInfo() } catch (err) { logger.info('Cannot fetch information from import for URL %s.', targetUrl, { err }) @@ -188,7 +191,7 @@ async function addYoutubeDLImport (req: express.Request, res: express.Response) // Get video subtitles try { - const subtitles = await getYoutubeDLSubs(targetUrl) + const subtitles = await youtubeDL.getYoutubeDLSubs() logger.info('Will create %s subtitles from youtube import %s.', subtitles.length, targetUrl) -- cgit v1.2.3 From 7d9ba5c08999c6482f0bc5e0c09c6f55b7724090 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Tue, 11 May 2021 11:15:29 +0200 Subject: Cleanup models directory organization --- server/controllers/api/videos/watching.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'server/controllers/api/videos') diff --git a/server/controllers/api/videos/watching.ts b/server/controllers/api/videos/watching.ts index 627f12aa9..08190e583 100644 --- a/server/controllers/api/videos/watching.ts +++ b/server/controllers/api/videos/watching.ts @@ -1,7 +1,7 @@ import * as express from 'express' import { UserWatchingVideo } from '../../../../shared' import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate, videoWatchingValidator } from '../../../middlewares' -import { UserVideoHistoryModel } from '../../../models/account/user-video-history' +import { UserVideoHistoryModel } from '../../../models/user/user-video-history' import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' const watchingRouter = express.Router() -- cgit v1.2.3 From 2b02c520e66ea452687cab39401b371711caa9ed Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Tue, 11 May 2021 11:27:40 +0200 Subject: Cleanup shared models --- server/controllers/api/videos/comment.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'server/controllers/api/videos') diff --git a/server/controllers/api/videos/comment.ts b/server/controllers/api/videos/comment.ts index f1f53d354..cfdf2773f 100644 --- a/server/controllers/api/videos/comment.ts +++ b/server/controllers/api/videos/comment.ts @@ -1,7 +1,7 @@ import * as express from 'express' import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' import { ResultList, ThreadsResultList, UserRight } from '../../../../shared/models' -import { VideoCommentCreate } from '../../../../shared/models/videos/video-comment.model' +import { VideoCommentCreate } from '../../../../shared/models/videos/comment/video-comment.model' import { auditLoggerFactory, CommentAuditView, getAuditIdFromRes } from '../../../helpers/audit-logger' import { getFormattedObjects } from '../../../helpers/utils' import { sequelizeTypescript } from '../../../initializers/database' -- cgit v1.2.3 From 32985a0a779e0e2100a3990b1f1188645e58dfb1 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Tue, 11 May 2021 14:56:00 +0200 Subject: Error if importing a torrent with multiple files --- server/controllers/api/videos/import.ts | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) (limited to 'server/controllers/api/videos') diff --git a/server/controllers/api/videos/import.ts b/server/controllers/api/videos/import.ts index 37fd42b90..4ed58f978 100644 --- a/server/controllers/api/videos/import.ts +++ b/server/controllers/api/videos/import.ts @@ -16,13 +16,13 @@ import { MVideoWithBlacklistLight } from '@server/types/models' import { MVideoImport, MVideoImportFormattable } from '@server/types/models/video/video-import' -import { VideoImportCreate, VideoImportState, VideoPrivacy, VideoState } from '../../../../shared' +import { ServerErrorCode, VideoImportCreate, VideoImportState, VideoPrivacy, VideoState } from '../../../../shared' import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' import { ThumbnailType } from '../../../../shared/models/videos/thumbnail.type' import { auditLoggerFactory, getAuditIdFromRes, VideoImportAuditView } from '../../../helpers/audit-logger' import { moveAndProcessCaptionFile } from '../../../helpers/captions-utils' import { isArray } from '../../../helpers/custom-validators/misc' -import { createReqFiles } from '../../../helpers/express-utils' +import { cleanUpReqFiles, createReqFiles } from '../../../helpers/express-utils' import { logger } from '../../../helpers/logger' import { getSecureTorrentName } from '../../../helpers/utils' import { YoutubeDL, YoutubeDLInfo } from '../../../helpers/youtube-dl' @@ -86,13 +86,23 @@ async function addTorrentImport (req: express.Request, res: express.Response, to // Rename the torrent to a secured name const newTorrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, getSecureTorrentName(torrentName)) - await move(torrentfile.path, newTorrentPath) + await move(torrentfile.path, newTorrentPath, { overwrite: true }) torrentfile.path = newTorrentPath const buf = await readFile(torrentfile.path) - const parsedTorrent = parseTorrent(buf) + const parsedTorrent = parseTorrent(buf) as parseTorrent.Instance - videoName = isArray(parsedTorrent.name) ? parsedTorrent.name[0] : parsedTorrent.name as string + if (parsedTorrent.files.length !== 1) { + cleanUpReqFiles(req) + + return res.status(HttpStatusCode.BAD_REQUEST_400) + .json({ + code: ServerErrorCode.INCORRECT_FILES_IN_TORRENT, + error: 'Torrents with only 1 file are supported.' + }) + } + + videoName = isArray(parsedTorrent.name) ? parsedTorrent.name[0] : parsedTorrent.name } else { magnetUri = body.magnetUri -- cgit v1.2.3 From 16c016e8b1d5ca46343d3363f9a49e24c5d7c944 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Wed, 12 May 2021 14:09:04 +0200 Subject: Stricter models typing --- server/controllers/api/videos/import.ts | 9 ++++++--- server/controllers/api/videos/index.ts | 4 ++-- 2 files changed, 8 insertions(+), 5 deletions(-) (limited to 'server/controllers/api/videos') diff --git a/server/controllers/api/videos/import.ts b/server/controllers/api/videos/import.ts index 4ed58f978..2c225315c 100644 --- a/server/controllers/api/videos/import.ts +++ b/server/controllers/api/videos/import.ts @@ -5,6 +5,7 @@ import * as parseTorrent from 'parse-torrent' import { join } from 'path' import { getEnabledResolutions } from '@server/lib/config' import { setVideoTags } from '@server/lib/video' +import { FilteredModelAttributes } from '@server/types' import { MChannelAccountDefault, MThumbnail, @@ -15,7 +16,7 @@ import { MVideoThumbnail, MVideoWithBlacklistLight } from '@server/types/models' -import { MVideoImport, MVideoImportFormattable } from '@server/types/models/video/video-import' +import { MVideoImportFormattable } from '@server/types/models/video/video-import' import { ServerErrorCode, VideoImportCreate, VideoImportState, VideoPrivacy, VideoState } from '../../../../shared' import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' import { ThumbnailType } from '../../../../shared/models/videos/thumbnail.type' @@ -253,7 +254,9 @@ function buildVideo (channelId: number, body: VideoImportCreate, importData: You privacy: body.privacy || VideoPrivacy.PRIVATE, duration: 0, // duration will be set by the import job channelId: channelId, - originallyPublishedAt: body.originallyPublishedAt || importData.originallyPublishedAt + originallyPublishedAt: body.originallyPublishedAt + ? new Date(body.originallyPublishedAt) + : importData.originallyPublishedAt } const video = new VideoModel(videoData) video.url = getLocalVideoActivityPubUrl(video) @@ -317,7 +320,7 @@ async function insertIntoDB (parameters: { previewModel: MThumbnail videoChannel: MChannelAccountDefault tags: string[] - videoImportAttributes: Partial + videoImportAttributes: FilteredModelAttributes user: MUser }): Promise { const { video, thumbnailModel, previewModel, videoChannel, tags, videoImportAttributes, user } = parameters diff --git a/server/controllers/api/videos/index.ts b/server/controllers/api/videos/index.ts index c32626d30..f5ce15074 100644 --- a/server/controllers/api/videos/index.ts +++ b/server/controllers/api/videos/index.ts @@ -308,7 +308,7 @@ async function addVideo (options: { if (videoInfo.scheduleUpdate) { await ScheduleVideoUpdateModel.create({ videoId: video.id, - updateAt: videoInfo.scheduleUpdate.updateAt, + updateAt: new Date(videoInfo.scheduleUpdate.updateAt), privacy: videoInfo.scheduleUpdate.privacy || null }, { transaction: t }) } @@ -435,7 +435,7 @@ async function updateVideo (req: express.Request, res: express.Response) { if (videoInfoToUpdate.scheduleUpdate) { await ScheduleVideoUpdateModel.upsert({ videoId: videoInstanceUpdated.id, - updateAt: videoInfoToUpdate.scheduleUpdate.updateAt, + updateAt: new Date(videoInfoToUpdate.scheduleUpdate.updateAt), privacy: videoInfoToUpdate.scheduleUpdate.privacy || null }, { transaction: t }) } else if (videoInfoToUpdate.scheduleUpdate === null) { -- cgit v1.2.3 From c158a5faabb8ef0bc5d121fda4522d63603e8bc5 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Wed, 12 May 2021 14:51:17 +0200 Subject: Refactor a little bit controllers --- server/controllers/api/videos/import.ts | 160 +++++++----- server/controllers/api/videos/index.ts | 406 ++--------------------------- server/controllers/api/videos/ownership.ts | 4 +- server/controllers/api/videos/update.ts | 191 ++++++++++++++ server/controllers/api/videos/upload.ts | 269 +++++++++++++++++++ 5 files changed, 571 insertions(+), 459 deletions(-) create mode 100644 server/controllers/api/videos/update.ts create mode 100644 server/controllers/api/videos/upload.ts (limited to 'server/controllers/api/videos') diff --git a/server/controllers/api/videos/import.ts b/server/controllers/api/videos/import.ts index 2c225315c..ee63c7b77 100644 --- a/server/controllers/api/videos/import.ts +++ b/server/controllers/api/videos/import.ts @@ -83,32 +83,15 @@ async function addTorrentImport (req: express.Request, res: express.Response, to let magnetUri: string if (torrentfile) { - torrentName = torrentfile.originalname + const result = await processTorrentOrAbortRequest(req, res, torrentfile) + if (!result) return - // 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) - const parsedTorrent = parseTorrent(buf) as parseTorrent.Instance - - if (parsedTorrent.files.length !== 1) { - cleanUpReqFiles(req) - - return res.status(HttpStatusCode.BAD_REQUEST_400) - .json({ - code: ServerErrorCode.INCORRECT_FILES_IN_TORRENT, - error: 'Torrents with only 1 file are supported.' - }) - } - - videoName = isArray(parsedTorrent.name) ? parsedTorrent.name[0] : parsedTorrent.name + videoName = result.name + torrentName = result.torrentName } else { - magnetUri = body.magnetUri - - const parsed = magnetUtil.decode(magnetUri) - videoName = isArray(parsed.name) ? parsed.name[0] : parsed.name as string + const result = processMagnetURI(body) + magnetUri = result.magnetUri + videoName = result.name } const video = buildVideo(res.locals.videoChannel.id, body, { name: videoName }) @@ -116,26 +99,26 @@ async function addTorrentImport (req: express.Request, res: express.Response, to const thumbnailModel = await processThumbnail(req, video) const previewModel = await processPreview(req, video) - const tags = body.tags || undefined - const videoImportAttributes = { - magnetUri, - torrentName, - state: VideoImportState.PENDING, - userId: user.id - } const videoImport = await insertIntoDB({ video, thumbnailModel, previewModel, videoChannel: res.locals.videoChannel, - tags, - videoImportAttributes, - user + tags: body.tags || undefined, + user, + videoImportAttributes: { + magnetUri, + torrentName, + state: VideoImportState.PENDING, + userId: user.id + } }) // Create job to import the video const payload = { - type: torrentfile ? 'torrent-file' as 'torrent-file' : 'magnet-uri' as 'magnet-uri', + type: torrentfile + ? 'torrent-file' as 'torrent-file' + : 'magnet-uri' as 'magnet-uri', videoImportId: videoImport.id, magnetUri } @@ -184,45 +167,22 @@ async function addYoutubeDLImport (req: express.Request, res: express.Response) previewModel = await processPreviewFromUrl(youtubeDLInfo.thumbnailUrl, video) } - const tags = body.tags || youtubeDLInfo.tags - const videoImportAttributes = { - targetUrl, - state: VideoImportState.PENDING, - userId: user.id - } const videoImport = await insertIntoDB({ video, thumbnailModel, previewModel, videoChannel: res.locals.videoChannel, - tags, - videoImportAttributes, - user + tags: body.tags || youtubeDLInfo.tags, + user, + videoImportAttributes: { + targetUrl, + state: VideoImportState.PENDING, + userId: user.id + } }) // Get video subtitles - try { - const subtitles = await youtubeDL.getYoutubeDLSubs() - - logger.info('Will create %s subtitles from youtube import %s.', subtitles.length, targetUrl) - - for (const subtitle of subtitles) { - const videoCaption = new VideoCaptionModel({ - videoId: video.id, - language: subtitle.language, - filename: VideoCaptionModel.generateCaptionName(subtitle.language) - }) as MVideoCaption - - // Move physical file - await moveAndProcessCaptionFile(subtitle, videoCaption) - - await sequelizeTypescript.transaction(async t => { - await VideoCaptionModel.insertOrReplaceLanguage(videoCaption, t) - }) - } - } catch (err) { - logger.warn('Cannot get video subtitles.', { err }) - } + await processYoutubeSubtitles(youtubeDL, targetUrl, video.id) // Create job to import the video const payload = { @@ -358,3 +318,71 @@ async function insertIntoDB (parameters: { return videoImport } + +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) + const parsedTorrent = parseTorrent(buf) as parseTorrent.Instance + + if (parsedTorrent.files.length !== 1) { + cleanUpReqFiles(req) + + res.status(HttpStatusCode.BAD_REQUEST_400) + .json({ + code: ServerErrorCode.INCORRECT_FILES_IN_TORRENT, + error: '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 = magnetUtil.decode(magnetUri) + + return { + name: extractNameFromArray(parsed.name), + magnetUri + } +} + +function extractNameFromArray (name: string | string[]) { + return isArray(name) ? name[0] : name +} + +async function processYoutubeSubtitles (youtubeDL: YoutubeDL, targetUrl: string, videoId: number) { + try { + const subtitles = await youtubeDL.getYoutubeDLSubs() + + logger.info('Will create %s subtitles from youtube import %s.', subtitles.length, targetUrl) + + for (const subtitle of subtitles) { + const videoCaption = new VideoCaptionModel({ + videoId, + language: subtitle.language, + filename: VideoCaptionModel.generateCaptionName(subtitle.language) + }) as MVideoCaption + + // Move physical file + await moveAndProcessCaptionFile(subtitle, videoCaption) + + await sequelizeTypescript.transaction(async t => { + await VideoCaptionModel.insertOrReplaceLanguage(videoCaption, t) + }) + } + } catch (err) { + logger.warn('Cannot get video subtitles.', { err }) + } +} diff --git a/server/controllers/api/videos/index.ts b/server/controllers/api/videos/index.ts index f5ce15074..6483d2e8a 100644 --- a/server/controllers/api/videos/index.ts +++ b/server/controllers/api/videos/index.ts @@ -1,43 +1,20 @@ import * as express from 'express' -import { move } from 'fs-extra' -import { extname } from 'path' import toInt from 'validator/lib/toInt' -import { deleteResumableUploadMetaFile, getResumableUploadPath } from '@server/helpers/upload' -import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent' -import { changeVideoChannelShare } from '@server/lib/activitypub/share' -import { getLocalVideoActivityPubUrl } from '@server/lib/activitypub/url' import { LiveManager } from '@server/lib/live-manager' -import { addOptimizeOrMergeAudioJob, buildLocalVideoFromReq, buildVideoThumbnailsFromReq, setVideoTags } from '@server/lib/video' -import { generateVideoFilename, getVideoFilePath } from '@server/lib/video-paths' import { getServerActor } from '@server/models/application/application' -import { MVideo, MVideoFile, MVideoFullLight } from '@server/types/models' -import { uploadx } from '@uploadx/core' -import { VideoCreate, VideosCommonQuery, VideoState, VideoUpdate } from '../../../../shared' +import { VideosCommonQuery } from '../../../../shared' import { HttpStatusCode } from '../../../../shared/core-utils/miscs' import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger' -import { resetSequelizeInstance, retryTransactionWrapper } from '../../../helpers/database-utils' -import { buildNSFWFilter, createReqFiles, getCountVideos } from '../../../helpers/express-utils' -import { getMetadataFromFile, getVideoFileFPS, getVideoFileResolution } from '../../../helpers/ffprobe-utils' -import { logger, loggerTagsFactory } from '../../../helpers/logger' +import { buildNSFWFilter, getCountVideos } from '../../../helpers/express-utils' +import { logger } from '../../../helpers/logger' import { getFormattedObjects } from '../../../helpers/utils' -import { CONFIG } from '../../../initializers/config' -import { - DEFAULT_AUDIO_RESOLUTION, - MIMETYPES, - VIDEO_CATEGORIES, - VIDEO_LANGUAGES, - VIDEO_LICENCES, - VIDEO_PRIVACIES -} from '../../../initializers/constants' +import { VIDEO_CATEGORIES, VIDEO_LANGUAGES, VIDEO_LICENCES, VIDEO_PRIVACIES } from '../../../initializers/constants' import { sequelizeTypescript } from '../../../initializers/database' import { sendView } from '../../../lib/activitypub/send/send-view' -import { federateVideoIfNeeded, fetchRemoteVideoDescription } from '../../../lib/activitypub/videos' +import { fetchRemoteVideoDescription } from '../../../lib/activitypub/videos' import { JobQueue } from '../../../lib/job-queue' -import { Notifier } from '../../../lib/notifier' import { Hooks } from '../../../lib/plugins/hooks' import { Redis } from '../../../lib/redis' -import { generateVideoMiniature } from '../../../lib/thumbnail' -import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist' import { asyncMiddleware, asyncRetryTransactionMiddleware, @@ -49,16 +26,11 @@ import { setDefaultPagination, setDefaultVideosSort, videoFileMetadataGetValidator, - videosAddLegacyValidator, - videosAddResumableInitValidator, - videosAddResumableValidator, videosCustomGetValidator, videosGetValidator, videosRemoveValidator, - videosSortValidator, - videosUpdateValidator + videosSortValidator } from '../../../middlewares' -import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update' import { VideoModel } from '../../../models/video/video' import { VideoFileModel } from '../../../models/video/video-file' import { blacklistRouter } from './blacklist' @@ -68,40 +40,12 @@ import { videoImportsRouter } from './import' import { liveRouter } from './live' import { ownershipVideoRouter } from './ownership' import { rateVideoRouter } from './rate' +import { updateRouter } from './update' +import { uploadRouter } from './upload' import { watchingRouter } from './watching' -const lTags = loggerTagsFactory('api', 'video') const auditLogger = auditLoggerFactory('videos') const videosRouter = express.Router() -const uploadxMiddleware = uploadx.upload({ directory: getResumableUploadPath() }) - -const reqVideoFileAdd = createReqFiles( - [ 'videofile', 'thumbnailfile', 'previewfile' ], - Object.assign({}, MIMETYPES.VIDEO.MIMETYPE_EXT, MIMETYPES.IMAGE.MIMETYPE_EXT), - { - videofile: CONFIG.STORAGE.TMP_DIR, - thumbnailfile: CONFIG.STORAGE.TMP_DIR, - previewfile: CONFIG.STORAGE.TMP_DIR - } -) - -const reqVideoFileAddResumable = createReqFiles( - [ 'thumbnailfile', 'previewfile' ], - MIMETYPES.IMAGE.MIMETYPE_EXT, - { - thumbnailfile: getResumableUploadPath(), - previewfile: getResumableUploadPath() - } -) - -const reqVideoFileUpdate = createReqFiles( - [ 'thumbnailfile', 'previewfile' ], - MIMETYPES.IMAGE.MIMETYPE_EXT, - { - thumbnailfile: CONFIG.STORAGE.TMP_DIR, - previewfile: CONFIG.STORAGE.TMP_DIR - } -) videosRouter.use('/', blacklistRouter) videosRouter.use('/', rateVideoRouter) @@ -111,6 +55,8 @@ videosRouter.use('/', videoImportsRouter) videosRouter.use('/', ownershipVideoRouter) videosRouter.use('/', watchingRouter) videosRouter.use('/', liveRouter) +videosRouter.use('/', uploadRouter) +videosRouter.use('/', updateRouter) videosRouter.get('/categories', listVideoCategories) videosRouter.get('/licences', listVideoLicences) @@ -127,39 +73,6 @@ videosRouter.get('/', asyncMiddleware(listVideos) ) -videosRouter.post('/upload', - authenticate, - reqVideoFileAdd, - asyncMiddleware(videosAddLegacyValidator), - asyncRetryTransactionMiddleware(addVideoLegacy) -) - -videosRouter.post('/upload-resumable', - authenticate, - reqVideoFileAddResumable, - asyncMiddleware(videosAddResumableInitValidator), - uploadxMiddleware -) - -videosRouter.delete('/upload-resumable', - authenticate, - uploadxMiddleware -) - -videosRouter.put('/upload-resumable', - authenticate, - uploadxMiddleware, // uploadx doesn't use call next() before the file upload completes - asyncMiddleware(videosAddResumableValidator), - asyncMiddleware(addVideoResumable) -) - -videosRouter.put('/:id', - authenticate, - reqVideoFileUpdate, - asyncMiddleware(videosUpdateValidator), - asyncRetryTransactionMiddleware(updateVideo) -) - videosRouter.get('/:id/description', asyncMiddleware(videosGetValidator), asyncMiddleware(getVideoDescription) @@ -209,279 +122,7 @@ function listVideoPrivacies (_req: express.Request, res: express.Response) { res.json(VIDEO_PRIVACIES) } -async function addVideoLegacy (req: express.Request, res: express.Response) { - // Uploading the video could be long - // Set timeout to 10 minutes, as Express's default is 2 minutes - req.setTimeout(1000 * 60 * 10, () => { - logger.error('Upload video has timed out.') - return res.sendStatus(HttpStatusCode.REQUEST_TIMEOUT_408) - }) - - const videoPhysicalFile = req.files['videofile'][0] - const videoInfo: VideoCreate = req.body - const files = req.files - - return addVideo({ res, videoPhysicalFile, videoInfo, files }) -} - -async function addVideoResumable (_req: express.Request, res: express.Response) { - const videoPhysicalFile = res.locals.videoFileResumable - const videoInfo = videoPhysicalFile.metadata - const files = { previewfile: videoInfo.previewfile } - - // Don't need the meta file anymore - await deleteResumableUploadMetaFile(videoPhysicalFile.path) - - return addVideo({ res, videoPhysicalFile, videoInfo, files }) -} - -async function addVideo (options: { - res: express.Response - videoPhysicalFile: express.VideoUploadFile - videoInfo: VideoCreate - files: express.UploadFiles -}) { - const { res, videoPhysicalFile, videoInfo, files } = options - const videoChannel = res.locals.videoChannel - const user = res.locals.oauth.token.User - - const videoData = buildLocalVideoFromReq(videoInfo, videoChannel.id) - - videoData.state = CONFIG.TRANSCODING.ENABLED - ? VideoState.TO_TRANSCODE - : VideoState.PUBLISHED - - videoData.duration = videoPhysicalFile.duration // duration was added by a previous middleware - - const video = new VideoModel(videoData) as MVideoFullLight - video.VideoChannel = videoChannel - video.url = getLocalVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object - - const videoFile = new VideoFileModel({ - extname: extname(videoPhysicalFile.filename), - size: videoPhysicalFile.size, - videoStreamingPlaylistId: null, - metadata: await getMetadataFromFile(videoPhysicalFile.path) - }) - - if (videoFile.isAudio()) { - videoFile.resolution = DEFAULT_AUDIO_RESOLUTION - } else { - videoFile.fps = await getVideoFileFPS(videoPhysicalFile.path) - videoFile.resolution = (await getVideoFileResolution(videoPhysicalFile.path)).videoFileResolution - } - - videoFile.filename = generateVideoFilename(video, false, videoFile.resolution, videoFile.extname) - - // Move physical file - const destination = getVideoFilePath(video, videoFile) - await move(videoPhysicalFile.path, destination) - // This is important in case if there is another attempt in the retry process - videoPhysicalFile.filename = getVideoFilePath(video, videoFile) - videoPhysicalFile.path = destination - - const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({ - video, - files, - fallback: type => generateVideoMiniature({ video, videoFile, type }) - }) - - const { videoCreated } = await sequelizeTypescript.transaction(async t => { - const sequelizeOptions = { transaction: t } - - const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight - - await videoCreated.addAndSaveThumbnail(thumbnailModel, t) - await videoCreated.addAndSaveThumbnail(previewModel, t) - - // Do not forget to add video channel information to the created video - videoCreated.VideoChannel = res.locals.videoChannel - - videoFile.videoId = video.id - await videoFile.save(sequelizeOptions) - - video.VideoFiles = [ videoFile ] - - await setVideoTags({ video, tags: videoInfo.tags, transaction: t }) - - // Schedule an update in the future? - if (videoInfo.scheduleUpdate) { - await ScheduleVideoUpdateModel.create({ - videoId: video.id, - updateAt: new Date(videoInfo.scheduleUpdate.updateAt), - privacy: videoInfo.scheduleUpdate.privacy || null - }, { transaction: t }) - } - - // Channel has a new content, set as updated - await videoCreated.VideoChannel.setAsUpdated(t) - - await autoBlacklistVideoIfNeeded({ - video, - user, - isRemote: false, - isNew: true, - transaction: t - }) - - auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(videoCreated.toFormattedDetailsJSON())) - logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid, lTags(videoCreated.uuid)) - - return { videoCreated } - }) - - // Create the torrent file in async way because it could be long - createTorrentAndSetInfoHashAsync(video, videoFile) - .catch(err => logger.error('Cannot create torrent file for video %s', video.url, { err, ...lTags(video.uuid) })) - .then(() => VideoModel.loadAndPopulateAccountAndServerAndTags(video.id)) - .then(refreshedVideo => { - if (!refreshedVideo) return - - // Only federate and notify after the torrent creation - Notifier.Instance.notifyOnNewVideoIfNeeded(refreshedVideo) - - return retryTransactionWrapper(() => { - return sequelizeTypescript.transaction(t => federateVideoIfNeeded(refreshedVideo, true, t)) - }) - }) - .catch(err => logger.error('Cannot federate or notify video creation %s', video.url, { err, ...lTags(video.uuid) })) - - if (video.state === VideoState.TO_TRANSCODE) { - await addOptimizeOrMergeAudioJob(videoCreated, videoFile, user) - } - - Hooks.runAction('action:api.video.uploaded', { video: videoCreated }) - - return res.json({ - video: { - id: videoCreated.id, - uuid: videoCreated.uuid - } - }) -} - -async function updateVideo (req: express.Request, res: express.Response) { - const videoInstance = res.locals.videoAll - const videoFieldsSave = videoInstance.toJSON() - const oldVideoAuditView = new VideoAuditView(videoInstance.toFormattedDetailsJSON()) - const videoInfoToUpdate: VideoUpdate = req.body - - const wasConfidentialVideo = videoInstance.isConfidential() - const hadPrivacyForFederation = videoInstance.hasPrivacyForFederation() - - const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({ - video: videoInstance, - files: req.files, - fallback: () => Promise.resolve(undefined), - automaticallyGenerated: false - }) - - try { - const videoInstanceUpdated = await sequelizeTypescript.transaction(async t => { - const sequelizeOptions = { transaction: t } - const oldVideoChannel = videoInstance.VideoChannel - - if (videoInfoToUpdate.name !== undefined) videoInstance.name = videoInfoToUpdate.name - if (videoInfoToUpdate.category !== undefined) videoInstance.category = videoInfoToUpdate.category - if (videoInfoToUpdate.licence !== undefined) videoInstance.licence = videoInfoToUpdate.licence - if (videoInfoToUpdate.language !== undefined) videoInstance.language = videoInfoToUpdate.language - if (videoInfoToUpdate.nsfw !== undefined) videoInstance.nsfw = videoInfoToUpdate.nsfw - if (videoInfoToUpdate.waitTranscoding !== undefined) videoInstance.waitTranscoding = videoInfoToUpdate.waitTranscoding - if (videoInfoToUpdate.support !== undefined) videoInstance.support = videoInfoToUpdate.support - if (videoInfoToUpdate.description !== undefined) videoInstance.description = videoInfoToUpdate.description - if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.commentsEnabled = videoInfoToUpdate.commentsEnabled - if (videoInfoToUpdate.downloadEnabled !== undefined) videoInstance.downloadEnabled = videoInfoToUpdate.downloadEnabled - - if (videoInfoToUpdate.originallyPublishedAt !== undefined && videoInfoToUpdate.originallyPublishedAt !== null) { - videoInstance.originallyPublishedAt = new Date(videoInfoToUpdate.originallyPublishedAt) - } - - let isNewVideo = false - if (videoInfoToUpdate.privacy !== undefined) { - isNewVideo = videoInstance.isNewVideo(videoInfoToUpdate.privacy) - - const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10) - videoInstance.setPrivacy(newPrivacy) - - // Unfederate the video if the new privacy is not compatible with federation - if (hadPrivacyForFederation && !videoInstance.hasPrivacyForFederation()) { - await VideoModel.sendDelete(videoInstance, { transaction: t }) - } - } - - const videoInstanceUpdated = await videoInstance.save(sequelizeOptions) as MVideoFullLight - - if (thumbnailModel) await videoInstanceUpdated.addAndSaveThumbnail(thumbnailModel, t) - if (previewModel) await videoInstanceUpdated.addAndSaveThumbnail(previewModel, 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? - if (videoInfoToUpdate.scheduleUpdate) { - await ScheduleVideoUpdateModel.upsert({ - videoId: videoInstanceUpdated.id, - updateAt: new Date(videoInfoToUpdate.scheduleUpdate.updateAt), - privacy: videoInfoToUpdate.scheduleUpdate.privacy || null - }, { transaction: t }) - } else if (videoInfoToUpdate.scheduleUpdate === null) { - await ScheduleVideoUpdateModel.deleteByVideoId(videoInstanceUpdated.id, t) - } - - await autoBlacklistVideoIfNeeded({ - video: videoInstanceUpdated, - user: res.locals.oauth.token.User, - isRemote: false, - isNew: false, - transaction: t - }) - - await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t) - - auditLogger.update( - getAuditIdFromRes(res), - new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()), - oldVideoAuditView - ) - logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid, lTags(videoInstance.uuid)) - - return videoInstanceUpdated - }) - - if (wasConfidentialVideo) { - Notifier.Instance.notifyOnNewVideoIfNeeded(videoInstanceUpdated) - } - - Hooks.runAction('action:api.video.updated', { video: videoInstanceUpdated, body: req.body }) - } catch (err) { - // Force fields we want to update - // If the transaction is retried, sequelize will think the object has not changed - // So it will skip the SQL request, even if the last one was ROLLBACKed! - resetSequelizeInstance(videoInstance, videoFieldsSave) - - throw err - } - - return res.type('json') - .status(HttpStatusCode.NO_CONTENT_204) - .end() -} - -async function getVideo (req: express.Request, res: express.Response) { +async function getVideo (_req: express.Request, res: express.Response) { // We need more attributes const userId: number = res.locals.oauth ? res.locals.oauth.token.User.id : null @@ -543,13 +184,10 @@ async function viewVideo (req: express.Request, res: express.Response) { async function getVideoDescription (req: express.Request, res: express.Response) { const videoInstance = res.locals.videoAll - let description = '' - if (videoInstance.isOwned()) { - description = videoInstance.description - } else { - description = await fetchRemoteVideoDescription(videoInstance) - } + const description = videoInstance.isOwned() + ? videoInstance.description + : await fetchRemoteVideoDescription(videoInstance) return res.json({ description }) } @@ -591,7 +229,7 @@ async function listVideos (req: express.Request, res: express.Response) { return res.json(getFormattedObjects(resultList.data, resultList.total)) } -async function removeVideo (req: express.Request, res: express.Response) { +async function removeVideo (_req: express.Request, res: express.Response) { const videoInstance = res.locals.videoAll await sequelizeTypescript.transaction(async t => { @@ -607,17 +245,3 @@ async function removeVideo (req: express.Request, res: express.Response) { .status(HttpStatusCode.NO_CONTENT_204) .end() } - -async function createTorrentAndSetInfoHashAsync (video: MVideo, fileArg: MVideoFile) { - await createTorrentAndSetInfoHash(video, fileArg) - - // Refresh videoFile because the createTorrentAndSetInfoHash could be long - const refreshedFile = await VideoFileModel.loadWithVideo(fileArg.id) - // File does not exist anymore, remove the generated torrent - if (!refreshedFile) return fileArg.removeTorrent() - - refreshedFile.infoHash = fileArg.infoHash - refreshedFile.torrentFilename = fileArg.torrentFilename - - return refreshedFile.save() -} diff --git a/server/controllers/api/videos/ownership.ts b/server/controllers/api/videos/ownership.ts index a85d7c30b..6102f28dc 100644 --- a/server/controllers/api/videos/ownership.ts +++ b/server/controllers/api/videos/ownership.ts @@ -99,7 +99,7 @@ async function listVideoOwnership (req: express.Request, res: express.Response) return res.json(getFormattedObjects(resultList.data, resultList.total)) } -async function acceptOwnership (req: express.Request, res: express.Response) { +function acceptOwnership (req: express.Request, res: express.Response) { return sequelizeTypescript.transaction(async t => { const videoChangeOwnership = res.locals.videoChangeOwnership const channel = res.locals.videoChannel @@ -126,7 +126,7 @@ async function acceptOwnership (req: express.Request, res: express.Response) { }) } -async function refuseOwnership (req: express.Request, res: express.Response) { +function refuseOwnership (req: express.Request, res: express.Response) { return sequelizeTypescript.transaction(async t => { const videoChangeOwnership = res.locals.videoChangeOwnership diff --git a/server/controllers/api/videos/update.ts b/server/controllers/api/videos/update.ts new file mode 100644 index 000000000..2450abd0e --- /dev/null +++ b/server/controllers/api/videos/update.ts @@ -0,0 +1,191 @@ +import * as express from 'express' +import { Transaction } from 'sequelize/types' +import { changeVideoChannelShare } from '@server/lib/activitypub/share' +import { buildVideoThumbnailsFromReq, setVideoTags } from '@server/lib/video' +import { FilteredModelAttributes } from '@server/types' +import { MVideoFullLight } from '@server/types/models' +import { VideoUpdate } from '../../../../shared' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs' +import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger' +import { resetSequelizeInstance } from '../../../helpers/database-utils' +import { createReqFiles } from '../../../helpers/express-utils' +import { logger, loggerTagsFactory } from '../../../helpers/logger' +import { CONFIG } from '../../../initializers/config' +import { MIMETYPES } from '../../../initializers/constants' +import { sequelizeTypescript } from '../../../initializers/database' +import { federateVideoIfNeeded } from '../../../lib/activitypub/videos' +import { Notifier } from '../../../lib/notifier' +import { Hooks } from '../../../lib/plugins/hooks' +import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist' +import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate, videosUpdateValidator } from '../../../middlewares' +import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update' +import { VideoModel } from '../../../models/video/video' + +const lTags = loggerTagsFactory('api', 'video') +const auditLogger = auditLoggerFactory('videos') +const updateRouter = express.Router() + +const reqVideoFileUpdate = createReqFiles( + [ 'thumbnailfile', 'previewfile' ], + MIMETYPES.IMAGE.MIMETYPE_EXT, + { + thumbnailfile: CONFIG.STORAGE.TMP_DIR, + previewfile: CONFIG.STORAGE.TMP_DIR + } +) + +updateRouter.put('/:id', + authenticate, + reqVideoFileUpdate, + asyncMiddleware(videosUpdateValidator), + asyncRetryTransactionMiddleware(updateVideo) +) + +// --------------------------------------------------------------------------- + +export { + updateRouter +} + +// --------------------------------------------------------------------------- + +export async function updateVideo (req: express.Request, res: express.Response) { + const videoInstance = res.locals.videoAll + const videoFieldsSave = videoInstance.toJSON() + const oldVideoAuditView = new VideoAuditView(videoInstance.toFormattedDetailsJSON()) + const videoInfoToUpdate: VideoUpdate = req.body + + const wasConfidentialVideo = videoInstance.isConfidential() + const hadPrivacyForFederation = videoInstance.hasPrivacyForFederation() + + const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({ + video: videoInstance, + files: req.files, + fallback: () => Promise.resolve(undefined), + automaticallyGenerated: false + }) + + try { + const videoInstanceUpdated = await sequelizeTypescript.transaction(async t => { + const sequelizeOptions = { transaction: t } + const oldVideoChannel = videoInstance.VideoChannel + + const keysToUpdate: (keyof VideoUpdate & FilteredModelAttributes)[] = [ + 'name', + 'category', + 'licence', + 'language', + 'nsfw', + 'waitTranscoding', + 'support', + 'description', + 'commentsEnabled', + 'downloadEnabled' + ] + + for (const key of keysToUpdate) { + if (videoInfoToUpdate[key] !== undefined) videoInstance.set(key, videoInfoToUpdate[key]) + } + + if (videoInfoToUpdate.originallyPublishedAt !== undefined && videoInfoToUpdate.originallyPublishedAt !== null) { + videoInstance.originallyPublishedAt = new Date(videoInfoToUpdate.originallyPublishedAt) + } + + // Privacy update? + let isNewVideo = false + if (videoInfoToUpdate.privacy !== undefined) { + isNewVideo = await updateVideoPrivacy({ videoInstance, videoInfoToUpdate, hadPrivacyForFederation, transaction: t }) + } + + const videoInstanceUpdated = await videoInstance.save(sequelizeOptions) as MVideoFullLight + + // Thumbnail & preview updates? + if (thumbnailModel) await videoInstanceUpdated.addAndSaveThumbnail(thumbnailModel, t) + if (previewModel) await videoInstanceUpdated.addAndSaveThumbnail(previewModel, 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) + + await autoBlacklistVideoIfNeeded({ + video: videoInstanceUpdated, + user: res.locals.oauth.token.User, + isRemote: false, + isNew: false, + transaction: t + }) + + await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t) + + auditLogger.update( + getAuditIdFromRes(res), + new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()), + oldVideoAuditView + ) + logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid, lTags(videoInstance.uuid)) + + return videoInstanceUpdated + }) + + if (wasConfidentialVideo) { + Notifier.Instance.notifyOnNewVideoIfNeeded(videoInstanceUpdated) + } + + Hooks.runAction('action:api.video.updated', { video: videoInstanceUpdated, body: req.body }) + } catch (err) { + // Force fields we want to update + // If the transaction is retried, sequelize will think the object has not changed + // So it will skip the SQL request, even if the last one was ROLLBACKed! + resetSequelizeInstance(videoInstance, videoFieldsSave) + + throw err + } + + return res.type('json') + .status(HttpStatusCode.NO_CONTENT_204) + .end() +} + +async function updateVideoPrivacy (options: { + videoInstance: MVideoFullLight + videoInfoToUpdate: VideoUpdate + hadPrivacyForFederation: boolean + transaction: Transaction +}) { + const { videoInstance, videoInfoToUpdate, hadPrivacyForFederation, transaction } = options + const isNewVideo = videoInstance.isNewVideo(videoInfoToUpdate.privacy) + + const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10) + videoInstance.setPrivacy(newPrivacy) + + // Unfederate the video if the new privacy is not compatible with federation + if (hadPrivacyForFederation && !videoInstance.hasPrivacyForFederation()) { + await VideoModel.sendDelete(videoInstance, { transaction }) + } + + return isNewVideo +} + +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) + } +} diff --git a/server/controllers/api/videos/upload.ts b/server/controllers/api/videos/upload.ts new file mode 100644 index 000000000..ebc17c760 --- /dev/null +++ b/server/controllers/api/videos/upload.ts @@ -0,0 +1,269 @@ +import * as express from 'express' +import { move } from 'fs-extra' +import { extname } from 'path' +import { deleteResumableUploadMetaFile, getResumableUploadPath } from '@server/helpers/upload' +import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent' +import { getLocalVideoActivityPubUrl } from '@server/lib/activitypub/url' +import { addOptimizeOrMergeAudioJob, buildLocalVideoFromReq, buildVideoThumbnailsFromReq, setVideoTags } from '@server/lib/video' +import { generateVideoFilename, getVideoFilePath } from '@server/lib/video-paths' +import { MVideo, MVideoFile, MVideoFullLight } from '@server/types/models' +import { uploadx } from '@uploadx/core' +import { VideoCreate, VideoState } from '../../../../shared' +import { HttpStatusCode } from '../../../../shared/core-utils/miscs' +import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger' +import { retryTransactionWrapper } from '../../../helpers/database-utils' +import { createReqFiles } from '../../../helpers/express-utils' +import { getMetadataFromFile, getVideoFileFPS, getVideoFileResolution } from '../../../helpers/ffprobe-utils' +import { logger, loggerTagsFactory } from '../../../helpers/logger' +import { CONFIG } from '../../../initializers/config' +import { DEFAULT_AUDIO_RESOLUTION, MIMETYPES } from '../../../initializers/constants' +import { sequelizeTypescript } from '../../../initializers/database' +import { federateVideoIfNeeded } from '../../../lib/activitypub/videos' +import { Notifier } from '../../../lib/notifier' +import { Hooks } from '../../../lib/plugins/hooks' +import { generateVideoMiniature } from '../../../lib/thumbnail' +import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist' +import { + asyncMiddleware, + asyncRetryTransactionMiddleware, + authenticate, + videosAddLegacyValidator, + videosAddResumableInitValidator, + videosAddResumableValidator +} from '../../../middlewares' +import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update' +import { VideoModel } from '../../../models/video/video' +import { VideoFileModel } from '../../../models/video/video-file' + +const lTags = loggerTagsFactory('api', 'video') +const auditLogger = auditLoggerFactory('videos') +const uploadRouter = express.Router() +const uploadxMiddleware = uploadx.upload({ directory: getResumableUploadPath() }) + +const reqVideoFileAdd = createReqFiles( + [ 'videofile', 'thumbnailfile', 'previewfile' ], + Object.assign({}, MIMETYPES.VIDEO.MIMETYPE_EXT, MIMETYPES.IMAGE.MIMETYPE_EXT), + { + videofile: CONFIG.STORAGE.TMP_DIR, + thumbnailfile: CONFIG.STORAGE.TMP_DIR, + previewfile: CONFIG.STORAGE.TMP_DIR + } +) + +const reqVideoFileAddResumable = createReqFiles( + [ 'thumbnailfile', 'previewfile' ], + MIMETYPES.IMAGE.MIMETYPE_EXT, + { + thumbnailfile: getResumableUploadPath(), + previewfile: getResumableUploadPath() + } +) + +uploadRouter.post('/upload', + authenticate, + reqVideoFileAdd, + asyncMiddleware(videosAddLegacyValidator), + asyncRetryTransactionMiddleware(addVideoLegacy) +) + +uploadRouter.post('/upload-resumable', + authenticate, + reqVideoFileAddResumable, + asyncMiddleware(videosAddResumableInitValidator), + uploadxMiddleware +) + +uploadRouter.delete('/upload-resumable', + authenticate, + uploadxMiddleware +) + +uploadRouter.put('/upload-resumable', + authenticate, + uploadxMiddleware, // uploadx doesn't use call next() before the file upload completes + asyncMiddleware(videosAddResumableValidator), + asyncMiddleware(addVideoResumable) +) + +// --------------------------------------------------------------------------- + +export { + uploadRouter +} + +// --------------------------------------------------------------------------- + +export async function addVideoLegacy (req: express.Request, res: express.Response) { + // Uploading the video could be long + // Set timeout to 10 minutes, as Express's default is 2 minutes + req.setTimeout(1000 * 60 * 10, () => { + logger.error('Upload video has timed out.') + return res.sendStatus(HttpStatusCode.REQUEST_TIMEOUT_408) + }) + + const videoPhysicalFile = req.files['videofile'][0] + const videoInfo: VideoCreate = req.body + const files = req.files + + return addVideo({ res, videoPhysicalFile, videoInfo, files }) +} + +export async function addVideoResumable (_req: express.Request, res: express.Response) { + const videoPhysicalFile = res.locals.videoFileResumable + const videoInfo = videoPhysicalFile.metadata + const files = { previewfile: videoInfo.previewfile } + + // Don't need the meta file anymore + await deleteResumableUploadMetaFile(videoPhysicalFile.path) + + return addVideo({ res, videoPhysicalFile, videoInfo, files }) +} + +async function addVideo (options: { + res: express.Response + videoPhysicalFile: express.VideoUploadFile + videoInfo: VideoCreate + files: express.UploadFiles +}) { + const { res, videoPhysicalFile, videoInfo, files } = options + const videoChannel = res.locals.videoChannel + const user = res.locals.oauth.token.User + + const videoData = buildLocalVideoFromReq(videoInfo, videoChannel.id) + + videoData.state = CONFIG.TRANSCODING.ENABLED + ? VideoState.TO_TRANSCODE + : VideoState.PUBLISHED + + videoData.duration = videoPhysicalFile.duration // duration was added by a previous middleware + + const video = new VideoModel(videoData) as MVideoFullLight + video.VideoChannel = videoChannel + video.url = getLocalVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object + + const videoFile = await buildNewFile(video, videoPhysicalFile) + + // Move physical file + const destination = getVideoFilePath(video, videoFile) + await move(videoPhysicalFile.path, destination) + // This is important in case if there is another attempt in the retry process + videoPhysicalFile.filename = getVideoFilePath(video, videoFile) + videoPhysicalFile.path = destination + + const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({ + video, + files, + fallback: type => generateVideoMiniature({ video, videoFile, type }) + }) + + const { videoCreated } = await sequelizeTypescript.transaction(async t => { + const sequelizeOptions = { transaction: t } + + const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight + + await videoCreated.addAndSaveThumbnail(thumbnailModel, t) + await videoCreated.addAndSaveThumbnail(previewModel, t) + + // Do not forget to add video channel information to the created video + videoCreated.VideoChannel = res.locals.videoChannel + + videoFile.videoId = video.id + await videoFile.save(sequelizeOptions) + + video.VideoFiles = [ videoFile ] + + await setVideoTags({ video, tags: videoInfo.tags, transaction: t }) + + // Schedule an update in the future? + if (videoInfo.scheduleUpdate) { + await ScheduleVideoUpdateModel.create({ + videoId: video.id, + updateAt: new Date(videoInfo.scheduleUpdate.updateAt), + privacy: videoInfo.scheduleUpdate.privacy || null + }, sequelizeOptions) + } + + // Channel has a new content, set as updated + await videoCreated.VideoChannel.setAsUpdated(t) + + await autoBlacklistVideoIfNeeded({ + video, + user, + isRemote: false, + isNew: true, + transaction: t + }) + + auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(videoCreated.toFormattedDetailsJSON())) + logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid, lTags(videoCreated.uuid)) + + return { videoCreated } + }) + + createTorrentFederate(video, videoFile) + + if (video.state === VideoState.TO_TRANSCODE) { + await addOptimizeOrMergeAudioJob(videoCreated, videoFile, user) + } + + Hooks.runAction('action:api.video.uploaded', { video: videoCreated }) + + return res.json({ + video: { + id: videoCreated.id, + uuid: videoCreated.uuid + } + }) +} + +async function buildNewFile (video: MVideo, videoPhysicalFile: express.VideoUploadFile) { + const videoFile = new VideoFileModel({ + extname: extname(videoPhysicalFile.filename), + size: videoPhysicalFile.size, + videoStreamingPlaylistId: null, + metadata: await getMetadataFromFile(videoPhysicalFile.path) + }) + + if (videoFile.isAudio()) { + videoFile.resolution = DEFAULT_AUDIO_RESOLUTION + } else { + videoFile.fps = await getVideoFileFPS(videoPhysicalFile.path) + videoFile.resolution = (await getVideoFileResolution(videoPhysicalFile.path)).videoFileResolution + } + + videoFile.filename = generateVideoFilename(video, false, videoFile.resolution, videoFile.extname) + + return videoFile +} + +async function createTorrentAndSetInfoHashAsync (video: MVideo, fileArg: MVideoFile) { + await createTorrentAndSetInfoHash(video, fileArg) + + // Refresh videoFile because the createTorrentAndSetInfoHash could be long + const refreshedFile = await VideoFileModel.loadWithVideo(fileArg.id) + // File does not exist anymore, remove the generated torrent + if (!refreshedFile) return fileArg.removeTorrent() + + refreshedFile.infoHash = fileArg.infoHash + refreshedFile.torrentFilename = fileArg.torrentFilename + + return refreshedFile.save() +} + +function createTorrentFederate (video: MVideoFullLight, videoFile: MVideoFile): void { + // Create the torrent file in async way because it could be long + createTorrentAndSetInfoHashAsync(video, videoFile) + .catch(err => logger.error('Cannot create torrent file for video %s', video.url, { err, ...lTags(video.uuid) })) + .then(() => VideoModel.loadAndPopulateAccountAndServerAndTags(video.id)) + .then(refreshedVideo => { + if (!refreshedVideo) return + + // Only federate and notify after the torrent creation + Notifier.Instance.notifyOnNewVideoIfNeeded(refreshedVideo) + + return retryTransactionWrapper(() => { + return sequelizeTypescript.transaction(t => federateVideoIfNeeded(refreshedVideo, true, t)) + }) + }) + .catch(err => logger.error('Cannot federate or notify video creation %s', video.url, { err, ...lTags(video.uuid) })) +} -- cgit v1.2.3 From 2539932e16129992a2c0889b4ff527c265a8e2c7 Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Thu, 27 May 2021 15:59:55 +0200 Subject: Instance homepage support (#4007) * Prepare homepage parsers * Add ability to update instance hompage * Add ability to set homepage as landing page * Add homepage preview in admin * Dynamically update left menu for homepage * Inject home content in homepage * Add videos list and channel miniature custom markup * Remove unused elements in markup service --- server/controllers/api/videos/import.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'server/controllers/api/videos') diff --git a/server/controllers/api/videos/import.ts b/server/controllers/api/videos/import.ts index ee63c7b77..0d5d7a962 100644 --- a/server/controllers/api/videos/import.ts +++ b/server/controllers/api/videos/import.ts @@ -3,7 +3,7 @@ import { move, readFile } from 'fs-extra' import * as magnetUtil from 'magnet-uri' import * as parseTorrent from 'parse-torrent' import { join } from 'path' -import { getEnabledResolutions } from '@server/lib/config' +import { ServerConfigManager } from '@server/lib/server-config-manager' import { setVideoTags } from '@server/lib/video' import { FilteredModelAttributes } from '@server/types' import { @@ -134,7 +134,7 @@ async function addYoutubeDLImport (req: express.Request, res: express.Response) const targetUrl = body.targetUrl const user = res.locals.oauth.token.User - const youtubeDL = new YoutubeDL(targetUrl, getEnabledResolutions('vod')) + const youtubeDL = new YoutubeDL(targetUrl, ServerConfigManager.Instance.getEnabledResolutions('vod')) // Get video infos let youtubeDLInfo: YoutubeDLInfo -- cgit v1.2.3