1 import * as express from 'express'
2 import { move } from 'fs-extra'
3 import { getLowercaseExtension } from '@server/helpers/core-utils'
4 import { deleteResumableUploadMetaFile, getResumableUploadPath } from '@server/helpers/upload'
5 import { uuidToShort } from '@server/helpers/uuid'
6 import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent'
7 import { getLocalVideoActivityPubUrl } from '@server/lib/activitypub/url'
8 import { addOptimizeOrMergeAudioJob, buildLocalVideoFromReq, buildVideoThumbnailsFromReq, setVideoTags } from '@server/lib/video'
9 import { generateWebTorrentVideoFilename, getVideoFilePath } from '@server/lib/video-paths'
10 import { openapiOperationDoc } from '@server/middlewares/doc'
11 import { MVideo, MVideoFile, MVideoFullLight } from '@server/types/models'
12 import { uploadx } from '@uploadx/core'
13 import { VideoCreate, VideoState } from '../../../../shared'
14 import { HttpStatusCode } from '../../../../shared/models'
15 import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger'
16 import { retryTransactionWrapper } from '../../../helpers/database-utils'
17 import { createReqFiles } from '../../../helpers/express-utils'
18 import { getMetadataFromFile, getVideoFileFPS, getVideoFileResolution } from '../../../helpers/ffprobe-utils'
19 import { logger, loggerTagsFactory } from '../../../helpers/logger'
20 import { CONFIG } from '../../../initializers/config'
21 import { DEFAULT_AUDIO_RESOLUTION, MIMETYPES } from '../../../initializers/constants'
22 import { sequelizeTypescript } from '../../../initializers/database'
23 import { federateVideoIfNeeded } from '../../../lib/activitypub/videos'
24 import { Notifier } from '../../../lib/notifier'
25 import { Hooks } from '../../../lib/plugins/hooks'
26 import { generateVideoMiniature } from '../../../lib/thumbnail'
27 import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist'
30 asyncRetryTransactionMiddleware,
32 videosAddLegacyValidator,
33 videosAddResumableInitValidator,
34 videosAddResumableValidator
35 } from '../../../middlewares'
36 import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update'
37 import { VideoModel } from '../../../models/video/video'
38 import { VideoFileModel } from '../../../models/video/video-file'
40 const lTags = loggerTagsFactory('api', 'video')
41 const auditLogger = auditLoggerFactory('videos')
42 const uploadRouter = express.Router()
43 const uploadxMiddleware = uploadx.upload({ directory: getResumableUploadPath() })
45 const reqVideoFileAdd = createReqFiles(
46 [ 'videofile', 'thumbnailfile', 'previewfile' ],
47 Object.assign({}, MIMETYPES.VIDEO.MIMETYPE_EXT, MIMETYPES.IMAGE.MIMETYPE_EXT),
49 videofile: CONFIG.STORAGE.TMP_DIR,
50 thumbnailfile: CONFIG.STORAGE.TMP_DIR,
51 previewfile: CONFIG.STORAGE.TMP_DIR
55 const reqVideoFileAddResumable = createReqFiles(
56 [ 'thumbnailfile', 'previewfile' ],
57 MIMETYPES.IMAGE.MIMETYPE_EXT,
59 thumbnailfile: getResumableUploadPath(),
60 previewfile: getResumableUploadPath()
64 uploadRouter.post('/upload',
65 openapiOperationDoc({ operationId: 'uploadLegacy' }),
68 asyncMiddleware(videosAddLegacyValidator),
69 asyncRetryTransactionMiddleware(addVideoLegacy)
72 uploadRouter.post('/upload-resumable',
73 openapiOperationDoc({ operationId: 'uploadResumableInit' }),
75 reqVideoFileAddResumable,
76 asyncMiddleware(videosAddResumableInitValidator),
80 uploadRouter.delete('/upload-resumable',
85 uploadRouter.put('/upload-resumable',
86 openapiOperationDoc({ operationId: 'uploadResumable' }),
88 uploadxMiddleware, // uploadx doesn't use call next() before the file upload completes
89 asyncMiddleware(videosAddResumableValidator),
90 asyncMiddleware(addVideoResumable)
93 // ---------------------------------------------------------------------------
99 // ---------------------------------------------------------------------------
101 export 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 return addVideo({ res, videoPhysicalFile, videoInfo, files })
119 export 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 // Don't need the meta file anymore
125 await deleteResumableUploadMetaFile(videoPhysicalFile.path)
127 return addVideo({ res, videoPhysicalFile, videoInfo, files })
130 async function addVideo (options: {
131 res: express.Response
132 videoPhysicalFile: express.VideoUploadFile
133 videoInfo: VideoCreate
134 files: express.UploadFiles
136 const { res, videoPhysicalFile, videoInfo, files } = options
137 const videoChannel = res.locals.videoChannel
138 const user = res.locals.oauth.token.User
140 const videoData = buildLocalVideoFromReq(videoInfo, videoChannel.id)
142 videoData.state = CONFIG.TRANSCODING.ENABLED
143 ? VideoState.TO_TRANSCODE
144 : VideoState.PUBLISHED
146 videoData.duration = videoPhysicalFile.duration // duration was added by a previous middleware
148 const video = new VideoModel(videoData) as MVideoFullLight
149 video.VideoChannel = videoChannel
150 video.url = getLocalVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
152 const videoFile = await buildNewFile(video, videoPhysicalFile)
154 // Move physical file
155 const destination = getVideoFilePath(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 = getVideoFilePath(video, videoFile)
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 setVideoTags({ video, tags: videoInfo.tags, transaction: t })
185 // Schedule an update in the future?
186 if (videoInfo.scheduleUpdate) {
187 await ScheduleVideoUpdateModel.create({
189 updateAt: new Date(videoInfo.scheduleUpdate.updateAt),
190 privacy: videoInfo.scheduleUpdate.privacy || null
194 // Channel has a new content, set as updated
195 await videoCreated.VideoChannel.setAsUpdated(t)
197 await autoBlacklistVideoIfNeeded({
205 auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(videoCreated.toFormattedDetailsJSON()))
206 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid, lTags(videoCreated.uuid))
208 return { videoCreated }
211 createTorrentFederate(video, videoFile)
213 if (video.state !== VideoState.TO_TRANSCODE) return
215 return addOptimizeOrMergeAudioJob(videoCreated, videoFile, user)
217 .catch(err => logger.error('Cannot add optimize/merge audio job for %s.', videoCreated.uuid, { err, ...lTags(videoCreated.uuid) }))
219 Hooks.runAction('action:api.video.uploaded', { video: videoCreated })
224 shortUUID: uuidToShort(videoCreated.uuid),
225 uuid: videoCreated.uuid
230 async function buildNewFile (video: MVideo, videoPhysicalFile: express.VideoUploadFile) {
231 const videoFile = new VideoFileModel({
232 extname: getLowercaseExtension(videoPhysicalFile.filename),
233 size: videoPhysicalFile.size,
234 videoStreamingPlaylistId: null,
235 metadata: await getMetadataFromFile(videoPhysicalFile.path)
238 if (videoFile.isAudio()) {
239 videoFile.resolution = DEFAULT_AUDIO_RESOLUTION
241 videoFile.fps = await getVideoFileFPS(videoPhysicalFile.path)
242 videoFile.resolution = (await getVideoFileResolution(videoPhysicalFile.path)).videoFileResolution
245 videoFile.filename = generateWebTorrentVideoFilename(videoFile.resolution, videoFile.extname)
250 async function createTorrentAndSetInfoHashAsync (video: MVideo, fileArg: MVideoFile) {
251 await createTorrentAndSetInfoHash(video, fileArg)
253 // Refresh videoFile because the createTorrentAndSetInfoHash could be long
254 const refreshedFile = await VideoFileModel.loadWithVideo(fileArg.id)
255 // File does not exist anymore, remove the generated torrent
256 if (!refreshedFile) return fileArg.removeTorrent()
258 refreshedFile.infoHash = fileArg.infoHash
259 refreshedFile.torrentFilename = fileArg.torrentFilename
261 return refreshedFile.save()
264 function createTorrentFederate (video: MVideoFullLight, videoFile: MVideoFile) {
265 // Create the torrent file in async way because it could be long
266 return createTorrentAndSetInfoHashAsync(video, videoFile)
267 .catch(err => logger.error('Cannot create torrent file for video %s', video.url, { err, ...lTags(video.uuid) }))
268 .then(() => VideoModel.loadAndPopulateAccountAndServerAndTags(video.id))
269 .then(refreshedVideo => {
270 if (!refreshedVideo) return
272 // Only federate and notify after the torrent creation
273 Notifier.Instance.notifyOnNewVideoIfNeeded(refreshedVideo)
275 return retryTransactionWrapper(() => {
276 return sequelizeTypescript.transaction(t => federateVideoIfNeeded(refreshedVideo, true, t))
279 .catch(err => logger.error('Cannot federate or notify video creation %s', video.url, { err, ...lTags(video.uuid) }))