]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/api/videos/upload.ts
Remove resumable cache after upload success
[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({ 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({ 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 res: express.Response
150 videoPhysicalFile: express.VideoUploadFile
151 videoInfo: VideoCreate
152 files: express.UploadFiles
153 }) {
154 const { res, videoPhysicalFile, videoInfo, files } = options
155 const videoChannel = res.locals.videoChannel
156 const user = res.locals.oauth.token.User
157
158 const videoData = buildLocalVideoFromReq(videoInfo, videoChannel.id)
159
160 videoData.state = buildNextVideoState()
161 videoData.duration = videoPhysicalFile.duration // duration was added by a previous middleware
162
163 const video = new VideoModel(videoData) as MVideoFullLight
164 video.VideoChannel = videoChannel
165 video.url = getLocalVideoActivityPubUrl(video) // We use the UUID, so set the URL after building the object
166
167 const videoFile = await buildNewFile(videoPhysicalFile)
168
169 // Move physical file
170 const destination = VideoPathManager.Instance.getFSVideoFileOutputPath(video, videoFile)
171 await move(videoPhysicalFile.path, destination)
172 // This is important in case if there is another attempt in the retry process
173 videoPhysicalFile.filename = basename(destination)
174 videoPhysicalFile.path = destination
175
176 const [ thumbnailModel, previewModel ] = await buildVideoThumbnailsFromReq({
177 video,
178 files,
179 fallback: type => generateVideoMiniature({ video, videoFile, type })
180 })
181
182 const { videoCreated } = await sequelizeTypescript.transaction(async t => {
183 const sequelizeOptions = { transaction: t }
184
185 const videoCreated = await video.save(sequelizeOptions) as MVideoFullLight
186
187 await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
188 await videoCreated.addAndSaveThumbnail(previewModel, t)
189
190 // Do not forget to add video channel information to the created video
191 videoCreated.VideoChannel = res.locals.videoChannel
192
193 videoFile.videoId = video.id
194 await videoFile.save(sequelizeOptions)
195
196 video.VideoFiles = [ videoFile ]
197
198 await setVideoTags({ video, tags: videoInfo.tags, transaction: t })
199
200 // Schedule an update in the future?
201 if (videoInfo.scheduleUpdate) {
202 await ScheduleVideoUpdateModel.create({
203 videoId: video.id,
204 updateAt: new Date(videoInfo.scheduleUpdate.updateAt),
205 privacy: videoInfo.scheduleUpdate.privacy || null
206 }, sequelizeOptions)
207 }
208
209 await autoBlacklistVideoIfNeeded({
210 video,
211 user,
212 isRemote: false,
213 isNew: true,
214 transaction: t
215 })
216
217 auditLogger.create(getAuditIdFromRes(res), new VideoAuditView(videoCreated.toFormattedDetailsJSON()))
218 logger.info('Video with name %s and uuid %s created.', videoInfo.name, videoCreated.uuid, lTags(videoCreated.uuid))
219
220 return { videoCreated }
221 })
222
223 // Channel has a new content, set as updated
224 await videoCreated.VideoChannel.setAsUpdated()
225
226 createTorrentFederate(video, videoFile)
227 .then(() => {
228 if (video.state === VideoState.TO_MOVE_TO_EXTERNAL_STORAGE) {
229 return addMoveToObjectStorageJob(video)
230 }
231
232 if (video.state === VideoState.TO_TRANSCODE) {
233 return addOptimizeOrMergeAudioJob(videoCreated, videoFile, user)
234 }
235 })
236 .catch(err => logger.error('Cannot add optimize/merge audio job for %s.', videoCreated.uuid, { err, ...lTags(videoCreated.uuid) }))
237
238 Hooks.runAction('action:api.video.uploaded', { video: videoCreated })
239
240 return {
241 video: {
242 id: videoCreated.id,
243 shortUUID: uuidToShort(videoCreated.uuid),
244 uuid: videoCreated.uuid
245 }
246 }
247 }
248
249 async function buildNewFile (videoPhysicalFile: express.VideoUploadFile) {
250 const videoFile = new VideoFileModel({
251 extname: getLowercaseExtension(videoPhysicalFile.filename),
252 size: videoPhysicalFile.size,
253 videoStreamingPlaylistId: null,
254 metadata: await getMetadataFromFile(videoPhysicalFile.path)
255 })
256
257 if (videoFile.isAudio()) {
258 videoFile.resolution = DEFAULT_AUDIO_RESOLUTION
259 } else {
260 videoFile.fps = await getVideoFileFPS(videoPhysicalFile.path)
261 videoFile.resolution = (await getVideoFileResolution(videoPhysicalFile.path)).resolution
262 }
263
264 videoFile.filename = generateWebTorrentVideoFilename(videoFile.resolution, videoFile.extname)
265
266 return videoFile
267 }
268
269 async function createTorrentAndSetInfoHashAsync (video: MVideo, fileArg: MVideoFile) {
270 await createTorrentAndSetInfoHash(video, fileArg)
271
272 // Refresh videoFile because the createTorrentAndSetInfoHash could be long
273 const refreshedFile = await VideoFileModel.loadWithVideo(fileArg.id)
274 // File does not exist anymore, remove the generated torrent
275 if (!refreshedFile) return fileArg.removeTorrent()
276
277 refreshedFile.infoHash = fileArg.infoHash
278 refreshedFile.torrentFilename = fileArg.torrentFilename
279
280 return refreshedFile.save()
281 }
282
283 function createTorrentFederate (video: MVideoFullLight, videoFile: MVideoFile) {
284 // Create the torrent file in async way because it could be long
285 return createTorrentAndSetInfoHashAsync(video, videoFile)
286 .catch(err => logger.error('Cannot create torrent file for video %s', video.url, { err, ...lTags(video.uuid) }))
287 .then(() => VideoModel.loadAndPopulateAccountAndServerAndTags(video.id))
288 .then(refreshedVideo => {
289 if (!refreshedVideo) return
290
291 // Only federate and notify after the torrent creation
292 Notifier.Instance.notifyOnNewVideoIfNeeded(refreshedVideo)
293
294 return retryTransactionWrapper(() => {
295 return sequelizeTypescript.transaction(t => federateVideoIfNeeded(refreshedVideo, true, t))
296 })
297 })
298 .catch(err => logger.error('Cannot federate or notify video creation %s', video.url, { err, ...lTags(video.uuid) }))
299 }
300
301 async function deleteUploadResumableCache (req: express.Request, res: express.Response, next: express.NextFunction) {
302 await Redis.Instance.deleteUploadSession(req.query.upload_id)
303
304 return next()
305 }