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