PackagistCommand.php 6.64 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
<?php
declare(strict_types = 1);

namespace T3o\TerFe2\Command;

/*
 * This file is part of the TYPO3 CMS project.
 *
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 *
 * The TYPO3 project - inspiring people to share!
 */

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use T3o\TerFe2\Domain\Model\Extension;
use T3o\TerFe2\Domain\Repository\ExtensionRepository;
use T3o\TerFe2\Domain\Repository\VersionRepository;
use T3o\TerFe2\Utility\VersionUtility;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Object\ObjectManager;
use TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager;
use TYPO3\CMS\Extbase\Persistence\Generic\Typo3QuerySettings;

class PackagistCommand extends Command
{
    /**
     * @var ObjectManager
     */
    protected $objectManager;

    /**
     * @var ExtensionRepository
     */
    protected $extensionRepository;

    /**
     * @var VersionRepository
     */
    protected $versionRepository;

    public function __construct(string $name = null, ObjectManager $objectManager = null, ExtensionRepository $extensionRepository = null, VersionRepository $versionRepository = null)
    {
        $this->objectManager = $objectManager ?? GeneralUtility::makeInstance(ObjectManager::class);
        //$this->extensionRepository = $extensionRepository ?? GeneralUtility::makeInstance(ExtensionRepository::class, $this->objectManager);
        //$this->versionRepository = $versionRepository ?? GeneralUtility::makeInstance(VersionRepository::class, $this->objectManager);
        $this->extensionRepository = $extensionRepository ?? $this->objectManager->get(ExtensionRepository::class);
        $this->versionRepository = $versionRepository ?? $this->objectManager->get(VersionRepository::class);
        //$this->extensionRepository = $extensionRepository ?? new ExtensionRepository();
        //$this->versionRepository = $versionRepository ?? new VersionRepository();
        parent::__construct($name);
    }

    protected function configure()
    {
        $this->setDescription('Fetches download numbers from Packagist');

        $this->addOption(
            'limit',
            'l',
            InputArgument::OPTIONAL,
            'This will set the limit of how many extension to fetch download data off',
            25
        );
    }

    /**
     * Fetch download data from Packagist
     *
     * @param InputInterface $input
     * @param OutputInterface $output
     *
     * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException
     * @throws \TYPO3\CMS\Extbase\Persistence\Exception\InvalidQueryException
     * @throws \TYPO3\CMS\Extbase\Persistence\Exception\UnknownObjectException
     */
    public function execute(InputInterface $input, OutputInterface $output)
    {
        $objectManager = GeneralUtility::makeInstance(ObjectManager::class);

        $io = new SymfonyStyle($input, $output);
        $limit = (int) $input->getOption('limit');
        $querySettings = $objectManager->get(Typo3QuerySettings::class);
        $querySettings->setRespectStoragePage(false);
        $this->extensionRepository->setDefaultQuerySettings($querySettings);
        $this->versionRepository->setDefaultQuerySettings($querySettings);

        $extensions = $this->extensionRepository->findWithComposerName($limit);

        // User-Agent https://twitter.com/seldaek/status/1095420243315511297
        $options = ['http' => ['user_agent' => 'Thanks a bunch! Fetching packagist Download Data for https://extensions.typo3.org - https://typo3.org/community/teams/typo3org/']];
        $context = stream_context_create($options);

        /** @var Extension $extension */
        foreach ($extensions as $extension) {
            $io->writeln('<info> Processing: ' . $extension->getExtKey() . '</info>');
            $packagistUrl = 'https://packagist.org/packages/' . $extension->getComposerName() . '/downloads.json';

            /** @var Extension $extension */
            $extension = $this->extensionRepository->findOneByExtKey($extension->getExtKey());
            $this->updateLastDownloadSyncForExtension($extension);

            // A Packagist URL returned 404 and would proceed, so it will be skipped for this run.
            // TODO: Perhaps an report should be generated if it keeps happening?
            if (!$this->doesUrlReturnOKCode($packagistUrl)) {
                continue;
            }

            $downloadData = json_decode(file_get_contents($packagistUrl, false, $context), true);

            foreach ($downloadData['package']['downloads']['versions'] as $version => $downloads) {
                $versionFound = $this->versionRepository->findOneByExtensionAndVersionString($extension, $version);
                if (null === $versionFound) {
                    continue;
                }

                if (!$version) {
                    continue;
                }

                VersionUtility::updateVersionCounter(
                    $extension->getExtKey(),
                    $versionFound->getUid(),
                    VersionUtility::DOWNLOAD_SOURCE_PACKAGIST,
                    $downloads['monthly']
                );
            }
        }
        $io->writeln('Fetching download numbers from Packagist is completed');
    }

    /**
     * Sets Extension Last Download Sync to secure oldest syncs happens first.
     * @param Extension $extension
     * @throws \TYPO3\CMS\Extbase\Object\Exception
     */
    private function updateLastDownloadSyncForExtension(Extension $extension): void
    {
        $extension->setLastDownloadSync(time());
        $this->extensionRepository->update($extension);
        /** @var PersistenceManager $persistenceManager */
        $persistenceManager = $this->objectManager->get(PersistenceManager::class);
        $persistenceManager->persistAll();
    }

    private function doesUrlReturnOKCode(string $url): bool
    {
        $handle = curl_init($url);
        curl_setopt($handle,  CURLOPT_RETURNTRANSFER, TRUE);

        /* Get the HTML or whatever is linked in $url. */
        $response = curl_exec($handle);

        /* Check for 404 (file not found). */
        $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
        if($httpCode != 200) {
            return false;
        }

        curl_close($handle);
        return true;
    }
}