]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/videos/index.ts
Put activity pub sends inside transactions
[github/Chocobozzz/PeerTube.git] / server / controllers / api / videos / index.ts
CommitLineData
4d4e5cd4 1import * as express from 'express'
4d4e5cd4 2import * as multer from 'multer'
93e1258c 3import { extname, join } from 'path'
571389d4 4import { VideoCreate, VideoPrivacy, VideoUpdate } from '../../../../shared'
65fcc311 5import {
571389d4
C
6 generateRandomString,
7 getFormattedObjects,
8 getVideoFileHeight,
9 logger,
10 renamePromise,
11 resetSequelizeInstance,
12 retryTransactionWrapper
13} from '../../../helpers'
40ff5707 14import { getServerAccount } from '../../../helpers/utils'
571389d4
C
15import { CONFIG, VIDEO_CATEGORIES, VIDEO_LANGUAGES, VIDEO_LICENCES, VIDEO_MIMETYPE_EXT, VIDEO_PRIVACIES } from '../../../initializers'
16import { database as db } from '../../../initializers/database'
54141398
C
17import { sendAddVideo } from '../../../lib/activitypub/send/send-add'
18import { sendUpdateVideo } from '../../../lib/activitypub/send/send-update'
40ff5707
C
19import { shareVideoByServer } from '../../../lib/activitypub/share'
20import { getVideoActivityPubUrl } from '../../../lib/activitypub/url'
21import { fetchRemoteVideoDescription } from '../../../lib/activitypub/videos'
22import { sendCreateViewToVideoFollowers } from '../../../lib/index'
571389d4 23import { transcodingJobScheduler } from '../../../lib/jobs/transcoding-job-scheduler/transcoding-job-scheduler'
65fcc311 24import {
571389d4 25 asyncMiddleware,
65fcc311
C
26 authenticate,
27 paginationValidator,
65fcc311
C
28 setPagination,
29 setVideosSearch,
571389d4 30 setVideosSort,
65fcc311
C
31 videosAddValidator,
32 videosGetValidator,
eb080476 33 videosRemoveValidator,
571389d4
C
34 videosSearchValidator,
35 videosSortValidator,
36 videosUpdateValidator
65fcc311 37} from '../../../middlewares'
d412e80e 38import { VideoInstance } from '../../../models'
65fcc311
C
39import { abuseVideoRouter } from './abuse'
40import { blacklistRouter } from './blacklist'
72c7248b 41import { videoChannelRouter } from './channel'
571389d4 42import { rateVideoRouter } from './rate'
40ff5707 43import { sendCreateViewToOrigin } from '../../../lib/activitypub/send/send-create'
65fcc311
C
44
45const videosRouter = express.Router()
9f10b292
C
46
47// multer configuration
f0f5567b 48const storage = multer.diskStorage({
075f16ca 49 destination: (req, file, cb) => {
65fcc311 50 cb(null, CONFIG.STORAGE.VIDEOS_DIR)
9f10b292
C
51 },
52
0d0e8dd0
C
53 filename: async (req, file, cb) => {
54 const extension = VIDEO_MIMETYPE_EXT[file.mimetype]
55 let randomString = ''
56
57 try {
58 randomString = await generateRandomString(16)
59 } catch (err) {
60 logger.error('Cannot generate random string for file name.', err)
61 randomString = 'fake-random-string'
62 }
63
efc32059 64 cb(null, randomString + extension)
9f10b292
C
65 }
66})
67
8c9c1942 68const reqFiles = multer({ storage: storage }).fields([{ name: 'videofile', maxCount: 1 }])
8c308c2b 69
65fcc311
C
70videosRouter.use('/', abuseVideoRouter)
71videosRouter.use('/', blacklistRouter)
72videosRouter.use('/', rateVideoRouter)
72c7248b 73videosRouter.use('/', videoChannelRouter)
d33242b0 74
65fcc311
C
75videosRouter.get('/categories', listVideoCategories)
76videosRouter.get('/licences', listVideoLicences)
77videosRouter.get('/languages', listVideoLanguages)
fd45e8f4 78videosRouter.get('/privacies', listVideoPrivacies)
6e07c3de 79
65fcc311
C
80videosRouter.get('/',
81 paginationValidator,
82 videosSortValidator,
83 setVideosSort,
84 setPagination,
eb080476 85 asyncMiddleware(listVideos)
fbf1134e 86)
65fcc311
C
87videosRouter.put('/:id',
88 authenticate,
a2431b7d 89 asyncMiddleware(videosUpdateValidator),
eb080476 90 asyncMiddleware(updateVideoRetryWrapper)
7b1f49de 91)
e95561cd 92videosRouter.post('/upload',
65fcc311 93 authenticate,
fbf1134e 94 reqFiles,
65fcc311 95 videosAddValidator,
eb080476 96 asyncMiddleware(addVideoRetryWrapper)
fbf1134e 97)
9567011b
C
98
99videosRouter.get('/:id/description',
a2431b7d 100 asyncMiddleware(videosGetValidator),
9567011b
C
101 asyncMiddleware(getVideoDescription)
102)
65fcc311 103videosRouter.get('/:id',
a2431b7d 104 asyncMiddleware(videosGetValidator),
68ce3ae0 105 getVideo
fbf1134e 106)
1f3e9fec
C
107videosRouter.post('/:id/views',
108 asyncMiddleware(videosGetValidator),
109 asyncMiddleware(viewVideo)
110)
198b205c 111
65fcc311
C
112videosRouter.delete('/:id',
113 authenticate,
a2431b7d 114 asyncMiddleware(videosRemoveValidator),
eb080476 115 asyncMiddleware(removeVideoRetryWrapper)
fbf1134e 116)
198b205c 117
65fcc311
C
118videosRouter.get('/search/:value',
119 videosSearchValidator,
120 paginationValidator,
121 videosSortValidator,
122 setVideosSort,
123 setPagination,
124 setVideosSearch,
eb080476 125 asyncMiddleware(searchVideos)
fbf1134e 126)
8c308c2b 127
9f10b292 128// ---------------------------------------------------------------------------
c45f7f84 129
65fcc311
C
130export {
131 videosRouter
132}
c45f7f84 133
9f10b292 134// ---------------------------------------------------------------------------
c45f7f84 135
556ddc31 136function listVideoCategories (req: express.Request, res: express.Response) {
65fcc311 137 res.json(VIDEO_CATEGORIES)
6e07c3de
C
138}
139
556ddc31 140function listVideoLicences (req: express.Request, res: express.Response) {
65fcc311 141 res.json(VIDEO_LICENCES)
6f0c39e2
C
142}
143
556ddc31 144function listVideoLanguages (req: express.Request, res: express.Response) {
65fcc311 145 res.json(VIDEO_LANGUAGES)
3092476e
C
146}
147
fd45e8f4
C
148function listVideoPrivacies (req: express.Request, res: express.Response) {
149 res.json(VIDEO_PRIVACIES)
150}
151
ed04d94f
C
152// Wrapper to video add that retry the function if there is a database error
153// We need this because we run the transaction in SERIALIZABLE isolation that can fail
eb080476 154async function addVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
d6a5b018 155 const options = {
556ddc31 156 arguments: [ req, res, req.files['videofile'][0] ],
d6a5b018
C
157 errorMessage: 'Cannot insert the video with many retries.'
158 }
ed04d94f 159
eb080476
C
160 await retryTransactionWrapper(addVideo, options)
161
162 // TODO : include Location of the new video -> 201
163 res.type('json').status(204).end()
ed04d94f
C
164}
165
eb080476 166async function addVideo (req: express.Request, res: express.Response, videoPhysicalFile: Express.Multer.File) {
556ddc31 167 const videoInfo: VideoCreate = req.body
6d33593a 168 let videoUUID = ''
9f10b292 169
eb080476
C
170 await db.sequelize.transaction(async t => {
171 const sequelizeOptions = { transaction: t }
172
173 const videoData = {
174 name: videoInfo.name,
175 remote: false,
176 extname: extname(videoPhysicalFile.filename),
177 category: videoInfo.category,
178 licence: videoInfo.licence,
179 language: videoInfo.language,
180 nsfw: videoInfo.nsfw,
181 description: videoInfo.description,
fd45e8f4 182 privacy: videoInfo.privacy,
eb080476
C
183 duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
184 channelId: res.locals.videoChannel.id
185 }
186 const video = db.Video.build(videoData)
54141398 187 video.url = getVideoActivityPubUrl(video)
6fcd19ba 188
eb080476
C
189 const videoFilePath = join(CONFIG.STORAGE.VIDEOS_DIR, videoPhysicalFile.filename)
190 const videoFileHeight = await getVideoFileHeight(videoFilePath)
93e1258c 191
eb080476
C
192 const videoFileData = {
193 extname: extname(videoPhysicalFile.filename),
194 resolution: videoFileHeight,
195 size: videoPhysicalFile.size
196 }
197 const videoFile = db.VideoFile.build(videoFileData)
198 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
199 const source = join(videoDir, videoPhysicalFile.filename)
200 const destination = join(videoDir, video.getVideoFilename(videoFile))
201
202 await renamePromise(source, destination)
203 // This is important in case if there is another attempt in the retry process
204 videoPhysicalFile.filename = video.getVideoFilename(videoFile)
205
206 const tasks = []
207
208 tasks.push(
209 video.createTorrentAndSetInfoHash(videoFile),
210 video.createThumbnail(videoFile),
211 video.createPreview(videoFile)
212 )
213
214 if (CONFIG.TRANSCODING.ENABLED === true) {
215 // Put uuid because we don't have id auto incremented for now
216 const dataInput = {
217 videoUUID: video.uuid
218 }
219
220 tasks.push(
571389d4 221 transcodingJobScheduler.createJob(t, 'videoFileOptimizer', dataInput)
eb080476
C
222 )
223 }
224 await Promise.all(tasks)
93e1258c 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
229 videoUUID = videoCreated.uuid
7920c273 230
eb080476 231 videoFile.videoId = video.id
feb4bdfd 232
eb080476
C
233 await videoFile.save(sequelizeOptions)
234 video.VideoFiles = [videoFile]
93e1258c 235
eb080476
C
236 if (videoInfo.tags) {
237 const tagInstances = await db.Tag.findOrCreateTags(videoInfo.tags, t)
238
239 await video.setTags(tagInstances, sequelizeOptions)
240 video.Tags = tagInstances
241 }
242
243 // Let transcoding job send the video to friends because the video file extension might change
244 if (CONFIG.TRANSCODING.ENABLED === true) return undefined
60862425 245 // Don't send video to remote servers, it is private
fd45e8f4 246 if (video.privacy === VideoPrivacy.PRIVATE) return undefined
eb080476 247
571389d4 248 await sendAddVideo(video, t)
efc32059 249 await shareVideoByServer(video, t)
7b1f49de 250 })
eb080476
C
251
252 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoUUID)
7b1f49de
C
253}
254
eb080476 255async function updateVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
d6a5b018
C
256 const options = {
257 arguments: [ req, res ],
258 errorMessage: 'Cannot update the video with many retries.'
259 }
ed04d94f 260
eb080476
C
261 await retryTransactionWrapper(updateVideo, options)
262
263 return res.type('json').status(204).end()
ed04d94f
C
264}
265
eb080476 266async function updateVideo (req: express.Request, res: express.Response) {
efc32059 267 const videoInstance: VideoInstance = 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
eb080476
C
272 try {
273 await db.sequelize.transaction(async t => {
274 const sequelizeOptions = {
275 transaction: t
276 }
7b1f49de 277
eb080476
C
278 if (videoInfoToUpdate.name !== undefined) videoInstance.set('name', videoInfoToUpdate.name)
279 if (videoInfoToUpdate.category !== undefined) videoInstance.set('category', videoInfoToUpdate.category)
280 if (videoInfoToUpdate.licence !== undefined) videoInstance.set('licence', videoInfoToUpdate.licence)
281 if (videoInfoToUpdate.language !== undefined) videoInstance.set('language', videoInfoToUpdate.language)
282 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfoToUpdate.nsfw)
fd45e8f4 283 if (videoInfoToUpdate.privacy !== undefined) videoInstance.set('privacy', videoInfoToUpdate.privacy)
eb080476 284 if (videoInfoToUpdate.description !== undefined) videoInstance.set('description', videoInfoToUpdate.description)
7b1f49de 285
54141398 286 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions)
7b1f49de 287
eb080476
C
288 if (videoInfoToUpdate.tags) {
289 const tagInstances = await db.Tag.findOrCreateTags(videoInfoToUpdate.tags, t)
7b1f49de 290
eb080476
C
291 await videoInstance.setTags(tagInstances, sequelizeOptions)
292 videoInstance.Tags = tagInstances
293 }
7920c273 294
eb080476 295 // Now we'll update the video's meta data to our friends
fd45e8f4 296 if (wasPrivateVideo === false) {
54141398 297 await sendUpdateVideo(videoInstanceUpdated, t)
fd45e8f4
C
298 }
299
60862425 300 // Video is not private anymore, send a create action to remote servers
fd45e8f4 301 if (wasPrivateVideo === true && videoInstance.privacy !== VideoPrivacy.PRIVATE) {
571389d4 302 await sendAddVideo(videoInstance, t)
572f8d3d 303 await shareVideoByServer(videoInstance, t)
fd45e8f4 304 }
eb080476 305 })
6fcd19ba 306
eb080476
C
307 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
308 } catch (err) {
6fcd19ba
C
309 // Force fields we want to update
310 // If the transaction is retried, sequelize will think the object has not changed
311 // So it will skip the SQL request, even if the last one was ROLLBACKed!
eb080476 312 resetSequelizeInstance(videoInstance, videoFieldsSave)
6fcd19ba
C
313
314 throw err
eb080476 315 }
9f10b292 316}
8c308c2b 317
1f3e9fec
C
318function getVideo (req: express.Request, res: express.Response) {
319 const videoInstance = res.locals.video
320
321 return res.json(videoInstance.toFormattedDetailsJSON())
322}
323
324async function viewVideo (req: express.Request, res: express.Response) {
818f7987 325 const videoInstance = res.locals.video
9e167724 326
1f3e9fec
C
327 await videoInstance.increment('views')
328 const serverAccount = await getServerAccount()
40ff5707 329
9e167724 330 if (videoInstance.isOwned()) {
1f3e9fec 331 await sendCreateViewToVideoFollowers(serverAccount, videoInstance, undefined)
e4c87ec2 332 } else {
1f3e9fec 333 await sendCreateViewToOrigin(serverAccount, videoInstance, undefined)
9e167724
C
334 }
335
1f3e9fec 336 return res.status(204).end()
9f10b292 337}
8c308c2b 338
9567011b
C
339async function getVideoDescription (req: express.Request, res: express.Response) {
340 const videoInstance = res.locals.video
341 let description = ''
342
343 if (videoInstance.isOwned()) {
344 description = videoInstance.description
345 } else {
571389d4 346 description = await fetchRemoteVideoDescription(videoInstance)
9567011b
C
347 }
348
349 return res.json({ description })
350}
351
eb080476
C
352async function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
353 const resultList = await db.Video.listForApi(req.query.start, req.query.count, req.query.sort)
354
355 return res.json(getFormattedObjects(resultList.data, resultList.total))
9f10b292 356}
c45f7f84 357
eb080476 358async function removeVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
91f6f169
C
359 const options = {
360 arguments: [ req, res ],
361 errorMessage: 'Cannot remove the video with many retries.'
362 }
8c308c2b 363
eb080476
C
364 await retryTransactionWrapper(removeVideo, options)
365
366 return res.type('json').status(204).end()
91f6f169
C
367}
368
eb080476 369async function removeVideo (req: express.Request, res: express.Response) {
91f6f169
C
370 const videoInstance: VideoInstance = res.locals.video
371
eb080476
C
372 await db.sequelize.transaction(async t => {
373 await videoInstance.destroy({ transaction: t })
91f6f169 374 })
eb080476
C
375
376 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
9f10b292 377}
8c308c2b 378
eb080476 379async function searchVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
60862425 380 const resultList = await db.Video.searchAndPopulateAccountAndServerAndTags(
eb080476
C
381 req.params.value,
382 req.query.field,
383 req.query.start,
384 req.query.count,
385 req.query.sort
386 )
387
388 return res.json(getFormattedObjects(resultList.data, resultList.total))
9f10b292 389}