diff options
Diffstat (limited to 'server/lib')
-rw-r--r-- | server/lib/job-queue/handlers/after-video-channel-import.ts | 37 | ||||
-rw-r--r-- | server/lib/job-queue/handlers/video-channel-import.ts | 36 | ||||
-rw-r--r-- | server/lib/job-queue/handlers/video-import.ts | 20 | ||||
-rw-r--r-- | server/lib/job-queue/job-queue.ts | 19 | ||||
-rw-r--r-- | server/lib/schedulers/video-channel-sync-latest-scheduler.ts | 61 | ||||
-rw-r--r-- | server/lib/server-config-manager.ts | 3 | ||||
-rw-r--r-- | server/lib/sync-channel.ts | 81 | ||||
-rw-r--r-- | server/lib/video-import.ts | 308 |
8 files changed, 556 insertions, 9 deletions
diff --git a/server/lib/job-queue/handlers/after-video-channel-import.ts b/server/lib/job-queue/handlers/after-video-channel-import.ts new file mode 100644 index 000000000..ffdd8c5b5 --- /dev/null +++ b/server/lib/job-queue/handlers/after-video-channel-import.ts | |||
@@ -0,0 +1,37 @@ | |||
1 | import { Job } from 'bullmq' | ||
2 | import { logger } from '@server/helpers/logger' | ||
3 | import { VideoChannelSyncModel } from '@server/models/video/video-channel-sync' | ||
4 | import { AfterVideoChannelImportPayload, VideoChannelSyncState, VideoImportPreventExceptionResult } from '@shared/models' | ||
5 | |||
6 | export async function processAfterVideoChannelImport (job: Job) { | ||
7 | const payload = job.data as AfterVideoChannelImportPayload | ||
8 | if (!payload.channelSyncId) return | ||
9 | |||
10 | logger.info('Processing after video channel import in job %s.', job.id) | ||
11 | |||
12 | const sync = await VideoChannelSyncModel.loadWithChannel(payload.channelSyncId) | ||
13 | if (!sync) { | ||
14 | logger.error('Unknown sync id %d.', payload.channelSyncId) | ||
15 | return | ||
16 | } | ||
17 | |||
18 | const childrenValues = await job.getChildrenValues<VideoImportPreventExceptionResult>() | ||
19 | |||
20 | let errors = 0 | ||
21 | let successes = 0 | ||
22 | |||
23 | for (const value of Object.values(childrenValues)) { | ||
24 | if (value.resultType === 'success') successes++ | ||
25 | else if (value.resultType === 'error') errors++ | ||
26 | } | ||
27 | |||
28 | if (errors > 0) { | ||
29 | sync.state = VideoChannelSyncState.FAILED | ||
30 | logger.error(`Finished synchronizing "${sync.VideoChannel.Actor.preferredUsername}" with failures.`, { errors, successes }) | ||
31 | } else { | ||
32 | sync.state = VideoChannelSyncState.SYNCED | ||
33 | logger.info(`Finished synchronizing "${sync.VideoChannel.Actor.preferredUsername}" successfully.`, { successes }) | ||
34 | } | ||
35 | |||
36 | await sync.save() | ||
37 | } | ||
diff --git a/server/lib/job-queue/handlers/video-channel-import.ts b/server/lib/job-queue/handlers/video-channel-import.ts new file mode 100644 index 000000000..9bdb2d269 --- /dev/null +++ b/server/lib/job-queue/handlers/video-channel-import.ts | |||
@@ -0,0 +1,36 @@ | |||
1 | import { Job } from 'bullmq' | ||
2 | import { logger } from '@server/helpers/logger' | ||
3 | import { CONFIG } from '@server/initializers/config' | ||
4 | import { synchronizeChannel } from '@server/lib/sync-channel' | ||
5 | import { VideoChannelModel } from '@server/models/video/video-channel' | ||
6 | import { VideoChannelImportPayload } from '@shared/models' | ||
7 | |||
8 | export async function processVideoChannelImport (job: Job) { | ||
9 | const payload = job.data as VideoChannelImportPayload | ||
10 | |||
11 | logger.info('Processing video channel import in job %s.', job.id) | ||
12 | |||
13 | // Channel import requires only http upload to be allowed | ||
14 | if (!CONFIG.IMPORT.VIDEOS.HTTP.ENABLED) { | ||
15 | logger.error('Cannot import channel as the HTTP upload is disabled') | ||
16 | return | ||
17 | } | ||
18 | |||
19 | if (!CONFIG.IMPORT.VIDEO_CHANNEL_SYNCHRONIZATION.ENABLED) { | ||
20 | logger.error('Cannot import channel as the synchronization is disabled') | ||
21 | return | ||
22 | } | ||
23 | |||
24 | const videoChannel = await VideoChannelModel.loadAndPopulateAccount(payload.videoChannelId) | ||
25 | |||
26 | try { | ||
27 | logger.info(`Starting importing videos from external channel "${payload.externalChannelUrl}" to "${videoChannel.name}" `) | ||
28 | |||
29 | await synchronizeChannel({ | ||
30 | channel: videoChannel, | ||
31 | externalChannelUrl: payload.externalChannelUrl | ||
32 | }) | ||
33 | } catch (err) { | ||
34 | logger.error(`Failed to import channel ${videoChannel.name}`, { err }) | ||
35 | } | ||
36 | } | ||
diff --git a/server/lib/job-queue/handlers/video-import.ts b/server/lib/job-queue/handlers/video-import.ts index f4629159c..9901b878c 100644 --- a/server/lib/job-queue/handlers/video-import.ts +++ b/server/lib/job-queue/handlers/video-import.ts | |||
@@ -8,7 +8,7 @@ import { generateWebTorrentVideoFilename } from '@server/lib/paths' | |||
8 | import { Hooks } from '@server/lib/plugins/hooks' | 8 | import { Hooks } from '@server/lib/plugins/hooks' |
9 | import { ServerConfigManager } from '@server/lib/server-config-manager' | 9 | import { ServerConfigManager } from '@server/lib/server-config-manager' |
10 | import { isAbleToUploadVideo } from '@server/lib/user' | 10 | import { isAbleToUploadVideo } from '@server/lib/user' |
11 | import { buildOptimizeOrMergeAudioJob, buildMoveToObjectStorageJob } from '@server/lib/video' | 11 | import { buildMoveToObjectStorageJob, buildOptimizeOrMergeAudioJob } from '@server/lib/video' |
12 | import { VideoPathManager } from '@server/lib/video-path-manager' | 12 | import { VideoPathManager } from '@server/lib/video-path-manager' |
13 | import { buildNextVideoState } from '@server/lib/video-state' | 13 | import { buildNextVideoState } from '@server/lib/video-state' |
14 | import { ThumbnailModel } from '@server/models/video/thumbnail' | 14 | import { ThumbnailModel } from '@server/models/video/thumbnail' |
@@ -18,6 +18,7 @@ import { isAudioFile } from '@shared/extra-utils' | |||
18 | import { | 18 | import { |
19 | ThumbnailType, | 19 | ThumbnailType, |
20 | VideoImportPayload, | 20 | VideoImportPayload, |
21 | VideoImportPreventExceptionResult, | ||
21 | VideoImportState, | 22 | VideoImportState, |
22 | VideoImportTorrentPayload, | 23 | VideoImportTorrentPayload, |
23 | VideoImportTorrentPayloadType, | 24 | VideoImportTorrentPayloadType, |
@@ -41,20 +42,29 @@ import { Notifier } from '../../notifier' | |||
41 | import { generateVideoMiniature } from '../../thumbnail' | 42 | import { generateVideoMiniature } from '../../thumbnail' |
42 | import { JobQueue } from '../job-queue' | 43 | import { JobQueue } from '../job-queue' |
43 | 44 | ||
44 | async function processVideoImport (job: Job) { | 45 | async function processVideoImport (job: Job): Promise<VideoImportPreventExceptionResult> { |
45 | const payload = job.data as VideoImportPayload | 46 | const payload = job.data as VideoImportPayload |
46 | 47 | ||
47 | const videoImport = await getVideoImportOrDie(payload) | 48 | const videoImport = await getVideoImportOrDie(payload) |
48 | if (videoImport.state === VideoImportState.CANCELLED) { | 49 | if (videoImport.state === VideoImportState.CANCELLED) { |
49 | logger.info('Do not process import since it has been cancelled', { payload }) | 50 | logger.info('Do not process import since it has been cancelled', { payload }) |
50 | return | 51 | return { resultType: 'success' } |
51 | } | 52 | } |
52 | 53 | ||
53 | videoImport.state = VideoImportState.PROCESSING | 54 | videoImport.state = VideoImportState.PROCESSING |
54 | await videoImport.save() | 55 | await videoImport.save() |
55 | 56 | ||
56 | if (payload.type === 'youtube-dl') return processYoutubeDLImport(job, videoImport, payload) | 57 | try { |
57 | if (payload.type === 'magnet-uri' || payload.type === 'torrent-file') return processTorrentImport(job, videoImport, payload) | 58 | if (payload.type === 'youtube-dl') await processYoutubeDLImport(job, videoImport, payload) |
59 | if (payload.type === 'magnet-uri' || payload.type === 'torrent-file') await processTorrentImport(job, videoImport, payload) | ||
60 | |||
61 | return { resultType: 'success' } | ||
62 | } catch (err) { | ||
63 | if (!payload.preventException) throw err | ||
64 | |||
65 | logger.warn('Catch error in video import to send value to parent job.', { payload, err }) | ||
66 | return { resultType: 'error' } | ||
67 | } | ||
58 | } | 68 | } |
59 | 69 | ||
60 | // --------------------------------------------------------------------------- | 70 | // --------------------------------------------------------------------------- |
diff --git a/server/lib/job-queue/job-queue.ts b/server/lib/job-queue/job-queue.ts index 281e2e51a..3970d48b7 100644 --- a/server/lib/job-queue/job-queue.ts +++ b/server/lib/job-queue/job-queue.ts | |||
@@ -22,6 +22,7 @@ import { | |||
22 | ActivitypubHttpFetcherPayload, | 22 | ActivitypubHttpFetcherPayload, |
23 | ActivitypubHttpUnicastPayload, | 23 | ActivitypubHttpUnicastPayload, |
24 | ActorKeysPayload, | 24 | ActorKeysPayload, |
25 | AfterVideoChannelImportPayload, | ||
25 | DeleteResumableUploadMetaFilePayload, | 26 | DeleteResumableUploadMetaFilePayload, |
26 | EmailPayload, | 27 | EmailPayload, |
27 | FederateVideoPayload, | 28 | FederateVideoPayload, |
@@ -31,6 +32,7 @@ import { | |||
31 | MoveObjectStoragePayload, | 32 | MoveObjectStoragePayload, |
32 | NotifyPayload, | 33 | NotifyPayload, |
33 | RefreshPayload, | 34 | RefreshPayload, |
35 | VideoChannelImportPayload, | ||
34 | VideoFileImportPayload, | 36 | VideoFileImportPayload, |
35 | VideoImportPayload, | 37 | VideoImportPayload, |
36 | VideoLiveEndingPayload, | 38 | VideoLiveEndingPayload, |
@@ -53,12 +55,14 @@ import { processFederateVideo } from './handlers/federate-video' | |||
53 | import { processManageVideoTorrent } from './handlers/manage-video-torrent' | 55 | import { processManageVideoTorrent } from './handlers/manage-video-torrent' |
54 | import { onMoveToObjectStorageFailure, processMoveToObjectStorage } from './handlers/move-to-object-storage' | 56 | import { onMoveToObjectStorageFailure, processMoveToObjectStorage } from './handlers/move-to-object-storage' |
55 | import { processNotify } from './handlers/notify' | 57 | import { processNotify } from './handlers/notify' |
58 | import { processVideoChannelImport } from './handlers/video-channel-import' | ||
56 | import { processVideoFileImport } from './handlers/video-file-import' | 59 | import { processVideoFileImport } from './handlers/video-file-import' |
57 | import { processVideoImport } from './handlers/video-import' | 60 | import { processVideoImport } from './handlers/video-import' |
58 | import { processVideoLiveEnding } from './handlers/video-live-ending' | 61 | import { processVideoLiveEnding } from './handlers/video-live-ending' |
59 | import { processVideoStudioEdition } from './handlers/video-studio-edition' | 62 | import { processVideoStudioEdition } from './handlers/video-studio-edition' |
60 | import { processVideoTranscoding } from './handlers/video-transcoding' | 63 | import { processVideoTranscoding } from './handlers/video-transcoding' |
61 | import { processVideosViewsStats } from './handlers/video-views-stats' | 64 | import { processVideosViewsStats } from './handlers/video-views-stats' |
65 | import { processAfterVideoChannelImport } from './handlers/after-video-channel-import' | ||
62 | 66 | ||
63 | export type CreateJobArgument = | 67 | export type CreateJobArgument = |
64 | { type: 'activitypub-http-broadcast', payload: ActivitypubHttpBroadcastPayload } | | 68 | { type: 'activitypub-http-broadcast', payload: ActivitypubHttpBroadcastPayload } | |
@@ -79,6 +83,9 @@ export type CreateJobArgument = | |||
79 | { type: 'delete-resumable-upload-meta-file', payload: DeleteResumableUploadMetaFilePayload } | | 83 | { type: 'delete-resumable-upload-meta-file', payload: DeleteResumableUploadMetaFilePayload } | |
80 | { type: 'video-studio-edition', payload: VideoStudioEditionPayload } | | 84 | { type: 'video-studio-edition', payload: VideoStudioEditionPayload } | |
81 | { type: 'manage-video-torrent', payload: ManageVideoTorrentPayload } | | 85 | { type: 'manage-video-torrent', payload: ManageVideoTorrentPayload } | |
86 | { type: 'move-to-object-storage', payload: MoveObjectStoragePayload } | | ||
87 | { type: 'video-channel-import', payload: VideoChannelImportPayload } | | ||
88 | { type: 'after-video-channel-import', payload: AfterVideoChannelImportPayload } | | ||
82 | { type: 'notify', payload: NotifyPayload } | | 89 | { type: 'notify', payload: NotifyPayload } | |
83 | { type: 'move-to-object-storage', payload: MoveObjectStoragePayload } | | 90 | { type: 'move-to-object-storage', payload: MoveObjectStoragePayload } | |
84 | { type: 'federate-video', payload: FederateVideoPayload } | 91 | { type: 'federate-video', payload: FederateVideoPayload } |
@@ -106,8 +113,10 @@ const handlers: { [id in JobType]: (job: Job) => Promise<any> } = { | |||
106 | 'video-redundancy': processVideoRedundancy, | 113 | 'video-redundancy': processVideoRedundancy, |
107 | 'move-to-object-storage': processMoveToObjectStorage, | 114 | 'move-to-object-storage': processMoveToObjectStorage, |
108 | 'manage-video-torrent': processManageVideoTorrent, | 115 | 'manage-video-torrent': processManageVideoTorrent, |
109 | 'notify': processNotify, | ||
110 | 'video-studio-edition': processVideoStudioEdition, | 116 | 'video-studio-edition': processVideoStudioEdition, |
117 | 'video-channel-import': processVideoChannelImport, | ||
118 | 'after-video-channel-import': processAfterVideoChannelImport, | ||
119 | 'notify': processNotify, | ||
111 | 'federate-video': processFederateVideo | 120 | 'federate-video': processFederateVideo |
112 | } | 121 | } |
113 | 122 | ||
@@ -134,6 +143,8 @@ const jobTypes: JobType[] = [ | |||
134 | 'move-to-object-storage', | 143 | 'move-to-object-storage', |
135 | 'manage-video-torrent', | 144 | 'manage-video-torrent', |
136 | 'video-studio-edition', | 145 | 'video-studio-edition', |
146 | 'video-channel-import', | ||
147 | 'after-video-channel-import', | ||
137 | 'notify', | 148 | 'notify', |
138 | 'federate-video' | 149 | 'federate-video' |
139 | ] | 150 | ] |
@@ -306,7 +317,7 @@ class JobQueue { | |||
306 | .catch(err => logger.error('Cannot create job.', { err, options })) | 317 | .catch(err => logger.error('Cannot create job.', { err, options })) |
307 | } | 318 | } |
308 | 319 | ||
309 | async createJob (options: CreateJobArgument & CreateJobOptions) { | 320 | createJob (options: CreateJobArgument & CreateJobOptions) { |
310 | const queue: Queue = this.queues[options.type] | 321 | const queue: Queue = this.queues[options.type] |
311 | if (queue === undefined) { | 322 | if (queue === undefined) { |
312 | logger.error('Unknown queue %s: cannot create job.', options.type) | 323 | logger.error('Unknown queue %s: cannot create job.', options.type) |
@@ -318,7 +329,7 @@ class JobQueue { | |||
318 | return queue.add('job', options.payload, jobOptions) | 329 | return queue.add('job', options.payload, jobOptions) |
319 | } | 330 | } |
320 | 331 | ||
321 | async createSequentialJobFlow (...jobs: ((CreateJobArgument & CreateJobOptions) | undefined)[]) { | 332 | createSequentialJobFlow (...jobs: ((CreateJobArgument & CreateJobOptions) | undefined)[]) { |
322 | let lastJob: FlowJob | 333 | let lastJob: FlowJob |
323 | 334 | ||
324 | for (const job of jobs) { | 335 | for (const job of jobs) { |
@@ -336,7 +347,7 @@ class JobQueue { | |||
336 | return this.flowProducer.add(lastJob) | 347 | return this.flowProducer.add(lastJob) |
337 | } | 348 | } |
338 | 349 | ||
339 | async createJobWithChildren (parent: CreateJobArgument & CreateJobOptions, children: (CreateJobArgument & CreateJobOptions)[]) { | 350 | createJobWithChildren (parent: CreateJobArgument & CreateJobOptions, children: (CreateJobArgument & CreateJobOptions)[]) { |
340 | return this.flowProducer.add({ | 351 | return this.flowProducer.add({ |
341 | ...this.buildJobFlowOption(parent), | 352 | ...this.buildJobFlowOption(parent), |
342 | 353 | ||
diff --git a/server/lib/schedulers/video-channel-sync-latest-scheduler.ts b/server/lib/schedulers/video-channel-sync-latest-scheduler.ts new file mode 100644 index 000000000..fd9a35299 --- /dev/null +++ b/server/lib/schedulers/video-channel-sync-latest-scheduler.ts | |||
@@ -0,0 +1,61 @@ | |||
1 | import { logger } from '@server/helpers/logger' | ||
2 | import { CONFIG } from '@server/initializers/config' | ||
3 | import { VideoChannelModel } from '@server/models/video/video-channel' | ||
4 | import { VideoChannelSyncModel } from '@server/models/video/video-channel-sync' | ||
5 | import { VideoChannelSyncState } from '@shared/models' | ||
6 | import { SCHEDULER_INTERVALS_MS } from '../../initializers/constants' | ||
7 | import { synchronizeChannel } from '../sync-channel' | ||
8 | import { AbstractScheduler } from './abstract-scheduler' | ||
9 | |||
10 | export class VideoChannelSyncLatestScheduler extends AbstractScheduler { | ||
11 | private static instance: AbstractScheduler | ||
12 | protected schedulerIntervalMs = SCHEDULER_INTERVALS_MS.CHANNEL_SYNC_CHECK_INTERVAL | ||
13 | |||
14 | private constructor () { | ||
15 | super() | ||
16 | } | ||
17 | |||
18 | protected async internalExecute () { | ||
19 | logger.debug('Running %s.%s', this.constructor.name, this.internalExecute.name) | ||
20 | |||
21 | if (!CONFIG.IMPORT.VIDEO_CHANNEL_SYNCHRONIZATION.ENABLED) { | ||
22 | logger.info('Discard channels synchronization as the feature is disabled') | ||
23 | return | ||
24 | } | ||
25 | |||
26 | const channelSyncs = await VideoChannelSyncModel.listSyncs() | ||
27 | |||
28 | for (const sync of channelSyncs) { | ||
29 | const channel = await VideoChannelModel.loadAndPopulateAccount(sync.videoChannelId) | ||
30 | |||
31 | try { | ||
32 | logger.info( | ||
33 | 'Creating video import jobs for "%s" sync with external channel "%s"', | ||
34 | channel.Actor.preferredUsername, sync.externalChannelUrl | ||
35 | ) | ||
36 | |||
37 | const onlyAfter = sync.lastSyncAt || sync.createdAt | ||
38 | |||
39 | sync.state = VideoChannelSyncState.PROCESSING | ||
40 | sync.lastSyncAt = new Date() | ||
41 | await sync.save() | ||
42 | |||
43 | await synchronizeChannel({ | ||
44 | channel, | ||
45 | externalChannelUrl: sync.externalChannelUrl, | ||
46 | videosCountLimit: CONFIG.IMPORT.VIDEO_CHANNEL_SYNCHRONIZATION.VIDEOS_LIMIT_PER_SYNCHRONIZATION, | ||
47 | channelSync: sync, | ||
48 | onlyAfter | ||
49 | }) | ||
50 | } catch (err) { | ||
51 | logger.error(`Failed to synchronize channel ${channel.Actor.preferredUsername}`, { err }) | ||
52 | sync.state = VideoChannelSyncState.FAILED | ||
53 | await sync.save() | ||
54 | } | ||
55 | } | ||
56 | } | ||
57 | |||
58 | static get Instance () { | ||
59 | return this.instance || (this.instance = new this()) | ||
60 | } | ||
61 | } | ||
diff --git a/server/lib/server-config-manager.ts b/server/lib/server-config-manager.ts index a3312fa20..78a9546ae 100644 --- a/server/lib/server-config-manager.ts +++ b/server/lib/server-config-manager.ts | |||
@@ -170,6 +170,9 @@ class ServerConfigManager { | |||
170 | torrent: { | 170 | torrent: { |
171 | enabled: CONFIG.IMPORT.VIDEOS.TORRENT.ENABLED | 171 | enabled: CONFIG.IMPORT.VIDEOS.TORRENT.ENABLED |
172 | } | 172 | } |
173 | }, | ||
174 | videoChannelSynchronization: { | ||
175 | enabled: CONFIG.IMPORT.VIDEO_CHANNEL_SYNCHRONIZATION.ENABLED | ||
173 | } | 176 | } |
174 | }, | 177 | }, |
175 | autoBlacklist: { | 178 | autoBlacklist: { |
diff --git a/server/lib/sync-channel.ts b/server/lib/sync-channel.ts new file mode 100644 index 000000000..50f80e6f9 --- /dev/null +++ b/server/lib/sync-channel.ts | |||
@@ -0,0 +1,81 @@ | |||
1 | import { logger } from '@server/helpers/logger' | ||
2 | import { YoutubeDLWrapper } from '@server/helpers/youtube-dl' | ||
3 | import { CONFIG } from '@server/initializers/config' | ||
4 | import { buildYoutubeDLImport } from '@server/lib/video-import' | ||
5 | import { UserModel } from '@server/models/user/user' | ||
6 | import { VideoImportModel } from '@server/models/video/video-import' | ||
7 | import { MChannelAccountDefault, MChannelSync } from '@server/types/models' | ||
8 | import { VideoChannelSyncState, VideoPrivacy } from '@shared/models' | ||
9 | import { CreateJobArgument, JobQueue } from './job-queue' | ||
10 | import { ServerConfigManager } from './server-config-manager' | ||
11 | |||
12 | export async function synchronizeChannel (options: { | ||
13 | channel: MChannelAccountDefault | ||
14 | externalChannelUrl: string | ||
15 | channelSync?: MChannelSync | ||
16 | videosCountLimit?: number | ||
17 | onlyAfter?: Date | ||
18 | }) { | ||
19 | const { channel, externalChannelUrl, videosCountLimit, onlyAfter, channelSync } = options | ||
20 | |||
21 | const user = await UserModel.loadByChannelActorId(channel.actorId) | ||
22 | const youtubeDL = new YoutubeDLWrapper( | ||
23 | externalChannelUrl, | ||
24 | ServerConfigManager.Instance.getEnabledResolutions('vod'), | ||
25 | CONFIG.TRANSCODING.ALWAYS_TRANSCODE_ORIGINAL_RESOLUTION | ||
26 | ) | ||
27 | |||
28 | const infoList = await youtubeDL.getInfoForListImport({ latestVideosCount: videosCountLimit }) | ||
29 | |||
30 | const targetUrls = infoList | ||
31 | .filter(videoInfo => { | ||
32 | if (!onlyAfter) return true | ||
33 | |||
34 | return videoInfo.originallyPublishedAt.getTime() >= onlyAfter.getTime() | ||
35 | }) | ||
36 | .map(videoInfo => videoInfo.webpageUrl) | ||
37 | |||
38 | logger.info( | ||
39 | 'Fetched %d candidate URLs for sync channel %s.', | ||
40 | targetUrls.length, channel.Actor.preferredUsername, { targetUrls } | ||
41 | ) | ||
42 | |||
43 | if (targetUrls.length === 0) { | ||
44 | if (channelSync) { | ||
45 | channelSync.state = VideoChannelSyncState.SYNCED | ||
46 | await channelSync.save() | ||
47 | } | ||
48 | |||
49 | return | ||
50 | } | ||
51 | |||
52 | const children: CreateJobArgument[] = [] | ||
53 | |||
54 | for (const targetUrl of targetUrls) { | ||
55 | if (await VideoImportModel.urlAlreadyImported(channel.id, targetUrl)) { | ||
56 | logger.debug('%s is already imported for channel %s, skipping video channel synchronization.', channel.name, targetUrl) | ||
57 | continue | ||
58 | } | ||
59 | |||
60 | const { job } = await buildYoutubeDLImport({ | ||
61 | user, | ||
62 | channel, | ||
63 | targetUrl, | ||
64 | channelSync, | ||
65 | importDataOverride: { | ||
66 | privacy: VideoPrivacy.PUBLIC | ||
67 | } | ||
68 | }) | ||
69 | |||
70 | children.push(job) | ||
71 | } | ||
72 | |||
73 | const parent: CreateJobArgument = { | ||
74 | type: 'after-video-channel-import', | ||
75 | payload: { | ||
76 | channelSyncId: channelSync?.id | ||
77 | } | ||
78 | } | ||
79 | |||
80 | await JobQueue.Instance.createJobWithChildren(parent, children) | ||
81 | } | ||
diff --git a/server/lib/video-import.ts b/server/lib/video-import.ts new file mode 100644 index 000000000..fb9306967 --- /dev/null +++ b/server/lib/video-import.ts | |||
@@ -0,0 +1,308 @@ | |||
1 | import { remove } from 'fs-extra' | ||
2 | import { moveAndProcessCaptionFile } from '@server/helpers/captions-utils' | ||
3 | import { isVTTFileValid } from '@server/helpers/custom-validators/video-captions' | ||
4 | import { isVideoFileExtnameValid } from '@server/helpers/custom-validators/videos' | ||
5 | import { isResolvingToUnicastOnly } from '@server/helpers/dns' | ||
6 | import { logger } from '@server/helpers/logger' | ||
7 | import { YoutubeDLInfo, YoutubeDLWrapper } from '@server/helpers/youtube-dl' | ||
8 | import { CONFIG } from '@server/initializers/config' | ||
9 | import { sequelizeTypescript } from '@server/initializers/database' | ||
10 | import { Hooks } from '@server/lib/plugins/hooks' | ||
11 | import { ServerConfigManager } from '@server/lib/server-config-manager' | ||
12 | import { setVideoTags } from '@server/lib/video' | ||
13 | import { autoBlacklistVideoIfNeeded } from '@server/lib/video-blacklist' | ||
14 | import { VideoModel } from '@server/models/video/video' | ||
15 | import { VideoCaptionModel } from '@server/models/video/video-caption' | ||
16 | import { VideoImportModel } from '@server/models/video/video-import' | ||
17 | import { FilteredModelAttributes } from '@server/types' | ||
18 | import { | ||
19 | MChannelAccountDefault, | ||
20 | MChannelSync, | ||
21 | MThumbnail, | ||
22 | MUser, | ||
23 | MVideoAccountDefault, | ||
24 | MVideoCaption, | ||
25 | MVideoImportFormattable, | ||
26 | MVideoTag, | ||
27 | MVideoThumbnail, | ||
28 | MVideoWithBlacklistLight | ||
29 | } from '@server/types/models' | ||
30 | import { ThumbnailType, VideoImportCreate, VideoImportPayload, VideoImportState, VideoPrivacy, VideoState } from '@shared/models' | ||
31 | import { getLocalVideoActivityPubUrl } from './activitypub/url' | ||
32 | import { updateVideoMiniatureFromExisting, updateVideoMiniatureFromUrl } from './thumbnail' | ||
33 | |||
34 | class YoutubeDlImportError extends Error { | ||
35 | code: YoutubeDlImportError.CODE | ||
36 | cause?: Error // Property to remove once ES2022 is used | ||
37 | constructor ({ message, code }) { | ||
38 | super(message) | ||
39 | this.code = code | ||
40 | } | ||
41 | |||
42 | static fromError (err: Error, code: YoutubeDlImportError.CODE, message?: string) { | ||
43 | const ytDlErr = new this({ message: message ?? err.message, code }) | ||
44 | ytDlErr.cause = err | ||
45 | ytDlErr.stack = err.stack // Useless once ES2022 is used | ||
46 | return ytDlErr | ||
47 | } | ||
48 | } | ||
49 | |||
50 | namespace YoutubeDlImportError { | ||
51 | export enum CODE { | ||
52 | FETCH_ERROR, | ||
53 | NOT_ONLY_UNICAST_URL | ||
54 | } | ||
55 | } | ||
56 | |||
57 | // --------------------------------------------------------------------------- | ||
58 | |||
59 | async function insertFromImportIntoDB (parameters: { | ||
60 | video: MVideoThumbnail | ||
61 | thumbnailModel: MThumbnail | ||
62 | previewModel: MThumbnail | ||
63 | videoChannel: MChannelAccountDefault | ||
64 | tags: string[] | ||
65 | videoImportAttributes: FilteredModelAttributes<VideoImportModel> | ||
66 | user: MUser | ||
67 | }): Promise<MVideoImportFormattable> { | ||
68 | const { video, thumbnailModel, previewModel, videoChannel, tags, videoImportAttributes, user } = parameters | ||
69 | |||
70 | const videoImport = await sequelizeTypescript.transaction(async t => { | ||
71 | const sequelizeOptions = { transaction: t } | ||
72 | |||
73 | // Save video object in database | ||
74 | const videoCreated = await video.save(sequelizeOptions) as (MVideoAccountDefault & MVideoWithBlacklistLight & MVideoTag) | ||
75 | videoCreated.VideoChannel = videoChannel | ||
76 | |||
77 | if (thumbnailModel) await videoCreated.addAndSaveThumbnail(thumbnailModel, t) | ||
78 | if (previewModel) await videoCreated.addAndSaveThumbnail(previewModel, t) | ||
79 | |||
80 | await autoBlacklistVideoIfNeeded({ | ||
81 | video: videoCreated, | ||
82 | user, | ||
83 | notify: false, | ||
84 | isRemote: false, | ||
85 | isNew: true, | ||
86 | transaction: t | ||
87 | }) | ||
88 | |||
89 | await setVideoTags({ video: videoCreated, tags, transaction: t }) | ||
90 | |||
91 | // Create video import object in database | ||
92 | const videoImport = await VideoImportModel.create( | ||
93 | Object.assign({ videoId: videoCreated.id }, videoImportAttributes), | ||
94 | sequelizeOptions | ||
95 | ) as MVideoImportFormattable | ||
96 | videoImport.Video = videoCreated | ||
97 | |||
98 | return videoImport | ||
99 | }) | ||
100 | |||
101 | return videoImport | ||
102 | } | ||
103 | |||
104 | async function buildVideoFromImport ({ channelId, importData, importDataOverride, importType }: { | ||
105 | channelId: number | ||
106 | importData: YoutubeDLInfo | ||
107 | importDataOverride?: Partial<VideoImportCreate> | ||
108 | importType: 'url' | 'torrent' | ||
109 | }): Promise<MVideoThumbnail> { | ||
110 | let videoData = { | ||
111 | name: importDataOverride?.name || importData.name || 'Unknown name', | ||
112 | remote: false, | ||
113 | category: importDataOverride?.category || importData.category, | ||
114 | licence: importDataOverride?.licence ?? importData.licence ?? CONFIG.DEFAULTS.PUBLISH.LICENCE, | ||
115 | language: importDataOverride?.language || importData.language, | ||
116 | commentsEnabled: importDataOverride?.commentsEnabled ?? CONFIG.DEFAULTS.PUBLISH.COMMENTS_ENABLED, | ||
117 | downloadEnabled: importDataOverride?.downloadEnabled ?? CONFIG.DEFAULTS.PUBLISH.DOWNLOAD_ENABLED, | ||
118 | waitTranscoding: importDataOverride?.waitTranscoding || false, | ||
119 | state: VideoState.TO_IMPORT, | ||
120 | nsfw: importDataOverride?.nsfw || importData.nsfw || false, | ||
121 | description: importDataOverride?.description || importData.description, | ||
122 | support: importDataOverride?.support || null, | ||
123 | privacy: importDataOverride?.privacy || VideoPrivacy.PRIVATE, | ||
124 | duration: 0, // duration will be set by the import job | ||
125 | channelId, | ||
126 | originallyPublishedAt: importDataOverride?.originallyPublishedAt | ||
127 | ? new Date(importDataOverride?.originallyPublishedAt) | ||
128 | : importData.originallyPublishedAt | ||
129 | } | ||
130 | |||
131 | videoData = await Hooks.wrapObject( | ||
132 | videoData, | ||
133 | importType === 'url' | ||
134 | ? 'filter:api.video.import-url.video-attribute.result' | ||
135 | : 'filter:api.video.import-torrent.video-attribute.result' | ||
136 | ) | ||
137 | |||
138 | const video = new VideoModel(videoData) | ||
139 | video.url = getLocalVideoActivityPubUrl(video) | ||
140 | |||
141 | return video | ||
142 | } | ||
143 | |||
144 | async function buildYoutubeDLImport (options: { | ||
145 | targetUrl: string | ||
146 | channel: MChannelAccountDefault | ||
147 | user: MUser | ||
148 | channelSync?: MChannelSync | ||
149 | importDataOverride?: Partial<VideoImportCreate> | ||
150 | thumbnailFilePath?: string | ||
151 | previewFilePath?: string | ||
152 | }) { | ||
153 | const { targetUrl, channel, channelSync, importDataOverride, thumbnailFilePath, previewFilePath, user } = options | ||
154 | |||
155 | const youtubeDL = new YoutubeDLWrapper( | ||
156 | targetUrl, | ||
157 | ServerConfigManager.Instance.getEnabledResolutions('vod'), | ||
158 | CONFIG.TRANSCODING.ALWAYS_TRANSCODE_ORIGINAL_RESOLUTION | ||
159 | ) | ||
160 | |||
161 | // Get video infos | ||
162 | let youtubeDLInfo: YoutubeDLInfo | ||
163 | try { | ||
164 | youtubeDLInfo = await youtubeDL.getInfoForDownload() | ||
165 | } catch (err) { | ||
166 | throw YoutubeDlImportError.fromError( | ||
167 | err, YoutubeDlImportError.CODE.FETCH_ERROR, `Cannot fetch information from import for URL ${targetUrl}` | ||
168 | ) | ||
169 | } | ||
170 | |||
171 | if (!await hasUnicastURLsOnly(youtubeDLInfo)) { | ||
172 | throw new YoutubeDlImportError({ | ||
173 | message: 'Cannot use non unicast IP as targetUrl.', | ||
174 | code: YoutubeDlImportError.CODE.NOT_ONLY_UNICAST_URL | ||
175 | }) | ||
176 | } | ||
177 | |||
178 | const video = await buildVideoFromImport({ | ||
179 | channelId: channel.id, | ||
180 | importData: youtubeDLInfo, | ||
181 | importDataOverride, | ||
182 | importType: 'url' | ||
183 | }) | ||
184 | |||
185 | const thumbnailModel = await forgeThumbnail({ | ||
186 | inputPath: thumbnailFilePath, | ||
187 | downloadUrl: youtubeDLInfo.thumbnailUrl, | ||
188 | video, | ||
189 | type: ThumbnailType.MINIATURE | ||
190 | }) | ||
191 | |||
192 | const previewModel = await forgeThumbnail({ | ||
193 | inputPath: previewFilePath, | ||
194 | downloadUrl: youtubeDLInfo.thumbnailUrl, | ||
195 | video, | ||
196 | type: ThumbnailType.PREVIEW | ||
197 | }) | ||
198 | |||
199 | const videoImport = await insertFromImportIntoDB({ | ||
200 | video, | ||
201 | thumbnailModel, | ||
202 | previewModel, | ||
203 | videoChannel: channel, | ||
204 | tags: importDataOverride?.tags || youtubeDLInfo.tags, | ||
205 | user, | ||
206 | videoImportAttributes: { | ||
207 | targetUrl, | ||
208 | state: VideoImportState.PENDING, | ||
209 | userId: user.id | ||
210 | } | ||
211 | }) | ||
212 | |||
213 | // Get video subtitles | ||
214 | await processYoutubeSubtitles(youtubeDL, targetUrl, video.id) | ||
215 | |||
216 | let fileExt = `.${youtubeDLInfo.ext}` | ||
217 | if (!isVideoFileExtnameValid(fileExt)) fileExt = '.mp4' | ||
218 | |||
219 | const payload: VideoImportPayload = { | ||
220 | type: 'youtube-dl' as 'youtube-dl', | ||
221 | videoImportId: videoImport.id, | ||
222 | fileExt, | ||
223 | // If part of a sync process, there is a parent job that will aggregate children results | ||
224 | preventException: !!channelSync | ||
225 | } | ||
226 | |||
227 | return { | ||
228 | videoImport, | ||
229 | job: { type: 'video-import' as 'video-import', payload } | ||
230 | } | ||
231 | } | ||
232 | |||
233 | // --------------------------------------------------------------------------- | ||
234 | |||
235 | export { | ||
236 | buildYoutubeDLImport, | ||
237 | YoutubeDlImportError, | ||
238 | insertFromImportIntoDB, | ||
239 | buildVideoFromImport | ||
240 | } | ||
241 | |||
242 | // --------------------------------------------------------------------------- | ||
243 | |||
244 | async function forgeThumbnail ({ inputPath, video, downloadUrl, type }: { | ||
245 | inputPath?: string | ||
246 | downloadUrl?: string | ||
247 | video: MVideoThumbnail | ||
248 | type: ThumbnailType | ||
249 | }): Promise<MThumbnail> { | ||
250 | if (inputPath) { | ||
251 | return updateVideoMiniatureFromExisting({ | ||
252 | inputPath, | ||
253 | video, | ||
254 | type, | ||
255 | automaticallyGenerated: false | ||
256 | }) | ||
257 | } else if (downloadUrl) { | ||
258 | try { | ||
259 | return await updateVideoMiniatureFromUrl({ downloadUrl, video, type }) | ||
260 | } catch (err) { | ||
261 | logger.warn('Cannot process thumbnail %s from youtubedl.', downloadUrl, { err }) | ||
262 | } | ||
263 | } | ||
264 | return null | ||
265 | } | ||
266 | |||
267 | async function processYoutubeSubtitles (youtubeDL: YoutubeDLWrapper, targetUrl: string, videoId: number) { | ||
268 | try { | ||
269 | const subtitles = await youtubeDL.getSubtitles() | ||
270 | |||
271 | logger.info('Will create %s subtitles from youtube import %s.', subtitles.length, targetUrl) | ||
272 | |||
273 | for (const subtitle of subtitles) { | ||
274 | if (!await isVTTFileValid(subtitle.path)) { | ||
275 | await remove(subtitle.path) | ||
276 | continue | ||
277 | } | ||
278 | |||
279 | const videoCaption = new VideoCaptionModel({ | ||
280 | videoId, | ||
281 | language: subtitle.language, | ||
282 | filename: VideoCaptionModel.generateCaptionName(subtitle.language) | ||
283 | }) as MVideoCaption | ||
284 | |||
285 | // Move physical file | ||
286 | await moveAndProcessCaptionFile(subtitle, videoCaption) | ||
287 | |||
288 | await sequelizeTypescript.transaction(async t => { | ||
289 | await VideoCaptionModel.insertOrReplaceLanguage(videoCaption, t) | ||
290 | }) | ||
291 | } | ||
292 | } catch (err) { | ||
293 | logger.warn('Cannot get video subtitles.', { err }) | ||
294 | } | ||
295 | } | ||
296 | |||
297 | async function hasUnicastURLsOnly (youtubeDLInfo: YoutubeDLInfo) { | ||
298 | const hosts = youtubeDLInfo.urls.map(u => new URL(u).hostname) | ||
299 | const uniqHosts = new Set(hosts) | ||
300 | |||
301 | for (const h of uniqHosts) { | ||
302 | if (await isResolvingToUnicastOnly(h) !== true) { | ||
303 | return false | ||
304 | } | ||
305 | } | ||
306 | |||
307 | return true | ||
308 | } | ||