Skip to content

Commit

Permalink
Fixes for kobo sync and proxy
Browse files Browse the repository at this point in the history
  • Loading branch information
SergioMendolia committed Nov 28, 2024
1 parent 91503aa commit 9cf0189
Show file tree
Hide file tree
Showing 6 changed files with 43 additions and 11 deletions.
9 changes: 8 additions & 1 deletion src/Controller/Kobo/KoboInitializationController.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,15 @@ public function initialization(Request $request, KoboDevice $kobo): Response
$jsonData['Resources']['image_url_template'] = $base.'/image/{ImageId}/{width}/{height}/{Quality}/isGreyscale/image.jpg';
$jsonData['Resources']['image_url_quality_template'] = $base.'/{ImageId}/{width}/{height}/false/image.jpg';

foreach ($jsonData['Resources'] as $key => $url) {
if (!is_string($url)) {
continue;
}
$jsonData['Resources'][$key] = str_replace('https://storeapi.kobo.com', $base, $url);
}

// Reading services
$jsonData['Resources']['reading_services_host'] = rtrim($this->generateUrl('app_dashboard', [], UrlGenerator::ABSOLUTE_URL), '/');
$jsonData['Resources']['reading_services_host'] = str_replace('https://', '', rtrim($this->generateUrl('app_dashboard', [], UrlGenerator::ABSOLUTE_URL), '/'));

$response = new JsonResponse($jsonData);
$response->headers->set('kobo-api-token', 'e30=');
Expand Down
7 changes: 5 additions & 2 deletions src/Controller/Kobo/KoboSyncController.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use App\Kobo\Response\SyncResponseFactory;
use App\Kobo\SyncToken;
use App\Repository\BookRepository;
use App\Repository\KoboDeviceRepository;
use App\Repository\KoboSyncedBookRepository;
use App\Repository\ShelfRepository;
use App\Service\KoboSyncTokenExtractor;
Expand All @@ -31,8 +32,9 @@ public function __construct(
protected KoboSyncedBookRepository $koboSyncedBookRepository,
protected ShelfRepository $shelfRepository,
protected LoggerInterface $logger,
protected SyncResponseFactory $syncResponseFactory)
{
protected KoboDeviceRepository $koboDeviceRepository,
protected SyncResponseFactory $syncResponseFactory,
) {
}

/**
Expand All @@ -55,6 +57,7 @@ public function apiEndpoint(KoboDevice $kobo, SyncToken $syncToken, Request $req
$this->logger->debug('Force sync for Kobo {id}', ['id' => $kobo->getId()]);
$this->koboSyncedBookRepository->deleteAllSyncedBooks($kobo);
$kobo->setForceSync(false);
$this->koboDeviceRepository->save($kobo);
$syncToken->currentDate = new \DateTime('now');
}
$this->logger->debug('First sync for Kobo {id}', ['id' => $kobo->getId()]);
Expand Down
2 changes: 1 addition & 1 deletion src/EventSubscriber/KoboRequestSubscriber.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public function onKernelResponse(ResponseEvent $event): void
$content = $event->getResponse()->getContent();
}

$this->koboLogger->info('Response from '.$event->getRequest()->getPathInfo(), ['response' => $content, 'headers' => $event->getResponse()->headers->all()]);
$this->koboLogger->info('Response given '.$event->getRequest()->getPathInfo(), ['response' => $content, 'headers' => $event->getResponse()->headers->all()]);
}

public function onKernelController(ControllerEvent $event): void
Expand Down
19 changes: 18 additions & 1 deletion src/Kobo/Proxy/KoboProxyLogger.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,27 @@ protected function onFailure(RequestInterface $request): \Closure

private function log(RequestInterface $request, ?ResponseInterface $response = null, ?\Throwable $error = null): void
{
$this->logger->info(sprintf('Proxied: %s', (string) $request->getUri()), [
try {
$requestContent = json_decode($request->getBody()->getContents(), true, 512, JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
$requestContent = $request->getBody()->getContents();
}
$responseContent = $response?->getBody()->getContents();
if ($responseContent !== null) {
try {
$responseContent = json_decode($responseContent, true, 512, JSON_THROW_ON_ERROR);
} catch (\JsonException) {
}
}

$this->logger->info(sprintf($request->getMethod().': %s', (string) $request->getUri()), [
'method' => $request->getMethod(),
'status' => $response?->getStatusCode(),
'token_hash' => md5($this->accessToken),
'request' => $requestContent,
'response' => $responseContent,
'request_headers' => $request->getHeaders(),
'response_headers' => $response?->getHeaders(),
]);

if ($error instanceof \Throwable) {
Expand Down
6 changes: 3 additions & 3 deletions src/Kobo/Response/ReadingStateResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public function __construct(
}

/**
* @return array<string, mixed>
* @return array<int,array<string, mixed>>
*/
public function createReadingState(): array
{
Expand All @@ -31,7 +31,7 @@ public function createReadingState(): array

$lastModified = $this->syncToken->maxLastModified($book->getUpdated(), $this->syncToken->currentDate, $book->getLastInteraction($this->kobo->getUser())?->getUpdated());

return [
return [[
'EntitlementId' => $uuid,
'Created' => $this->syncToken->maxLastCreated($book->getCreated(), $this->syncToken->currentDate, $book->getLastInteraction($this->kobo->getUser())?->getCreated()),
'LastModified' => $lastModified,
Expand All @@ -48,7 +48,7 @@ public function createReadingState(): array

// "Statistics"=> get_statistics_response(kobo_reading_state.statistics),
'CurrentBookmark' => $this->createBookmark($this->kobo->getUser()->getBookmarkForBook($book)),
];
]];
}

/**
Expand Down
11 changes: 8 additions & 3 deletions src/Kobo/Response/SyncResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
/**
* @phpstan-type BookEntitlement array<string, mixed>
* @phpstan-type BookMetadata array<string, mixed>
* @phpstan-type BookReadingState array<string, mixed>
* @phpstan-type BookReadingState array<int,array<string, mixed>>
* @phpstan-type BookTag array<string, mixed>
*/
class SyncResponse
Expand Down Expand Up @@ -217,10 +217,13 @@ private function createBookTagFromShelf(Shelf $shelf): array

private function createBookEntitlement(Book $book): array
{
$rs = $this->createReadingState($book);
$rs = reset($rs);

return [
'BookEntitlement' => $this->createEntitlement($book),
'BookMetadata' => $this->metadataResponse->fromBook($book, $this->kobo, $this->syncToken),
'ReadingState' => $this->createReadingState($book),
'ReadingState' => $rs,
];
}

Expand All @@ -235,7 +238,9 @@ private function getChangedReadingState(): array

return array_map(function (Book $book) {
$response = new \stdClass();
$response->ChangedReadingState = $this->createReadingState($book);
$rs = $this->createReadingState($book);
$rs = reset($rs);
$response->ChangedReadingState = $rs;

return $response;
}, $books);
Expand Down

0 comments on commit 9cf0189

Please sign in to comment.