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