]>
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, | |
11 | IMAGE_MIMETYPE_EXT, | |
12 | PREVIEWS_SIZE, | |
13 | sequelizeTypescript, | |
14 | THUMBNAILS_SIZE, | |
15 | VIDEO_CATEGORIES, | |
16 | VIDEO_LANGUAGES, | |
17 | VIDEO_LICENCES, | |
18 | VIDEO_MIMETYPE_EXT, | |
19 | VIDEO_PRIVACIES | |
20 | } from '../../../initializers' | |
21 | import { | |
22 | changeVideoChannelShare, | |
23 | federateVideoIfNeeded, | |
24 | fetchRemoteVideoDescription, | |
25 | getVideoActivityPubUrl | |
26 | } from '../../../lib/activitypub' | |
27 | import { sendCreateView } from '../../../lib/activitypub/send' | |
28 | import { JobQueue } from '../../../lib/job-queue' | |
29 | import { Redis } from '../../../lib/redis' | |
30 | import { | |
31 | asyncMiddleware, | |
32 | asyncRetryTransactionMiddleware, | |
33 | authenticate, | |
34 | commonVideosFiltersValidator, | |
35 | optionalAuthenticate, | |
36 | paginationValidator, | |
37 | setDefaultPagination, | |
38 | setDefaultSort, | |
39 | videosAddValidator, | |
40 | videosGetValidator, | |
41 | videosRemoveValidator, | |
42 | videosSortValidator, | |
43 | videosUpdateValidator | |
44 | } from '../../../middlewares' | |
45 | import { TagModel } from '../../../models/video/tag' | |
46 | import { VideoModel } from '../../../models/video/video' | |
47 | import { VideoFileModel } from '../../../models/video/video-file' | |
48 | import { abuseVideoRouter } from './abuse' | |
49 | import { blacklistRouter } from './blacklist' | |
50 | import { videoCommentRouter } from './comment' | |
51 | import { rateVideoRouter } from './rate' | |
52 | import { ownershipVideoRouter } from './ownership' | |
53 | import { VideoFilter } from '../../../../shared/models/videos/video-query.type' | |
54 | import { buildNSFWFilter, createReqFiles } from '../../../helpers/express-utils' | |
55 | import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update' | |
56 | import { videoCaptionsRouter } from './captions' | |
57 | import { videoImportsRouter } from './import' | |
58 | import { resetSequelizeInstance } from '../../../helpers/database-utils' | |
59 | import { rename } from 'fs-extra' | |
60 | import { watchingRouter } from './watching' | |
61 | ||
62 | const auditLogger = auditLoggerFactory('videos') | |
63 | const videosRouter = express.Router() | |
64 | ||
65 | const reqVideoFileAdd = createReqFiles( | |
66 | [ 'videofile', 'thumbnailfile', 'previewfile' ], | |
67 | Object.assign({}, VIDEO_MIMETYPE_EXT, IMAGE_MIMETYPE_EXT), | |
68 | { | |
69 | videofile: CONFIG.STORAGE.VIDEOS_DIR, | |
70 | thumbnailfile: CONFIG.STORAGE.THUMBNAILS_DIR, | |
71 | previewfile: CONFIG.STORAGE.PREVIEWS_DIR | |
72 | } | |
73 | ) | |
74 | const reqVideoFileUpdate = createReqFiles( | |
75 | [ 'thumbnailfile', 'previewfile' ], | |
76 | IMAGE_MIMETYPE_EXT, | |
77 | { | |
78 | thumbnailfile: CONFIG.STORAGE.THUMBNAILS_DIR, | |
79 | previewfile: CONFIG.STORAGE.PREVIEWS_DIR | |
80 | } | |
81 | ) | |
82 | ||
83 | videosRouter.use('/', abuseVideoRouter) | |
84 | videosRouter.use('/', blacklistRouter) | |
85 | videosRouter.use('/', rateVideoRouter) | |
86 | videosRouter.use('/', videoCommentRouter) | |
87 | videosRouter.use('/', videoCaptionsRouter) | |
88 | videosRouter.use('/', videoImportsRouter) | |
89 | videosRouter.use('/', ownershipVideoRouter) | |
90 | videosRouter.use('/', watchingRouter) | |
91 | ||
92 | videosRouter.get('/categories', listVideoCategories) | |
93 | videosRouter.get('/licences', listVideoLicences) | |
94 | videosRouter.get('/languages', listVideoLanguages) | |
95 | videosRouter.get('/privacies', listVideoPrivacies) | |
96 | ||
97 | videosRouter.get('/', | |
98 | paginationValidator, | |
99 | videosSortValidator, | |
100 | setDefaultSort, | |
101 | setDefaultPagination, | |
102 | optionalAuthenticate, | |
103 | commonVideosFiltersValidator, | |
104 | asyncMiddleware(listVideos) | |
105 | ) | |
106 | videosRouter.put('/:id', | |
107 | authenticate, | |
108 | reqVideoFileUpdate, | |
109 | asyncMiddleware(videosUpdateValidator), | |
110 | asyncRetryTransactionMiddleware(updateVideo) | |
111 | ) | |
112 | videosRouter.post('/upload', | |
113 | authenticate, | |
114 | reqVideoFileAdd, | |
115 | asyncMiddleware(videosAddValidator), | |
116 | asyncRetryTransactionMiddleware(addVideo) | |
117 | ) | |
118 | ||
119 | videosRouter.get('/:id/description', | |
120 | asyncMiddleware(videosGetValidator), | |
121 | asyncMiddleware(getVideoDescription) | |
122 | ) | |
123 | videosRouter.get('/:id', | |
124 | optionalAuthenticate, | |
125 | asyncMiddleware(videosGetValidator), | |
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 rename(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 | return res.json(videoInstance.toFormattedDetailsJSON()) | |
389 | } | |
390 | ||
391 | async function viewVideo (req: express.Request, res: express.Response) { | |
392 | const videoInstance = res.locals.video | |
393 | ||
394 | const ip = req.ip | |
395 | const exists = await Redis.Instance.isVideoIPViewExists(ip, videoInstance.uuid) | |
396 | if (exists) { | |
397 | logger.debug('View for ip %s and video %s already exists.', ip, videoInstance.uuid) | |
398 | return res.status(204).end() | |
399 | } | |
400 | ||
401 | await Promise.all([ | |
402 | Redis.Instance.addVideoView(videoInstance.id), | |
403 | Redis.Instance.setIPVideoView(ip, videoInstance.uuid) | |
404 | ]) | |
405 | ||
406 | const serverActor = await getServerActor() | |
407 | ||
408 | await sendCreateView(serverActor, videoInstance, undefined) | |
409 | ||
410 | return res.status(204).end() | |
411 | } | |
412 | ||
413 | async function getVideoDescription (req: express.Request, res: express.Response) { | |
414 | const videoInstance = res.locals.video | |
415 | let description = '' | |
416 | ||
417 | if (videoInstance.isOwned()) { | |
418 | description = videoInstance.description | |
419 | } else { | |
420 | description = await fetchRemoteVideoDescription(videoInstance) | |
421 | } | |
422 | ||
423 | return res.json({ description }) | |
424 | } | |
425 | ||
426 | async function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) { | |
427 | const resultList = await VideoModel.listForApi({ | |
428 | start: req.query.start, | |
429 | count: req.query.count, | |
430 | sort: req.query.sort, | |
431 | includeLocalVideos: true, | |
432 | categoryOneOf: req.query.categoryOneOf, | |
433 | licenceOneOf: req.query.licenceOneOf, | |
434 | languageOneOf: req.query.languageOneOf, | |
435 | tagsOneOf: req.query.tagsOneOf, | |
436 | tagsAllOf: req.query.tagsAllOf, | |
437 | nsfw: buildNSFWFilter(res, req.query.nsfw), | |
438 | filter: req.query.filter as VideoFilter, | |
439 | withFiles: false, | |
440 | userId: res.locals.oauth ? res.locals.oauth.token.User.id : undefined | |
441 | }) | |
442 | ||
443 | return res.json(getFormattedObjects(resultList.data, resultList.total)) | |
444 | } | |
445 | ||
446 | async function removeVideo (req: express.Request, res: express.Response) { | |
447 | const videoInstance: VideoModel = res.locals.video | |
448 | ||
449 | await sequelizeTypescript.transaction(async t => { | |
450 | await videoInstance.destroy({ transaction: t }) | |
451 | }) | |
452 | ||
453 | auditLogger.delete(getAuditIdFromRes(res), new VideoAuditView(videoInstance.toFormattedDetailsJSON())) | |
454 | logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid) | |
455 | ||
456 | return res.type('json').status(204).end() | |
457 | } |