]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/videos/index.ts
Add beautiful loading bar
[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 { sendCreateViewToOrigin } from '../../../lib/activitypub/send/send-create'
19 import { sendUpdateVideo } from '../../../lib/activitypub/send/send-update'
20 import { shareVideoByServer } from '../../../lib/activitypub/share'
21 import { getVideoActivityPubUrl } from '../../../lib/activitypub/url'
22 import { fetchRemoteVideoDescription } from '../../../lib/activitypub/videos'
23 import { sendCreateViewToVideoFollowers } from '../../../lib/index'
24 import { transcodingJobScheduler } from '../../../lib/jobs/transcoding-job-scheduler/transcoding-job-scheduler'
25 import {
26 asyncMiddleware,
27 authenticate,
28 paginationValidator,
29 setPagination,
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
44 const videosRouter = express.Router()
45
46 // multer configuration
47 const storage = multer.diskStorage({
48 destination: (req, file, cb) => {
49 cb(null, CONFIG.STORAGE.VIDEOS_DIR)
50 },
51
52 filename: async (req, file, cb) => {
53 const extension = VIDEO_MIMETYPE_EXT[file.mimetype]
54 let randomString = ''
55
56 try {
57 randomString = await generateRandomString(16)
58 } catch (err) {
59 logger.error('Cannot generate random string for file name.', err)
60 randomString = 'fake-random-string'
61 }
62
63 cb(null, randomString + extension)
64 }
65 })
66
67 const reqFiles = multer({ storage: storage }).fields([{ name: 'videofile', maxCount: 1 }])
68
69 videosRouter.use('/', abuseVideoRouter)
70 videosRouter.use('/', blacklistRouter)
71 videosRouter.use('/', rateVideoRouter)
72 videosRouter.use('/', videoChannelRouter)
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 setVideosSort,
83 setPagination,
84 asyncMiddleware(listVideos)
85 )
86 videosRouter.get('/search',
87 videosSearchValidator,
88 paginationValidator,
89 videosSortValidator,
90 setVideosSort,
91 setPagination,
92 asyncMiddleware(searchVideos)
93 )
94 videosRouter.put('/:id',
95 authenticate,
96 asyncMiddleware(videosUpdateValidator),
97 asyncMiddleware(updateVideoRetryWrapper)
98 )
99 videosRouter.post('/upload',
100 authenticate,
101 reqFiles,
102 videosAddValidator,
103 asyncMiddleware(addVideoRetryWrapper)
104 )
105
106 videosRouter.get('/:id/description',
107 asyncMiddleware(videosGetValidator),
108 asyncMiddleware(getVideoDescription)
109 )
110 videosRouter.get('/:id',
111 asyncMiddleware(videosGetValidator),
112 getVideo
113 )
114 videosRouter.post('/:id/views',
115 asyncMiddleware(videosGetValidator),
116 asyncMiddleware(viewVideo)
117 )
118
119 videosRouter.delete('/:id',
120 authenticate,
121 asyncMiddleware(videosRemoveValidator),
122 asyncMiddleware(removeVideoRetryWrapper)
123 )
124
125 // ---------------------------------------------------------------------------
126
127 export {
128 videosRouter
129 }
130
131 // ---------------------------------------------------------------------------
132
133 function listVideoCategories (req: express.Request, res: express.Response) {
134 res.json(VIDEO_CATEGORIES)
135 }
136
137 function listVideoLicences (req: express.Request, res: express.Response) {
138 res.json(VIDEO_LICENCES)
139 }
140
141 function listVideoLanguages (req: express.Request, res: express.Response) {
142 res.json(VIDEO_LANGUAGES)
143 }
144
145 function listVideoPrivacies (req: express.Request, res: express.Response) {
146 res.json(VIDEO_PRIVACIES)
147 }
148
149 // Wrapper to video add that retry the function if there is a database error
150 // We need this because we run the transaction in SERIALIZABLE isolation that can fail
151 async function addVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
152 const options = {
153 arguments: [ req, res, req.files['videofile'][0] ],
154 errorMessage: 'Cannot insert the video with many retries.'
155 }
156
157 const video = await retryTransactionWrapper(addVideo, options)
158
159 res.json({
160 video: {
161 id: video.id,
162 uuid: video.uuid
163 }
164 }).end()
165 }
166
167 async function addVideo (req: express.Request, res: express.Response, videoPhysicalFile: Express.Multer.File) {
168 const videoInfo: VideoCreate = req.body
169
170 // Prepare data so we don't block the transaction
171 const videoData = {
172 name: videoInfo.name,
173 remote: false,
174 extname: extname(videoPhysicalFile.filename),
175 category: videoInfo.category,
176 licence: videoInfo.licence,
177 language: videoInfo.language,
178 nsfw: videoInfo.nsfw,
179 description: videoInfo.description,
180 privacy: videoInfo.privacy,
181 duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
182 channelId: res.locals.videoChannel.id
183 }
184 const video = db.Video.build(videoData)
185 video.url = getVideoActivityPubUrl(video)
186
187 const videoFilePath = join(CONFIG.STORAGE.VIDEOS_DIR, videoPhysicalFile.filename)
188 const videoFileHeight = await getVideoFileHeight(videoFilePath)
189
190 const videoFileData = {
191 extname: extname(videoPhysicalFile.filename),
192 resolution: videoFileHeight,
193 size: videoPhysicalFile.size
194 }
195 const videoFile = db.VideoFile.build(videoFileData)
196 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
197 const source = join(videoDir, videoPhysicalFile.filename)
198 const destination = join(videoDir, video.getVideoFilename(videoFile))
199
200 await renamePromise(source, destination)
201 // This is important in case if there is another attempt in the retry process
202 videoPhysicalFile.filename = video.getVideoFilename(videoFile)
203
204 const tasks = []
205
206 tasks.push(
207 video.createTorrentAndSetInfoHash(videoFile),
208 video.createThumbnail(videoFile),
209 video.createPreview(videoFile)
210 )
211 await Promise.all(tasks)
212
213 return db.sequelize.transaction(async t => {
214 const sequelizeOptions = { transaction: t }
215
216 if (CONFIG.TRANSCODING.ENABLED === true) {
217 // Put uuid because we don't have id auto incremented for now
218 const dataInput = {
219 videoUUID: video.uuid
220 }
221
222 await transcodingJobScheduler.createJob(t, 'videoFileOptimizer', dataInput)
223 }
224
225 const videoCreated = await video.save(sequelizeOptions)
226 // Do not forget to add video channel information to the created video
227 videoCreated.VideoChannel = res.locals.videoChannel
228
229 videoFile.videoId = video.id
230 await videoFile.save(sequelizeOptions)
231
232 video.VideoFiles = [ videoFile ]
233
234 if (videoInfo.tags) {
235 const tagInstances = await db.Tag.findOrCreateTags(videoInfo.tags, t)
236
237 await video.setTags(tagInstances, sequelizeOptions)
238 video.Tags = tagInstances
239 }
240
241 // Let transcoding job send the video to friends because the video file extension might change
242 if (CONFIG.TRANSCODING.ENABLED === true) return videoCreated
243 // Don't send video to remote servers, it is private
244 if (video.privacy === VideoPrivacy.PRIVATE) return videoCreated
245
246 await sendAddVideo(video, t)
247 await shareVideoByServer(video, t)
248
249 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
250
251 return videoCreated
252 })
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', parseInt(videoInfoToUpdate.privacy.toString(), 10))
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 && videoInstanceUpdated.privacy !== VideoPrivacy.PRIVATE) {
302 await sendAddVideo(videoInstanceUpdated, t)
303 await shareVideoByServer(videoInstanceUpdated, 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.query.search,
382 req.query.start,
383 req.query.count,
384 req.query.sort
385 )
386
387 return res.json(getFormattedObjects(resultList.data, resultList.total))
388 }