Move to eslint
[oweals/peertube.git] / server / lib / job-queue / handlers / video-import.ts
1 import * as Bull from 'bull'
2 import { logger } from '../../../helpers/logger'
3 import { downloadYoutubeDLVideo } from '../../../helpers/youtube-dl'
4 import { VideoImportModel } from '../../../models/video/video-import'
5 import { VideoImportState } from '../../../../shared/models/videos'
6 import { getDurationFromVideoFile, getVideoFileFPS, getVideoFileResolution } from '../../../helpers/ffmpeg-utils'
7 import { extname } from 'path'
8 import { VideoFileModel } from '../../../models/video/video-file'
9 import { VIDEO_IMPORT_TIMEOUT } from '../../../initializers/constants'
10 import { VideoState } from '../../../../shared'
11 import { JobQueue } from '../index'
12 import { federateVideoIfNeeded } from '../../activitypub'
13 import { VideoModel } from '../../../models/video/video'
14 import { createTorrentAndSetInfoHash, downloadWebTorrentVideo } from '../../../helpers/webtorrent'
15 import { getSecureTorrentName } from '../../../helpers/utils'
16 import { move, remove, stat } from 'fs-extra'
17 import { Notifier } from '../../notifier'
18 import { CONFIG } from '../../../initializers/config'
19 import { sequelizeTypescript } from '../../../initializers/database'
20 import { createVideoMiniatureFromUrl, generateVideoMiniature } from '../../thumbnail'
21 import { ThumbnailType } from '../../../../shared/models/videos/thumbnail.type'
22 import { MThumbnail } from '../../../typings/models/video/thumbnail'
23 import { MVideoImportDefault, MVideoImportDefaultFiles, MVideoImportVideo } from '@server/typings/models/video/video-import'
24 import { getVideoFilePath } from '@server/lib/video-paths'
25
26 type VideoImportYoutubeDLPayload = {
27   type: 'youtube-dl'
28   videoImportId: number
29
30   thumbnailUrl: string
31   downloadThumbnail: boolean
32   downloadPreview: boolean
33 }
34
35 type VideoImportTorrentPayload = {
36   type: 'magnet-uri' | 'torrent-file'
37   videoImportId: number
38 }
39
40 export type VideoImportPayload = VideoImportYoutubeDLPayload | VideoImportTorrentPayload
41
42 async function processVideoImport (job: Bull.Job) {
43   const payload = job.data as VideoImportPayload
44
45   if (payload.type === 'youtube-dl') return processYoutubeDLImport(job, payload)
46   if (payload.type === 'magnet-uri' || payload.type === 'torrent-file') return processTorrentImport(job, payload)
47 }
48
49 // ---------------------------------------------------------------------------
50
51 export {
52   processVideoImport
53 }
54
55 // ---------------------------------------------------------------------------
56
57 async function processTorrentImport (job: Bull.Job, payload: VideoImportTorrentPayload) {
58   logger.info('Processing torrent video import in job %d.', job.id)
59
60   const videoImport = await getVideoImportOrDie(payload.videoImportId)
61
62   const options = {
63     videoImportId: payload.videoImportId,
64
65     downloadThumbnail: false,
66     downloadPreview: false,
67
68     generateThumbnail: true,
69     generatePreview: true
70   }
71   const target = {
72     torrentName: videoImport.torrentName ? getSecureTorrentName(videoImport.torrentName) : undefined,
73     magnetUri: videoImport.magnetUri
74   }
75   return processFile(() => downloadWebTorrentVideo(target, VIDEO_IMPORT_TIMEOUT), videoImport, options)
76 }
77
78 async function processYoutubeDLImport (job: Bull.Job, payload: VideoImportYoutubeDLPayload) {
79   logger.info('Processing youtubeDL video import in job %d.', job.id)
80
81   const videoImport = await getVideoImportOrDie(payload.videoImportId)
82   const options = {
83     videoImportId: videoImport.id,
84
85     downloadThumbnail: payload.downloadThumbnail,
86     downloadPreview: payload.downloadPreview,
87     thumbnailUrl: payload.thumbnailUrl,
88
89     generateThumbnail: false,
90     generatePreview: false
91   }
92
93   return processFile(() => downloadYoutubeDLVideo(videoImport.targetUrl, VIDEO_IMPORT_TIMEOUT), videoImport, options)
94 }
95
96 async function getVideoImportOrDie (videoImportId: number) {
97   const videoImport = await VideoImportModel.loadAndPopulateVideo(videoImportId)
98   if (!videoImport || !videoImport.Video) {
99     throw new Error('Cannot import video %s: the video import or video linked to this import does not exist anymore.')
100   }
101
102   return videoImport
103 }
104
105 type ProcessFileOptions = {
106   videoImportId: number
107
108   downloadThumbnail: boolean
109   downloadPreview: boolean
110   thumbnailUrl?: string
111
112   generateThumbnail: boolean
113   generatePreview: boolean
114 }
115 async function processFile (downloader: () => Promise<string>, videoImport: MVideoImportDefault, options: ProcessFileOptions) {
116   let tempVideoPath: string
117   let videoDestFile: string
118   let videoFile: VideoFileModel
119
120   try {
121     // Download video from youtubeDL
122     tempVideoPath = await downloader()
123
124     // Get information about this video
125     const stats = await stat(tempVideoPath)
126     const isAble = await videoImport.User.isAbleToUploadVideo({ size: stats.size })
127     if (isAble === false) {
128       throw new Error('The user video quota is exceeded with this video to import.')
129     }
130
131     const { videoFileResolution } = await getVideoFileResolution(tempVideoPath)
132     const fps = await getVideoFileFPS(tempVideoPath)
133     const duration = await getDurationFromVideoFile(tempVideoPath)
134
135     // Create video file object in database
136     const videoFileData = {
137       extname: extname(tempVideoPath),
138       resolution: videoFileResolution,
139       size: stats.size,
140       fps,
141       videoId: videoImport.videoId
142     }
143     videoFile = new VideoFileModel(videoFileData)
144
145     const videoWithFiles = Object.assign(videoImport.Video, { VideoFiles: [ videoFile ], VideoStreamingPlaylists: [] })
146     // To clean files if the import fails
147     const videoImportWithFiles: MVideoImportDefaultFiles = Object.assign(videoImport, { Video: videoWithFiles })
148
149     // Move file
150     videoDestFile = getVideoFilePath(videoImportWithFiles.Video, videoFile)
151     await move(tempVideoPath, videoDestFile)
152     tempVideoPath = null // This path is not used anymore
153
154     // Process thumbnail
155     let thumbnailModel: MThumbnail
156     if (options.downloadThumbnail && options.thumbnailUrl) {
157       thumbnailModel = await createVideoMiniatureFromUrl(options.thumbnailUrl, videoImportWithFiles.Video, ThumbnailType.MINIATURE)
158     } else if (options.generateThumbnail || options.downloadThumbnail) {
159       thumbnailModel = await generateVideoMiniature(videoImportWithFiles.Video, videoFile, ThumbnailType.MINIATURE)
160     }
161
162     // Process preview
163     let previewModel: MThumbnail
164     if (options.downloadPreview && options.thumbnailUrl) {
165       previewModel = await createVideoMiniatureFromUrl(options.thumbnailUrl, videoImportWithFiles.Video, ThumbnailType.PREVIEW)
166     } else if (options.generatePreview || options.downloadPreview) {
167       previewModel = await generateVideoMiniature(videoImportWithFiles.Video, videoFile, ThumbnailType.PREVIEW)
168     }
169
170     // Create torrent
171     await createTorrentAndSetInfoHash(videoImportWithFiles.Video, videoFile)
172
173     const { videoImportUpdated, video } = await sequelizeTypescript.transaction(async t => {
174       const videoImportToUpdate = videoImportWithFiles as MVideoImportVideo
175
176       // Refresh video
177       const video = await VideoModel.load(videoImportToUpdate.videoId, t)
178       if (!video) throw new Error('Video linked to import ' + videoImportToUpdate.videoId + ' does not exist anymore.')
179
180       const videoFileCreated = await videoFile.save({ transaction: t })
181       videoImportToUpdate.Video = Object.assign(video, { VideoFiles: [ videoFileCreated ] })
182
183       // Update video DB object
184       video.duration = duration
185       video.state = CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED
186       await video.save({ transaction: t })
187
188       if (thumbnailModel) await video.addAndSaveThumbnail(thumbnailModel, t)
189       if (previewModel) await video.addAndSaveThumbnail(previewModel, t)
190
191       // Now we can federate the video (reload from database, we need more attributes)
192       const videoForFederation = await VideoModel.loadAndPopulateAccountAndServerAndTags(video.uuid, t)
193       await federateVideoIfNeeded(videoForFederation, true, t)
194
195       // Update video import object
196       videoImportToUpdate.state = VideoImportState.SUCCESS
197       const videoImportUpdated = await videoImportToUpdate.save({ transaction: t }) as MVideoImportVideo
198       videoImportUpdated.Video = video
199
200       logger.info('Video %s imported.', video.uuid)
201
202       return { videoImportUpdated, video: videoForFederation }
203     })
204
205     Notifier.Instance.notifyOnFinishedVideoImport(videoImportUpdated, true)
206
207     if (video.isBlacklisted()) {
208       const videoBlacklist = Object.assign(video.VideoBlacklist, { Video: video })
209
210       Notifier.Instance.notifyOnVideoAutoBlacklist(videoBlacklist)
211     } else {
212       Notifier.Instance.notifyOnNewVideoIfNeeded(video)
213     }
214
215     // Create transcoding jobs?
216     if (video.state === VideoState.TO_TRANSCODE) {
217       // Put uuid because we don't have id auto incremented for now
218       const dataInput = {
219         type: 'optimize' as 'optimize',
220         videoUUID: videoImportUpdated.Video.uuid,
221         isNewVideo: true
222       }
223
224       await JobQueue.Instance.createJobWithPromise({ type: 'video-transcoding', payload: dataInput })
225     }
226
227   } catch (err) {
228     try {
229       if (tempVideoPath) await remove(tempVideoPath)
230     } catch (errUnlink) {
231       logger.warn('Cannot cleanup files after a video import error.', { err: errUnlink })
232     }
233
234     videoImport.error = err.message
235     videoImport.state = VideoImportState.FAILED
236     await videoImport.save()
237
238     Notifier.Instance.notifyOnFinishedVideoImport(videoImport, false)
239
240     throw err
241   }
242 }