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