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