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