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