Skip to content

Commit

Permalink
[WIP] intercept errors when API connection fails, logging, messages
Browse files Browse the repository at this point in the history
  • Loading branch information
pixelmatseriks committed Nov 20, 2023
1 parent d20ec87 commit 1bfc656
Show file tree
Hide file tree
Showing 12 changed files with 176 additions and 22 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -117,12 +117,12 @@ jobs:
run: |
composer require --no-progress typo3/minimal:"$TYPO3"
composer show
- if: "matrix.composer-dependencies == 'lowest'"
- if: matrix.composer-dependencies == 'lowest'
name: "Install lowest dependencies with composer"
run: |
composer update --no-ansi --no-interaction --no-progress --with-dependencies --prefer-lowest
composer show
- if: "matrix.composer-dependencies == 'highest'"
- if: matrix.composer-dependencies == 'highest'
name: "Install highest dependencies with composer"
run: |
composer update --no-ansi --no-interaction --no-progress --with-dependencies
Expand Down
9 changes: 9 additions & 0 deletions Classes/Command/UpdateQbankFileStatusCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,15 @@ protected function execute(InputInterface $input, OutputInterface $output)

continue;
}
} catch (\Throwable $th) {
$io->writeln(
sprintf(
'QBank file [%s] was not found: "%s"',
$file['tx_qbank_id'],
$th->getMessage()
)
);
break;
}

$remoteUpdate = (int)$media->getUpdated()->getTimestamp();
Expand Down
31 changes: 29 additions & 2 deletions Classes/Controller/ManagementController.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
use TYPO3\CMS\Core\Imaging\Icon;
use TYPO3\CMS\Core\Imaging\IconFactory;
use TYPO3\CMS\Core\Localization\LanguageService;
use TYPO3\CMS\Core\Log\LogManager;
use TYPO3\CMS\Core\Messaging\AbstractMessage;
use TYPO3\CMS\Core\Page\JavaScriptModuleInstruction;
use TYPO3\CMS\Core\Page\PageRenderer;
Expand Down Expand Up @@ -90,7 +91,24 @@ public function initializeAction(): void
*/
protected function initializeView(): void
{
$apiStatus = [];
try {
$checkStatus = $this->qbankService->fetchMediaProperties();
} catch (\Throwable $th) {
$apiStatus = [
'errorMessage' => $th->getMessage(),
'errorCode' => $th->getCode(),
];
$logger = GeneralUtility::makeInstance(LogManager::class)->getLogger(__CLASS__);
$logger->error(
sprintf(
'Failed to connect to QBank API: "%s"',
$th->getMessage()
)
);
}
$this->moduleTemplate->assignMultiple([
'apiStatus' => $apiStatus,
'dateFormat' => $GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'],
'timeFormat' => $GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'],
'dateTimeFormat' =>
Expand Down Expand Up @@ -192,7 +210,11 @@ protected function overviewAction(): ResponseInterface
{
$this->generateDropdownMenu('overview');
$this->generateButtons('overview');
$properties = $this->qbankService->fetchMediaProperties();
try {
$properties = $this->qbankService->fetchMediaProperties();
} catch (\Throwable $th) {
$properties = [];
}
$this->moduleTemplate->assign('properties', $properties);
return $this->moduleTemplate->renderResponse('Management/Overview');
}
Expand All @@ -206,9 +228,14 @@ protected function mappingsAction(): ResponseInterface
$this->generateButtons('mappings');
$mappingRepository = GeneralUtility::makeInstance(MappingRepository::class);
$mappings = $mappingRepository->findAll();
try {
$mediaProperties = $this->qbankService->fetchMediaProperties();
} catch (\Throwable $th) {
$mediaProperties = [];
}
$this->moduleTemplate->assignMultiple([
'mappings' => $mappings,
'mediaProperties' => $this->qbankService->fetchMediaProperties(),
'mediaProperties' => $mediaProperties,
'fileProperties' => PropertyUtility::getFileProperties(),
]);
return $this->moduleTemplate->renderResponse('Management/Mappings');
Expand Down
56 changes: 40 additions & 16 deletions Classes/Hook/MediaUsageReporterDataHandlerHook.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
namespace Pixelant\Qbank\Hook;

use Pixelant\Qbank\Service\QbankService;
use Pixelant\Qbank\Utility\MessageUtility;
use TYPO3\CMS\Core\DataHandling\DataHandler;
use TYPO3\CMS\Core\Type\ContextualFeedbackSeverity;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\MathUtility;

Expand All @@ -26,9 +28,20 @@ public function processDatamap_afterAllOperations(DataHandler $dataHandler): voi
foreach ($dataHandler->datamap['sys_file_reference'] ?? [] as $id => $record) {
// Only process new records
if (!MathUtility::canBeInterpretedAsInteger($id)) {
GeneralUtility::makeInstance(QbankService::class)->reportMediaUsageInFileReference(
$dataHandler->substNEWwithIDs[$id]
);
try {
GeneralUtility::makeInstance(QbankService::class)->reportMediaUsageInFileReference(
$dataHandler->substNEWwithIDs[$id]
);
} catch (\Throwable $th) {
MessageUtility::enqueueMessage(
sprintf(
'Media usage was not reported to QBank: "%s"',
$th->getMessage()
),
'Connection to QBank API failed',
ContextualFeedbackSeverity::ERROR
);
}
}
}
}
Expand All @@ -52,22 +65,33 @@ public function processCmdmap_preProcess(
DataHandler $dataHandler
): void {
if ($table === 'sys_file_reference') {
switch ($command) {
case 'move':
/** @var QbankService $qbankService */
$qbankService = GeneralUtility::makeInstance(QbankService::class);
$qbankService->removeMediaUsageInFileReference($id);
$qbankService->reportMediaUsageInFileReference($id);
try {
switch ($command) {
case 'move':
/** @var QbankService $qbankService */
$qbankService = GeneralUtility::makeInstance(QbankService::class);
$qbankService->removeMediaUsageInFileReference($id);
$qbankService->reportMediaUsageInFileReference($id);

break;
case 'delete':
GeneralUtility::makeInstance(QbankService::class)->removeMediaUsageInFileReference($id);
break;
case 'delete':
GeneralUtility::makeInstance(QbankService::class)->removeMediaUsageInFileReference($id);

break;
case 'undelete':
GeneralUtility::makeInstance(QbankService::class)->reportMediaUsageInFileReference($id);
break;
case 'undelete':
GeneralUtility::makeInstance(QbankService::class)->reportMediaUsageInFileReference($id);

break;
break;
}
} catch (\Throwable $th) {
MessageUtility::enqueueMessage(
sprintf(
'Media usage was not reported to QBank: "%s"',
$th->getMessage()
),
'Connection to QBank API failed',
ContextualFeedbackSeverity::ERROR
);
}
}
}
Expand Down
14 changes: 13 additions & 1 deletion Classes/Repository/AbstractRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@

use Pixelant\Qbank\Utility\QbankUtility;
use QBNK\QBank\API\QBankApi;
use TYPO3\CMS\Core\Log\LogManager;
use TYPO3\CMS\Core\SingletonInterface;
use TYPO3\CMS\Core\Utility\GeneralUtility;

class AbstractRepository implements SingletonInterface
{
Expand All @@ -17,6 +19,16 @@ class AbstractRepository implements SingletonInterface

public function __construct()
{
$this->api = QbankUtility::getApi();
try {
$this->api = QbankUtility::getApi();
} catch (\Throwable $th) {
$logger = GeneralUtility::makeInstance(LogManager::class)->getLogger(__CLASS__);
$logger->error(
sprintf(
'Failed to connect to QBank API: "%s"',
$th->getMessage()
)
);
}
}
}
13 changes: 13 additions & 0 deletions Classes/Service/QbankService.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
use Pixelant\Qbank\Service\Event\FilePropertyChangeEvent;
use Pixelant\Qbank\Service\Event\FileReferenceUrlEvent;
use Pixelant\Qbank\Service\Event\ResolvePageTitleEvent;
use Pixelant\Qbank\Utility\MessageUtility;
use Pixelant\Qbank\Utility\PropertyUtility;
use Pixelant\Qbank\Utility\QbankUtility;
use QBNK\QBank\API\Exception\RequestException;
Expand All @@ -37,6 +38,7 @@
use TYPO3\CMS\Core\Resource\ResourceFactory;
use TYPO3\CMS\Core\SingletonInterface;
use TYPO3\CMS\Core\Site\SiteFinder;
use TYPO3\CMS\Core\Type\ContextualFeedbackSeverity;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\StringUtility;

Expand Down Expand Up @@ -252,6 +254,17 @@ public function synchronizeMetadata(int $fileId): void
1625149218
);
}
} catch (\Throwable $th) {
MessageUtility::enqueueMessage(
sprintf(
'Could not synchronize metadata for file [%s]: "%s"',
$fileId,
$th->getMessage()
),
'QBank',
ContextualFeedbackSeverity::ERROR
);
return;
}

$metaDataMappings = GeneralUtility::makeInstance(MappingRepository::class)->findAllAsKeyValuePairs(false);
Expand Down
46 changes: 46 additions & 0 deletions Classes/Utility/MessageUtility.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php

declare(strict_types=1);

namespace Pixelant\Qbank\Utility;

use TYPO3\CMS\Core\Context\Context;
use TYPO3\CMS\Core\Log\LogManager;
use TYPO3\CMS\Core\Messaging\FlashMessage;
use TYPO3\CMS\Core\Messaging\FlashMessageQueue;
use TYPO3\CMS\Core\Messaging\FlashMessageService;
use TYPO3\CMS\Core\Type\ContextualFeedbackSeverity;
use TYPO3\CMS\Core\Utility\GeneralUtility;

/**
* Convenience methods relating to TYPO3 messaging.
*/
class MessageUtility
{
public static function enqueueMessage(
string $message,
string $title = '',
ContextualFeedbackSeverity $severity = ContextualFeedbackSeverity::OK
): void {
$context = GeneralUtility::makeInstance(Context::class);
$beUserId = $context->getPropertyFromAspect('backend.user', 'id');

if ($beUserId > 0) {
$flashMessageService = GeneralUtility::makeInstance(FlashMessageService::class);
$notificationQueue = $flashMessageService->getMessageQueueByIdentifier(
FlashMessageQueue::NOTIFICATION_QUEUE
);
$flashMessage = GeneralUtility::makeInstance(
FlashMessage::class,
$message,
$title,
$severity,
true
);
$notificationQueue->enqueue($flashMessage);
}

$logger = GeneralUtility::makeInstance(LogManager::class)->getLogger(__CLASS__);
$logger->error($message . PHP_EOL . $title);
}
}
3 changes: 3 additions & 0 deletions Resources/Private/Language/locallang_mod_qbank.xlf
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@
<trans-unit id="target_property">
<source>TYPO3 property</source>
</trans-unit>
<trans-unit id="api_error">
<source>Connection to QBank API failed</source>
</trans-unit>
</body>
</file>
</xliff>
10 changes: 10 additions & 0 deletions Resources/Private/Partials/ApiStatus.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<f:if condition="{apiStatus -> f:count()}">
<div role="alert" class="alert alert-danger alert-dismissible">
<div class="media">
<div class="media-body">
<h4 class="alert-title">{f:translate(key: 'LLL:EXT:qbank/Resources/Private/Language/locallang_mod_qbank.xlf:api_error')}</h4>
<p class="alert-message">{apiStatus.errorMessage}</p>
</div>
</div>
</div>
</f:if>
2 changes: 2 additions & 0 deletions Resources/Private/Templates/Management/List.html
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
<h1><f:translate key="be.list.title" /></h1>
<p><f:translate key="be.list.description" /></p>

<f:render partial="ApiStatus" arguments="{apiStatus: apiStatus}" />

<f:if condition="{qbankFiles -> f:count()}">
<f:render section="table" arguments="{_all}" />
</f:if>
Expand Down
8 changes: 7 additions & 1 deletion Resources/Private/Templates/Management/Mappings.html
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@
<f:section name="Content">
<h1><f:translate key="be.mappings.title" /></h1>
<p><f:translate key="be.mappings.description" /></p>

<f:render partial="ApiStatus" arguments="{apiStatus: apiStatus}" />

<f:if condition="{mappings -> f:count()}">
<f:render section="table" arguments="{_all}" />
</f:if>
Expand All @@ -31,7 +34,10 @@ <h1><f:translate key="be.mappings.title" /></h1>
<f:for each="{mappings}" as="mapping">
<tr>
<td>
<f:translate key="{mediaProperties.{mapping.source_property}.label}" default="{mediaProperties.{mapping.source_property}.label}"/>
<f:if condition="{mediaProperties.{mapping.source_property}.label}">
<f:then><f:translate key="{mediaProperties.{mapping.source_property}.label}" default="{mediaProperties.{mapping.source_property}.label}"/></f:then>
<f:else>({mapping.source_property})</f:else>
</f:if>
</td>
<td>
<f:alias map="{
Expand Down
2 changes: 2 additions & 0 deletions Resources/Private/Templates/Management/Overview.html
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
<h1><f:translate key="be.overview.title" /></h1>
<p><f:translate key="be.overview.description" /></p>

<f:render partial="ApiStatus" arguments="{apiStatus: apiStatus}" />

<f:if condition="{propertyTypes}">
<f:for each="{propertyTypes}" as="propertyType" iteration="i">
<p>{propertyType.name} - [{propertyType.systemName}] - {propertyType.description} - {propertyType.dataTypeId}</p>
Expand Down

0 comments on commit 1bfc656

Please sign in to comment.