Updated LocateShortUrlVisit listener so that it updates geolite db is needed

This commit is contained in:
Alejandro Celaya 2019-07-20 11:21:00 +02:00
parent 37e286df48
commit e0e522c3f5
3 changed files with 34 additions and 2 deletions

1
.gitignore vendored
View File

@ -7,6 +7,7 @@ vendor/
data/database.sqlite
data/shlink-tests.db
data/GeoLite2-City.mmdb
data/GeoLite2-City.mmdb.*
docs/swagger-ui*
docker-compose.override.yml
.phpunit.result.cache

View File

@ -3,6 +3,7 @@ declare(strict_types=1);
namespace Shlinkio\Shlink\Core;
use Shlinkio\Shlink\CLI\Util\GeolocationDbUpdater;
use Shlinkio\Shlink\Common\IpGeolocation\IpLocationResolverInterface;
use Zend\ServiceManager\AbstractFactory\ConfigAbstractFactory;
@ -24,7 +25,12 @@ return [
],
ConfigAbstractFactory::class => [
EventDispatcher\LocateShortUrlVisit::class => [IpLocationResolverInterface::class, 'em', 'Logger_Shlink'],
EventDispatcher\LocateShortUrlVisit::class => [
IpLocationResolverInterface::class,
'em',
'Logger_Shlink',
GeolocationDbUpdater::class,
],
],
];

View File

@ -5,6 +5,8 @@ namespace Shlinkio\Shlink\Core\EventDispatcher;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Shlinkio\Shlink\CLI\Exception\GeolocationDbUpdateFailedException;
use Shlinkio\Shlink\CLI\Util\GeolocationDbUpdaterInterface;
use Shlinkio\Shlink\Common\Exception\WrongIpException;
use Shlinkio\Shlink\Common\IpGeolocation\IpLocationResolverInterface;
use Shlinkio\Shlink\Common\IpGeolocation\Model\Location;
@ -21,15 +23,19 @@ class LocateShortUrlVisit
private $em;
/** @var LoggerInterface */
private $logger;
/** @var GeolocationDbUpdaterInterface */
private $dbUpdater;
public function __construct(
IpLocationResolverInterface $ipLocationResolver,
EntityManagerInterface $em,
LoggerInterface $logger
LoggerInterface $logger,
GeolocationDbUpdaterInterface $dbUpdater
) {
$this->ipLocationResolver = $ipLocationResolver;
$this->em = $em;
$this->logger = $logger;
$this->dbUpdater = $dbUpdater;
}
public function __invoke(ShortUrlVisited $shortUrlVisited): void
@ -43,6 +49,25 @@ class LocateShortUrlVisit
return;
}
try {
$this->dbUpdater->checkDbUpdate(function (bool $olderDbExists) {
$this->logger->notice(sprintf('%s GeoLite2 database...', $olderDbExists ? 'Updating' : 'Downloading'));
});
} catch (GeolocationDbUpdateFailedException $e) {
if (! $e->olderDbExists()) {
$this->logger->error(
sprintf(
'GeoLite2 database download failed. It is not possible to locate visit with id %s. {e}',
$visitId
),
['e' => $e]
);
return;
}
$this->logger->warning('GeoLite2 database update failed. Proceeding with old version. {e}', ['e' => $e]);
}
try {
$location = $visit->isLocatable()
? $this->ipLocationResolver->resolveIpLocation($visit->getRemoteAddr())