]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - server/controllers/api/videos/index.ts
Add blacklist reason field
[github/Chocobozzz/PeerTube.git] / server / controllers / api / videos / index.ts
... / ...
CommitLineData
1import * as express from 'express'
2import { extname, join } from 'path'
3import { VideoCreate, VideoPrivacy, VideoState, VideoUpdate } from '../../../../shared'
4import { renamePromise } from '../../../helpers/core-utils'
5import { getVideoFileFPS, getVideoFileResolution } from '../../../helpers/ffmpeg-utils'
6import { processImage } from '../../../helpers/image-utils'
7import { logger } from '../../../helpers/logger'
8import { auditLoggerFactory, VideoAuditView } from '../../../helpers/audit-logger'
9import { getFormattedObjects, getServerActor, resetSequelizeInstance } from '../../../helpers/utils'
10import {
11 CONFIG,
12 IMAGE_MIMETYPE_EXT,
13 PREVIEWS_SIZE,
14 sequelizeTypescript,
15 THUMBNAILS_SIZE,
16 VIDEO_CATEGORIES,
17 VIDEO_LANGUAGES,
18 VIDEO_LICENCES,
19 VIDEO_MIMETYPE_EXT,
20 VIDEO_PRIVACIES
21} from '../../../initializers'
22import {
23 changeVideoChannelShare,
24 federateVideoIfNeeded,
25 fetchRemoteVideoDescription,
26 getVideoActivityPubUrl
27} from '../../../lib/activitypub'
28import { sendCreateView } from '../../../lib/activitypub/send'
29import { JobQueue } from '../../../lib/job-queue'
30import { Redis } from '../../../lib/redis'
31import {
32 asyncMiddleware,
33 asyncRetryTransactionMiddleware,
34 authenticate,
35 commonVideosFiltersValidator,
36 optionalAuthenticate,
37 paginationValidator,
38 setDefaultPagination,
39 setDefaultSort,
40 videosAddValidator,
41 videosGetValidator,
42 videosRemoveValidator,
43 videosSortValidator,
44 videosUpdateValidator
45} from '../../../middlewares'
46import { TagModel } from '../../../models/video/tag'
47import { VideoModel } from '../../../models/video/video'
48import { VideoFileModel } from '../../../models/video/video-file'
49import { abuseVideoRouter } from './abuse'
50import { blacklistRouter } from './blacklist'
51import { videoCommentRouter } from './comment'
52import { rateVideoRouter } from './rate'
53import { VideoFilter } from '../../../../shared/models/videos/video-query.type'
54import { createReqFiles, buildNSFWFilter } from '../../../helpers/express-utils'
55import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update'
56import { videoCaptionsRouter } from './captions'
57import { videoImportsRouter } from './import'
58
59const auditLogger = auditLoggerFactory('videos')
60const videosRouter = express.Router()
61
62const reqVideoFileAdd = createReqFiles(
63 [ 'videofile', 'thumbnailfile', 'previewfile' ],
64 Object.assign({}, VIDEO_MIMETYPE_EXT, IMAGE_MIMETYPE_EXT),
65 {
66 videofile: CONFIG.STORAGE.VIDEOS_DIR,
67 thumbnailfile: CONFIG.STORAGE.THUMBNAILS_DIR,
68 previewfile: CONFIG.STORAGE.PREVIEWS_DIR
69 }
70)
71const reqVideoFileUpdate = createReqFiles(
72 [ 'thumbnailfile', 'previewfile' ],
73 IMAGE_MIMETYPE_EXT,
74 {
75 thumbnailfile: CONFIG.STORAGE.THUMBNAILS_DIR,
76 previewfile: CONFIG.STORAGE.PREVIEWS_DIR
77 }
78)
79
80videosRouter.use('/', abuseVideoRouter)
81videosRouter.use('/', blacklistRouter)
82videosRouter.use('/', rateVideoRouter)
83videosRouter.use('/', videoCommentRouter)
84videosRouter.use('/', videoCaptionsRouter)
85videosRouter.use('/', videoImportsRouter)
86
87videosRouter.get('/categories', listVideoCategories)
88videosRouter.get('/licences', listVideoLicences)
89videosRouter.get('/languages', listVideoLanguages)
90videosRouter.get('/privacies', listVideoPrivacies)
91
92videosRouter.get('/',
93 paginationValidator,
94 videosSortValidator,
95 setDefaultSort,
96 setDefaultPagination,
97 optionalAuthenticate,
98 commonVideosFiltersValidator,
99 asyncMiddleware(listVideos)
100)
101videosRouter.put('/:id',
102 authenticate,
103 reqVideoFileUpdate,
104 asyncMiddleware(videosUpdateValidator),
105 asyncRetryTransactionMiddleware(updateVideo)
106)
107videosRouter.post('/upload',
108 authenticate,
109 reqVideoFileAdd,
110 asyncMiddleware(videosAddValidator),
111 asyncRetryTransactionMiddleware(addVideo)
112)
113
114videosRouter.get('/:id/description',
115 asyncMiddleware(videosGetValidator),
116 asyncMiddleware(getVideoDescription)
117)
118videosRouter.get('/:id',
119 asyncMiddleware(videosGetValidator),
120 getVideo
121)
122videosRouter.post('/:id/views',
123 asyncMiddleware(videosGetValidator),
124 asyncMiddleware(viewVideo)
125)
126
127videosRouter.delete('/:id',
128 authenticate,
129 asyncMiddleware(videosRemoveValidator),
130 asyncRetryTransactionMiddleware(removeVideo)
131)
132
133// ---------------------------------------------------------------------------
134
135export {
136 videosRouter
137}
138
139// ---------------------------------------------------------------------------
140
141function listVideoCategories (req: express.Request, res: express.Response) {
142 res.json(VIDEO_CATEGORIES)
143}
144
145function listVideoLicences (req: express.Request, res: express.Response) {
146 res.json(VIDEO_LICENCES)
147}
148
149function listVideoLanguages (req: express.Request, res: express.Response) {
150 res.json(VIDEO_LANGUAGES)
151}
152
153function listVideoPrivacies (req: express.Request, res: express.Response) {
154 res.json(VIDEO_PRIVACIES)
155}
156
157async function addVideo (req: express.Request, res: express.Response) {
158 const videoPhysicalFile = req.files['videofile'][0]
159 const videoInfo: VideoCreate = req.body
160
161 // Prepare data so we don't block the transaction
162 const videoData = {
163 name: videoInfo.name,
164 remote: false,
165 category: videoInfo.category,
166 licence: videoInfo.licence,
167 language: videoInfo.language,
168 commentsEnabled: videoInfo.commentsEnabled || false,
169 waitTranscoding: videoInfo.waitTranscoding || false,
170 state: CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED,
171 nsfw: videoInfo.nsfw || false,
172 description: videoInfo.description,
173 support: videoInfo.support,
174 privacy: videoInfo.privacy,
175 duration: videoPhysicalFile['duration'], // duration was added by a previous middleware
176 channelId: res.locals.videoChannel.id
177 }
178 const video = new VideoModel(videoData)
179 video.url = getVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
180
181 // Build the file object
182 const { videoFileResolution } = await getVideoFileResolution(videoPhysicalFile.path)
183 const fps = await getVideoFileFPS(videoPhysicalFile.path)
184
185 const videoFileData = {
186 extname: extname(videoPhysicalFile.filename),
187 resolution: videoFileResolution,
188 size: videoPhysicalFile.size,
189 fps
190 }
191 const videoFile = new VideoFileModel(videoFileData)
192
193 // Move physical file
194 const videoDir = CONFIG.STORAGE.VIDEOS_DIR
195 const destination = join(videoDir, video.getVideoFilename(videoFile))
196 await renamePromise(videoPhysicalFile.path, destination)
197 // This is important in case if there is another attempt in the retry process
198 videoPhysicalFile.filename = video.getVideoFilename(videoFile)
199 videoPhysicalFile.path = destination
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 }
209
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 }
218
219 // Create the torrent file
220 await video.createTorrentAndSetInfoHash(videoFile)
221
222 const videoCreated = await sequelizeTypescript.transaction(async t => {
223 const sequelizeOptions = { transaction: t }
224
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
228
229 videoFile.videoId = video.id
230 await videoFile.save(sequelizeOptions)
231
232 video.VideoFiles = [ videoFile ]
233
234 // Create tags
235 if (videoInfo.tags !== undefined) {
236 const tagInstances = await TagModel.findOrCreateTags(videoInfo.tags, t)
237
238 await video.$set('Tags', tagInstances, sequelizeOptions)
239 video.Tags = tagInstances
240 }
241
242 // Schedule an update in the future?
243 if (videoInfo.scheduleUpdate) {
244 await ScheduleVideoUpdateModel.create({
245 videoId: video.id,
246 updateAt: videoInfo.scheduleUpdate.updateAt,
247 privacy: videoInfo.scheduleUpdate.privacy || null
248 }, { transaction: t })
249 }
250
251 await federateVideoIfNeeded(video, true, t)
252
253 auditLogger.create(res.locals.oauth.token.User.Account.Actor.getIdentifier(), new VideoAuditView(videoCreated.toFormattedDetailsJSON()))
254 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid)
255
256 return videoCreated
257 })
258
259 if (video.state === VideoState.TO_TRANSCODE) {
260 // Put uuid because we don't have id auto incremented for now
261 const dataInput = {
262 videoUUID: videoCreated.uuid,
263 isNewVideo: true
264 }
265
266 await JobQueue.Instance.createJob({ type: 'video-file', payload: dataInput })
267 }
268
269 return res.json({
270 video: {
271 id: videoCreated.id,
272 uuid: videoCreated.uuid
273 }
274 }).end()
275}
276
277async function updateVideo (req: express.Request, res: express.Response) {
278 const videoInstance: VideoModel = res.locals.video
279 const videoFieldsSave = videoInstance.toJSON()
280 const oldVideoAuditView = new VideoAuditView(videoInstance.toFormattedDetailsJSON())
281 const videoInfoToUpdate: VideoUpdate = req.body
282 const wasPrivateVideo = videoInstance.privacy === VideoPrivacy.PRIVATE
283
284 // Process thumbnail or create it from the video
285 if (req.files && req.files['thumbnailfile']) {
286 const thumbnailPhysicalFile = req.files['thumbnailfile'][0]
287 await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, videoInstance.getThumbnailName()), THUMBNAILS_SIZE)
288 }
289
290 // Process preview or create it from the video
291 if (req.files && req.files['previewfile']) {
292 const previewPhysicalFile = req.files['previewfile'][0]
293 await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, videoInstance.getPreviewName()), PREVIEWS_SIZE)
294 }
295
296 try {
297 await sequelizeTypescript.transaction(async t => {
298 const sequelizeOptions = {
299 transaction: t
300 }
301 const oldVideoChannel = videoInstance.VideoChannel
302
303 if (videoInfoToUpdate.name !== undefined) videoInstance.set('name', videoInfoToUpdate.name)
304 if (videoInfoToUpdate.category !== undefined) videoInstance.set('category', videoInfoToUpdate.category)
305 if (videoInfoToUpdate.licence !== undefined) videoInstance.set('licence', videoInfoToUpdate.licence)
306 if (videoInfoToUpdate.language !== undefined) videoInstance.set('language', videoInfoToUpdate.language)
307 if (videoInfoToUpdate.nsfw !== undefined) videoInstance.set('nsfw', videoInfoToUpdate.nsfw)
308 if (videoInfoToUpdate.waitTranscoding !== undefined) videoInstance.set('waitTranscoding', videoInfoToUpdate.waitTranscoding)
309 if (videoInfoToUpdate.support !== undefined) videoInstance.set('support', videoInfoToUpdate.support)
310 if (videoInfoToUpdate.description !== undefined) videoInstance.set('description', videoInfoToUpdate.description)
311 if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.set('commentsEnabled', videoInfoToUpdate.commentsEnabled)
312 if (videoInfoToUpdate.privacy !== undefined) {
313 const newPrivacy = parseInt(videoInfoToUpdate.privacy.toString(), 10)
314 videoInstance.set('privacy', newPrivacy)
315
316 if (wasPrivateVideo === true && newPrivacy !== VideoPrivacy.PRIVATE) {
317 videoInstance.set('publishedAt', new Date())
318 }
319 }
320
321 const videoInstanceUpdated = await videoInstance.save(sequelizeOptions)
322
323 // Video tags update?
324 if (videoInfoToUpdate.tags !== undefined) {
325 const tagInstances = await TagModel.findOrCreateTags(videoInfoToUpdate.tags, t)
326
327 await videoInstanceUpdated.$set('Tags', tagInstances, sequelizeOptions)
328 videoInstanceUpdated.Tags = tagInstances
329 }
330
331 // Video channel update?
332 if (res.locals.videoChannel && videoInstanceUpdated.channelId !== res.locals.videoChannel.id) {
333 await videoInstanceUpdated.$set('VideoChannel', res.locals.videoChannel, { transaction: t })
334 videoInstanceUpdated.VideoChannel = res.locals.videoChannel
335
336 if (wasPrivateVideo === false) await changeVideoChannelShare(videoInstanceUpdated, oldVideoChannel, t)
337 }
338
339 // Schedule an update in the future?
340 if (videoInfoToUpdate.scheduleUpdate) {
341 await ScheduleVideoUpdateModel.upsert({
342 videoId: videoInstanceUpdated.id,
343 updateAt: videoInfoToUpdate.scheduleUpdate.updateAt,
344 privacy: videoInfoToUpdate.scheduleUpdate.privacy || null
345 }, { transaction: t })
346 } else if (videoInfoToUpdate.scheduleUpdate === null) {
347 await ScheduleVideoUpdateModel.deleteByVideoId(videoInstanceUpdated.id, t)
348 }
349
350 const isNewVideo = wasPrivateVideo && videoInstanceUpdated.privacy !== VideoPrivacy.PRIVATE
351 await federateVideoIfNeeded(videoInstanceUpdated, isNewVideo, t)
352
353 auditLogger.update(
354 res.locals.oauth.token.User.Account.Actor.getIdentifier(),
355 new VideoAuditView(videoInstanceUpdated.toFormattedDetailsJSON()),
356 oldVideoAuditView
357 )
358 logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid)
359 })
360 } catch (err) {
361 // Force fields we want to update
362 // If the transaction is retried, sequelize will think the object has not changed
363 // So it will skip the SQL request, even if the last one was ROLLBACKed!
364 resetSequelizeInstance(videoInstance, videoFieldsSave)
365
366 throw err
367 }
368
369 return res.type('json').status(204).end()
370}
371
372function getVideo (req: express.Request, res: express.Response) {
373 const videoInstance = res.locals.video
374
375 return res.json(videoInstance.toFormattedDetailsJSON())
376}
377
378async function viewVideo (req: express.Request, res: express.Response) {
379 const videoInstance = res.locals.video
380
381 const ip = req.ip
382 const exists = await Redis.Instance.isViewExists(ip, videoInstance.uuid)
383 if (exists) {
384 logger.debug('View for ip %s and video %s already exists.', ip, videoInstance.uuid)
385 return res.status(204).end()
386 }
387
388 await videoInstance.increment('views')
389 await Redis.Instance.setView(ip, videoInstance.uuid)
390
391 const serverAccount = await getServerActor()
392
393 await sendCreateView(serverAccount, videoInstance, undefined)
394
395 return res.status(204).end()
396}
397
398async function getVideoDescription (req: express.Request, res: express.Response) {
399 const videoInstance = res.locals.video
400 let description = ''
401
402 if (videoInstance.isOwned()) {
403 description = videoInstance.description
404 } else {
405 description = await fetchRemoteVideoDescription(videoInstance)
406 }
407
408 return res.json({ description })
409}
410
411async function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) {
412 const resultList = await VideoModel.listForApi({
413 start: req.query.start,
414 count: req.query.count,
415 sort: req.query.sort,
416 categoryOneOf: req.query.categoryOneOf,
417 licenceOneOf: req.query.licenceOneOf,
418 languageOneOf: req.query.languageOneOf,
419 tagsOneOf: req.query.tagsOneOf,
420 tagsAllOf: req.query.tagsAllOf,
421 nsfw: buildNSFWFilter(res, req.query.nsfw),
422 filter: req.query.filter as VideoFilter,
423 withFiles: false
424 })
425
426 return res.json(getFormattedObjects(resultList.data, resultList.total))
427}
428
429async function removeVideo (req: express.Request, res: express.Response) {
430 const videoInstance: VideoModel = res.locals.video
431
432 await sequelizeTypescript.transaction(async t => {
433 await videoInstance.destroy({ transaction: t })
434 })
435
436 auditLogger.delete(res.locals.oauth.token.User.Account.Actor.getIdentifier(), new VideoAuditView(videoInstance.toFormattedDetailsJSON()))
437 logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid)
438
439 return res.type('json').status(204).end()
440}