<commit_before>import { logger } from '@server/helpers/logger'
import { YoutubeDLWrapper } from '@server/helpers/youtube-dl'
import { CONFIG } from '@server/initializers/config'
import { buildYoutubeDLImport } from '@server/lib/video-import'
import { UserModel } from '@server/models/user/user'
import { VideoImportModel } from '@server/models/video/video-import'
import { MChannel, MChannelAccountDefault, MChannelSync } from '@server/types/models'
import { VideoChannelSyncState, VideoPrivacy } from '@shared/models'
import { CreateJobArgument, JobQueue } from './job-queue'
import { ServerConfigManager } from './server-config-manager'

export async function synchronizeChannel (options: {
  channel: MChannelAccountDefault
  externalChannelUrl: string
  channelSync?: MChannelSync
  videosCountLimit?: number
  onlyAfter?: Date
}) {
  const { channel, externalChannelUrl, videosCountLimit, onlyAfter, channelSync } = options

  if (channelSync) {
    channelSync.state = VideoChannelSyncState.PROCESSING
    channelSync.lastSyncAt = new Date()
    await channelSync.save()
  }

  const user = await UserModel.loadByChannelActorId(channel.actorId)
  const youtubeDL = new YoutubeDLWrapper(
    externalChannelUrl,
    ServerConfigManager.Instance.getEnabledResolutions('vod'),
    CONFIG.TRANSCODING.ALWAYS_TRANSCODE_ORIGINAL_RESOLUTION
  )

  const targetUrls = await youtubeDL.getInfoForListImport({ latestVideosCount: videosCountLimit })

  logger.info(
    'Fetched %d candidate URLs for sync channel %s.',
    targetUrls.length, channel.Actor.preferredUsername, { targetUrls }
  )

  if (targetUrls.length === 0) {
    if (channelSync) {
      channelSync.state = VideoChannelSyncState.SYNCED
      await channelSync.save()
    }

    return
  }

  const children: CreateJobArgument[] = []

  for (const targetUrl of targetUrls) {
    if (await skipImport(channel, targetUrl, onlyAfter)) continue

    const { job } = await buildYoutubeDLImport({
      user,
      channel,
      targetUrl,
      channelSync,
      importDataOverride: {
        privacy: VideoPrivacy.PUBLIC
      }
    })

    children.push(job)
  }

  // Will update the channel sync status
  const parent: CreateJobArgument = {
    type: 'after-video-channel-import',
    payload: {
      channelSyncId: channelSync?.id
    }
  }

  await JobQueue.Instance.createJobWithChildren(parent, children)
}

// ---------------------------------------------------------------------------

async function skipImport (channel: MChannel, targetUrl: string, onlyAfter?: Date) {
  if (await VideoImportModel.urlAlreadyImported(channel.id, targetUrl)) {
    logger.debug('%s is already imported for channel %s, skipping video channel synchronization.', channel.name, targetUrl)
    return true
  }

  if (onlyAfter) {
    const youtubeDL = new YoutubeDLWrapper(
      targetUrl,
      ServerConfigManager.Instance.getEnabledResolutions('vod'),
      CONFIG.TRANSCODING.ALWAYS_TRANSCODE_ORIGINAL_RESOLUTION
    )

    const videoInfo = await youtubeDL.getInfoForDownload()

    const onlyAfterWithoutTime = new Date(onlyAfter)
    onlyAfterWithoutTime.setHours(0, 0, 0)

    if (videoInfo.originallyPublishedAtWithoutTime.getTime() >= onlyAfterWithoutTime.getTime()) {<commit_msg>Fix onlyAfter comparison<commit_after>import { logger } from '@server/helpers/logger'
import { YoutubeDLWrapper } from '@server/helpers/youtube-dl'
import { CONFIG } from '@server/initializers/config'
import { buildYoutubeDLImport } from '@server/lib/video-import'
import { UserModel } from '@server/models/user/user'
import { VideoImportModel } from '@server/models/video/video-import'
import { MChannel, MChannelAccountDefault, MChannelSync } from '@server/types/models'
import { VideoChannelSyncState, VideoPrivacy } from '@shared/models'
import { CreateJobArgument, JobQueue } from './job-queue'
import { ServerConfigManager } from './server-config-manager'

export async function synchronizeChannel (options: {
  channel: MChannelAccountDefault
  externalChannelUrl: string
  channelSync?: MChannelSync
  videosCountLimit?: number
  onlyAfter?: Date
}) {
  const { channel, externalChannelUrl, videosCountLimit, onlyAfter, channelSync } = options

  if (channelSync) {
    channelSync.state = VideoChannelSyncState.PROCESSING
    channelSync.lastSyncAt = new Date()
    await channelSync.save()
  }

  const user = await UserModel.loadByChannelActorId(channel.actorId)
  const youtubeDL = new YoutubeDLWrapper(
    externalChannelUrl,
    ServerConfigManager.Instance.getEnabledResolutions('vod'),
    CONFIG.TRANSCODING.ALWAYS_TRANSCODE_ORIGINAL_RESOLUTION
  )

  const targetUrls = await youtubeDL.getInfoForListImport({ latestVideosCount: videosCountLimit })

  logger.info(
    'Fetched %d candidate URLs for sync channel %s.',
    targetUrls.length, channel.Actor.preferredUsername, { targetUrls }
  )

  if (targetUrls.length === 0) {
    if (channelSync) {
      channelSync.state = VideoChannelSyncState.SYNCED
      await channelSync.save()
    }

    return
  }

  const children: CreateJobArgument[] = []

  for (const targetUrl of targetUrls) {
    if (await skipImport(channel, targetUrl, onlyAfter)) continue

    const { job } = await buildYoutubeDLImport({
      user,
      channel,
      targetUrl,
      channelSync,
      importDataOverride: {
        privacy: VideoPrivacy.PUBLIC
      }
    })

    children.push(job)
  }

  // Will update the channel sync status
  const parent: CreateJobArgument = {
    type: 'after-video-channel-import',
    payload: {
      channelSyncId: channelSync?.id
    }
  }

  await JobQueue.Instance.createJobWithChildren(parent, children)
}

// ---------------------------------------------------------------------------

async function skipImport (channel: MChannel, targetUrl: string, onlyAfter?: Date) {
  if (await VideoImportModel.urlAlreadyImported(channel.id, targetUrl)) {
    logger.debug('%s is already imported for channel %s, skipping video channel synchronization.', targetUrl, channel.name)
    return true
  }

  if (onlyAfter) {
    const youtubeDL = new YoutubeDLWrapper(
      targetUrl,
      ServerConfigManager.Instance.getEnabledResolutions('vod'),
      CONFIG.TRANSCODING.ALWAYS_TRANSCODE_ORIGINAL_RESOLUTION
    )

    const videoInfo = await youtubeDL.getInfoForDownload()

    const onlyAfterWithoutTime = new Date(onlyAfter)
    onlyAfterWithoutTime.setHours(0, 0, 0, 0)

    if (videoInfo.originallyPublishedAtWithoutTime.getTime() < onlyAfterWithoutTime.getTime()) {
{'fraction_non_alphanumeric': 0.11790056949361244, 'fraction_numerical': 0.0013852547329536709, 'mean_word_length': 3.743065693430657, 'pattern_counts': {'":': 0, '<': 4, '<?xml version=': 0, '>': 4, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4523193', 'n_tokens_mistral': 1897, 'n_tokens_neox': 1831, 'n_words': 419}