]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/videos/upload.ts
Limit live bitrate
[github/Chocobozzz/PeerTube.git] / server / controllers / api / videos / upload.ts
CommitLineData
c158a5fa
C
1import * as express from 'express'
2import { move } from 'fs-extra'
ea54cd04 3import { getLowercaseExtension } from '@server/helpers/core-utils'
c158a5fa 4import { deleteResumableUploadMetaFile, getResumableUploadPath } from '@server/helpers/upload'
d4a8e7a6 5import { uuidToShort } from '@server/helpers/uuid'
c158a5fa
C
6import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent'
7import { getLocalVideoActivityPubUrl } from '@server/lib/activitypub/url'
8import { addOptimizeOrMergeAudioJob, buildLocalVideoFromReq, buildVideoThumbnailsFromReq, setVideoTags } from '@server/lib/video'
83903cb6 9import { generateWebTorrentVideoFilename, getVideoFilePath } from '@server/lib/video-paths'
1c627fd8 10import { openapiOperationDoc } from '@server/middlewares/doc'
c158a5fa
C
11import { MVideo, MVideoFile, MVideoFullLight } from '@server/types/models'
12import { uploadx } from '@uploadx/core'
13import { VideoCreate, VideoState } from '../../../../shared'
c0e8b12e 14import { HttpStatusCode } from '../../../../shared/models'
c158a5fa
C
15import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger'
16import { retryTransactionWrapper } from '../../../helpers/database-utils'
17import { createReqFiles } from '../../../helpers/express-utils'
18import { getMetadataFromFile, getVideoFileFPS, getVideoFileResolution } from '../../../helpers/ffprobe-utils'
19import { logger, loggerTagsFactory } from '../../../helpers/logger'
20import { CONFIG } from '../../../initializers/config'
21import { DEFAULT_AUDIO_RESOLUTION, MIMETYPES } from '../../../initializers/constants'
22import { sequelizeTypescript } from '../../../initializers/database'
23import { federateVideoIfNeeded } from '../../../lib/activitypub/videos'
24import { Notifier } from '../../../lib/notifier'
25import { Hooks } from '../../../lib/plugins/hooks'
26import { generateVideoMiniature } from '../../../lib/thumbnail'
27import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist'
28import {
29 asyncMiddleware,
30 asyncRetryTransactionMiddleware,
31 authenticate,
32 videosAddLegacyValidator,
33 videosAddResumableInitValidator,
34 videosAddResumableValidator
35} from '../../../middlewares'
36import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update'
37import { VideoModel } from '../../../models/video/video'
38import { VideoFileModel } from '../../../models/video/video-file'
39
40const lTags = loggerTagsFactory('api', 'video')
41const auditLogger = auditLoggerFactory('videos')
42const uploadRouter = express.Router()
43const uploadxMiddleware = uploadx.upload({ directory: getResumableUploadPath() })
44
45const reqVideoFileAdd = createReqFiles(
46 [ 'videofile', 'thumbnailfile', 'previewfile' ],
47 Object.assign({}, MIMETYPES.VIDEO.MIMETYPE_EXT, MIMETYPES.IMAGE.MIMETYPE_EXT),
48 {
49 videofile: CONFIG.STORAGE.TMP_DIR,
50 thumbnailfile: CONFIG.STORAGE.TMP_DIR,
51 previewfile: CONFIG.STORAGE.TMP_DIR
52 }
53)
54
55const reqVideoFileAddResumable = createReqFiles(
56 [ 'thumbnailfile', 'previewfile' ],
57 MIMETYPES.IMAGE.MIMETYPE_EXT,
58 {
59 thumbnailfile: getResumableUploadPath(),
60 previewfile: getResumableUploadPath()
61 }
62)
63
64uploadRouter.post('/upload',
1c627fd8 65 openapiOperationDoc({ operationId: 'uploadLegacy' }),
c158a5fa
C
66 authenticate,
67 reqVideoFileAdd,
68 asyncMiddleware(videosAddLegacyValidator),
69 asyncRetryTransactionMiddleware(addVideoLegacy)
70)
71
72uploadRouter.post('/upload-resumable',
1c627fd8 73 openapiOperationDoc({ operationId: 'uploadResumableInit' }),
c158a5fa
C
74 authenticate,
75 reqVideoFileAddResumable,
76 asyncMiddleware(videosAddResumableInitValidator),
77 uploadxMiddleware
78)
79
80uploadRouter.delete('/upload-resumable',
81 authenticate,
82 uploadxMiddleware
83)
84
85uploadRouter.put('/upload-resumable',
1c627fd8 86 openapiOperationDoc({ operationId: 'uploadResumable' }),
c158a5fa
C
87 authenticate,
88 uploadxMiddleware, // uploadx doesn't use call next() before the file upload completes
89 asyncMiddleware(videosAddResumableValidator),
90 asyncMiddleware(addVideoResumable)
91)
92
93// ---------------------------------------------------------------------------
94
95export {
96 uploadRouter
97}
98
99// ---------------------------------------------------------------------------
100
101export 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, () => {
76148b27
RK
105 logger.error('Video upload has timed out.')
106 return res.fail({
107 status: HttpStatusCode.REQUEST_TIMEOUT_408,
108 message: 'Video upload has timed out.'
109 })
c158a5fa
C
110 })
111
112 const videoPhysicalFile = req.files['videofile'][0]
113 const videoInfo: VideoCreate = req.body
114 const files = req.files
115
116 return addVideo({ res, videoPhysicalFile, videoInfo, files })
117}
118
119export 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 }
123
124 // Don't need the meta file anymore
125 await deleteResumableUploadMetaFile(videoPhysicalFile.path)
126
127 return addVideo({ res, videoPhysicalFile, videoInfo, files })
128}
129
130async function addVideo (options: {
131 res: express.Response
132 videoPhysicalFile: express.VideoUploadFile
133 videoInfo: VideoCreate
134 files: express.UploadFiles
135}) {
136 const { res, videoPhysicalFile, videoInfo, files } = options
137 const videoChannel = res.locals.videoChannel
138 const user = res.locals.oauth.token.User
139
140 const videoData = buildLocalVideoFromReq(videoInfo, videoChannel.id)
141
142 videoData.state = CONFIG.TRANSCODING.ENABLED
143 ? VideoState.TO_TRANSCODE
144 : VideoState.PUBLISHED
145
146 videoData.duration = videoPhysicalFile.duration // duration was added by a previous middleware
147
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
151
152 const videoFile = await buildNewFile(video, videoPhysicalFile)
153
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
160
161 const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
162 video,
163 files,
164 fallback: type => generateVideoMiniature({ video, videoFile, type })
165 })
166
167 const { videoCreated } = await sequelizeTypescript.transaction(async t => {
168 const sequelizeOptions = { transaction: t }
169
170 const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight
171
172 await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
173 await videoCreated.addAndSaveThumbnail(previewModel, t)
174
175 // Do not forget to add video channel information to the created video
176 videoCreated.VideoChannel = res.locals.videoChannel
177
178 videoFile.videoId = video.id
179 await videoFile.save(sequelizeOptions)
180
181 video.VideoFiles = [ videoFile ]
182
183 await setVideoTags({ video, tags: videoInfo.tags, transaction: t })
184
185 // Schedule an update in the future?
186 if (videoInfo.scheduleUpdate) {
187 await ScheduleVideoUpdateModel.create({
188 videoId: video.id,
189 updateAt: new Date(videoInfo.scheduleUpdate.updateAt),
190 privacy: videoInfo.scheduleUpdate.privacy || null
191 }, sequelizeOptions)
192 }
193
194 // Channel has a new content, set as updated
195 await videoCreated.VideoChannel.setAsUpdated(t)
196
197 await autoBlacklistVideoIfNeeded({
198 video,
199 user,
200 isRemote: false,
201 isNew: true,
202 transaction: t
203 })
204
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))
207
208 return { videoCreated }
209 })
210
211 createTorrentFederate(video, videoFile)
764b1a14
C
212 .then(() => {
213 if (video.state !== VideoState.TO_TRANSCODE) return
c158a5fa 214
764b1a14
C
215 return addOptimizeOrMergeAudioJob(videoCreated, videoFile, user)
216 })
217 .catch(err => logger.error('Cannot add optimize/merge audio job for %s.', videoCreated.uuid, { err, ...lTags(videoCreated.uuid) }))
c158a5fa
C
218
219 Hooks.runAction('action:api.video.uploaded', { video: videoCreated })
220
221 return res.json({
222 video: {
223 id: videoCreated.id,
d4a8e7a6 224 shortUUID: uuidToShort(videoCreated.uuid),
c158a5fa
C
225 uuid: videoCreated.uuid
226 }
227 })
228}
229
230async function buildNewFile (video: MVideo, videoPhysicalFile: express.VideoUploadFile) {
231 const videoFile = new VideoFileModel({
ea54cd04 232 extname: getLowercaseExtension(videoPhysicalFile.filename),
c158a5fa
C
233 size: videoPhysicalFile.size,
234 videoStreamingPlaylistId: null,
235 metadata: await getMetadataFromFile(videoPhysicalFile.path)
236 })
237
238 if (videoFile.isAudio()) {
239 videoFile.resolution = DEFAULT_AUDIO_RESOLUTION
240 } else {
241 videoFile.fps = await getVideoFileFPS(videoPhysicalFile.path)
242 videoFile.resolution = (await getVideoFileResolution(videoPhysicalFile.path)).videoFileResolution
243 }
244
83903cb6 245 videoFile.filename = generateWebTorrentVideoFilename(videoFile.resolution, videoFile.extname)
c158a5fa
C
246
247 return videoFile
248}
249
250async function createTorrentAndSetInfoHashAsync (video: MVideo, fileArg: MVideoFile) {
251 await createTorrentAndSetInfoHash(video, fileArg)
252
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()
257
258 refreshedFile.infoHash = fileArg.infoHash
259 refreshedFile.torrentFilename = fileArg.torrentFilename
260
261 return refreshedFile.save()
262}
263
764b1a14 264function createTorrentFederate (video: MVideoFullLight, videoFile: MVideoFile) {
c158a5fa 265 // Create the torrent file in async way because it could be long
764b1a14 266 return createTorrentAndSetInfoHashAsync(video, videoFile)
c158a5fa
C
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
271
272 // Only federate and notify after the torrent creation
273 Notifier.Instance.notifyOnNewVideoIfNeeded(refreshedVideo)
274
275 return retryTransactionWrapper(() => {
276 return sequelizeTypescript.transaction(t => federateVideoIfNeeded(refreshedVideo, true, t))
277 })
278 })
279 .catch(err => logger.error('Cannot federate or notify video creation %s', video.url, { err, ...lTags(video.uuid) }))
280}