]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/videos/upload.ts
Improve target bitrate calculation
[github/Chocobozzz/PeerTube.git] / server / controllers / api / videos / upload.ts
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'
28 import {
29 asyncMiddleware,
30 asyncRetryTransactionMiddleware,
31 authenticate,
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'
39
40 const lTags = loggerTagsFactory('api', 'video')
41 const auditLogger = auditLoggerFactory('videos')
42 const uploadRouter = express.Router()
43 const uploadxMiddleware = uploadx.upload({ directory: getResumableUploadPath() })
44
45 const 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
55 const reqVideoFileAddResumable = createReqFiles(
56 [ 'thumbnailfile', 'previewfile' ],
57 MIMETYPES.IMAGE.MIMETYPE_EXT,
58 {
59 thumbnailfile: getResumableUploadPath(),
60 previewfile: getResumableUploadPath()
61 }
62 )
63
64 uploadRouter.post('/upload',
65 openapiOperationDoc({ operationId: 'uploadLegacy' }),
66 authenticate,
67 reqVideoFileAdd,
68 asyncMiddleware(videosAddLegacyValidator),
69 asyncRetryTransactionMiddleware(addVideoLegacy)
70 )
71
72 uploadRouter.post('/upload-resumable',
73 openapiOperationDoc({ operationId: 'uploadResumableInit' }),
74 authenticate,
75 reqVideoFileAddResumable,
76 asyncMiddleware(videosAddResumableInitValidator),
77 uploadxMiddleware
78 )
79
80 uploadRouter.delete('/upload-resumable',
81 authenticate,
82 uploadxMiddleware
83 )
84
85 uploadRouter.put('/upload-resumable',
86 openapiOperationDoc({ operationId: 'uploadResumable' }),
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
95 export {
96 uploadRouter
97 }
98
99 // ---------------------------------------------------------------------------
100
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.')
106 return res.fail({
107 status: HttpStatusCode.REQUEST_TIMEOUT_408,
108 message: 'Video upload has timed out.'
109 })
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
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 }
123
124 // Don't need the meta file anymore
125 await deleteResumableUploadMetaFile(videoPhysicalFile.path)
126
127 return addVideo({ res, videoPhysicalFile, videoInfo, files })
128 }
129
130 async 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)
212 .then(() => {
213 if (video.state !== VideoState.TO_TRANSCODE) return
214
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) }))
218
219 Hooks.runAction('action:api.video.uploaded', { video: videoCreated })
220
221 return res.json({
222 video: {
223 id: videoCreated.id,
224 shortUUID: uuidToShort(videoCreated.uuid),
225 uuid: videoCreated.uuid
226 }
227 })
228 }
229
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)
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)).resolution
243 }
244
245 videoFile.filename = generateWebTorrentVideoFilename(videoFile.resolution, videoFile.extname)
246
247 return videoFile
248 }
249
250 async 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
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
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 }