]>
Commit | Line | Data |
---|---|---|
4d4e5cd4 | 1 | import * as express from 'express' |
8054669f | 2 | import { move } from 'fs-extra' |
3f6b7aa1 | 3 | import { extname } from 'path' |
8054669f | 4 | import toInt from 'validator/lib/toInt' |
8054669f C |
5 | import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent' |
6 | import { changeVideoChannelShare } from '@server/lib/activitypub/share' | |
de94ac86 | 7 | import { getLocalVideoActivityPubUrl } from '@server/lib/activitypub/url' |
7a4ea932 | 8 | import { LiveManager } from '@server/lib/live-manager' |
77d7e851 | 9 | import { addOptimizeOrMergeAudioJob, buildLocalVideoFromReq, buildVideoThumbnailsFromReq, setVideoTags } from '@server/lib/video' |
90a8bd30 | 10 | import { generateVideoFilename, getVideoFilePath } from '@server/lib/video-paths' |
8054669f | 11 | import { getServerActor } from '@server/models/application/application' |
d61893f7 | 12 | import { MVideo, MVideoFile, MVideoFullLight } from '@server/types/models' |
1ef65f4c | 13 | import { VideoCreate, VideoState, VideoUpdate } from '../../../../shared' |
77d7e851 | 14 | import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' |
8054669f C |
15 | import { VideoFilter } from '../../../../shared/models/videos/video-query.type' |
16 | import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger' | |
d61893f7 | 17 | import { resetSequelizeInstance, retryTransactionWrapper } from '../../../helpers/database-utils' |
8054669f | 18 | import { buildNSFWFilter, createReqFiles, getCountVideos } from '../../../helpers/express-utils' |
daf6e480 | 19 | import { getMetadataFromFile, getVideoFileFPS, getVideoFileResolution } from '../../../helpers/ffprobe-utils' |
da854ddd | 20 | import { logger } from '../../../helpers/logger' |
8dc8a34e | 21 | import { getFormattedObjects } from '../../../helpers/utils' |
8054669f | 22 | import { CONFIG } from '../../../initializers/config' |
b345a804 C |
23 | import { |
24 | DEFAULT_AUDIO_RESOLUTION, | |
25 | MIMETYPES, | |
26 | VIDEO_CATEGORIES, | |
27 | VIDEO_LANGUAGES, | |
28 | VIDEO_LICENCES, | |
a1587156 | 29 | VIDEO_PRIVACIES |
b345a804 | 30 | } from '../../../initializers/constants' |
8054669f C |
31 | import { sequelizeTypescript } from '../../../initializers/database' |
32 | import { sendView } from '../../../lib/activitypub/send/send-view' | |
8dc8a34e | 33 | import { federateVideoIfNeeded, fetchRemoteVideoDescription } from '../../../lib/activitypub/videos' |
94a5ff8a | 34 | import { JobQueue } from '../../../lib/job-queue' |
8054669f C |
35 | import { Notifier } from '../../../lib/notifier' |
36 | import { Hooks } from '../../../lib/plugins/hooks' | |
b5c0e955 | 37 | import { Redis } from '../../../lib/redis' |
1ef65f4c | 38 | import { generateVideoMiniature } from '../../../lib/thumbnail' |
8054669f | 39 | import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist' |
65fcc311 | 40 | import { |
ac81d1a0 | 41 | asyncMiddleware, |
90d4bb81 | 42 | asyncRetryTransactionMiddleware, |
ac81d1a0 | 43 | authenticate, |
8d427346 | 44 | checkVideoFollowConstraints, |
d525fc39 | 45 | commonVideosFiltersValidator, |
0883b324 | 46 | optionalAuthenticate, |
ac81d1a0 C |
47 | paginationValidator, |
48 | setDefaultPagination, | |
8054669f | 49 | setDefaultVideosSort, |
d57d1d83 | 50 | videoFileMetadataGetValidator, |
ac81d1a0 | 51 | videosAddValidator, |
09209296 | 52 | videosCustomGetValidator, |
ac81d1a0 C |
53 | videosGetValidator, |
54 | videosRemoveValidator, | |
ac81d1a0 | 55 | videosSortValidator, |
d57d1d83 | 56 | videosUpdateValidator |
65fcc311 | 57 | } from '../../../middlewares' |
8054669f | 58 | import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update' |
3fd3ab2d C |
59 | import { VideoModel } from '../../../models/video/video' |
60 | import { VideoFileModel } from '../../../models/video/video-file' | |
65fcc311 | 61 | import { blacklistRouter } from './blacklist' |
40e87e9e | 62 | import { videoCaptionsRouter } from './captions' |
8054669f | 63 | import { videoCommentRouter } from './comment' |
fbad87b0 | 64 | import { videoImportsRouter } from './import' |
c6c0fa6c | 65 | import { liveRouter } from './live' |
8054669f C |
66 | import { ownershipVideoRouter } from './ownership' |
67 | import { rateVideoRouter } from './rate' | |
6e46de09 | 68 | import { watchingRouter } from './watching' |
65fcc311 | 69 | |
80e36cd9 | 70 | const auditLogger = auditLoggerFactory('videos') |
65fcc311 | 71 | const videosRouter = express.Router() |
9f10b292 | 72 | |
ac81d1a0 C |
73 | const reqVideoFileAdd = createReqFiles( |
74 | [ 'videofile', 'thumbnailfile', 'previewfile' ], | |
14e2014a | 75 | Object.assign({}, MIMETYPES.VIDEO.MIMETYPE_EXT, MIMETYPES.IMAGE.MIMETYPE_EXT), |
ac81d1a0 | 76 | { |
6040f87d C |
77 | videofile: CONFIG.STORAGE.TMP_DIR, |
78 | thumbnailfile: CONFIG.STORAGE.TMP_DIR, | |
79 | previewfile: CONFIG.STORAGE.TMP_DIR | |
ac81d1a0 C |
80 | } |
81 | ) | |
82 | const reqVideoFileUpdate = createReqFiles( | |
83 | [ 'thumbnailfile', 'previewfile' ], | |
14e2014a | 84 | MIMETYPES.IMAGE.MIMETYPE_EXT, |
ac81d1a0 | 85 | { |
6040f87d C |
86 | thumbnailfile: CONFIG.STORAGE.TMP_DIR, |
87 | previewfile: CONFIG.STORAGE.TMP_DIR | |
ac81d1a0 C |
88 | } |
89 | ) | |
8c308c2b | 90 | |
65fcc311 C |
91 | videosRouter.use('/', blacklistRouter) |
92 | videosRouter.use('/', rateVideoRouter) | |
bf1f6508 | 93 | videosRouter.use('/', videoCommentRouter) |
40e87e9e | 94 | videosRouter.use('/', videoCaptionsRouter) |
fbad87b0 | 95 | videosRouter.use('/', videoImportsRouter) |
74d63469 | 96 | videosRouter.use('/', ownershipVideoRouter) |
6e46de09 | 97 | videosRouter.use('/', watchingRouter) |
c6c0fa6c | 98 | videosRouter.use('/', liveRouter) |
d33242b0 | 99 | |
65fcc311 C |
100 | videosRouter.get('/categories', listVideoCategories) |
101 | videosRouter.get('/licences', listVideoLicences) | |
102 | videosRouter.get('/languages', listVideoLanguages) | |
fd45e8f4 | 103 | videosRouter.get('/privacies', listVideoPrivacies) |
6e07c3de | 104 | |
65fcc311 C |
105 | videosRouter.get('/', |
106 | paginationValidator, | |
107 | videosSortValidator, | |
8054669f | 108 | setDefaultVideosSort, |
f05a1c30 | 109 | setDefaultPagination, |
0883b324 | 110 | optionalAuthenticate, |
d525fc39 | 111 | commonVideosFiltersValidator, |
eb080476 | 112 | asyncMiddleware(listVideos) |
fbf1134e | 113 | ) |
65fcc311 C |
114 | videosRouter.put('/:id', |
115 | authenticate, | |
ac81d1a0 | 116 | reqVideoFileUpdate, |
a2431b7d | 117 | asyncMiddleware(videosUpdateValidator), |
90d4bb81 | 118 | asyncRetryTransactionMiddleware(updateVideo) |
7b1f49de | 119 | ) |
e95561cd | 120 | videosRouter.post('/upload', |
65fcc311 | 121 | authenticate, |
ac81d1a0 | 122 | reqVideoFileAdd, |
3fd3ab2d | 123 | asyncMiddleware(videosAddValidator), |
90d4bb81 | 124 | asyncRetryTransactionMiddleware(addVideo) |
fbf1134e | 125 | ) |
9567011b C |
126 | |
127 | videosRouter.get('/:id/description', | |
a2431b7d | 128 | asyncMiddleware(videosGetValidator), |
9567011b C |
129 | asyncMiddleware(getVideoDescription) |
130 | ) | |
8319d6ae RK |
131 | videosRouter.get('/:id/metadata/:videoFileId', |
132 | asyncMiddleware(videoFileMetadataGetValidator), | |
133 | asyncMiddleware(getVideoFileMetadata) | |
134 | ) | |
65fcc311 | 135 | videosRouter.get('/:id', |
6e46de09 | 136 | optionalAuthenticate, |
09209296 | 137 | asyncMiddleware(videosCustomGetValidator('only-video-with-rights')), |
8d427346 | 138 | asyncMiddleware(checkVideoFollowConstraints), |
09209296 | 139 | asyncMiddleware(getVideo) |
fbf1134e | 140 | ) |
1f3e9fec | 141 | videosRouter.post('/:id/views', |
2c8776fc | 142 | asyncMiddleware(videosCustomGetValidator('only-immutable-attributes')), |
1f3e9fec C |
143 | asyncMiddleware(viewVideo) |
144 | ) | |
198b205c | 145 | |
65fcc311 C |
146 | videosRouter.delete('/:id', |
147 | authenticate, | |
a2431b7d | 148 | asyncMiddleware(videosRemoveValidator), |
90d4bb81 | 149 | asyncRetryTransactionMiddleware(removeVideo) |
fbf1134e | 150 | ) |
198b205c | 151 | |
9f10b292 | 152 | // --------------------------------------------------------------------------- |
c45f7f84 | 153 | |
65fcc311 C |
154 | export { |
155 | videosRouter | |
156 | } | |
c45f7f84 | 157 | |
9f10b292 | 158 | // --------------------------------------------------------------------------- |
c45f7f84 | 159 | |
556ddc31 | 160 | function listVideoCategories (req: express.Request, res: express.Response) { |
65fcc311 | 161 | res.json(VIDEO_CATEGORIES) |
6e07c3de C |
162 | } |
163 | ||
556ddc31 | 164 | function listVideoLicences (req: express.Request, res: express.Response) { |
65fcc311 | 165 | res.json(VIDEO_LICENCES) |
6f0c39e2 C |
166 | } |
167 | ||
556ddc31 | 168 | function listVideoLanguages (req: express.Request, res: express.Response) { |
65fcc311 | 169 | res.json(VIDEO_LANGUAGES) |
3092476e C |
170 | } |
171 | ||
fd45e8f4 C |
172 | function listVideoPrivacies (req: express.Request, res: express.Response) { |
173 | res.json(VIDEO_PRIVACIES) | |
174 | } | |
175 | ||
90d4bb81 | 176 | async function addVideo (req: express.Request, res: express.Response) { |
bb4ba6d9 | 177 | // Uploading the video could be long |
d4132d3f | 178 | // Set timeout to 10 minutes, as Express's default is 2 minutes |
8b917537 C |
179 | req.setTimeout(1000 * 60 * 10, () => { |
180 | logger.error('Upload video has timed out.') | |
2d53be02 | 181 | return res.sendStatus(HttpStatusCode.REQUEST_TIMEOUT_408) |
8b917537 C |
182 | }) |
183 | ||
90d4bb81 | 184 | const videoPhysicalFile = req.files['videofile'][0] |
556ddc31 | 185 | const videoInfo: VideoCreate = req.body |
9f10b292 | 186 | |
1ef65f4c C |
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 | |
7ccddd7b | 190 | |
af4ae64f | 191 | const video = new VideoModel(videoData) as MVideoFullLight |
90a8bd30 | 192 | video.VideoChannel = res.locals.videoChannel |
de94ac86 | 193 | video.url = getLocalVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object |
eb080476 | 194 | |
46a6db24 | 195 | const videoFile = new VideoFileModel({ |
e11f68a3 | 196 | extname: extname(videoPhysicalFile.filename), |
d7a25329 | 197 | size: videoPhysicalFile.size, |
8319d6ae | 198 | videoStreamingPlaylistId: null, |
daf6e480 | 199 | metadata: await getMetadataFromFile(videoPhysicalFile.path) |
46a6db24 | 200 | }) |
2186386c | 201 | |
ad3405d0 C |
202 | if (videoFile.isAudio()) { |
203 | videoFile.resolution = DEFAULT_AUDIO_RESOLUTION | |
204 | } else { | |
536598cf C |
205 | videoFile.fps = await getVideoFileFPS(videoPhysicalFile.path) |
206 | videoFile.resolution = (await getVideoFileResolution(videoPhysicalFile.path)).videoFileResolution | |
536598cf C |
207 | } |
208 | ||
90a8bd30 C |
209 | videoFile.filename = generateVideoFilename(video, false, videoFile.resolution, videoFile.extname) |
210 | ||
2186386c | 211 | // Move physical file |
d7a25329 | 212 | const destination = getVideoFilePath(video, videoFile) |
14e2014a | 213 | await move(videoPhysicalFile.path, destination) |
e3a682a8 | 214 | // This is important in case if there is another attempt in the retry process |
d7a25329 | 215 | videoPhysicalFile.filename = getVideoFilePath(video, videoFile) |
82815eb6 | 216 | videoPhysicalFile.path = destination |
ac81d1a0 | 217 | |
1ef65f4c C |
218 | const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({ |
219 | video, | |
220 | files: req.files, | |
a35a2279 | 221 | fallback: type => generateVideoMiniature({ video, videoFile, type }) |
1ef65f4c | 222 | }) |
eb080476 | 223 | |
5b77537c | 224 | const { videoCreated } = await sequelizeTypescript.transaction(async t => { |
e11f68a3 | 225 | const sequelizeOptions = { transaction: t } |
eb080476 | 226 | |
453e83ea | 227 | const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight |
e8bafea3 | 228 | |
3acc5084 C |
229 | await videoCreated.addAndSaveThumbnail(thumbnailModel, t) |
230 | await videoCreated.addAndSaveThumbnail(previewModel, t) | |
e8bafea3 | 231 | |
eb080476 C |
232 | // Do not forget to add video channel information to the created video |
233 | videoCreated.VideoChannel = res.locals.videoChannel | |
7920c273 | 234 | |
eb080476 | 235 | videoFile.videoId = video.id |
eb080476 | 236 | await videoFile.save(sequelizeOptions) |
e11f68a3 C |
237 | |
238 | video.VideoFiles = [ videoFile ] | |
93e1258c | 239 | |
1ef65f4c | 240 | await setVideoTags({ video, tags: videoInfo.tags, transaction: t }) |
eb080476 | 241 | |
2baea0c7 C |
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 | ||
5b77537c | 251 | await autoBlacklistVideoIfNeeded({ |
6691c522 C |
252 | video, |
253 | user: res.locals.oauth.token.User, | |
254 | isRemote: false, | |
255 | isNew: true, | |
256 | transaction: t | |
257 | }) | |
eb080476 | 258 | |
993cef4b | 259 | auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(videoCreated.toFormattedDetailsJSON())) |
cadb46d8 C |
260 | logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid) |
261 | ||
5b77537c | 262 | return { videoCreated } |
cadb46d8 | 263 | }) |
94a5ff8a | 264 | |
d61893f7 C |
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 })) | |
e8d246d5 | 280 | |
2186386c | 281 | if (video.state === VideoState.TO_TRANSCODE) { |
77d7e851 | 282 | await addOptimizeOrMergeAudioJob(videoCreated, videoFile, res.locals.oauth.token.User) |
94a5ff8a C |
283 | } |
284 | ||
b4055e1c C |
285 | Hooks.runAction('action:api.video.uploaded', { video: videoCreated }) |
286 | ||
90d4bb81 C |
287 | return res.json({ |
288 | video: { | |
289 | id: videoCreated.id, | |
290 | uuid: videoCreated.uuid | |
291 | } | |
c6c0fa6c | 292 | }) |
ed04d94f C |
293 | } |
294 | ||
eb080476 | 295 | async function updateVideo (req: express.Request, res: express.Response) { |
453e83ea | 296 | const videoInstance = res.locals.videoAll |
7f4e7c36 | 297 | const videoFieldsSave = videoInstance.toJSON() |
80e36cd9 | 298 | const oldVideoAuditView = new VideoAuditView(videoInstance.toFormattedDetailsJSON()) |
556ddc31 | 299 | const videoInfoToUpdate: VideoUpdate = req.body |
46a6db24 | 300 | |
22a73cb8 C |
301 | const wasConfidentialVideo = videoInstance.isConfidential() |
302 | const hadPrivacyForFederation = videoInstance.hasPrivacyForFederation() | |
7b1f49de | 303 | |
1ef65f4c C |
304 | const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({ |
305 | video: videoInstance, | |
306 | files: req.files, | |
307 | fallback: () => Promise.resolve(undefined), | |
308 | automaticallyGenerated: false | |
309 | }) | |
ac81d1a0 | 310 | |
eb080476 | 311 | try { |
e8d246d5 C |
312 | const videoInstanceUpdated = await sequelizeTypescript.transaction(async t => { |
313 | const sequelizeOptions = { transaction: t } | |
0f320037 | 314 | const oldVideoChannel = videoInstance.VideoChannel |
7b1f49de | 315 | |
6691c522 C |
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 | |
b718fd22 C |
326 | |
327 | if (videoInfoToUpdate.originallyPublishedAt !== undefined && videoInfoToUpdate.originallyPublishedAt !== null) { | |
1735c825 | 328 | videoInstance.originallyPublishedAt = new Date(videoInfoToUpdate.originallyPublishedAt) |
1e74f19a | 329 | } |
330 | ||
22a73cb8 | 331 | let isNewVideo = false |
2922e048 | 332 | if (videoInfoToUpdate.privacy !== undefined) { |
22a73cb8 | 333 | isNewVideo = videoInstance.isNewVideo(videoInfoToUpdate.privacy) |
2922e048 | 334 | |
22a73cb8 C |
335 | const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10) |
336 | videoInstance.setPrivacy(newPrivacy) | |
46a6db24 | 337 | |
22a73cb8 C |
338 | // Unfederate the video if the new privacy is not compatible with federation |
339 | if (hadPrivacyForFederation && !videoInstance.hasPrivacyForFederation()) { | |
46a6db24 C |
340 | await VideoModel.sendDelete(videoInstance, { transaction: t }) |
341 | } | |
2922e048 | 342 | } |
7b1f49de | 343 | |
453e83ea | 344 | const videoInstanceUpdated = await videoInstance.save(sequelizeOptions) as MVideoFullLight |
7b1f49de | 345 | |
3acc5084 C |
346 | if (thumbnailModel) await videoInstanceUpdated.addAndSaveThumbnail(thumbnailModel, t) |
347 | if (previewModel) await videoInstanceUpdated.addAndSaveThumbnail(previewModel, t) | |
e8bafea3 | 348 | |
0f320037 | 349 | // Video tags update? |
1ef65f4c C |
350 | await setVideoTags({ |
351 | video: videoInstanceUpdated, | |
352 | tags: videoInfoToUpdate.tags, | |
353 | transaction: t, | |
354 | defaultValue: videoInstanceUpdated.Tags | |
355 | }) | |
7920c273 | 356 | |
0f320037 C |
357 | // Video channel update? |
358 | if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) { | |
6200d8d9 | 359 | await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t }) |
2186386c | 360 | videoInstanceUpdated.VideoChannel = res.locals.videoChannel |
0f320037 | 361 | |
22a73cb8 | 362 | if (hadPrivacyForFederation === true) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t) |
fd45e8f4 C |
363 | } |
364 | ||
2baea0c7 C |
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 }) | |
e94fc297 C |
372 | } else if (videoInfoToUpdate.scheduleUpdate === null) { |
373 | await ScheduleVideoUpdateModel.deleteByVideoId(videoInstanceUpdated.id, t) | |
2baea0c7 C |
374 | } |
375 | ||
6691c522 C |
376 | await autoBlacklistVideoIfNeeded({ |
377 | video: videoInstanceUpdated, | |
378 | user: res.locals.oauth.token.User, | |
379 | isRemote: false, | |
380 | isNew: false, | |
381 | transaction: t | |
382 | }) | |
383 | ||
5b77537c | 384 | await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t) |
6fcd19ba | 385 | |
80e36cd9 | 386 | auditLogger.update( |
993cef4b | 387 | getAuditIdFromRes(res), |
80e36cd9 AB |
388 | new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()), |
389 | oldVideoAuditView | |
390 | ) | |
391 | logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid) | |
e8d246d5 C |
392 | |
393 | return videoInstanceUpdated | |
80e36cd9 | 394 | }) |
e8d246d5 | 395 | |
22a73cb8 | 396 | if (wasConfidentialVideo) { |
5b77537c | 397 | Notifier.Instance.notifyOnNewVideoIfNeeded(videoInstanceUpdated) |
e8d246d5 | 398 | } |
b4055e1c | 399 | |
7294aab0 | 400 | Hooks.runAction('action:api.video.updated', { video: videoInstanceUpdated, body: req.body }) |
eb080476 | 401 | } catch (err) { |
6fcd19ba C |
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! | |
eb080476 | 405 | resetSequelizeInstance(videoInstance, videoFieldsSave) |
6fcd19ba C |
406 | |
407 | throw err | |
eb080476 | 408 | } |
90d4bb81 | 409 | |
2d53be02 RK |
410 | return res.type('json') |
411 | .status(HttpStatusCode.NO_CONTENT_204) | |
412 | .end() | |
9f10b292 | 413 | } |
8c308c2b | 414 | |
09209296 C |
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 | |
b4055e1c | 418 | |
89cd1275 C |
419 | const video = await Hooks.wrapPromiseFun( |
420 | VideoModel.loadForGetAPI, | |
453e83ea | 421 | { id: res.locals.onlyVideoWithRights.id, userId }, |
b4055e1c C |
422 | 'filter:api.video.get.result' |
423 | ) | |
1f3e9fec | 424 | |
09209296 C |
425 | if (video.isOutdated()) { |
426 | JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'video', url: video.url } }) | |
04b8c3fb C |
427 | } |
428 | ||
09209296 | 429 | return res.json(video.toFormattedDetailsJSON()) |
1f3e9fec C |
430 | } |
431 | ||
432 | async function viewVideo (req: express.Request, res: express.Response) { | |
e4bf7856 | 433 | const immutableVideoAttrs = res.locals.onlyImmutableVideo |
9e167724 | 434 | |
490b595a | 435 | const ip = req.ip |
e4bf7856 | 436 | const exists = await Redis.Instance.doesVideoIPViewExist(ip, immutableVideoAttrs.uuid) |
b5c0e955 | 437 | if (exists) { |
e4bf7856 | 438 | logger.debug('View for ip %s and video %s already exists.', ip, immutableVideoAttrs.uuid) |
2d53be02 | 439 | return res.sendStatus(HttpStatusCode.NO_CONTENT_204) |
b5c0e955 C |
440 | } |
441 | ||
e4bf7856 | 442 | const video = await VideoModel.load(immutableVideoAttrs.id) |
b5c0e955 | 443 | |
e4bf7856 C |
444 | const promises: Promise<any>[] = [ |
445 | Redis.Instance.setIPVideoView(ip, video.uuid, video.isLive) | |
446 | ] | |
9e167724 | 447 | |
e4bf7856 | 448 | let federateView = true |
b4055e1c | 449 | |
e4bf7856 C |
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 | ||
2d53be02 | 472 | return res.sendStatus(HttpStatusCode.NO_CONTENT_204) |
9f10b292 | 473 | } |
8c308c2b | 474 | |
9567011b | 475 | async function getVideoDescription (req: express.Request, res: express.Response) { |
453e83ea | 476 | const videoInstance = res.locals.videoAll |
9567011b C |
477 | let description = '' |
478 | ||
479 | if (videoInstance.isOwned()) { | |
480 | description = videoInstance.description | |
481 | } else { | |
571389d4 | 482 | description = await fetchRemoteVideoDescription(videoInstance) |
9567011b C |
483 | } |
484 | ||
485 | return res.json({ description }) | |
486 | } | |
487 | ||
8319d6ae RK |
488 | async function getVideoFileMetadata (req: express.Request, res: express.Response) { |
489 | const videoFile = await VideoFileModel.loadWithMetadata(toInt(req.params.videoFileId)) | |
583eb04b | 490 | |
8319d6ae RK |
491 | return res.json(videoFile.metadata) |
492 | } | |
493 | ||
04b8c3fb | 494 | async function listVideos (req: express.Request, res: express.Response) { |
fe987656 C |
495 | const countVideos = getCountVideos(req) |
496 | ||
b4055e1c | 497 | const apiOptions = await Hooks.wrapObject({ |
48dce1c9 C |
498 | start: req.query.start, |
499 | count: req.query.count, | |
500 | sort: req.query.sort, | |
06a05d5f | 501 | includeLocalVideos: true, |
d525fc39 C |
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), | |
48dce1c9 | 508 | filter: req.query.filter as VideoFilter, |
6e46de09 | 509 | withFiles: false, |
fe987656 C |
510 | user: res.locals.oauth ? res.locals.oauth.token.User : undefined, |
511 | countVideos | |
b4055e1c C |
512 | }, 'filter:api.videos.list.params') |
513 | ||
89cd1275 C |
514 | const resultList = await Hooks.wrapPromiseFun( |
515 | VideoModel.listForApi, | |
516 | apiOptions, | |
b4055e1c C |
517 | 'filter:api.videos.list.result' |
518 | ) | |
eb080476 C |
519 | |
520 | return res.json(getFormattedObjects(resultList.data, resultList.total)) | |
9f10b292 | 521 | } |
c45f7f84 | 522 | |
eb080476 | 523 | async function removeVideo (req: express.Request, res: express.Response) { |
453e83ea | 524 | const videoInstance = res.locals.videoAll |
91f6f169 | 525 | |
3fd3ab2d | 526 | await sequelizeTypescript.transaction(async t => { |
eb080476 | 527 | await videoInstance.destroy({ transaction: t }) |
91f6f169 | 528 | }) |
eb080476 | 529 | |
993cef4b | 530 | auditLogger.delete(getAuditIdFromRes(res), new VideoAuditView(videoInstance.toFormattedDetailsJSON())) |
eb080476 | 531 | logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid) |
90d4bb81 | 532 | |
b4055e1c C |
533 | Hooks.runAction('action:api.video.deleted', { video: videoInstance }) |
534 | ||
2d53be02 RK |
535 | return res.type('json') |
536 | .status(HttpStatusCode.NO_CONTENT_204) | |
537 | .end() | |
9f10b292 | 538 | } |
d61893f7 C |
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 | } |