Completed
Push — master ( f277c1...6f7267 )
by Stanislav
02:15
created

WeburgDownload::execute()   C

Complexity

Conditions 7
Paths 12

Size

Total Lines 43
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 6
Bugs 2 Features 0
Metric Value
c 6
b 2
f 0
dl 0
loc 43
rs 6.7272
cc 7
eloc 27
nc 12
nop 2
1
<?php
2
3
namespace Popstas\Transmission\Console\Command;
4
5
use Popstas\Transmission\Console\WeburgClient;
6
use Symfony\Component\Console\Helper\ProgressBar;
7
use Symfony\Component\Console\Input\InputInterface;
8
use Symfony\Component\Console\Input\InputOption;
9
use Symfony\Component\Console\Output\OutputInterface;
10
11
class WeburgDownload extends Command
12
{
13
    protected function configure()
14
    {
15
        parent::configure();
16
        $this
17
            ->setName('weburg-download')
18
            ->setAliases(['wd'])
19
            ->setDescription('Download torrents from weburg.net')
20
            ->addOption('download-torrents-dir', null, InputOption::VALUE_OPTIONAL, 'Torrents destination directory')
21
            ->addOption('days', null, InputOption::VALUE_OPTIONAL, 'Max age of series torrent', 3)
22
            ->addArgument('movie-id', null, 'Movie ID or URL')
23
            ->setHelp(<<<EOT
24
The <info>weburg-download</info> scans weburg.net top page and downloads popular torrents.
25
EOT
26
            );
27
    }
28
29
    protected function execute(InputInterface $input, OutputInterface $output)
30
    {
31
        $config = $this->getApplication()->getConfig();
32
33
        $weburgClient = $this->getApplication()->getWeburgClient();
34
        if (!isset($weburgClient)) {
35
            $this->getApplication()->setWeburgClient($this->createWeburgClient());
36
            $weburgClient = $this->getApplication()->getWeburgClient();
37
        }
38
39
        try {
40
            list($torrentsDir, $downloadDir) = $this->getTorrentsDirectory($input);
41
        } catch (\RuntimeException $e) {
42
            $output->writeln($e->getMessage());
43
            return 1;
44
        }
45
46
        $movieArgument = $input->getArgument('movie-id');
47
        if (isset($movieArgument)) {
48
            $movieId = $weburgClient->cleanMovieId($movieArgument);
49
            if (!$movieId) {
50
                $output->writeln($movieArgument . ' seems not weburg movie ID or URL');
51
                return 1;
52
            }
53
54
            $daysMax = $config->overrideConfig($input, 'days', 'weburg-series-max-age');
55
56
            $torrentsUrls = $this->getMovieTorrentsUrls($weburgClient, $movieId, $daysMax);
57
58
        } else {
59
            $torrentsUrls = $this->getPopularTorrentsUrls($output, $weburgClient, $downloadDir);
60
        }
61
62
        if (!$input->getOption('dry-run')) {
63
            foreach ($torrentsUrls as $torrentUrl) {
64
                $weburgClient->downloadTorrent($torrentUrl, $torrentsDir);
65
            }
66
        } else {
67
            $output->writeln('dry-run, don\'t really download');
68
        }
69
70
        return 0;
71
    }
72
73
    public function getPopularTorrentsUrls(OutputInterface $output, WeburgClient $weburgClient, $downloadDir)
74
    {
75
        $torrentsUrls = [];
76
77
        $config = $this->getApplication()->getConfig();
78
        $logger = $this->getApplication()->getLogger();
79
80
        $moviesIds = $weburgClient->getMoviesIds();
81
82
        $progress = new ProgressBar($output, count($moviesIds));
83
        $progress->start();
84
85
        foreach ($moviesIds as $movieId) {
86
            $progress->setMessage('Check movie ' . $movieId . '...');
87
            $progress->advance();
88
89
            $downloadedLogfile = $downloadDir . '/' . $movieId;
90
91
            $isDownloaded = file_exists($downloadedLogfile);
92
            if ($isDownloaded) {
93
                continue;
94
            }
95
96
            $movieInfo = $weburgClient->getMovieInfoById($movieId);
97
            foreach (array_keys($movieInfo) as $infoField) {
98
                if (!isset($movieInfo[$infoField])) {
99
                    $logger->warning('Cannot find ' . $infoField . ' in movie ' . $movieId);
100
                }
101
            }
102
103
            $isTorrentPopular = $weburgClient->isTorrentPopular(
104
                $movieInfo,
105
                $config->get('download-comments-min'),
106
                $config->get('download-imdb-min'),
107
                $config->get('download-kinopoisk-min'),
108
                $config->get('download-votes-min')
109
            );
110
111
            if ($isTorrentPopular) {
112
                $progress->setMessage('Download movie ' . $movieId . '...');
113
114
                $movieUrls = $weburgClient->getMovieTorrentUrlsById($movieId);
115
                $torrentsUrls = array_merge($torrentsUrls, $movieUrls);
116
                $logger->info('Download movie ' . $movieId . ': ' . $movieInfo['title']);
117
118
                file_put_contents(
119
                    $downloadedLogfile,
120
                    date('Y-m-d H:i:s') . "\n" . implode("\n", $torrentsUrls)
121
                );
122
            }
123
        }
124
125
        $progress->finish();
126
        
127
        return $torrentsUrls;
128
    }
129
130
    public function getMovieTorrentsUrls(WeburgClient $weburgClient, $movieId, $daysMax)
131
    {
132
        $torrentsUrls = [];
133
134
        $logger = $this->getApplication()->getLogger();
135
136
        $movieInfo = $weburgClient->getMovieInfoById($movieId);
137
        $logger->info('Search series ' . $movieId);
138
        if (!empty($movieInfo['hashes'])) {
139
            $seriesUrls = $weburgClient->getSeriesTorrents($movieId, $movieInfo['hashes'], $daysMax);
140
            $torrentsUrls = array_merge($torrentsUrls, $seriesUrls);
141
142
            if (count($seriesUrls)) {
143
                $logger->info('Download series ' . $movieId . ': '
144
                    . $movieInfo['title'] . ' (' . count($seriesUrls) . ')');
145
            }
146
        } else {
147
            $torrentsUrls = array_merge($torrentsUrls, $weburgClient->getMovieTorrentUrlsById($movieId));
148
        }
149
        
150
        return $torrentsUrls;
151
    }
152
153
    /**
154
     * @param InputInterface $input
155
     * @return array
156
     * @throws \RuntimeException
157
     */
158
    private function getTorrentsDirectory(InputInterface $input)
159
    {
160
        $config = $this->getApplication()->getConfig();
161
162
        $torrentsDir = $config->overrideConfig($input, 'download-torrents-dir');
163
        if (!$torrentsDir) {
164
            throw new \RuntimeException('Destination directory not defined. '
165
                .'Use command with --download-torrents-dir=/path/to/dir parameter '
166
                .'or define destination directory \'download-torrents-dir\' in config file.');
167
        }
168
169
        if (!file_exists($torrentsDir)) {
170
            throw new \RuntimeException('Destination directory not exists: ' . $torrentsDir);
171
        }
172
173
        $downloadDir = $torrentsDir . '/downloaded';
174
        if (!file_exists($downloadDir)) {
175
            mkdir($downloadDir, 0777);
176
        }
177
178
        return [$torrentsDir, $downloadDir];
179
    }
180
}
181