]>
Commit | Line | Data |
---|---|---|
1 | import * as express from 'express' | |
2 | import * as magnetUtil from 'magnet-uri' | |
3 | import 'multer' | |
4 | import { auditLoggerFactory, getAuditIdFromRes, VideoImportAuditView } from '../../../helpers/audit-logger' | |
5 | import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate, videoImportAddValidator } from '../../../middlewares' | |
6 | import { MIMETYPES } from '../../../initializers/constants' | |
7 | import { getYoutubeDLInfo, YoutubeDLInfo } from '../../../helpers/youtube-dl' | |
8 | import { createReqFiles } from '../../../helpers/express-utils' | |
9 | import { logger } from '../../../helpers/logger' | |
10 | import { VideoImportCreate, VideoImportState, VideoPrivacy, VideoState } from '../../../../shared' | |
11 | import { VideoModel } from '../../../models/video/video' | |
12 | import { getVideoActivityPubUrl } from '../../../lib/activitypub' | |
13 | import { TagModel } from '../../../models/video/tag' | |
14 | import { VideoImportModel } from '../../../models/video/video-import' | |
15 | import { JobQueue } from '../../../lib/job-queue/job-queue' | |
16 | import { join } from 'path' | |
17 | import { isArray } from '../../../helpers/custom-validators/misc' | |
18 | import { VideoChannelModel } from '../../../models/video/video-channel' | |
19 | import * as Bluebird from 'bluebird' | |
20 | import * as parseTorrent from 'parse-torrent' | |
21 | import { getSecureTorrentName } from '../../../helpers/utils' | |
22 | import { move, readFile } from 'fs-extra' | |
23 | import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist' | |
24 | import { CONFIG } from '../../../initializers/config' | |
25 | import { sequelizeTypescript } from '../../../initializers/database' | |
26 | import { createVideoMiniatureFromExisting } from '../../../lib/thumbnail' | |
27 | import { ThumbnailType } from '../../../../shared/models/videos/thumbnail.type' | |
28 | import { ThumbnailModel } from '../../../models/video/thumbnail' | |
29 | import { UserModel } from '../../../models/account/user' | |
30 | ||
31 | const auditLogger = auditLoggerFactory('video-imports') | |
32 | const videoImportsRouter = express.Router() | |
33 | ||
34 | const reqVideoFileImport = createReqFiles( | |
35 | [ 'thumbnailfile', 'previewfile', 'torrentfile' ], | |
36 | Object.assign({}, MIMETYPES.TORRENT.MIMETYPE_EXT, MIMETYPES.IMAGE.MIMETYPE_EXT), | |
37 | { | |
38 | thumbnailfile: CONFIG.STORAGE.TMP_DIR, | |
39 | previewfile: CONFIG.STORAGE.TMP_DIR, | |
40 | torrentfile: CONFIG.STORAGE.TMP_DIR | |
41 | } | |
42 | ) | |
43 | ||
44 | videoImportsRouter.post('/imports', | |
45 | authenticate, | |
46 | reqVideoFileImport, | |
47 | asyncMiddleware(videoImportAddValidator), | |
48 | asyncRetryTransactionMiddleware(addVideoImport) | |
49 | ) | |
50 | ||
51 | // --------------------------------------------------------------------------- | |
52 | ||
53 | export { | |
54 | videoImportsRouter | |
55 | } | |
56 | ||
57 | // --------------------------------------------------------------------------- | |
58 | ||
59 | function addVideoImport (req: express.Request, res: express.Response) { | |
60 | if (req.body.targetUrl) return addYoutubeDLImport(req, res) | |
61 | ||
62 | const file = req.files && req.files['torrentfile'] ? req.files['torrentfile'][0] : undefined | |
63 | if (req.body.magnetUri || file) return addTorrentImport(req, res, file) | |
64 | } | |
65 | ||
66 | async function addTorrentImport (req: express.Request, res: express.Response, torrentfile: Express.Multer.File) { | |
67 | const body: VideoImportCreate = req.body | |
68 | const user = res.locals.oauth.token.User | |
69 | ||
70 | let videoName: string | |
71 | let torrentName: string | |
72 | let magnetUri: string | |
73 | ||
74 | if (torrentfile) { | |
75 | torrentName = torrentfile.originalname | |
76 | ||
77 | // Rename the torrent to a secured name | |
78 | const newTorrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, getSecureTorrentName(torrentName)) | |
79 | await move(torrentfile.path, newTorrentPath) | |
80 | torrentfile.path = newTorrentPath | |
81 | ||
82 | const buf = await readFile(torrentfile.path) | |
83 | const parsedTorrent = parseTorrent(buf) | |
84 | ||
85 | videoName = isArray(parsedTorrent.name) ? parsedTorrent.name[ 0 ] : parsedTorrent.name as string | |
86 | } else { | |
87 | magnetUri = body.magnetUri | |
88 | ||
89 | const parsed = magnetUtil.decode(magnetUri) | |
90 | videoName = isArray(parsed.name) ? parsed.name[ 0 ] : parsed.name as string | |
91 | } | |
92 | ||
93 | const video = buildVideo(res.locals.videoChannel.id, body, { name: videoName }) | |
94 | ||
95 | const thumbnailModel = await processThumbnail(req, video) | |
96 | const previewModel = await processPreview(req, video) | |
97 | ||
98 | const tags = body.tags || undefined | |
99 | const videoImportAttributes = { | |
100 | magnetUri, | |
101 | torrentName, | |
102 | state: VideoImportState.PENDING, | |
103 | userId: user.id | |
104 | } | |
105 | const videoImport = await insertIntoDB({ | |
106 | video, | |
107 | thumbnailModel, | |
108 | previewModel, | |
109 | videoChannel: res.locals.videoChannel, | |
110 | tags, | |
111 | videoImportAttributes, | |
112 | user | |
113 | }) | |
114 | ||
115 | // Create job to import the video | |
116 | const payload = { | |
117 | type: torrentfile ? 'torrent-file' as 'torrent-file' : 'magnet-uri' as 'magnet-uri', | |
118 | videoImportId: videoImport.id, | |
119 | magnetUri | |
120 | } | |
121 | await JobQueue.Instance.createJob({ type: 'video-import', payload }) | |
122 | ||
123 | auditLogger.create(getAuditIdFromRes(res), new VideoImportAuditView(videoImport.toFormattedJSON())) | |
124 | ||
125 | return res.json(videoImport.toFormattedJSON()).end() | |
126 | } | |
127 | ||
128 | async function addYoutubeDLImport (req: express.Request, res: express.Response) { | |
129 | const body: VideoImportCreate = req.body | |
130 | const targetUrl = body.targetUrl | |
131 | const user = res.locals.oauth.token.User | |
132 | ||
133 | let youtubeDLInfo: YoutubeDLInfo | |
134 | try { | |
135 | youtubeDLInfo = await getYoutubeDLInfo(targetUrl) | |
136 | } catch (err) { | |
137 | logger.info('Cannot fetch information from import for URL %s.', targetUrl, { err }) | |
138 | ||
139 | return res.status(400).json({ | |
140 | error: 'Cannot fetch remote information of this URL.' | |
141 | }).end() | |
142 | } | |
143 | ||
144 | const video = buildVideo(res.locals.videoChannel.id, body, youtubeDLInfo) | |
145 | ||
146 | const thumbnailModel = await processThumbnail(req, video) | |
147 | const previewModel = await processPreview(req, video) | |
148 | ||
149 | const tags = body.tags || youtubeDLInfo.tags | |
150 | const videoImportAttributes = { | |
151 | targetUrl, | |
152 | state: VideoImportState.PENDING, | |
153 | userId: user.id | |
154 | } | |
155 | const videoImport = await insertIntoDB({ | |
156 | video, | |
157 | thumbnailModel, | |
158 | previewModel, | |
159 | videoChannel: res.locals.videoChannel, | |
160 | tags, | |
161 | videoImportAttributes, | |
162 | user | |
163 | }) | |
164 | ||
165 | // Create job to import the video | |
166 | const payload = { | |
167 | type: 'youtube-dl' as 'youtube-dl', | |
168 | videoImportId: videoImport.id, | |
169 | thumbnailUrl: youtubeDLInfo.thumbnailUrl, | |
170 | downloadThumbnail: !thumbnailModel, | |
171 | downloadPreview: !previewModel | |
172 | } | |
173 | await JobQueue.Instance.createJob({ type: 'video-import', payload }) | |
174 | ||
175 | auditLogger.create(getAuditIdFromRes(res), new VideoImportAuditView(videoImport.toFormattedJSON())) | |
176 | ||
177 | return res.json(videoImport.toFormattedJSON()).end() | |
178 | } | |
179 | ||
180 | function buildVideo (channelId: number, body: VideoImportCreate, importData: YoutubeDLInfo) { | |
181 | const videoData = { | |
182 | name: body.name || importData.name || 'Unknown name', | |
183 | remote: false, | |
184 | category: body.category || importData.category, | |
185 | licence: body.licence || importData.licence, | |
186 | language: body.language || undefined, | |
187 | commentsEnabled: body.commentsEnabled || true, | |
188 | downloadEnabled: body.downloadEnabled || true, | |
189 | waitTranscoding: body.waitTranscoding || false, | |
190 | state: VideoState.TO_IMPORT, | |
191 | nsfw: body.nsfw || importData.nsfw || false, | |
192 | description: body.description || importData.description, | |
193 | support: body.support || null, | |
194 | privacy: body.privacy || VideoPrivacy.PRIVATE, | |
195 | duration: 0, // duration will be set by the import job | |
196 | channelId: channelId, | |
197 | originallyPublishedAt: importData.originallyPublishedAt | |
198 | } | |
199 | const video = new VideoModel(videoData) | |
200 | video.url = getVideoActivityPubUrl(video) | |
201 | ||
202 | return video | |
203 | } | |
204 | ||
205 | async function processThumbnail (req: express.Request, video: VideoModel) { | |
206 | const thumbnailField = req.files ? req.files['thumbnailfile'] : undefined | |
207 | if (thumbnailField) { | |
208 | const thumbnailPhysicalFile = thumbnailField[ 0 ] | |
209 | ||
210 | return createVideoMiniatureFromExisting(thumbnailPhysicalFile.path, video, ThumbnailType.MINIATURE, false) | |
211 | } | |
212 | ||
213 | return undefined | |
214 | } | |
215 | ||
216 | async function processPreview (req: express.Request, video: VideoModel) { | |
217 | const previewField = req.files ? req.files['previewfile'] : undefined | |
218 | if (previewField) { | |
219 | const previewPhysicalFile = previewField[0] | |
220 | ||
221 | return createVideoMiniatureFromExisting(previewPhysicalFile.path, video, ThumbnailType.PREVIEW, false) | |
222 | } | |
223 | ||
224 | return undefined | |
225 | } | |
226 | ||
227 | function insertIntoDB (parameters: { | |
228 | video: VideoModel, | |
229 | thumbnailModel: ThumbnailModel, | |
230 | previewModel: ThumbnailModel, | |
231 | videoChannel: VideoChannelModel, | |
232 | tags: string[], | |
233 | videoImportAttributes: Partial<VideoImportModel>, | |
234 | user: UserModel | |
235 | }): Bluebird<VideoImportModel> { | |
236 | const { video, thumbnailModel, previewModel, videoChannel, tags, videoImportAttributes, user } = parameters | |
237 | ||
238 | return sequelizeTypescript.transaction(async t => { | |
239 | const sequelizeOptions = { transaction: t } | |
240 | ||
241 | // Save video object in database | |
242 | const videoCreated = await video.save(sequelizeOptions) | |
243 | videoCreated.VideoChannel = videoChannel | |
244 | ||
245 | if (thumbnailModel) await videoCreated.addAndSaveThumbnail(thumbnailModel, t) | |
246 | if (previewModel) await videoCreated.addAndSaveThumbnail(previewModel, t) | |
247 | ||
248 | await autoBlacklistVideoIfNeeded({ | |
249 | video, | |
250 | user, | |
251 | notify: false, | |
252 | isRemote: false, | |
253 | isNew: true, | |
254 | transaction: t | |
255 | }) | |
256 | ||
257 | // Set tags to the video | |
258 | if (tags) { | |
259 | const tagInstances = await TagModel.findOrCreateTags(tags, t) | |
260 | ||
261 | await videoCreated.$set('Tags', tagInstances, sequelizeOptions) | |
262 | videoCreated.Tags = tagInstances | |
263 | } else { | |
264 | videoCreated.Tags = [] | |
265 | } | |
266 | ||
267 | // Create video import object in database | |
268 | const videoImport = await VideoImportModel.create( | |
269 | Object.assign({ videoId: videoCreated.id }, videoImportAttributes), | |
270 | sequelizeOptions | |
271 | ) | |
272 | videoImport.Video = videoCreated | |
273 | ||
274 | return videoImport | |
275 | }) | |
276 | } |