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