]>
Commit | Line | Data |
---|---|---|
41fb13c3 | 1 | import express from 'express' |
c158a5fa | 2 | import { move } from 'fs-extra' |
0305db28 | 3 | import { basename } from 'path' |
790c2837 | 4 | import { getResumableUploadPath } from '@server/helpers/upload' |
c158a5fa C |
5 | import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent' |
6 | import { getLocalVideoActivityPubUrl } from '@server/lib/activitypub/url' | |
0305db28 | 7 | import { generateWebTorrentVideoFilename } from '@server/lib/paths' |
276250f0 | 8 | import { Redis } from '@server/lib/redis' |
6d472b40 | 9 | import { uploadx } from '@server/lib/uploadx' |
0305db28 JB |
10 | import { |
11 | addMoveToObjectStorageJob, | |
12 | addOptimizeOrMergeAudioJob, | |
13 | buildLocalVideoFromReq, | |
14 | buildVideoThumbnailsFromReq, | |
15 | setVideoTags | |
16 | } from '@server/lib/video' | |
17 | import { VideoPathManager } from '@server/lib/video-path-manager' | |
18 | import { buildNextVideoState } from '@server/lib/video-state' | |
1c627fd8 | 19 | import { openapiOperationDoc } from '@server/middlewares/doc' |
c158a5fa | 20 | import { MVideo, MVideoFile, MVideoFullLight } from '@server/types/models' |
0628157f C |
21 | import { getLowercaseExtension } from '@shared/core-utils' |
22 | import { isAudioFile, uuidToShort } from '@shared/extra-utils' | |
d17c7b4e | 23 | import { HttpStatusCode, VideoCreate, VideoResolution, VideoState } from '@shared/models' |
c158a5fa C |
24 | import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger' |
25 | import { retryTransactionWrapper } from '../../../helpers/database-utils' | |
26 | import { createReqFiles } from '../../../helpers/express-utils' | |
c729caf6 | 27 | import { ffprobePromise, buildFileMetadata, getVideoStreamFPS, getVideoStreamDimensionsInfo } from '../../../helpers/ffmpeg' |
c158a5fa C |
28 | import { logger, loggerTagsFactory } from '../../../helpers/logger' |
29 | import { CONFIG } from '../../../initializers/config' | |
482b2623 | 30 | import { MIMETYPES } from '../../../initializers/constants' |
c158a5fa C |
31 | import { sequelizeTypescript } from '../../../initializers/database' |
32 | import { federateVideoIfNeeded } from '../../../lib/activitypub/videos' | |
33 | import { Notifier } from '../../../lib/notifier' | |
34 | import { Hooks } from '../../../lib/plugins/hooks' | |
35 | import { generateVideoMiniature } from '../../../lib/thumbnail' | |
36 | import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist' | |
37 | import { | |
38 | asyncMiddleware, | |
39 | asyncRetryTransactionMiddleware, | |
40 | authenticate, | |
41 | videosAddLegacyValidator, | |
42 | videosAddResumableInitValidator, | |
2f0a0ae2 | 43 | videosAddResumableValidator |
c158a5fa C |
44 | } from '../../../middlewares' |
45 | import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update' | |
46 | import { VideoModel } from '../../../models/video/video' | |
47 | import { VideoFileModel } from '../../../models/video/video-file' | |
48 | ||
49 | const lTags = loggerTagsFactory('api', 'video') | |
50 | const auditLogger = auditLoggerFactory('videos') | |
51 | const uploadRouter = express.Router() | |
020d3d3d | 52 | |
c158a5fa C |
53 | const reqVideoFileAdd = createReqFiles( |
54 | [ 'videofile', 'thumbnailfile', 'previewfile' ], | |
55 | Object.assign({}, MIMETYPES.VIDEO.MIMETYPE_EXT, MIMETYPES.IMAGE.MIMETYPE_EXT), | |
56 | { | |
57 | videofile: CONFIG.STORAGE.TMP_DIR, | |
58 | thumbnailfile: CONFIG.STORAGE.TMP_DIR, | |
59 | previewfile: CONFIG.STORAGE.TMP_DIR | |
60 | } | |
61 | ) | |
62 | ||
63 | const reqVideoFileAddResumable = createReqFiles( | |
64 | [ 'thumbnailfile', 'previewfile' ], | |
65 | MIMETYPES.IMAGE.MIMETYPE_EXT, | |
66 | { | |
67 | thumbnailfile: getResumableUploadPath(), | |
68 | previewfile: getResumableUploadPath() | |
69 | } | |
70 | ) | |
71 | ||
72 | uploadRouter.post('/upload', | |
1c627fd8 | 73 | openapiOperationDoc({ operationId: 'uploadLegacy' }), |
c158a5fa C |
74 | authenticate, |
75 | reqVideoFileAdd, | |
76 | asyncMiddleware(videosAddLegacyValidator), | |
77 | asyncRetryTransactionMiddleware(addVideoLegacy) | |
78 | ) | |
79 | ||
80 | uploadRouter.post('/upload-resumable', | |
1c627fd8 | 81 | openapiOperationDoc({ operationId: 'uploadResumableInit' }), |
c158a5fa C |
82 | authenticate, |
83 | reqVideoFileAddResumable, | |
84 | asyncMiddleware(videosAddResumableInitValidator), | |
020d3d3d | 85 | uploadx.upload |
c158a5fa C |
86 | ) |
87 | ||
88 | uploadRouter.delete('/upload-resumable', | |
89 | authenticate, | |
020d3d3d C |
90 | asyncMiddleware(deleteUploadResumableCache), |
91 | uploadx.upload | |
c158a5fa C |
92 | ) |
93 | ||
94 | uploadRouter.put('/upload-resumable', | |
1c627fd8 | 95 | openapiOperationDoc({ operationId: 'uploadResumable' }), |
c158a5fa | 96 | authenticate, |
020d3d3d | 97 | uploadx.upload, // uploadx doesn't next() before the file upload completes |
c158a5fa C |
98 | asyncMiddleware(videosAddResumableValidator), |
99 | asyncMiddleware(addVideoResumable) | |
100 | ) | |
101 | ||
102 | // --------------------------------------------------------------------------- | |
103 | ||
104 | export { | |
105 | uploadRouter | |
106 | } | |
107 | ||
108 | // --------------------------------------------------------------------------- | |
109 | ||
020d3d3d | 110 | async function addVideoLegacy (req: express.Request, res: express.Response) { |
c158a5fa C |
111 | // Uploading the video could be long |
112 | // Set timeout to 10 minutes, as Express's default is 2 minutes | |
113 | req.setTimeout(1000 * 60 * 10, () => { | |
76148b27 RK |
114 | logger.error('Video upload has timed out.') |
115 | return res.fail({ | |
116 | status: HttpStatusCode.REQUEST_TIMEOUT_408, | |
117 | message: 'Video upload has timed out.' | |
118 | }) | |
c158a5fa C |
119 | }) |
120 | ||
121 | const videoPhysicalFile = req.files['videofile'][0] | |
122 | const videoInfo: VideoCreate = req.body | |
123 | const files = req.files | |
124 | ||
7226e90f | 125 | const response = await addVideo({ req, res, videoPhysicalFile, videoInfo, files }) |
276250f0 RK |
126 | |
127 | return res.json(response) | |
c158a5fa C |
128 | } |
129 | ||
020d3d3d | 130 | async function addVideoResumable (req: express.Request, res: express.Response) { |
c158a5fa C |
131 | const videoPhysicalFile = res.locals.videoFileResumable |
132 | const videoInfo = videoPhysicalFile.metadata | |
133 | const files = { previewfile: videoInfo.previewfile } | |
134 | ||
7226e90f | 135 | const response = await addVideo({ req, res, videoPhysicalFile, videoInfo, files }) |
276250f0 RK |
136 | await Redis.Instance.setUploadSession(req.query.upload_id, response) |
137 | ||
138 | return res.json(response) | |
c158a5fa C |
139 | } |
140 | ||
141 | async function addVideo (options: { | |
7226e90f | 142 | req: express.Request |
c158a5fa C |
143 | res: express.Response |
144 | videoPhysicalFile: express.VideoUploadFile | |
145 | videoInfo: VideoCreate | |
146 | files: express.UploadFiles | |
147 | }) { | |
7226e90f | 148 | const { req, res, videoPhysicalFile, videoInfo, files } = options |
c158a5fa C |
149 | const videoChannel = res.locals.videoChannel |
150 | const user = res.locals.oauth.token.User | |
151 | ||
d17d7430 C |
152 | let videoData = buildLocalVideoFromReq(videoInfo, videoChannel.id) |
153 | videoData = await Hooks.wrapObject(videoData, 'filter:api.video.upload.video-attribute.result') | |
c158a5fa | 154 | |
0305db28 | 155 | videoData.state = buildNextVideoState() |
c158a5fa C |
156 | videoData.duration = videoPhysicalFile.duration // duration was added by a previous middleware |
157 | ||
158 | const video = new VideoModel(videoData) as MVideoFullLight | |
159 | video.VideoChannel = videoChannel | |
160 | video.url = getLocalVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object | |
161 | ||
0305db28 | 162 | const videoFile = await buildNewFile(videoPhysicalFile) |
c158a5fa C |
163 | |
164 | // Move physical file | |
0305db28 | 165 | const destination = VideoPathManager.Instance.getFSVideoFileOutputPath(video, videoFile) |
c158a5fa C |
166 | await move(videoPhysicalFile.path, destination) |
167 | // This is important in case if there is another attempt in the retry process | |
0305db28 | 168 | videoPhysicalFile.filename = basename(destination) |
c158a5fa C |
169 | videoPhysicalFile.path = destination |
170 | ||
171 | const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({ | |
172 | video, | |
173 | files, | |
174 | fallback: type => generateVideoMiniature({ video, videoFile, type }) | |
175 | }) | |
176 | ||
177 | const { videoCreated } = await sequelizeTypescript.transaction(async t => { | |
178 | const sequelizeOptions = { transaction: t } | |
179 | ||
180 | const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight | |
181 | ||
182 | await videoCreated.addAndSaveThumbnail(thumbnailModel, t) | |
183 | await videoCreated.addAndSaveThumbnail(previewModel, t) | |
184 | ||
185 | // Do not forget to add video channel information to the created video | |
186 | videoCreated.VideoChannel = res.locals.videoChannel | |
187 | ||
188 | videoFile.videoId = video.id | |
189 | await videoFile.save(sequelizeOptions) | |
190 | ||
191 | video.VideoFiles = [ videoFile ] | |
192 | ||
193 | await setVideoTags({ video, tags: videoInfo.tags, transaction: t }) | |
194 | ||
195 | // Schedule an update in the future? | |
196 | if (videoInfo.scheduleUpdate) { | |
197 | await ScheduleVideoUpdateModel.create({ | |
198 | videoId: video.id, | |
199 | updateAt: new Date(videoInfo.scheduleUpdate.updateAt), | |
200 | privacy: videoInfo.scheduleUpdate.privacy || null | |
201 | }, sequelizeOptions) | |
202 | } | |
203 | ||
c158a5fa C |
204 | await autoBlacklistVideoIfNeeded({ |
205 | video, | |
206 | user, | |
207 | isRemote: false, | |
208 | isNew: true, | |
209 | transaction: t | |
210 | }) | |
211 | ||
212 | auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(videoCreated.toFormattedDetailsJSON())) | |
213 | logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid, lTags(videoCreated.uuid)) | |
214 | ||
215 | return { videoCreated } | |
216 | }) | |
217 | ||
3419e0e1 C |
218 | // Channel has a new content, set as updated |
219 | await videoCreated.VideoChannel.setAsUpdated() | |
220 | ||
c158a5fa | 221 | createTorrentFederate(video, videoFile) |
764b1a14 | 222 | .then(() => { |
0305db28 JB |
223 | if (video.state === VideoState.TO_MOVE_TO_EXTERNAL_STORAGE) { |
224 | return addMoveToObjectStorageJob(video) | |
225 | } | |
c158a5fa | 226 | |
0305db28 JB |
227 | if (video.state === VideoState.TO_TRANSCODE) { |
228 | return addOptimizeOrMergeAudioJob(videoCreated, videoFile, user) | |
229 | } | |
764b1a14 C |
230 | }) |
231 | .catch(err => logger.error('Cannot add optimize/merge audio job for %s.', videoCreated.uuid, { err, ...lTags(videoCreated.uuid) })) | |
c158a5fa | 232 | |
7226e90f | 233 | Hooks.runAction('action:api.video.uploaded', { video: videoCreated, req, res }) |
c158a5fa | 234 | |
276250f0 | 235 | return { |
c158a5fa C |
236 | video: { |
237 | id: videoCreated.id, | |
d4a8e7a6 | 238 | shortUUID: uuidToShort(videoCreated.uuid), |
c158a5fa C |
239 | uuid: videoCreated.uuid |
240 | } | |
276250f0 | 241 | } |
c158a5fa C |
242 | } |
243 | ||
0305db28 | 244 | async function buildNewFile (videoPhysicalFile: express.VideoUploadFile) { |
c158a5fa | 245 | const videoFile = new VideoFileModel({ |
ea54cd04 | 246 | extname: getLowercaseExtension(videoPhysicalFile.filename), |
c158a5fa C |
247 | size: videoPhysicalFile.size, |
248 | videoStreamingPlaylistId: null, | |
c729caf6 | 249 | metadata: await buildFileMetadata(videoPhysicalFile.path) |
c158a5fa C |
250 | }) |
251 | ||
482b2623 C |
252 | const probe = await ffprobePromise(videoPhysicalFile.path) |
253 | ||
254 | if (await isAudioFile(videoPhysicalFile.path, probe)) { | |
255 | videoFile.resolution = VideoResolution.H_NOVIDEO | |
c158a5fa | 256 | } else { |
c729caf6 C |
257 | videoFile.fps = await getVideoStreamFPS(videoPhysicalFile.path, probe) |
258 | videoFile.resolution = (await getVideoStreamDimensionsInfo(videoPhysicalFile.path, probe)).resolution | |
c158a5fa C |
259 | } |
260 | ||
83903cb6 | 261 | videoFile.filename = generateWebTorrentVideoFilename(videoFile.resolution, videoFile.extname) |
c158a5fa C |
262 | |
263 | return videoFile | |
264 | } | |
265 | ||
266 | async function createTorrentAndSetInfoHashAsync (video: MVideo, fileArg: MVideoFile) { | |
267 | await createTorrentAndSetInfoHash(video, fileArg) | |
268 | ||
269 | // Refresh videoFile because the createTorrentAndSetInfoHash could be long | |
270 | const refreshedFile = await VideoFileModel.loadWithVideo(fileArg.id) | |
271 | // File does not exist anymore, remove the generated torrent | |
272 | if (!refreshedFile) return fileArg.removeTorrent() | |
273 | ||
274 | refreshedFile.infoHash = fileArg.infoHash | |
275 | refreshedFile.torrentFilename = fileArg.torrentFilename | |
276 | ||
277 | return refreshedFile.save() | |
278 | } | |
279 | ||
764b1a14 | 280 | function createTorrentFederate (video: MVideoFullLight, videoFile: MVideoFile) { |
c158a5fa | 281 | // Create the torrent file in async way because it could be long |
764b1a14 | 282 | return createTorrentAndSetInfoHashAsync(video, videoFile) |
c158a5fa C |
283 | .catch(err => logger.error('Cannot create torrent file for video %s', video.url, { err, ...lTags(video.uuid) })) |
284 | .then(() => VideoModel.loadAndPopulateAccountAndServerAndTags(video.id)) | |
285 | .then(refreshedVideo => { | |
286 | if (!refreshedVideo) return | |
287 | ||
288 | // Only federate and notify after the torrent creation | |
289 | Notifier.Instance.notifyOnNewVideoIfNeeded(refreshedVideo) | |
290 | ||
291 | return retryTransactionWrapper(() => { | |
292 | return sequelizeTypescript.transaction(t => federateVideoIfNeeded(refreshedVideo, true, t)) | |
293 | }) | |
294 | }) | |
295 | .catch(err => logger.error('Cannot federate or notify video creation %s', video.url, { err, ...lTags(video.uuid) })) | |
296 | } | |
020d3d3d C |
297 | |
298 | async function deleteUploadResumableCache (req: express.Request, res: express.Response, next: express.NextFunction) { | |
299 | await Redis.Instance.deleteUploadSession(req.query.upload_id) | |
300 | ||
301 | return next() | |
302 | } |