]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/videos/upload.ts
Ensure peertube root directory is setup to be traversed by nginx (#5028)
[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'
47
48const lTags = loggerTagsFactory('api', 'video')
49const auditLogger = auditLoggerFactory('videos')
50const uploadRouter = express.Router()
020d3d3d 51
c158a5fa
C
52const reqVideoFileAdd = createReqFiles(
53 [ 'videofile', 'thumbnailfile', 'previewfile' ],
d3d3deaa 54 { ...MIMETYPES.VIDEO.MIMETYPE_EXT, ...MIMETYPES.IMAGE.MIMETYPE_EXT }
c158a5fa
C
55)
56
57const reqVideoFileAddResumable = createReqFiles(
58 [ 'thumbnailfile', 'previewfile' ],
59 MIMETYPES.IMAGE.MIMETYPE_EXT,
d3d3deaa 60 getResumableUploadPath()
c158a5fa
C
61)
62
63uploadRouter.post('/upload',
1c627fd8 64 openapiOperationDoc({ operationId: 'uploadLegacy' }),
c158a5fa
C
65 authenticate,
66 reqVideoFileAdd,
67 asyncMiddleware(videosAddLegacyValidator),
68 asyncRetryTransactionMiddleware(addVideoLegacy)
69)
70
71uploadRouter.post('/upload-resumable',
1c627fd8 72 openapiOperationDoc({ operationId: 'uploadResumableInit' }),
c158a5fa
C
73 authenticate,
74 reqVideoFileAddResumable,
75 asyncMiddleware(videosAddResumableInitValidator),
020d3d3d 76 uploadx.upload
c158a5fa
C
77)
78
79uploadRouter.delete('/upload-resumable',
80 authenticate,
020d3d3d
C
81 asyncMiddleware(deleteUploadResumableCache),
82 uploadx.upload
c158a5fa
C
83)
84
85uploadRouter.put('/upload-resumable',
1c627fd8 86 openapiOperationDoc({ operationId: 'uploadResumable' }),
c158a5fa 87 authenticate,
020d3d3d 88 uploadx.upload, // uploadx doesn't next() before the file upload completes
c158a5fa
C
89 asyncMiddleware(videosAddResumableValidator),
90 asyncMiddleware(addVideoResumable)
91)
92
93// ---------------------------------------------------------------------------
94
95export {
96 uploadRouter
97}
98
99// ---------------------------------------------------------------------------
100
020d3d3d 101async function addVideoLegacy (req: express.Request, res: express.Response) {
c158a5fa
C
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
7226e90f 116 const response = await addVideo({ req, res, videoPhysicalFile, videoInfo, files })
276250f0
RK
117
118 return res.json(response)
c158a5fa
C
119}
120
020d3d3d 121async function addVideoResumable (req: express.Request, res: express.Response) {
c158a5fa
C
122 const videoPhysicalFile = res.locals.videoFileResumable
123 const videoInfo = videoPhysicalFile.metadata
124 const files = { previewfile: videoInfo.previewfile }
125
7226e90f 126 const response = await addVideo({ req, res, videoPhysicalFile, videoInfo, files })
276250f0
RK
127 await Redis.Instance.setUploadSession(req.query.upload_id, response)
128
129 return res.json(response)
c158a5fa
C
130}
131
132async function addVideo (options: {
7226e90f 133 req: express.Request
c158a5fa
C
134 res: express.Response
135 videoPhysicalFile: express.VideoUploadFile
136 videoInfo: VideoCreate
137 files: express.UploadFiles
138}) {
7226e90f 139 const { req, res, videoPhysicalFile, videoInfo, files } = options
c158a5fa
C
140 const videoChannel = res.locals.videoChannel
141 const user = res.locals.oauth.token.User
142
d17d7430
C
143 let videoData = buildLocalVideoFromReq(videoInfo, videoChannel.id)
144 videoData = await Hooks.wrapObject(videoData, 'filter:api.video.upload.video-attribute.result')
c158a5fa 145
0305db28 146 videoData.state = buildNextVideoState()
c158a5fa
C
147 videoData.duration = videoPhysicalFile.duration // duration was added by a previous middleware
148
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
152
0305db28 153 const videoFile = await buildNewFile(videoPhysicalFile)
c158a5fa
C
154
155 // Move physical file
0305db28 156 const destination = VideoPathManager.Instance.getFSVideoFileOutputPath(video, videoFile)
c158a5fa
C
157 await move(videoPhysicalFile.path, destination)
158 // This is important in case if there is another attempt in the retry process
0305db28 159 videoPhysicalFile.filename = basename(destination)
c158a5fa
C
160 videoPhysicalFile.path = destination
161
162 const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
163 video,
164 files,
165 fallback: type => generateVideoMiniature({ video, videoFile, type })
166 })
167
168 const { videoCreated } = await sequelizeTypescript.transaction(async t => {
169 const sequelizeOptions = { transaction: t }
170
171 const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight
172
173 await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
174 await videoCreated.addAndSaveThumbnail(previewModel, t)
175
176 // Do not forget to add video channel information to the created video
177 videoCreated.VideoChannel = res.locals.videoChannel
178
179 videoFile.videoId = video.id
180 await videoFile.save(sequelizeOptions)
181
182 video.VideoFiles = [ videoFile ]
183
184 await setVideoTags({ video, tags: videoInfo.tags, transaction: t })
185
186 // Schedule an update in the future?
187 if (videoInfo.scheduleUpdate) {
188 await ScheduleVideoUpdateModel.create({
189 videoId: video.id,
190 updateAt: new Date(videoInfo.scheduleUpdate.updateAt),
191 privacy: videoInfo.scheduleUpdate.privacy || null
192 }, sequelizeOptions)
193 }
194
c158a5fa
C
195 await autoBlacklistVideoIfNeeded({
196 video,
197 user,
198 isRemote: false,
199 isNew: true,
200 transaction: t
201 })
202
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))
205
206 return { videoCreated }
207 })
208
3419e0e1
C
209 // Channel has a new content, set as updated
210 await videoCreated.VideoChannel.setAsUpdated()
211
f012319a
C
212 createTorrentFederate(videoCreated, videoFile)
213 .catch(err => {
214 logger.error('Cannot create torrent or federate video for %s.', videoCreated.uuid, { err, ...lTags(videoCreated.uuid) })
215
216 return videoCreated
217 }).then(refreshedVideo => {
218 if (!refreshedVideo) return
219
220 if (refreshedVideo.state === VideoState.TO_MOVE_TO_EXTERNAL_STORAGE) {
1808a1f8 221 return addMoveToObjectStorageJob({ video: refreshedVideo, previousVideoState: undefined })
0305db28 222 }
c158a5fa 223
f012319a 224 if (refreshedVideo.state === VideoState.TO_TRANSCODE) {
1808a1f8 225 return addOptimizeOrMergeAudioJob({ video: refreshedVideo, videoFile, user })
0305db28 226 }
f012319a 227 }).catch(err => logger.error('Cannot add optimize/merge audio job for %s.', videoCreated.uuid, { err, ...lTags(videoCreated.uuid) }))
c158a5fa 228
7226e90f 229 Hooks.runAction('action:api.video.uploaded', { video: videoCreated, req, res })
c158a5fa 230
276250f0 231 return {
c158a5fa
C
232 video: {
233 id: videoCreated.id,
d4a8e7a6 234 shortUUID: uuidToShort(videoCreated.uuid),
c158a5fa
C
235 uuid: videoCreated.uuid
236 }
276250f0 237 }
c158a5fa
C
238}
239
0305db28 240async function buildNewFile (videoPhysicalFile: express.VideoUploadFile) {
c158a5fa 241 const videoFile = new VideoFileModel({
ea54cd04 242 extname: getLowercaseExtension(videoPhysicalFile.filename),
c158a5fa
C
243 size: videoPhysicalFile.size,
244 videoStreamingPlaylistId: null,
c729caf6 245 metadata: await buildFileMetadata(videoPhysicalFile.path)
c158a5fa
C
246 })
247
482b2623
C
248 const probe = await ffprobePromise(videoPhysicalFile.path)
249
250 if (await isAudioFile(videoPhysicalFile.path, probe)) {
251 videoFile.resolution = VideoResolution.H_NOVIDEO
c158a5fa 252 } else {
c729caf6
C
253 videoFile.fps = await getVideoStreamFPS(videoPhysicalFile.path, probe)
254 videoFile.resolution = (await getVideoStreamDimensionsInfo(videoPhysicalFile.path, probe)).resolution
c158a5fa
C
255 }
256
83903cb6 257 videoFile.filename = generateWebTorrentVideoFilename(videoFile.resolution, videoFile.extname)
c158a5fa
C
258
259 return videoFile
260}
261
f012319a
C
262async function createTorrentFederate (video: MVideoFullLight, videoFile: MVideoFile) {
263 const payload: ManageVideoTorrentPayload = { videoId: video.id, videoFileId: videoFile.id, action: 'create' }
c158a5fa 264
f012319a
C
265 const job = await JobQueue.Instance.createJobWithPromise({ type: 'manage-video-torrent', payload })
266 await job.finished()
c158a5fa 267
f012319a
C
268 const refreshedVideo = await VideoModel.loadAndPopulateAccountAndServerAndTags(video.id)
269 if (!refreshedVideo) return
c158a5fa 270
f012319a
C
271 // Only federate and notify after the torrent creation
272 Notifier.Instance.notifyOnNewVideoIfNeeded(refreshedVideo)
c158a5fa 273
f012319a
C
274 await retryTransactionWrapper(() => {
275 return sequelizeTypescript.transaction(t => federateVideoIfNeeded(refreshedVideo, true, t))
276 })
c158a5fa 277
f012319a 278 return refreshedVideo
c158a5fa 279}
020d3d3d
C
280
281async function deleteUploadResumableCache (req: express.Request, res: express.Response, next: express.NextFunction) {
282 await Redis.Instance.deleteUploadSession(req.query.upload_id)
283
284 return next()
285}