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