240 lines
8.5 KiB
PHP
240 lines
8.5 KiB
PHP
<?php
|
|
|
|
namespace App\Services\CafeBazaar;
|
|
|
|
use App\Models\MobileApp;
|
|
use Illuminate\Support\Arr;
|
|
use Illuminate\Support\Facades\Cache;
|
|
use Throwable;
|
|
|
|
class SyncCafeBazaarAppAction
|
|
{
|
|
private const MAX_RECORDS_PER_RUN = 500;
|
|
|
|
private const MAX_REVIEW_PAGES = 50;
|
|
|
|
public function __construct(
|
|
private readonly CafeBazaarClient $bazaar,
|
|
private readonly BazaarPurchaseRecorder $purchases,
|
|
private readonly BazaarSubscriptionRecorder $subscriptions,
|
|
private readonly BazaarReviewRecorder $reviews,
|
|
private readonly BazaarReleaseRecorder $releases,
|
|
) {}
|
|
|
|
/** @return array<string, mixed> */
|
|
public function execute(MobileApp $app, bool $force = false): array
|
|
{
|
|
$result = Cache::lock("cafe-bazaar-sync:{$app->getKey()}", 330)->get(
|
|
fn (): array => $this->synchronize($app->fresh(), $force),
|
|
);
|
|
|
|
return $result === false
|
|
? ['status' => 'skipped', 'reason' => 'A synchronization is already running.']
|
|
: $result;
|
|
}
|
|
|
|
/** @return array<string, mixed> */
|
|
private function synchronize(MobileApp $app, bool $force): array
|
|
{
|
|
$startedAt = now();
|
|
$summary = [
|
|
'purchases_checked' => 0,
|
|
'subscriptions_checked' => 0,
|
|
'reviews_imported' => 0,
|
|
'review_pages_checked' => 0,
|
|
'release_states_checked' => 0,
|
|
'failures' => [],
|
|
];
|
|
|
|
$app->update([
|
|
'bazaar_sync_status' => 'running',
|
|
'bazaar_sync_started_at' => $startedAt,
|
|
'bazaar_sync_error' => null,
|
|
]);
|
|
|
|
try {
|
|
if (filled($app->bazaar_api_secret)) {
|
|
$this->syncPurchases($app, $force, $summary);
|
|
$this->syncSubscriptions($app, $force, $summary);
|
|
$this->syncReleaseStates($app, $summary);
|
|
}
|
|
|
|
if (filled($app->bazaar_comments_header) && filled($app->bazaar_comments_secret)) {
|
|
$this->syncReviews($app, $force, $summary);
|
|
}
|
|
|
|
$summary['duration_ms'] = $startedAt->diffInMilliseconds(now());
|
|
$summary['status'] = $summary['failures'] === [] ? 'succeeded' : 'partial';
|
|
|
|
$app->update([
|
|
'bazaar_sync_status' => $summary['status'],
|
|
'bazaar_last_synced_at' => now(),
|
|
'bazaar_sync_error' => $this->failureMessage($summary['failures']),
|
|
'bazaar_sync_summary' => $summary,
|
|
]);
|
|
|
|
return $summary;
|
|
} catch (Throwable $exception) {
|
|
$app->update([
|
|
'bazaar_sync_status' => 'failed',
|
|
'bazaar_last_synced_at' => now(),
|
|
'bazaar_sync_error' => $exception->getMessage(),
|
|
'bazaar_sync_summary' => [...$summary, 'status' => 'failed'],
|
|
]);
|
|
|
|
throw $exception;
|
|
}
|
|
}
|
|
|
|
/** @param array<string, mixed> $summary */
|
|
private function syncPurchases(MobileApp $app, bool $force, array &$summary): void
|
|
{
|
|
$query = $app->bazaarPurchases()->oldest('id');
|
|
|
|
if (! $force) {
|
|
$query->where(fn ($query) => $query
|
|
->whereNull('validated_at')
|
|
->orWhere('validated_at', '<=', now()->subDay()));
|
|
}
|
|
|
|
foreach ($query->limit(self::MAX_RECORDS_PER_RUN)->get() as $purchase) {
|
|
$response = $this->bazaar->validatePurchase($app, $purchase->product_id, $purchase->purchase_token);
|
|
$summary['purchases_checked']++;
|
|
|
|
if ($response->successful()) {
|
|
$this->purchases->record($app, $purchase->product_id, $purchase->purchase_token, $response);
|
|
} else {
|
|
$this->addFailure($summary, 'purchase', $purchase->id, $response);
|
|
}
|
|
}
|
|
}
|
|
|
|
/** @param array<string, mixed> $summary */
|
|
private function syncSubscriptions(MobileApp $app, bool $force, array &$summary): void
|
|
{
|
|
$query = $app->bazaarSubscriptions()->oldest('id');
|
|
|
|
if (! $force) {
|
|
$query->where(fn ($query) => $query
|
|
->whereNull('validated_at')
|
|
->orWhere('validated_at', '<=', now()->subMinutes($app->bazaar_sync_interval_minutes)));
|
|
}
|
|
|
|
foreach ($query->limit(self::MAX_RECORDS_PER_RUN)->get() as $subscription) {
|
|
$response = $this->bazaar->subscription($app, $subscription->subscription_id, $subscription->purchase_token);
|
|
$summary['subscriptions_checked']++;
|
|
|
|
if ($response->successful()) {
|
|
$this->subscriptions->record($app, $subscription->subscription_id, $subscription->purchase_token, $response);
|
|
} else {
|
|
$this->addFailure($summary, 'subscription', $subscription->id, $response);
|
|
}
|
|
}
|
|
}
|
|
|
|
/** @param array<string, mixed> $summary */
|
|
private function syncReviews(MobileApp $app, bool $force, array &$summary): void
|
|
{
|
|
$filters = [];
|
|
$continuationCursor = $force ? null : Arr::get($app->bazaar_sync_summary, 'reviews_next_cursor');
|
|
$continuationAfter = $force ? null : Arr::get($app->bazaar_sync_summary, 'reviews_filter_after');
|
|
|
|
if (is_string($continuationCursor) && $continuationCursor !== '') {
|
|
$filters['cursor'] = $continuationCursor;
|
|
|
|
if (is_string($continuationAfter) && $continuationAfter !== '') {
|
|
$filters['publish_date_after'] = $continuationAfter;
|
|
}
|
|
} elseif (! $force && ($latestPublishedAt = $app->bazaarReviews()->max('published_at')) !== null) {
|
|
$filters['publish_date_after'] = now()->parse($latestPublishedAt)->subDay()->toIso8601String();
|
|
}
|
|
|
|
$summary['reviews_filter_after'] = $filters['publish_date_after'] ?? null;
|
|
|
|
for ($page = 1; $page <= self::MAX_REVIEW_PAGES; $page++) {
|
|
$summary['reviews_next_cursor'] = $filters['cursor'] ?? null;
|
|
$response = $this->bazaar->reviews($app, $filters);
|
|
$summary['review_pages_checked']++;
|
|
|
|
if (! $response->successful()) {
|
|
$this->addFailure($summary, 'reviews', $page, $response);
|
|
|
|
return;
|
|
}
|
|
|
|
$results = Arr::get($response->body, 'results', []);
|
|
$this->reviews->recordPage($app, $response);
|
|
$summary['reviews_imported'] += is_array($results) ? count($results) : 0;
|
|
|
|
$cursor = $this->nextCursor(Arr::get($response->body, 'next'));
|
|
|
|
if ($cursor === null) {
|
|
$summary['reviews_next_cursor'] = null;
|
|
|
|
return;
|
|
}
|
|
|
|
$filters['cursor'] = $cursor;
|
|
$summary['reviews_next_cursor'] = $cursor;
|
|
}
|
|
}
|
|
|
|
/** @param array<string, mixed> $summary */
|
|
private function syncReleaseStates(MobileApp $app, array &$summary): void
|
|
{
|
|
foreach (['uncommitted', 'committed', 'published'] as $state) {
|
|
$response = $this->bazaar->lastRelease($app, $state);
|
|
$summary['release_states_checked']++;
|
|
|
|
if ($response->successful()) {
|
|
$this->releases->record($app, $state, $response);
|
|
} elseif ($response->status !== 404) {
|
|
$this->addFailure($summary, 'release_'.$state, null, $response);
|
|
}
|
|
}
|
|
}
|
|
|
|
private function nextCursor(mixed $next): ?string
|
|
{
|
|
if (! is_string($next) || $next === '') {
|
|
return null;
|
|
}
|
|
|
|
$query = parse_url($next, PHP_URL_QUERY);
|
|
|
|
if (! is_string($query)) {
|
|
return null;
|
|
}
|
|
|
|
parse_str($query, $parameters);
|
|
$cursor = $parameters['cursor'] ?? null;
|
|
|
|
return is_string($cursor) && $cursor !== '' ? $cursor : null;
|
|
}
|
|
|
|
/** @param array<string, mixed> $summary */
|
|
private function addFailure(array &$summary, string $operation, int|string|null $record, BazaarResponse $response): void
|
|
{
|
|
if (count($summary['failures']) >= 25) {
|
|
return;
|
|
}
|
|
|
|
$summary['failures'][] = array_filter([
|
|
'operation' => $operation,
|
|
'record' => $record,
|
|
'status' => $response->status,
|
|
'message' => Arr::get($response->body, 'error_description', Arr::get($response->body, 'error')),
|
|
], fn (mixed $value): bool => $value !== null);
|
|
}
|
|
|
|
/** @param array<int, array<string, mixed>> $failures */
|
|
private function failureMessage(array $failures): ?string
|
|
{
|
|
if ($failures === []) {
|
|
return null;
|
|
}
|
|
|
|
return count($failures).' Bazaar operation(s) failed. See the synchronization summary and API request log.';
|
|
}
|
|
}
|