Completed
Push — master ( 6f7267...183492 )
by Stanislav
10:16
created

WeburgDownload   A

Complexity

Total Complexity 19

Size/Duplication

Total Lines 166
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 7
Bugs 2 Features 1
Metric Value
wmc 19
c 7
b 2
f 1
lcom 1
cbo 6
dl 0
loc 166
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A configure() 0 15 1
B execute() 0 28 4
B getPopularTorrentsUrls() 0 56 6
B getMovieTorrentsUrls() 0 26 4
B getTorrentsDirectory() 0 22 4
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
        $weburgClient = $this->getApplication()->getWeburgClient();
33
34
        try {
35
            list($torrentsDir, $downloadDir) = $this->getTorrentsDirectory($input);
36
37
            $movieArgument = $input->getArgument('movie-id');
38
            if (isset($movieArgument)) {
39
                $daysMax = $config->overrideConfig($input, 'days', 'weburg-series-max-age');
40
                $torrentsUrls = $this->getMovieTorrentsUrls($weburgClient, $movieArgument, $daysMax);
41
            } else {
42
                $torrentsUrls = $this->getPopularTorrentsUrls($output, $weburgClient, $downloadDir);
43
            }
44
45
            $this->dryRun($input, $output, function () use ($weburgClient, $torrentsDir, $torrentsUrls) {
46
                foreach ($torrentsUrls as $torrentUrl) {
47
                    $weburgClient->downloadTorrent($torrentUrl, $torrentsDir);
48
                }
49
            }, 'dry-run, don\'t really download');
50
        } catch (\RuntimeException $e) {
51
            $output->writeln($e->getMessage());
52
            return 1;
53
        }
54
55
        return 0;
56
    }
57
58
    public function getPopularTorrentsUrls(OutputInterface $output, WeburgClient $weburgClient, $downloadDir)
59
    {
60
        $torrentsUrls = [];
61
62
        $config = $this->getApplication()->getConfig();
63
        $logger = $this->getApplication()->getLogger();
64
65
        $moviesIds = $weburgClient->getMoviesIds();
66
67
        $progress = new ProgressBar($output, count($moviesIds));
68
        $progress->start();
69
70
        foreach ($moviesIds as $movieId) {
71
            $progress->setMessage('Check movie ' . $movieId . '...');
72
            $progress->advance();
73
74
            $downloadedLogfile = $downloadDir . '/' . $movieId;
75
76
            $isDownloaded = file_exists($downloadedLogfile);
77
            if ($isDownloaded) {
78
                continue;
79
            }
80
81
            $movieInfo = $weburgClient->getMovieInfoById($movieId);
82
            foreach (array_keys($movieInfo) as $infoField) {
83
                if (!isset($movieInfo[$infoField])) {
84
                    $logger->warning('Cannot find ' . $infoField . ' in movie ' . $movieId);
85
                }
86
            }
87
88
            $isTorrentPopular = $weburgClient->isTorrentPopular(
89
                $movieInfo,
90
                $config->get('download-comments-min'),
91
                $config->get('download-imdb-min'),
92
                $config->get('download-kinopoisk-min'),
93
                $config->get('download-votes-min')
94
            );
95
96
            if ($isTorrentPopular) {
97
                $progress->setMessage('Download movie ' . $movieId . '...');
98
99
                $movieUrls = $weburgClient->getMovieTorrentUrlsById($movieId);
100
                $torrentsUrls = array_merge($torrentsUrls, $movieUrls);
101
                $logger->info('Download movie ' . $movieId . ': ' . $movieInfo['title']);
102
103
                file_put_contents(
104
                    $downloadedLogfile,
105
                    date('Y-m-d H:i:s') . "\n" . implode("\n", $torrentsUrls)
106
                );
107
            }
108
        }
109
110
        $progress->finish();
111
        
112
        return $torrentsUrls;
113
    }
114
115
    /**
116
     * @param WeburgClient $weburgClient
117
     * @param $movieId
118
     * @param $daysMax
119
     * @return array
120
     * @throws \RuntimeException
121
     */
122
    public function getMovieTorrentsUrls(WeburgClient $weburgClient, $movieId, $daysMax)
123
    {
124
        $torrentsUrls = [];
125
        $logger = $this->getApplication()->getLogger();
126
127
        $movieId = $weburgClient->cleanMovieId($movieId);
128
        if (!$movieId) {
129
            throw new \RuntimeException($movieId . ' seems not weburg movie ID or URL');
130
        }
131
132
        $movieInfo = $weburgClient->getMovieInfoById($movieId);
133
        $logger->info('Search series ' . $movieId);
134
        if (!empty($movieInfo['hashes'])) {
135
            $seriesUrls = $weburgClient->getSeriesTorrents($movieId, $movieInfo['hashes'], $daysMax);
136
            $torrentsUrls = array_merge($torrentsUrls, $seriesUrls);
137
138
            if (count($seriesUrls)) {
139
                $logger->info('Download series ' . $movieId . ': '
140
                    . $movieInfo['title'] . ' (' . count($seriesUrls) . ')');
141
            }
142
        } else {
143
            $torrentsUrls = array_merge($torrentsUrls, $weburgClient->getMovieTorrentUrlsById($movieId));
144
        }
145
        
146
        return $torrentsUrls;
147
    }
148
149
    /**
150
     * @param InputInterface $input
151
     * @return array
152
     * @throws \RuntimeException
153
     */
154
    private function getTorrentsDirectory(InputInterface $input)
155
    {
156
        $config = $this->getApplication()->getConfig();
157
158
        $torrentsDir = $config->overrideConfig($input, 'download-torrents-dir');
159
        if (!$torrentsDir) {
160
            throw new \RuntimeException('Destination directory not defined. '
161
                .'Use command with --download-torrents-dir=/path/to/dir parameter '
162
                .'or define destination directory \'download-torrents-dir\' in config file.');
163
        }
164
165
        if (!file_exists($torrentsDir)) {
166
            throw new \RuntimeException('Destination directory not exists: ' . $torrentsDir);
167
        }
168
169
        $downloadDir = $torrentsDir . '/downloaded';
170
        if (!file_exists($downloadDir)) {
171
            mkdir($downloadDir, 0777);
172
        }
173
174
        return [$torrentsDir, $downloadDir];
175
    }
176
}
177