]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/api/videos/import.ts
Add filter hooks tests
[github/Chocobozzz/PeerTube.git] / server / controllers / api / videos / import.ts
CommitLineData
fbad87b0 1import * as express from 'express'
990b6a0b
C
2import * as magnetUtil from 'magnet-uri'
3import 'multer'
993cef4b 4import { auditLoggerFactory, getAuditIdFromRes, VideoImportAuditView } from '../../../helpers/audit-logger'
7e5f9f00 5import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate, videoImportAddValidator } from '../../../middlewares'
e8bafea3 6import { MIMETYPES } from '../../../initializers/constants'
fbad87b0
C
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'
fbad87b0 16import { join } from 'path'
ce33919c 17import { isArray } from '../../../helpers/custom-validators/misc'
ce33919c
C
18import { VideoChannelModel } from '../../../models/video/video-channel'
19import * as Bluebird from 'bluebird'
990b6a0b 20import * as parseTorrent from 'parse-torrent'
990b6a0b 21import { getSecureTorrentName } from '../../../helpers/utils'
6dd9de95 22import { move, readFile } from 'fs-extra'
7ccddd7b 23import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist'
6dd9de95 24import { CONFIG } from '../../../initializers/config'
74dc3bca 25import { sequelizeTypescript } from '../../../initializers/database'
3acc5084 26import { createVideoMiniatureFromExisting } from '../../../lib/thumbnail'
e8bafea3
C
27import { ThumbnailType } from '../../../../shared/models/videos/thumbnail.type'
28import { ThumbnailModel } from '../../../models/video/thumbnail'
03371ad9 29import { UserModel } from '../../../models/account/user'
fbad87b0
C
30
31const auditLogger = auditLoggerFactory('video-imports')
32const videoImportsRouter = express.Router()
33
34const reqVideoFileImport = createReqFiles(
990b6a0b 35 [ 'thumbnailfile', 'previewfile', 'torrentfile' ],
14e2014a 36 Object.assign({}, MIMETYPES.TORRENT.MIMETYPE_EXT, MIMETYPES.IMAGE.MIMETYPE_EXT),
fbad87b0 37 {
6040f87d
C
38 thumbnailfile: CONFIG.STORAGE.TMP_DIR,
39 previewfile: CONFIG.STORAGE.TMP_DIR,
40 torrentfile: CONFIG.STORAGE.TMP_DIR
fbad87b0
C
41 }
42)
43
44videoImportsRouter.post('/imports',
45 authenticate,
46 reqVideoFileImport,
47 asyncMiddleware(videoImportAddValidator),
48 asyncRetryTransactionMiddleware(addVideoImport)
49)
50
fbad87b0
C
51// ---------------------------------------------------------------------------
52
53export {
54 videoImportsRouter
55}
56
57// ---------------------------------------------------------------------------
58
ce33919c
C
59function addVideoImport (req: express.Request, res: express.Response) {
60 if (req.body.targetUrl) return addYoutubeDLImport(req, res)
61
a84b8fa5 62 const file = req.files && req.files['torrentfile'] ? req.files['torrentfile'][0] : undefined
990b6a0b 63 if (req.body.magnetUri || file) return addTorrentImport(req, res, file)
ce33919c
C
64}
65
990b6a0b 66async function addTorrentImport (req: express.Request, res: express.Response, torrentfile: Express.Multer.File) {
ce33919c 67 const body: VideoImportCreate = req.body
a84b8fa5 68 const user = res.locals.oauth.token.User
ce33919c 69
990b6a0b
C
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))
f481c4f9 79 await move(torrentfile.path, newTorrentPath)
990b6a0b
C
80 torrentfile.path = newTorrentPath
81
62689b94 82 const buf = await readFile(torrentfile.path)
990b6a0b
C
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 }
ce33919c 92
e8bafea3 93 const video = buildVideo(res.locals.videoChannel.id, body, { name: videoName })
ce33919c 94
e8bafea3
C
95 const thumbnailModel = await processThumbnail(req, video)
96 const previewModel = await processPreview(req, video)
ce33919c 97
3e17515e 98 const tags = body.tags || undefined
ce33919c
C
99 const videoImportAttributes = {
100 magnetUri,
990b6a0b 101 torrentName,
a84b8fa5
C
102 state: VideoImportState.PENDING,
103 userId: user.id
ce33919c 104 }
e8bafea3
C
105 const videoImport = await insertIntoDB({
106 video,
107 thumbnailModel,
108 previewModel,
109 videoChannel: res.locals.videoChannel,
110 tags,
03371ad9
C
111 videoImportAttributes,
112 user
e8bafea3 113 })
ce33919c
C
114
115 // Create job to import the video
116 const payload = {
990b6a0b 117 type: torrentfile ? 'torrent-file' as 'torrent-file' : 'magnet-uri' as 'magnet-uri',
ce33919c
C
118 videoImportId: videoImport.id,
119 magnetUri
120 }
121 await JobQueue.Instance.createJob({ type: 'video-import', payload })
122
993cef4b 123 auditLogger.create(getAuditIdFromRes(res), new VideoImportAuditView(videoImport.toFormattedJSON()))
ce33919c
C
124
125 return res.json(videoImport.toFormattedJSON()).end()
126}
127
128async function addYoutubeDLImport (req: express.Request, res: express.Response) {
fbad87b0
C
129 const body: VideoImportCreate = req.body
130 const targetUrl = body.targetUrl
a84b8fa5 131 const user = res.locals.oauth.token.User
fbad87b0
C
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
e8bafea3 144 const video = buildVideo(res.locals.videoChannel.id, body, youtubeDLInfo)
ce33919c 145
e8bafea3
C
146 const thumbnailModel = await processThumbnail(req, video)
147 const previewModel = await processPreview(req, video)
ce33919c
C
148
149 const tags = body.tags || youtubeDLInfo.tags
150 const videoImportAttributes = {
151 targetUrl,
a84b8fa5
C
152 state: VideoImportState.PENDING,
153 userId: user.id
ce33919c 154 }
e8bafea3 155 const videoImport = await insertIntoDB({
03371ad9 156 video,
e8bafea3
C
157 thumbnailModel,
158 previewModel,
159 videoChannel: res.locals.videoChannel,
160 tags,
03371ad9
C
161 videoImportAttributes,
162 user
e8bafea3 163 })
ce33919c
C
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,
e8bafea3
C
170 downloadThumbnail: !thumbnailModel,
171 downloadPreview: !previewModel
ce33919c
C
172 }
173 await JobQueue.Instance.createJob({ type: 'video-import', payload })
174
993cef4b 175 auditLogger.create(getAuditIdFromRes(res), new VideoImportAuditView(videoImport.toFormattedJSON()))
ce33919c
C
176
177 return res.json(videoImport.toFormattedJSON()).end()
178}
179
e8bafea3 180function buildVideo (channelId: number, body: VideoImportCreate, importData: YoutubeDLInfo) {
fbad87b0 181 const videoData = {
ce33919c 182 name: body.name || importData.name || 'Unknown name',
fbad87b0 183 remote: false,
ce33919c
C
184 category: body.category || importData.category,
185 licence: body.licence || importData.licence,
590fb506 186 language: body.language || undefined,
fbad87b0 187 commentsEnabled: body.commentsEnabled || true,
7f2cfe3a 188 downloadEnabled: body.downloadEnabled || true,
fbad87b0
C
189 waitTranscoding: body.waitTranscoding || false,
190 state: VideoState.TO_IMPORT,
ce33919c
C
191 nsfw: body.nsfw || importData.nsfw || false,
192 description: body.description || importData.description,
fbad87b0
C
193 support: body.support || null,
194 privacy: body.privacy || VideoPrivacy.PRIVATE,
195 duration: 0, // duration will be set by the import job
4e553a41
AM
196 channelId: channelId,
197 originallyPublishedAt: importData.originallyPublishedAt
fbad87b0
C
198 }
199 const video = new VideoModel(videoData)
200 video.url = getVideoActivityPubUrl(video)
201
ce33919c
C
202 return video
203}
204
205async function processThumbnail (req: express.Request, video: VideoModel) {
5d08a6a7 206 const thumbnailField = req.files ? req.files['thumbnailfile'] : undefined
fbad87b0
C
207 if (thumbnailField) {
208 const thumbnailPhysicalFile = thumbnailField[ 0 ]
ce33919c 209
3acc5084 210 return createVideoMiniatureFromExisting(thumbnailPhysicalFile.path, video, ThumbnailType.MINIATURE)
fbad87b0
C
211 }
212
e8bafea3 213 return undefined
ce33919c
C
214}
215
216async function processPreview (req: express.Request, video: VideoModel) {
5d08a6a7 217 const previewField = req.files ? req.files['previewfile'] : undefined
fbad87b0
C
218 if (previewField) {
219 const previewPhysicalFile = previewField[0]
ce33919c 220
3acc5084 221 return createVideoMiniatureFromExisting(previewPhysicalFile.path, video, ThumbnailType.PREVIEW)
fbad87b0
C
222 }
223
e8bafea3 224 return undefined
ce33919c
C
225}
226
e8bafea3 227function insertIntoDB (parameters: {
ce33919c 228 video: VideoModel,
e8bafea3
C
229 thumbnailModel: ThumbnailModel,
230 previewModel: ThumbnailModel,
ce33919c
C
231 videoChannel: VideoChannelModel,
232 tags: string[],
03371ad9
C
233 videoImportAttributes: Partial<VideoImportModel>,
234 user: UserModel
e8bafea3 235}): Bluebird<VideoImportModel> {
03371ad9 236 const { video, thumbnailModel, previewModel, videoChannel, tags, videoImportAttributes, user } = parameters
e8bafea3 237
ce33919c 238 return sequelizeTypescript.transaction(async t => {
fbad87b0
C
239 const sequelizeOptions = { transaction: t }
240
241 // Save video object in database
242 const videoCreated = await video.save(sequelizeOptions)
ce33919c 243 videoCreated.VideoChannel = videoChannel
fbad87b0 244
3acc5084
C
245 if (thumbnailModel) await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
246 if (previewModel) await videoCreated.addAndSaveThumbnail(previewModel, t)
e8bafea3 247
6691c522 248 await autoBlacklistVideoIfNeeded({ video, user, isRemote: false, isNew: true, transaction: t })
7ccddd7b 249
fbad87b0 250 // Set tags to the video
3e17515e 251 if (tags) {
590fb506 252 const tagInstances = await TagModel.findOrCreateTags(tags, t)
fbad87b0
C
253
254 await videoCreated.$set('Tags', tagInstances, sequelizeOptions)
255 videoCreated.Tags = tagInstances
3e17515e
C
256 } else {
257 videoCreated.Tags = []
fbad87b0
C
258 }
259
260 // Create video import object in database
ce33919c
C
261 const videoImport = await VideoImportModel.create(
262 Object.assign({ videoId: videoCreated.id }, videoImportAttributes),
263 sequelizeOptions
264 )
fbad87b0
C
265 videoImport.Video = videoCreated
266
267 return videoImport
268 })
fbad87b0 269}