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