]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - server/controllers/api/videos/upload.ts
Fix benchmark ci
[github/Chocobozzz/PeerTube.git] / server / controllers / api / videos / upload.ts
... / ...
CommitLineData
1import express from 'express'
2import { move } from 'fs-extra'
3import { basename } from 'path'
4import { getLowercaseExtension } from '@server/helpers/core-utils'
5import { getResumableUploadPath } from '@server/helpers/upload'
6import { uuidToShort } from '@server/helpers/uuid'
7import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent'
8import { getLocalVideoActivityPubUrl } from '@server/lib/activitypub/url'
9import { generateWebTorrentVideoFilename } from '@server/lib/paths'
10import { Redis } from '@server/lib/redis'
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'
20import { openapiOperationDoc } from '@server/middlewares/doc'
21import { MVideo, MVideoFile, MVideoFullLight } from '@server/types/models'
22import { Uploadx } from '@uploadx/core'
23import { VideoCreate, VideoState } from '../../../../shared'
24import { HttpStatusCode } from '../../../../shared/models'
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,
44 videosResumableUploadIdValidator,
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()
54
55const uploadx = new Uploadx({ directory: getResumableUploadPath() })
56uploadx.getUserId = (_, res: express.Response) => res.locals.oauth?.token.user.id
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',
78 openapiOperationDoc({ operationId: 'uploadLegacy' }),
79 authenticate,
80 reqVideoFileAdd,
81 asyncMiddleware(videosAddLegacyValidator),
82 asyncRetryTransactionMiddleware(addVideoLegacy)
83)
84
85uploadRouter.post('/upload-resumable',
86 openapiOperationDoc({ operationId: 'uploadResumableInit' }),
87 authenticate,
88 reqVideoFileAddResumable,
89 asyncMiddleware(videosAddResumableInitValidator),
90 uploadx.upload
91)
92
93uploadRouter.delete('/upload-resumable',
94 authenticate,
95 videosResumableUploadIdValidator,
96 asyncMiddleware(deleteUploadResumableCache),
97 uploadx.upload
98)
99
100uploadRouter.put('/upload-resumable',
101 openapiOperationDoc({ operationId: 'uploadResumable' }),
102 authenticate,
103 videosResumableUploadIdValidator,
104 uploadx.upload, // uploadx doesn't next() before the file upload completes
105 asyncMiddleware(videosAddResumableValidator),
106 asyncMiddleware(addVideoResumable)
107)
108
109// ---------------------------------------------------------------------------
110
111export {
112 uploadRouter
113}
114
115// ---------------------------------------------------------------------------
116
117async function addVideoLegacy (req: express.Request, res: express.Response) {
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, () => {
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 })
126 })
127
128 const videoPhysicalFile = req.files['videofile'][0]
129 const videoInfo: VideoCreate = req.body
130 const files = req.files
131
132 const response = await addVideo({ req, res, videoPhysicalFile, videoInfo, files })
133
134 return res.json(response)
135}
136
137async function addVideoResumable (req: express.Request, res: express.Response) {
138 const videoPhysicalFile = res.locals.videoFileResumable
139 const videoInfo = videoPhysicalFile.metadata
140 const files = { previewfile: videoInfo.previewfile }
141
142 const response = await addVideo({ req, res, videoPhysicalFile, videoInfo, files })
143 await Redis.Instance.setUploadSession(req.query.upload_id, response)
144
145 return res.json(response)
146}
147
148async function addVideo (options: {
149 req: express.Request
150 res: express.Response
151 videoPhysicalFile: express.VideoUploadFile
152 videoInfo: VideoCreate
153 files: express.UploadFiles
154}) {
155 const { req, res, videoPhysicalFile, videoInfo, files } = options
156 const videoChannel = res.locals.videoChannel
157 const user = res.locals.oauth.token.User
158
159 const videoData = buildLocalVideoFromReq(videoInfo, videoChannel.id)
160
161 videoData.state = buildNextVideoState()
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
168 const videoFile = await buildNewFile(videoPhysicalFile)
169
170 // Move physical file
171 const destination = VideoPathManager.Instance.getFSVideoFileOutputPath(video, videoFile)
172 await move(videoPhysicalFile.path, destination)
173 // This is important in case if there is another attempt in the retry process
174 videoPhysicalFile.filename = basename(destination)
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
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
224 // Channel has a new content, set as updated
225 await videoCreated.VideoChannel.setAsUpdated()
226
227 createTorrentFederate(video, videoFile)
228 .then(() => {
229 if (video.state === VideoState.TO_MOVE_TO_EXTERNAL_STORAGE) {
230 return addMoveToObjectStorageJob(video)
231 }
232
233 if (video.state === VideoState.TO_TRANSCODE) {
234 return addOptimizeOrMergeAudioJob(videoCreated, videoFile, user)
235 }
236 })
237 .catch(err => logger.error('Cannot add optimize/merge audio job for %s.', videoCreated.uuid, { err, ...lTags(videoCreated.uuid) }))
238
239 Hooks.runAction('action:api.video.uploaded', { video: videoCreated, req, res })
240
241 return {
242 video: {
243 id: videoCreated.id,
244 shortUUID: uuidToShort(videoCreated.uuid),
245 uuid: videoCreated.uuid
246 }
247 }
248}
249
250async function buildNewFile (videoPhysicalFile: express.VideoUploadFile) {
251 const videoFile = new VideoFileModel({
252 extname: getLowercaseExtension(videoPhysicalFile.filename),
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)
262 videoFile.resolution = (await getVideoFileResolution(videoPhysicalFile.path)).resolution
263 }
264
265 videoFile.filename = generateWebTorrentVideoFilename(videoFile.resolution, videoFile.extname)
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
284function createTorrentFederate (video: MVideoFullLight, videoFile: MVideoFile) {
285 // Create the torrent file in async way because it could be long
286 return createTorrentAndSetInfoHashAsync(video, videoFile)
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}
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}