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