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