]>
Commit | Line | Data |
---|---|---|
1 | import * as express from 'express' | |
2 | import { move, readFile } from 'fs-extra' | |
3 | import * as magnetUtil from 'magnet-uri' | |
4 | import * as parseTorrent from 'parse-torrent' | |
5 | import { join } from 'path' | |
6 | import { setVideoTags } from '@server/lib/video' | |
7 | import { | |
8 | MChannelAccountDefault, | |
9 | MThumbnail, | |
10 | MUser, | |
11 | MVideoAccountDefault, | |
12 | MVideoCaptionVideo, | |
13 | MVideoTag, | |
14 | MVideoThumbnailAccountDefault, | |
15 | MVideoWithBlacklistLight | |
16 | } from '@server/types/models' | |
17 | import { MVideoImport, MVideoImportFormattable } from '@server/types/models/video/video-import' | |
18 | import { VideoImportCreate, VideoImportState, VideoPrivacy, VideoState } from '../../../../shared' | |
19 | import { HttpStatusCode } from '../../../../shared/core-utils/miscs/http-error-codes' | |
20 | import { ThumbnailType } from '../../../../shared/models/videos/thumbnail.type' | |
21 | import { auditLoggerFactory, getAuditIdFromRes, VideoImportAuditView } from '../../../helpers/audit-logger' | |
22 | import { moveAndProcessCaptionFile } from '../../../helpers/captions-utils' | |
23 | import { isArray } from '../../../helpers/custom-validators/misc' | |
24 | import { createReqFiles } from '../../../helpers/express-utils' | |
25 | import { logger } from '../../../helpers/logger' | |
26 | import { getSecureTorrentName } from '../../../helpers/utils' | |
27 | import { getYoutubeDLInfo, getYoutubeDLSubs, YoutubeDLInfo } from '../../../helpers/youtube-dl' | |
28 | import { CONFIG } from '../../../initializers/config' | |
29 | import { MIMETYPES } from '../../../initializers/constants' | |
30 | import { sequelizeTypescript } from '../../../initializers/database' | |
31 | import { getLocalVideoActivityPubUrl } from '../../../lib/activitypub/url' | |
32 | import { JobQueue } from '../../../lib/job-queue/job-queue' | |
33 | import { createVideoMiniatureFromExisting, createVideoMiniatureFromUrl } from '../../../lib/thumbnail' | |
34 | import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist' | |
35 | import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate, videoImportAddValidator } from '../../../middlewares' | |
36 | import { VideoModel } from '../../../models/video/video' | |
37 | import { VideoCaptionModel } from '../../../models/video/video-caption' | |
38 | import { VideoImportModel } from '../../../models/video/video-import' | |
39 | ||
40 | const auditLogger = auditLoggerFactory('video-imports') | |
41 | const videoImportsRouter = express.Router() | |
42 | ||
43 | const reqVideoFileImport = createReqFiles( | |
44 | [ 'thumbnailfile', 'previewfile', 'torrentfile' ], | |
45 | Object.assign({}, MIMETYPES.TORRENT.MIMETYPE_EXT, MIMETYPES.IMAGE.MIMETYPE_EXT), | |
46 | { | |
47 | thumbnailfile: CONFIG.STORAGE.TMP_DIR, | |
48 | previewfile: CONFIG.STORAGE.TMP_DIR, | |
49 | torrentfile: CONFIG.STORAGE.TMP_DIR | |
50 | } | |
51 | ) | |
52 | ||
53 | videoImportsRouter.post('/imports', | |
54 | authenticate, | |
55 | reqVideoFileImport, | |
56 | asyncMiddleware(videoImportAddValidator), | |
57 | asyncRetryTransactionMiddleware(addVideoImport) | |
58 | ) | |
59 | ||
60 | // --------------------------------------------------------------------------- | |
61 | ||
62 | export { | |
63 | videoImportsRouter | |
64 | } | |
65 | ||
66 | // --------------------------------------------------------------------------- | |
67 | ||
68 | function addVideoImport (req: express.Request, res: express.Response) { | |
69 | if (req.body.targetUrl) return addYoutubeDLImport(req, res) | |
70 | ||
71 | const file = req.files?.['torrentfile']?.[0] | |
72 | if (req.body.magnetUri || file) return addTorrentImport(req, res, file) | |
73 | } | |
74 | ||
75 | async function addTorrentImport (req: express.Request, res: express.Response, torrentfile: Express.Multer.File) { | |
76 | const body: VideoImportCreate = req.body | |
77 | const user = res.locals.oauth.token.User | |
78 | ||
79 | let videoName: string | |
80 | let torrentName: string | |
81 | let magnetUri: string | |
82 | ||
83 | if (torrentfile) { | |
84 | torrentName = torrentfile.originalname | |
85 | ||
86 | // Rename the torrent to a secured name | |
87 | const newTorrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, getSecureTorrentName(torrentName)) | |
88 | await move(torrentfile.path, newTorrentPath) | |
89 | torrentfile.path = newTorrentPath | |
90 | ||
91 | const buf = await readFile(torrentfile.path) | |
92 | const parsedTorrent = parseTorrent(buf) | |
93 | ||
94 | videoName = isArray(parsedTorrent.name) ? parsedTorrent.name[0] : parsedTorrent.name as string | |
95 | } else { | |
96 | magnetUri = body.magnetUri | |
97 | ||
98 | const parsed = magnetUtil.decode(magnetUri) | |
99 | videoName = isArray(parsed.name) ? parsed.name[0] : parsed.name as string | |
100 | } | |
101 | ||
102 | const video = buildVideo(res.locals.videoChannel.id, body, { name: videoName }) | |
103 | ||
104 | const thumbnailModel = await processThumbnail(req, video) | |
105 | const previewModel = await processPreview(req, video) | |
106 | ||
107 | const tags = body.tags || undefined | |
108 | const videoImportAttributes = { | |
109 | magnetUri, | |
110 | torrentName, | |
111 | state: VideoImportState.PENDING, | |
112 | userId: user.id | |
113 | } | |
114 | const videoImport = await insertIntoDB({ | |
115 | video, | |
116 | thumbnailModel, | |
117 | previewModel, | |
118 | videoChannel: res.locals.videoChannel, | |
119 | tags, | |
120 | videoImportAttributes, | |
121 | user | |
122 | }) | |
123 | ||
124 | // Create job to import the video | |
125 | const payload = { | |
126 | type: torrentfile ? 'torrent-file' as 'torrent-file' : 'magnet-uri' as 'magnet-uri', | |
127 | videoImportId: videoImport.id, | |
128 | magnetUri | |
129 | } | |
130 | await JobQueue.Instance.createJobWithPromise({ type: 'video-import', payload }) | |
131 | ||
132 | auditLogger.create(getAuditIdFromRes(res), new VideoImportAuditView(videoImport.toFormattedJSON())) | |
133 | ||
134 | return res.json(videoImport.toFormattedJSON()).end() | |
135 | } | |
136 | ||
137 | async function addYoutubeDLImport (req: express.Request, res: express.Response) { | |
138 | const body: VideoImportCreate = req.body | |
139 | const targetUrl = body.targetUrl | |
140 | const user = res.locals.oauth.token.User | |
141 | ||
142 | // Get video infos | |
143 | let youtubeDLInfo: YoutubeDLInfo | |
144 | try { | |
145 | youtubeDLInfo = await getYoutubeDLInfo(targetUrl) | |
146 | } catch (err) { | |
147 | logger.info('Cannot fetch information from import for URL %s.', targetUrl, { err }) | |
148 | ||
149 | return res.status(HttpStatusCode.BAD_REQUEST_400) | |
150 | .json({ | |
151 | error: 'Cannot fetch remote information of this URL.' | |
152 | }) | |
153 | } | |
154 | ||
155 | const video = buildVideo(res.locals.videoChannel.id, body, youtubeDLInfo) | |
156 | ||
157 | let thumbnailModel: MThumbnail | |
158 | ||
159 | // Process video thumbnail from request.files | |
160 | thumbnailModel = await processThumbnail(req, video) | |
161 | ||
162 | // Process video thumbnail from url if processing from request.files failed | |
163 | if (!thumbnailModel && youtubeDLInfo.thumbnailUrl) { | |
164 | thumbnailModel = await processThumbnailFromUrl(youtubeDLInfo.thumbnailUrl, video) | |
165 | } | |
166 | ||
167 | let previewModel: MThumbnail | |
168 | ||
169 | // Process video preview from request.files | |
170 | previewModel = await processPreview(req, video) | |
171 | ||
172 | // Process video preview from url if processing from request.files failed | |
173 | if (!previewModel && youtubeDLInfo.thumbnailUrl) { | |
174 | previewModel = await processPreviewFromUrl(youtubeDLInfo.thumbnailUrl, video) | |
175 | } | |
176 | ||
177 | const tags = body.tags || youtubeDLInfo.tags | |
178 | const videoImportAttributes = { | |
179 | targetUrl, | |
180 | state: VideoImportState.PENDING, | |
181 | userId: user.id | |
182 | } | |
183 | const videoImport = await insertIntoDB({ | |
184 | video, | |
185 | thumbnailModel, | |
186 | previewModel, | |
187 | videoChannel: res.locals.videoChannel, | |
188 | tags, | |
189 | videoImportAttributes, | |
190 | user | |
191 | }) | |
192 | ||
193 | // Get video subtitles | |
194 | try { | |
195 | const subtitles = await getYoutubeDLSubs(targetUrl) | |
196 | ||
197 | logger.info('Will create %s subtitles from youtube import %s.', subtitles.length, targetUrl) | |
198 | ||
199 | for (const subtitle of subtitles) { | |
200 | const videoCaption = new VideoCaptionModel({ | |
201 | videoId: video.id, | |
202 | language: subtitle.language | |
203 | }) as MVideoCaptionVideo | |
204 | videoCaption.Video = video | |
205 | ||
206 | // Move physical file | |
207 | await moveAndProcessCaptionFile(subtitle, videoCaption) | |
208 | ||
209 | await sequelizeTypescript.transaction(async t => { | |
210 | await VideoCaptionModel.insertOrReplaceLanguage(video.id, subtitle.language, null, t) | |
211 | }) | |
212 | } | |
213 | } catch (err) { | |
214 | logger.warn('Cannot get video subtitles.', { err }) | |
215 | } | |
216 | ||
217 | // Create job to import the video | |
218 | const payload = { | |
219 | type: 'youtube-dl' as 'youtube-dl', | |
220 | videoImportId: videoImport.id, | |
221 | generateThumbnail: !thumbnailModel, | |
222 | generatePreview: !previewModel, | |
223 | fileExt: `.${youtubeDLInfo.ext || 'mp4'}` | |
224 | } | |
225 | await JobQueue.Instance.createJobWithPromise({ type: 'video-import', payload }) | |
226 | ||
227 | auditLogger.create(getAuditIdFromRes(res), new VideoImportAuditView(videoImport.toFormattedJSON())) | |
228 | ||
229 | return res.json(videoImport.toFormattedJSON()).end() | |
230 | } | |
231 | ||
232 | function buildVideo (channelId: number, body: VideoImportCreate, importData: YoutubeDLInfo) { | |
233 | const videoData = { | |
234 | name: body.name || importData.name || 'Unknown name', | |
235 | remote: false, | |
236 | category: body.category || importData.category, | |
237 | licence: body.licence || importData.licence, | |
238 | language: body.language || importData.language, | |
239 | commentsEnabled: body.commentsEnabled !== false, // If the value is not "false", the default is "true" | |
240 | downloadEnabled: body.downloadEnabled !== false, | |
241 | waitTranscoding: body.waitTranscoding || false, | |
242 | state: VideoState.TO_IMPORT, | |
243 | nsfw: body.nsfw || importData.nsfw || false, | |
244 | description: body.description || importData.description, | |
245 | support: body.support || null, | |
246 | privacy: body.privacy || VideoPrivacy.PRIVATE, | |
247 | duration: 0, // duration will be set by the import job | |
248 | channelId: channelId, | |
249 | originallyPublishedAt: body.originallyPublishedAt || importData.originallyPublishedAt | |
250 | } | |
251 | const video = new VideoModel(videoData) | |
252 | video.url = getLocalVideoActivityPubUrl(video) | |
253 | ||
254 | return video | |
255 | } | |
256 | ||
257 | async function processThumbnail (req: express.Request, video: VideoModel) { | |
258 | const thumbnailField = req.files ? req.files['thumbnailfile'] : undefined | |
259 | if (thumbnailField) { | |
260 | const thumbnailPhysicalFile = thumbnailField[0] | |
261 | ||
262 | return createVideoMiniatureFromExisting({ | |
263 | inputPath: thumbnailPhysicalFile.path, | |
264 | video, | |
265 | type: ThumbnailType.MINIATURE, | |
266 | automaticallyGenerated: false | |
267 | }) | |
268 | } | |
269 | ||
270 | return undefined | |
271 | } | |
272 | ||
273 | async function processPreview (req: express.Request, video: VideoModel) { | |
274 | const previewField = req.files ? req.files['previewfile'] : undefined | |
275 | if (previewField) { | |
276 | const previewPhysicalFile = previewField[0] | |
277 | ||
278 | return createVideoMiniatureFromExisting({ | |
279 | inputPath: previewPhysicalFile.path, | |
280 | video, | |
281 | type: ThumbnailType.PREVIEW, | |
282 | automaticallyGenerated: false | |
283 | }) | |
284 | } | |
285 | ||
286 | return undefined | |
287 | } | |
288 | ||
289 | async function processThumbnailFromUrl (url: string, video: VideoModel) { | |
290 | try { | |
291 | return createVideoMiniatureFromUrl(url, video, ThumbnailType.MINIATURE) | |
292 | } catch (err) { | |
293 | logger.warn('Cannot generate video thumbnail %s for %s.', url, video.url, { err }) | |
294 | return undefined | |
295 | } | |
296 | } | |
297 | ||
298 | async function processPreviewFromUrl (url: string, video: VideoModel) { | |
299 | try { | |
300 | return createVideoMiniatureFromUrl(url, video, ThumbnailType.PREVIEW) | |
301 | } catch (err) { | |
302 | logger.warn('Cannot generate video preview %s for %s.', url, video.url, { err }) | |
303 | return undefined | |
304 | } | |
305 | } | |
306 | ||
307 | function insertIntoDB (parameters: { | |
308 | video: MVideoThumbnailAccountDefault | |
309 | thumbnailModel: MThumbnail | |
310 | previewModel: MThumbnail | |
311 | videoChannel: MChannelAccountDefault | |
312 | tags: string[] | |
313 | videoImportAttributes: Partial<MVideoImport> | |
314 | user: MUser | |
315 | }): Promise<MVideoImportFormattable> { | |
316 | const { video, thumbnailModel, previewModel, videoChannel, tags, videoImportAttributes, user } = parameters | |
317 | ||
318 | return sequelizeTypescript.transaction(async t => { | |
319 | const sequelizeOptions = { transaction: t } | |
320 | ||
321 | // Save video object in database | |
322 | const videoCreated = await video.save(sequelizeOptions) as (MVideoAccountDefault & MVideoWithBlacklistLight & MVideoTag) | |
323 | videoCreated.VideoChannel = videoChannel | |
324 | ||
325 | if (thumbnailModel) await videoCreated.addAndSaveThumbnail(thumbnailModel, t) | |
326 | if (previewModel) await videoCreated.addAndSaveThumbnail(previewModel, t) | |
327 | ||
328 | await autoBlacklistVideoIfNeeded({ | |
329 | video: videoCreated, | |
330 | user, | |
331 | notify: false, | |
332 | isRemote: false, | |
333 | isNew: true, | |
334 | transaction: t | |
335 | }) | |
336 | ||
337 | await setVideoTags({ video: videoCreated, tags, transaction: t }) | |
338 | ||
339 | // Create video import object in database | |
340 | const videoImport = await VideoImportModel.create( | |
341 | Object.assign({ videoId: videoCreated.id }, videoImportAttributes), | |
342 | sequelizeOptions | |
343 | ) as MVideoImportFormattable | |
344 | videoImport.Video = videoCreated | |
345 | ||
346 | return videoImport | |
347 | }) | |
348 | } |