]>
Commit | Line | Data |
---|---|---|
1 | import * as express from 'express' | |
2 | import { extname, join } from 'path' | |
3 | import { VideoCreate, VideoPrivacy, VideoUpdate } from '../../../../shared' | |
4 | import { renamePromise } from '../../../helpers/core-utils' | |
5 | import { retryTransactionWrapper } from '../../../helpers/database-utils' | |
6 | import { getVideoFileResolution } from '../../../helpers/ffmpeg-utils' | |
7 | import { processImage } from '../../../helpers/image-utils' | |
8 | import { logger } from '../../../helpers/logger' | |
9 | import { createReqFiles, getFormattedObjects, getServerActor, resetSequelizeInstance } from '../../../helpers/utils' | |
10 | import { | |
11 | CONFIG, | |
12 | IMAGE_MIMETYPE_EXT, | |
13 | PREVIEWS_SIZE, | |
14 | sequelizeTypescript, | |
15 | THUMBNAILS_SIZE, | |
16 | VIDEO_CATEGORIES, | |
17 | VIDEO_LANGUAGES, | |
18 | VIDEO_LICENCES, | |
19 | VIDEO_MIMETYPE_EXT, | |
20 | VIDEO_PRIVACIES | |
21 | } from '../../../initializers' | |
22 | import { | |
23 | fetchRemoteVideoDescription, | |
24 | getVideoActivityPubUrl, | |
25 | shareVideoByServerAndChannel | |
26 | } from '../../../lib/activitypub' | |
27 | import { sendCreateVideo, sendCreateView, sendUpdateVideo } from '../../../lib/activitypub/send' | |
28 | import { JobQueue } from '../../../lib/job-queue' | |
29 | import { Redis } from '../../../lib/redis' | |
30 | import { | |
31 | asyncMiddleware, | |
32 | authenticate, | |
33 | optionalAuthenticate, | |
34 | paginationValidator, | |
35 | setDefaultPagination, | |
36 | setDefaultSort, | |
37 | videosAddValidator, | |
38 | videosGetValidator, | |
39 | videosRemoveValidator, | |
40 | videosSearchValidator, | |
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 { videoChannelRouter } from './channel' | |
50 | import { videoCommentRouter } from './comment' | |
51 | import { rateVideoRouter } from './rate' | |
52 | import { User } from '../../../../shared/models/users' | |
53 | import { VideoFilter } from '../../../../shared/models/videos/video-query.type' | |
54 | import { VideoSortField } from '../../../../client/src/app/shared/video/sort-field.type' | |
55 | ||
56 | const videosRouter = express.Router() | |
57 | ||
58 | const reqVideoFileAdd = createReqFiles( | |
59 | [ 'videofile', 'thumbnailfile', 'previewfile' ], | |
60 | Object.assign({}, VIDEO_MIMETYPE_EXT, IMAGE_MIMETYPE_EXT), | |
61 | { | |
62 | videofile: CONFIG.STORAGE.VIDEOS_DIR, | |
63 | thumbnailfile: CONFIG.STORAGE.THUMBNAILS_DIR, | |
64 | previewfile: CONFIG.STORAGE.PREVIEWS_DIR | |
65 | } | |
66 | ) | |
67 | const reqVideoFileUpdate = createReqFiles( | |
68 | [ 'thumbnailfile', 'previewfile' ], | |
69 | IMAGE_MIMETYPE_EXT, | |
70 | { | |
71 | thumbnailfile: CONFIG.STORAGE.THUMBNAILS_DIR, | |
72 | previewfile: CONFIG.STORAGE.PREVIEWS_DIR | |
73 | } | |
74 | ) | |
75 | ||
76 | videosRouter.use('/', abuseVideoRouter) | |
77 | videosRouter.use('/', blacklistRouter) | |
78 | videosRouter.use('/', rateVideoRouter) | |
79 | videosRouter.use('/', videoChannelRouter) | |
80 | videosRouter.use('/', videoCommentRouter) | |
81 | ||
82 | videosRouter.get('/categories', listVideoCategories) | |
83 | videosRouter.get('/licences', listVideoLicences) | |
84 | videosRouter.get('/languages', listVideoLanguages) | |
85 | videosRouter.get('/privacies', listVideoPrivacies) | |
86 | ||
87 | videosRouter.get('/', | |
88 | paginationValidator, | |
89 | videosSortValidator, | |
90 | setDefaultSort, | |
91 | setDefaultPagination, | |
92 | optionalAuthenticate, | |
93 | asyncMiddleware(listVideos) | |
94 | ) | |
95 | videosRouter.get('/search', | |
96 | videosSearchValidator, | |
97 | paginationValidator, | |
98 | videosSortValidator, | |
99 | setDefaultSort, | |
100 | setDefaultPagination, | |
101 | optionalAuthenticate, | |
102 | asyncMiddleware(searchVideos) | |
103 | ) | |
104 | videosRouter.put('/:id', | |
105 | authenticate, | |
106 | reqVideoFileUpdate, | |
107 | asyncMiddleware(videosUpdateValidator), | |
108 | asyncMiddleware(updateVideoRetryWrapper) | |
109 | ) | |
110 | videosRouter.post('/upload', | |
111 | authenticate, | |
112 | reqVideoFileAdd, | |
113 | asyncMiddleware(videosAddValidator), | |
114 | asyncMiddleware(addVideoRetryWrapper) | |
115 | ) | |
116 | ||
117 | videosRouter.get('/:id/description', | |
118 | asyncMiddleware(videosGetValidator), | |
119 | asyncMiddleware(getVideoDescription) | |
120 | ) | |
121 | videosRouter.get('/:id', | |
122 | asyncMiddleware(videosGetValidator), | |
123 | getVideo | |
124 | ) | |
125 | videosRouter.post('/:id/views', | |
126 | asyncMiddleware(videosGetValidator), | |
127 | asyncMiddleware(viewVideo) | |
128 | ) | |
129 | ||
130 | videosRouter.delete('/:id', | |
131 | authenticate, | |
132 | asyncMiddleware(videosRemoveValidator), | |
133 | asyncMiddleware(removeVideoRetryWrapper) | |
134 | ) | |
135 | ||
136 | // --------------------------------------------------------------------------- | |
137 | ||
138 | export { | |
139 | videosRouter | |
140 | } | |
141 | ||
142 | // --------------------------------------------------------------------------- | |
143 | ||
144 | function listVideoCategories (req: express.Request, res: express.Response) { | |
145 | res.json(VIDEO_CATEGORIES) | |
146 | } | |
147 | ||
148 | function listVideoLicences (req: express.Request, res: express.Response) { | |
149 | res.json(VIDEO_LICENCES) | |
150 | } | |
151 | ||
152 | function listVideoLanguages (req: express.Request, res: express.Response) { | |
153 | res.json(VIDEO_LANGUAGES) | |
154 | } | |
155 | ||
156 | function listVideoPrivacies (req: express.Request, res: express.Response) { | |
157 | res.json(VIDEO_PRIVACIES) | |
158 | } | |
159 | ||
160 | // Wrapper to video add that retry the function if there is a database error | |
161 | // We need this because we run the transaction in SERIALIZABLE isolation that can fail | |
162 | async function addVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) { | |
163 | const options = { | |
164 | arguments: [ req, res, req.files['videofile'][0] ], | |
165 | errorMessage: 'Cannot insert the video with many retries.' | |
166 | } | |
167 | ||
168 | const video = await retryTransactionWrapper(addVideo, options) | |
169 | ||
170 | res.json({ | |
171 | video: { | |
172 | id: video.id, | |
173 | uuid: video.uuid | |
174 | } | |
175 | }).end() | |
176 | } | |
177 | ||
178 | async function addVideo (req: express.Request, res: express.Response, videoPhysicalFile: Express.Multer.File) { | |
179 | const videoInfo: VideoCreate = req.body | |
180 | ||
181 | // Prepare data so we don't block the transaction | |
182 | const videoData = { | |
183 | name: videoInfo.name, | |
184 | remote: false, | |
185 | extname: extname(videoPhysicalFile.filename), | |
186 | category: videoInfo.category, | |
187 | licence: videoInfo.licence, | |
188 | language: videoInfo.language, | |
189 | commentsEnabled: videoInfo.commentsEnabled, | |
190 | nsfw: videoInfo.nsfw, | |
191 | description: videoInfo.description, | |
192 | support: videoInfo.support, | |
193 | privacy: videoInfo.privacy, | |
194 | duration: videoPhysicalFile['duration'], // duration was added by a previous middleware | |
195 | channelId: res.locals.videoChannel.id | |
196 | } | |
197 | const video = new VideoModel(videoData) | |
198 | video.url = getVideoActivityPubUrl(video) | |
199 | ||
200 | const { videoFileResolution } = await getVideoFileResolution(videoPhysicalFile.path) | |
201 | ||
202 | const videoFileData = { | |
203 | extname: extname(videoPhysicalFile.filename), | |
204 | resolution: videoFileResolution, | |
205 | size: videoPhysicalFile.size | |
206 | } | |
207 | const videoFile = new VideoFileModel(videoFileData) | |
208 | const videoDir = CONFIG.STORAGE.VIDEOS_DIR | |
209 | const destination = join(videoDir, video.getVideoFilename(videoFile)) | |
210 | ||
211 | await renamePromise(videoPhysicalFile.path, destination) | |
212 | // This is important in case if there is another attempt in the retry process | |
213 | videoPhysicalFile.filename = video.getVideoFilename(videoFile) | |
214 | videoPhysicalFile.path = destination | |
215 | ||
216 | // Process thumbnail or create it from the video | |
217 | const thumbnailField = req.files['thumbnailfile'] | |
218 | if (thumbnailField) { | |
219 | const thumbnailPhysicalFile = thumbnailField[0] | |
220 | await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName()), THUMBNAILS_SIZE) | |
221 | } else { | |
222 | await video.createThumbnail(videoFile) | |
223 | } | |
224 | ||
225 | // Process preview or create it from the video | |
226 | const previewField = req.files['previewfile'] | |
227 | if (previewField) { | |
228 | const previewPhysicalFile = previewField[0] | |
229 | await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName()), PREVIEWS_SIZE) | |
230 | } else { | |
231 | await video.createPreview(videoFile) | |
232 | } | |
233 | ||
234 | await video.createTorrentAndSetInfoHash(videoFile) | |
235 | ||
236 | const videoCreated = await sequelizeTypescript.transaction(async t => { | |
237 | const sequelizeOptions = { transaction: t } | |
238 | ||
239 | const videoCreated = await video.save(sequelizeOptions) | |
240 | // Do not forget to add video channel information to the created video | |
241 | videoCreated.VideoChannel = res.locals.videoChannel | |
242 | ||
243 | videoFile.videoId = video.id | |
244 | await videoFile.save(sequelizeOptions) | |
245 | ||
246 | video.VideoFiles = [ videoFile ] | |
247 | ||
248 | if (videoInfo.tags) { | |
249 | const tagInstances = await TagModel.findOrCreateTags(videoInfo.tags, t) | |
250 | ||
251 | await video.$set('Tags', tagInstances, sequelizeOptions) | |
252 | video.Tags = tagInstances | |
253 | } | |
254 | ||
255 | // Let transcoding job send the video to friends because the video file extension might change | |
256 | if (CONFIG.TRANSCODING.ENABLED === true) return videoCreated | |
257 | // Don't send video to remote servers, it is private | |
258 | if (video.privacy === VideoPrivacy.PRIVATE) return videoCreated | |
259 | ||
260 | await sendCreateVideo(video, t) | |
261 | await shareVideoByServerAndChannel(video, t) | |
262 | ||
263 | logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid) | |
264 | ||
265 | return videoCreated | |
266 | }) | |
267 | ||
268 | if (CONFIG.TRANSCODING.ENABLED === true) { | |
269 | // Put uuid because we don't have id auto incremented for now | |
270 | const dataInput = { | |
271 | videoUUID: videoCreated.uuid | |
272 | } | |
273 | ||
274 | await JobQueue.Instance.createJob({ type: 'video-file', payload: dataInput }) | |
275 | } | |
276 | ||
277 | return videoCreated | |
278 | } | |
279 | ||
280 | async function updateVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) { | |
281 | const options = { | |
282 | arguments: [ req, res ], | |
283 | errorMessage: 'Cannot update the video with many retries.' | |
284 | } | |
285 | ||
286 | await retryTransactionWrapper(updateVideo, options) | |
287 | ||
288 | return res.type('json').status(204).end() | |
289 | } | |
290 | ||
291 | async function updateVideo (req: express.Request, res: express.Response) { | |
292 | const videoInstance: VideoModel = res.locals.video | |
293 | const videoFieldsSave = videoInstance.toJSON() | |
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 | ||
315 | if (videoInfoToUpdate.name !== undefined) videoInstance.set('name', videoInfoToUpdate.name) | |
316 | if (videoInfoToUpdate.category !== undefined) videoInstance.set('category', videoInfoToUpdate.category) | |
317 | if (videoInfoToUpdate.licence !== undefined) videoInstance.set('licence', videoInfoToUpdate.licence) | |
318 | if (videoInfoToUpdate.language !== undefined) videoInstance.set('language', videoInfoToUpdate.language) | |
319 | if (videoInfoToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfoToUpdate.nsfw) | |
320 | if (videoInfoToUpdate.support !== undefined) videoInstance.set('support', videoInfoToUpdate.support) | |
321 | if (videoInfoToUpdate.description !== undefined) videoInstance.set('description', videoInfoToUpdate.description) | |
322 | if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.set('commentsEnabled', videoInfoToUpdate.commentsEnabled) | |
323 | if (videoInfoToUpdate.privacy !== undefined) { | |
324 | const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10) | |
325 | videoInstance.set('privacy', newPrivacy) | |
326 | ||
327 | if (wasPrivateVideo === true && newPrivacy !== VideoPrivacy.PRIVATE) { | |
328 | videoInstance.set('publishedAt', new Date()) | |
329 | } | |
330 | } | |
331 | ||
332 | const videoInstanceUpdated = await videoInstance.save(sequelizeOptions) | |
333 | ||
334 | if (videoInfoToUpdate.tags) { | |
335 | const tagInstances = await TagModel.findOrCreateTags(videoInfoToUpdate.tags, t) | |
336 | ||
337 | await videoInstance.$set('Tags', tagInstances, sequelizeOptions) | |
338 | videoInstance.Tags = tagInstances | |
339 | } | |
340 | ||
341 | // Now we'll update the video's meta data to our friends | |
342 | if (wasPrivateVideo === false) { | |
343 | await sendUpdateVideo(videoInstanceUpdated, t) | |
344 | } | |
345 | ||
346 | // Video is not private anymore, send a create action to remote servers | |
347 | if (wasPrivateVideo === true && videoInstanceUpdated.privacy !== VideoPrivacy.PRIVATE) { | |
348 | await sendCreateVideo(videoInstanceUpdated, t) | |
349 | await shareVideoByServerAndChannel(videoInstanceUpdated, t) | |
350 | } | |
351 | }) | |
352 | ||
353 | logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid) | |
354 | } catch (err) { | |
355 | // Force fields we want to update | |
356 | // If the transaction is retried, sequelize will think the object has not changed | |
357 | // So it will skip the SQL request, even if the last one was ROLLBACKed! | |
358 | resetSequelizeInstance(videoInstance, videoFieldsSave) | |
359 | ||
360 | throw err | |
361 | } | |
362 | } | |
363 | ||
364 | function getVideo (req: express.Request, res: express.Response) { | |
365 | const videoInstance = res.locals.video | |
366 | ||
367 | return res.json(videoInstance.toFormattedDetailsJSON()) | |
368 | } | |
369 | ||
370 | async function viewVideo (req: express.Request, res: express.Response) { | |
371 | const videoInstance = res.locals.video | |
372 | ||
373 | const ip = req.ip | |
374 | const exists = await Redis.Instance.isViewExists(ip, videoInstance.uuid) | |
375 | if (exists) { | |
376 | logger.debug('View for ip %s and video %s already exists.', ip, videoInstance.uuid) | |
377 | return res.status(204).end() | |
378 | } | |
379 | ||
380 | await videoInstance.increment('views') | |
381 | await Redis.Instance.setView(ip, videoInstance.uuid) | |
382 | ||
383 | const serverAccount = await getServerActor() | |
384 | ||
385 | await sendCreateView(serverAccount, videoInstance, undefined) | |
386 | ||
387 | return res.status(204).end() | |
388 | } | |
389 | ||
390 | async function getVideoDescription (req: express.Request, res: express.Response) { | |
391 | const videoInstance = res.locals.video | |
392 | let description = '' | |
393 | ||
394 | if (videoInstance.isOwned()) { | |
395 | description = videoInstance.description | |
396 | } else { | |
397 | description = await fetchRemoteVideoDescription(videoInstance) | |
398 | } | |
399 | ||
400 | return res.json({ description }) | |
401 | } | |
402 | ||
403 | async function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) { | |
404 | const resultList = await VideoModel.listForApi( | |
405 | req.query.start as number, | |
406 | req.query.count as number, | |
407 | req.query.sort as VideoSortField, | |
408 | isNSFWHidden(res), | |
409 | req.query.filter as VideoFilter | |
410 | ) | |
411 | ||
412 | return res.json(getFormattedObjects(resultList.data, resultList.total)) | |
413 | } | |
414 | ||
415 | async function removeVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) { | |
416 | const options = { | |
417 | arguments: [ req, res ], | |
418 | errorMessage: 'Cannot remove the video with many retries.' | |
419 | } | |
420 | ||
421 | await retryTransactionWrapper(removeVideo, options) | |
422 | ||
423 | return res.type('json').status(204).end() | |
424 | } | |
425 | ||
426 | async function removeVideo (req: express.Request, res: express.Response) { | |
427 | const videoInstance: VideoModel = res.locals.video | |
428 | ||
429 | await sequelizeTypescript.transaction(async t => { | |
430 | await videoInstance.destroy({ transaction: t }) | |
431 | }) | |
432 | ||
433 | logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid) | |
434 | } | |
435 | ||
436 | async function searchVideos (req: express.Request, res: express.Response, next: express.NextFunction) { | |
437 | const resultList = await VideoModel.searchAndPopulateAccountAndServer( | |
438 | req.query.search as string, | |
439 | req.query.start as number, | |
440 | req.query.count as number, | |
441 | req.query.sort as VideoSortField, | |
442 | isNSFWHidden(res) | |
443 | ) | |
444 | ||
445 | return res.json(getFormattedObjects(resultList.data, resultList.total)) | |
446 | } | |
447 | ||
448 | function isNSFWHidden (res: express.Response) { | |
449 | if (res.locals.oauth) { | |
450 | const user: User = res.locals.oauth.token.User | |
451 | if (user) return user.nsfwPolicy === 'do_not_list' | |
452 | } | |
453 | ||
454 | return CONFIG.INSTANCE.DEFAULT_NSFW_POLICY === 'do_not_list' | |
455 | } |