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