]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/videos/index.ts
Fix images size limit
[github/Chocobozzz/PeerTube.git] / server / controllers / api / videos / index.ts
1 import * as express from 'express'
2 import { extname, join } from 'path'
3 import { VideoCreate, VideoPrivacy, VideoState, VideoUpdate } from '../../../../shared'
4 import { renamePromise } from '../../../helpers/core-utils'
5 import { getVideoFileResolution } from '../../../helpers/ffmpeg-utils'
6 import { processImage } from '../../../helpers/image-utils'
7 import { logger } from '../../../helpers/logger'
8 import { getFormattedObjects, getServerActor, resetSequelizeInstance } 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 optionalAuthenticate,
35 paginationValidator,
36 setDefaultPagination,
37 setDefaultSort,
38 videosAddValidator,
39 videosGetValidator,
40 videosRemoveValidator,
41 videosSearchValidator,
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 { VideoFilter } from '../../../../shared/models/videos/video-query.type'
53 import { VideoSortField } from '../../../../client/src/app/shared/video/sort-field.type'
54 import { createReqFiles, isNSFWHidden } from '../../../helpers/express-utils'
55 import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update'
56
57 const videosRouter = express.Router()
58
59 const reqVideoFileAdd = createReqFiles(
60 [ 'videofile', 'thumbnailfile', 'previewfile' ],
61 Object.assign({}, VIDEO_MIMETYPE_EXT, IMAGE_MIMETYPE_EXT),
62 {
63 videofile: CONFIG.STORAGE.VIDEOS_DIR,
64 thumbnailfile: CONFIG.STORAGE.THUMBNAILS_DIR,
65 previewfile: CONFIG.STORAGE.PREVIEWS_DIR
66 }
67 )
68 const reqVideoFileUpdate = createReqFiles(
69 [ 'thumbnailfile', 'previewfile' ],
70 IMAGE_MIMETYPE_EXT,
71 {
72 thumbnailfile: CONFIG.STORAGE.THUMBNAILS_DIR,
73 previewfile: CONFIG.STORAGE.PREVIEWS_DIR
74 }
75 )
76
77 videosRouter.use('/', abuseVideoRouter)
78 videosRouter.use('/', blacklistRouter)
79 videosRouter.use('/', rateVideoRouter)
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 asyncRetryTransactionMiddleware(updateVideo)
109 )
110 videosRouter.post('/upload',
111 authenticate,
112 reqVideoFileAdd,
113 asyncMiddleware(videosAddValidator),
114 asyncRetryTransactionMiddleware(addVideo)
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 asyncRetryTransactionMiddleware(removeVideo)
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 async function addVideo (req: express.Request, res: express.Response) {
161 const videoPhysicalFile = req.files['videofile'][0]
162 const videoInfo: VideoCreate = req.body
163
164 // Prepare data so we don't block the transaction
165 const videoData = {
166 name: videoInfo.name,
167 remote: false,
168 extname: extname(videoPhysicalFile.filename),
169 category: videoInfo.category,
170 licence: videoInfo.licence,
171 language: videoInfo.language,
172 commentsEnabled: videoInfo.commentsEnabled || false,
173 waitTranscoding: videoInfo.waitTranscoding || false,
174 state: CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED,
175 nsfw: videoInfo.nsfw || false,
176 description: videoInfo.description,
177 support: videoInfo.support,
178 privacy: videoInfo.privacy,
179 duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
180 channelId: res.locals.videoChannel.id
181 }
182 const video = new VideoModel(videoData)
183 video.url = getVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
184
185 // Build the file object
186 const { videoFileResolution } = await getVideoFileResolution(videoPhysicalFile.path)
187 const videoFileData = {
188 extname: extname(videoPhysicalFile.filename),
189 resolution: videoFileResolution,
190 size: videoPhysicalFile.size
191 }
192 const videoFile = new VideoFileModel(videoFileData)
193
194 // Move physical file
195 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
196 const destination = join(videoDir, video.getVideoFilename(videoFile))
197 await renamePromise(videoPhysicalFile.path, destination)
198 // This is important in case if there is another attempt in the retry process
199 videoPhysicalFile.filename = video.getVideoFilename(videoFile)
200 videoPhysicalFile.path = destination
201
202 // Process thumbnail or create it from the video
203 const thumbnailField = req.files['thumbnailfile']
204 if (thumbnailField) {
205 const thumbnailPhysicalFile = thumbnailField[0]
206 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName()), THUMBNAILS_SIZE)
207 } else {
208 await video.createThumbnail(videoFile)
209 }
210
211 // Process preview or create it from the video
212 const previewField = req.files['previewfile']
213 if (previewField) {
214 const previewPhysicalFile = previewField[0]
215 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName()), PREVIEWS_SIZE)
216 } else {
217 await video.createPreview(videoFile)
218 }
219
220 // Create the torrent file
221 await video.createTorrentAndSetInfoHash(videoFile)
222
223 const videoCreated = await sequelizeTypescript.transaction(async t => {
224 const sequelizeOptions = { transaction: t }
225
226 const videoCreated = await video.save(sequelizeOptions)
227 // Do not forget to add video channel information to the created video
228 videoCreated.VideoChannel = res.locals.videoChannel
229
230 videoFile.videoId = video.id
231 await videoFile.save(sequelizeOptions)
232
233 video.VideoFiles = [ videoFile ]
234
235 // Create tags
236 if (videoInfo.tags !== undefined) {
237 const tagInstances = await TagModel.findOrCreateTags(videoInfo.tags, t)
238
239 await video.$set('Tags', tagInstances, sequelizeOptions)
240 video.Tags = tagInstances
241 }
242
243 // Schedule an update in the future?
244 if (videoInfo.scheduleUpdate) {
245 await ScheduleVideoUpdateModel.create({
246 videoId: video.id,
247 updateAt: videoInfo.scheduleUpdate.updateAt,
248 privacy: videoInfo.scheduleUpdate.privacy || null
249 }, { transaction: t })
250 }
251
252 await federateVideoIfNeeded(video, true, t)
253
254 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
255
256 return videoCreated
257 })
258
259 if (video.state === VideoState.TO_TRANSCODE) {
260 // Put uuid because we don't have id auto incremented for now
261 const dataInput = {
262 videoUUID: videoCreated.uuid,
263 isNewVideo: true
264 }
265
266 await JobQueue.Instance.createJob({ type: 'video-file', payload: dataInput })
267 }
268
269 return res.json({
270 video: {
271 id: videoCreated.id,
272 uuid: videoCreated.uuid
273 }
274 }).end()
275 }
276
277 async function updateVideo (req: express.Request, res: express.Response) {
278 const videoInstance: VideoModel = res.locals.video
279 const videoFieldsSave = videoInstance.toJSON()
280 const videoInfoToUpdate: VideoUpdate = req.body
281 const wasPrivateVideo = videoInstance.privacy === VideoPrivacy.PRIVATE
282
283 // Process thumbnail or create it from the video
284 if (req.files && req.files['thumbnailfile']) {
285 const thumbnailPhysicalFile = req.files['thumbnailfile'][0]
286 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, videoInstance.getThumbnailName()), THUMBNAILS_SIZE)
287 }
288
289 // Process preview or create it from the video
290 if (req.files && req.files['previewfile']) {
291 const previewPhysicalFile = req.files['previewfile'][0]
292 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, videoInstance.getPreviewName()), PREVIEWS_SIZE)
293 }
294
295 try {
296 await sequelizeTypescript.transaction(async t => {
297 const sequelizeOptions = {
298 transaction: t
299 }
300 const oldVideoChannel = videoInstance.VideoChannel
301
302 if (videoInfoToUpdate.name !== undefined) videoInstance.set('name', videoInfoToUpdate.name)
303 if (videoInfoToUpdate.category !== undefined) videoInstance.set('category', videoInfoToUpdate.category)
304 if (videoInfoToUpdate.licence !== undefined) videoInstance.set('licence', videoInfoToUpdate.licence)
305 if (videoInfoToUpdate.language !== undefined) videoInstance.set('language', videoInfoToUpdate.language)
306 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfoToUpdate.nsfw)
307 if (videoInfoToUpdate.waitTranscoding !== undefined) videoInstance.set('waitTranscoding', videoInfoToUpdate.waitTranscoding)
308 if (videoInfoToUpdate.support !== undefined) videoInstance.set('support', videoInfoToUpdate.support)
309 if (videoInfoToUpdate.description !== undefined) videoInstance.set('description', videoInfoToUpdate.description)
310 if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.set('commentsEnabled', videoInfoToUpdate.commentsEnabled)
311 if (videoInfoToUpdate.privacy !== undefined) {
312 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
313 videoInstance.set('privacy', newPrivacy)
314
315 if (wasPrivateVideo === true && newPrivacy !== VideoPrivacy.PRIVATE) {
316 videoInstance.set('publishedAt', new Date())
317 }
318 }
319
320 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions)
321
322 // Video tags update?
323 if (videoInfoToUpdate.tags !== undefined) {
324 const tagInstances = await TagModel.findOrCreateTags(videoInfoToUpdate.tags, t)
325
326 await videoInstanceUpdated.$set('Tags', tagInstances, sequelizeOptions)
327 videoInstanceUpdated.Tags = tagInstances
328 }
329
330 // Video channel update?
331 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
332 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
333 videoInstanceUpdated.VideoChannel = res.locals.videoChannel
334
335 if (wasPrivateVideo === false) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
336 }
337
338 // Schedule an update in the future?
339 if (videoInfoToUpdate.scheduleUpdate) {
340 await ScheduleVideoUpdateModel.upsert({
341 videoId: videoInstanceUpdated.id,
342 updateAt: videoInfoToUpdate.scheduleUpdate.updateAt,
343 privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
344 }, { transaction: t })
345 } else if (videoInfoToUpdate.scheduleUpdate === null) {
346 await ScheduleVideoUpdateModel.deleteByVideoId(videoInstanceUpdated.id, t)
347 }
348
349 const isNewVideo = wasPrivateVideo && videoInstanceUpdated.privacy !== VideoPrivacy.PRIVATE
350 await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t)
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 return res.type('json').status(204).end()
364 }
365
366 function getVideo (req: express.Request, res: express.Response) {
367 const videoInstance = res.locals.video
368
369 return res.json(videoInstance.toFormattedDetailsJSON())
370 }
371
372 async function viewVideo (req: express.Request, res: express.Response) {
373 const videoInstance = res.locals.video
374
375 const ip = req.ip
376 const exists = await Redis.Instance.isViewExists(ip, videoInstance.uuid)
377 if (exists) {
378 logger.debug('View for ip %s and video %s already exists.', ip, videoInstance.uuid)
379 return res.status(204).end()
380 }
381
382 await videoInstance.increment('views')
383 await Redis.Instance.setView(ip, videoInstance.uuid)
384
385 const serverAccount = await getServerActor()
386
387 await sendCreateView(serverAccount, videoInstance, undefined)
388
389 return res.status(204).end()
390 }
391
392 async function getVideoDescription (req: express.Request, res: express.Response) {
393 const videoInstance = res.locals.video
394 let description = ''
395
396 if (videoInstance.isOwned()) {
397 description = videoInstance.description
398 } else {
399 description = await fetchRemoteVideoDescription(videoInstance)
400 }
401
402 return res.json({ description })
403 }
404
405 async function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
406 const resultList = await VideoModel.listForApi({
407 start: req.query.start,
408 count: req.query.count,
409 sort: req.query.sort,
410 hideNSFW: isNSFWHidden(res),
411 filter: req.query.filter as VideoFilter,
412 withFiles: false
413 })
414
415 return res.json(getFormattedObjects(resultList.data, resultList.total))
416 }
417
418 async function removeVideo (req: express.Request, res: express.Response) {
419 const videoInstance: VideoModel = res.locals.video
420
421 await sequelizeTypescript.transaction(async t => {
422 await videoInstance.destroy({ transaction: t })
423 })
424
425 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
426
427 return res.type('json').status(204).end()
428 }
429
430 async function searchVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
431 const resultList = await VideoModel.searchAndPopulateAccountAndServer(
432 req.query.search as string,
433 req.query.start as number,
434 req.query.count as number,
435 req.query.sort as VideoSortField,
436 isNSFWHidden(res)
437 )
438
439 return res.json(getFormattedObjects(resultList.data, resultList.total))
440 }