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