]>
Commit | Line | Data |
---|---|---|
1 | import * as Bull from 'bull' | |
2 | import { move, remove, stat } from 'fs-extra' | |
3 | import { extname } from 'path' | |
4 | import { addOptimizeOrMergeAudioJob } from '@server/helpers/video' | |
5 | import { isPostImportVideoAccepted } from '@server/lib/moderation' | |
6 | import { Hooks } from '@server/lib/plugins/hooks' | |
7 | import { isAbleToUploadVideo } from '@server/lib/user' | |
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/ffmpeg-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(() => downloadYoutubeDLVideo(videoImport.targetUrl, payload.fileExt, VIDEO_IMPORT_TIMEOUT), videoImport, options) | |
83 | } | |
84 | ||
85 | async function getVideoImportOrDie (videoImportId: number) { | |
86 | const videoImport = await VideoImportModel.loadAndPopulateVideo(videoImportId) | |
87 | if (!videoImport || !videoImport.Video) { | |
88 | throw new Error('Cannot import video %s: the video import or video linked to this import does not exist anymore.') | |
89 | } | |
90 | ||
91 | return videoImport | |
92 | } | |
93 | ||
94 | type ProcessFileOptions = { | |
95 | type: VideoImportYoutubeDLPayloadType | VideoImportTorrentPayloadType | |
96 | videoImportId: number | |
97 | ||
98 | generateThumbnail: boolean | |
99 | generatePreview: boolean | |
100 | } | |
101 | async function processFile (downloader: () => Promise<string>, videoImport: MVideoImportDefault, options: ProcessFileOptions) { | |
102 | let tempVideoPath: string | |
103 | let videoDestFile: string | |
104 | let videoFile: VideoFileModel | |
105 | ||
106 | try { | |
107 | // Download video from youtubeDL | |
108 | tempVideoPath = await downloader() | |
109 | ||
110 | // Get information about this video | |
111 | const stats = await stat(tempVideoPath) | |
112 | const isAble = await isAbleToUploadVideo(videoImport.User.id, stats.size) | |
113 | if (isAble === false) { | |
114 | throw new Error('The user video quota is exceeded with this video to import.') | |
115 | } | |
116 | ||
117 | const { videoFileResolution } = await getVideoFileResolution(tempVideoPath) | |
118 | const fps = await getVideoFileFPS(tempVideoPath) | |
119 | const duration = await getDurationFromVideoFile(tempVideoPath) | |
120 | ||
121 | // Prepare video file object for creation in database | |
122 | const videoFileData = { | |
123 | extname: extname(tempVideoPath), | |
124 | resolution: videoFileResolution, | |
125 | size: stats.size, | |
126 | fps, | |
127 | videoId: videoImport.videoId | |
128 | } | |
129 | videoFile = new VideoFileModel(videoFileData) | |
130 | ||
131 | const hookName = options.type === 'youtube-dl' | |
132 | ? 'filter:api.video.post-import-url.accept.result' | |
133 | : 'filter:api.video.post-import-torrent.accept.result' | |
134 | ||
135 | // Check we accept this video | |
136 | const acceptParameters = { | |
137 | videoImport, | |
138 | video: videoImport.Video, | |
139 | videoFilePath: tempVideoPath, | |
140 | videoFile, | |
141 | user: videoImport.User | |
142 | } | |
143 | const acceptedResult = await Hooks.wrapFun(isPostImportVideoAccepted, acceptParameters, hookName) | |
144 | ||
145 | if (acceptedResult.accepted !== true) { | |
146 | logger.info('Refused imported video.', { acceptedResult, acceptParameters }) | |
147 | ||
148 | videoImport.state = VideoImportState.REJECTED | |
149 | await videoImport.save() | |
150 | ||
151 | throw new Error(acceptedResult.errorMessage) | |
152 | } | |
153 | ||
154 | // Video is accepted, resuming preparation | |
155 | const videoWithFiles = Object.assign(videoImport.Video, { VideoFiles: [ videoFile ], VideoStreamingPlaylists: [] }) | |
156 | // To clean files if the import fails | |
157 | const videoImportWithFiles: MVideoImportDefaultFiles = Object.assign(videoImport, { Video: videoWithFiles }) | |
158 | ||
159 | // Move file | |
160 | videoDestFile = getVideoFilePath(videoImportWithFiles.Video, videoFile) | |
161 | await move(tempVideoPath, videoDestFile) | |
162 | tempVideoPath = null // This path is not used anymore | |
163 | ||
164 | // Process thumbnail | |
165 | let thumbnailModel: MThumbnail | |
166 | if (options.generateThumbnail) { | |
167 | thumbnailModel = await generateVideoMiniature(videoImportWithFiles.Video, videoFile, ThumbnailType.MINIATURE) | |
168 | } | |
169 | ||
170 | // Process preview | |
171 | let previewModel: MThumbnail | |
172 | if (options.generatePreview) { | |
173 | previewModel = await generateVideoMiniature(videoImportWithFiles.Video, videoFile, ThumbnailType.PREVIEW) | |
174 | } | |
175 | ||
176 | // Create torrent | |
177 | await createTorrentAndSetInfoHash(videoImportWithFiles.Video, videoFile) | |
178 | ||
179 | const { videoImportUpdated, video } = await sequelizeTypescript.transaction(async t => { | |
180 | const videoImportToUpdate = videoImportWithFiles as MVideoImportVideo | |
181 | ||
182 | // Refresh video | |
183 | const video = await VideoModel.load(videoImportToUpdate.videoId, t) | |
184 | if (!video) throw new Error('Video linked to import ' + videoImportToUpdate.videoId + ' does not exist anymore.') | |
185 | ||
186 | const videoFileCreated = await videoFile.save({ transaction: t }) | |
187 | videoImportToUpdate.Video = Object.assign(video, { VideoFiles: [ videoFileCreated ] }) | |
188 | ||
189 | // Update video DB object | |
190 | video.duration = duration | |
191 | video.state = CONFIG.TRANSCODING.ENABLED ? VideoState.TO_TRANSCODE : VideoState.PUBLISHED | |
192 | await video.save({ transaction: t }) | |
193 | ||
194 | if (thumbnailModel) await video.addAndSaveThumbnail(thumbnailModel, t) | |
195 | if (previewModel) await video.addAndSaveThumbnail(previewModel, t) | |
196 | ||
197 | // Now we can federate the video (reload from database, we need more attributes) | |
198 | const videoForFederation = await VideoModel.loadAndPopulateAccountAndServerAndTags(video.uuid, t) | |
199 | await federateVideoIfNeeded(videoForFederation, true, t) | |
200 | ||
201 | // Update video import object | |
202 | videoImportToUpdate.state = VideoImportState.SUCCESS | |
203 | const videoImportUpdated = await videoImportToUpdate.save({ transaction: t }) as MVideoImportVideo | |
204 | videoImportUpdated.Video = video | |
205 | ||
206 | logger.info('Video %s imported.', video.uuid) | |
207 | ||
208 | return { videoImportUpdated, video: videoForFederation } | |
209 | }) | |
210 | ||
211 | Notifier.Instance.notifyOnFinishedVideoImport(videoImportUpdated, true) | |
212 | ||
213 | if (video.isBlacklisted()) { | |
214 | const videoBlacklist = Object.assign(video.VideoBlacklist, { Video: video }) | |
215 | ||
216 | Notifier.Instance.notifyOnVideoAutoBlacklist(videoBlacklist) | |
217 | } else { | |
218 | Notifier.Instance.notifyOnNewVideoIfNeeded(video) | |
219 | } | |
220 | ||
221 | // Create transcoding jobs? | |
222 | if (video.state === VideoState.TO_TRANSCODE) { | |
223 | await addOptimizeOrMergeAudioJob(videoImportUpdated.Video, videoFile) | |
224 | } | |
225 | ||
226 | } catch (err) { | |
227 | try { | |
228 | if (tempVideoPath) await remove(tempVideoPath) | |
229 | } catch (errUnlink) { | |
230 | logger.warn('Cannot cleanup files after a video import error.', { err: errUnlink }) | |
231 | } | |
232 | ||
233 | videoImport.error = err.message | |
234 | if (videoImport.state !== VideoImportState.REJECTED) { | |
235 | videoImport.state = VideoImportState.FAILED | |
236 | } | |
237 | await videoImport.save() | |
238 | ||
239 | Notifier.Instance.notifyOnFinishedVideoImport(videoImport, false) | |
240 | ||
241 | throw err | |
242 | } | |
243 | } |