]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/videos/index.ts
Refractor retry transaction function
[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'
65fcc311
C
55
56const videosRouter = express.Router()
9f10b292 57
ac81d1a0
C
58const reqVideoFileAdd = createReqFiles(
59 [ 'videofile', 'thumbnailfile', 'previewfile' ],
60 Object.assign({}, VIDEO_MIMETYPE_EXT, IMAGE_MIMETYPE_EXT),
61 {
62 videofile: CONFIG.STORAGE.VIDEOS_DIR,
63 thumbnailfile: CONFIG.STORAGE.THUMBNAILS_DIR,
64 previewfile: CONFIG.STORAGE.PREVIEWS_DIR
65 }
66)
67const reqVideoFileUpdate = createReqFiles(
68 [ 'thumbnailfile', 'previewfile' ],
69 IMAGE_MIMETYPE_EXT,
70 {
71 thumbnailfile: CONFIG.STORAGE.THUMBNAILS_DIR,
72 previewfile: CONFIG.STORAGE.PREVIEWS_DIR
73 }
74)
8c308c2b 75
65fcc311
C
76videosRouter.use('/', abuseVideoRouter)
77videosRouter.use('/', blacklistRouter)
78videosRouter.use('/', rateVideoRouter)
bf1f6508 79videosRouter.use('/', videoCommentRouter)
d33242b0 80
65fcc311
C
81videosRouter.get('/categories', listVideoCategories)
82videosRouter.get('/licences', listVideoLicences)
83videosRouter.get('/languages', listVideoLanguages)
fd45e8f4 84videosRouter.get('/privacies', listVideoPrivacies)
6e07c3de 85
65fcc311
C
86videosRouter.get('/',
87 paginationValidator,
88 videosSortValidator,
1174a847 89 setDefaultSort,
f05a1c30 90 setDefaultPagination,
0883b324 91 optionalAuthenticate,
eb080476 92 asyncMiddleware(listVideos)
fbf1134e 93)
f3aaa9a9
C
94videosRouter.get('/search',
95 videosSearchValidator,
96 paginationValidator,
97 videosSortValidator,
1174a847 98 setDefaultSort,
f05a1c30 99 setDefaultPagination,
0883b324 100 optionalAuthenticate,
f3aaa9a9
C
101 asyncMiddleware(searchVideos)
102)
65fcc311
C
103videosRouter.put('/:id',
104 authenticate,
ac81d1a0 105 reqVideoFileUpdate,
a2431b7d 106 asyncMiddleware(videosUpdateValidator),
90d4bb81 107 asyncRetryTransactionMiddleware(updateVideo)
7b1f49de 108)
e95561cd 109videosRouter.post('/upload',
65fcc311 110 authenticate,
ac81d1a0 111 reqVideoFileAdd,
3fd3ab2d 112 asyncMiddleware(videosAddValidator),
90d4bb81 113 asyncRetryTransactionMiddleware(addVideo)
fbf1134e 114)
9567011b
C
115
116videosRouter.get('/:id/description',
a2431b7d 117 asyncMiddleware(videosGetValidator),
9567011b
C
118 asyncMiddleware(getVideoDescription)
119)
65fcc311 120videosRouter.get('/:id',
a2431b7d 121 asyncMiddleware(videosGetValidator),
68ce3ae0 122 getVideo
fbf1134e 123)
1f3e9fec
C
124videosRouter.post('/:id/views',
125 asyncMiddleware(videosGetValidator),
126 asyncMiddleware(viewVideo)
127)
198b205c 128
65fcc311
C
129videosRouter.delete('/:id',
130 authenticate,
a2431b7d 131 asyncMiddleware(videosRemoveValidator),
90d4bb81 132 asyncRetryTransactionMiddleware(removeVideo)
fbf1134e 133)
198b205c 134
9f10b292 135// ---------------------------------------------------------------------------
c45f7f84 136
65fcc311
C
137export {
138 videosRouter
139}
c45f7f84 140
9f10b292 141// ---------------------------------------------------------------------------
c45f7f84 142
556ddc31 143function listVideoCategories (req: express.Request, res: express.Response) {
65fcc311 144 res.json(VIDEO_CATEGORIES)
6e07c3de
C
145}
146
556ddc31 147function listVideoLicences (req: express.Request, res: express.Response) {
65fcc311 148 res.json(VIDEO_LICENCES)
6f0c39e2
C
149}
150
556ddc31 151function listVideoLanguages (req: express.Request, res: express.Response) {
65fcc311 152 res.json(VIDEO_LANGUAGES)
3092476e
C
153}
154
fd45e8f4
C
155function listVideoPrivacies (req: express.Request, res: express.Response) {
156 res.json(VIDEO_PRIVACIES)
157}
158
90d4bb81
C
159async function addVideo (req: express.Request, res: express.Response) {
160 const videoPhysicalFile = req.files['videofile'][0]
556ddc31 161 const videoInfo: VideoCreate = req.body
9f10b292 162
e11f68a3
C
163 // Prepare data so we don't block the transaction
164 const videoData = {
165 name: videoInfo.name,
166 remote: false,
167 extname: extname(videoPhysicalFile.filename),
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)
e11f68a3
C
186 const videoFileData = {
187 extname: extname(videoPhysicalFile.filename),
056aa7f2 188 resolution: videoFileResolution,
e11f68a3
C
189 size: videoPhysicalFile.size
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
2efd32f6 234 if (videoInfo.tags !== undefined) {
3fd3ab2d 235 const tagInstances = await TagModel.findOrCreateTags(videoInfo.tags, t)
eb080476 236
3fd3ab2d 237 await video.$set('Tags', tagInstances, sequelizeOptions)
eb080476
C
238 video.Tags = tagInstances
239 }
240
2186386c 241 await federateVideoIfNeeded(video, true, t)
eb080476 242
cadb46d8
C
243 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
244
245 return videoCreated
246 })
94a5ff8a 247
2186386c 248 if (video.state === VideoState.TO_TRANSCODE) {
94a5ff8a
C
249 // Put uuid because we don't have id auto incremented for now
250 const dataInput = {
0c948c16
C
251 videoUUID: videoCreated.uuid,
252 isNewVideo: true
94a5ff8a
C
253 }
254
255 await JobQueue.Instance.createJob({ type: 'video-file', payload: dataInput })
256 }
257
90d4bb81
C
258 return res.json({
259 video: {
260 id: videoCreated.id,
261 uuid: videoCreated.uuid
262 }
263 }).end()
ed04d94f
C
264}
265
eb080476 266async function updateVideo (req: express.Request, res: express.Response) {
3fd3ab2d 267 const videoInstance: VideoModel = res.locals.video
7f4e7c36 268 const videoFieldsSave = videoInstance.toJSON()
556ddc31 269 const videoInfoToUpdate: VideoUpdate = req.body
fd45e8f4 270 const wasPrivateVideo = videoInstance.privacy === VideoPrivacy.PRIVATE
7b1f49de 271
ac81d1a0
C
272 // Process thumbnail or create it from the video
273 if (req.files && req.files['thumbnailfile']) {
274 const thumbnailPhysicalFile = req.files['thumbnailfile'][0]
275 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, videoInstance.getThumbnailName()), THUMBNAILS_SIZE)
276 }
277
278 // Process preview or create it from the video
279 if (req.files && req.files['previewfile']) {
280 const previewPhysicalFile = req.files['previewfile'][0]
281 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, videoInstance.getPreviewName()), PREVIEWS_SIZE)
282 }
283
eb080476 284 try {
3fd3ab2d 285 await sequelizeTypescript.transaction(async t => {
eb080476
C
286 const sequelizeOptions = {
287 transaction: t
288 }
0f320037 289 const oldVideoChannel = videoInstance.VideoChannel
7b1f49de 290
eb080476
C
291 if (videoInfoToUpdate.name !== undefined) videoInstance.set('name', videoInfoToUpdate.name)
292 if (videoInfoToUpdate.category !== undefined) videoInstance.set('category', videoInfoToUpdate.category)
293 if (videoInfoToUpdate.licence !== undefined) videoInstance.set('licence', videoInfoToUpdate.licence)
294 if (videoInfoToUpdate.language !== undefined) videoInstance.set('language', videoInfoToUpdate.language)
295 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfoToUpdate.nsfw)
2186386c 296 if (videoInfoToUpdate.waitTranscoding !== undefined) videoInstance.set('waitTranscoding', videoInfoToUpdate.waitTranscoding)
2422c46b 297 if (videoInfoToUpdate.support !== undefined) videoInstance.set('support', videoInfoToUpdate.support)
eb080476 298 if (videoInfoToUpdate.description !== undefined) videoInstance.set('description', videoInfoToUpdate.description)
47564bbe 299 if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.set('commentsEnabled', videoInfoToUpdate.commentsEnabled)
2922e048
JLB
300 if (videoInfoToUpdate.privacy !== undefined) {
301 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
302 videoInstance.set('privacy', newPrivacy)
303
304 if (wasPrivateVideo === true && newPrivacy !== VideoPrivacy.PRIVATE) {
305 videoInstance.set('publishedAt', new Date())
306 }
307 }
7b1f49de 308
54141398 309 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions)
7b1f49de 310
0f320037 311 // Video tags update?
2efd32f6 312 if (videoInfoToUpdate.tags !== undefined) {
3fd3ab2d 313 const tagInstances = await TagModel.findOrCreateTags(videoInfoToUpdate.tags, t)
7b1f49de 314
0f320037
C
315 await videoInstanceUpdated.$set('Tags', tagInstances, sequelizeOptions)
316 videoInstanceUpdated.Tags = tagInstances
eb080476 317 }
7920c273 318
0f320037
C
319 // Video channel update?
320 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
6200d8d9 321 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
2186386c 322 videoInstanceUpdated.VideoChannel = res.locals.videoChannel
0f320037
C
323
324 if (wasPrivateVideo === false) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
fd45e8f4
C
325 }
326
2186386c
C
327 const isNewVideo = wasPrivateVideo && videoInstanceUpdated.privacy !== VideoPrivacy.PRIVATE
328 await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo)
eb080476 329 })
6fcd19ba 330
eb080476
C
331 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
332 } catch (err) {
6fcd19ba
C
333 // Force fields we want to update
334 // If the transaction is retried, sequelize will think the object has not changed
335 // So it will skip the SQL request, even if the last one was ROLLBACKed!
eb080476 336 resetSequelizeInstance(videoInstance, videoFieldsSave)
6fcd19ba
C
337
338 throw err
eb080476 339 }
90d4bb81
C
340
341 return res.type('json').status(204).end()
9f10b292 342}
8c308c2b 343
1f3e9fec
C
344function getVideo (req: express.Request, res: express.Response) {
345 const videoInstance = res.locals.video
346
347 return res.json(videoInstance.toFormattedDetailsJSON())
348}
349
350async function viewVideo (req: express.Request, res: express.Response) {
818f7987 351 const videoInstance = res.locals.video
9e167724 352
490b595a 353 const ip = req.ip
b5c0e955
C
354 const exists = await Redis.Instance.isViewExists(ip, videoInstance.uuid)
355 if (exists) {
356 logger.debug('View for ip %s and video %s already exists.', ip, videoInstance.uuid)
357 return res.status(204).end()
358 }
359
1f3e9fec 360 await videoInstance.increment('views')
b5c0e955
C
361 await Redis.Instance.setView(ip, videoInstance.uuid)
362
50d6de9c 363 const serverAccount = await getServerActor()
40ff5707 364
07197db4 365 await sendCreateView(serverAccount, videoInstance, undefined)
9e167724 366
1f3e9fec 367 return res.status(204).end()
9f10b292 368}
8c308c2b 369
9567011b
C
370async function getVideoDescription (req: express.Request, res: express.Response) {
371 const videoInstance = res.locals.video
372 let description = ''
373
374 if (videoInstance.isOwned()) {
375 description = videoInstance.description
376 } else {
571389d4 377 description = await fetchRemoteVideoDescription(videoInstance)
9567011b
C
378 }
379
380 return res.json({ description })
381}
382
eb080476 383async function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
48dce1c9
C
384 const resultList = await VideoModel.listForApi({
385 start: req.query.start,
386 count: req.query.count,
387 sort: req.query.sort,
388 hideNSFW: isNSFWHidden(res),
389 filter: req.query.filter as VideoFilter,
390 withFiles: false
391 })
eb080476
C
392
393 return res.json(getFormattedObjects(resultList.data, resultList.total))
9f10b292 394}
c45f7f84 395
eb080476 396async function removeVideo (req: express.Request, res: express.Response) {
3fd3ab2d 397 const videoInstance: VideoModel = res.locals.video
91f6f169 398
3fd3ab2d 399 await sequelizeTypescript.transaction(async t => {
eb080476 400 await videoInstance.destroy({ transaction: t })
91f6f169 401 })
eb080476
C
402
403 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
90d4bb81
C
404
405 return res.type('json').status(204).end()
9f10b292 406}
8c308c2b 407
eb080476 408async function searchVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
66dc5907 409 const resultList = await VideoModel.searchAndPopulateAccountAndServer(
0883b324
C
410 req.query.search as string,
411 req.query.start as number,
412 req.query.count as number,
413 req.query.sort as VideoSortField,
414 isNSFWHidden(res)
eb080476
C
415 )
416
417 return res.json(getFormattedObjects(resultList.data, resultList.total))
9f10b292 418}