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