init
This commit is contained in:
232 files changed
+25416
No files matched your search
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\CafeBazaar;
|
||||
|
||||
use App\Models\BazaarPurchase;
|
||||
use App\Models\MobileApp;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Support\Arr;
|
||||
|
||||
class BazaarPurchaseRecorder
|
||||
{
|
||||
public function record(MobileApp $app, string $productId, string $purchaseToken, BazaarResponse $response): ?BazaarPurchase
|
||||
{
|
||||
if (! $response->successful()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$purchaseState = (int) Arr::get($response->body, 'purchaseState', 0);
|
||||
$purchaseTime = Arr::get($response->body, 'purchaseTime');
|
||||
|
||||
return BazaarPurchase::updateOrCreate(
|
||||
['mobile_app_id' => $app->id, 'purchase_token_hash' => hash('sha256', $purchaseToken)],
|
||||
[
|
||||
'purchase_token' => $purchaseToken,
|
||||
'product_id' => $productId,
|
||||
'status' => $purchaseState === 1 ? 'refunded' : 'purchased',
|
||||
'is_consumed' => (int) Arr::get($response->body, 'consumptionState', 1) === 0,
|
||||
'purchased_at' => is_numeric($purchaseTime) ? CarbonImmutable::createFromTimestampMs((int) $purchaseTime) : null,
|
||||
'validated_at' => now(),
|
||||
'bazaar_response' => $response->body,
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\CafeBazaar;
|
||||
|
||||
use App\Models\BazaarRelease;
|
||||
use App\Models\MobileApp;
|
||||
use Illuminate\Support\Arr;
|
||||
|
||||
class BazaarReleaseRecorder
|
||||
{
|
||||
public function record(MobileApp $app, string $status, BazaarResponse $response, array $attributes = []): ?BazaarRelease
|
||||
{
|
||||
if (! $response->successful()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$release = BazaarRelease::query()
|
||||
->whereBelongsTo($app)
|
||||
->latest()
|
||||
->first();
|
||||
|
||||
$release ??= new BazaarRelease(['mobile_app_id' => $app->id]);
|
||||
$release->fill([
|
||||
...$attributes,
|
||||
'bazaar_release_id' => Arr::get($response->body, 'release.id', $release->bazaar_release_id),
|
||||
'status' => $status,
|
||||
'bazaar_response' => $response->body,
|
||||
]);
|
||||
$release->save();
|
||||
|
||||
return $release;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\CafeBazaar;
|
||||
|
||||
use Illuminate\Http\JsonResponse;
|
||||
|
||||
class BazaarResponse
|
||||
{
|
||||
public function __construct(
|
||||
public readonly int $status,
|
||||
public readonly array $body,
|
||||
) {}
|
||||
|
||||
public function successful(): bool
|
||||
{
|
||||
return $this->status >= 200 && $this->status < 300;
|
||||
}
|
||||
|
||||
public function toJsonResponse(): JsonResponse
|
||||
{
|
||||
return response()->json([
|
||||
'data' => $this->successful() ? $this->body : null,
|
||||
'error' => $this->successful() ? null : $this->body,
|
||||
'meta' => ['bazaar_status' => $this->status],
|
||||
], $this->status);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\CafeBazaar;
|
||||
|
||||
use App\Models\BazaarReview;
|
||||
use App\Models\MobileApp;
|
||||
use Illuminate\Support\Arr;
|
||||
|
||||
class BazaarReviewRecorder
|
||||
{
|
||||
public function recordPage(MobileApp $app, BazaarResponse $response): void
|
||||
{
|
||||
if (! $response->successful()) {
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (Arr::get($response->body, 'results', []) as $review) {
|
||||
BazaarReview::updateOrCreate(
|
||||
['mobile_app_id' => $app->id, 'bazaar_review_id' => $review['id']],
|
||||
[
|
||||
'user_account_id' => Arr::get($review, 'user_account_id'),
|
||||
'rate' => Arr::get($review, 'rate'),
|
||||
'text' => Arr::get($review, 'text'),
|
||||
'app_version_code' => Arr::get($review, 'app_version_code'),
|
||||
'is_edited' => Arr::get($review, 'is_edited', false),
|
||||
'published_at' => Arr::get($review, 'publish_date'),
|
||||
'developer_reply_text' => Arr::get($review, 'developer_reply.text'),
|
||||
'developer_reply_email' => Arr::get($review, 'developer_reply.email'),
|
||||
'developer_replied_at' => Arr::get($review, 'developer_reply.publish_date'),
|
||||
'bazaar_response' => $review,
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
public function recordReply(MobileApp $app, int $reviewId, BazaarResponse $response): void
|
||||
{
|
||||
if (! $response->successful()) {
|
||||
return;
|
||||
}
|
||||
|
||||
BazaarReview::query()
|
||||
->whereBelongsTo($app)
|
||||
->where('bazaar_review_id', $reviewId)
|
||||
->update([
|
||||
'developer_reply_text' => Arr::get($response->body, 'text'),
|
||||
'developer_reply_email' => Arr::get($response->body, 'email'),
|
||||
'developer_replied_at' => now(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\CafeBazaar;
|
||||
|
||||
class BazaarSignatureVerifier
|
||||
{
|
||||
public function verify(string $publicKey, string $originalJson, string $signature): bool
|
||||
{
|
||||
$pem = str_contains($publicKey, 'BEGIN PUBLIC KEY')
|
||||
? $publicKey
|
||||
: "-----BEGIN PUBLIC KEY-----\n".chunk_split(preg_replace('/\s+/', '', $publicKey) ?? '', 64, "\n")."-----END PUBLIC KEY-----\n";
|
||||
|
||||
$key = openssl_pkey_get_public($pem);
|
||||
$decodedSignature = base64_decode($signature, true);
|
||||
|
||||
if ($key === false || $decodedSignature === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return openssl_verify($originalJson, $decodedSignature, $key, OPENSSL_ALGO_SHA1) === 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\CafeBazaar;
|
||||
|
||||
use App\Models\BazaarSubscription;
|
||||
use App\Models\MobileApp;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Support\Arr;
|
||||
|
||||
class BazaarSubscriptionRecorder
|
||||
{
|
||||
public function record(MobileApp $app, string $subscriptionId, string $purchaseToken, BazaarResponse $response): ?BazaarSubscription
|
||||
{
|
||||
if (! $response->successful()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$startsAt = CarbonImmutable::createFromTimestampMs((int) Arr::get($response->body, 'initiationTimestampMsec'));
|
||||
$validUntil = CarbonImmutable::createFromTimestampMs((int) Arr::get($response->body, 'validUntilTimestampMsec'));
|
||||
|
||||
return BazaarSubscription::updateOrCreate(
|
||||
['mobile_app_id' => $app->id, 'purchase_token_hash' => hash('sha256', $purchaseToken)],
|
||||
[
|
||||
'purchase_token' => $purchaseToken,
|
||||
'subscription_id' => $subscriptionId,
|
||||
'linked_subscription_token' => Arr::get($response->body, 'linkedSubscriptionToken'),
|
||||
'status' => $validUntil->isFuture() ? 'active' : 'expired',
|
||||
'auto_renewing' => (bool) Arr::get($response->body, 'autoRenewing', false),
|
||||
'starts_at' => $startsAt,
|
||||
'valid_until' => $validUntil,
|
||||
'validated_at' => now(),
|
||||
'bazaar_response' => $response->body,
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\CafeBazaar;
|
||||
|
||||
use App\Models\BazaarApiRequest;
|
||||
use App\Models\MobileApp;
|
||||
use Illuminate\Http\Client\ConnectionException;
|
||||
use Illuminate\Http\Client\PendingRequest;
|
||||
use Illuminate\Http\Client\Response;
|
||||
use Illuminate\Http\UploadedFile;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Str;
|
||||
use InvalidArgumentException;
|
||||
use Throwable;
|
||||
|
||||
class CafeBazaarClient
|
||||
{
|
||||
private const BILLING_BASE_URL = 'https://pardakht.cafebazaar.ir/devapi/v2/api';
|
||||
|
||||
private const PISHKHAN_BASE_URL = 'https://api.pishkhan.cafebazaar.ir/v1/apps/releases';
|
||||
|
||||
private const COMMENTS_BASE_URL = 'https://sandoghche.cafebazaar.ir/api/v0/reviews';
|
||||
|
||||
private const ACCOUNT_BASE_URL = 'https://account.cafebazaar.ir/api/v0';
|
||||
|
||||
public function validatePurchase(MobileApp $app, string $productId, string $purchaseToken): BazaarResponse
|
||||
{
|
||||
return $this->send($app, 'purchase.validate', 'GET', self::BILLING_BASE_URL.'/validate/'.$this->path($app->package_name).'/inapp/'.$this->path($productId).'/purchases/'.$this->path($purchaseToken).'/', request: $this->bazaarApiRequest($app));
|
||||
}
|
||||
|
||||
public function consumePurchase(MobileApp $app, string $purchaseToken): BazaarResponse
|
||||
{
|
||||
return $this->send($app, 'purchase.consume', 'POST', self::BILLING_BASE_URL.'/consume/'.$this->path($app->package_name).'/purchases/', ['token' => $purchaseToken], $this->bazaarApiRequest($app));
|
||||
}
|
||||
|
||||
public function refundPurchase(MobileApp $app, string $purchaseToken): BazaarResponse
|
||||
{
|
||||
return $this->send($app, 'purchase.refund', 'POST', self::BILLING_BASE_URL.'/refund/'.$this->path($app->package_name).'/purchases/'.$this->path($purchaseToken).'/', request: $this->bazaarApiRequest($app));
|
||||
}
|
||||
|
||||
public function subscription(MobileApp $app, string $subscriptionId, string $purchaseToken): BazaarResponse
|
||||
{
|
||||
return $this->send($app, 'subscription.show', 'GET', self::BILLING_BASE_URL.'/applications/'.$this->path($app->package_name).'/subscriptions/'.$this->path($subscriptionId).'/purchases/'.$this->path($purchaseToken).'/', request: $this->bazaarApiRequest($app));
|
||||
}
|
||||
|
||||
public function activeSubscriptions(MobileApp $app, string $purchaseToken): BazaarResponse
|
||||
{
|
||||
return $this->send($app, 'subscription.active', 'GET', self::BILLING_BASE_URL.'/applications/'.$this->path($app->package_name).'/active-subscriptions/'.$this->path($purchaseToken).'/', request: $this->bazaarApiRequest($app));
|
||||
}
|
||||
|
||||
public function cancelSubscription(MobileApp $app, string $subscriptionId, string $purchaseToken): BazaarResponse
|
||||
{
|
||||
return $this->send($app, 'subscription.cancel', 'POST', self::BILLING_BASE_URL.'/applications/'.$this->path($app->package_name).'/subscriptions/'.$this->path($subscriptionId).'/purchases/'.$this->path($purchaseToken).'/cancel/', request: $this->bazaarApiRequest($app));
|
||||
}
|
||||
|
||||
public function exchangeLoginCode(MobileApp $app, string $code): BazaarResponse
|
||||
{
|
||||
return $this->send($app, 'login.exchange', 'POST', self::ACCOUNT_BASE_URL.'/tokens', [
|
||||
'grant_type' => 'authorization_code',
|
||||
'code' => $code,
|
||||
'client_id' => $app->bazaar_login_client_id,
|
||||
'client_secret' => $app->bazaar_login_client_secret,
|
||||
], $this->request()->asForm());
|
||||
}
|
||||
|
||||
public function refreshLoginToken(MobileApp $app, string $refreshToken): BazaarResponse
|
||||
{
|
||||
return $this->send($app, 'login.refresh', 'POST', self::ACCOUNT_BASE_URL.'/tokens/refresh', [
|
||||
'grant_type' => 'refresh_token',
|
||||
'refresh_token' => $refreshToken,
|
||||
], $this->request()->asForm());
|
||||
}
|
||||
|
||||
public function userInfo(MobileApp $app, string $accessToken, string $tokenType = 'Bearer'): BazaarResponse
|
||||
{
|
||||
return $this->send($app, 'login.userinfo', 'GET', self::ACCOUNT_BASE_URL.'/userinfo', request: $this->request()->withToken($accessToken, $tokenType));
|
||||
}
|
||||
|
||||
public function reviews(MobileApp $app, array $filters): BazaarResponse
|
||||
{
|
||||
return $this->send($app, 'reviews.list', 'GET', self::COMMENTS_BASE_URL.'/', $filters, $this->commentsRequest($app));
|
||||
}
|
||||
|
||||
public function replyToReview(MobileApp $app, int $reviewId, array $reply): BazaarResponse
|
||||
{
|
||||
return $this->send($app, 'reviews.reply', 'POST', self::COMMENTS_BASE_URL.'/'.$reviewId.'/', $reply, $this->commentsRequest($app));
|
||||
}
|
||||
|
||||
public function createRelease(MobileApp $app): BazaarResponse
|
||||
{
|
||||
return $this->pishkhan($app, 'release.create', 'POST', '/');
|
||||
}
|
||||
|
||||
public function deleteRelease(MobileApp $app): BazaarResponse
|
||||
{
|
||||
return $this->pishkhan($app, 'release.delete', 'DELETE', '/');
|
||||
}
|
||||
|
||||
public function uploadApk(MobileApp $app, UploadedFile $apk, string $architecture): BazaarResponse
|
||||
{
|
||||
$request = $this->pishkhanRequest($app)
|
||||
->attach('apk', $apk->getContent(), $apk->hashName(), ['Content-Type' => 'application/vnd.android.package-archive']);
|
||||
|
||||
return $this->send($app, 'release.upload_apk', 'POST', self::PISHKHAN_BASE_URL.'/upload/', ['architecture' => $architecture], $request);
|
||||
}
|
||||
|
||||
public function uploadAab(MobileApp $app, UploadedFile $aab): BazaarResponse
|
||||
{
|
||||
$request = $this->pishkhanRequest($app)->attach('aab', $aab->getContent(), $aab->hashName());
|
||||
|
||||
return $this->send($app, 'release.upload_aab', 'POST', self::PISHKHAN_BASE_URL.'/upload-aab/', request: $request);
|
||||
}
|
||||
|
||||
public function uploadBin(MobileApp $app, UploadedFile $bin): BazaarResponse
|
||||
{
|
||||
$request = $this->pishkhanRequest($app)->attach('file', $bin->getContent(), $bin->hashName());
|
||||
|
||||
return $this->send($app, 'release.upload_bin', 'POST', self::PISHKHAN_BASE_URL.'/upload-bin/', request: $request);
|
||||
}
|
||||
|
||||
public function bundleStatus(MobileApp $app): BazaarResponse
|
||||
{
|
||||
return $this->pishkhan($app, 'release.bundle_status', 'GET', '/bundle-status/');
|
||||
}
|
||||
|
||||
public function commitRelease(MobileApp $app, array $data): BazaarResponse
|
||||
{
|
||||
return $this->pishkhan($app, 'release.commit', 'POST', '/commit/', $data);
|
||||
}
|
||||
|
||||
public function lastRelease(MobileApp $app, string $state): BazaarResponse
|
||||
{
|
||||
return $this->pishkhan($app, 'release.last_'.$state, 'GET', '/last-'.$state.'/');
|
||||
}
|
||||
|
||||
private function pishkhan(MobileApp $app, string $operation, string $method, string $path, array $data = []): BazaarResponse
|
||||
{
|
||||
return $this->send($app, $operation, $method, self::PISHKHAN_BASE_URL.$path, $data, $this->pishkhanRequest($app));
|
||||
}
|
||||
|
||||
private function bazaarApiRequest(MobileApp $app): PendingRequest
|
||||
{
|
||||
return $this->request()->withHeaders(['CAFEBAZAAR-PISHKHAN-API-SECRET' => $app->bazaar_api_secret]);
|
||||
}
|
||||
|
||||
private function pishkhanRequest(MobileApp $app): PendingRequest
|
||||
{
|
||||
return $this->bazaarApiRequest($app);
|
||||
}
|
||||
|
||||
private function commentsRequest(MobileApp $app): PendingRequest
|
||||
{
|
||||
return $this->request()->withHeaders([$app->bazaar_comments_header => $app->bazaar_comments_secret]);
|
||||
}
|
||||
|
||||
private function request(): PendingRequest
|
||||
{
|
||||
return Http::acceptJson()->connectTimeout(5)->timeout(20)->retry([100, 300], throw: false);
|
||||
}
|
||||
|
||||
private function send(MobileApp $app, string $operation, string $method, string $url, array $data = [], ?PendingRequest $request = null): BazaarResponse
|
||||
{
|
||||
$startedAt = hrtime(true);
|
||||
$request ??= $this->request();
|
||||
|
||||
try {
|
||||
$response = $this->dispatch($request, $method, $url, $data);
|
||||
$body = $this->responseBody($response);
|
||||
$this->logRequest($app, $operation, $method, $url, $response->status(), $response->successful(), $startedAt, $data, $body);
|
||||
|
||||
return new BazaarResponse($response->status(), $body);
|
||||
} catch (ConnectionException $exception) {
|
||||
$body = ['error' => 'bazaar_unavailable', 'error_description' => 'Cafe Bazaar could not be reached.'];
|
||||
$this->logRequest($app, $operation, $method, $url, 502, false, $startedAt, $data, $body, $exception);
|
||||
|
||||
return new BazaarResponse(502, $body);
|
||||
}
|
||||
}
|
||||
|
||||
private function dispatch(PendingRequest $request, string $method, string $url, array $data): Response
|
||||
{
|
||||
return match ($method) {
|
||||
'GET' => $request->get($url, $data),
|
||||
'POST' => $request->post($url, $data),
|
||||
'DELETE' => $request->delete($url, $data),
|
||||
default => throw new InvalidArgumentException("Unsupported Bazaar method [{$method}]."),
|
||||
};
|
||||
}
|
||||
|
||||
private function responseBody(Response $response): array
|
||||
{
|
||||
$body = $response->json();
|
||||
|
||||
return is_array($body) ? $body : ['raw' => Str::limit($response->body(), 2000)];
|
||||
}
|
||||
|
||||
private function logRequest(MobileApp $app, string $operation, string $method, string $url, int $statusCode, bool $successful, int $startedAt, array $requestMetadata, array $responseBody, ?Throwable $exception = null): void
|
||||
{
|
||||
BazaarApiRequest::create([
|
||||
'mobile_app_id' => $app->id,
|
||||
'operation' => $operation,
|
||||
'method' => $method,
|
||||
'url' => $this->redactUrl($url),
|
||||
'status_code' => $statusCode,
|
||||
'successful' => $successful,
|
||||
'duration_ms' => (int) ((hrtime(true) - $startedAt) / 1_000_000),
|
||||
'request_metadata' => $this->redact($requestMetadata),
|
||||
'response_body' => $this->redact($responseBody),
|
||||
'error_message' => $exception?->getMessage(),
|
||||
]);
|
||||
}
|
||||
|
||||
private function redact(array $data): array
|
||||
{
|
||||
return collect($data)->mapWithKeys(function (mixed $value, string|int $key): array {
|
||||
if (is_string($key) && Str::contains(Str::lower($key), ['token', 'secret', 'code'])) {
|
||||
return [$key => '[REDACTED]'];
|
||||
}
|
||||
|
||||
return [$key => is_array($value) ? $this->redact($value) : $value];
|
||||
})->all();
|
||||
}
|
||||
|
||||
private function redactUrl(string $url): string
|
||||
{
|
||||
return preg_replace('#/(purchases|active-subscriptions)/[^/]+#', '/$1/[REDACTED]', $url) ?? $url;
|
||||
}
|
||||
|
||||
private function path(string $value): string
|
||||
{
|
||||
return rawurlencode($value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
<?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.';
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user