]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - server/controllers/api/videos/import.ts
Merge branch 'release/v1.3.0' into develop
[github/Chocobozzz/PeerTube.git] / server / controllers / api / videos / import.ts
... / ...
CommitLineData
1import * as express from 'express'
2import * as magnetUtil from 'magnet-uri'
3import 'multer'
4import { auditLoggerFactory, getAuditIdFromRes, VideoImportAuditView } from '../../../helpers/audit-logger'
5import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate, videoImportAddValidator } from '../../../middlewares'
6import { MIMETYPES } from '../../../initializers/constants'
7import { getYoutubeDLInfo, YoutubeDLInfo } from '../../../helpers/youtube-dl'
8import { createReqFiles } from '../../../helpers/express-utils'
9import { logger } from '../../../helpers/logger'
10import { VideoImportCreate, VideoImportState, VideoPrivacy, VideoState } from '../../../../shared'
11import { VideoModel } from '../../../models/video/video'
12import { getVideoActivityPubUrl } from '../../../lib/activitypub'
13import { TagModel } from '../../../models/video/tag'
14import { VideoImportModel } from '../../../models/video/video-import'
15import { JobQueue } from '../../../lib/job-queue/job-queue'
16import { join } from 'path'
17import { isArray } from '../../../helpers/custom-validators/misc'
18import { VideoChannelModel } from '../../../models/video/video-channel'
19import * as Bluebird from 'bluebird'
20import * as parseTorrent from 'parse-torrent'
21import { getSecureTorrentName } from '../../../helpers/utils'
22import { move, readFile } from 'fs-extra'
23import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist'
24import { CONFIG } from '../../../initializers/config'
25import { sequelizeTypescript } from '../../../initializers/database'
26import { createVideoMiniatureFromExisting } from '../../../lib/thumbnail'
27import { ThumbnailType } from '../../../../shared/models/videos/thumbnail.type'
28import { ThumbnailModel } from '../../../models/video/thumbnail'
29import { UserModel } from '../../../models/account/user'
30
31const auditLogger = auditLoggerFactory('video-imports')
32const videoImportsRouter = express.Router()
33
34const 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
44videoImportsRouter.post('/imports',
45 authenticate,
46 reqVideoFileImport,
47 asyncMiddleware(videoImportAddValidator),
48 asyncRetryTransactionMiddleware(addVideoImport)
49)
50
51// ---------------------------------------------------------------------------
52
53export {
54 videoImportsRouter
55}
56
57// ---------------------------------------------------------------------------
58
59function 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
66async 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
128async 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
180function 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
205async 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)
211 }
212
213 return undefined
214}
215
216async 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)
222 }
223
224 return undefined
225}
226
227function 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(video, user, t)
249
250 // Set tags to the video
251 if (tags) {
252 const tagInstances = await TagModel.findOrCreateTags(tags, t)
253
254 await videoCreated.$set('Tags', tagInstances, sequelizeOptions)
255 videoCreated.Tags = tagInstances
256 } else {
257 videoCreated.Tags = []
258 }
259
260 // Create video import object in database
261 const videoImport = await VideoImportModel.create(
262 Object.assign({ videoId: videoCreated.id }, videoImportAttributes),
263 sequelizeOptions
264 )
265 videoImport.Video = videoCreated
266
267 return videoImport
268 })
269}