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