]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/videos/upload.ts
Remove resumable cache after upload success
[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'
ea54cd04 4import { getLowercaseExtension } from '@server/helpers/core-utils'
790c2837 5import { getResumableUploadPath } from '@server/helpers/upload'
d4a8e7a6 6import { uuidToShort } from '@server/helpers/uuid'
c158a5fa
C
7import { createTorrentAndSetInfoHash } from '@server/helpers/webtorrent'
8import { getLocalVideoActivityPubUrl } from '@server/lib/activitypub/url'
0305db28 9import { generateWebTorrentVideoFilename } from '@server/lib/paths'
276250f0 10import { Redis } from '@server/lib/redis'
0305db28
JB
11import {
12 addMoveToObjectStorageJob,
13 addOptimizeOrMergeAudioJob,
14 buildLocalVideoFromReq,
15 buildVideoThumbnailsFromReq,
16 setVideoTags
17} from '@server/lib/video'
18import { VideoPathManager } from '@server/lib/video-path-manager'
19import { buildNextVideoState } from '@server/lib/video-state'
1c627fd8 20import { openapiOperationDoc } from '@server/middlewares/doc'
c158a5fa 21import { MVideo, MVideoFile, MVideoFullLight } from '@server/types/models'
020d3d3d 22import { Uploadx } from '@uploadx/core'
c158a5fa 23import { VideoCreate, VideoState } from '../../../../shared'
c0e8b12e 24import { HttpStatusCode } from '../../../../shared/models'
c158a5fa
C
25import { auditLoggerFactory, getAuditIdFromRes, VideoAuditView } from '../../../helpers/audit-logger'
26import { retryTransactionWrapper } from '../../../helpers/database-utils'
27import { createReqFiles } from '../../../helpers/express-utils'
28import { getMetadataFromFile, getVideoFileFPS, getVideoFileResolution } from '../../../helpers/ffprobe-utils'
29import { logger, loggerTagsFactory } from '../../../helpers/logger'
30import { CONFIG } from '../../../initializers/config'
31import { DEFAULT_AUDIO_RESOLUTION, MIMETYPES } from '../../../initializers/constants'
32import { sequelizeTypescript } from '../../../initializers/database'
33import { federateVideoIfNeeded } from '../../../lib/activitypub/videos'
34import { Notifier } from '../../../lib/notifier'
35import { Hooks } from '../../../lib/plugins/hooks'
36import { generateVideoMiniature } from '../../../lib/thumbnail'
37import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist'
38import {
39 asyncMiddleware,
40 asyncRetryTransactionMiddleware,
41 authenticate,
42 videosAddLegacyValidator,
43 videosAddResumableInitValidator,
020d3d3d 44 videosResumableUploadIdValidator,
c158a5fa
C
45 videosAddResumableValidator
46} from '../../../middlewares'
47import { ScheduleVideoUpdateModel } from '../../../models/video/schedule-video-update'
48import { VideoModel } from '../../../models/video/video'
49import { VideoFileModel } from '../../../models/video/video-file'
50
51const lTags = loggerTagsFactory('api', 'video')
52const auditLogger = auditLoggerFactory('videos')
53const uploadRouter = express.Router()
020d3d3d
C
54
55const uploadx = new Uploadx({ directory: getResumableUploadPath() })
56uploadx.getUserId = (_, res: express.Response) => res.locals.oauth?.token.user.id
c158a5fa
C
57
58const 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
68const reqVideoFileAddResumable = createReqFiles(
69 [ 'thumbnailfile', 'previewfile' ],
70 MIMETYPES.IMAGE.MIMETYPE_EXT,
71 {
72 thumbnailfile: getResumableUploadPath(),
73 previewfile: getResumableUploadPath()
74 }
75)
76
77uploadRouter.post('/upload',
1c627fd8 78 openapiOperationDoc({ operationId: 'uploadLegacy' }),
c158a5fa
C
79 authenticate,
80 reqVideoFileAdd,
81 asyncMiddleware(videosAddLegacyValidator),
82 asyncRetryTransactionMiddleware(addVideoLegacy)
83)
84
85uploadRouter.post('/upload-resumable',
1c627fd8 86 openapiOperationDoc({ operationId: 'uploadResumableInit' }),
c158a5fa
C
87 authenticate,
88 reqVideoFileAddResumable,
89 asyncMiddleware(videosAddResumableInitValidator),
020d3d3d 90 uploadx.upload
c158a5fa
C
91)
92
93uploadRouter.delete('/upload-resumable',
94 authenticate,
020d3d3d
C
95 videosResumableUploadIdValidator,
96 asyncMiddleware(deleteUploadResumableCache),
97 uploadx.upload
c158a5fa
C
98)
99
100uploadRouter.put('/upload-resumable',
1c627fd8 101 openapiOperationDoc({ operationId: 'uploadResumable' }),
c158a5fa 102 authenticate,
020d3d3d
C
103 videosResumableUploadIdValidator,
104 uploadx.upload, // uploadx doesn't next() before the file upload completes
c158a5fa
C
105 asyncMiddleware(videosAddResumableValidator),
106 asyncMiddleware(addVideoResumable)
107)
108
109// ---------------------------------------------------------------------------
110
111export {
112 uploadRouter
113}
114
115// ---------------------------------------------------------------------------
116
020d3d3d 117async function addVideoLegacy (req: express.Request, res: express.Response) {
c158a5fa
C
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, () => {
76148b27
RK
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 })
c158a5fa
C
126 })
127
128 const videoPhysicalFile = req.files['videofile'][0]
129 const videoInfo: VideoCreate = req.body
130 const files = req.files
131
276250f0
RK
132 const response = await addVideo({ res, videoPhysicalFile, videoInfo, files })
133
134 return res.json(response)
c158a5fa
C
135}
136
020d3d3d 137async function addVideoResumable (req: express.Request, res: express.Response) {
c158a5fa
C
138 const videoPhysicalFile = res.locals.videoFileResumable
139 const videoInfo = videoPhysicalFile.metadata
140 const files = { previewfile: videoInfo.previewfile }
141
276250f0
RK
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)
c158a5fa
C
146}
147
148async 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
0305db28 160 videoData.state = buildNextVideoState()
c158a5fa
C
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
0305db28 167 const videoFile = await buildNewFile(videoPhysicalFile)
c158a5fa
C
168
169 // Move physical file
0305db28 170 const destination = VideoPathManager.Instance.getFSVideoFileOutputPath(video, videoFile)
c158a5fa
C
171 await move(videoPhysicalFile.path, destination)
172 // This is important in case if there is another attempt in the retry process
0305db28 173 videoPhysicalFile.filename = basename(destination)
c158a5fa
C
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
c158a5fa
C
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
3419e0e1
C
223 // Channel has a new content, set as updated
224 await videoCreated.VideoChannel.setAsUpdated()
225
c158a5fa 226 createTorrentFederate(video, videoFile)
764b1a14 227 .then(() => {
0305db28
JB
228 if (video.state === VideoState.TO_MOVE_TO_EXTERNAL_STORAGE) {
229 return addMoveToObjectStorageJob(video)
230 }
c158a5fa 231
0305db28
JB
232 if (video.state === VideoState.TO_TRANSCODE) {
233 return addOptimizeOrMergeAudioJob(videoCreated, videoFile, user)
234 }
764b1a14
C
235 })
236 .catch(err => logger.error('Cannot add optimize/merge audio job for %s.', videoCreated.uuid, { err, ...lTags(videoCreated.uuid) }))
c158a5fa
C
237
238 Hooks.runAction('action:api.video.uploaded', { video: videoCreated })
239
276250f0 240 return {
c158a5fa
C
241 video: {
242 id: videoCreated.id,
d4a8e7a6 243 shortUUID: uuidToShort(videoCreated.uuid),
c158a5fa
C
244 uuid: videoCreated.uuid
245 }
276250f0 246 }
c158a5fa
C
247}
248
0305db28 249async function buildNewFile (videoPhysicalFile: express.VideoUploadFile) {
c158a5fa 250 const videoFile = new VideoFileModel({
ea54cd04 251 extname: getLowercaseExtension(videoPhysicalFile.filename),
c158a5fa
C
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)
679c12e6 261 videoFile.resolution = (await getVideoFileResolution(videoPhysicalFile.path)).resolution
c158a5fa
C
262 }
263
83903cb6 264 videoFile.filename = generateWebTorrentVideoFilename(videoFile.resolution, videoFile.extname)
c158a5fa
C
265
266 return videoFile
267}
268
269async 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
764b1a14 283function createTorrentFederate (video: MVideoFullLight, videoFile: MVideoFile) {
c158a5fa 284 // Create the torrent file in async way because it could be long
764b1a14 285 return createTorrentAndSetInfoHashAsync(video, videoFile)
c158a5fa
C
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}
020d3d3d
C
300
301async 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}