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