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