]>
Commit | Line | Data |
---|---|---|
1 | import * as express from 'express' | |
2 | import { extname, join } from 'path' | |
3 | import { VideoCreate, VideoPrivacy, VideoUpdate } from '../../../../shared' | |
4 | import { renamePromise } from '../../../helpers/core-utils' | |
5 | import { retryTransactionWrapper } from '../../../helpers/database-utils' | |
6 | import { getVideoFileHeight } from '../../../helpers/ffmpeg-utils' | |
7 | import { processImage } from '../../../helpers/image-utils' | |
8 | import { logger } from '../../../helpers/logger' | |
9 | import { createReqFiles, getFormattedObjects, getServerActor, resetSequelizeInstance } from '../../../helpers/utils' | |
10 | import { | |
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' | |
22 | import { fetchRemoteVideoDescription, getVideoActivityPubUrl, shareVideoByServerAndChannel } from '../../../lib/activitypub' | |
23 | import { sendCreateVideo, sendCreateViewToOrigin, sendCreateViewToVideoFollowers, sendUpdateVideo } from '../../../lib/activitypub/send' | |
24 | import { JobQueue } from '../../../lib/job-queue' | |
25 | import { | |
26 | asyncMiddleware, | |
27 | authenticate, | |
28 | paginationValidator, | |
29 | setDefaultPagination, | |
30 | setDefaultSort, | |
31 | videosAddValidator, | |
32 | videosGetValidator, | |
33 | videosRemoveValidator, | |
34 | videosSearchValidator, | |
35 | videosSortValidator, | |
36 | videosUpdateValidator | |
37 | } from '../../../middlewares' | |
38 | import { TagModel } from '../../../models/video/tag' | |
39 | import { VideoModel } from '../../../models/video/video' | |
40 | import { VideoFileModel } from '../../../models/video/video-file' | |
41 | import { abuseVideoRouter } from './abuse' | |
42 | import { blacklistRouter } from './blacklist' | |
43 | import { videoChannelRouter } from './channel' | |
44 | import { videoCommentRouter } from './comment' | |
45 | import { rateVideoRouter } from './rate' | |
46 | ||
47 | const videosRouter = express.Router() | |
48 | ||
49 | const reqVideoFileAdd = createReqFiles( | |
50 | [ 'videofile', 'thumbnailfile', 'previewfile' ], | |
51 | Object.assign({}, VIDEO_MIMETYPE_EXT, IMAGE_MIMETYPE_EXT), | |
52 | { | |
53 | videofile: CONFIG.STORAGE.VIDEOS_DIR, | |
54 | thumbnailfile: CONFIG.STORAGE.THUMBNAILS_DIR, | |
55 | previewfile: CONFIG.STORAGE.PREVIEWS_DIR | |
56 | } | |
57 | ) | |
58 | const reqVideoFileUpdate = createReqFiles( | |
59 | [ 'thumbnailfile', 'previewfile' ], | |
60 | IMAGE_MIMETYPE_EXT, | |
61 | { | |
62 | thumbnailfile: CONFIG.STORAGE.THUMBNAILS_DIR, | |
63 | previewfile: CONFIG.STORAGE.PREVIEWS_DIR | |
64 | } | |
65 | ) | |
66 | ||
67 | videosRouter.use('/', abuseVideoRouter) | |
68 | videosRouter.use('/', blacklistRouter) | |
69 | videosRouter.use('/', rateVideoRouter) | |
70 | videosRouter.use('/', videoChannelRouter) | |
71 | videosRouter.use('/', videoCommentRouter) | |
72 | ||
73 | videosRouter.get('/categories', listVideoCategories) | |
74 | videosRouter.get('/licences', listVideoLicences) | |
75 | videosRouter.get('/languages', listVideoLanguages) | |
76 | videosRouter.get('/privacies', listVideoPrivacies) | |
77 | ||
78 | videosRouter.get('/', | |
79 | paginationValidator, | |
80 | videosSortValidator, | |
81 | setDefaultSort, | |
82 | setDefaultPagination, | |
83 | asyncMiddleware(listVideos) | |
84 | ) | |
85 | videosRouter.get('/search', | |
86 | videosSearchValidator, | |
87 | paginationValidator, | |
88 | videosSortValidator, | |
89 | setDefaultSort, | |
90 | setDefaultPagination, | |
91 | asyncMiddleware(searchVideos) | |
92 | ) | |
93 | videosRouter.put('/:id', | |
94 | authenticate, | |
95 | reqVideoFileUpdate, | |
96 | asyncMiddleware(videosUpdateValidator), | |
97 | asyncMiddleware(updateVideoRetryWrapper) | |
98 | ) | |
99 | videosRouter.post('/upload', | |
100 | authenticate, | |
101 | reqVideoFileAdd, | |
102 | asyncMiddleware(videosAddValidator), | |
103 | asyncMiddleware(addVideoRetryWrapper) | |
104 | ) | |
105 | ||
106 | videosRouter.get('/:id/description', | |
107 | asyncMiddleware(videosGetValidator), | |
108 | asyncMiddleware(getVideoDescription) | |
109 | ) | |
110 | videosRouter.get('/:id', | |
111 | asyncMiddleware(videosGetValidator), | |
112 | getVideo | |
113 | ) | |
114 | videosRouter.post('/:id/views', | |
115 | asyncMiddleware(videosGetValidator), | |
116 | asyncMiddleware(viewVideo) | |
117 | ) | |
118 | ||
119 | videosRouter.delete('/:id', | |
120 | authenticate, | |
121 | asyncMiddleware(videosRemoveValidator), | |
122 | asyncMiddleware(removeVideoRetryWrapper) | |
123 | ) | |
124 | ||
125 | // --------------------------------------------------------------------------- | |
126 | ||
127 | export { | |
128 | videosRouter | |
129 | } | |
130 | ||
131 | // --------------------------------------------------------------------------- | |
132 | ||
133 | function listVideoCategories (req: express.Request, res: express.Response) { | |
134 | res.json(VIDEO_CATEGORIES) | |
135 | } | |
136 | ||
137 | function listVideoLicences (req: express.Request, res: express.Response) { | |
138 | res.json(VIDEO_LICENCES) | |
139 | } | |
140 | ||
141 | function listVideoLanguages (req: express.Request, res: express.Response) { | |
142 | res.json(VIDEO_LANGUAGES) | |
143 | } | |
144 | ||
145 | function listVideoPrivacies (req: express.Request, res: express.Response) { | |
146 | res.json(VIDEO_PRIVACIES) | |
147 | } | |
148 | ||
149 | // Wrapper to video add that retry the function if there is a database error | |
150 | // We need this because we run the transaction in SERIALIZABLE isolation that can fail | |
151 | async function addVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) { | |
152 | const options = { | |
153 | arguments: [ req, res, req.files['videofile'][0] ], | |
154 | errorMessage: 'Cannot insert the video with many retries.' | |
155 | } | |
156 | ||
157 | const video = await retryTransactionWrapper(addVideo, options) | |
158 | ||
159 | res.json({ | |
160 | video: { | |
161 | id: video.id, | |
162 | uuid: video.uuid | |
163 | } | |
164 | }).end() | |
165 | } | |
166 | ||
167 | async function addVideo (req: express.Request, res: express.Response, videoPhysicalFile: Express.Multer.File) { | |
168 | const videoInfo: VideoCreate = req.body | |
169 | ||
170 | // Prepare data so we don't block the transaction | |
171 | const videoData = { | |
172 | name: videoInfo.name, | |
173 | remote: false, | |
174 | extname: extname(videoPhysicalFile.filename), | |
175 | category: videoInfo.category, | |
176 | licence: videoInfo.licence, | |
177 | language: videoInfo.language, | |
178 | commentsEnabled: videoInfo.commentsEnabled, | |
179 | nsfw: videoInfo.nsfw, | |
180 | description: videoInfo.description, | |
181 | privacy: videoInfo.privacy, | |
182 | duration: videoPhysicalFile['duration'], // duration was added by a previous middleware | |
183 | channelId: res.locals.videoChannel.id | |
184 | } | |
185 | const video = new VideoModel(videoData) | |
186 | video.url = getVideoActivityPubUrl(video) | |
187 | ||
188 | const videoFileHeight = await getVideoFileHeight(videoPhysicalFile.path) | |
189 | ||
190 | const videoFileData = { | |
191 | extname: extname(videoPhysicalFile.filename), | |
192 | resolution: videoFileHeight, | |
193 | size: videoPhysicalFile.size | |
194 | } | |
195 | const videoFile = new VideoFileModel(videoFileData) | |
196 | const videoDir = CONFIG.STORAGE.VIDEOS_DIR | |
197 | const destination = join(videoDir, video.getVideoFilename(videoFile)) | |
198 | ||
199 | await renamePromise(videoPhysicalFile.path, destination) | |
200 | // This is important in case if there is another attempt in the retry process | |
201 | videoPhysicalFile.filename = video.getVideoFilename(videoFile) | |
202 | ||
203 | // Process thumbnail or create it from the video | |
204 | const thumbnailField = req.files['thumbnailfile'] | |
205 | if (thumbnailField) { | |
206 | const thumbnailPhysicalFile = thumbnailField[0] | |
207 | await processImage(thumbnailPhysicalFile, join(CONFIG.STORAGE.THUMBNAILS_DIR, video.getThumbnailName()), THUMBNAILS_SIZE) | |
208 | } else { | |
209 | await video.createThumbnail(videoFile) | |
210 | } | |
211 | ||
212 | // Process preview or create it from the video | |
213 | const previewField = req.files['previewfile'] | |
214 | if (previewField) { | |
215 | const previewPhysicalFile = previewField[0] | |
216 | await processImage(previewPhysicalFile, join(CONFIG.STORAGE.PREVIEWS_DIR, video.getPreviewName()), PREVIEWS_SIZE) | |
217 | } else { | |
218 | await video.createPreview(videoFile) | |
219 | } | |
220 | ||
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 | if (videoInfo.tags) { | |
236 | const tagInstances = await TagModel.findOrCreateTags(videoInfo.tags, t) | |
237 | ||
238 | await video.$set('Tags', tagInstances, sequelizeOptions) | |
239 | video.Tags = tagInstances | |
240 | } | |
241 | ||
242 | // Let transcoding job send the video to friends because the video file extension might change | |
243 | if (CONFIG.TRANSCODING.ENABLED === true) return videoCreated | |
244 | // Don't send video to remote servers, it is private | |
245 | if (video.privacy === VideoPrivacy.PRIVATE) return videoCreated | |
246 | ||
247 | await sendCreateVideo(video, t) | |
248 | await shareVideoByServerAndChannel(video, t) | |
249 | ||
250 | logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid) | |
251 | ||
252 | return videoCreated | |
253 | }) | |
254 | ||
255 | if (CONFIG.TRANSCODING.ENABLED === true) { | |
256 | // Put uuid because we don't have id auto incremented for now | |
257 | const dataInput = { | |
258 | videoUUID: videoCreated.uuid | |
259 | } | |
260 | ||
261 | await JobQueue.Instance.createJob({ type: 'video-file', payload: dataInput }) | |
262 | } | |
263 | ||
264 | return videoCreated | |
265 | } | |
266 | ||
267 | async function updateVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) { | |
268 | const options = { | |
269 | arguments: [ req, res ], | |
270 | errorMessage: 'Cannot update the video with many retries.' | |
271 | } | |
272 | ||
273 | await retryTransactionWrapper(updateVideo, options) | |
274 | ||
275 | return res.type('json').status(204).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 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 | ||
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) | |
307 | if (videoInfoToUpdate.privacy !== undefined) videoInstance.set('privacy', parseInt(videoInfoToUpdate.privacy.toString(), 10)) | |
308 | if (videoInfoToUpdate.description !== undefined) videoInstance.set('description', videoInfoToUpdate.description) | |
309 | if (videoInfoToUpdate.commentsEnabled !== undefined) videoInstance.set('commentsEnabled', videoInfoToUpdate.commentsEnabled) | |
310 | ||
311 | const videoInstanceUpdated = await videoInstance.save(sequelizeOptions) | |
312 | ||
313 | if (videoInfoToUpdate.tags) { | |
314 | const tagInstances = await TagModel.findOrCreateTags(videoInfoToUpdate.tags, t) | |
315 | ||
316 | await videoInstance.$set('Tags', tagInstances, sequelizeOptions) | |
317 | videoInstance.Tags = tagInstances | |
318 | } | |
319 | ||
320 | // Now we'll update the video's meta data to our friends | |
321 | if (wasPrivateVideo === false) { | |
322 | await sendUpdateVideo(videoInstanceUpdated, t) | |
323 | } | |
324 | ||
325 | // Video is not private anymore, send a create action to remote servers | |
326 | if (wasPrivateVideo === true && videoInstanceUpdated.privacy !== VideoPrivacy.PRIVATE) { | |
327 | await sendCreateVideo(videoInstanceUpdated, t) | |
328 | await shareVideoByServerAndChannel(videoInstanceUpdated, t) | |
329 | } | |
330 | }) | |
331 | ||
332 | logger.info('Video with name %s and uuid %s updated.', videoInstance.name, videoInstance.uuid) | |
333 | } catch (err) { | |
334 | // Force fields we want to update | |
335 | // If the transaction is retried, sequelize will think the object has not changed | |
336 | // So it will skip the SQL request, even if the last one was ROLLBACKed! | |
337 | resetSequelizeInstance(videoInstance, videoFieldsSave) | |
338 | ||
339 | throw err | |
340 | } | |
341 | } | |
342 | ||
343 | function getVideo (req: express.Request, res: express.Response) { | |
344 | const videoInstance = res.locals.video | |
345 | ||
346 | return res.json(videoInstance.toFormattedDetailsJSON()) | |
347 | } | |
348 | ||
349 | async function viewVideo (req: express.Request, res: express.Response) { | |
350 | const videoInstance = res.locals.video | |
351 | ||
352 | await videoInstance.increment('views') | |
353 | const serverAccount = await getServerActor() | |
354 | ||
355 | if (videoInstance.isOwned()) { | |
356 | await sendCreateViewToVideoFollowers(serverAccount, videoInstance, undefined) | |
357 | } else { | |
358 | await sendCreateViewToOrigin(serverAccount, videoInstance, undefined) | |
359 | } | |
360 | ||
361 | return res.status(204).end() | |
362 | } | |
363 | ||
364 | async function getVideoDescription (req: express.Request, res: express.Response) { | |
365 | const videoInstance = res.locals.video | |
366 | let description = '' | |
367 | ||
368 | if (videoInstance.isOwned()) { | |
369 | description = videoInstance.description | |
370 | } else { | |
371 | description = await fetchRemoteVideoDescription(videoInstance) | |
372 | } | |
373 | ||
374 | return res.json({ description }) | |
375 | } | |
376 | ||
377 | async function listVideos (req: express.Request, res: express.Response, next: express.NextFunction) { | |
378 | const resultList = await VideoModel.listForApi(req.query.start, req.query.count, req.query.sort) | |
379 | ||
380 | return res.json(getFormattedObjects(resultList.data, resultList.total)) | |
381 | } | |
382 | ||
383 | async function removeVideoRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) { | |
384 | const options = { | |
385 | arguments: [ req, res ], | |
386 | errorMessage: 'Cannot remove the video with many retries.' | |
387 | } | |
388 | ||
389 | await retryTransactionWrapper(removeVideo, options) | |
390 | ||
391 | return res.type('json').status(204).end() | |
392 | } | |
393 | ||
394 | async function removeVideo (req: express.Request, res: express.Response) { | |
395 | const videoInstance: VideoModel = res.locals.video | |
396 | ||
397 | await sequelizeTypescript.transaction(async t => { | |
398 | await videoInstance.destroy({ transaction: t }) | |
399 | }) | |
400 | ||
401 | logger.info('Video with name %s and uuid %s deleted.', videoInstance.name, videoInstance.uuid) | |
402 | } | |
403 | ||
404 | async function searchVideos (req: express.Request, res: express.Response, next: express.NextFunction) { | |
405 | const resultList = await VideoModel.searchAndPopulateAccountAndServerAndTags( | |
406 | req.query.search, | |
407 | req.query.start, | |
408 | req.query.count, | |
409 | req.query.sort | |
410 | ) | |
411 | ||
412 | return res.json(getFormattedObjects(resultList.data, resultList.total)) | |
413 | } |