]>
Commit | Line | Data |
---|---|---|
4d4e5cd4 | 1 | import * as express from 'express' |
4d4e5cd4 | 2 | import * as multer from 'multer' |
93e1258c | 3 | import { extname, join } from 'path' |
9f10b292 | 4 | |
e02643f3 | 5 | import { database as db } from '../../../initializers/database' |
65fcc311 C |
6 | import { |
7 | CONFIG, | |
8 | REQUEST_VIDEO_QADU_TYPES, | |
9 | REQUEST_VIDEO_EVENT_TYPES, | |
10 | VIDEO_CATEGORIES, | |
11 | VIDEO_LICENCES, | |
fd45e8f4 C |
12 | VIDEO_LANGUAGES, |
13 | VIDEO_PRIVACIES | |
65fcc311 C |
14 | } from '../../../initializers' |
15 | import { | |
16 | addEventToRemoteVideo, | |
17 | quickAndDirtyUpdateVideoToFriends, | |
18 | addVideoToFriends, | |
93e1258c | 19 | updateVideoToFriends, |
9567011b C |
20 | JobScheduler, |
21 | fetchRemoteDescription | |
65fcc311 C |
22 | } from '../../../lib' |
23 | import { | |
24 | authenticate, | |
25 | paginationValidator, | |
26 | videosSortValidator, | |
27 | setVideosSort, | |
28 | setPagination, | |
29 | setVideosSearch, | |
30 | videosUpdateValidator, | |
31 | videosSearchValidator, | |
32 | videosAddValidator, | |
33 | videosGetValidator, | |
eb080476 C |
34 | videosRemoveValidator, |
35 | asyncMiddleware | |
65fcc311 C |
36 | } from '../../../middlewares' |
37 | import { | |
38 | logger, | |
65fcc311 | 39 | retryTransactionWrapper, |
65fcc311 | 40 | generateRandomString, |
0aef76c4 | 41 | getFormattedObjects, |
14d3270f | 42 | renamePromise, |
eb080476 C |
43 | getVideoFileHeight, |
44 | resetSequelizeInstance | |
65fcc311 | 45 | } from '../../../helpers' |
d412e80e | 46 | import { VideoInstance } from '../../../models' |
fd45e8f4 | 47 | import { VideoCreate, VideoUpdate, VideoPrivacy } from '../../../../shared' |
65fcc311 C |
48 | |
49 | import { abuseVideoRouter } from './abuse' | |
50 | import { blacklistRouter } from './blacklist' | |
51 | import { rateVideoRouter } from './rate' | |
72c7248b | 52 | import { videoChannelRouter } from './channel' |
65fcc311 C |
53 | |
54 | const videosRouter = express.Router() | |
9f10b292 C |
55 | |
56 | // multer configuration | |
f0f5567b | 57 | const storage = multer.diskStorage({ |
075f16ca | 58 | destination: (req, file, cb) => { |
65fcc311 | 59 | cb(null, CONFIG.STORAGE.VIDEOS_DIR) |
9f10b292 C |
60 | }, |
61 | ||
075f16ca | 62 | filename: (req, file, cb) => { |
f0f5567b | 63 | let extension = '' |
9f10b292 C |
64 | if (file.mimetype === 'video/webm') extension = 'webm' |
65 | else if (file.mimetype === 'video/mp4') extension = 'mp4' | |
66 | else if (file.mimetype === 'video/ogg') extension = 'ogv' | |
6fcd19ba C |
67 | generateRandomString(16) |
68 | .then(randomString => { | |
556ddc31 | 69 | cb(null, randomString + '.' + extension) |
6fcd19ba C |
70 | }) |
71 | .catch(err => { | |
ad0997ad | 72 | logger.error('Cannot generate random string for file name.', err) |
6fcd19ba C |
73 | throw err |
74 | }) | |
9f10b292 C |
75 | } |
76 | }) | |
77 | ||
8c9c1942 | 78 | const reqFiles = multer({ storage: storage }).fields([{ name: 'videofile', maxCount: 1 }]) |
8c308c2b | 79 | |
65fcc311 C |
80 | videosRouter.use('/', abuseVideoRouter) |
81 | videosRouter.use('/', blacklistRouter) | |
82 | videosRouter.use('/', rateVideoRouter) | |
72c7248b | 83 | videosRouter.use('/', videoChannelRouter) |
d33242b0 | 84 | |
65fcc311 C |
85 | videosRouter.get('/categories', listVideoCategories) |
86 | videosRouter.get('/licences', listVideoLicences) | |
87 | videosRouter.get('/languages', listVideoLanguages) | |
fd45e8f4 | 88 | videosRouter.get('/privacies', listVideoPrivacies) |
6e07c3de | 89 | |
65fcc311 C |
90 | videosRouter.get('/', |
91 | paginationValidator, | |
92 | videosSortValidator, | |
93 | setVideosSort, | |
94 | setPagination, | |
eb080476 | 95 | asyncMiddleware(listVideos) |
fbf1134e | 96 | ) |
65fcc311 C |
97 | videosRouter.put('/:id', |
98 | authenticate, | |
65fcc311 | 99 | videosUpdateValidator, |
eb080476 | 100 | asyncMiddleware(updateVideoRetryWrapper) |
7b1f49de | 101 | ) |
e95561cd | 102 | videosRouter.post('/upload', |
65fcc311 | 103 | authenticate, |
fbf1134e | 104 | reqFiles, |
65fcc311 | 105 | videosAddValidator, |
eb080476 | 106 | asyncMiddleware(addVideoRetryWrapper) |
fbf1134e | 107 | ) |
9567011b C |
108 | |
109 | videosRouter.get('/:id/description', | |
110 | videosGetValidator, | |
111 | asyncMiddleware(getVideoDescription) | |
112 | ) | |
65fcc311 C |
113 | videosRouter.get('/:id', |
114 | videosGetValidator, | |
68ce3ae0 | 115 | getVideo |
fbf1134e | 116 | ) |
198b205c | 117 | |
65fcc311 C |
118 | videosRouter.delete('/:id', |
119 | authenticate, | |
120 | videosRemoveValidator, | |
eb080476 | 121 | asyncMiddleware(removeVideoRetryWrapper) |
fbf1134e | 122 | ) |
198b205c | 123 | |
65fcc311 C |
124 | videosRouter.get('/search/:value', |
125 | videosSearchValidator, | |
126 | paginationValidator, | |
127 | videosSortValidator, | |
128 | setVideosSort, | |
129 | setPagination, | |
130 | setVideosSearch, | |
eb080476 | 131 | asyncMiddleware(searchVideos) |
fbf1134e | 132 | ) |
8c308c2b | 133 | |
9f10b292 | 134 | // --------------------------------------------------------------------------- |
c45f7f84 | 135 | |
65fcc311 C |
136 | export { |
137 | videosRouter | |
138 | } | |
c45f7f84 | 139 | |
9f10b292 | 140 | // --------------------------------------------------------------------------- |
c45f7f84 | 141 | |
556ddc31 | 142 | function listVideoCategories (req: express.Request, res: express.Response) { |
65fcc311 | 143 | res.json(VIDEO_CATEGORIES) |
6e07c3de C |
144 | } |
145 | ||
556ddc31 | 146 | function listVideoLicences (req: express.Request, res: express.Response) { |
65fcc311 | 147 | res.json(VIDEO_LICENCES) |
6f0c39e2 C |
148 | } |
149 | ||
556ddc31 | 150 | function listVideoLanguages (req: express.Request, res: express.Response) { |
65fcc311 | 151 | res.json(VIDEO_LANGUAGES) |
3092476e C |
152 | } |
153 | ||
fd45e8f4 C |
154 | function listVideoPrivacies (req: express.Request, res: express.Response) { |
155 | res.json(VIDEO_PRIVACIES) | |
156 | } | |
157 | ||
ed04d94f C |
158 | // Wrapper to video add that retry the function if there is a database error |
159 | // We need this because we run the transaction in SERIALIZABLE isolation that can fail | |
eb080476 | 160 | async function addVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) { |
d6a5b018 | 161 | const options = { |
556ddc31 | 162 | arguments: [ req, res, req.files['videofile'][0] ], |
d6a5b018 C |
163 | errorMessage: 'Cannot insert the video with many retries.' |
164 | } | |
ed04d94f | 165 | |
eb080476 C |
166 | await retryTransactionWrapper(addVideo, options) |
167 | ||
168 | // TODO : include Location of the new video -> 201 | |
169 | res.type('json').status(204).end() | |
ed04d94f C |
170 | } |
171 | ||
eb080476 | 172 | async function addVideo (req: express.Request, res: express.Response, videoPhysicalFile: Express.Multer.File) { |
556ddc31 | 173 | const videoInfo: VideoCreate = req.body |
6d33593a | 174 | let videoUUID = '' |
9f10b292 | 175 | |
eb080476 C |
176 | await db.sequelize.transaction(async t => { |
177 | const sequelizeOptions = { transaction: t } | |
178 | ||
179 | const videoData = { | |
180 | name: videoInfo.name, | |
181 | remote: false, | |
182 | extname: extname(videoPhysicalFile.filename), | |
183 | category: videoInfo.category, | |
184 | licence: videoInfo.licence, | |
185 | language: videoInfo.language, | |
186 | nsfw: videoInfo.nsfw, | |
187 | description: videoInfo.description, | |
fd45e8f4 | 188 | privacy: videoInfo.privacy, |
eb080476 C |
189 | duration: videoPhysicalFile['duration'], // duration was added by a previous middleware |
190 | channelId: res.locals.videoChannel.id | |
191 | } | |
192 | const video = db.Video.build(videoData) | |
6fcd19ba | 193 | |
eb080476 C |
194 | const videoFilePath = join(CONFIG.STORAGE.VIDEOS_DIR, videoPhysicalFile.filename) |
195 | const videoFileHeight = await getVideoFileHeight(videoFilePath) | |
93e1258c | 196 | |
eb080476 C |
197 | const videoFileData = { |
198 | extname: extname(videoPhysicalFile.filename), | |
199 | resolution: videoFileHeight, | |
200 | size: videoPhysicalFile.size | |
201 | } | |
202 | const videoFile = db.VideoFile.build(videoFileData) | |
203 | const videoDir = CONFIG.STORAGE.VIDEOS_DIR | |
204 | const source = join(videoDir, videoPhysicalFile.filename) | |
205 | const destination = join(videoDir, video.getVideoFilename(videoFile)) | |
206 | ||
207 | await renamePromise(source, destination) | |
208 | // This is important in case if there is another attempt in the retry process | |
209 | videoPhysicalFile.filename = video.getVideoFilename(videoFile) | |
210 | ||
211 | const tasks = [] | |
212 | ||
213 | tasks.push( | |
214 | video.createTorrentAndSetInfoHash(videoFile), | |
215 | video.createThumbnail(videoFile), | |
216 | video.createPreview(videoFile) | |
217 | ) | |
218 | ||
219 | if (CONFIG.TRANSCODING.ENABLED === true) { | |
220 | // Put uuid because we don't have id auto incremented for now | |
221 | const dataInput = { | |
222 | videoUUID: video.uuid | |
223 | } | |
224 | ||
225 | tasks.push( | |
226 | JobScheduler.Instance.createJob(t, 'videoFileOptimizer', dataInput) | |
227 | ) | |
228 | } | |
229 | await Promise.all(tasks) | |
93e1258c | 230 | |
eb080476 C |
231 | const videoCreated = await video.save(sequelizeOptions) |
232 | // Do not forget to add video channel information to the created video | |
233 | videoCreated.VideoChannel = res.locals.videoChannel | |
234 | videoUUID = videoCreated.uuid | |
7920c273 | 235 | |
eb080476 | 236 | videoFile.videoId = video.id |
feb4bdfd | 237 | |
eb080476 C |
238 | await videoFile.save(sequelizeOptions) |
239 | video.VideoFiles = [videoFile] | |
93e1258c | 240 | |
eb080476 C |
241 | if (videoInfo.tags) { |
242 | const tagInstances = await db.Tag.findOrCreateTags(videoInfo.tags, t) | |
243 | ||
244 | await video.setTags(tagInstances, sequelizeOptions) | |
245 | video.Tags = tagInstances | |
246 | } | |
247 | ||
248 | // Let transcoding job send the video to friends because the video file extension might change | |
249 | if (CONFIG.TRANSCODING.ENABLED === true) return undefined | |
fd45e8f4 C |
250 | // Don't send video to remote pods, it is private |
251 | if (video.privacy === VideoPrivacy.PRIVATE) return undefined | |
eb080476 C |
252 | |
253 | const remoteVideo = await video.toAddRemoteJSON() | |
254 | // Now we'll add the video's meta data to our friends | |
255 | return addVideoToFriends(remoteVideo, t) | |
7b1f49de | 256 | }) |
eb080476 C |
257 | |
258 | logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoUUID) | |
7b1f49de C |
259 | } |
260 | ||
eb080476 | 261 | async function updateVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) { |
d6a5b018 C |
262 | const options = { |
263 | arguments: [ req, res ], | |
264 | errorMessage: 'Cannot update the video with many retries.' | |
265 | } | |
ed04d94f | 266 | |
eb080476 C |
267 | await retryTransactionWrapper(updateVideo, options) |
268 | ||
269 | return res.type('json').status(204).end() | |
ed04d94f C |
270 | } |
271 | ||
eb080476 | 272 | async function updateVideo (req: express.Request, res: express.Response) { |
818f7987 | 273 | const videoInstance = res.locals.video |
7f4e7c36 | 274 | const videoFieldsSave = videoInstance.toJSON() |
556ddc31 | 275 | const videoInfoToUpdate: VideoUpdate = req.body |
fd45e8f4 | 276 | const wasPrivateVideo = videoInstance.privacy === VideoPrivacy.PRIVATE |
7b1f49de | 277 | |
eb080476 C |
278 | try { |
279 | await db.sequelize.transaction(async t => { | |
280 | const sequelizeOptions = { | |
281 | transaction: t | |
282 | } | |
7b1f49de | 283 | |
eb080476 C |
284 | if (videoInfoToUpdate.name !== undefined) videoInstance.set('name', videoInfoToUpdate.name) |
285 | if (videoInfoToUpdate.category !== undefined) videoInstance.set('category', videoInfoToUpdate.category) | |
286 | if (videoInfoToUpdate.licence !== undefined) videoInstance.set('licence', videoInfoToUpdate.licence) | |
287 | if (videoInfoToUpdate.language !== undefined) videoInstance.set('language', videoInfoToUpdate.language) | |
288 | if (videoInfoToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfoToUpdate.nsfw) | |
fd45e8f4 | 289 | if (videoInfoToUpdate.privacy !== undefined) videoInstance.set('privacy', videoInfoToUpdate.privacy) |
eb080476 | 290 | if (videoInfoToUpdate.description !== undefined) videoInstance.set('description', videoInfoToUpdate.description) |
7b1f49de | 291 | |
eb080476 | 292 | await videoInstance.save(sequelizeOptions) |
7b1f49de | 293 | |
eb080476 C |
294 | if (videoInfoToUpdate.tags) { |
295 | const tagInstances = await db.Tag.findOrCreateTags(videoInfoToUpdate.tags, t) | |
7b1f49de | 296 | |
eb080476 C |
297 | await videoInstance.setTags(tagInstances, sequelizeOptions) |
298 | videoInstance.Tags = tagInstances | |
299 | } | |
7920c273 | 300 | |
eb080476 | 301 | // Now we'll update the video's meta data to our friends |
fd45e8f4 C |
302 | if (wasPrivateVideo === false) { |
303 | const json = videoInstance.toUpdateRemoteJSON() | |
304 | return updateVideoToFriends(json, t) | |
305 | } | |
306 | ||
307 | // Video is not private anymore, send a create action to remote pods | |
308 | if (wasPrivateVideo === true && videoInstance.privacy !== VideoPrivacy.PRIVATE) { | |
309 | const remoteVideo = await videoInstance.toAddRemoteJSON() | |
310 | return addVideoToFriends(remoteVideo, t) | |
311 | } | |
eb080476 | 312 | }) |
6fcd19ba | 313 | |
eb080476 C |
314 | logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid) |
315 | } catch (err) { | |
6fcd19ba C |
316 | // Force fields we want to update |
317 | // If the transaction is retried, sequelize will think the object has not changed | |
318 | // So it will skip the SQL request, even if the last one was ROLLBACKed! | |
eb080476 | 319 | resetSequelizeInstance(videoInstance, videoFieldsSave) |
6fcd19ba C |
320 | |
321 | throw err | |
eb080476 | 322 | } |
9f10b292 | 323 | } |
8c308c2b | 324 | |
556ddc31 | 325 | function getVideo (req: express.Request, res: express.Response) { |
818f7987 | 326 | const videoInstance = res.locals.video |
9e167724 C |
327 | |
328 | if (videoInstance.isOwned()) { | |
329 | // The increment is done directly in the database, not using the instance value | |
eb080476 C |
330 | // FIXME: make a real view system |
331 | // For example, only add a view when a user watch a video during 30s etc | |
6fcd19ba C |
332 | videoInstance.increment('views') |
333 | .then(() => { | |
6fcd19ba C |
334 | const qaduParams = { |
335 | videoId: videoInstance.id, | |
336 | type: REQUEST_VIDEO_QADU_TYPES.VIEWS | |
337 | } | |
338 | return quickAndDirtyUpdateVideoToFriends(qaduParams) | |
339 | }) | |
eb080476 | 340 | .catch(err => logger.error('Cannot add view to video %s.', videoInstance.uuid, err)) |
e4c87ec2 C |
341 | } else { |
342 | // Just send the event to our friends | |
d38b8281 C |
343 | const eventParams = { |
344 | videoId: videoInstance.id, | |
65fcc311 | 345 | type: REQUEST_VIDEO_EVENT_TYPES.VIEWS |
d38b8281 | 346 | } |
65fcc311 | 347 | addEventToRemoteVideo(eventParams) |
eb080476 | 348 | .catch(err => logger.error('Cannot add event to remote video %s.', videoInstance.uuid, err)) |
9e167724 C |
349 | } |
350 | ||
351 | // Do not wait the view system | |
eb080476 | 352 | return res.json(videoInstance.toFormattedDetailsJSON()) |
9f10b292 | 353 | } |
8c308c2b | 354 | |
9567011b C |
355 | async function getVideoDescription (req: express.Request, res: express.Response) { |
356 | const videoInstance = res.locals.video | |
357 | let description = '' | |
358 | ||
359 | if (videoInstance.isOwned()) { | |
360 | description = videoInstance.description | |
361 | } else { | |
362 | description = await fetchRemoteDescription(videoInstance) | |
363 | } | |
364 | ||
365 | return res.json({ description }) | |
366 | } | |
367 | ||
eb080476 C |
368 | async function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) { |
369 | const resultList = await db.Video.listForApi(req.query.start, req.query.count, req.query.sort) | |
370 | ||
371 | return res.json(getFormattedObjects(resultList.data, resultList.total)) | |
9f10b292 | 372 | } |
c45f7f84 | 373 | |
eb080476 | 374 | async function removeVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) { |
91f6f169 C |
375 | const options = { |
376 | arguments: [ req, res ], | |
377 | errorMessage: 'Cannot remove the video with many retries.' | |
378 | } | |
8c308c2b | 379 | |
eb080476 C |
380 | await retryTransactionWrapper(removeVideo, options) |
381 | ||
382 | return res.type('json').status(204).end() | |
91f6f169 C |
383 | } |
384 | ||
eb080476 | 385 | async function removeVideo (req: express.Request, res: express.Response) { |
91f6f169 C |
386 | const videoInstance: VideoInstance = res.locals.video |
387 | ||
eb080476 C |
388 | await db.sequelize.transaction(async t => { |
389 | await videoInstance.destroy({ transaction: t }) | |
91f6f169 | 390 | }) |
eb080476 C |
391 | |
392 | logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid) | |
9f10b292 | 393 | } |
8c308c2b | 394 | |
eb080476 C |
395 | async function searchVideos (req: express.Request, res: express.Response, next: express.NextFunction) { |
396 | const resultList = await db.Video.searchAndPopulateAuthorAndPodAndTags( | |
397 | req.params.value, | |
398 | req.query.field, | |
399 | req.query.start, | |
400 | req.query.count, | |
401 | req.query.sort | |
402 | ) | |
403 | ||
404 | return res.json(getFormattedObjects(resultList.data, resultList.total)) | |
9f10b292 | 405 | } |