]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/videos/upload.ts
Process video torrents in order
[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
48 const lTags = loggerTagsFactory('api', 'video')
49 const auditLogger = auditLoggerFactory('videos')
50 const uploadRouter = express.Router()
51
52 const reqVideoFileAdd = createReqFiles(
53 [ 'videofile', 'thumbnailfile', 'previewfile' ],
54 { ...MIMETYPES.VIDEO.MIMETYPE_EXT, ...MIMETYPES.IMAGE.MIMETYPE_EXT }
55 )
56
57 const reqVideoFileAddResumable = createReqFiles(
58 [ 'thumbnailfile', 'previewfile' ],
59 MIMETYPES.IMAGE.MIMETYPE_EXT,
60 getResumableUploadPath()
61 )
62
63 uploadRouter.post('/upload',
64 openapiOperationDoc({ operationId: 'uploadLegacy' }),
65 authenticate,
66 reqVideoFileAdd,
67 asyncMiddleware(videosAddLegacyValidator),
68 asyncRetryTransactionMiddleware(addVideoLegacy)
69 )
70
71 uploadRouter.post('/upload-resumable',
72 openapiOperationDoc({ operationId: 'uploadResumableInit' }),
73 authenticate,
74 reqVideoFileAddResumable,
75 asyncMiddleware(videosAddResumableInitValidator),
76 uploadx.upload
77 )
78
79 uploadRouter.delete('/upload-resumable',
80 authenticate,
81 asyncMiddleware(deleteUploadResumableCache),
82 uploadx.upload
83 )
84
85 uploadRouter.put('/upload-resumable',
86 openapiOperationDoc({ operationId: 'uploadResumable' }),
87 authenticate,
88 uploadx.upload, // uploadx doesn't 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 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 const response = await addVideo({ req, res, videoPhysicalFile, videoInfo, files })
117
118 return res.json(response)
119 }
120
121 async function addVideoResumable (req: express.Request, res: express.Response) {
122 const videoPhysicalFile = res.locals.videoFileResumable
123 const videoInfo = videoPhysicalFile.metadata
124 const files = { previewfile: videoInfo.previewfile }
125
126 const response = await addVideo({ req, res, videoPhysicalFile, videoInfo, files })
127 await Redis.Instance.setUploadSession(req.query.upload_id, response)
128
129 return res.json(response)
130 }
131
132 async function addVideo (options: {
133 req: express.Request
134 res: express.Response
135 videoPhysicalFile: express.VideoUploadFile
136 videoInfo: VideoCreate
137 files: express.UploadFiles
138 }) {
139 const { req, res, videoPhysicalFile, videoInfo, files } = options
140 const videoChannel = res.locals.videoChannel
141 const user = res.locals.oauth.token.User
142
143 let videoData = buildLocalVideoFromReq(videoInfo, videoChannel.id)
144 videoData = await Hooks.wrapObject(videoData, 'filter:api.video.upload.video-attribute.result')
145
146 videoData.state = buildNextVideoState()
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
153 const videoFile = await buildNewFile(videoPhysicalFile)
154
155 // Move physical file
156 const destination = VideoPathManager.Instance.getFSVideoFileOutputPath(video, videoFile)
157 await move(videoPhysicalFile.path, destination)
158 // This is important in case if there is another attempt in the retry process
159 videoPhysicalFile.filename = basename(destination)
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
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
209 // Channel has a new content, set as updated
210 await videoCreated.VideoChannel.setAsUpdated()
211
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) {
221 return addMoveToObjectStorageJob(refreshedVideo)
222 }
223
224 if (refreshedVideo.state === VideoState.TO_TRANSCODE) {
225 return addOptimizeOrMergeAudioJob(refreshedVideo, videoFile, user)
226 }
227 }).catch(err => logger.error('Cannot add optimize/merge audio job for %s.', videoCreated.uuid, { err, ...lTags(videoCreated.uuid) }))
228
229 Hooks.runAction('action:api.video.uploaded', { video: videoCreated, req, res })
230
231 return {
232 video: {
233 id: videoCreated.id,
234 shortUUID: uuidToShort(videoCreated.uuid),
235 uuid: videoCreated.uuid
236 }
237 }
238 }
239
240 async function buildNewFile (videoPhysicalFile: express.VideoUploadFile) {
241 const videoFile = new VideoFileModel({
242 extname: getLowercaseExtension(videoPhysicalFile.filename),
243 size: videoPhysicalFile.size,
244 videoStreamingPlaylistId: null,
245 metadata: await buildFileMetadata(videoPhysicalFile.path)
246 })
247
248 const probe = await ffprobePromise(videoPhysicalFile.path)
249
250 if (await isAudioFile(videoPhysicalFile.path, probe)) {
251 videoFile.resolution = VideoResolution.H_NOVIDEO
252 } else {
253 videoFile.fps = await getVideoStreamFPS(videoPhysicalFile.path, probe)
254 videoFile.resolution = (await getVideoStreamDimensionsInfo(videoPhysicalFile.path, probe)).resolution
255 }
256
257 videoFile.filename = generateWebTorrentVideoFilename(videoFile.resolution, videoFile.extname)
258
259 return videoFile
260 }
261
262 async function createTorrentFederate (video: MVideoFullLight, videoFile: MVideoFile) {
263 const payload: ManageVideoTorrentPayload = { videoId: video.id, videoFileId: videoFile.id, action: 'create' }
264
265 const job = await JobQueue.Instance.createJobWithPromise({ type: 'manage-video-torrent', payload })
266 await job.finished()
267
268 const refreshedVideo = await VideoModel.loadAndPopulateAccountAndServerAndTags(video.id)
269 if (!refreshedVideo) return
270
271 // Only federate and notify after the torrent creation
272 Notifier.Instance.notifyOnNewVideoIfNeeded(refreshedVideo)
273
274 await retryTransactionWrapper(() => {
275 return sequelizeTypescript.transaction(t => federateVideoIfNeeded(refreshedVideo, true, t))
276 })
277
278 return refreshedVideo
279 }
280
281 async 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 }