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