]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/videos/index.ts
Implement captions/subtitles
[github/Chocobozzz/PeerTube.git] / server / controllers / api / videos / index.ts
CommitLineData
4d4e5cd4 1import * as express from 'express'
93e1258c 2import { extname, join } from 'path'
2186386c 3import { VideoCreate, VideoPrivacy, VideoState, VideoUpdate } from '../../../../shared'
da854ddd 4import { renamePromise } from '../../../helpers/core-utils'
3a6f351b 5import { getVideoFileFPS, getVideoFileResolution } from '../../../helpers/ffmpeg-utils'
ac81d1a0 6import { processImage } from '../../../helpers/image-utils'
da854ddd 7import { logger } from '../../../helpers/logger'
0626e7af 8import { getFormattedObjects, getServerActor, resetSequelizeInstance } from '../../../helpers/utils'
65fcc311 9import {
ac81d1a0
C
10 CONFIG,
11 IMAGE_MIMETYPE_EXT,
12 PREVIEWS_SIZE,
13 sequelizeTypescript,
14 THUMBNAILS_SIZE,
15 VIDEO_CATEGORIES,
16 VIDEO_LANGUAGES,
17 VIDEO_LICENCES,
18 VIDEO_MIMETYPE_EXT,
3fd3ab2d
C
19 VIDEO_PRIVACIES
20} from '../../../initializers'
0f320037
C
21import {
22 changeVideoChannelShare,
2186386c 23 federateVideoIfNeeded,
0f320037 24 fetchRemoteVideoDescription,
2186386c 25 getVideoActivityPubUrl
0f320037 26} from '../../../lib/activitypub'
2186386c 27import { sendCreateView } from '../../../lib/activitypub/send'
94a5ff8a 28import { JobQueue } from '../../../lib/job-queue'
b5c0e955 29import { Redis } from '../../../lib/redis'
65fcc311 30import {
ac81d1a0 31 asyncMiddleware,
90d4bb81 32 asyncRetryTransactionMiddleware,
ac81d1a0 33 authenticate,
0883b324 34 optionalAuthenticate,
ac81d1a0
C
35 paginationValidator,
36 setDefaultPagination,
37 setDefaultSort,
38 videosAddValidator,
39 videosGetValidator,
40 videosRemoveValidator,
41 videosSearchValidator,
42 videosSortValidator,
43 videosUpdateValidator
65fcc311 44} from '../../../middlewares'
3fd3ab2d
C
45import { TagModel } from '../../../models/video/tag'
46import { VideoModel } from '../../../models/video/video'
47import { VideoFileModel } from '../../../models/video/video-file'
65fcc311
C
48import { abuseVideoRouter } from './abuse'
49import { blacklistRouter } from './blacklist'
bf1f6508 50import { videoCommentRouter } from './comment'
571389d4 51import { rateVideoRouter } from './rate'
0883b324
C
52import { VideoFilter } from '../../../../shared/models/videos/video-query.type'
53import { VideoSortField } from '../../../../client/src/app/shared/video/sort-field.type'
2186386c 54import { createReqFiles, isNSFWHidden } from '../../../helpers/express-utils'
2baea0c7 55import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update'
40e87e9e 56import { videoCaptionsRouter } from './captions'
65fcc311
C
57
58const videosRouter = express.Router()
9f10b292 59
ac81d1a0
C
60const reqVideoFileAdd = createReqFiles(
61 [ 'videofile', 'thumbnailfile', 'previewfile' ],
62 Object.assign({}, VIDEO_MIMETYPE_EXT, IMAGE_MIMETYPE_EXT),
63 {
64 videofile: CONFIG.STORAGE.VIDEOS_DIR,
65 thumbnailfile: CONFIG.STORAGE.THUMBNAILS_DIR,
66 previewfile: CONFIG.STORAGE.PREVIEWS_DIR
67 }
68)
69const reqVideoFileUpdate = createReqFiles(
70 [ 'thumbnailfile', 'previewfile' ],
71 IMAGE_MIMETYPE_EXT,
72 {
73 thumbnailfile: CONFIG.STORAGE.THUMBNAILS_DIR,
74 previewfile: CONFIG.STORAGE.PREVIEWS_DIR
75 }
76)
8c308c2b 77
65fcc311
C
78videosRouter.use('/', abuseVideoRouter)
79videosRouter.use('/', blacklistRouter)
80videosRouter.use('/', rateVideoRouter)
bf1f6508 81videosRouter.use('/', videoCommentRouter)
40e87e9e 82videosRouter.use('/', videoCaptionsRouter)
d33242b0 83
65fcc311
C
84videosRouter.get('/categories', listVideoCategories)
85videosRouter.get('/licences', listVideoLicences)
86videosRouter.get('/languages', listVideoLanguages)
fd45e8f4 87videosRouter.get('/privacies', listVideoPrivacies)
6e07c3de 88
65fcc311
C
89videosRouter.get('/',
90 paginationValidator,
91 videosSortValidator,
1174a847 92 setDefaultSort,
f05a1c30 93 setDefaultPagination,
0883b324 94 optionalAuthenticate,
eb080476 95 asyncMiddleware(listVideos)
fbf1134e 96)
f3aaa9a9
C
97videosRouter.get('/search',
98 videosSearchValidator,
99 paginationValidator,
100 videosSortValidator,
1174a847 101 setDefaultSort,
f05a1c30 102 setDefaultPagination,
0883b324 103 optionalAuthenticate,
f3aaa9a9
C
104 asyncMiddleware(searchVideos)
105)
65fcc311
C
106videosRouter.put('/:id',
107 authenticate,
ac81d1a0 108 reqVideoFileUpdate,
a2431b7d 109 asyncMiddleware(videosUpdateValidator),
90d4bb81 110 asyncRetryTransactionMiddleware(updateVideo)
7b1f49de 111)
e95561cd 112videosRouter.post('/upload',
65fcc311 113 authenticate,
ac81d1a0 114 reqVideoFileAdd,
3fd3ab2d 115 asyncMiddleware(videosAddValidator),
90d4bb81 116 asyncRetryTransactionMiddleware(addVideo)
fbf1134e 117)
9567011b
C
118
119videosRouter.get('/:id/description',
a2431b7d 120 asyncMiddleware(videosGetValidator),
9567011b
C
121 asyncMiddleware(getVideoDescription)
122)
65fcc311 123videosRouter.get('/:id',
a2431b7d 124 asyncMiddleware(videosGetValidator),
68ce3ae0 125 getVideo
fbf1134e 126)
1f3e9fec
C
127videosRouter.post('/:id/views',
128 asyncMiddleware(videosGetValidator),
129 asyncMiddleware(viewVideo)
130)
198b205c 131
65fcc311
C
132videosRouter.delete('/:id',
133 authenticate,
a2431b7d 134 asyncMiddleware(videosRemoveValidator),
90d4bb81 135 asyncRetryTransactionMiddleware(removeVideo)
fbf1134e 136)
198b205c 137
9f10b292 138// ---------------------------------------------------------------------------
c45f7f84 139
65fcc311
C
140export {
141 videosRouter
142}
c45f7f84 143
9f10b292 144// ---------------------------------------------------------------------------
c45f7f84 145
556ddc31 146function listVideoCategories (req: express.Request, res: express.Response) {
65fcc311 147 res.json(VIDEO_CATEGORIES)
6e07c3de
C
148}
149
556ddc31 150function listVideoLicences (req: express.Request, res: express.Response) {
65fcc311 151 res.json(VIDEO_LICENCES)
6f0c39e2
C
152}
153
556ddc31 154function listVideoLanguages (req: express.Request, res: express.Response) {
65fcc311 155 res.json(VIDEO_LANGUAGES)
3092476e
C
156}
157
fd45e8f4
C
158function listVideoPrivacies (req: express.Request, res: express.Response) {
159 res.json(VIDEO_PRIVACIES)
160}
161
90d4bb81
C
162async function addVideo (req: express.Request, res: express.Response) {
163 const videoPhysicalFile = req.files['videofile'][0]
556ddc31 164 const videoInfo: VideoCreate = req.body
9f10b292 165
e11f68a3
C
166 // Prepare data so we don't block the transaction
167 const videoData = {
168 name: videoInfo.name,
169 remote: false,
170 extname: extname(videoPhysicalFile.filename),
171 category: videoInfo.category,
172 licence: videoInfo.licence,
173 language: videoInfo.language,
2186386c
C
174 commentsEnabled: videoInfo.commentsEnabled || false,
175 waitTranscoding: videoInfo.waitTranscoding || false,
176 state: CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED,
177 nsfw: videoInfo.nsfw || false,
e11f68a3 178 description: videoInfo.description,
2422c46b 179 support: videoInfo.support,
e11f68a3
C
180 privacy: videoInfo.privacy,
181 duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
182 channelId: res.locals.videoChannel.id
183 }
3fd3ab2d 184 const video = new VideoModel(videoData)
2186386c 185 video.url = getVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
eb080476 186
2186386c 187 // Build the file object
056aa7f2 188 const { videoFileResolution } = await getVideoFileResolution(videoPhysicalFile.path)
3a6f351b
C
189 const fps = await getVideoFileFPS(videoPhysicalFile.path)
190
e11f68a3
C
191 const videoFileData = {
192 extname: extname(videoPhysicalFile.filename),
056aa7f2 193 resolution: videoFileResolution,
3a6f351b
C
194 size: videoPhysicalFile.size,
195 fps
e11f68a3 196 }
3fd3ab2d 197 const videoFile = new VideoFileModel(videoFileData)
2186386c
C
198
199 // Move physical file
e11f68a3 200 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
e11f68a3 201 const destination = join(videoDir, video.getVideoFilename(videoFile))
ac81d1a0 202 await renamePromise(videoPhysicalFile.path, destination)
e3a682a8
C
203 // This is important in case if there is another attempt in the retry process
204 videoPhysicalFile.filename = video.getVideoFilename(videoFile)
82815eb6 205 videoPhysicalFile.path = destination
ac81d1a0
C
206
207 // Process thumbnail or create it from the video
208 const thumbnailField = req.files['thumbnailfile']
209 if (thumbnailField) {
210 const thumbnailPhysicalFile = thumbnailField[0]
211 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName()), THUMBNAILS_SIZE)
212 } else {
213 await video.createThumbnail(videoFile)
214 }
93e1258c 215
ac81d1a0
C
216 // Process preview or create it from the video
217 const previewField = req.files['previewfile']
218 if (previewField) {
219 const previewPhysicalFile = previewField[0]
220 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName()), PREVIEWS_SIZE)
221 } else {
222 await video.createPreview(videoFile)
223 }
eb080476 224
2186386c 225 // Create the torrent file
ac81d1a0 226 await video.createTorrentAndSetInfoHash(videoFile)
eb080476 227
94a5ff8a 228 const videoCreated = await sequelizeTypescript.transaction(async t => {
e11f68a3 229 const sequelizeOptions = { transaction: t }
eb080476 230
eb080476
C
231 const videoCreated = await video.save(sequelizeOptions)
232 // Do not forget to add video channel information to the created video
233 videoCreated.VideoChannel = res.locals.videoChannel
7920c273 234
eb080476 235 videoFile.videoId = video.id
eb080476 236 await videoFile.save(sequelizeOptions)
e11f68a3
C
237
238 video.VideoFiles = [ videoFile ]
93e1258c 239
2baea0c7 240 // Create tags
2efd32f6 241 if (videoInfo.tags !== undefined) {
3fd3ab2d 242 const tagInstances = await TagModel.findOrCreateTags(videoInfo.tags, t)
eb080476 243
3fd3ab2d 244 await video.$set('Tags', tagInstances, sequelizeOptions)
eb080476
C
245 video.Tags = tagInstances
246 }
247
2baea0c7
C
248 // Schedule an update in the future?
249 if (videoInfo.scheduleUpdate) {
250 await ScheduleVideoUpdateModel.create({
251 videoId: video.id,
252 updateAt: videoInfo.scheduleUpdate.updateAt,
253 privacy: videoInfo.scheduleUpdate.privacy || null
254 }, { transaction: t })
255 }
256
2186386c 257 await federateVideoIfNeeded(video, true, t)
eb080476 258
cadb46d8
C
259 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
260
261 return videoCreated
262 })
94a5ff8a 263
2186386c 264 if (video.state === VideoState.TO_TRANSCODE) {
94a5ff8a
C
265 // Put uuid because we don't have id auto incremented for now
266 const dataInput = {
0c948c16
C
267 videoUUID: videoCreated.uuid,
268 isNewVideo: true
94a5ff8a
C
269 }
270
271 await JobQueue.Instance.createJob({ type: 'video-file', payload: dataInput })
272 }
273
90d4bb81
C
274 return res.json({
275 video: {
276 id: videoCreated.id,
277 uuid: videoCreated.uuid
278 }
279 }).end()
ed04d94f
C
280}
281
eb080476 282async function updateVideo (req: express.Request, res: express.Response) {
3fd3ab2d 283 const videoInstance: VideoModel = res.locals.video
7f4e7c36 284 const videoFieldsSave = videoInstance.toJSON()
556ddc31 285 const videoInfoToUpdate: VideoUpdate = req.body
fd45e8f4 286 const wasPrivateVideo = videoInstance.privacy === VideoPrivacy.PRIVATE
7b1f49de 287
ac81d1a0
C
288 // Process thumbnail or create it from the video
289 if (req.files && req.files['thumbnailfile']) {
290 const thumbnailPhysicalFile = req.files['thumbnailfile'][0]
291 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, videoInstance.getThumbnailName()), THUMBNAILS_SIZE)
292 }
293
294 // Process preview or create it from the video
295 if (req.files && req.files['previewfile']) {
296 const previewPhysicalFile = req.files['previewfile'][0]
297 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, videoInstance.getPreviewName()), PREVIEWS_SIZE)
298 }
299
eb080476 300 try {
3fd3ab2d 301 await sequelizeTypescript.transaction(async t => {
eb080476
C
302 const sequelizeOptions = {
303 transaction: t
304 }
0f320037 305 const oldVideoChannel = videoInstance.VideoChannel
7b1f49de 306
eb080476
C
307 if (videoInfoToUpdate.name !== undefined) videoInstance.set('name', videoInfoToUpdate.name)
308 if (videoInfoToUpdate.category !== undefined) videoInstance.set('category', videoInfoToUpdate.category)
309 if (videoInfoToUpdate.licence !== undefined) videoInstance.set('licence', videoInfoToUpdate.licence)
310 if (videoInfoToUpdate.language !== undefined) videoInstance.set('language', videoInfoToUpdate.language)
311 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfoToUpdate.nsfw)
2186386c 312 if (videoInfoToUpdate.waitTranscoding !== undefined) videoInstance.set('waitTranscoding', videoInfoToUpdate.waitTranscoding)
2422c46b 313 if (videoInfoToUpdate.support !== undefined) videoInstance.set('support', videoInfoToUpdate.support)
eb080476 314 if (videoInfoToUpdate.description !== undefined) videoInstance.set('description', videoInfoToUpdate.description)
47564bbe 315 if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.set('commentsEnabled', videoInfoToUpdate.commentsEnabled)
2922e048
JLB
316 if (videoInfoToUpdate.privacy !== undefined) {
317 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
318 videoInstance.set('privacy', newPrivacy)
319
320 if (wasPrivateVideo === true && newPrivacy !== VideoPrivacy.PRIVATE) {
321 videoInstance.set('publishedAt', new Date())
322 }
323 }
7b1f49de 324
54141398 325 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions)
7b1f49de 326
0f320037 327 // Video tags update?
2efd32f6 328 if (videoInfoToUpdate.tags !== undefined) {
3fd3ab2d 329 const tagInstances = await TagModel.findOrCreateTags(videoInfoToUpdate.tags, t)
7b1f49de 330
0f320037
C
331 await videoInstanceUpdated.$set('Tags', tagInstances, sequelizeOptions)
332 videoInstanceUpdated.Tags = tagInstances
eb080476 333 }
7920c273 334
0f320037
C
335 // Video channel update?
336 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
6200d8d9 337 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
2186386c 338 videoInstanceUpdated.VideoChannel = res.locals.videoChannel
0f320037
C
339
340 if (wasPrivateVideo === false) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
fd45e8f4
C
341 }
342
2baea0c7
C
343 // Schedule an update in the future?
344 if (videoInfoToUpdate.scheduleUpdate) {
345 await ScheduleVideoUpdateModel.upsert({
346 videoId: videoInstanceUpdated.id,
347 updateAt: videoInfoToUpdate.scheduleUpdate.updateAt,
348 privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
349 }, { transaction: t })
e94fc297
C
350 } else if (videoInfoToUpdate.scheduleUpdate === null) {
351 await ScheduleVideoUpdateModel.deleteByVideoId(videoInstanceUpdated.id, t)
2baea0c7
C
352 }
353
2186386c 354 const isNewVideo = wasPrivateVideo && videoInstanceUpdated.privacy !== VideoPrivacy.PRIVATE
e94fc297 355 await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t)
eb080476 356 })
6fcd19ba 357
eb080476
C
358 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
359 } catch (err) {
6fcd19ba
C
360 // Force fields we want to update
361 // If the transaction is retried, sequelize will think the object has not changed
362 // So it will skip the SQL request, even if the last one was ROLLBACKed!
eb080476 363 resetSequelizeInstance(videoInstance, videoFieldsSave)
6fcd19ba
C
364
365 throw err
eb080476 366 }
90d4bb81
C
367
368 return res.type('json').status(204).end()
9f10b292 369}
8c308c2b 370
1f3e9fec
C
371function getVideo (req: express.Request, res: express.Response) {
372 const videoInstance = res.locals.video
373
374 return res.json(videoInstance.toFormattedDetailsJSON())
375}
376
377async function viewVideo (req: express.Request, res: express.Response) {
818f7987 378 const videoInstance = res.locals.video
9e167724 379
490b595a 380 const ip = req.ip
b5c0e955
C
381 const exists = await Redis.Instance.isViewExists(ip, videoInstance.uuid)
382 if (exists) {
383 logger.debug('View for ip %s and video %s already exists.', ip, videoInstance.uuid)
384 return res.status(204).end()
385 }
386
1f3e9fec 387 await videoInstance.increment('views')
b5c0e955
C
388 await Redis.Instance.setView(ip, videoInstance.uuid)
389
50d6de9c 390 const serverAccount = await getServerActor()
40ff5707 391
07197db4 392 await sendCreateView(serverAccount, videoInstance, undefined)
9e167724 393
1f3e9fec 394 return res.status(204).end()
9f10b292 395}
8c308c2b 396
9567011b
C
397async function getVideoDescription (req: express.Request, res: express.Response) {
398 const videoInstance = res.locals.video
399 let description = ''
400
401 if (videoInstance.isOwned()) {
402 description = videoInstance.description
403 } else {
571389d4 404 description = await fetchRemoteVideoDescription(videoInstance)
9567011b
C
405 }
406
407 return res.json({ description })
408}
409
eb080476 410async function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
48dce1c9
C
411 const resultList = await VideoModel.listForApi({
412 start: req.query.start,
413 count: req.query.count,
414 sort: req.query.sort,
61b909b9 415 category: req.query.category,
48dce1c9
C
416 hideNSFW: isNSFWHidden(res),
417 filter: req.query.filter as VideoFilter,
418 withFiles: false
419 })
eb080476
C
420
421 return res.json(getFormattedObjects(resultList.data, resultList.total))
9f10b292 422}
c45f7f84 423
eb080476 424async function removeVideo (req: express.Request, res: express.Response) {
3fd3ab2d 425 const videoInstance: VideoModel = res.locals.video
91f6f169 426
3fd3ab2d 427 await sequelizeTypescript.transaction(async t => {
eb080476 428 await videoInstance.destroy({ transaction: t })
91f6f169 429 })
eb080476
C
430
431 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
90d4bb81
C
432
433 return res.type('json').status(204).end()
9f10b292 434}
8c308c2b 435
eb080476 436async function searchVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
66dc5907 437 const resultList = await VideoModel.searchAndPopulateAccountAndServer(
0883b324
C
438 req.query.search as string,
439 req.query.start as number,
440 req.query.count as number,
441 req.query.sort as VideoSortField,
442 isNSFWHidden(res)
eb080476
C
443 )
444
445 return res.json(getFormattedObjects(resultList.data, resultList.total))
9f10b292 446}