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