]>
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 | } 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() | |
52 | ||
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', | |
73 | openapiOperationDoc({ operationId: 'uploadLegacy' }), | |
74 | authenticate, | |
75 | reqVideoFileAdd, | |
76 | asyncMiddleware(videosAddLegacyValidator), | |
77 | asyncRetryTransactionMiddleware(addVideoLegacy) | |
78 | ) | |
79 | ||
80 | uploadRouter.post('/upload-resumable', | |
81 | openapiOperationDoc({ operationId: 'uploadResumableInit' }), | |
82 | authenticate, | |
83 | reqVideoFileAddResumable, | |
84 | asyncMiddleware(videosAddResumableInitValidator), | |
85 | uploadx.upload | |
86 | ) | |
87 | ||
88 | uploadRouter.delete('/upload-resumable', | |
89 | authenticate, | |
90 | asyncMiddleware(deleteUploadResumableCache), | |
91 | uploadx.upload | |
92 | ) | |
93 | ||
94 | uploadRouter.put('/upload-resumable', | |
95 | openapiOperationDoc({ operationId: 'uploadResumable' }), | |
96 | authenticate, | |
97 | uploadx.upload, // uploadx doesn't next() before the file upload completes | |
98 | asyncMiddleware(videosAddResumableValidator), | |
99 | asyncMiddleware(addVideoResumable) | |
100 | ) | |
101 | ||
102 | // --------------------------------------------------------------------------- | |
103 | ||
104 | export { | |
105 | uploadRouter | |
106 | } | |
107 | ||
108 | // --------------------------------------------------------------------------- | |
109 | ||
110 | async function addVideoLegacy (req: express.Request, res: express.Response) { | |
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, () => { | |
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 | }) | |
119 | }) | |
120 | ||
121 | const videoPhysicalFile = req.files['videofile'][0] | |
122 | const videoInfo: VideoCreate = req.body | |
123 | const files = req.files | |
124 | ||
125 | const response = await addVideo({ req, res, videoPhysicalFile, videoInfo, files }) | |
126 | ||
127 | return res.json(response) | |
128 | } | |
129 | ||
130 | async function addVideoResumable (req: express.Request, res: express.Response) { | |
131 | const videoPhysicalFile = res.locals.videoFileResumable | |
132 | const videoInfo = videoPhysicalFile.metadata | |
133 | const files = { previewfile: videoInfo.previewfile } | |
134 | ||
135 | const response = await addVideo({ req, res, videoPhysicalFile, videoInfo, files }) | |
136 | await Redis.Instance.setUploadSession(req.query.upload_id, response) | |
137 | ||
138 | return res.json(response) | |
139 | } | |
140 | ||
141 | async function addVideo (options: { | |
142 | req: express.Request | |
143 | res: express.Response | |
144 | videoPhysicalFile: express.VideoUploadFile | |
145 | videoInfo: VideoCreate | |
146 | files: express.UploadFiles | |
147 | }) { | |
148 | const { req, res, videoPhysicalFile, videoInfo, files } = options | |
149 | const videoChannel = res.locals.videoChannel | |
150 | const user = res.locals.oauth.token.User | |
151 | ||
152 | let videoData = buildLocalVideoFromReq(videoInfo, videoChannel.id) | |
153 | videoData = await Hooks.wrapObject(videoData, 'filter:api.video.upload.video-attribute.result') | |
154 | ||
155 | videoData.state = buildNextVideoState() | |
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 | ||
162 | const videoFile = await buildNewFile(videoPhysicalFile) | |
163 | ||
164 | // Move physical file | |
165 | const destination = VideoPathManager.Instance.getFSVideoFileOutputPath(video, videoFile) | |
166 | await move(videoPhysicalFile.path, destination) | |
167 | // This is important in case if there is another attempt in the retry process | |
168 | videoPhysicalFile.filename = basename(destination) | |
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 | ||
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 | ||
218 | // Channel has a new content, set as updated | |
219 | await videoCreated.VideoChannel.setAsUpdated() | |
220 | ||
221 | createTorrentFederate(video, videoFile) | |
222 | .then(() => { | |
223 | if (video.state === VideoState.TO_MOVE_TO_EXTERNAL_STORAGE) { | |
224 | return addMoveToObjectStorageJob(video) | |
225 | } | |
226 | ||
227 | if (video.state === VideoState.TO_TRANSCODE) { | |
228 | return addOptimizeOrMergeAudioJob(videoCreated, videoFile, user) | |
229 | } | |
230 | }) | |
231 | .catch(err => logger.error('Cannot add optimize/merge audio job for %s.', videoCreated.uuid, { err, ...lTags(videoCreated.uuid) })) | |
232 | ||
233 | Hooks.runAction('action:api.video.uploaded', { video: videoCreated, req, res }) | |
234 | ||
235 | return { | |
236 | video: { | |
237 | id: videoCreated.id, | |
238 | shortUUID: uuidToShort(videoCreated.uuid), | |
239 | uuid: videoCreated.uuid | |
240 | } | |
241 | } | |
242 | } | |
243 | ||
244 | async function buildNewFile (videoPhysicalFile: express.VideoUploadFile) { | |
245 | const videoFile = new VideoFileModel({ | |
246 | extname: getLowercaseExtension(videoPhysicalFile.filename), | |
247 | size: videoPhysicalFile.size, | |
248 | videoStreamingPlaylistId: null, | |
249 | metadata: await getMetadataFromFile(videoPhysicalFile.path) | |
250 | }) | |
251 | ||
252 | const probe = await ffprobePromise(videoPhysicalFile.path) | |
253 | ||
254 | if (await isAudioFile(videoPhysicalFile.path, probe)) { | |
255 | videoFile.resolution = VideoResolution.H_NOVIDEO | |
256 | } else { | |
257 | videoFile.fps = await getVideoFileFPS(videoPhysicalFile.path, probe) | |
258 | videoFile.resolution = (await getVideoFileResolution(videoPhysicalFile.path, probe)).resolution | |
259 | } | |
260 | ||
261 | videoFile.filename = generateWebTorrentVideoFilename(videoFile.resolution, videoFile.extname) | |
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 | ||
280 | function createTorrentFederate (video: MVideoFullLight, videoFile: MVideoFile) { | |
281 | // Create the torrent file in async way because it could be long | |
282 | return createTorrentAndSetInfoHashAsync(video, videoFile) | |
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 | } | |
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 | } |