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