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