]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/videos/index.ts
Add ability for uploaders to schedule video update
[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'
056aa7f2 5import { 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'
65fcc311
C
56
57const videosRouter = express.Router()
9f10b292 58
ac81d1a0
C
59const reqVideoFileAdd = createReqFiles(
60 [ 'videofile', 'thumbnailfile', 'previewfile' ],
61 Object.assign({}, VIDEO_MIMETYPE_EXT, IMAGE_MIMETYPE_EXT),
62 {
63 videofile: CONFIG.STORAGE.VIDEOS_DIR,
64 thumbnailfile: CONFIG.STORAGE.THUMBNAILS_DIR,
65 previewfile: CONFIG.STORAGE.PREVIEWS_DIR
66 }
67)
68const reqVideoFileUpdate = createReqFiles(
69 [ 'thumbnailfile', 'previewfile' ],
70 IMAGE_MIMETYPE_EXT,
71 {
72 thumbnailfile: CONFIG.STORAGE.THUMBNAILS_DIR,
73 previewfile: CONFIG.STORAGE.PREVIEWS_DIR
74 }
75)
8c308c2b 76
65fcc311
C
77videosRouter.use('/', abuseVideoRouter)
78videosRouter.use('/', blacklistRouter)
79videosRouter.use('/', rateVideoRouter)
bf1f6508 80videosRouter.use('/', videoCommentRouter)
d33242b0 81
65fcc311
C
82videosRouter.get('/categories', listVideoCategories)
83videosRouter.get('/licences', listVideoLicences)
84videosRouter.get('/languages', listVideoLanguages)
fd45e8f4 85videosRouter.get('/privacies', listVideoPrivacies)
6e07c3de 86
65fcc311
C
87videosRouter.get('/',
88 paginationValidator,
89 videosSortValidator,
1174a847 90 setDefaultSort,
f05a1c30 91 setDefaultPagination,
0883b324 92 optionalAuthenticate,
eb080476 93 asyncMiddleware(listVideos)
fbf1134e 94)
f3aaa9a9
C
95videosRouter.get('/search',
96 videosSearchValidator,
97 paginationValidator,
98 videosSortValidator,
1174a847 99 setDefaultSort,
f05a1c30 100 setDefaultPagination,
0883b324 101 optionalAuthenticate,
f3aaa9a9
C
102 asyncMiddleware(searchVideos)
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,
168 extname: extname(videoPhysicalFile.filename),
169 category: videoInfo.category,
170 licence: videoInfo.licence,
171 language: videoInfo.language,
2186386c
C
172 commentsEnabled: videoInfo.commentsEnabled || false,
173 waitTranscoding: videoInfo.waitTranscoding || false,
174 state: CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED,
175 nsfw: videoInfo.nsfw || false,
e11f68a3 176 description: videoInfo.description,
2422c46b 177 support: videoInfo.support,
e11f68a3
C
178 privacy: videoInfo.privacy,
179 duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
180 channelId: res.locals.videoChannel.id
181 }
3fd3ab2d 182 const video = new VideoModel(videoData)
2186386c 183 video.url = getVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
eb080476 184
2186386c 185 // Build the file object
056aa7f2 186 const { videoFileResolution } = await getVideoFileResolution(videoPhysicalFile.path)
e11f68a3
C
187 const videoFileData = {
188 extname: extname(videoPhysicalFile.filename),
056aa7f2 189 resolution: videoFileResolution,
e11f68a3
C
190 size: videoPhysicalFile.size
191 }
3fd3ab2d 192 const videoFile = new VideoFileModel(videoFileData)
2186386c
C
193
194 // Move physical file
e11f68a3 195 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
e11f68a3 196 const destination = join(videoDir, video.getVideoFilename(videoFile))
ac81d1a0 197 await renamePromise(videoPhysicalFile.path, destination)
e3a682a8
C
198 // This is important in case if there is another attempt in the retry process
199 videoPhysicalFile.filename = video.getVideoFilename(videoFile)
82815eb6 200 videoPhysicalFile.path = destination
ac81d1a0
C
201
202 // Process thumbnail or create it from the video
203 const thumbnailField = req.files['thumbnailfile']
204 if (thumbnailField) {
205 const thumbnailPhysicalFile = thumbnailField[0]
206 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName()), THUMBNAILS_SIZE)
207 } else {
208 await video.createThumbnail(videoFile)
209 }
93e1258c 210
ac81d1a0
C
211 // Process preview or create it from the video
212 const previewField = req.files['previewfile']
213 if (previewField) {
214 const previewPhysicalFile = previewField[0]
215 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName()), PREVIEWS_SIZE)
216 } else {
217 await video.createPreview(videoFile)
218 }
eb080476 219
2186386c 220 // Create the torrent file
ac81d1a0 221 await video.createTorrentAndSetInfoHash(videoFile)
eb080476 222
94a5ff8a 223 const videoCreated = await sequelizeTypescript.transaction(async t => {
e11f68a3 224 const sequelizeOptions = { transaction: t }
eb080476 225
eb080476
C
226 const videoCreated = await video.save(sequelizeOptions)
227 // Do not forget to add video channel information to the created video
228 videoCreated.VideoChannel = res.locals.videoChannel
7920c273 229
eb080476 230 videoFile.videoId = video.id
eb080476 231 await videoFile.save(sequelizeOptions)
e11f68a3
C
232
233 video.VideoFiles = [ videoFile ]
93e1258c 234
2baea0c7 235 // Create tags
2efd32f6 236 if (videoInfo.tags !== undefined) {
3fd3ab2d 237 const tagInstances = await TagModel.findOrCreateTags(videoInfo.tags, t)
eb080476 238
3fd3ab2d 239 await video.$set('Tags', tagInstances, sequelizeOptions)
eb080476
C
240 video.Tags = tagInstances
241 }
242
2baea0c7
C
243 // Schedule an update in the future?
244 if (videoInfo.scheduleUpdate) {
245 await ScheduleVideoUpdateModel.create({
246 videoId: video.id,
247 updateAt: videoInfo.scheduleUpdate.updateAt,
248 privacy: videoInfo.scheduleUpdate.privacy || null
249 }, { transaction: t })
250 }
251
2186386c 252 await federateVideoIfNeeded(video, true, t)
eb080476 253
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()
556ddc31 280 const videoInfoToUpdate: VideoUpdate = req.body
fd45e8f4 281 const wasPrivateVideo = videoInstance.privacy === VideoPrivacy.PRIVATE
7b1f49de 282
ac81d1a0
C
283 // Process thumbnail or create it from the video
284 if (req.files && req.files['thumbnailfile']) {
285 const thumbnailPhysicalFile = req.files['thumbnailfile'][0]
286 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, videoInstance.getThumbnailName()), THUMBNAILS_SIZE)
287 }
288
289 // Process preview or create it from the video
290 if (req.files && req.files['previewfile']) {
291 const previewPhysicalFile = req.files['previewfile'][0]
292 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, videoInstance.getPreviewName()), PREVIEWS_SIZE)
293 }
294
eb080476 295 try {
3fd3ab2d 296 await sequelizeTypescript.transaction(async t => {
eb080476
C
297 const sequelizeOptions = {
298 transaction: t
299 }
0f320037 300 const oldVideoChannel = videoInstance.VideoChannel
7b1f49de 301
eb080476
C
302 if (videoInfoToUpdate.name !== undefined) videoInstance.set('name', videoInfoToUpdate.name)
303 if (videoInfoToUpdate.category !== undefined) videoInstance.set('category', videoInfoToUpdate.category)
304 if (videoInfoToUpdate.licence !== undefined) videoInstance.set('licence', videoInfoToUpdate.licence)
305 if (videoInfoToUpdate.language !== undefined) videoInstance.set('language', videoInfoToUpdate.language)
306 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfoToUpdate.nsfw)
2186386c 307 if (videoInfoToUpdate.waitTranscoding !== undefined) videoInstance.set('waitTranscoding', videoInfoToUpdate.waitTranscoding)
2422c46b 308 if (videoInfoToUpdate.support !== undefined) videoInstance.set('support', videoInfoToUpdate.support)
eb080476 309 if (videoInfoToUpdate.description !== undefined) videoInstance.set('description', videoInfoToUpdate.description)
47564bbe 310 if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.set('commentsEnabled', videoInfoToUpdate.commentsEnabled)
2922e048
JLB
311 if (videoInfoToUpdate.privacy !== undefined) {
312 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
313 videoInstance.set('privacy', newPrivacy)
314
315 if (wasPrivateVideo === true && newPrivacy !== VideoPrivacy.PRIVATE) {
316 videoInstance.set('publishedAt', new Date())
317 }
318 }
7b1f49de 319
54141398 320 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions)
7b1f49de 321
0f320037 322 // Video tags update?
2efd32f6 323 if (videoInfoToUpdate.tags !== undefined) {
3fd3ab2d 324 const tagInstances = await TagModel.findOrCreateTags(videoInfoToUpdate.tags, t)
7b1f49de 325
0f320037
C
326 await videoInstanceUpdated.$set('Tags', tagInstances, sequelizeOptions)
327 videoInstanceUpdated.Tags = tagInstances
eb080476 328 }
7920c273 329
0f320037
C
330 // Video channel update?
331 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
6200d8d9 332 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
2186386c 333 videoInstanceUpdated.VideoChannel = res.locals.videoChannel
0f320037
C
334
335 if (wasPrivateVideo === false) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
fd45e8f4
C
336 }
337
2baea0c7
C
338 // Schedule an update in the future?
339 if (videoInfoToUpdate.scheduleUpdate) {
340 await ScheduleVideoUpdateModel.upsert({
341 videoId: videoInstanceUpdated.id,
342 updateAt: videoInfoToUpdate.scheduleUpdate.updateAt,
343 privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
344 }, { transaction: t })
345 }
346
2186386c
C
347 const isNewVideo = wasPrivateVideo && videoInstanceUpdated.privacy !== VideoPrivacy.PRIVATE
348 await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo)
eb080476 349 })
6fcd19ba 350
eb080476
C
351 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
352 } catch (err) {
6fcd19ba
C
353 // Force fields we want to update
354 // If the transaction is retried, sequelize will think the object has not changed
355 // So it will skip the SQL request, even if the last one was ROLLBACKed!
eb080476 356 resetSequelizeInstance(videoInstance, videoFieldsSave)
6fcd19ba
C
357
358 throw err
eb080476 359 }
90d4bb81
C
360
361 return res.type('json').status(204).end()
9f10b292 362}
8c308c2b 363
1f3e9fec
C
364function getVideo (req: express.Request, res: express.Response) {
365 const videoInstance = res.locals.video
366
367 return res.json(videoInstance.toFormattedDetailsJSON())
368}
369
370async function viewVideo (req: express.Request, res: express.Response) {
818f7987 371 const videoInstance = res.locals.video
9e167724 372
490b595a 373 const ip = req.ip
b5c0e955
C
374 const exists = await Redis.Instance.isViewExists(ip, videoInstance.uuid)
375 if (exists) {
376 logger.debug('View for ip %s and video %s already exists.', ip, videoInstance.uuid)
377 return res.status(204).end()
378 }
379
1f3e9fec 380 await videoInstance.increment('views')
b5c0e955
C
381 await Redis.Instance.setView(ip, videoInstance.uuid)
382
50d6de9c 383 const serverAccount = await getServerActor()
40ff5707 384
07197db4 385 await sendCreateView(serverAccount, videoInstance, undefined)
9e167724 386
1f3e9fec 387 return res.status(204).end()
9f10b292 388}
8c308c2b 389
9567011b
C
390async function getVideoDescription (req: express.Request, res: express.Response) {
391 const videoInstance = res.locals.video
392 let description = ''
393
394 if (videoInstance.isOwned()) {
395 description = videoInstance.description
396 } else {
571389d4 397 description = await fetchRemoteVideoDescription(videoInstance)
9567011b
C
398 }
399
400 return res.json({ description })
401}
402
eb080476 403async function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
48dce1c9
C
404 const resultList = await VideoModel.listForApi({
405 start: req.query.start,
406 count: req.query.count,
407 sort: req.query.sort,
408 hideNSFW: isNSFWHidden(res),
409 filter: req.query.filter as VideoFilter,
410 withFiles: false
411 })
eb080476
C
412
413 return res.json(getFormattedObjects(resultList.data, resultList.total))
9f10b292 414}
c45f7f84 415
eb080476 416async function removeVideo (req: express.Request, res: express.Response) {
3fd3ab2d 417 const videoInstance: VideoModel = res.locals.video
91f6f169 418
3fd3ab2d 419 await sequelizeTypescript.transaction(async t => {
eb080476 420 await videoInstance.destroy({ transaction: t })
91f6f169 421 })
eb080476
C
422
423 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
90d4bb81
C
424
425 return res.type('json').status(204).end()
9f10b292 426}
8c308c2b 427
eb080476 428async function searchVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
66dc5907 429 const resultList = await VideoModel.searchAndPopulateAccountAndServer(
0883b324
C
430 req.query.search as string,
431 req.query.start as number,
432 req.query.count as number,
433 req.query.sort as VideoSortField,
434 isNSFWHidden(res)
eb080476
C
435 )
436
437 return res.json(getFormattedObjects(resultList.data, resultList.total))
9f10b292 438}