]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/videos/upload.ts
6773b500f4e0981ddc56a74cf9ea1d497a79ed39
[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 { getLowercaseExtension } from '@server/helpers/core-utils'
5 import { getResumableUploadPath } from '@server/helpers/upload'
6 import { uuidToShort } from '@server/helpers/uuid'
7 import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent'
8 import { getLocalVideoActivityPubUrl } from '@server/lib/activitypub/url'
9 import { generateWebTorrentVideoFilename } from '@server/lib/paths'
10 import { Redis } from '@server/lib/redis'
11 import {
12 addMoveToObjectStorageJob,
13 addOptimizeOrMergeAudioJob,
14 buildLocalVideoFromReq,
15 buildVideoThumbnailsFromReq,
16 setVideoTags
17 } from '@server/lib/video'
18 import { VideoPathManager } from '@server/lib/video-path-manager'
19 import { buildNextVideoState } from '@server/lib/video-state'
20 import { openapiOperationDoc } from '@server/middlewares/doc'
21 import { MVideo, MVideoFile, MVideoFullLight } from '@server/types/models'
22 import { Uploadx } from '@uploadx/core'
23 import { VideoCreate, VideoState } from '../../../../shared'
24 import { HttpStatusCode } from '../../../../shared/models'
25 import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger'
26 import { retryTransactionWrapper } from '../../../helpers/database-utils'
27 import { createReqFiles } from '../../../helpers/express-utils'
28 import { getMetadataFromFile, getVideoFileFPS, getVideoFileResolution } from '../../../helpers/ffprobe-utils'
29 import { logger, loggerTagsFactory } from '../../../helpers/logger'
30 import { CONFIG } from '../../../initializers/config'
31 import { DEFAULT_AUDIO_RESOLUTION, MIMETYPES } from '../../../initializers/constants'
32 import { sequelizeTypescript } from '../../../initializers/database'
33 import { federateVideoIfNeeded } from '../../../lib/activitypub/videos'
34 import { Notifier } from '../../../lib/notifier'
35 import { Hooks } from '../../../lib/plugins/hooks'
36 import { generateVideoMiniature } from '../../../lib/thumbnail'
37 import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist'
38 import {
39 asyncMiddleware,
40 asyncRetryTransactionMiddleware,
41 authenticate,
42 videosAddLegacyValidator,
43 videosAddResumableInitValidator,
44 videosResumableUploadIdValidator,
45 videosAddResumableValidator
46 } from '../../../middlewares'
47 import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update'
48 import { VideoModel } from '../../../models/video/video'
49 import { VideoFileModel } from '../../../models/video/video-file'
50
51 const lTags = loggerTagsFactory('api', 'video')
52 const auditLogger = auditLoggerFactory('videos')
53 const uploadRouter = express.Router()
54
55 const uploadx = new Uploadx({ directory: getResumableUploadPath() })
56 uploadx.getUserId = (_, res: express.Response) => res.locals.oauth?.token.user.id
57
58 const reqVideoFileAdd = createReqFiles(
59 [ 'videofile', 'thumbnailfile', 'previewfile' ],
60 Object.assign({}, MIMETYPES.VIDEO.MIMETYPE_EXT, MIMETYPES.IMAGE.MIMETYPE_EXT),
61 {
62 videofile: CONFIG.STORAGE.TMP_DIR,
63 thumbnailfile: CONFIG.STORAGE.TMP_DIR,
64 previewfile: CONFIG.STORAGE.TMP_DIR
65 }
66 )
67
68 const reqVideoFileAddResumable = createReqFiles(
69 [ 'thumbnailfile', 'previewfile' ],
70 MIMETYPES.IMAGE.MIMETYPE_EXT,
71 {
72 thumbnailfile: getResumableUploadPath(),
73 previewfile: getResumableUploadPath()
74 }
75 )
76
77 uploadRouter.post('/upload',
78 openapiOperationDoc({ operationId: 'uploadLegacy' }),
79 authenticate,
80 reqVideoFileAdd,
81 asyncMiddleware(videosAddLegacyValidator),
82 asyncRetryTransactionMiddleware(addVideoLegacy)
83 )
84
85 uploadRouter.post('/upload-resumable',
86 openapiOperationDoc({ operationId: 'uploadResumableInit' }),
87 authenticate,
88 reqVideoFileAddResumable,
89 asyncMiddleware(videosAddResumableInitValidator),
90 uploadx.upload
91 )
92
93 uploadRouter.delete('/upload-resumable',
94 authenticate,
95 videosResumableUploadIdValidator,
96 asyncMiddleware(deleteUploadResumableCache),
97 uploadx.upload
98 )
99
100 uploadRouter.put('/upload-resumable',
101 openapiOperationDoc({ operationId: 'uploadResumable' }),
102 authenticate,
103 videosResumableUploadIdValidator,
104 uploadx.upload, // uploadx doesn't next() before the file upload completes
105 asyncMiddleware(videosAddResumableValidator),
106 asyncMiddleware(addVideoResumable)
107 )
108
109 // ---------------------------------------------------------------------------
110
111 export {
112 uploadRouter
113 }
114
115 // ---------------------------------------------------------------------------
116
117 async function addVideoLegacy (req: express.Request, res: express.Response) {
118 // Uploading the video could be long
119 // Set timeout to 10 minutes, as Express's default is 2 minutes
120 req.setTimeout(1000 * 60 * 10, () => {
121 logger.error('Video upload has timed out.')
122 return res.fail({
123 status: HttpStatusCode.REQUEST_TIMEOUT_408,
124 message: 'Video upload has timed out.'
125 })
126 })
127
128 const videoPhysicalFile = req.files['videofile'][0]
129 const videoInfo: VideoCreate = req.body
130 const files = req.files
131
132 const response = await addVideo({ req, res, videoPhysicalFile, videoInfo, files })
133
134 return res.json(response)
135 }
136
137 async function addVideoResumable (req: express.Request, res: express.Response) {
138 const videoPhysicalFile = res.locals.videoFileResumable
139 const videoInfo = videoPhysicalFile.metadata
140 const files = { previewfile: videoInfo.previewfile }
141
142 const response = await addVideo({ req, res, videoPhysicalFile, videoInfo, files })
143 await Redis.Instance.setUploadSession(req.query.upload_id, response)
144
145 return res.json(response)
146 }
147
148 async function addVideo (options: {
149 req: express.Request
150 res: express.Response
151 videoPhysicalFile: express.VideoUploadFile
152 videoInfo: VideoCreate
153 files: express.UploadFiles
154 }) {
155 const { req, res, videoPhysicalFile, videoInfo, files } = options
156 const videoChannel = res.locals.videoChannel
157 const user = res.locals.oauth.token.User
158
159 const videoData = buildLocalVideoFromReq(videoInfo, videoChannel.id)
160
161 videoData.state = buildNextVideoState()
162 videoData.duration = videoPhysicalFile.duration // duration was added by a previous middleware
163
164 const video = new VideoModel(videoData) as MVideoFullLight
165 video.VideoChannel = videoChannel
166 video.url = getLocalVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
167
168 const videoFile = await buildNewFile(videoPhysicalFile)
169
170 // Move physical file
171 const destination = VideoPathManager.Instance.getFSVideoFileOutputPath(video, videoFile)
172 await move(videoPhysicalFile.path, destination)
173 // This is important in case if there is another attempt in the retry process
174 videoPhysicalFile.filename = basename(destination)
175 videoPhysicalFile.path = destination
176
177 const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
178 video,
179 files,
180 fallback: type => generateVideoMiniature({ video, videoFile, type })
181 })
182
183 const { videoCreated } = await sequelizeTypescript.transaction(async t => {
184 const sequelizeOptions = { transaction: t }
185
186 const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight
187
188 await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
189 await videoCreated.addAndSaveThumbnail(previewModel, t)
190
191 // Do not forget to add video channel information to the created video
192 videoCreated.VideoChannel = res.locals.videoChannel
193
194 videoFile.videoId = video.id
195 await videoFile.save(sequelizeOptions)
196
197 video.VideoFiles = [ videoFile ]
198
199 await setVideoTags({ video, tags: videoInfo.tags, transaction: t })
200
201 // Schedule an update in the future?
202 if (videoInfo.scheduleUpdate) {
203 await ScheduleVideoUpdateModel.create({
204 videoId: video.id,
205 updateAt: new Date(videoInfo.scheduleUpdate.updateAt),
206 privacy: videoInfo.scheduleUpdate.privacy || null
207 }, sequelizeOptions)
208 }
209
210 await autoBlacklistVideoIfNeeded({
211 video,
212 user,
213 isRemote: false,
214 isNew: true,
215 transaction: t
216 })
217
218 auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(videoCreated.toFormattedDetailsJSON()))
219 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid, lTags(videoCreated.uuid))
220
221 return { videoCreated }
222 })
223
224 // Channel has a new content, set as updated
225 await videoCreated.VideoChannel.setAsUpdated()
226
227 createTorrentFederate(video, videoFile)
228 .then(() => {
229 if (video.state === VideoState.TO_MOVE_TO_EXTERNAL_STORAGE) {
230 return addMoveToObjectStorageJob(video)
231 }
232
233 if (video.state === VideoState.TO_TRANSCODE) {
234 return addOptimizeOrMergeAudioJob(videoCreated, videoFile, user)
235 }
236 })
237 .catch(err => logger.error('Cannot add optimize/merge audio job for %s.', videoCreated.uuid, { err, ...lTags(videoCreated.uuid) }))
238
239 Hooks.runAction('action:api.video.uploaded', { video: videoCreated, req, res })
240
241 return {
242 video: {
243 id: videoCreated.id,
244 shortUUID: uuidToShort(videoCreated.uuid),
245 uuid: videoCreated.uuid
246 }
247 }
248 }
249
250 async function buildNewFile (videoPhysicalFile: express.VideoUploadFile) {
251 const videoFile = new VideoFileModel({
252 extname: getLowercaseExtension(videoPhysicalFile.filename),
253 size: videoPhysicalFile.size,
254 videoStreamingPlaylistId: null,
255 metadata: await getMetadataFromFile(videoPhysicalFile.path)
256 })
257
258 if (videoFile.isAudio()) {
259 videoFile.resolution = DEFAULT_AUDIO_RESOLUTION
260 } else {
261 videoFile.fps = await getVideoFileFPS(videoPhysicalFile.path)
262 videoFile.resolution = (await getVideoFileResolution(videoPhysicalFile.path)).resolution
263 }
264
265 videoFile.filename = generateWebTorrentVideoFilename(videoFile.resolution, videoFile.extname)
266
267 return videoFile
268 }
269
270 async function createTorrentAndSetInfoHashAsync (video: MVideo, fileArg: MVideoFile) {
271 await createTorrentAndSetInfoHash(video, fileArg)
272
273 // Refresh videoFile because the createTorrentAndSetInfoHash could be long
274 const refreshedFile = await VideoFileModel.loadWithVideo(fileArg.id)
275 // File does not exist anymore, remove the generated torrent
276 if (!refreshedFile) return fileArg.removeTorrent()
277
278 refreshedFile.infoHash = fileArg.infoHash
279 refreshedFile.torrentFilename = fileArg.torrentFilename
280
281 return refreshedFile.save()
282 }
283
284 function createTorrentFederate (video: MVideoFullLight, videoFile: MVideoFile) {
285 // Create the torrent file in async way because it could be long
286 return createTorrentAndSetInfoHashAsync(video, videoFile)
287 .catch(err => logger.error('Cannot create torrent file for video %s', video.url, { err, ...lTags(video.uuid) }))
288 .then(() => VideoModel.loadAndPopulateAccountAndServerAndTags(video.id))
289 .then(refreshedVideo => {
290 if (!refreshedVideo) return
291
292 // Only federate and notify after the torrent creation
293 Notifier.Instance.notifyOnNewVideoIfNeeded(refreshedVideo)
294
295 return retryTransactionWrapper(() => {
296 return sequelizeTypescript.transaction(t => federateVideoIfNeeded(refreshedVideo, true, t))
297 })
298 })
299 .catch(err => logger.error('Cannot federate or notify video creation %s', video.url, { err, ...lTags(video.uuid) }))
300 }
301
302 async function deleteUploadResumableCache (req: express.Request, res: express.Response, next: express.NextFunction) {
303 await Redis.Instance.deleteUploadSession(req.query.upload_id)
304
305 return next()
306 }