]>
Commit | Line | Data |
---|---|---|
41fb13c3 | 1 | import express from 'express' |
c158a5fa | 2 | import { move } from 'fs-extra' |
0305db28 | 3 | import { basename } from 'path' |
ea54cd04 | 4 | import { getLowercaseExtension } from '@server/helpers/core-utils' |
c158a5fa | 5 | import { deleteResumableUploadMetaFile, getResumableUploadPath } from '@server/helpers/upload' |
d4a8e7a6 | 6 | import { uuidToShort } from '@server/helpers/uuid' |
c158a5fa C |
7 | import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent' |
8 | import { getLocalVideoActivityPubUrl } from '@server/lib/activitypub/url' | |
0305db28 JB |
9 | import { generateWebTorrentVideoFilename } from '@server/lib/paths' |
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 C |
20 | import { MVideo, MVideoFile, MVideoFullLight } from '@server/types/models' |
21 | import { uploadx } from '@uploadx/core' | |
22 | import { VideoCreate, VideoState } from '../../../../shared' | |
c0e8b12e | 23 | import { HttpStatusCode } 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' | |
27 | import { getMetadataFromFile, getVideoFileFPS, getVideoFileResolution } from '../../../helpers/ffprobe-utils' | |
28 | import { logger, loggerTagsFactory } from '../../../helpers/logger' | |
29 | import { CONFIG } from '../../../initializers/config' | |
30 | import { DEFAULT_AUDIO_RESOLUTION, 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 | const uploadxMiddleware = uploadx.upload({ directory: getResumableUploadPath() }) | |
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', | |
1c627fd8 | 74 | openapiOperationDoc({ operationId: 'uploadLegacy' }), |
c158a5fa C |
75 | authenticate, |
76 | reqVideoFileAdd, | |
77 | asyncMiddleware(videosAddLegacyValidator), | |
78 | asyncRetryTransactionMiddleware(addVideoLegacy) | |
79 | ) | |
80 | ||
81 | uploadRouter.post('/upload-resumable', | |
1c627fd8 | 82 | openapiOperationDoc({ operationId: 'uploadResumableInit' }), |
c158a5fa C |
83 | authenticate, |
84 | reqVideoFileAddResumable, | |
85 | asyncMiddleware(videosAddResumableInitValidator), | |
86 | uploadxMiddleware | |
87 | ) | |
88 | ||
89 | uploadRouter.delete('/upload-resumable', | |
90 | authenticate, | |
91 | uploadxMiddleware | |
92 | ) | |
93 | ||
94 | uploadRouter.put('/upload-resumable', | |
1c627fd8 | 95 | openapiOperationDoc({ operationId: 'uploadResumable' }), |
c158a5fa C |
96 | authenticate, |
97 | uploadxMiddleware, // uploadx doesn't use call 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 | export 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, () => { | |
76148b27 RK |
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 | }) | |
c158a5fa C |
119 | }) |
120 | ||
121 | const videoPhysicalFile = req.files['videofile'][0] | |
122 | const videoInfo: VideoCreate = req.body | |
123 | const files = req.files | |
124 | ||
125 | return addVideo({ res, videoPhysicalFile, videoInfo, files }) | |
126 | } | |
127 | ||
128 | export async function addVideoResumable (_req: express.Request, res: express.Response) { | |
129 | const videoPhysicalFile = res.locals.videoFileResumable | |
130 | const videoInfo = videoPhysicalFile.metadata | |
131 | const files = { previewfile: videoInfo.previewfile } | |
132 | ||
133 | // Don't need the meta file anymore | |
134 | await deleteResumableUploadMetaFile(videoPhysicalFile.path) | |
135 | ||
136 | return addVideo({ res, videoPhysicalFile, videoInfo, files }) | |
137 | } | |
138 | ||
139 | async function addVideo (options: { | |
140 | res: express.Response | |
141 | videoPhysicalFile: express.VideoUploadFile | |
142 | videoInfo: VideoCreate | |
143 | files: express.UploadFiles | |
144 | }) { | |
145 | const { res, videoPhysicalFile, videoInfo, files } = options | |
146 | const videoChannel = res.locals.videoChannel | |
147 | const user = res.locals.oauth.token.User | |
148 | ||
149 | const videoData = buildLocalVideoFromReq(videoInfo, videoChannel.id) | |
150 | ||
0305db28 | 151 | videoData.state = buildNextVideoState() |
c158a5fa C |
152 | videoData.duration = videoPhysicalFile.duration // duration was added by a previous middleware |
153 | ||
154 | const video = new VideoModel(videoData) as MVideoFullLight | |
155 | video.VideoChannel = videoChannel | |
156 | video.url = getLocalVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object | |
157 | ||
0305db28 | 158 | const videoFile = await buildNewFile(videoPhysicalFile) |
c158a5fa C |
159 | |
160 | // Move physical file | |
0305db28 | 161 | const destination = VideoPathManager.Instance.getFSVideoFileOutputPath(video, videoFile) |
c158a5fa C |
162 | await move(videoPhysicalFile.path, destination) |
163 | // This is important in case if there is another attempt in the retry process | |
0305db28 | 164 | videoPhysicalFile.filename = basename(destination) |
c158a5fa C |
165 | videoPhysicalFile.path = destination |
166 | ||
167 | const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({ | |
168 | video, | |
169 | files, | |
170 | fallback: type => generateVideoMiniature({ video, videoFile, type }) | |
171 | }) | |
172 | ||
173 | const { videoCreated } = await sequelizeTypescript.transaction(async t => { | |
174 | const sequelizeOptions = { transaction: t } | |
175 | ||
176 | const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight | |
177 | ||
178 | await videoCreated.addAndSaveThumbnail(thumbnailModel, t) | |
179 | await videoCreated.addAndSaveThumbnail(previewModel, t) | |
180 | ||
181 | // Do not forget to add video channel information to the created video | |
182 | videoCreated.VideoChannel = res.locals.videoChannel | |
183 | ||
184 | videoFile.videoId = video.id | |
185 | await videoFile.save(sequelizeOptions) | |
186 | ||
187 | video.VideoFiles = [ videoFile ] | |
188 | ||
189 | await setVideoTags({ video, tags: videoInfo.tags, transaction: t }) | |
190 | ||
191 | // Schedule an update in the future? | |
192 | if (videoInfo.scheduleUpdate) { | |
193 | await ScheduleVideoUpdateModel.create({ | |
194 | videoId: video.id, | |
195 | updateAt: new Date(videoInfo.scheduleUpdate.updateAt), | |
196 | privacy: videoInfo.scheduleUpdate.privacy || null | |
197 | }, sequelizeOptions) | |
198 | } | |
199 | ||
c158a5fa C |
200 | await autoBlacklistVideoIfNeeded({ |
201 | video, | |
202 | user, | |
203 | isRemote: false, | |
204 | isNew: true, | |
205 | transaction: t | |
206 | }) | |
207 | ||
208 | auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(videoCreated.toFormattedDetailsJSON())) | |
209 | logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid, lTags(videoCreated.uuid)) | |
210 | ||
211 | return { videoCreated } | |
212 | }) | |
213 | ||
3419e0e1 C |
214 | // Channel has a new content, set as updated |
215 | await videoCreated.VideoChannel.setAsUpdated() | |
216 | ||
c158a5fa | 217 | createTorrentFederate(video, videoFile) |
764b1a14 | 218 | .then(() => { |
0305db28 JB |
219 | if (video.state === VideoState.TO_MOVE_TO_EXTERNAL_STORAGE) { |
220 | return addMoveToObjectStorageJob(video) | |
221 | } | |
c158a5fa | 222 | |
0305db28 JB |
223 | if (video.state === VideoState.TO_TRANSCODE) { |
224 | return addOptimizeOrMergeAudioJob(videoCreated, videoFile, user) | |
225 | } | |
764b1a14 C |
226 | }) |
227 | .catch(err => logger.error('Cannot add optimize/merge audio job for %s.', videoCreated.uuid, { err, ...lTags(videoCreated.uuid) })) | |
c158a5fa C |
228 | |
229 | Hooks.runAction('action:api.video.uploaded', { video: videoCreated }) | |
230 | ||
231 | return res.json({ | |
232 | video: { | |
233 | id: videoCreated.id, | |
d4a8e7a6 | 234 | shortUUID: uuidToShort(videoCreated.uuid), |
c158a5fa C |
235 | uuid: videoCreated.uuid |
236 | } | |
237 | }) | |
238 | } | |
239 | ||
0305db28 | 240 | async function buildNewFile (videoPhysicalFile: express.VideoUploadFile) { |
c158a5fa | 241 | const videoFile = new VideoFileModel({ |
ea54cd04 | 242 | extname: getLowercaseExtension(videoPhysicalFile.filename), |
c158a5fa C |
243 | size: videoPhysicalFile.size, |
244 | videoStreamingPlaylistId: null, | |
245 | metadata: await getMetadataFromFile(videoPhysicalFile.path) | |
246 | }) | |
247 | ||
248 | if (videoFile.isAudio()) { | |
249 | videoFile.resolution = DEFAULT_AUDIO_RESOLUTION | |
250 | } else { | |
251 | videoFile.fps = await getVideoFileFPS(videoPhysicalFile.path) | |
679c12e6 | 252 | videoFile.resolution = (await getVideoFileResolution(videoPhysicalFile.path)).resolution |
c158a5fa C |
253 | } |
254 | ||
83903cb6 | 255 | videoFile.filename = generateWebTorrentVideoFilename(videoFile.resolution, videoFile.extname) |
c158a5fa C |
256 | |
257 | return videoFile | |
258 | } | |
259 | ||
260 | async function createTorrentAndSetInfoHashAsync (video: MVideo, fileArg: MVideoFile) { | |
261 | await createTorrentAndSetInfoHash(video, fileArg) | |
262 | ||
263 | // Refresh videoFile because the createTorrentAndSetInfoHash could be long | |
264 | const refreshedFile = await VideoFileModel.loadWithVideo(fileArg.id) | |
265 | // File does not exist anymore, remove the generated torrent | |
266 | if (!refreshedFile) return fileArg.removeTorrent() | |
267 | ||
268 | refreshedFile.infoHash = fileArg.infoHash | |
269 | refreshedFile.torrentFilename = fileArg.torrentFilename | |
270 | ||
271 | return refreshedFile.save() | |
272 | } | |
273 | ||
764b1a14 | 274 | function createTorrentFederate (video: MVideoFullLight, videoFile: MVideoFile) { |
c158a5fa | 275 | // Create the torrent file in async way because it could be long |
764b1a14 | 276 | return createTorrentAndSetInfoHashAsync(video, videoFile) |
c158a5fa C |
277 | .catch(err => logger.error('Cannot create torrent file for video %s', video.url, { err, ...lTags(video.uuid) })) |
278 | .then(() => VideoModel.loadAndPopulateAccountAndServerAndTags(video.id)) | |
279 | .then(refreshedVideo => { | |
280 | if (!refreshedVideo) return | |
281 | ||
282 | // Only federate and notify after the torrent creation | |
283 | Notifier.Instance.notifyOnNewVideoIfNeeded(refreshedVideo) | |
284 | ||
285 | return retryTransactionWrapper(() => { | |
286 | return sequelizeTypescript.transaction(t => federateVideoIfNeeded(refreshedVideo, true, t)) | |
287 | }) | |
288 | }) | |
289 | .catch(err => logger.error('Cannot federate or notify video creation %s', video.url, { err, ...lTags(video.uuid) })) | |
290 | } |