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