]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/videos/upload.ts
store uploaded video filename (#4885)
[github/Chocobozzz/PeerTube.git] / server / controllers / api / videos / upload.ts
1 import express from 'express'
2 import { move } from 'fs-extra'
3 import { basename } from 'path'
4 import { getResumableUploadPath } from '@server/helpers/upload'
5 import { getLocalVideoActivityPubUrl } from '@server/lib/activitypub/url'
6 import { JobQueue } from '@server/lib/job-queue'
7 import { generateWebTorrentVideoFilename } from '@server/lib/paths'
8 import { Redis } from '@server/lib/redis'
9 import { uploadx } from '@server/lib/uploadx'
10 import {
11 addMoveToObjectStorageJob,
12 addOptimizeOrMergeAudioJob,
13 buildLocalVideoFromReq,
14 buildVideoThumbnailsFromReq,
15 setVideoTags
16 } from '@server/lib/video'
17 import { VideoPathManager } from '@server/lib/video-path-manager'
18 import { buildNextVideoState } from '@server/lib/video-state'
19 import { openapiOperationDoc } from '@server/middlewares/doc'
20 import { MVideoFile, MVideoFullLight } from '@server/types/models'
21 import { getLowercaseExtension } from '@shared/core-utils'
22 import { isAudioFile, uuidToShort } from '@shared/extra-utils'
23 import { HttpStatusCode, ManageVideoTorrentPayload, VideoCreate, VideoResolution, VideoState } from '@shared/models'
24 import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger'
25 import { retryTransactionWrapper } from '../../../helpers/database-utils'
26 import { createReqFiles } from '../../../helpers/express-utils'
27 import { buildFileMetadata, ffprobePromise, getVideoStreamDimensionsInfo, getVideoStreamFPS } from '../../../helpers/ffmpeg'
28 import { logger, loggerTagsFactory } from '../../../helpers/logger'
29 import { MIMETYPES } from '../../../initializers/constants'
30 import { sequelizeTypescript } from '../../../initializers/database'
31 import { federateVideoIfNeeded } from '../../../lib/activitypub/videos'
32 import { Notifier } from '../../../lib/notifier'
33 import { Hooks } from '../../../lib/plugins/hooks'
34 import { generateVideoMiniature } from '../../../lib/thumbnail'
35 import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist'
36 import {
37 asyncMiddleware,
38 asyncRetryTransactionMiddleware,
39 authenticate,
40 videosAddLegacyValidator,
41 videosAddResumableInitValidator,
42 videosAddResumableValidator
43 } from '../../../middlewares'
44 import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update'
45 import { VideoModel } from '../../../models/video/video'
46 import { VideoFileModel } from '../../../models/video/video-file'
47 import { VideoSourceModel } from '@server/models/video/video-source'
48
49 const lTags = loggerTagsFactory('api', 'video')
50 const auditLogger = auditLoggerFactory('videos')
51 const uploadRouter = express.Router()
52
53 const reqVideoFileAdd = createReqFiles(
54 [ 'videofile', 'thumbnailfile', 'previewfile' ],
55 { ...MIMETYPES.VIDEO.MIMETYPE_EXT, ...MIMETYPES.IMAGE.MIMETYPE_EXT }
56 )
57
58 const reqVideoFileAddResumable = createReqFiles(
59 [ 'thumbnailfile', 'previewfile' ],
60 MIMETYPES.IMAGE.MIMETYPE_EXT,
61 getResumableUploadPath()
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 uploadx.upload
78 )
79
80 uploadRouter.delete('/upload-resumable',
81 authenticate,
82 asyncMiddleware(deleteUploadResumableCache),
83 uploadx.upload
84 )
85
86 uploadRouter.put('/upload-resumable',
87 openapiOperationDoc({ operationId: 'uploadResumable' }),
88 authenticate,
89 uploadx.upload, // uploadx doesn't next() before the file upload completes
90 asyncMiddleware(videosAddResumableValidator),
91 asyncMiddleware(addVideoResumable)
92 )
93
94 // ---------------------------------------------------------------------------
95
96 export {
97 uploadRouter
98 }
99
100 // ---------------------------------------------------------------------------
101
102 async function addVideoLegacy (req: express.Request, res: express.Response) {
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, () => {
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 })
111 })
112
113 const videoPhysicalFile = req.files['videofile'][0]
114 const videoInfo: VideoCreate = req.body
115 const files = req.files
116
117 const response = await addVideo({ req, res, videoPhysicalFile, videoInfo, files })
118
119 return res.json(response)
120 }
121
122 async function addVideoResumable (req: express.Request, res: express.Response) {
123 const videoPhysicalFile = res.locals.videoFileResumable
124 const videoInfo = videoPhysicalFile.metadata
125 const files = { previewfile: videoInfo.previewfile }
126
127 const response = await addVideo({ req, res, videoPhysicalFile, videoInfo, files })
128 await Redis.Instance.setUploadSession(req.query.upload_id, response)
129
130 return res.json(response)
131 }
132
133 async function addVideo (options: {
134 req: express.Request
135 res: express.Response
136 videoPhysicalFile: express.VideoUploadFile
137 videoInfo: VideoCreate
138 files: express.UploadFiles
139 }) {
140 const { req, res, videoPhysicalFile, videoInfo, files } = options
141 const videoChannel = res.locals.videoChannel
142 const user = res.locals.oauth.token.User
143
144 let videoData = buildLocalVideoFromReq(videoInfo, videoChannel.id)
145 videoData = await Hooks.wrapObject(videoData, 'filter:api.video.upload.video-attribute.result')
146
147 videoData.state = buildNextVideoState()
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
154 const videoFile = await buildNewFile(videoPhysicalFile)
155 const originalFilename = videoPhysicalFile.originalname
156
157 // Move physical file
158 const destination = VideoPathManager.Instance.getFSVideoFileOutputPath(video, videoFile)
159 await move(videoPhysicalFile.path, destination)
160 // This is important in case if there is another attempt in the retry process
161 videoPhysicalFile.filename = basename(destination)
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
186 await VideoSourceModel.create({
187 filename: originalFilename,
188 videoId: video.id
189 }, { transaction: t })
190
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
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
216 // Channel has a new content, set as updated
217 await videoCreated.VideoChannel.setAsUpdated()
218
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) {
228 return addMoveToObjectStorageJob({ video: refreshedVideo, previousVideoState: undefined })
229 }
230
231 if (refreshedVideo.state === VideoState.TO_TRANSCODE) {
232 return addOptimizeOrMergeAudioJob({ video: refreshedVideo, videoFile, user })
233 }
234 }).catch(err => logger.error('Cannot add optimize/merge audio job for %s.', videoCreated.uuid, { err, ...lTags(videoCreated.uuid) }))
235
236 Hooks.runAction('action:api.video.uploaded', { video: videoCreated, req, res })
237
238 return {
239 video: {
240 id: videoCreated.id,
241 shortUUID: uuidToShort(videoCreated.uuid),
242 uuid: videoCreated.uuid
243 }
244 }
245 }
246
247 async function buildNewFile (videoPhysicalFile: express.VideoUploadFile) {
248 const videoFile = new VideoFileModel({
249 extname: getLowercaseExtension(videoPhysicalFile.filename),
250 size: videoPhysicalFile.size,
251 videoStreamingPlaylistId: null,
252 metadata: await buildFileMetadata(videoPhysicalFile.path)
253 })
254
255 const probe = await ffprobePromise(videoPhysicalFile.path)
256
257 if (await isAudioFile(videoPhysicalFile.path, probe)) {
258 videoFile.resolution = VideoResolution.H_NOVIDEO
259 } else {
260 videoFile.fps = await getVideoStreamFPS(videoPhysicalFile.path, probe)
261 videoFile.resolution = (await getVideoStreamDimensionsInfo(videoPhysicalFile.path, probe)).resolution
262 }
263
264 videoFile.filename = generateWebTorrentVideoFilename(videoFile.resolution, videoFile.extname)
265
266 return videoFile
267 }
268
269 async function createTorrentFederate (video: MVideoFullLight, videoFile: MVideoFile) {
270 const payload: ManageVideoTorrentPayload = { videoId: video.id, videoFileId: videoFile.id, action: 'create' }
271
272 const job = await JobQueue.Instance.createJobWithPromise({ type: 'manage-video-torrent', payload })
273 await job.finished()
274
275 const refreshedVideo = await VideoModel.loadAndPopulateAccountAndServerAndTags(video.id)
276 if (!refreshedVideo) return
277
278 // Only federate and notify after the torrent creation
279 Notifier.Instance.notifyOnNewVideoIfNeeded(refreshedVideo)
280
281 await retryTransactionWrapper(() => {
282 return sequelizeTypescript.transaction(t => federateVideoIfNeeded(refreshedVideo, true, t))
283 })
284
285 return refreshedVideo
286 }
287
288 async 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 }