Use originallyPublishedAt from body on import if it exists
[oweals/peertube.git] / server / controllers / api / videos / import.ts
1 import * as express from 'express'
2 import * as magnetUtil from 'magnet-uri'
3 import { auditLoggerFactory, getAuditIdFromRes, VideoImportAuditView } from '../../../helpers/audit-logger'
4 import { asyncMiddleware, asyncRetryTransactionMiddleware, authenticate, videoImportAddValidator } from '../../../middlewares'
5 import { MIMETYPES } from '../../../initializers/constants'
6 import { getYoutubeDLInfo, YoutubeDLInfo, getYoutubeDLSubs } from '../../../helpers/youtube-dl'
7 import { createReqFiles } from '../../../helpers/express-utils'
8 import { logger } from '../../../helpers/logger'
9 import { VideoImportCreate, VideoImportState, VideoPrivacy, VideoState } from '../../../../shared'
10 import { VideoModel } from '../../../models/video/video'
11 import { VideoCaptionModel } from '../../../models/video/video-caption'
12 import { moveAndProcessCaptionFile } from '../../../helpers/captions-utils'
13 import { getVideoActivityPubUrl } from '../../../lib/activitypub'
14 import { TagModel } from '../../../models/video/tag'
15 import { VideoImportModel } from '../../../models/video/video-import'
16 import { JobQueue } from '../../../lib/job-queue/job-queue'
17 import { join } from 'path'
18 import { isArray } from '../../../helpers/custom-validators/misc'
19 import * as Bluebird from 'bluebird'
20 import * as parseTorrent from 'parse-torrent'
21 import { getSecureTorrentName } from '../../../helpers/utils'
22 import { move, readFile } from 'fs-extra'
23 import { autoBlacklistVideoIfNeeded } from '../../../lib/video-blacklist'
24 import { CONFIG } from '../../../initializers/config'
25 import { sequelizeTypescript } from '../../../initializers/database'
26 import { createVideoMiniatureFromExisting } from '../../../lib/thumbnail'
27 import { ThumbnailType } from '../../../../shared/models/videos/thumbnail.type'
28 import {
29   MChannelAccountDefault,
30   MThumbnail,
31   MUser,
32   MVideoAccountDefault,
33   MVideoCaptionVideo,
34   MVideoTag,
35   MVideoThumbnailAccountDefault,
36   MVideoWithBlacklistLight
37 } from '@server/typings/models'
38 import { MVideoImport, MVideoImportFormattable } from '@server/typings/models/video/video-import'
39
40 const auditLogger = auditLoggerFactory('video-imports')
41 const videoImportsRouter = express.Router()
42
43 const reqVideoFileImport = createReqFiles(
44   [ 'thumbnailfile', 'previewfile', 'torrentfile' ],
45   Object.assign({}, MIMETYPES.TORRENT.MIMETYPE_EXT, MIMETYPES.IMAGE.MIMETYPE_EXT),
46   {
47     thumbnailfile: CONFIG.STORAGE.TMP_DIR,
48     previewfile: CONFIG.STORAGE.TMP_DIR,
49     torrentfile: CONFIG.STORAGE.TMP_DIR
50   }
51 )
52
53 videoImportsRouter.post('/imports',
54   authenticate,
55   reqVideoFileImport,
56   asyncMiddleware(videoImportAddValidator),
57   asyncRetryTransactionMiddleware(addVideoImport)
58 )
59
60 // ---------------------------------------------------------------------------
61
62 export {
63   videoImportsRouter
64 }
65
66 // ---------------------------------------------------------------------------
67
68 function addVideoImport (req: express.Request, res: express.Response) {
69   if (req.body.targetUrl) return addYoutubeDLImport(req, res)
70
71   const file = req.files && req.files['torrentfile'] ? req.files['torrentfile'][0] : undefined
72   if (req.body.magnetUri || file) return addTorrentImport(req, res, file)
73 }
74
75 async function addTorrentImport (req: express.Request, res: express.Response, torrentfile: Express.Multer.File) {
76   const body: VideoImportCreate = req.body
77   const user = res.locals.oauth.token.User
78
79   let videoName: string
80   let torrentName: string
81   let magnetUri: string
82
83   if (torrentfile) {
84     torrentName = torrentfile.originalname
85
86     // Rename the torrent to a secured name
87     const newTorrentPath = join(CONFIG.STORAGE.TORRENTS_DIR, getSecureTorrentName(torrentName))
88     await move(torrentfile.path, newTorrentPath)
89     torrentfile.path = newTorrentPath
90
91     const buf = await readFile(torrentfile.path)
92     const parsedTorrent = parseTorrent(buf)
93
94     videoName = isArray(parsedTorrent.name) ? parsedTorrent.name[0] : parsedTorrent.name as string
95   } else {
96     magnetUri = body.magnetUri
97
98     const parsed = magnetUtil.decode(magnetUri)
99     videoName = isArray(parsed.name) ? parsed.name[0] : parsed.name as string
100   }
101
102   const video = buildVideo(res.locals.videoChannel.id, body, { name: videoName })
103
104   const thumbnailModel = await processThumbnail(req, video)
105   const previewModel = await processPreview(req, video)
106
107   const tags = body.tags || undefined
108   const videoImportAttributes = {
109     magnetUri,
110     torrentName,
111     state: VideoImportState.PENDING,
112     userId: user.id
113   }
114   const videoImport = await insertIntoDB({
115     video,
116     thumbnailModel,
117     previewModel,
118     videoChannel: res.locals.videoChannel,
119     tags,
120     videoImportAttributes,
121     user
122   })
123
124   // Create job to import the video
125   const payload = {
126     type: torrentfile ? 'torrent-file' as 'torrent-file' : 'magnet-uri' as 'magnet-uri',
127     videoImportId: videoImport.id,
128     magnetUri
129   }
130   await JobQueue.Instance.createJobWithPromise({ type: 'video-import', payload })
131
132   auditLogger.create(getAuditIdFromRes(res), new VideoImportAuditView(videoImport.toFormattedJSON()))
133
134   return res.json(videoImport.toFormattedJSON()).end()
135 }
136
137 async function addYoutubeDLImport (req: express.Request, res: express.Response) {
138   const body: VideoImportCreate = req.body
139   const targetUrl = body.targetUrl
140   const user = res.locals.oauth.token.User
141
142   // Get video infos
143   let youtubeDLInfo: YoutubeDLInfo
144   try {
145     youtubeDLInfo = await getYoutubeDLInfo(targetUrl)
146   } catch (err) {
147     logger.info('Cannot fetch information from import for URL %s.', targetUrl, { err })
148
149     return res.status(400).json({
150       error: 'Cannot fetch remote information of this URL.'
151     }).end()
152   }
153
154   const video = buildVideo(res.locals.videoChannel.id, body, youtubeDLInfo)
155
156   const thumbnailModel = await processThumbnail(req, video)
157   const previewModel = await processPreview(req, video)
158
159   const tags = body.tags || youtubeDLInfo.tags
160   const videoImportAttributes = {
161     targetUrl,
162     state: VideoImportState.PENDING,
163     userId: user.id
164   }
165   const videoImport = await insertIntoDB({
166     video,
167     thumbnailModel,
168     previewModel,
169     videoChannel: res.locals.videoChannel,
170     tags,
171     videoImportAttributes,
172     user
173   })
174
175   // Get video subtitles
176   try {
177     const subtitles = await getYoutubeDLSubs(targetUrl)
178
179     logger.info('Will create %s subtitles from youtube import %s.', subtitles.length, targetUrl)
180
181     for (const subtitle of subtitles) {
182       const videoCaption = new VideoCaptionModel({
183         videoId: video.id,
184         language: subtitle.language
185       }) as MVideoCaptionVideo
186       videoCaption.Video = video
187
188       // Move physical file
189       await moveAndProcessCaptionFile(subtitle, videoCaption)
190
191       await sequelizeTypescript.transaction(async t => {
192         await VideoCaptionModel.insertOrReplaceLanguage(video.id, subtitle.language, null, t)
193       })
194     }
195   } catch (err) {
196     logger.warn('Cannot get video subtitles.', { err })
197   }
198
199   // Create job to import the video
200   const payload = {
201     type: 'youtube-dl' as 'youtube-dl',
202     videoImportId: videoImport.id,
203     thumbnailUrl: youtubeDLInfo.thumbnailUrl,
204     downloadThumbnail: !thumbnailModel,
205     downloadPreview: !previewModel,
206     fileExt: youtubeDLInfo.fileExt
207       ? `.${youtubeDLInfo.fileExt}`
208       : '.mp4'
209   }
210   await JobQueue.Instance.createJobWithPromise({ type: 'video-import', payload })
211
212   auditLogger.create(getAuditIdFromRes(res), new VideoImportAuditView(videoImport.toFormattedJSON()))
213
214   return res.json(videoImport.toFormattedJSON()).end()
215 }
216
217 function buildVideo (channelId: number, body: VideoImportCreate, importData: YoutubeDLInfo) {
218   const videoData = {
219     name: body.name || importData.name || 'Unknown name',
220     remote: false,
221     category: body.category || importData.category,
222     licence: body.licence || importData.licence,
223     language: body.language || undefined,
224     commentsEnabled: body.commentsEnabled !== false, // If the value is not "false", the default is "true"
225     downloadEnabled: body.downloadEnabled !== false,
226     waitTranscoding: body.waitTranscoding || false,
227     state: VideoState.TO_IMPORT,
228     nsfw: body.nsfw || importData.nsfw || false,
229     description: body.description || importData.description,
230     support: body.support || null,
231     privacy: body.privacy || VideoPrivacy.PRIVATE,
232     duration: 0, // duration will be set by the import job
233     channelId: channelId,
234     originallyPublishedAt: body.originallyPublishedAt || importData.originallyPublishedAt
235   }
236   const video = new VideoModel(videoData)
237   video.url = getVideoActivityPubUrl(video)
238
239   return video
240 }
241
242 async function processThumbnail (req: express.Request, video: VideoModel) {
243   const thumbnailField = req.files ? req.files['thumbnailfile'] : undefined
244   if (thumbnailField) {
245     const thumbnailPhysicalFile = thumbnailField[0]
246
247     return createVideoMiniatureFromExisting(thumbnailPhysicalFile.path, video, ThumbnailType.MINIATURE, false)
248   }
249
250   return undefined
251 }
252
253 async function processPreview (req: express.Request, video: VideoModel) {
254   const previewField = req.files ? req.files['previewfile'] : undefined
255   if (previewField) {
256     const previewPhysicalFile = previewField[0]
257
258     return createVideoMiniatureFromExisting(previewPhysicalFile.path, video, ThumbnailType.PREVIEW, false)
259   }
260
261   return undefined
262 }
263
264 function insertIntoDB (parameters: {
265   video: MVideoThumbnailAccountDefault
266   thumbnailModel: MThumbnail
267   previewModel: MThumbnail
268   videoChannel: MChannelAccountDefault
269   tags: string[]
270   videoImportAttributes: Partial<MVideoImport>
271   user: MUser
272 }): Bluebird<MVideoImportFormattable> {
273   const { video, thumbnailModel, previewModel, videoChannel, tags, videoImportAttributes, user } = parameters
274
275   return sequelizeTypescript.transaction(async t => {
276     const sequelizeOptions = { transaction: t }
277
278     // Save video object in database
279     const videoCreated = await video.save(sequelizeOptions) as (MVideoAccountDefault & MVideoWithBlacklistLight & MVideoTag)
280     videoCreated.VideoChannel = videoChannel
281
282     if (thumbnailModel) await videoCreated.addAndSaveThumbnail(thumbnailModel, t)
283     if (previewModel) await videoCreated.addAndSaveThumbnail(previewModel, t)
284
285     await autoBlacklistVideoIfNeeded({
286       video: videoCreated,
287       user,
288       notify: false,
289       isRemote: false,
290       isNew: true,
291       transaction: t
292     })
293
294     // Set tags to the video
295     if (tags) {
296       const tagInstances = await TagModel.findOrCreateTags(tags, t)
297
298       await videoCreated.$set('Tags', tagInstances, sequelizeOptions)
299       videoCreated.Tags = tagInstances
300     } else {
301       videoCreated.Tags = []
302     }
303
304     // Create video import object in database
305     const videoImport = await VideoImportModel.create(
306       Object.assign({ videoId: videoCreated.id }, videoImportAttributes),
307       sequelizeOptions
308     ) as MVideoImportFormattable
309     videoImport.Video = videoCreated
310
311     return videoImport
312   })
313 }