]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/videos/index.ts
Design second video upload step
[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 17import { sendAddVideo } from '../../../lib/activitypub/send/send-add'
cadb46d8 18import { sendCreateViewToOrigin } from '../../../lib/activitypub/send/send-create'
54141398 19import { sendUpdateVideo } from '../../../lib/activitypub/send/send-update'
40ff5707
C
20import { shareVideoByServer } from '../../../lib/activitypub/share'
21import { getVideoActivityPubUrl } from '../../../lib/activitypub/url'
22import { fetchRemoteVideoDescription } from '../../../lib/activitypub/videos'
23import { sendCreateViewToVideoFollowers } from '../../../lib/index'
571389d4 24import { transcodingJobScheduler } from '../../../lib/jobs/transcoding-job-scheduler/transcoding-job-scheduler'
65fcc311 25import {
571389d4 26 asyncMiddleware,
65fcc311
C
27 authenticate,
28 paginationValidator,
65fcc311 29 setPagination,
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'
65fcc311
C
43
44const videosRouter = express.Router()
9f10b292
C
45
46// multer configuration
f0f5567b 47const storage = multer.diskStorage({
075f16ca 48 destination: (req, file, cb) => {
65fcc311 49 cb(null, CONFIG.STORAGE.VIDEOS_DIR)
9f10b292
C
50 },
51
0d0e8dd0
C
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
efc32059 63 cb(null, randomString + extension)
9f10b292
C
64 }
65})
66
8c9c1942 67const reqFiles = multer({ storage: storage }).fields([{ name: 'videofile', maxCount: 1 }])
8c308c2b 68
65fcc311
C
69videosRouter.use('/', abuseVideoRouter)
70videosRouter.use('/', blacklistRouter)
71videosRouter.use('/', rateVideoRouter)
72c7248b 72videosRouter.use('/', videoChannelRouter)
d33242b0 73
65fcc311
C
74videosRouter.get('/categories', listVideoCategories)
75videosRouter.get('/licences', listVideoLicences)
76videosRouter.get('/languages', listVideoLanguages)
fd45e8f4 77videosRouter.get('/privacies', listVideoPrivacies)
6e07c3de 78
65fcc311
C
79videosRouter.get('/',
80 paginationValidator,
81 videosSortValidator,
82 setVideosSort,
83 setPagination,
eb080476 84 asyncMiddleware(listVideos)
fbf1134e 85)
f3aaa9a9
C
86videosRouter.get('/search',
87 videosSearchValidator,
88 paginationValidator,
89 videosSortValidator,
90 setVideosSort,
91 setPagination,
92 asyncMiddleware(searchVideos)
93)
65fcc311
C
94videosRouter.put('/:id',
95 authenticate,
a2431b7d 96 asyncMiddleware(videosUpdateValidator),
eb080476 97 asyncMiddleware(updateVideoRetryWrapper)
7b1f49de 98)
e95561cd 99videosRouter.post('/upload',
65fcc311 100 authenticate,
fbf1134e 101 reqFiles,
65fcc311 102 videosAddValidator,
eb080476 103 asyncMiddleware(addVideoRetryWrapper)
fbf1134e 104)
9567011b
C
105
106videosRouter.get('/:id/description',
a2431b7d 107 asyncMiddleware(videosGetValidator),
9567011b
C
108 asyncMiddleware(getVideoDescription)
109)
65fcc311 110videosRouter.get('/:id',
a2431b7d 111 asyncMiddleware(videosGetValidator),
68ce3ae0 112 getVideo
fbf1134e 113)
1f3e9fec
C
114videosRouter.post('/:id/views',
115 asyncMiddleware(videosGetValidator),
116 asyncMiddleware(viewVideo)
117)
198b205c 118
65fcc311
C
119videosRouter.delete('/:id',
120 authenticate,
a2431b7d 121 asyncMiddleware(videosRemoveValidator),
eb080476 122 asyncMiddleware(removeVideoRetryWrapper)
fbf1134e 123)
198b205c 124
9f10b292 125// ---------------------------------------------------------------------------
c45f7f84 126
65fcc311
C
127export {
128 videosRouter
129}
c45f7f84 130
9f10b292 131// ---------------------------------------------------------------------------
c45f7f84 132
556ddc31 133function listVideoCategories (req: express.Request, res: express.Response) {
65fcc311 134 res.json(VIDEO_CATEGORIES)
6e07c3de
C
135}
136
556ddc31 137function listVideoLicences (req: express.Request, res: express.Response) {
65fcc311 138 res.json(VIDEO_LICENCES)
6f0c39e2
C
139}
140
556ddc31 141function listVideoLanguages (req: express.Request, res: express.Response) {
65fcc311 142 res.json(VIDEO_LANGUAGES)
3092476e
C
143}
144
fd45e8f4
C
145function listVideoPrivacies (req: express.Request, res: express.Response) {
146 res.json(VIDEO_PRIVACIES)
147}
148
ed04d94f
C
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
eb080476 151async function addVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
d6a5b018 152 const options = {
556ddc31 153 arguments: [ req, res, req.files['videofile'][0] ],
d6a5b018
C
154 errorMessage: 'Cannot insert the video with many retries.'
155 }
ed04d94f 156
cadb46d8 157 const video = await retryTransactionWrapper(addVideo, options)
eb080476 158
cadb46d8
C
159 res.json({
160 video: {
161 id: video.id,
162 uuid: video.uuid
163 }
164 }).end()
ed04d94f
C
165}
166
cadb46d8 167function addVideo (req: express.Request, res: express.Response, videoPhysicalFile: Express.Multer.File) {
556ddc31 168 const videoInfo: VideoCreate = req.body
9f10b292 169
cadb46d8 170 return db.sequelize.transaction(async t => {
eb080476
C
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,
fd45e8f4 182 privacy: videoInfo.privacy,
eb080476
C
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)
54141398 187 video.url = getVideoActivityPubUrl(video)
6fcd19ba 188
eb080476
C
189 const videoFilePath = join(CONFIG.STORAGE.VIDEOS_DIR, videoPhysicalFile.filename)
190 const videoFileHeight = await getVideoFileHeight(videoFilePath)
93e1258c 191
eb080476
C
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(
571389d4 221 transcodingJobScheduler.createJob(t, 'videoFileOptimizer', dataInput)
eb080476
C
222 )
223 }
224 await Promise.all(tasks)
93e1258c 225
eb080476
C
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
7920c273 229
eb080476 230 videoFile.videoId = video.id
feb4bdfd 231
eb080476
C
232 await videoFile.save(sequelizeOptions)
233 video.VideoFiles = [videoFile]
93e1258c 234
eb080476
C
235 if (videoInfo.tags) {
236 const tagInstances = await db.Tag.findOrCreateTags(videoInfo.tags, t)
237
238 await video.setTags(tagInstances, sequelizeOptions)
239 video.Tags = tagInstances
240 }
241
242 // Let transcoding job send the video to friends because the video file extension might change
cadb46d8 243 if (CONFIG.TRANSCODING.ENABLED === true) return videoCreated
60862425 244 // Don't send video to remote servers, it is private
cadb46d8 245 if (video.privacy === VideoPrivacy.PRIVATE) return videoCreated
eb080476 246
571389d4 247 await sendAddVideo(video, t)
efc32059 248 await shareVideoByServer(video, t)
eb080476 249
cadb46d8
C
250 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
251
252 return videoCreated
253 })
7b1f49de
C
254}
255
eb080476 256async function updateVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
d6a5b018
C
257 const options = {
258 arguments: [ req, res ],
259 errorMessage: 'Cannot update the video with many retries.'
260 }
ed04d94f 261
eb080476
C
262 await retryTransactionWrapper(updateVideo, options)
263
264 return res.type('json').status(204).end()
ed04d94f
C
265}
266
eb080476 267async function updateVideo (req: express.Request, res: express.Response) {
efc32059 268 const videoInstance: VideoInstance = res.locals.video
7f4e7c36 269 const videoFieldsSave = videoInstance.toJSON()
556ddc31 270 const videoInfoToUpdate: VideoUpdate = req.body
fd45e8f4 271 const wasPrivateVideo = videoInstance.privacy === VideoPrivacy.PRIVATE
7b1f49de 272
eb080476
C
273 try {
274 await db.sequelize.transaction(async t => {
275 const sequelizeOptions = {
276 transaction: t
277 }
7b1f49de 278
eb080476
C
279 if (videoInfoToUpdate.name !== undefined) videoInstance.set('name', videoInfoToUpdate.name)
280 if (videoInfoToUpdate.category !== undefined) videoInstance.set('category', videoInfoToUpdate.category)
281 if (videoInfoToUpdate.licence !== undefined) videoInstance.set('licence', videoInfoToUpdate.licence)
282 if (videoInfoToUpdate.language !== undefined) videoInstance.set('language', videoInfoToUpdate.language)
283 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfoToUpdate.nsfw)
fd45e8f4 284 if (videoInfoToUpdate.privacy !== undefined) videoInstance.set('privacy', videoInfoToUpdate.privacy)
eb080476 285 if (videoInfoToUpdate.description !== undefined) videoInstance.set('description', videoInfoToUpdate.description)
7b1f49de 286
54141398 287 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions)
7b1f49de 288
eb080476
C
289 if (videoInfoToUpdate.tags) {
290 const tagInstances = await db.Tag.findOrCreateTags(videoInfoToUpdate.tags, t)
7b1f49de 291
eb080476
C
292 await videoInstance.setTags(tagInstances, sequelizeOptions)
293 videoInstance.Tags = tagInstances
294 }
7920c273 295
eb080476 296 // Now we'll update the video's meta data to our friends
fd45e8f4 297 if (wasPrivateVideo === false) {
54141398 298 await sendUpdateVideo(videoInstanceUpdated, t)
fd45e8f4
C
299 }
300
60862425 301 // Video is not private anymore, send a create action to remote servers
fd45e8f4 302 if (wasPrivateVideo === true && videoInstance.privacy !== VideoPrivacy.PRIVATE) {
571389d4 303 await sendAddVideo(videoInstance, t)
572f8d3d 304 await shareVideoByServer(videoInstance, t)
fd45e8f4 305 }
eb080476 306 })
6fcd19ba 307
eb080476
C
308 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
309 } catch (err) {
6fcd19ba
C
310 // Force fields we want to update
311 // If the transaction is retried, sequelize will think the object has not changed
312 // So it will skip the SQL request, even if the last one was ROLLBACKed!
eb080476 313 resetSequelizeInstance(videoInstance, videoFieldsSave)
6fcd19ba
C
314
315 throw err
eb080476 316 }
9f10b292 317}
8c308c2b 318
1f3e9fec
C
319function getVideo (req: express.Request, res: express.Response) {
320 const videoInstance = res.locals.video
321
322 return res.json(videoInstance.toFormattedDetailsJSON())
323}
324
325async function viewVideo (req: express.Request, res: express.Response) {
818f7987 326 const videoInstance = res.locals.video
9e167724 327
1f3e9fec
C
328 await videoInstance.increment('views')
329 const serverAccount = await getServerAccount()
40ff5707 330
9e167724 331 if (videoInstance.isOwned()) {
1f3e9fec 332 await sendCreateViewToVideoFollowers(serverAccount, videoInstance, undefined)
e4c87ec2 333 } else {
1f3e9fec 334 await sendCreateViewToOrigin(serverAccount, videoInstance, undefined)
9e167724
C
335 }
336
1f3e9fec 337 return res.status(204).end()
9f10b292 338}
8c308c2b 339
9567011b
C
340async function getVideoDescription (req: express.Request, res: express.Response) {
341 const videoInstance = res.locals.video
342 let description = ''
343
344 if (videoInstance.isOwned()) {
345 description = videoInstance.description
346 } else {
571389d4 347 description = await fetchRemoteVideoDescription(videoInstance)
9567011b
C
348 }
349
350 return res.json({ description })
351}
352
eb080476
C
353async function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
354 const resultList = await db.Video.listForApi(req.query.start, req.query.count, req.query.sort)
355
356 return res.json(getFormattedObjects(resultList.data, resultList.total))
9f10b292 357}
c45f7f84 358
eb080476 359async function removeVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
91f6f169
C
360 const options = {
361 arguments: [ req, res ],
362 errorMessage: 'Cannot remove the video with many retries.'
363 }
8c308c2b 364
eb080476
C
365 await retryTransactionWrapper(removeVideo, options)
366
367 return res.type('json').status(204).end()
91f6f169
C
368}
369
eb080476 370async function removeVideo (req: express.Request, res: express.Response) {
91f6f169
C
371 const videoInstance: VideoInstance = res.locals.video
372
eb080476
C
373 await db.sequelize.transaction(async t => {
374 await videoInstance.destroy({ transaction: t })
91f6f169 375 })
eb080476
C
376
377 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
9f10b292 378}
8c308c2b 379
eb080476 380async function searchVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
60862425 381 const resultList = await db.Video.searchAndPopulateAccountAndServerAndTags(
f3aaa9a9 382 req.query.search,
eb080476
C
383 req.query.start,
384 req.query.count,
385 req.query.sort
386 )
387
388 return res.json(getFormattedObjects(resultList.data, resultList.total))
9f10b292 389}