]>
Commit | Line | Data |
---|---|---|
1 | import * as express from 'express' | |
2 | import { extname, join } from 'path' | |
3 | import { VideoCreate, VideoPrivacy, VideoState, VideoUpdate } from '../../../../shared' | |
4 | import { getVideoFileFPS, getVideoFileResolution } from '../../../helpers/ffmpeg-utils' | |
5 | import { processImage } from '../../../helpers/image-utils' | |
6 | import { logger } from '../../../helpers/logger' | |
7 | import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger' | |
8 | import { getFormattedObjects, getServerActor } from '../../../helpers/utils' | |
9 | import { | |
10 | CONFIG, MIMETYPES, | |
11 | PREVIEWS_SIZE, | |
12 | sequelizeTypescript, | |
13 | THUMBNAILS_SIZE, | |
14 | VIDEO_CATEGORIES, | |
15 | VIDEO_LANGUAGES, | |
16 | VIDEO_LICENCES, | |
17 | VIDEO_PRIVACIES | |
18 | } from '../../../initializers' | |
19 | import { | |
20 | changeVideoChannelShare, | |
21 | federateVideoIfNeeded, | |
22 | fetchRemoteVideoDescription, | |
23 | getVideoActivityPubUrl | |
24 | } from '../../../lib/activitypub' | |
25 | import { sendCreateView } from '../../../lib/activitypub/send' | |
26 | import { JobQueue } from '../../../lib/job-queue' | |
27 | import { Redis } from '../../../lib/redis' | |
28 | import { | |
29 | asyncMiddleware, | |
30 | asyncRetryTransactionMiddleware, | |
31 | authenticate, | |
32 | checkVideoFollowConstraints, | |
33 | commonVideosFiltersValidator, | |
34 | optionalAuthenticate, | |
35 | paginationValidator, | |
36 | setDefaultPagination, | |
37 | setDefaultSort, | |
38 | videosAddValidator, | |
39 | videosGetValidator, | |
40 | videosRemoveValidator, | |
41 | videosSortValidator, | |
42 | videosUpdateValidator | |
43 | } from '../../../middlewares' | |
44 | import { TagModel } from '../../../models/video/tag' | |
45 | import { VideoModel } from '../../../models/video/video' | |
46 | import { VideoFileModel } from '../../../models/video/video-file' | |
47 | import { abuseVideoRouter } from './abuse' | |
48 | import { blacklistRouter } from './blacklist' | |
49 | import { videoCommentRouter } from './comment' | |
50 | import { rateVideoRouter } from './rate' | |
51 | import { ownershipVideoRouter } from './ownership' | |
52 | import { VideoFilter } from '../../../../shared/models/videos/video-query.type' | |
53 | import { buildNSFWFilter, createReqFiles } from '../../../helpers/express-utils' | |
54 | import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update' | |
55 | import { videoCaptionsRouter } from './captions' | |
56 | import { videoImportsRouter } from './import' | |
57 | import { resetSequelizeInstance } from '../../../helpers/database-utils' | |
58 | import { move } from 'fs-extra' | |
59 | import { watchingRouter } from './watching' | |
60 | ||
61 | const auditLogger = auditLoggerFactory('videos') | |
62 | const videosRouter = express.Router() | |
63 | ||
64 | const reqVideoFileAdd = createReqFiles( | |
65 | [ 'videofile', 'thumbnailfile', 'previewfile' ], | |
66 | Object.assign({}, MIMETYPES.VIDEO.MIMETYPE_EXT, MIMETYPES.IMAGE.MIMETYPE_EXT), | |
67 | { | |
68 | videofile: CONFIG.STORAGE.TMP_DIR, | |
69 | thumbnailfile: CONFIG.STORAGE.TMP_DIR, | |
70 | previewfile: CONFIG.STORAGE.TMP_DIR | |
71 | } | |
72 | ) | |
73 | const reqVideoFileUpdate = createReqFiles( | |
74 | [ 'thumbnailfile', 'previewfile' ], | |
75 | MIMETYPES.IMAGE.MIMETYPE_EXT, | |
76 | { | |
77 | thumbnailfile: CONFIG.STORAGE.TMP_DIR, | |
78 | previewfile: CONFIG.STORAGE.TMP_DIR | |
79 | } | |
80 | ) | |
81 | ||
82 | videosRouter.use('/', abuseVideoRouter) | |
83 | videosRouter.use('/', blacklistRouter) | |
84 | videosRouter.use('/', rateVideoRouter) | |
85 | videosRouter.use('/', videoCommentRouter) | |
86 | videosRouter.use('/', videoCaptionsRouter) | |
87 | videosRouter.use('/', videoImportsRouter) | |
88 | videosRouter.use('/', ownershipVideoRouter) | |
89 | videosRouter.use('/', watchingRouter) | |
90 | ||
91 | videosRouter.get('/categories', listVideoCategories) | |
92 | videosRouter.get('/licences', listVideoLicences) | |
93 | videosRouter.get('/languages', listVideoLanguages) | |
94 | videosRouter.get('/privacies', listVideoPrivacies) | |
95 | ||
96 | videosRouter.get('/', | |
97 | paginationValidator, | |
98 | videosSortValidator, | |
99 | setDefaultSort, | |
100 | setDefaultPagination, | |
101 | optionalAuthenticate, | |
102 | commonVideosFiltersValidator, | |
103 | asyncMiddleware(listVideos) | |
104 | ) | |
105 | videosRouter.put('/:id', | |
106 | authenticate, | |
107 | reqVideoFileUpdate, | |
108 | asyncMiddleware(videosUpdateValidator), | |
109 | asyncRetryTransactionMiddleware(updateVideo) | |
110 | ) | |
111 | videosRouter.post('/upload', | |
112 | authenticate, | |
113 | reqVideoFileAdd, | |
114 | asyncMiddleware(videosAddValidator), | |
115 | asyncRetryTransactionMiddleware(addVideo) | |
116 | ) | |
117 | ||
118 | videosRouter.get('/:id/description', | |
119 | asyncMiddleware(videosGetValidator), | |
120 | asyncMiddleware(getVideoDescription) | |
121 | ) | |
122 | videosRouter.get('/:id', | |
123 | optionalAuthenticate, | |
124 | asyncMiddleware(videosGetValidator), | |
125 | asyncMiddleware(checkVideoFollowConstraints), | |
126 | getVideo | |
127 | ) | |
128 | videosRouter.post('/:id/views', | |
129 | asyncMiddleware(videosGetValidator), | |
130 | asyncMiddleware(viewVideo) | |
131 | ) | |
132 | ||
133 | videosRouter.delete('/:id', | |
134 | authenticate, | |
135 | asyncMiddleware(videosRemoveValidator), | |
136 | asyncRetryTransactionMiddleware(removeVideo) | |
137 | ) | |
138 | ||
139 | // --------------------------------------------------------------------------- | |
140 | ||
141 | export { | |
142 | videosRouter | |
143 | } | |
144 | ||
145 | // --------------------------------------------------------------------------- | |
146 | ||
147 | function listVideoCategories (req: express.Request, res: express.Response) { | |
148 | res.json(VIDEO_CATEGORIES) | |
149 | } | |
150 | ||
151 | function listVideoLicences (req: express.Request, res: express.Response) { | |
152 | res.json(VIDEO_LICENCES) | |
153 | } | |
154 | ||
155 | function listVideoLanguages (req: express.Request, res: express.Response) { | |
156 | res.json(VIDEO_LANGUAGES) | |
157 | } | |
158 | ||
159 | function listVideoPrivacies (req: express.Request, res: express.Response) { | |
160 | res.json(VIDEO_PRIVACIES) | |
161 | } | |
162 | ||
163 | async function addVideo (req: express.Request, res: express.Response) { | |
164 | // Processing the video could be long | |
165 | // Set timeout to 10 minutes | |
166 | req.setTimeout(1000 * 60 * 10, () => { | |
167 | logger.error('Upload video has timed out.') | |
168 | return res.sendStatus(408) | |
169 | }) | |
170 | ||
171 | const videoPhysicalFile = req.files['videofile'][0] | |
172 | const videoInfo: VideoCreate = req.body | |
173 | ||
174 | // Prepare data so we don't block the transaction | |
175 | const videoData = { | |
176 | name: videoInfo.name, | |
177 | remote: false, | |
178 | category: videoInfo.category, | |
179 | licence: videoInfo.licence, | |
180 | language: videoInfo.language, | |
181 | commentsEnabled: videoInfo.commentsEnabled || false, | |
182 | waitTranscoding: videoInfo.waitTranscoding || false, | |
183 | state: CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED, | |
184 | nsfw: videoInfo.nsfw || false, | |
185 | description: videoInfo.description, | |
186 | support: videoInfo.support, | |
187 | privacy: videoInfo.privacy, | |
188 | duration: videoPhysicalFile['duration'], // duration was added by a previous middleware | |
189 | channelId: res.locals.videoChannel.id | |
190 | } | |
191 | const video = new VideoModel(videoData) | |
192 | video.url = getVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object | |
193 | ||
194 | // Build the file object | |
195 | const { videoFileResolution } = await getVideoFileResolution(videoPhysicalFile.path) | |
196 | const fps = await getVideoFileFPS(videoPhysicalFile.path) | |
197 | ||
198 | const videoFileData = { | |
199 | extname: extname(videoPhysicalFile.filename), | |
200 | resolution: videoFileResolution, | |
201 | size: videoPhysicalFile.size, | |
202 | fps | |
203 | } | |
204 | const videoFile = new VideoFileModel(videoFileData) | |
205 | ||
206 | // Move physical file | |
207 | const videoDir = CONFIG.STORAGE.VIDEOS_DIR | |
208 | const destination = join(videoDir, video.getVideoFilename(videoFile)) | |
209 | await move(videoPhysicalFile.path, destination) | |
210 | // This is important in case if there is another attempt in the retry process | |
211 | videoPhysicalFile.filename = video.getVideoFilename(videoFile) | |
212 | videoPhysicalFile.path = destination | |
213 | ||
214 | // Process thumbnail or create it from the video | |
215 | const thumbnailField = req.files['thumbnailfile'] | |
216 | if (thumbnailField) { | |
217 | const thumbnailPhysicalFile = thumbnailField[0] | |
218 | await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName()), THUMBNAILS_SIZE) | |
219 | } else { | |
220 | await video.createThumbnail(videoFile) | |
221 | } | |
222 | ||
223 | // Process preview or create it from the video | |
224 | const previewField = req.files['previewfile'] | |
225 | if (previewField) { | |
226 | const previewPhysicalFile = previewField[0] | |
227 | await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName()), PREVIEWS_SIZE) | |
228 | } else { | |
229 | await video.createPreview(videoFile) | |
230 | } | |
231 | ||
232 | // Create the torrent file | |
233 | await video.createTorrentAndSetInfoHash(videoFile) | |
234 | ||
235 | const videoCreated = await sequelizeTypescript.transaction(async t => { | |
236 | const sequelizeOptions = { transaction: t } | |
237 | ||
238 | const videoCreated = await video.save(sequelizeOptions) | |
239 | // Do not forget to add video channel information to the created video | |
240 | videoCreated.VideoChannel = res.locals.videoChannel | |
241 | ||
242 | videoFile.videoId = video.id | |
243 | await videoFile.save(sequelizeOptions) | |
244 | ||
245 | video.VideoFiles = [ videoFile ] | |
246 | ||
247 | // Create tags | |
248 | if (videoInfo.tags !== undefined) { | |
249 | const tagInstances = await TagModel.findOrCreateTags(videoInfo.tags, t) | |
250 | ||
251 | await video.$set('Tags', tagInstances, sequelizeOptions) | |
252 | video.Tags = tagInstances | |
253 | } | |
254 | ||
255 | // Schedule an update in the future? | |
256 | if (videoInfo.scheduleUpdate) { | |
257 | await ScheduleVideoUpdateModel.create({ | |
258 | videoId: video.id, | |
259 | updateAt: videoInfo.scheduleUpdate.updateAt, | |
260 | privacy: videoInfo.scheduleUpdate.privacy || null | |
261 | }, { transaction: t }) | |
262 | } | |
263 | ||
264 | await federateVideoIfNeeded(video, true, t) | |
265 | ||
266 | auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(videoCreated.toFormattedDetailsJSON())) | |
267 | logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid) | |
268 | ||
269 | return videoCreated | |
270 | }) | |
271 | ||
272 | if (video.state === VideoState.TO_TRANSCODE) { | |
273 | // Put uuid because we don't have id auto incremented for now | |
274 | const dataInput = { | |
275 | videoUUID: videoCreated.uuid, | |
276 | isNewVideo: true | |
277 | } | |
278 | ||
279 | await JobQueue.Instance.createJob({ type: 'video-file', payload: dataInput }) | |
280 | } | |
281 | ||
282 | return res.json({ | |
283 | video: { | |
284 | id: videoCreated.id, | |
285 | uuid: videoCreated.uuid | |
286 | } | |
287 | }).end() | |
288 | } | |
289 | ||
290 | async function updateVideo (req: express.Request, res: express.Response) { | |
291 | const videoInstance: VideoModel = res.locals.video | |
292 | const videoFieldsSave = videoInstance.toJSON() | |
293 | const oldVideoAuditView = new VideoAuditView(videoInstance.toFormattedDetailsJSON()) | |
294 | const videoInfoToUpdate: VideoUpdate = req.body | |
295 | const wasPrivateVideo = videoInstance.privacy === VideoPrivacy.PRIVATE | |
296 | ||
297 | // Process thumbnail or create it from the video | |
298 | if (req.files && req.files['thumbnailfile']) { | |
299 | const thumbnailPhysicalFile = req.files['thumbnailfile'][0] | |
300 | await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, videoInstance.getThumbnailName()), THUMBNAILS_SIZE) | |
301 | } | |
302 | ||
303 | // Process preview or create it from the video | |
304 | if (req.files && req.files['previewfile']) { | |
305 | const previewPhysicalFile = req.files['previewfile'][0] | |
306 | await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, videoInstance.getPreviewName()), PREVIEWS_SIZE) | |
307 | } | |
308 | ||
309 | try { | |
310 | await sequelizeTypescript.transaction(async t => { | |
311 | const sequelizeOptions = { | |
312 | transaction: t | |
313 | } | |
314 | const oldVideoChannel = videoInstance.VideoChannel | |
315 | ||
316 | if (videoInfoToUpdate.name !== undefined) videoInstance.set('name', videoInfoToUpdate.name) | |
317 | if (videoInfoToUpdate.category !== undefined) videoInstance.set('category', videoInfoToUpdate.category) | |
318 | if (videoInfoToUpdate.licence !== undefined) videoInstance.set('licence', videoInfoToUpdate.licence) | |
319 | if (videoInfoToUpdate.language !== undefined) videoInstance.set('language', videoInfoToUpdate.language) | |
320 | if (videoInfoToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfoToUpdate.nsfw) | |
321 | if (videoInfoToUpdate.waitTranscoding !== undefined) videoInstance.set('waitTranscoding', videoInfoToUpdate.waitTranscoding) | |
322 | if (videoInfoToUpdate.support !== undefined) videoInstance.set('support', videoInfoToUpdate.support) | |
323 | if (videoInfoToUpdate.description !== undefined) videoInstance.set('description', videoInfoToUpdate.description) | |
324 | if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.set('commentsEnabled', videoInfoToUpdate.commentsEnabled) | |
325 | if (videoInfoToUpdate.privacy !== undefined) { | |
326 | const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10) | |
327 | videoInstance.set('privacy', newPrivacy) | |
328 | ||
329 | if (wasPrivateVideo === true && newPrivacy !== VideoPrivacy.PRIVATE) { | |
330 | videoInstance.set('publishedAt', new Date()) | |
331 | } | |
332 | } | |
333 | ||
334 | const videoInstanceUpdated = await videoInstance.save(sequelizeOptions) | |
335 | ||
336 | // Video tags update? | |
337 | if (videoInfoToUpdate.tags !== undefined) { | |
338 | const tagInstances = await TagModel.findOrCreateTags(videoInfoToUpdate.tags, t) | |
339 | ||
340 | await videoInstanceUpdated.$set('Tags', tagInstances, sequelizeOptions) | |
341 | videoInstanceUpdated.Tags = tagInstances | |
342 | } | |
343 | ||
344 | // Video channel update? | |
345 | if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) { | |
346 | await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t }) | |
347 | videoInstanceUpdated.VideoChannel = res.locals.videoChannel | |
348 | ||
349 | if (wasPrivateVideo === false) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t) | |
350 | } | |
351 | ||
352 | // Schedule an update in the future? | |
353 | if (videoInfoToUpdate.scheduleUpdate) { | |
354 | await ScheduleVideoUpdateModel.upsert({ | |
355 | videoId: videoInstanceUpdated.id, | |
356 | updateAt: videoInfoToUpdate.scheduleUpdate.updateAt, | |
357 | privacy: videoInfoToUpdate.scheduleUpdate.privacy || null | |
358 | }, { transaction: t }) | |
359 | } else if (videoInfoToUpdate.scheduleUpdate === null) { | |
360 | await ScheduleVideoUpdateModel.deleteByVideoId(videoInstanceUpdated.id, t) | |
361 | } | |
362 | ||
363 | const isNewVideo = wasPrivateVideo && videoInstanceUpdated.privacy !== VideoPrivacy.PRIVATE | |
364 | await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t) | |
365 | ||
366 | auditLogger.update( | |
367 | getAuditIdFromRes(res), | |
368 | new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()), | |
369 | oldVideoAuditView | |
370 | ) | |
371 | logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid) | |
372 | }) | |
373 | } catch (err) { | |
374 | // Force fields we want to update | |
375 | // If the transaction is retried, sequelize will think the object has not changed | |
376 | // So it will skip the SQL request, even if the last one was ROLLBACKed! | |
377 | resetSequelizeInstance(videoInstance, videoFieldsSave) | |
378 | ||
379 | throw err | |
380 | } | |
381 | ||
382 | return res.type('json').status(204).end() | |
383 | } | |
384 | ||
385 | function getVideo (req: express.Request, res: express.Response) { | |
386 | const videoInstance = res.locals.video | |
387 | ||
388 | if (videoInstance.isOutdated()) { | |
389 | JobQueue.Instance.createJob({ type: 'activitypub-refresher', payload: { type: 'video', videoUrl: videoInstance.url } }) | |
390 | .catch(err => logger.error('Cannot create AP refresher job for video %s.', videoInstance.url, { err })) | |
391 | } | |
392 | ||
393 | return res.json(videoInstance.toFormattedDetailsJSON()) | |
394 | } | |
395 | ||
396 | async function viewVideo (req: express.Request, res: express.Response) { | |
397 | const videoInstance = res.locals.video | |
398 | ||
399 | const ip = req.ip | |
400 | const exists = await Redis.Instance.isVideoIPViewExists(ip, videoInstance.uuid) | |
401 | if (exists) { | |
402 | logger.debug('View for ip %s and video %s already exists.', ip, videoInstance.uuid) | |
403 | return res.status(204).end() | |
404 | } | |
405 | ||
406 | await Promise.all([ | |
407 | Redis.Instance.addVideoView(videoInstance.id), | |
408 | Redis.Instance.setIPVideoView(ip, videoInstance.uuid) | |
409 | ]) | |
410 | ||
411 | const serverActor = await getServerActor() | |
412 | await sendCreateView(serverActor, videoInstance, undefined) | |
413 | ||
414 | return res.status(204).end() | |
415 | } | |
416 | ||
417 | async function getVideoDescription (req: express.Request, res: express.Response) { | |
418 | const videoInstance = res.locals.video | |
419 | let description = '' | |
420 | ||
421 | if (videoInstance.isOwned()) { | |
422 | description = videoInstance.description | |
423 | } else { | |
424 | description = await fetchRemoteVideoDescription(videoInstance) | |
425 | } | |
426 | ||
427 | return res.json({ description }) | |
428 | } | |
429 | ||
430 | async function listVideos (req: express.Request, res: express.Response) { | |
431 | const resultList = await VideoModel.listForApi({ | |
432 | start: req.query.start, | |
433 | count: req.query.count, | |
434 | sort: req.query.sort, | |
435 | includeLocalVideos: true, | |
436 | categoryOneOf: req.query.categoryOneOf, | |
437 | licenceOneOf: req.query.licenceOneOf, | |
438 | languageOneOf: req.query.languageOneOf, | |
439 | tagsOneOf: req.query.tagsOneOf, | |
440 | tagsAllOf: req.query.tagsAllOf, | |
441 | nsfw: buildNSFWFilter(res, req.query.nsfw), | |
442 | filter: req.query.filter as VideoFilter, | |
443 | withFiles: false, | |
444 | user: res.locals.oauth ? res.locals.oauth.token.User : undefined | |
445 | }) | |
446 | ||
447 | return res.json(getFormattedObjects(resultList.data, resultList.total)) | |
448 | } | |
449 | ||
450 | async function removeVideo (req: express.Request, res: express.Response) { | |
451 | const videoInstance: VideoModel = res.locals.video | |
452 | ||
453 | await sequelizeTypescript.transaction(async t => { | |
454 | await videoInstance.destroy({ transaction: t }) | |
455 | }) | |
456 | ||
457 | auditLogger.delete(getAuditIdFromRes(res), new VideoAuditView(videoInstance.toFormattedDetailsJSON())) | |
458 | logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid) | |
459 | ||
460 | return res.type('json').status(204).end() | |
461 | } |