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