<commit_before><?php

namespace Bluelyte\Johnny;

use Bluelyte\TPB\Client\Client as TpbClient;
use Bluelyte\IMDB\Client\Client as ImdbClient;
use Bluelyte\Transmission\Remote;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;

class Downloader
{
    /**
     * @var Bluelyte\TPB\Client\Client
     */
    protected $tpbClient;

    /**
     * @var Bluelyte\IMDB\Client\Client
     */
    protected $imdbClient;

    /**
     * @var Bluelyte\Transmission\Remote
     */
    protected $remote;

    /**
     * @var Monolog\Logger
     */
    protected $logger;

    /**
     * List of IMDB identifiers for shows to download
     * @var array
     */
    protected $series = array();

    /**
     * Path to destination directory for downloaded files
     * @var string
     */
    protected $downloadPath = null;

    /**
     * Downloads the latest episodes of the specified shows to the specified
     * download path.
     */
    public function downloadLatestEpisodes()
    {
        $series = $this->getSeries();
        $downloadPath = $this->getDownloadPath();
        $imdb = $this->getImdbClient();
        $tpb = $this->getTpbClient();
        $remote = $this->getRemote();
        $logger = $this->getLogger();

        $remote->setDownloadPath($downloadPath);
        $remote->start();

        foreach ($series as $id)
        {
            $logger->debug('Fetching show info for ID ' . $id);
            $showInfo = $imdb->getShowInfo($id);
            $title = $showInfo['title'];
            $latestSeason = $showInfo['latestSeason'];

            $logger->debug('Fetching episodes for "' . $title . '" season ' . $latestSeason);
            $episodes = $imdb->getSeasonEpisodes($id, $latestSeason);
            $latestEpisode = max(array_keys($episodes));

            $logger->debug('Checking if episode ' . $latestEpisode . ' has already been downloaded');
            $pattern = '/' . preg_replace('/\s+/', '.+', preg_quote($title)) . '.+s0?' . $latestSeason . 'e0?' . $latestEpisode . '[^0-9]/i';
            $iterator = new \RecursiveRegexIterator(new \RecursiveDirectoryIterator($downloadPath), $pattern);
            if ($iterator->hasChildren()) {
                $logger->debug('Episode has been downloaded, skipping');
                continue;
            }

            $logger->debug('Searching for episode torrent');
            $term = $title . ' S' . str_pad($latestSeason, 2, '0', STR_PAD_LEFT) . 'E' . str_pad($latestEpisode, 2, '0', STR_PAD_LEFT);
            $response = $tpb->search($term);
            $results = array_filter($response['results'], function($result) use ($pattern) {
                return (boolean) preg_match($pattern, $result['name']);
            });
            $result = reset($results);
            if (!$result) {
                $logger->debug('No results found, skipping');
                continue;
            }

            $logger->debug('Adding torrent "' . $result['name'] . '" with link "'. $result['magnetLink'] . '" to download queue');
            $remote->addTorrents($result['magnetLink']);
        }

        $logger->debug('Starting torrent downloads');
        $remote->startTorrents();
    }

    public function getSeries()
    {
        return $this->series;
    }

    public function setSeries(array $series)
    {
        $this->series = $series;
    }

    public function setDownloadPath($downloadPath)
    {
        if (!is_dir($downloadPath) || !is_writable($downloadPath)) {<commit_msg>Fixed existing episode recognition not working<commit_after><?php

namespace Bluelyte\Johnny;

use Bluelyte\TPB\Client\Client as TpbClient;
use Bluelyte\IMDB\Client\Client as ImdbClient;
use Bluelyte\Transmission\Remote;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;

class Downloader
{
    /**
     * @var Bluelyte\TPB\Client\Client
     */
    protected $tpbClient;

    /**
     * @var Bluelyte\IMDB\Client\Client
     */
    protected $imdbClient;

    /**
     * @var Bluelyte\Transmission\Remote
     */
    protected $remote;

    /**
     * @var Monolog\Logger
     */
    protected $logger;

    /**
     * List of IMDB identifiers for shows to download
     * @var array
     */
    protected $series = array();

    /**
     * Path to destination directory for downloaded files
     * @var string
     */
    protected $downloadPath = null;

    /**
     * Downloads the latest episodes of the specified shows to the specified
     * download path.
     */
    public function downloadLatestEpisodes()
    {
        $series = $this->getSeries();
        $downloadPath = $this->getDownloadPath();
        $imdb = $this->getImdbClient();
        $tpb = $this->getTpbClient();
        $remote = $this->getRemote();
        $logger = $this->getLogger();

        $remote->setDownloadPath($downloadPath);
        $remote->start();

        foreach ($series as $id)
        {
            $logger->debug('Fetching show info for ID ' . $id);
            $showInfo = $imdb->getShowInfo($id);
            $title = $showInfo['title'];
            $latestSeason = $showInfo['latestSeason'];

            $logger->debug('Fetching episodes for "' . $title . '" season ' . $latestSeason);
            $episodes = $imdb->getSeasonEpisodes($id, $latestSeason);
            $latestEpisode = max(array_keys($episodes));

            $logger->debug('Checking if episode ' . $latestEpisode . ' has already been downloaded');
            $pattern = '/' . preg_replace('/\s+/', '.+', preg_quote($title)) . '.+s0?' . $latestSeason . 'e0?' . $latestEpisode . '[^0-9]/i';

            $files = array_filter(
                iterator_to_array(new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($downloadPath))),
                function($entry) use ($pattern) {
                    return (boolean) preg_match($pattern, $entry->getPathname());
                }
            );
            if ($files) {
                $logger->debug('Skipping, found episode at ' . reset($files));
                continue;
            }

            $logger->debug('Searching for episode torrent');
            $term = $title . ' S' . str_pad($latestSeason, 2, '0', STR_PAD_LEFT) . 'E' . str_pad($latestEpisode, 2, '0', STR_PAD_LEFT);
            $response = $tpb->search($term);
            $results = array_filter($response['results'], function($result) use ($pattern) {
                return (boolean) preg_match($pattern, $result['name']);
            });
            $result = reset($results);
            if (!$result) {
                $logger->debug('Skipping, no results found');
                continue;
            }

            $logger->debug('Adding torrent "' . $result['name'] . '" with link "'. $result['magnetLink'] . '" to download queue');
            $remote->addTorrents($result['magnetLink']);
        }

        $logger->debug('Starting torrent downloads');
        $remote->startTorrents();
    }

    public function getSeries()
    {
        return $this->series;
    }

    public function setSeries(array $series)
    {
        $this->series = $series;
    }

    public function setDownloadPath($downloadPath)
    {
        if (!is_dir($downloadPath) || !is_writable($downloadPath)) {
{'fraction_non_alphanumeric': 0.1477961432506887, 'fraction_numerical': 0.0022038567493112946, 'mean_word_length': 2.235739750445633, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 51, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 52, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4357941', 'n_tokens_mistral': 2144, 'n_tokens_neox': 2047, 'n_words': 442}