]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/videos/upload.ts
store uploaded video filename (#4885)
[github/Chocobozzz/PeerTube.git] / server / controllers / api / videos / upload.ts
CommitLineData
41fb13c3 1import express from 'express'
c158a5fa 2import { move } from 'fs-extra'
0305db28 3import { basename } from 'path'
790c2837 4import { getResumableUploadPath } from '@server/helpers/upload'
c158a5fa 5import { getLocalVideoActivityPubUrl } from '@server/lib/activitypub/url'
f012319a 6import { JobQueue } from '@server/lib/job-queue'
0305db28 7import { generateWebTorrentVideoFilename } from '@server/lib/paths'
276250f0 8import { Redis } from '@server/lib/redis'
6d472b40 9import { uploadx } from '@server/lib/uploadx'
0305db28
JB
10import {
11 addMoveToObjectStorageJob,
12 addOptimizeOrMergeAudioJob,
13 buildLocalVideoFromReq,
14 buildVideoThumbnailsFromReq,
15 setVideoTags
16} from '@server/lib/video'
17import { VideoPathManager } from '@server/lib/video-path-manager'
18import { buildNextVideoState } from '@server/lib/video-state'
1c627fd8 19import { openapiOperationDoc } from '@server/middlewares/doc'
f012319a 20import { MVideoFile, MVideoFullLight } from '@server/types/models'
0628157f
C
21import { getLowercaseExtension } from '@shared/core-utils'
22import { isAudioFile, uuidToShort } from '@shared/extra-utils'
f012319a 23import { HttpStatusCode, ManageVideoTorrentPayload, VideoCreate, VideoResolution, VideoState } from '@shared/models'
c158a5fa
C
24import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger'
25import { retryTransactionWrapper } from '../../../helpers/database-utils'
26import { createReqFiles } from '../../../helpers/express-utils'
d3d3deaa 27import { buildFileMetadata, ffprobePromise, getVideoStreamDimensionsInfo, getVideoStreamFPS } from '../../../helpers/ffmpeg'
c158a5fa 28import { logger, loggerTagsFactory } from '../../../helpers/logger'
482b2623 29import { MIMETYPES } from '../../../initializers/constants'
c158a5fa
C
30import { sequelizeTypescript } from '../../../initializers/database'
31import { federateVideoIfNeeded } from '../../../lib/activitypub/videos'
32import { Notifier } from '../../../lib/notifier'
33import { Hooks } from '../../../lib/plugins/hooks'
34import { generateVideoMiniature } from '../../../lib/thumbnail'
35import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist'
36import {
37 asyncMiddleware,
38 asyncRetryTransactionMiddleware,
39 authenticate,
40 videosAddLegacyValidator,
41 videosAddResumableInitValidator,
2f0a0ae2 42 videosAddResumableValidator
c158a5fa
C
43} from '../../../middlewares'
44import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update'
45import { VideoModel } from '../../../models/video/video'
46import { VideoFileModel } from '../../../models/video/video-file'
2e401e85 47import { VideoSourceModel } from '@server/models/video/video-source'
c158a5fa
C
48
49const lTags = loggerTagsFactory('api', 'video')
50const auditLogger = auditLoggerFactory('videos')
51const uploadRouter = express.Router()
020d3d3d 52
c158a5fa
C
53const reqVideoFileAdd = createReqFiles(
54 [ 'videofile', 'thumbnailfile', 'previewfile' ],
d3d3deaa 55 { ...MIMETYPES.VIDEO.MIMETYPE_EXT, ...MIMETYPES.IMAGE.MIMETYPE_EXT }
c158a5fa
C
56)
57
58const reqVideoFileAddResumable = createReqFiles(
59 [ 'thumbnailfile', 'previewfile' ],
60 MIMETYPES.IMAGE.MIMETYPE_EXT,
d3d3deaa 61 getResumableUploadPath()
c158a5fa
C
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),
020d3d3d 77 uploadx.upload
c158a5fa
C
78)
79
80uploadRouter.delete('/upload-resumable',
81 authenticate,
020d3d3d
C
82 asyncMiddleware(deleteUploadResumableCache),
83 uploadx.upload
c158a5fa
C
84)
85
86uploadRouter.put('/upload-resumable',
1c627fd8 87 openapiOperationDoc({ operationId: 'uploadResumable' }),
c158a5fa 88 authenticate,
020d3d3d 89 uploadx.upload, // uploadx doesn't next() before the file upload completes
c158a5fa
C
90 asyncMiddleware(videosAddResumableValidator),
91 asyncMiddleware(addVideoResumable)
92)
93
94// ---------------------------------------------------------------------------
95
96export {
97 uploadRouter
98}
99
100// ---------------------------------------------------------------------------
101
020d3d3d 102async function addVideoLegacy (req: express.Request, res: express.Response) {
c158a5fa
C
103 // Uploading the video could be long
104 // Set timeout to 10 minutes, as Express's default is 2 minutes
105 req.setTimeout(1000 * 60 * 10, () => {
76148b27
RK
106 logger.error('Video upload has timed out.')
107 return res.fail({
108 status: HttpStatusCode.REQUEST_TIMEOUT_408,
109 message: 'Video upload has timed out.'
110 })
c158a5fa
C
111 })
112
113 const videoPhysicalFile = req.files['videofile'][0]
114 const videoInfo: VideoCreate = req.body
115 const files = req.files
116
7226e90f 117 const response = await addVideo({ req, res, videoPhysicalFile, videoInfo, files })
276250f0
RK
118
119 return res.json(response)
c158a5fa
C
120}
121
020d3d3d 122async function addVideoResumable (req: express.Request, res: express.Response) {
c158a5fa
C
123 const videoPhysicalFile = res.locals.videoFileResumable
124 const videoInfo = videoPhysicalFile.metadata
125 const files = { previewfile: videoInfo.previewfile }
126
7226e90f 127 const response = await addVideo({ req, res, videoPhysicalFile, videoInfo, files })
276250f0
RK
128 await Redis.Instance.setUploadSession(req.query.upload_id, response)
129
130 return res.json(response)
c158a5fa
C
131}
132
133async function addVideo (options: {
7226e90f 134 req: express.Request
c158a5fa
C
135 res: express.Response
136 videoPhysicalFile: express.VideoUploadFile
137 videoInfo: VideoCreate
138 files: express.UploadFiles
139}) {
7226e90f 140 const { req, res, videoPhysicalFile, videoInfo, files } = options
c158a5fa
C
141 const videoChannel = res.locals.videoChannel
142 const user = res.locals.oauth.token.User
143
d17d7430
C
144 let videoData = buildLocalVideoFromReq(videoInfo, videoChannel.id)
145 videoData = await Hooks.wrapObject(videoData, 'filter:api.video.upload.video-attribute.result')
c158a5fa 146
0305db28 147 videoData.state = buildNextVideoState()
c158a5fa
C
148 videoData.duration = videoPhysicalFile.duration // duration was added by a previous middleware
149
150 const video = new VideoModel(videoData) as MVideoFullLight
151 video.VideoChannel = videoChannel
152 video.url = getLocalVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
153
0305db28 154 const videoFile = await buildNewFile(videoPhysicalFile)
2e401e85 155 const originalFilename = videoPhysicalFile.originalname
c158a5fa
C
156
157 // Move physical file
0305db28 158 const destination = VideoPathManager.Instance.getFSVideoFileOutputPath(video, videoFile)
c158a5fa
C
159 await move(videoPhysicalFile.path, destination)
160 // This is important in case if there is another attempt in the retry process
0305db28 161 videoPhysicalFile.filename = basename(destination)
c158a5fa
C
162 videoPhysicalFile.path = destination
163
164 const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
165 video,
166 files,
167 fallback: type => generateVideoMiniature({ video, videoFile, type })
168 })
169
170 const { videoCreated } = await sequelizeTypescript.transaction(async t => {
171 const sequelizeOptions = { transaction: t }
172
173 const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight
174
175 await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
176 await videoCreated.addAndSaveThumbnail(previewModel, t)
177
178 // Do not forget to add video channel information to the created video
179 videoCreated.VideoChannel = res.locals.videoChannel
180
181 videoFile.videoId = video.id
182 await videoFile.save(sequelizeOptions)
183
184 video.VideoFiles = [ videoFile ]
185
2e401e85 186 await VideoSourceModel.create({
187 filename: originalFilename,
188 videoId: video.id
189 }, { transaction: t })
190
c158a5fa
C
191 await setVideoTags({ video, tags: videoInfo.tags, transaction: t })
192
193 // Schedule an update in the future?
194 if (videoInfo.scheduleUpdate) {
195 await ScheduleVideoUpdateModel.create({
196 videoId: video.id,
197 updateAt: new Date(videoInfo.scheduleUpdate.updateAt),
198 privacy: videoInfo.scheduleUpdate.privacy || null
199 }, sequelizeOptions)
200 }
201
c158a5fa
C
202 await autoBlacklistVideoIfNeeded({
203 video,
204 user,
205 isRemote: false,
206 isNew: true,
207 transaction: t
208 })
209
210 auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(videoCreated.toFormattedDetailsJSON()))
211 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid, lTags(videoCreated.uuid))
212
213 return { videoCreated }
214 })
215
3419e0e1
C
216 // Channel has a new content, set as updated
217 await videoCreated.VideoChannel.setAsUpdated()
218
f012319a
C
219 createTorrentFederate(videoCreated, videoFile)
220 .catch(err => {
221 logger.error('Cannot create torrent or federate video for %s.', videoCreated.uuid, { err, ...lTags(videoCreated.uuid) })
222
223 return videoCreated
224 }).then(refreshedVideo => {
225 if (!refreshedVideo) return
226
227 if (refreshedVideo.state === VideoState.TO_MOVE_TO_EXTERNAL_STORAGE) {
1808a1f8 228 return addMoveToObjectStorageJob({ video: refreshedVideo, previousVideoState: undefined })
0305db28 229 }
c158a5fa 230
f012319a 231 if (refreshedVideo.state === VideoState.TO_TRANSCODE) {
1808a1f8 232 return addOptimizeOrMergeAudioJob({ video: refreshedVideo, videoFile, user })
0305db28 233 }
f012319a 234 }).catch(err => logger.error('Cannot add optimize/merge audio job for %s.', videoCreated.uuid, { err, ...lTags(videoCreated.uuid) }))
c158a5fa 235
7226e90f 236 Hooks.runAction('action:api.video.uploaded', { video: videoCreated, req, res })
c158a5fa 237
276250f0 238 return {
c158a5fa
C
239 video: {
240 id: videoCreated.id,
d4a8e7a6 241 shortUUID: uuidToShort(videoCreated.uuid),
c158a5fa
C
242 uuid: videoCreated.uuid
243 }
276250f0 244 }
c158a5fa
C
245}
246
0305db28 247async function buildNewFile (videoPhysicalFile: express.VideoUploadFile) {
c158a5fa 248 const videoFile = new VideoFileModel({
ea54cd04 249 extname: getLowercaseExtension(videoPhysicalFile.filename),
c158a5fa
C
250 size: videoPhysicalFile.size,
251 videoStreamingPlaylistId: null,
c729caf6 252 metadata: await buildFileMetadata(videoPhysicalFile.path)
c158a5fa
C
253 })
254
482b2623
C
255 const probe = await ffprobePromise(videoPhysicalFile.path)
256
257 if (await isAudioFile(videoPhysicalFile.path, probe)) {
258 videoFile.resolution = VideoResolution.H_NOVIDEO
c158a5fa 259 } else {
c729caf6
C
260 videoFile.fps = await getVideoStreamFPS(videoPhysicalFile.path, probe)
261 videoFile.resolution = (await getVideoStreamDimensionsInfo(videoPhysicalFile.path, probe)).resolution
c158a5fa
C
262 }
263
83903cb6 264 videoFile.filename = generateWebTorrentVideoFilename(videoFile.resolution, videoFile.extname)
c158a5fa
C
265
266 return videoFile
267}
268
f012319a
C
269async function createTorrentFederate (video: MVideoFullLight, videoFile: MVideoFile) {
270 const payload: ManageVideoTorrentPayload = { videoId: video.id, videoFileId: videoFile.id, action: 'create' }
c158a5fa 271
f012319a
C
272 const job = await JobQueue.Instance.createJobWithPromise({ type: 'manage-video-torrent', payload })
273 await job.finished()
c158a5fa 274
f012319a
C
275 const refreshedVideo = await VideoModel.loadAndPopulateAccountAndServerAndTags(video.id)
276 if (!refreshedVideo) return
c158a5fa 277
f012319a
C
278 // Only federate and notify after the torrent creation
279 Notifier.Instance.notifyOnNewVideoIfNeeded(refreshedVideo)
c158a5fa 280
f012319a
C
281 await retryTransactionWrapper(() => {
282 return sequelizeTypescript.transaction(t => federateVideoIfNeeded(refreshedVideo, true, t))
283 })
c158a5fa 284
f012319a 285 return refreshedVideo
c158a5fa 286}
020d3d3d
C
287
288async function deleteUploadResumableCache (req: express.Request, res: express.Response, next: express.NextFunction) {
289 await Redis.Instance.deleteUploadSession(req.query.upload_id)
290
291 return next()
292}