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