]>
Commit | Line | Data |
---|---|---|
1 | import * as express from 'express' | |
2 | import { move } from 'fs-extra' | |
3 | import { extname } from 'path' | |
4 | import toInt from 'validator/lib/toInt' | |
5 | import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent' | |
6 | import { changeVideoChannelShare } from '@server/lib/activitypub/share' | |
7 | import { getLocalVideoActivityPubUrl } from '@server/lib/activitypub/url' | |
8 | import { LiveManager } from '@server/lib/live-manager' | |
9 | import { addOptimizeOrMergeAudioJob, buildLocalVideoFromReq, buildVideoThumbnailsFromReq, setVideoTags } from '@server/lib/video' | |
10 | import { generateVideoFilename, getVideoFilePath } from '@server/lib/video-paths' | |
11 | import { getServerActor } from '@server/models/application/application' | |
12 | import { MVideo, MVideoFile, MVideoFullLight } from '@server/types/models' | |
13 | import { VideoCreate, VideoState, VideoUpdate } from '../../../../shared' | |
14 | import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' | |
15 | import { VideoFilter } from '../../../../shared/models/videos/video-query.type' | |
16 | import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger' | |
17 | import { resetSequelizeInstance, retryTransactionWrapper } from '../../../helpers/database-utils' | |
18 | import { buildNSFWFilter, createReqFiles, getCountVideos } from '../../../helpers/express-utils' | |
19 | import { getMetadataFromFile, getVideoFileFPS, getVideoFileResolution } from '../../../helpers/ffprobe-utils' | |
20 | import { logger } from '../../../helpers/logger' | |
21 | import { getFormattedObjects } from '../../../helpers/utils' | |
22 | import { CONFIG } from '../../../initializers/config' | |
23 | import { | |
24 | DEFAULT_AUDIO_RESOLUTION, | |
25 | MIMETYPES, | |
26 | VIDEO_CATEGORIES, | |
27 | VIDEO_LANGUAGES, | |
28 | VIDEO_LICENCES, | |
29 | VIDEO_PRIVACIES | |
30 | } from '../../../initializers/constants' | |
31 | import { sequelizeTypescript } from '../../../initializers/database' | |
32 | import { sendView } from '../../../lib/activitypub/send/send-view' | |
33 | import { federateVideoIfNeeded, fetchRemoteVideoDescription } from '../../../lib/activitypub/videos' | |
34 | import { JobQueue } from '../../../lib/job-queue' | |
35 | import { Notifier } from '../../../lib/notifier' | |
36 | import { Hooks } from '../../../lib/plugins/hooks' | |
37 | import { Redis } from '../../../lib/redis' | |
38 | import { generateVideoMiniature } from '../../../lib/thumbnail' | |
39 | import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist' | |
40 | import { | |
41 | asyncMiddleware, | |
42 | asyncRetryTransactionMiddleware, | |
43 | authenticate, | |
44 | checkVideoFollowConstraints, | |
45 | commonVideosFiltersValidator, | |
46 | optionalAuthenticate, | |
47 | paginationValidator, | |
48 | setDefaultPagination, | |
49 | setDefaultVideosSort, | |
50 | videoFileMetadataGetValidator, | |
51 | videosAddValidator, | |
52 | videosCustomGetValidator, | |
53 | videosGetValidator, | |
54 | videosRemoveValidator, | |
55 | videosSortValidator, | |
56 | videosUpdateValidator | |
57 | } from '../../../middlewares' | |
58 | import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update' | |
59 | import { VideoModel } from '../../../models/video/video' | |
60 | import { VideoFileModel } from '../../../models/video/video-file' | |
61 | import { blacklistRouter } from './blacklist' | |
62 | import { videoCaptionsRouter } from './captions' | |
63 | import { videoCommentRouter } from './comment' | |
64 | import { videoImportsRouter } from './import' | |
65 | import { liveRouter } from './live' | |
66 | import { ownershipVideoRouter } from './ownership' | |
67 | import { rateVideoRouter } from './rate' | |
68 | import { watchingRouter } from './watching' | |
69 | ||
70 | const auditLogger = auditLoggerFactory('videos') | |
71 | const videosRouter = express.Router() | |
72 | ||
73 | const reqVideoFileAdd = createReqFiles( | |
74 | [ 'videofile', 'thumbnailfile', 'previewfile' ], | |
75 | Object.assign({}, MIMETYPES.VIDEO.MIMETYPE_EXT, MIMETYPES.IMAGE.MIMETYPE_EXT), | |
76 | { | |
77 | videofile: CONFIG.STORAGE.TMP_DIR, | |
78 | thumbnailfile: CONFIG.STORAGE.TMP_DIR, | |
79 | previewfile: CONFIG.STORAGE.TMP_DIR | |
80 | } | |
81 | ) | |
82 | const reqVideoFileUpdate = createReqFiles( | |
83 | [ 'thumbnailfile', 'previewfile' ], | |
84 | MIMETYPES.IMAGE.MIMETYPE_EXT, | |
85 | { | |
86 | thumbnailfile: CONFIG.STORAGE.TMP_DIR, | |
87 | previewfile: CONFIG.STORAGE.TMP_DIR | |
88 | } | |
89 | ) | |
90 | ||
91 | videosRouter.use('/', blacklistRouter) | |
92 | videosRouter.use('/', rateVideoRouter) | |
93 | videosRouter.use('/', videoCommentRouter) | |
94 | videosRouter.use('/', videoCaptionsRouter) | |
95 | videosRouter.use('/', videoImportsRouter) | |
96 | videosRouter.use('/', ownershipVideoRouter) | |
97 | videosRouter.use('/', watchingRouter) | |
98 | videosRouter.use('/', liveRouter) | |
99 | ||
100 | videosRouter.get('/categories', listVideoCategories) | |
101 | videosRouter.get('/licences', listVideoLicences) | |
102 | videosRouter.get('/languages', listVideoLanguages) | |
103 | videosRouter.get('/privacies', listVideoPrivacies) | |
104 | ||
105 | videosRouter.get('/', | |
106 | paginationValidator, | |
107 | videosSortValidator, | |
108 | setDefaultVideosSort, | |
109 | setDefaultPagination, | |
110 | optionalAuthenticate, | |
111 | commonVideosFiltersValidator, | |
112 | asyncMiddleware(listVideos) | |
113 | ) | |
114 | videosRouter.put('/:id', | |
115 | authenticate, | |
116 | reqVideoFileUpdate, | |
117 | asyncMiddleware(videosUpdateValidator), | |
118 | asyncRetryTransactionMiddleware(updateVideo) | |
119 | ) | |
120 | videosRouter.post('/upload', | |
121 | authenticate, | |
122 | reqVideoFileAdd, | |
123 | asyncMiddleware(videosAddValidator), | |
124 | asyncRetryTransactionMiddleware(addVideo) | |
125 | ) | |
126 | ||
127 | videosRouter.get('/:id/description', | |
128 | asyncMiddleware(videosGetValidator), | |
129 | asyncMiddleware(getVideoDescription) | |
130 | ) | |
131 | videosRouter.get('/:id/metadata/:videoFileId', | |
132 | asyncMiddleware(videoFileMetadataGetValidator), | |
133 | asyncMiddleware(getVideoFileMetadata) | |
134 | ) | |
135 | videosRouter.get('/:id', | |
136 | optionalAuthenticate, | |
137 | asyncMiddleware(videosCustomGetValidator('only-video-with-rights')), | |
138 | asyncMiddleware(checkVideoFollowConstraints), | |
139 | asyncMiddleware(getVideo) | |
140 | ) | |
141 | videosRouter.post('/:id/views', | |
142 | asyncMiddleware(videosCustomGetValidator('only-immutable-attributes')), | |
143 | asyncMiddleware(viewVideo) | |
144 | ) | |
145 | ||
146 | videosRouter.delete('/:id', | |
147 | authenticate, | |
148 | asyncMiddleware(videosRemoveValidator), | |
149 | asyncRetryTransactionMiddleware(removeVideo) | |
150 | ) | |
151 | ||
152 | // --------------------------------------------------------------------------- | |
153 | ||
154 | export { | |
155 | videosRouter | |
156 | } | |
157 | ||
158 | // --------------------------------------------------------------------------- | |
159 | ||
160 | function listVideoCategories (req: express.Request, res: express.Response) { | |
161 | res.json(VIDEO_CATEGORIES) | |
162 | } | |
163 | ||
164 | function listVideoLicences (req: express.Request, res: express.Response) { | |
165 | res.json(VIDEO_LICENCES) | |
166 | } | |
167 | ||
168 | function listVideoLanguages (req: express.Request, res: express.Response) { | |
169 | res.json(VIDEO_LANGUAGES) | |
170 | } | |
171 | ||
172 | function listVideoPrivacies (req: express.Request, res: express.Response) { | |
173 | res.json(VIDEO_PRIVACIES) | |
174 | } | |
175 | ||
176 | async function addVideo (req: express.Request, res: express.Response) { | |
177 | // Uploading the video could be long | |
178 | // Set timeout to 10 minutes, as Express's default is 2 minutes | |
179 | req.setTimeout(1000 * 60 * 10, () => { | |
180 | logger.error('Upload video has timed out.') | |
181 | return res.sendStatus(HttpStatusCode.REQUEST_TIMEOUT_408) | |
182 | }) | |
183 | ||
184 | const videoPhysicalFile = req.files['videofile'][0] | |
185 | const videoInfo: VideoCreate = req.body | |
186 | ||
187 | const videoData = buildLocalVideoFromReq(videoInfo, res.locals.videoChannel.id) | |
188 | videoData.state = CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED | |
189 | videoData.duration = videoPhysicalFile['duration'] // duration was added by a previous middleware | |
190 | ||
191 | const video = new VideoModel(videoData) as MVideoFullLight | |
192 | video.VideoChannel = res.locals.videoChannel | |
193 | video.url = getLocalVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object | |
194 | ||
195 | const videoFile = new VideoFileModel({ | |
196 | extname: extname(videoPhysicalFile.filename), | |
197 | size: videoPhysicalFile.size, | |
198 | videoStreamingPlaylistId: null, | |
199 | metadata: await getMetadataFromFile(videoPhysicalFile.path) | |
200 | }) | |
201 | ||
202 | if (videoFile.isAudio()) { | |
203 | videoFile.resolution = DEFAULT_AUDIO_RESOLUTION | |
204 | } else { | |
205 | videoFile.fps = await getVideoFileFPS(videoPhysicalFile.path) | |
206 | videoFile.resolution = (await getVideoFileResolution(videoPhysicalFile.path)).videoFileResolution | |
207 | } | |
208 | ||
209 | videoFile.filename = generateVideoFilename(video, false, videoFile.resolution, videoFile.extname) | |
210 | ||
211 | // Move physical file | |
212 | const destination = getVideoFilePath(video, videoFile) | |
213 | await move(videoPhysicalFile.path, destination) | |
214 | // This is important in case if there is another attempt in the retry process | |
215 | videoPhysicalFile.filename = getVideoFilePath(video, videoFile) | |
216 | videoPhysicalFile.path = destination | |
217 | ||
218 | const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({ | |
219 | video, | |
220 | files: req.files, | |
221 | fallback: type => generateVideoMiniature({ video, videoFile, type }) | |
222 | }) | |
223 | ||
224 | const { videoCreated } = await sequelizeTypescript.transaction(async t => { | |
225 | const sequelizeOptions = { transaction: t } | |
226 | ||
227 | const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight | |
228 | ||
229 | await videoCreated.addAndSaveThumbnail(thumbnailModel, t) | |
230 | await videoCreated.addAndSaveThumbnail(previewModel, t) | |
231 | ||
232 | // Do not forget to add video channel information to the created video | |
233 | videoCreated.VideoChannel = res.locals.videoChannel | |
234 | ||
235 | videoFile.videoId = video.id | |
236 | await videoFile.save(sequelizeOptions) | |
237 | ||
238 | video.VideoFiles = [ videoFile ] | |
239 | ||
240 | await setVideoTags({ video, tags: videoInfo.tags, transaction: t }) | |
241 | ||
242 | // Schedule an update in the future? | |
243 | if (videoInfo.scheduleUpdate) { | |
244 | await ScheduleVideoUpdateModel.create({ | |
245 | videoId: video.id, | |
246 | updateAt: videoInfo.scheduleUpdate.updateAt, | |
247 | privacy: videoInfo.scheduleUpdate.privacy || null | |
248 | }, { transaction: t }) | |
249 | } | |
250 | ||
251 | await autoBlacklistVideoIfNeeded({ | |
252 | video, | |
253 | user: res.locals.oauth.token.User, | |
254 | isRemote: false, | |
255 | isNew: true, | |
256 | transaction: t | |
257 | }) | |
258 | ||
259 | auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(videoCreated.toFormattedDetailsJSON())) | |
260 | logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid) | |
261 | ||
262 | return { videoCreated } | |
263 | }) | |
264 | ||
265 | // Create the torrent file in async way because it could be long | |
266 | createTorrentAndSetInfoHashAsync(video, videoFile) | |
267 | .catch(err => logger.error('Cannot create torrent file for video %s', video.url, { err })) | |
268 | .then(() => VideoModel.loadAndPopulateAccountAndServerAndTags(video.id)) | |
269 | .then(refreshedVideo => { | |
270 | if (!refreshedVideo) return | |
271 | ||
272 | // Only federate and notify after the torrent creation | |
273 | Notifier.Instance.notifyOnNewVideoIfNeeded(refreshedVideo) | |
274 | ||
275 | return retryTransactionWrapper(() => { | |
276 | return sequelizeTypescript.transaction(t => federateVideoIfNeeded(refreshedVideo, true, t)) | |
277 | }) | |
278 | }) | |
279 | .catch(err => logger.error('Cannot federate or notify video creation %s', video.url, { err })) | |
280 | ||
281 | if (video.state === VideoState.TO_TRANSCODE) { | |
282 | await addOptimizeOrMergeAudioJob(videoCreated, videoFile, res.locals.oauth.token.User) | |
283 | } | |
284 | ||
285 | Hooks.runAction('action:api.video.uploaded', { video: videoCreated }) | |
286 | ||
287 | return res.json({ | |
288 | video: { | |
289 | id: videoCreated.id, | |
290 | uuid: videoCreated.uuid | |
291 | } | |
292 | }) | |
293 | } | |
294 | ||
295 | async function updateVideo (req: express.Request, res: express.Response) { | |
296 | const videoInstance = res.locals.videoAll | |
297 | const videoFieldsSave = videoInstance.toJSON() | |
298 | const oldVideoAuditView = new VideoAuditView(videoInstance.toFormattedDetailsJSON()) | |
299 | const videoInfoToUpdate: VideoUpdate = req.body | |
300 | ||
301 | const wasConfidentialVideo = videoInstance.isConfidential() | |
302 | const hadPrivacyForFederation = videoInstance.hasPrivacyForFederation() | |
303 | ||
304 | const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({ | |
305 | video: videoInstance, | |
306 | files: req.files, | |
307 | fallback: () => Promise.resolve(undefined), | |
308 | automaticallyGenerated: false | |
309 | }) | |
310 | ||
311 | try { | |
312 | const videoInstanceUpdated = await sequelizeTypescript.transaction(async t => { | |
313 | const sequelizeOptions = { transaction: t } | |
314 | const oldVideoChannel = videoInstance.VideoChannel | |
315 | ||
316 | if (videoInfoToUpdate.name !== undefined) videoInstance.name = videoInfoToUpdate.name | |
317 | if (videoInfoToUpdate.category !== undefined) videoInstance.category = videoInfoToUpdate.category | |
318 | if (videoInfoToUpdate.licence !== undefined) videoInstance.licence = videoInfoToUpdate.licence | |
319 | if (videoInfoToUpdate.language !== undefined) videoInstance.language = videoInfoToUpdate.language | |
320 | if (videoInfoToUpdate.nsfw !== undefined) videoInstance.nsfw = videoInfoToUpdate.nsfw | |
321 | if (videoInfoToUpdate.waitTranscoding !== undefined) videoInstance.waitTranscoding = videoInfoToUpdate.waitTranscoding | |
322 | if (videoInfoToUpdate.support !== undefined) videoInstance.support = videoInfoToUpdate.support | |
323 | if (videoInfoToUpdate.description !== undefined) videoInstance.description = videoInfoToUpdate.description | |
324 | if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.commentsEnabled = videoInfoToUpdate.commentsEnabled | |
325 | if (videoInfoToUpdate.downloadEnabled !== undefined) videoInstance.downloadEnabled = videoInfoToUpdate.downloadEnabled | |
326 | ||
327 | if (videoInfoToUpdate.originallyPublishedAt !== undefined && videoInfoToUpdate.originallyPublishedAt !== null) { | |
328 | videoInstance.originallyPublishedAt = new Date(videoInfoToUpdate.originallyPublishedAt) | |
329 | } | |
330 | ||
331 | let isNewVideo = false | |
332 | if (videoInfoToUpdate.privacy !== undefined) { | |
333 | isNewVideo = videoInstance.isNewVideo(videoInfoToUpdate.privacy) | |
334 | ||
335 | const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10) | |
336 | videoInstance.setPrivacy(newPrivacy) | |
337 | ||
338 | // Unfederate the video if the new privacy is not compatible with federation | |
339 | if (hadPrivacyForFederation && !videoInstance.hasPrivacyForFederation()) { | |
340 | await VideoModel.sendDelete(videoInstance, { transaction: t }) | |
341 | } | |
342 | } | |
343 | ||
344 | const videoInstanceUpdated = await videoInstance.save(sequelizeOptions) as MVideoFullLight | |
345 | ||
346 | if (thumbnailModel) await videoInstanceUpdated.addAndSaveThumbnail(thumbnailModel, t) | |
347 | if (previewModel) await videoInstanceUpdated.addAndSaveThumbnail(previewModel, t) | |
348 | ||
349 | // Video tags update? | |
350 | await setVideoTags({ | |
351 | video: videoInstanceUpdated, | |
352 | tags: videoInfoToUpdate.tags, | |
353 | transaction: t, | |
354 | defaultValue: videoInstanceUpdated.Tags | |
355 | }) | |
356 | ||
357 | // Video channel update? | |
358 | if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) { | |
359 | await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t }) | |
360 | videoInstanceUpdated.VideoChannel = res.locals.videoChannel | |
361 | ||
362 | if (hadPrivacyForFederation === true) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t) | |
363 | } | |
364 | ||
365 | // Schedule an update in the future? | |
366 | if (videoInfoToUpdate.scheduleUpdate) { | |
367 | await ScheduleVideoUpdateModel.upsert({ | |
368 | videoId: videoInstanceUpdated.id, | |
369 | updateAt: videoInfoToUpdate.scheduleUpdate.updateAt, | |
370 | privacy: videoInfoToUpdate.scheduleUpdate.privacy || null | |
371 | }, { transaction: t }) | |
372 | } else if (videoInfoToUpdate.scheduleUpdate === null) { | |
373 | await ScheduleVideoUpdateModel.deleteByVideoId(videoInstanceUpdated.id, t) | |
374 | } | |
375 | ||
376 | await autoBlacklistVideoIfNeeded({ | |
377 | video: videoInstanceUpdated, | |
378 | user: res.locals.oauth.token.User, | |
379 | isRemote: false, | |
380 | isNew: false, | |
381 | transaction: t | |
382 | }) | |
383 | ||
384 | await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t) | |
385 | ||
386 | auditLogger.update( | |
387 | getAuditIdFromRes(res), | |
388 | new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()), | |
389 | oldVideoAuditView | |
390 | ) | |
391 | logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid) | |
392 | ||
393 | return videoInstanceUpdated | |
394 | }) | |
395 | ||
396 | if (wasConfidentialVideo) { | |
397 | Notifier.Instance.notifyOnNewVideoIfNeeded(videoInstanceUpdated) | |
398 | } | |
399 | ||
400 | Hooks.runAction('action:api.video.updated', { video: videoInstanceUpdated, body: req.body }) | |
401 | } catch (err) { | |
402 | // Force fields we want to update | |
403 | // If the transaction is retried, sequelize will think the object has not changed | |
404 | // So it will skip the SQL request, even if the last one was ROLLBACKed! | |
405 | resetSequelizeInstance(videoInstance, videoFieldsSave) | |
406 | ||
407 | throw err | |
408 | } | |
409 | ||
410 | return res.type('json') | |
411 | .status(HttpStatusCode.NO_CONTENT_204) | |
412 | .end() | |
413 | } | |
414 | ||
415 | async function getVideo (req: express.Request, res: express.Response) { | |
416 | // We need more attributes | |
417 | const userId: number = res.locals.oauth ? res.locals.oauth.token.User.id : null | |
418 | ||
419 | const video = await Hooks.wrapPromiseFun( | |
420 | VideoModel.loadForGetAPI, | |
421 | { id: res.locals.onlyVideoWithRights.id, userId }, | |
422 | 'filter:api.video.get.result' | |
423 | ) | |
424 | ||
425 | if (video.isOutdated()) { | |
426 | JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'video', url: video.url } }) | |
427 | } | |
428 | ||
429 | return res.json(video.toFormattedDetailsJSON()) | |
430 | } | |
431 | ||
432 | async function viewVideo (req: express.Request, res: express.Response) { | |
433 | const immutableVideoAttrs = res.locals.onlyImmutableVideo | |
434 | ||
435 | const ip = req.ip | |
436 | const exists = await Redis.Instance.doesVideoIPViewExist(ip, immutableVideoAttrs.uuid) | |
437 | if (exists) { | |
438 | logger.debug('View for ip %s and video %s already exists.', ip, immutableVideoAttrs.uuid) | |
439 | return res.sendStatus(HttpStatusCode.NO_CONTENT_204) | |
440 | } | |
441 | ||
442 | const video = await VideoModel.load(immutableVideoAttrs.id) | |
443 | ||
444 | const promises: Promise<any>[] = [ | |
445 | Redis.Instance.setIPVideoView(ip, video.uuid, video.isLive) | |
446 | ] | |
447 | ||
448 | let federateView = true | |
449 | ||
450 | // Increment our live manager | |
451 | if (video.isLive && video.isOwned()) { | |
452 | LiveManager.Instance.addViewTo(video.id) | |
453 | ||
454 | // Views of our local live will be sent by our live manager | |
455 | federateView = false | |
456 | } | |
457 | ||
458 | // Increment our video views cache counter | |
459 | if (!video.isLive) { | |
460 | promises.push(Redis.Instance.addVideoView(video.id)) | |
461 | } | |
462 | ||
463 | if (federateView) { | |
464 | const serverActor = await getServerActor() | |
465 | promises.push(sendView(serverActor, video, undefined)) | |
466 | } | |
467 | ||
468 | await Promise.all(promises) | |
469 | ||
470 | Hooks.runAction('action:api.video.viewed', { video, ip }) | |
471 | ||
472 | return res.sendStatus(HttpStatusCode.NO_CONTENT_204) | |
473 | } | |
474 | ||
475 | async function getVideoDescription (req: express.Request, res: express.Response) { | |
476 | const videoInstance = res.locals.videoAll | |
477 | let description = '' | |
478 | ||
479 | if (videoInstance.isOwned()) { | |
480 | description = videoInstance.description | |
481 | } else { | |
482 | description = await fetchRemoteVideoDescription(videoInstance) | |
483 | } | |
484 | ||
485 | return res.json({ description }) | |
486 | } | |
487 | ||
488 | async function getVideoFileMetadata (req: express.Request, res: express.Response) { | |
489 | const videoFile = await VideoFileModel.loadWithMetadata(toInt(req.params.videoFileId)) | |
490 | ||
491 | return res.json(videoFile.metadata) | |
492 | } | |
493 | ||
494 | async function listVideos (req: express.Request, res: express.Response) { | |
495 | const countVideos = getCountVideos(req) | |
496 | ||
497 | const apiOptions = await Hooks.wrapObject({ | |
498 | start: req.query.start, | |
499 | count: req.query.count, | |
500 | sort: req.query.sort, | |
501 | includeLocalVideos: true, | |
502 | categoryOneOf: req.query.categoryOneOf, | |
503 | licenceOneOf: req.query.licenceOneOf, | |
504 | languageOneOf: req.query.languageOneOf, | |
505 | tagsOneOf: req.query.tagsOneOf, | |
506 | tagsAllOf: req.query.tagsAllOf, | |
507 | nsfw: buildNSFWFilter(res, req.query.nsfw), | |
508 | filter: req.query.filter as VideoFilter, | |
509 | withFiles: false, | |
510 | user: res.locals.oauth ? res.locals.oauth.token.User : undefined, | |
511 | countVideos | |
512 | }, 'filter:api.videos.list.params') | |
513 | ||
514 | const resultList = await Hooks.wrapPromiseFun( | |
515 | VideoModel.listForApi, | |
516 | apiOptions, | |
517 | 'filter:api.videos.list.result' | |
518 | ) | |
519 | ||
520 | return res.json(getFormattedObjects(resultList.data, resultList.total)) | |
521 | } | |
522 | ||
523 | async function removeVideo (req: express.Request, res: express.Response) { | |
524 | const videoInstance = res.locals.videoAll | |
525 | ||
526 | await sequelizeTypescript.transaction(async t => { | |
527 | await videoInstance.destroy({ transaction: t }) | |
528 | }) | |
529 | ||
530 | auditLogger.delete(getAuditIdFromRes(res), new VideoAuditView(videoInstance.toFormattedDetailsJSON())) | |
531 | logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid) | |
532 | ||
533 | Hooks.runAction('action:api.video.deleted', { video: videoInstance }) | |
534 | ||
535 | return res.type('json') | |
536 | .status(HttpStatusCode.NO_CONTENT_204) | |
537 | .end() | |
538 | } | |
539 | ||
540 | async function createTorrentAndSetInfoHashAsync (video: MVideo, fileArg: MVideoFile) { | |
541 | await createTorrentAndSetInfoHash(video, fileArg) | |
542 | ||
543 | // Refresh videoFile because the createTorrentAndSetInfoHash could be long | |
544 | const refreshedFile = await VideoFileModel.loadWithVideo(fileArg.id) | |
545 | // File does not exist anymore, remove the generated torrent | |
546 | if (!refreshedFile) return fileArg.removeTorrent() | |
547 | ||
548 | refreshedFile.infoHash = fileArg.infoHash | |
549 | refreshedFile.torrentFilename = fileArg.torrentFilename | |
550 | ||
551 | return refreshedFile.save() | |
552 | } |