]>
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, VideosCommonQuery, VideoState, VideoUpdate } from '../../../../shared' | |
14 | import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' | |
15 | import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger' | |
16 | import { resetSequelizeInstance, retryTransactionWrapper } from '../../../helpers/database-utils' | |
17 | import { buildNSFWFilter, createReqFiles, getCountVideos } from '../../../helpers/express-utils' | |
18 | import { getMetadataFromFile, getVideoFileFPS, getVideoFileResolution } from '../../../helpers/ffprobe-utils' | |
19 | import { logger, loggerTagsFactory } from '../../../helpers/logger' | |
20 | import { getFormattedObjects } from '../../../helpers/utils' | |
21 | import { CONFIG } from '../../../initializers/config' | |
22 | import { | |
23 | DEFAULT_AUDIO_RESOLUTION, | |
24 | MIMETYPES, | |
25 | VIDEO_CATEGORIES, | |
26 | VIDEO_LANGUAGES, | |
27 | VIDEO_LICENCES, | |
28 | VIDEO_PRIVACIES | |
29 | } from '../../../initializers/constants' | |
30 | import { sequelizeTypescript } from '../../../initializers/database' | |
31 | import { sendView } from '../../../lib/activitypub/send/send-view' | |
32 | import { federateVideoIfNeeded, fetchRemoteVideoDescription } from '../../../lib/activitypub/videos' | |
33 | import { JobQueue } from '../../../lib/job-queue' | |
34 | import { Notifier } from '../../../lib/notifier' | |
35 | import { Hooks } from '../../../lib/plugins/hooks' | |
36 | import { Redis } from '../../../lib/redis' | |
37 | import { generateVideoMiniature } from '../../../lib/thumbnail' | |
38 | import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist' | |
39 | import { | |
40 | asyncMiddleware, | |
41 | asyncRetryTransactionMiddleware, | |
42 | authenticate, | |
43 | checkVideoFollowConstraints, | |
44 | commonVideosFiltersValidator, | |
45 | optionalAuthenticate, | |
46 | paginationValidator, | |
47 | setDefaultPagination, | |
48 | setDefaultVideosSort, | |
49 | videoFileMetadataGetValidator, | |
50 | videosAddValidator, | |
51 | videosCustomGetValidator, | |
52 | videosGetValidator, | |
53 | videosRemoveValidator, | |
54 | videosSortValidator, | |
55 | videosUpdateValidator | |
56 | } from '../../../middlewares' | |
57 | import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update' | |
58 | import { VideoModel } from '../../../models/video/video' | |
59 | import { VideoFileModel } from '../../../models/video/video-file' | |
60 | import { blacklistRouter } from './blacklist' | |
61 | import { videoCaptionsRouter } from './captions' | |
62 | import { videoCommentRouter } from './comment' | |
63 | import { videoImportsRouter } from './import' | |
64 | import { liveRouter } from './live' | |
65 | import { ownershipVideoRouter } from './ownership' | |
66 | import { rateVideoRouter } from './rate' | |
67 | import { watchingRouter } from './watching' | |
68 | ||
69 | const lTags = loggerTagsFactory('api', 'video') | |
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 | // Channel has a new content, set as updated | |
252 | await videoCreated.VideoChannel.setAsUpdated(t) | |
253 | ||
254 | await autoBlacklistVideoIfNeeded({ | |
255 | video, | |
256 | user: res.locals.oauth.token.User, | |
257 | isRemote: false, | |
258 | isNew: true, | |
259 | transaction: t | |
260 | }) | |
261 | ||
262 | auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(videoCreated.toFormattedDetailsJSON())) | |
263 | logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid, lTags(videoCreated.uuid)) | |
264 | ||
265 | return { videoCreated } | |
266 | }) | |
267 | ||
268 | // Create the torrent file in async way because it could be long | |
269 | createTorrentAndSetInfoHashAsync(video, videoFile) | |
270 | .catch(err => logger.error('Cannot create torrent file for video %s', video.url, { err, ...lTags(video.uuid) })) | |
271 | .then(() => VideoModel.loadAndPopulateAccountAndServerAndTags(video.id)) | |
272 | .then(refreshedVideo => { | |
273 | if (!refreshedVideo) return | |
274 | ||
275 | // Only federate and notify after the torrent creation | |
276 | Notifier.Instance.notifyOnNewVideoIfNeeded(refreshedVideo) | |
277 | ||
278 | return retryTransactionWrapper(() => { | |
279 | return sequelizeTypescript.transaction(t => federateVideoIfNeeded(refreshedVideo, true, t)) | |
280 | }) | |
281 | }) | |
282 | .catch(err => logger.error('Cannot federate or notify video creation %s', video.url, { err, ...lTags(video.uuid) })) | |
283 | ||
284 | if (video.state === VideoState.TO_TRANSCODE) { | |
285 | await addOptimizeOrMergeAudioJob(videoCreated, videoFile, res.locals.oauth.token.User) | |
286 | } | |
287 | ||
288 | Hooks.runAction('action:api.video.uploaded', { video: videoCreated }) | |
289 | ||
290 | return res.json({ | |
291 | video: { | |
292 | id: videoCreated.id, | |
293 | uuid: videoCreated.uuid | |
294 | } | |
295 | }) | |
296 | } | |
297 | ||
298 | async function updateVideo (req: express.Request, res: express.Response) { | |
299 | const videoInstance = res.locals.videoAll | |
300 | const videoFieldsSave = videoInstance.toJSON() | |
301 | const oldVideoAuditView = new VideoAuditView(videoInstance.toFormattedDetailsJSON()) | |
302 | const videoInfoToUpdate: VideoUpdate = req.body | |
303 | ||
304 | const wasConfidentialVideo = videoInstance.isConfidential() | |
305 | const hadPrivacyForFederation = videoInstance.hasPrivacyForFederation() | |
306 | ||
307 | const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({ | |
308 | video: videoInstance, | |
309 | files: req.files, | |
310 | fallback: () => Promise.resolve(undefined), | |
311 | automaticallyGenerated: false | |
312 | }) | |
313 | ||
314 | try { | |
315 | const videoInstanceUpdated = await sequelizeTypescript.transaction(async t => { | |
316 | const sequelizeOptions = { transaction: t } | |
317 | const oldVideoChannel = videoInstance.VideoChannel | |
318 | ||
319 | if (videoInfoToUpdate.name !== undefined) videoInstance.name = videoInfoToUpdate.name | |
320 | if (videoInfoToUpdate.category !== undefined) videoInstance.category = videoInfoToUpdate.category | |
321 | if (videoInfoToUpdate.licence !== undefined) videoInstance.licence = videoInfoToUpdate.licence | |
322 | if (videoInfoToUpdate.language !== undefined) videoInstance.language = videoInfoToUpdate.language | |
323 | if (videoInfoToUpdate.nsfw !== undefined) videoInstance.nsfw = videoInfoToUpdate.nsfw | |
324 | if (videoInfoToUpdate.waitTranscoding !== undefined) videoInstance.waitTranscoding = videoInfoToUpdate.waitTranscoding | |
325 | if (videoInfoToUpdate.support !== undefined) videoInstance.support = videoInfoToUpdate.support | |
326 | if (videoInfoToUpdate.description !== undefined) videoInstance.description = videoInfoToUpdate.description | |
327 | if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.commentsEnabled = videoInfoToUpdate.commentsEnabled | |
328 | if (videoInfoToUpdate.downloadEnabled !== undefined) videoInstance.downloadEnabled = videoInfoToUpdate.downloadEnabled | |
329 | ||
330 | if (videoInfoToUpdate.originallyPublishedAt !== undefined && videoInfoToUpdate.originallyPublishedAt !== null) { | |
331 | videoInstance.originallyPublishedAt = new Date(videoInfoToUpdate.originallyPublishedAt) | |
332 | } | |
333 | ||
334 | let isNewVideo = false | |
335 | if (videoInfoToUpdate.privacy !== undefined) { | |
336 | isNewVideo = videoInstance.isNewVideo(videoInfoToUpdate.privacy) | |
337 | ||
338 | const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10) | |
339 | videoInstance.setPrivacy(newPrivacy) | |
340 | ||
341 | // Unfederate the video if the new privacy is not compatible with federation | |
342 | if (hadPrivacyForFederation && !videoInstance.hasPrivacyForFederation()) { | |
343 | await VideoModel.sendDelete(videoInstance, { transaction: t }) | |
344 | } | |
345 | } | |
346 | ||
347 | const videoInstanceUpdated = await videoInstance.save(sequelizeOptions) as MVideoFullLight | |
348 | ||
349 | if (thumbnailModel) await videoInstanceUpdated.addAndSaveThumbnail(thumbnailModel, t) | |
350 | if (previewModel) await videoInstanceUpdated.addAndSaveThumbnail(previewModel, t) | |
351 | ||
352 | // Video tags update? | |
353 | if (videoInfoToUpdate.tags !== undefined) { | |
354 | await setVideoTags({ | |
355 | video: videoInstanceUpdated, | |
356 | tags: videoInfoToUpdate.tags, | |
357 | transaction: t | |
358 | }) | |
359 | } | |
360 | ||
361 | // Video channel update? | |
362 | if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) { | |
363 | await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t }) | |
364 | videoInstanceUpdated.VideoChannel = res.locals.videoChannel | |
365 | ||
366 | if (hadPrivacyForFederation === true) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t) | |
367 | } | |
368 | ||
369 | // Schedule an update in the future? | |
370 | if (videoInfoToUpdate.scheduleUpdate) { | |
371 | await ScheduleVideoUpdateModel.upsert({ | |
372 | videoId: videoInstanceUpdated.id, | |
373 | updateAt: videoInfoToUpdate.scheduleUpdate.updateAt, | |
374 | privacy: videoInfoToUpdate.scheduleUpdate.privacy || null | |
375 | }, { transaction: t }) | |
376 | } else if (videoInfoToUpdate.scheduleUpdate === null) { | |
377 | await ScheduleVideoUpdateModel.deleteByVideoId(videoInstanceUpdated.id, t) | |
378 | } | |
379 | ||
380 | await autoBlacklistVideoIfNeeded({ | |
381 | video: videoInstanceUpdated, | |
382 | user: res.locals.oauth.token.User, | |
383 | isRemote: false, | |
384 | isNew: false, | |
385 | transaction: t | |
386 | }) | |
387 | ||
388 | await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t) | |
389 | ||
390 | auditLogger.update( | |
391 | getAuditIdFromRes(res), | |
392 | new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()), | |
393 | oldVideoAuditView | |
394 | ) | |
395 | logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid, lTags(videoInstance.uuid)) | |
396 | ||
397 | return videoInstanceUpdated | |
398 | }) | |
399 | ||
400 | if (wasConfidentialVideo) { | |
401 | Notifier.Instance.notifyOnNewVideoIfNeeded(videoInstanceUpdated) | |
402 | } | |
403 | ||
404 | Hooks.runAction('action:api.video.updated', { video: videoInstanceUpdated, body: req.body }) | |
405 | } catch (err) { | |
406 | // Force fields we want to update | |
407 | // If the transaction is retried, sequelize will think the object has not changed | |
408 | // So it will skip the SQL request, even if the last one was ROLLBACKed! | |
409 | resetSequelizeInstance(videoInstance, videoFieldsSave) | |
410 | ||
411 | throw err | |
412 | } | |
413 | ||
414 | return res.type('json') | |
415 | .status(HttpStatusCode.NO_CONTENT_204) | |
416 | .end() | |
417 | } | |
418 | ||
419 | async function getVideo (req: express.Request, res: express.Response) { | |
420 | // We need more attributes | |
421 | const userId: number = res.locals.oauth ? res.locals.oauth.token.User.id : null | |
422 | ||
423 | const video = await Hooks.wrapPromiseFun( | |
424 | VideoModel.loadForGetAPI, | |
425 | { id: res.locals.onlyVideoWithRights.id, userId }, | |
426 | 'filter:api.video.get.result' | |
427 | ) | |
428 | ||
429 | if (video.isOutdated()) { | |
430 | JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'video', url: video.url } }) | |
431 | } | |
432 | ||
433 | return res.json(video.toFormattedDetailsJSON()) | |
434 | } | |
435 | ||
436 | async function viewVideo (req: express.Request, res: express.Response) { | |
437 | const immutableVideoAttrs = res.locals.onlyImmutableVideo | |
438 | ||
439 | const ip = req.ip | |
440 | const exists = await Redis.Instance.doesVideoIPViewExist(ip, immutableVideoAttrs.uuid) | |
441 | if (exists) { | |
442 | logger.debug('View for ip %s and video %s already exists.', ip, immutableVideoAttrs.uuid) | |
443 | return res.sendStatus(HttpStatusCode.NO_CONTENT_204) | |
444 | } | |
445 | ||
446 | const video = await VideoModel.load(immutableVideoAttrs.id) | |
447 | ||
448 | const promises: Promise<any>[] = [ | |
449 | Redis.Instance.setIPVideoView(ip, video.uuid, video.isLive) | |
450 | ] | |
451 | ||
452 | let federateView = true | |
453 | ||
454 | // Increment our live manager | |
455 | if (video.isLive && video.isOwned()) { | |
456 | LiveManager.Instance.addViewTo(video.id) | |
457 | ||
458 | // Views of our local live will be sent by our live manager | |
459 | federateView = false | |
460 | } | |
461 | ||
462 | // Increment our video views cache counter | |
463 | if (!video.isLive) { | |
464 | promises.push(Redis.Instance.addVideoView(video.id)) | |
465 | } | |
466 | ||
467 | if (federateView) { | |
468 | const serverActor = await getServerActor() | |
469 | promises.push(sendView(serverActor, video, undefined)) | |
470 | } | |
471 | ||
472 | await Promise.all(promises) | |
473 | ||
474 | Hooks.runAction('action:api.video.viewed', { video, ip }) | |
475 | ||
476 | return res.sendStatus(HttpStatusCode.NO_CONTENT_204) | |
477 | } | |
478 | ||
479 | async function getVideoDescription (req: express.Request, res: express.Response) { | |
480 | const videoInstance = res.locals.videoAll | |
481 | let description = '' | |
482 | ||
483 | if (videoInstance.isOwned()) { | |
484 | description = videoInstance.description | |
485 | } else { | |
486 | description = await fetchRemoteVideoDescription(videoInstance) | |
487 | } | |
488 | ||
489 | return res.json({ description }) | |
490 | } | |
491 | ||
492 | async function getVideoFileMetadata (req: express.Request, res: express.Response) { | |
493 | const videoFile = await VideoFileModel.loadWithMetadata(toInt(req.params.videoFileId)) | |
494 | ||
495 | return res.json(videoFile.metadata) | |
496 | } | |
497 | ||
498 | async function listVideos (req: express.Request, res: express.Response) { | |
499 | const query = req.query as VideosCommonQuery | |
500 | const countVideos = getCountVideos(req) | |
501 | ||
502 | const apiOptions = await Hooks.wrapObject({ | |
503 | start: query.start, | |
504 | count: query.count, | |
505 | sort: query.sort, | |
506 | includeLocalVideos: true, | |
507 | categoryOneOf: query.categoryOneOf, | |
508 | licenceOneOf: query.licenceOneOf, | |
509 | languageOneOf: query.languageOneOf, | |
510 | tagsOneOf: query.tagsOneOf, | |
511 | tagsAllOf: query.tagsAllOf, | |
512 | nsfw: buildNSFWFilter(res, query.nsfw), | |
513 | isLive: query.isLive, | |
514 | filter: query.filter, | |
515 | withFiles: false, | |
516 | user: res.locals.oauth ? res.locals.oauth.token.User : undefined, | |
517 | countVideos | |
518 | }, 'filter:api.videos.list.params') | |
519 | ||
520 | const resultList = await Hooks.wrapPromiseFun( | |
521 | VideoModel.listForApi, | |
522 | apiOptions, | |
523 | 'filter:api.videos.list.result' | |
524 | ) | |
525 | ||
526 | return res.json(getFormattedObjects(resultList.data, resultList.total)) | |
527 | } | |
528 | ||
529 | async function removeVideo (req: express.Request, res: express.Response) { | |
530 | const videoInstance = res.locals.videoAll | |
531 | ||
532 | await sequelizeTypescript.transaction(async t => { | |
533 | await videoInstance.destroy({ transaction: t }) | |
534 | }) | |
535 | ||
536 | auditLogger.delete(getAuditIdFromRes(res), new VideoAuditView(videoInstance.toFormattedDetailsJSON())) | |
537 | logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid) | |
538 | ||
539 | Hooks.runAction('action:api.video.deleted', { video: videoInstance }) | |
540 | ||
541 | return res.type('json') | |
542 | .status(HttpStatusCode.NO_CONTENT_204) | |
543 | .end() | |
544 | } | |
545 | ||
546 | async function createTorrentAndSetInfoHashAsync (video: MVideo, fileArg: MVideoFile) { | |
547 | await createTorrentAndSetInfoHash(video, fileArg) | |
548 | ||
549 | // Refresh videoFile because the createTorrentAndSetInfoHash could be long | |
550 | const refreshedFile = await VideoFileModel.loadWithVideo(fileArg.id) | |
551 | // File does not exist anymore, remove the generated torrent | |
552 | if (!refreshedFile) return fileArg.removeTorrent() | |
553 | ||
554 | refreshedFile.infoHash = fileArg.infoHash | |
555 | refreshedFile.torrentFilename = fileArg.torrentFilename | |
556 | ||
557 | return refreshedFile.save() | |
558 | } |