events/Classes/Service/DestinationDataImportService.php

648 lines
21 KiB
PHP
Raw Normal View History

2019-08-12 07:43:37 +02:00
<?php
namespace Wrm\Events\Service;
use Exception;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\DataHandling\DataHandler;
use TYPO3\CMS\Core\DataHandling\SlugHelper;
use TYPO3\CMS\Core\Log\Logger;
use TYPO3\CMS\Core\Log\LogManager;
2021-09-06 15:18:48 +02:00
use TYPO3\CMS\Core\Resource\Exception\FolderDoesNotExistException;
use TYPO3\CMS\Core\Resource\File;
2019-08-12 07:43:37 +02:00
use TYPO3\CMS\Core\Resource\Index\MetaDataRepository;
use TYPO3\CMS\Core\Resource\ResourceStorage;
2019-08-12 07:43:37 +02:00
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Configuration\ConfigurationManager;
use TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface;
use TYPO3\CMS\Extbase\Object\ObjectManager;
use TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager;
2019-08-12 07:43:37 +02:00
use TYPO3\CMS\Extbase\Persistence\ObjectStorage;
use Wrm\Events\Domain\Model\Category;
use Wrm\Events\Domain\Model\Date;
use Wrm\Events\Domain\Model\Event;
use Wrm\Events\Domain\Model\Import;
use Wrm\Events\Domain\Model\Organizer;
2021-12-14 16:22:29 +01:00
use Wrm\Events\Domain\Model\Region;
use Wrm\Events\Domain\Repository\CategoryRepository;
2019-08-12 07:43:37 +02:00
use Wrm\Events\Domain\Repository\DateRepository;
use Wrm\Events\Domain\Repository\EventRepository;
use Wrm\Events\Domain\Repository\OrganizerRepository;
use Wrm\Events\Service\DestinationDataImportService\CategoriesAssignment;
use Wrm\Events\Service\DestinationDataImportService\CategoriesAssignment\Import as CategoryImport;
use Wrm\Events\Service\DestinationDataImportService\DataFetcher;
use Wrm\Events\Service\DestinationDataImportService\DatesFactory;
2022-08-02 15:56:18 +02:00
use Wrm\Events\Service\DestinationDataImportService\LocationAssignment;
2022-11-23 10:59:55 +01:00
use Wrm\Events\Service\DestinationDataImportService\Slugger;
2019-08-12 07:43:37 +02:00
class DestinationDataImportService
{
2019-08-12 07:43:37 +02:00
/**
* @var Import
2019-08-12 07:43:37 +02:00
*/
private $import;
2019-08-12 07:43:37 +02:00
/**
* @var Event
2019-08-12 07:43:37 +02:00
*/
private $tmpCurrentEvent;
2019-08-12 07:43:37 +02:00
/**
* @var Logger
2019-08-12 07:43:37 +02:00
*/
private $logger;
2019-08-12 07:43:37 +02:00
/**
* @var EventRepository
*/
private $eventRepository;
2019-08-12 07:43:37 +02:00
/**
* @var OrganizerRepository
*/
private $organizerRepository;
2019-08-12 07:43:37 +02:00
/**
* @var DateRepository
*/
private $dateRepository;
2019-08-12 07:43:37 +02:00
/**
* @var MetaDataRepository
*/
private $metaDataRepository;
2019-08-12 07:43:37 +02:00
/**
* @var ConfigurationManager
*/
private $configurationManager;
2019-08-12 07:43:37 +02:00
/**
* @var ObjectManager
*/
private $objectManager;
2019-08-12 07:43:37 +02:00
/**
* @var PersistenceManager
*/
private $persistenceManager;
/**
* @var DataFetcher
*/
private $dataFetcher;
/**
* @var DatesFactory
*/
private $datesFactory;
/**
* @var CategoriesAssignment
*/
private $categoriesAssignment;
2022-08-02 15:56:18 +02:00
/**
* @var LocationAssignment
*/
private $locationAssignment;
2022-11-23 10:59:55 +01:00
/**
* @var Slugger
*/
private $slugger;
2019-08-12 07:43:37 +02:00
/**
* ImportService constructor.
* @param EventRepository $eventRepository
* @param OrganizerRepository $organizerRepository
* @param DateRepository $dateRepository
* @param MetaDataRepository $metaDataRepository
* @param ConfigurationManager $configurationManager
* @param PersistenceManager $persistenceManager
* @param ObjectManager $objectManager
* @param DataFetcher $dataFetcher
* @param CategoriesAssignment $categoriesAssignment
2022-08-02 15:56:18 +02:00
* @param LocationAssignment $locationAssignment
2022-11-23 10:59:55 +01:00
* @param Slugger $slugger
2019-08-12 07:43:37 +02:00
*/
public function __construct(
EventRepository $eventRepository,
OrganizerRepository $organizerRepository,
DateRepository $dateRepository,
MetaDataRepository $metaDataRepository,
ConfigurationManager $configurationManager,
PersistenceManager $persistenceManager,
2019-08-12 15:49:52 +02:00
ObjectManager $objectManager,
DataFetcher $dataFetcher,
DatesFactory $datesFactory,
2022-08-02 15:56:18 +02:00
CategoriesAssignment $categoriesAssignment,
2022-11-23 10:59:55 +01:00
LocationAssignment $locationAssignment,
Slugger $slugger
2019-08-12 07:43:37 +02:00
) {
$this->eventRepository = $eventRepository;
$this->organizerRepository = $organizerRepository;
$this->dateRepository = $dateRepository;
$this->metaDataRepository = $metaDataRepository;
$this->configurationManager = $configurationManager;
$this->persistenceManager = $persistenceManager;
$this->objectManager = $objectManager;
$this->dataFetcher = $dataFetcher;
$this->datesFactory = $datesFactory;
$this->categoriesAssignment = $categoriesAssignment;
2022-08-02 15:56:18 +02:00
$this->locationAssignment = $locationAssignment;
2022-11-23 10:59:55 +01:00
$this->slugger = $slugger;
2019-08-12 15:49:52 +02:00
}
2019-08-12 07:43:37 +02:00
public function import(
Import $import
): int {
$this->import = $import;
2019-08-12 15:49:52 +02:00
// Get configuration
2019-08-12 07:43:37 +02:00
$frameworkConfiguration = $this->configurationManager->getConfiguration(
ConfigurationManagerInterface::CONFIGURATION_TYPE_FRAMEWORK
);
2019-08-12 15:49:52 +02:00
// Set storage pid
2019-08-12 07:43:37 +02:00
$persistenceConfiguration = [
'persistence' => [
'storagePid' => $this->import->getStoragePid(),
2019-08-12 07:43:37 +02:00
],
];
2019-08-12 15:49:52 +02:00
// Set Configuration
2019-08-12 07:43:37 +02:00
$this->configurationManager->setConfiguration(array_merge($frameworkConfiguration, $persistenceConfiguration));
2019-08-13 11:17:34 +02:00
$this->logger = GeneralUtility::makeInstance(LogManager::class)->getLogger(__CLASS__);
2019-10-09 15:03:58 +02:00
$this->logger->info('Starting Destination Data Import Service');
2019-08-12 07:43:37 +02:00
try {
$data = $this->dataFetcher->fetchSearchResult($import);
} catch (Exception $e) {
2019-08-13 09:12:30 +02:00
$this->logger->error('Could not receive data.');
2019-08-12 07:43:37 +02:00
return 1;
}
return $this->processData($data);
}
public function processData(array $data): int
{
2019-10-09 15:03:58 +02:00
$this->logger->info('Processing json ' . count($data['items']));
// Get selected region
$selectedRegion = $this->import->getRegion();
2019-08-12 07:43:37 +02:00
foreach ($data['items'] as $event) {
2019-08-12 15:49:52 +02:00
$this->logger->info('Processing event ' . substr($event['title'], 0, 20));
2019-08-12 15:49:52 +02:00
// Event already exists? If not create one!
$this->tmpCurrentEvent = $this->getOrCreateEvent($event['global_id'], $event['title']);
2020-10-01 08:34:13 +02:00
// Set language UID
$this->tmpCurrentEvent->setLanguageUid(-1);
2019-08-12 07:43:37 +02:00
// Set selected Region
2021-12-14 16:22:29 +01:00
if ($selectedRegion instanceof Region) {
$this->tmpCurrentEvent->setRegion($selectedRegion);
}
2019-08-12 07:43:37 +02:00
// Set Title
$this->tmpCurrentEvent->setTitle(substr($event['title'], 0, 254));
2019-08-12 07:43:37 +02:00
// Set Highlight (Is only set in rest if true)
if ($event['highlight'] ?? false) {
2019-08-12 07:43:37 +02:00
$this->tmpCurrentEvent->setHighlight($event['highlight']);
}
2019-08-12 07:43:37 +02:00
// Set Texts
if ($event['texts'] ?? false) {
$this->setTexts($event['texts']);
}
2022-08-02 15:56:18 +02:00
$this->tmpCurrentEvent->setLocation(
$this->locationAssignment->getLocation($event)
);
2019-09-23 15:41:41 +02:00
2019-08-13 09:12:30 +02:00
// Set Categories
if ($event['categories'] ?? false) {
$this->setCategories($event['categories']);
}
// Set Features
if ($event['features']) {
$this->setFeatures($event['features']);
}
2019-08-12 07:43:37 +02:00
// Set Organizer
if ($event['addresses'] ?? false) {
$this->setOrganizer($event['addresses']);
}
2020-10-01 09:45:32 +02:00
// Set Social
if ($event['media_objects'] ?? false) {
2020-08-19 11:30:13 +02:00
$this->setSocial($event['media_objects']);
}
2020-08-19 11:30:13 +02:00
2022-08-02 15:56:18 +02:00
if ($event['web'] ?? false) {
$this->tmpCurrentEvent->setWeb($event['web']);
}
2020-10-01 09:45:32 +02:00
// Set Tickets
if ($event['media_objects'] ?? false) {
2020-10-01 09:45:32 +02:00
$this->setTickets($event['media_objects']);
}
2020-10-01 09:45:32 +02:00
2019-08-12 07:43:37 +02:00
// Set Dates
if ($event['timeIntervals'] ?? false) {
$this->setDates(
$event['timeIntervals'],
(bool) $this->getAttributeValue($event, 'DETAILS_ABGESAGT')
);
}
2019-08-12 15:49:52 +02:00
// Set Assets
if ($event['media_objects'] ?? false) {
$this->setAssets($event['media_objects']);
}
2019-08-12 15:49:52 +02:00
// Update and persist
$this->logger->info('Persist database');
$this->eventRepository->update($this->tmpCurrentEvent);
$this->persistenceManager->persistAll();
}
2022-11-23 10:59:55 +01:00
$this->logger->info('Update slugs');
$this->slugger->update('tx_events_domain_model_event');
$this->slugger->update('tx_events_domain_model_date');
2019-10-09 15:03:58 +02:00
$this->logger->info('Finished import');
2019-08-12 15:49:52 +02:00
return 0;
}
2019-08-12 07:43:37 +02:00
private function setCategories(array $categories): void
{
$categories = $this->categoriesAssignment->getCategories(new CategoryImport(
$this->import->getCategoryParent(),
$this->import->getCategoriesPid(),
$categories
));
$this->tmpCurrentEvent->setCategories($categories);
}
private function setFeatures(array $features): void
{
$features = $this->categoriesAssignment->getCategories(new CategoryImport(
$this->import->getFeaturesParent(),
$this->import->getFeaturesPid(),
$features,
true
));
$this->tmpCurrentEvent->setFeatures($features);
2019-08-13 09:12:30 +02:00
}
private function setDates(
array $timeIntervals,
bool $canceled
): void {
2019-10-09 15:03:58 +02:00
// @TODO: does not seem to work -->
2019-08-12 15:49:52 +02:00
//$currentEventDates = $this->tmpCurrentEvent->getDates();
//$this->tmpCurrentEvent->removeAllDates($currentEventDates);
// <--
// TODO: Workaround delete dates
$currentEventDates = $this->tmpCurrentEvent->getDates();
$this->logger->info('Found ' . count($currentEventDates) . ' to delete');
foreach ($currentEventDates as $currentDate) {
$this->dateRepository->remove($currentDate);
}
2019-08-12 07:43:37 +02:00
$dates = $this->datesFactory->createDates($timeIntervals, $canceled);
foreach ($dates as $date) {
$this->tmpCurrentEvent->addDate($date);
2019-08-12 15:49:52 +02:00
}
2019-10-11 15:12:07 +02:00
$this->logger->info('Finished setup dates');
2019-08-12 15:49:52 +02:00
}
2019-08-12 07:43:37 +02:00
private function setOrganizer(array $addresses): void
{
foreach ($addresses as $address) {
2019-08-12 15:49:52 +02:00
if ($address['rel'] == "organizer") {
$tmpOrganizer = $this->organizerRepository->findOneByName($address['name']);
2019-08-13 11:17:34 +02:00
if ($tmpOrganizer) {
2019-08-12 15:49:52 +02:00
$this->tmpCurrentEvent->setOrganizer($tmpOrganizer);
2019-08-13 11:17:34 +02:00
continue;
2019-08-12 15:49:52 +02:00
}
$tmpOrganizer = $this->objectManager->get(Organizer::class);
2020-10-01 08:34:13 +02:00
$tmpOrganizer->setLanguageUid(-1);
$tmpOrganizer->setName($address['name'] ?? '');
$tmpOrganizer->setCity($address['city'] ?? '');
$tmpOrganizer->setZip($address['zip'] ?? '');
$tmpOrganizer->setStreet($address['street'] ?? '');
$tmpOrganizer->setPhone($address['phone'] ?? '');
$tmpOrganizer->setWeb($address['web'] ?? '');
$tmpOrganizer->setEmail($address['email'] ?? '');
$tmpOrganizer->setDistrict($address['district'] ?? '');
2019-08-13 11:17:34 +02:00
$this->organizerRepository->add($tmpOrganizer);
$this->tmpCurrentEvent->setOrganizer($tmpOrganizer);
2019-08-12 15:49:52 +02:00
}
}
}
2019-08-12 07:43:37 +02:00
2020-08-19 11:30:13 +02:00
/**
* @param array $media
*/
private function setSocial(array $media): void
{
foreach ($media as $link) {
if ($link['rel'] == "socialmedia" && $link['value'] == "Facebook") {
2020-08-19 11:30:13 +02:00
$this->tmpCurrentEvent->setFacebook($link['url']);
}
if ($link['rel'] == "socialmedia" && $link['value'] == "YouTube") {
2020-08-19 11:30:13 +02:00
$this->tmpCurrentEvent->setYouTube($link['url']);
}
if ($link['rel'] == "socialmedia" && $link['value'] == "Instagram") {
2020-08-19 11:30:13 +02:00
$this->tmpCurrentEvent->setInstagram($link['url']);
}
2020-10-01 09:45:32 +02:00
}
}
private function setTickets(array $media): void
{
foreach ($media as $link) {
if (isset($link['rel']) === false) {
continue;
}
if ($link['rel'] === 'ticket') {
2020-10-01 09:45:32 +02:00
$this->tmpCurrentEvent->setTicket($link['url']);
return;
}
if (
$link['rel'] === 'booking'
&& !$this->hasRelation('ticket', $media)
) {
2020-08-19 11:30:13 +02:00
$this->tmpCurrentEvent->setTicket($link['url']);
return;
}
if (
$link['rel'] === 'PRICE_KARTENLINK'
&& !$this->hasRelation('ticket', $media)
&& !$this->hasRelation('booking', $media)
) {
2020-10-01 09:45:32 +02:00
$this->tmpCurrentEvent->setTicket($link['url']);
return;
2020-10-01 09:45:32 +02:00
}
}
}
private function hasRelation(string $needle, array $haystack): bool
{
foreach ($haystack as $key => $value) {
if (isset($haystack['rel']) && $haystack['rel'] === $needle) {
2020-10-01 09:45:32 +02:00
return true;
}
if (is_array($value) && $this->hasRelation($needle, $value)) {
return true;
2020-10-01 09:45:32 +02:00
}
2020-08-19 11:30:13 +02:00
}
2020-10-01 09:45:32 +02:00
return false;
2020-08-19 11:30:13 +02:00
}
private function setTexts(array $texts): void
{
foreach ($texts as $text) {
if (isset($text['value']) === false) {
continue;
}
2019-08-12 15:49:52 +02:00
if ($text['rel'] == "details" && $text['type'] == "text/plain") {
2020-08-19 11:30:13 +02:00
$this->tmpCurrentEvent->setDetails(str_replace('\n\n', '\n', $text['value']));
2019-08-12 15:49:52 +02:00
}
if ($text['rel'] == "teaser" && $text['type'] == "text/plain") {
2020-08-19 11:30:13 +02:00
$this->tmpCurrentEvent->setTeaser(str_replace('\n\n', '\n', $text['value']));
2019-08-12 15:49:52 +02:00
}
2020-03-16 14:06:03 +01:00
if ($text['rel'] == "PRICE_INFO" && $text['type'] == "text/plain") {
2020-08-19 11:30:13 +02:00
$this->tmpCurrentEvent->setPriceInfo(str_replace('\n\n', '\n', $text['value']));
2020-03-16 14:06:03 +01:00
}
2019-08-12 15:49:52 +02:00
}
}
2019-08-12 07:43:37 +02:00
private function getOrCreateEvent(string $globalId, string $title): Event
{
2019-08-12 15:49:52 +02:00
$event = $this->eventRepository->findOneByGlobalId($globalId);
2019-08-12 07:43:37 +02:00
if ($event instanceof Event) {
$this->logger->info(
'Found "' . substr($title, 0, 20) . '..." with global id ' . $globalId . ' in database'
);
2019-08-13 11:17:34 +02:00
return $event;
2019-08-12 15:49:52 +02:00
}
2019-08-12 07:43:37 +02:00
2019-08-13 11:17:34 +02:00
// New event is created
$this->logger->info(substr($title, 0, 20) . ' does not exist');
$event = $this->objectManager->get(Event::class);
2019-08-13 11:17:34 +02:00
// Create event and persist
$event->setGlobalId($globalId);
$this->eventRepository->add($event);
$this->persistenceManager->persistAll();
$this->logger->info(
'Not found "' . substr($title, 0, 20) . '..." with global id ' . $globalId . ' in database.'
. ' Created new one.'
);
2019-08-12 15:49:52 +02:00
return $event;
}
2019-08-12 07:43:37 +02:00
private function setAssets(array $assets): void
{
2019-10-09 15:03:58 +02:00
$this->logger->info("Set assets");
$allowedMimeTypes = [
'image/jpeg',
'image/png',
];
$importFolder = $this->import->getFilesFolder();
2019-08-13 11:17:34 +02:00
$error = false;
foreach ($assets as $media_object) {
if (
$media_object['rel'] == "default"
&& in_array($media_object['type'], $allowedMimeTypes)
) {
$fileUrl = urldecode($media_object['url']);
$orgFileNameSanitized = $importFolder->getStorage()->sanitizeFileName(
2020-08-18 15:22:34 +02:00
basename(
urldecode($media_object['url'])
2020-08-18 14:27:44 +02:00
)
);
$this->logger->info('File attached:' . $fileUrl);
2020-08-18 14:27:44 +02:00
$this->logger->info('File attached sanitized:' . $orgFileNameSanitized);
2019-10-09 15:03:58 +02:00
if ($importFolder->hasFile($orgFileNameSanitized)) {
2019-08-13 09:12:30 +02:00
$this->logger->info('File already exists');
2019-08-12 15:49:52 +02:00
} else {
2020-08-18 14:27:44 +02:00
$this->logger->info("File don't exist " . $orgFileNameSanitized);
2019-08-12 15:49:52 +02:00
// Load the file
if ($filename = $this->loadFile($fileUrl)) {
2019-08-12 15:49:52 +02:00
// Move file to defined folder
$this->logger->info('Adding file ' . $filename);
2021-09-06 15:18:48 +02:00
$importFolder->addFile($filename, basename($fileUrl));
2019-08-12 07:43:37 +02:00
} else {
2019-08-12 15:49:52 +02:00
$error = true;
2019-08-12 07:43:37 +02:00
}
2019-08-12 15:49:52 +02:00
}
2019-08-12 07:43:37 +02:00
2019-08-12 15:49:52 +02:00
if ($error !== true) {
if ($this->tmpCurrentEvent->getImages()->count() > 0) {
2019-08-12 15:49:52 +02:00
$this->logger->info('Relation found');
// TODO: How to delete file references?
2019-08-12 15:49:52 +02:00
} else {
$this->logger->info('No relation found');
if ($importFolder->hasFile($orgFileNameSanitized) === false) {
$this->logger->warning('Could not find file.', [$orgFileNameSanitized]);
continue;
}
$file = $importFolder->getStorage()->getFileInFolder($orgFileNameSanitized, $importFolder);
if (!$file instanceof File) {
$this->logger->warning('Could not find file.', [$orgFileNameSanitized]);
continue;
}
$this->metaDataRepository->update(
$file->getUid(),
[
'title' => $this->getShortenedString($media_object['value'], 100),
'description' => $media_object['description'] ?? '',
'alternative' => 'DD Import'
]
);
$this->createFileRelations(
$file->getUid(),
'tx_events_domain_model_event',
$this->tmpCurrentEvent->getUid(),
'images',
$this->import->getStoragePid()
);
2019-08-12 07:43:37 +02:00
}
}
2019-08-12 15:49:52 +02:00
}
2019-08-13 11:17:34 +02:00
$error = false;
2019-08-12 07:43:37 +02:00
}
}
private function loadFile(string $fileUrl): string
{
$this->logger->info('Getting file ' . $fileUrl);
$file = new \SplFileInfo($fileUrl);
$temporaryFilename = GeneralUtility::tempnam($file->getBasename());
try {
$response = $this->dataFetcher->fetchImage($fileUrl);
} catch (Exception $e) {
$this->logger->error('Cannot load file ' . $fileUrl);
return '';
}
$fileContent = $response->getBody()->__toString();
if ($response->getStatusCode() !== 200) {
$this->logger->error('Cannot load file ' . $fileUrl);
}
if (GeneralUtility::writeFile($temporaryFilename, $fileContent, true) === false) {
$this->logger->error('Could not write temporary file.');
return '';
2019-08-12 07:43:37 +02:00
}
return $temporaryFilename;
2019-08-12 07:43:37 +02:00
}
private function createFileRelations(
int $uid_local,
string $tablenames,
int $uid_foreign,
string $fieldname,
int $storagePid
): bool {
2019-08-12 07:43:37 +02:00
$newId = 'NEW1234';
$data = array();
$data['sys_file_reference'][$newId] = array(
'table_local' => 'sys_file',
'uid_local' => $uid_local,
'tablenames' => $tablenames,
'uid_foreign' => $uid_foreign,
'fieldname' => $fieldname,
'pid' => $storagePid
);
$data[$tablenames][$uid_foreign] = array(
'pid' => $storagePid,
$fieldname => $newId
);
$dataHandler = $this->objectManager->get(DataHandler::class);
2019-08-12 07:43:37 +02:00
$dataHandler->start($data, array());
$dataHandler->process_datamap();
if (count($dataHandler->errorLog) === 0) {
return true;
}
2019-08-13 11:17:34 +02:00
foreach ($dataHandler->errorLog as $error) {
2019-08-13 11:17:34 +02:00
$this->logger->info($error);
}
return false;
2019-08-12 07:43:37 +02:00
}
/**
* Fetch the boolean value for requested attribute.
*
* Returns first if multiple attributes with same key exist.
* Casts "true" and "false" to true and false.
*/
private function getAttributeValue(
array $event,
string $attributeKey
): bool {
$attributes = array_filter($event['attributes'] ?? [], function (array $attribute) use ($attributeKey) {
$currentKey = $attribute['key'] ?? '';
return $currentKey === $attributeKey;
});
if ($attributes === []) {
return false;
}
$value = $attributes[0]['value'] ?? null;
if ($value === 'true') {
return true;
}
if ($value === 'false') {
return false;
}
return (bool) $value;
}
private function getShortenedString(string $string, int $lenght): string
{
if ($string === mb_substr($string, 0, $lenght)) {
return $string;
}
return mb_substr($string, 0, $lenght - 3) . ' …';
}
2019-10-09 15:03:58 +02:00
}