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 addMoveToObjectStorageJob,
12 addOptimizeOrMergeAudioJob,
13 buildLocalVideoFromReq,
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 { MVideoFile, MVideoFullLight } from '@server/types/models'
21 import { getLowercaseExtension } from '@shared/core-utils'
22 import { isAudioFile, uuidToShort } from '@shared/extra-utils'
23 import { HttpStatusCode, ManageVideoTorrentPayload, VideoCreate, VideoResolution, VideoState } from '@shared/models'
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 { 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 { federateVideoIfNeeded } from '../../../lib/activitypub/videos'
32 import { Notifier } from '../../../lib/notifier'
33 import { Hooks } from '../../../lib/plugins/hooks'
34 import { generateVideoMiniature } from '../../../lib/thumbnail'
35 import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist'
38 asyncRetryTransactionMiddleware,
40 videosAddLegacyValidator,
41 videosAddResumableInitValidator,
42 videosAddResumableValidator
43 } from '../../../middlewares'
44 import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update'
45 import { VideoModel } from '../../../models/video/video'
46 import { VideoFileModel } from '../../../models/video/video-file'
48 const lTags = loggerTagsFactory('api', 'video')
49 const auditLogger = auditLoggerFactory('videos')
50 const uploadRouter = express.Router()
52 const reqVideoFileAdd = createReqFiles(
53 [ 'videofile', 'thumbnailfile', 'previewfile' ],
54 { ...MIMETYPES.VIDEO.MIMETYPE_EXT, ...MIMETYPES.IMAGE.MIMETYPE_EXT }
57 const reqVideoFileAddResumable = createReqFiles(
58 [ 'thumbnailfile', 'previewfile' ],
59 MIMETYPES.IMAGE.MIMETYPE_EXT,
60 getResumableUploadPath()
63 uploadRouter.post('/upload',
64 openapiOperationDoc({ operationId: 'uploadLegacy' }),
67 asyncMiddleware(videosAddLegacyValidator),
68 asyncRetryTransactionMiddleware(addVideoLegacy)
71 uploadRouter.post('/upload-resumable',
72 openapiOperationDoc({ operationId: 'uploadResumableInit' }),
74 reqVideoFileAddResumable,
75 asyncMiddleware(videosAddResumableInitValidator),
79 uploadRouter.delete('/upload-resumable',
81 asyncMiddleware(deleteUploadResumableCache),
85 uploadRouter.put('/upload-resumable',
86 openapiOperationDoc({ operationId: 'uploadResumable' }),
88 uploadx.upload, // uploadx doesn't next() before the file upload completes
89 asyncMiddleware(videosAddResumableValidator),
90 asyncMiddleware(addVideoResumable)
93 // ---------------------------------------------------------------------------
99 // ---------------------------------------------------------------------------
101 async function addVideoLegacy (req: express.Request, res: express.Response) {
102 // Uploading the video could be long
103 // Set timeout to 10 minutes, as Express's default is 2 minutes
104 req.setTimeout(1000 * 60 * 10, () => {
105 logger.error('Video upload has timed out.')
107 status: HttpStatusCode.REQUEST_TIMEOUT_408,
108 message: 'Video upload has timed out.'
112 const videoPhysicalFile = req.files['videofile'][0]
113 const videoInfo: VideoCreate = req.body
114 const files = req.files
116 const response = await addVideo({ req, res, videoPhysicalFile, videoInfo, files })
118 return res.json(response)
121 async function addVideoResumable (req: express.Request, res: express.Response) {
122 const videoPhysicalFile = res.locals.videoFileResumable
123 const videoInfo = videoPhysicalFile.metadata
124 const files = { previewfile: videoInfo.previewfile }
126 const response = await addVideo({ req, res, videoPhysicalFile, videoInfo, files })
127 await Redis.Instance.setUploadSession(req.query.upload_id, response)
129 return res.json(response)
132 async function addVideo (options: {
134 res: express.Response
135 videoPhysicalFile: express.VideoUploadFile
136 videoInfo: VideoCreate
137 files: express.UploadFiles
139 const { req, res, videoPhysicalFile, videoInfo, files } = options
140 const videoChannel = res.locals.videoChannel
141 const user = res.locals.oauth.token.User
143 let videoData = buildLocalVideoFromReq(videoInfo, videoChannel.id)
144 videoData = await Hooks.wrapObject(videoData, 'filter:api.video.upload.video-attribute.result')
146 videoData.state = buildNextVideoState()
147 videoData.duration = videoPhysicalFile.duration // duration was added by a previous middleware
149 const video = new VideoModel(videoData) as MVideoFullLight
150 video.VideoChannel = videoChannel
151 video.url = getLocalVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
153 const videoFile = await buildNewFile(videoPhysicalFile)
155 // Move physical file
156 const destination = VideoPathManager.Instance.getFSVideoFileOutputPath(video, videoFile)
157 await move(videoPhysicalFile.path, destination)
158 // This is important in case if there is another attempt in the retry process
159 videoPhysicalFile.filename = basename(destination)
160 videoPhysicalFile.path = destination
162 const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
165 fallback: type => generateVideoMiniature({ video, videoFile, type })
168 const { videoCreated } = await sequelizeTypescript.transaction(async t => {
169 const sequelizeOptions = { transaction: t }
171 const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight
173 await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
174 await videoCreated.addAndSaveThumbnail(previewModel, t)
176 // Do not forget to add video channel information to the created video
177 videoCreated.VideoChannel = res.locals.videoChannel
179 videoFile.videoId = video.id
180 await videoFile.save(sequelizeOptions)
182 video.VideoFiles = [ videoFile ]
184 await setVideoTags({ video, tags: videoInfo.tags, transaction: t })
186 // Schedule an update in the future?
187 if (videoInfo.scheduleUpdate) {
188 await ScheduleVideoUpdateModel.create({
190 updateAt: new Date(videoInfo.scheduleUpdate.updateAt),
191 privacy: videoInfo.scheduleUpdate.privacy || null
195 await autoBlacklistVideoIfNeeded({
203 auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(videoCreated.toFormattedDetailsJSON()))
204 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid, lTags(videoCreated.uuid))
206 return { videoCreated }
209 // Channel has a new content, set as updated
210 await videoCreated.VideoChannel.setAsUpdated()
212 createTorrentFederate(videoCreated, videoFile)
214 logger.error('Cannot create torrent or federate video for %s.', videoCreated.uuid, { err, ...lTags(videoCreated.uuid) })
217 }).then(refreshedVideo => {
218 if (!refreshedVideo) return
220 if (refreshedVideo.state === VideoState.TO_MOVE_TO_EXTERNAL_STORAGE) {
221 return addMoveToObjectStorageJob({ video: refreshedVideo, previousVideoState: undefined })
224 if (refreshedVideo.state === VideoState.TO_TRANSCODE) {
225 return addOptimizeOrMergeAudioJob({ video: refreshedVideo, videoFile, user })
227 }).catch(err => logger.error('Cannot add optimize/merge audio job for %s.', videoCreated.uuid, { err, ...lTags(videoCreated.uuid) }))
229 Hooks.runAction('action:api.video.uploaded', { video: videoCreated, req, res })
234 shortUUID: uuidToShort(videoCreated.uuid),
235 uuid: videoCreated.uuid
240 async function buildNewFile (videoPhysicalFile: express.VideoUploadFile) {
241 const videoFile = new VideoFileModel({
242 extname: getLowercaseExtension(videoPhysicalFile.filename),
243 size: videoPhysicalFile.size,
244 videoStreamingPlaylistId: null,
245 metadata: await buildFileMetadata(videoPhysicalFile.path)
248 const probe = await ffprobePromise(videoPhysicalFile.path)
250 if (await isAudioFile(videoPhysicalFile.path, probe)) {
251 videoFile.resolution = VideoResolution.H_NOVIDEO
253 videoFile.fps = await getVideoStreamFPS(videoPhysicalFile.path, probe)
254 videoFile.resolution = (await getVideoStreamDimensionsInfo(videoPhysicalFile.path, probe)).resolution
257 videoFile.filename = generateWebTorrentVideoFilename(videoFile.resolution, videoFile.extname)
262 async function createTorrentFederate (video: MVideoFullLight, videoFile: MVideoFile) {
263 const payload: ManageVideoTorrentPayload = { videoId: video.id, videoFileId: videoFile.id, action: 'create' }
265 const job = await JobQueue.Instance.createJobWithPromise({ type: 'manage-video-torrent', payload })
268 const refreshedVideo = await VideoModel.loadAndPopulateAccountAndServerAndTags(video.id)
269 if (!refreshedVideo) return
271 // Only federate and notify after the torrent creation
272 Notifier.Instance.notifyOnNewVideoIfNeeded(refreshedVideo)
274 await retryTransactionWrapper(() => {
275 return sequelizeTypescript.transaction(t => federateVideoIfNeeded(refreshedVideo, true, t))
278 return refreshedVideo
281 async function deleteUploadResumableCache (req: express.Request, res: express.Response, next: express.NextFunction) {
282 await Redis.Instance.deleteUploadSession(req.query.upload_id)