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