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 { getLocalVideoActivityPubUrl } from '@server/lib/activitypub/url'
6 import { JobQueue } from '@server/lib/job-queue'
7 import { generateWebTorrentVideoFilename } from '@server/lib/paths'
8 import { Redis } from '@server/lib/redis'
9 import { uploadx } from '@server/lib/uploadx'
11 buildLocalVideoFromReq,
12 buildMoveToObjectStorageJob,
13 buildOptimizeOrMergeAudioJob,
14 buildVideoThumbnailsFromReq,
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 { VideoSourceModel } from '@server/models/video/video-source'
21 import { MUserId, MVideoFile, MVideoFullLight } from '@server/types/models'
22 import { getLowercaseExtension } from '@shared/core-utils'
23 import { isAudioFile, uuidToShort } from '@shared/extra-utils'
24 import { HttpStatusCode, VideoCreate, VideoResolution, VideoState } from '@shared/models'
25 import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger'
26 import { createReqFiles } from '../../../helpers/express-utils'
27 import { buildFileMetadata, ffprobePromise, getVideoStreamDimensionsInfo, getVideoStreamFPS } from '../../../helpers/ffmpeg'
28 import { logger, loggerTagsFactory } from '../../../helpers/logger'
29 import { MIMETYPES } from '../../../initializers/constants'
30 import { sequelizeTypescript } from '../../../initializers/database'
31 import { Hooks } from '../../../lib/plugins/hooks'
32 import { generateVideoMiniature } from '../../../lib/thumbnail'
33 import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist'
36 asyncRetryTransactionMiddleware,
38 videosAddLegacyValidator,
39 videosAddResumableInitValidator,
40 videosAddResumableValidator
41 } from '../../../middlewares'
42 import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update'
43 import { VideoModel } from '../../../models/video/video'
44 import { VideoFileModel } from '../../../models/video/video-file'
46 const lTags = loggerTagsFactory('api', 'video')
47 const auditLogger = auditLoggerFactory('videos')
48 const uploadRouter = express.Router()
50 const reqVideoFileAdd = createReqFiles(
51 [ 'videofile', 'thumbnailfile', 'previewfile' ],
52 { ...MIMETYPES.VIDEO.MIMETYPE_EXT, ...MIMETYPES.IMAGE.MIMETYPE_EXT }
55 const reqVideoFileAddResumable = createReqFiles(
56 [ 'thumbnailfile', 'previewfile' ],
57 MIMETYPES.IMAGE.MIMETYPE_EXT,
58 getResumableUploadPath()
61 uploadRouter.post('/upload',
62 openapiOperationDoc({ operationId: 'uploadLegacy' }),
65 asyncMiddleware(videosAddLegacyValidator),
66 asyncRetryTransactionMiddleware(addVideoLegacy)
69 uploadRouter.post('/upload-resumable',
70 openapiOperationDoc({ operationId: 'uploadResumableInit' }),
72 reqVideoFileAddResumable,
73 asyncMiddleware(videosAddResumableInitValidator),
77 uploadRouter.delete('/upload-resumable',
79 asyncMiddleware(deleteUploadResumableCache),
83 uploadRouter.put('/upload-resumable',
84 openapiOperationDoc({ operationId: 'uploadResumable' }),
86 uploadx.upload, // uploadx doesn't next() before the file upload completes
87 asyncMiddleware(videosAddResumableValidator),
88 asyncMiddleware(addVideoResumable)
91 // ---------------------------------------------------------------------------
97 // ---------------------------------------------------------------------------
99 async function addVideoLegacy (req: express.Request, res: express.Response) {
100 // Uploading the video could be long
101 // Set timeout to 10 minutes, as Express's default is 2 minutes
102 req.setTimeout(1000 * 60 * 10, () => {
103 logger.error('Video upload has timed out.')
105 status: HttpStatusCode.REQUEST_TIMEOUT_408,
106 message: 'Video upload has timed out.'
110 const videoPhysicalFile = req.files['videofile'][0]
111 const videoInfo: VideoCreate = req.body
112 const files = req.files
114 const response = await addVideo({ req, res, videoPhysicalFile, videoInfo, files })
116 return res.json(response)
119 async function addVideoResumable (req: express.Request, res: express.Response) {
120 const videoPhysicalFile = res.locals.videoFileResumable
121 const videoInfo = videoPhysicalFile.metadata
122 const files = { previewfile: videoInfo.previewfile }
124 const response = await addVideo({ req, res, videoPhysicalFile, videoInfo, files })
125 await Redis.Instance.setUploadSession(req.query.upload_id, response)
127 return res.json(response)
130 async function addVideo (options: {
132 res: express.Response
133 videoPhysicalFile: express.VideoUploadFile
134 videoInfo: VideoCreate
135 files: express.UploadFiles
137 const { req, res, videoPhysicalFile, videoInfo, files } = options
138 const videoChannel = res.locals.videoChannel
139 const user = res.locals.oauth.token.User
141 let videoData = buildLocalVideoFromReq(videoInfo, videoChannel.id)
142 videoData = await Hooks.wrapObject(videoData, 'filter:api.video.upload.video-attribute.result')
144 videoData.state = buildNextVideoState()
145 videoData.duration = videoPhysicalFile.duration // duration was added by a previous middleware
147 const video = new VideoModel(videoData) as MVideoFullLight
148 video.VideoChannel = videoChannel
149 video.url = getLocalVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
151 const videoFile = await buildNewFile(videoPhysicalFile)
152 const originalFilename = videoPhysicalFile.originalname
154 // Move physical file
155 const destination = VideoPathManager.Instance.getFSVideoFileOutputPath(video, videoFile)
156 await move(videoPhysicalFile.path, destination)
157 // This is important in case if there is another attempt in the retry process
158 videoPhysicalFile.filename = basename(destination)
159 videoPhysicalFile.path = destination
161 const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
164 fallback: type => generateVideoMiniature({ video, videoFile, type })
167 const { videoCreated } = await sequelizeTypescript.transaction(async t => {
168 const sequelizeOptions = { transaction: t }
170 const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight
172 await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
173 await videoCreated.addAndSaveThumbnail(previewModel, t)
175 // Do not forget to add video channel information to the created video
176 videoCreated.VideoChannel = res.locals.videoChannel
178 videoFile.videoId = video.id
179 await videoFile.save(sequelizeOptions)
181 video.VideoFiles = [ videoFile ]
183 await VideoSourceModel.create({
184 filename: originalFilename,
186 }, { transaction: t })
188 await setVideoTags({ video, tags: videoInfo.tags, transaction: t })
190 // Schedule an update in the future?
191 if (videoInfo.scheduleUpdate) {
192 await ScheduleVideoUpdateModel.create({
194 updateAt: new Date(videoInfo.scheduleUpdate.updateAt),
195 privacy: videoInfo.scheduleUpdate.privacy || null
199 await autoBlacklistVideoIfNeeded({
207 auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(videoCreated.toFormattedDetailsJSON()))
208 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid, lTags(videoCreated.uuid))
210 return { videoCreated }
213 // Channel has a new content, set as updated
214 await videoCreated.VideoChannel.setAsUpdated()
216 addVideoJobsAfterUpload(videoCreated, videoFile, user)
217 .catch(err => logger.error('Cannot build new video jobs of %s.', videoCreated.uuid, { err, ...lTags(videoCreated.uuid) }))
219 Hooks.runAction('action:api.video.uploaded', { video: videoCreated, req, res })
224 shortUUID: uuidToShort(videoCreated.uuid),
225 uuid: videoCreated.uuid
230 async function buildNewFile (videoPhysicalFile: express.VideoUploadFile) {
231 const videoFile = new VideoFileModel({
232 extname: getLowercaseExtension(videoPhysicalFile.filename),
233 size: videoPhysicalFile.size,
234 videoStreamingPlaylistId: null,
235 metadata: await buildFileMetadata(videoPhysicalFile.path)
238 const probe = await ffprobePromise(videoPhysicalFile.path)
240 if (await isAudioFile(videoPhysicalFile.path, probe)) {
241 videoFile.resolution = VideoResolution.H_NOVIDEO
243 videoFile.fps = await getVideoStreamFPS(videoPhysicalFile.path, probe)
244 videoFile.resolution = (await getVideoStreamDimensionsInfo(videoPhysicalFile.path, probe)).resolution
247 videoFile.filename = generateWebTorrentVideoFilename(videoFile.resolution, videoFile.extname)
252 async function addVideoJobsAfterUpload (video: MVideoFullLight, videoFile: MVideoFile, user: MUserId) {
253 return JobQueue.Instance.createSequentialJobFlow(
255 type: 'manage-video-torrent' as 'manage-video-torrent',
258 videoFileId: videoFile.id,
263 type: 'federate-video' as 'federate-video',
265 videoUUID: video.uuid,
270 video.state === VideoState.TO_MOVE_TO_EXTERNAL_STORAGE
271 ? await buildMoveToObjectStorageJob({ video, previousVideoState: undefined })
274 video.state === VideoState.TO_TRANSCODE
275 ? await buildOptimizeOrMergeAudioJob({ video, videoFile, user })
280 async function deleteUploadResumableCache (req: express.Request, res: express.Response, next: express.NextFunction) {
281 await Redis.Instance.deleteUploadSession(req.query.upload_id)