]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/videos/index.ts
Add ability to click on the account in watch page
[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, 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.support !== undefined) videoInstance.set('support', videoInfoToUpdate.support)
311 if (videoInfoToUpdate.description !== undefined) videoInstance.set('description', videoInfoToUpdate.description)
312 if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.set('commentsEnabled', videoInfoToUpdate.commentsEnabled)
313 if (videoInfoToUpdate.privacy !== undefined) {
314 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
315 videoInstance.set('privacy', newPrivacy)
316
317 if (wasPrivateVideo === true && newPrivacy !== VideoPrivacy.PRIVATE) {
318 videoInstance.set('publishedAt', new Date())
319 }
320 }
321
322 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions)
323
324 if (videoInfoToUpdate.tags) {
325 const tagInstances = await TagModel.findOrCreateTags(videoInfoToUpdate.tags, t)
326
327 await videoInstance.$set('Tags', tagInstances, sequelizeOptions)
328 videoInstance.Tags = tagInstances
329 }
330
331 // Now we'll update the video's meta data to our friends
332 if (wasPrivateVideo === false) {
333 await sendUpdateVideo(videoInstanceUpdated, t)
334 }
335
336 // Video is not private anymore, send a create action to remote servers
337 if (wasPrivateVideo === true && videoInstanceUpdated.privacy !== VideoPrivacy.PRIVATE) {
338 await sendCreateVideo(videoInstanceUpdated, t)
339 await shareVideoByServerAndChannel(videoInstanceUpdated, t)
340 }
341 })
342
343 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
344 } catch (err) {
345 // Force fields we want to update
346 // If the transaction is retried, sequelize will think the object has not changed
347 // So it will skip the SQL request, even if the last one was ROLLBACKed!
348 resetSequelizeInstance(videoInstance, videoFieldsSave)
349
350 throw err
351 }
352 }
353
354 function getVideo (req: express.Request, res: express.Response) {
355 const videoInstance = res.locals.video
356
357 return res.json(videoInstance.toFormattedDetailsJSON())
358 }
359
360 async function viewVideo (req: express.Request, res: express.Response) {
361 const videoInstance = res.locals.video
362
363 const ip = req.ip
364 const exists = await Redis.Instance.isViewExists(ip, videoInstance.uuid)
365 if (exists) {
366 logger.debug('View for ip %s and video %s already exists.', ip, videoInstance.uuid)
367 return res.status(204).end()
368 }
369
370 await videoInstance.increment('views')
371 await Redis.Instance.setView(ip, videoInstance.uuid)
372
373 const serverAccount = await getServerActor()
374
375 await sendCreateView(serverAccount, videoInstance, undefined)
376
377 return res.status(204).end()
378 }
379
380 async function getVideoDescription (req: express.Request, res: express.Response) {
381 const videoInstance = res.locals.video
382 let description = ''
383
384 if (videoInstance.isOwned()) {
385 description = videoInstance.description
386 } else {
387 description = await fetchRemoteVideoDescription(videoInstance)
388 }
389
390 return res.json({ description })
391 }
392
393 async function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
394 const resultList = await VideoModel.listForApi(req.query.start, req.query.count, req.query.sort, req.query.filter)
395
396 return res.json(getFormattedObjects(resultList.data, resultList.total))
397 }
398
399 async function removeVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
400 const options = {
401 arguments: [ req, res ],
402 errorMessage: 'Cannot remove the video with many retries.'
403 }
404
405 await retryTransactionWrapper(removeVideo, options)
406
407 return res.type('json').status(204).end()
408 }
409
410 async function removeVideo (req: express.Request, res: express.Response) {
411 const videoInstance: VideoModel = res.locals.video
412
413 await sequelizeTypescript.transaction(async t => {
414 await videoInstance.destroy({ transaction: t })
415 })
416
417 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
418 }
419
420 async function searchVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
421 const resultList = await VideoModel.searchAndPopulateAccountAndServer(
422 req.query.search,
423 req.query.start,
424 req.query.count,
425 req.query.sort
426 )
427
428 return res.json(getFormattedObjects(resultList.data, resultList.total))
429 }