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