Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 56 additions & 4 deletions app/Enum/WebserviceEndpoint.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,62 @@

namespace App\Enum;

use App\RemoteSite\Responses\FinalizeUpdate;
use App\RemoteSite\Responses\GetUpdate;
use App\RemoteSite\Responses\HealthCheck;
use App\RemoteSite\Responses\PrepareUpdate;

enum WebserviceEndpoint: string
{
case HEALTH_CHECK = "/api/index.php/v1/joomlaupdate/healthcheck";
case FETCH_UPDATES = "/api/index.php/v1/joomlaupdate/fetchUpdate";
case PREPARE_UPDATE = "/api/index.php/v1/joomlaupdate/prepareUpdate";
case FINALIZE_UPDATE = "/api/index.php/v1/joomlaupdate/finalizeUpdate";
case checkHealth = "/api/index.php/v1/joomlaupdate/healthcheck";
case getUpdate = "/api/index.php/v1/joomlaupdate/getUpdate";
case prepareUpdate = "/api/index.php/v1/joomlaupdate/prepareUpdate";
case finalizeUpdate = "/api/index.php/v1/joomlaupdate/finalizeUpdate";

public function getMethod(): HttpMethod
{
switch ($this->name) {
case self::checkHealth->name:
case self::getUpdate->name:
return HttpMethod::GET;

// no break
case self::prepareUpdate->name:
case self::finalizeUpdate->name:
return HttpMethod::POST;
}

throw new \ValueError("No method defined");
}

public function getResponseClass(): string
{
switch ($this->name) {
case self::checkHealth->name:
return HealthCheck::class;
case self::getUpdate->name:
return GetUpdate::class;
case self::prepareUpdate->name:
return PrepareUpdate::class;
case self::finalizeUpdate->name:
return FinalizeUpdate::class;
}
}

public function getUrl(): string
{
return $this->value;
}

public static function tryFromName(string $name): ?static
{
$reflection = new \ReflectionEnum(static::class);

if (!$reflection->hasCase($name)) {
return null;
}

/** @var static */
return $reflection->getCase($name)->getValue();
}
}
91 changes: 91 additions & 0 deletions app/Jobs/UpdateSite.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,16 @@

use App\Models\Site;
use App\RemoteSite\Connection;
use App\RemoteSite\Responses\PrepareUpdate;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Log;

class UpdateSite implements ShouldQueue
{
use Queueable;
protected int $preUpdateCode;

/**
* Create a new job instance.
Expand All @@ -30,5 +34,92 @@ public function handle(): void

// Test connection and get current version
$healthResult = $connection->checkHealth();

// Check the version
if (version_compare($healthResult->cms_version, $this->targetVersion, ">=")) {
Log::info("Site is already up to date: " . $this->site->id);

return;
}

// Store pre-update response code
$this->preUpdateCode = $this->site->getFrontendStatus();

// Let site fetch available updates
$updateResult = $connection->getUpdate();

// Check if update is found and return if not
if (is_null($updateResult->availableUpdate)) {
Log::info("No update available for site: " . $this->site->id);

return;
}

// Check the version and return if it does not match
if ($updateResult->availableUpdate !== $this->targetVersion) {
Log::info("Update version mismatch for site: " . $this->site->id);

return;
}

$prepareResult = $connection->prepareUpdate($this->targetVersion);

// Perform the actual extraction
$this->performExtraction($prepareResult);

// Run the postupdate steps
if (!$connection->finalizeUpdate()->success) {
throw new \Exception("Update for site failed in postprocessing: " . $this->site->id);
}

// Compare codes
if ($this->site->getFrontendStatus() !== $this->preUpdateCode) {
throw new \Exception("Status code has changed after update for site: " . $this->site->id);
}
}

protected function performExtraction(PrepareUpdate $prepareResult): void
{
/** Create a separate connection with the extraction password **/
$connection = App::makeWith(Connection::class, [
"baseUrl" => $this->site->url,
"key" => $prepareResult->password
]);

// Ping server
$pingResult = $connection->performExtractionRequest(["task" => "ping"]);

if (empty($pingResult["message"]) || $pingResult["message"] === 'Invalid login') {
throw new \Exception(
"Invalid ping response for site: " . $this->site->id
);
}

// Start extraction
$stepResult = $connection->performExtractionRequest(["task" => "startExtract"]);

// Run actual core update
while (array_key_exists("done", $stepResult) && $stepResult["done"] !== true) {
if ($stepResult["status"] !== true) {
throw new \Exception(
"Invalid extract response for site: " . $this->site->id
);
}

// Make next extraction step
$stepResult = $connection->performExtractionRequest(
[
"task" => "stepExtract",
"instance" => $stepResult["instance"]
]
);
}

// Clean up restore
$connection->performExtractionRequest(
[
"task" => "finalizeUpdate"
]
);
}
}
10 changes: 10 additions & 0 deletions app/Models/Site.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
namespace App\Models;

use App\RemoteSite\Connection;
use GuzzleHttp\Client;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\App;

class Site extends Model
{
Expand Down Expand Up @@ -45,4 +47,12 @@ public function getConnectionAttribute(): Connection
{
return new Connection($this->url, $this->key);
}

public function getFrontendStatus(): int
{
/** @var Client $httpClient */
$httpClient = App::make(Client::class);

return $httpClient->get($this->url)->getStatusCode();
}
}
38 changes: 29 additions & 9 deletions app/RemoteSite/Connection.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,35 +6,55 @@

use App\Enum\HttpMethod;
use App\Enum\WebserviceEndpoint;
use App\RemoteSite\Responses\FinalizeUpdate as FinalizeUpdateResponse;
use App\RemoteSite\Responses\HealthCheck as HealthCheckResponse;
use App\RemoteSite\Responses\GetUpdate as GetUpdateResponse;
use App\RemoteSite\Responses\PrepareUpdate as PrepareUpdateResponse;
use App\RemoteSite\Responses\ResponseInterface;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use Illuminate\Support\Facades\App;
use Psr\Http\Message\RequestInterface;

/**
* @method HealthCheckResponse checkHealth()
* @method GetUpdateResponse getUpdate()
* @method PrepareUpdateResponse prepareUpdate(string $targetVersion)
* @method FinalizeUpdateResponse finalizeUpdate()
*/
class Connection
{
public function __construct(protected readonly string $baseUrl, protected readonly string $key)
{
}

public function checkHealth(): HealthCheckResponse
public function __call(string $method, array $arguments): ResponseInterface
{
$healthData = $this->performWebserviceRequest(
HttpMethod::GET,
WebserviceEndpoint::HEALTH_CHECK
$endpoint = WebserviceEndpoint::tryFromName($method);

if (is_null($endpoint)) {
throw new \BadMethodCallException();
}

// Call
$data = $this->performWebserviceRequest(
$endpoint->getMethod(),
$endpoint->getUrl(),
...$arguments
);

return HealthCheckResponse::from($healthData['data']['attributes']);
$responseClass = $endpoint->getResponseClass();

return $responseClass::from($data);
}

public function performExtractionRequest(array $requestData): array
{
$request = new Request(
'POST',
$this->baseUrl . 'extract.php'
$this->baseUrl . '/extract.php'
);

$data['password'] = $this->key;
Expand All @@ -55,12 +75,12 @@ public function performExtractionRequest(array $requestData): array

protected function performWebserviceRequest(
HttpMethod $method,
WebserviceEndpoint $endpoint,
string $endpoint,
array $requestData = []
): array {
$request = new Request(
$method->name,
$this->baseUrl . $endpoint->value,
$this->baseUrl . $endpoint,
[
'X-JUpdate-Token' => $this->key
]
Expand All @@ -85,7 +105,7 @@ protected function performWebserviceRequest(
);
}

return $responseData;
return $responseData['data']['attributes'];
}

protected function performHttpRequest(
Expand Down
13 changes: 13 additions & 0 deletions app/RemoteSite/Responses/FinalizeUpdate.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

namespace App\RemoteSite\Responses;

use App\DTO\BaseDTO;

class FinalizeUpdate extends BaseDTO implements ResponseInterface
{
public function __construct(
public bool $success
) {
}
}
13 changes: 13 additions & 0 deletions app/RemoteSite/Responses/GetUpdate.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

namespace App\RemoteSite\Responses;

use App\DTO\BaseDTO;

class GetUpdate extends BaseDTO implements ResponseInterface
{
public function __construct(
public ?string $availableUpdate
) {
}
}
2 changes: 1 addition & 1 deletion app/RemoteSite/Responses/HealthCheck.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

use App\DTO\BaseDTO;

class HealthCheck extends BaseDTO
class HealthCheck extends BaseDTO implements ResponseInterface
{
public function __construct(
public string $php_version,
Expand Down
14 changes: 14 additions & 0 deletions app/RemoteSite/Responses/PrepareUpdate.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

namespace App\RemoteSite\Responses;

use App\DTO\BaseDTO;

class PrepareUpdate extends BaseDTO implements ResponseInterface
{
public function __construct(
public string $password,
public int $filesize
) {
}
}
10 changes: 10 additions & 0 deletions app/RemoteSite/Responses/ResponseInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

namespace App\RemoteSite\Responses;

interface ResponseInterface
{
public static function from(array $data): static;

public function toArray(): array;
}
5 changes: 4 additions & 1 deletion pint.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
{
"preset": "psr12"
"preset": "psr12",
"notName": [
"WebserviceEndpoint.php"
]
}
16 changes: 0 additions & 16 deletions tests/Unit/ExampleTest.php

This file was deleted.

Loading
Loading