2FAuth/app/Services/ReleaseRadarService.php

88 lines
2.4 KiB
PHP
Raw Normal View History

2022-09-21 21:50:41 +02:00
<?php
namespace App\Services;
use App\Facades\Settings;
use App\Helpers\Helpers;
2022-09-21 21:50:41 +02:00
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
class ReleaseRadarService
{
/**
* Run a scheduled release scan
2022-11-22 15:15:52 +01:00
*
* @return void
2022-09-21 21:50:41 +02:00
*/
public static function scheduledScan() : void
2022-09-21 21:50:41 +02:00
{
2022-12-09 10:52:17 +01:00
if ((Settings::get('lastRadarScan') + (60 * 60 * 24 * 7)) < time()) {
self::newRelease();
}
}
/**
* Run a manual release scan
2022-11-22 15:15:52 +01:00
*
* @return false|string False if no new release, the new release number otherwise
*/
public static function manualScan() : false|string
{
return self::newRelease();
}
/**
* Run a release scan
2022-11-22 15:15:52 +01:00
*
* @return false|string False if no new release, the new release number otherwise
*/
protected static function newRelease() : false|string
{
Log::info('Release scan started');
if ($latestReleaseData = json_decode(self::getLatestReleaseData())) {
2022-11-22 15:15:52 +01:00
$githubVersion = Helpers::cleanVersionNumber($latestReleaseData->tag_name);
$installedVersion = Helpers::cleanVersionNumber(config('2fauth.version'));
2022-12-09 10:52:17 +01:00
if ($githubVersion && $installedVersion) {
if (version_compare($githubVersion, $installedVersion) > 0 && $latestReleaseData->prerelease == false && $latestReleaseData->draft == false) {
2022-12-09 10:52:17 +01:00
Settings::set('latestRelease', $latestReleaseData->tag_name);
2022-11-22 15:15:52 +01:00
Log::info(sprintf('New release found: %s', var_export($latestReleaseData->tag_name, true)));
2022-12-09 10:52:17 +01:00
return $latestReleaseData->tag_name;
} else {
Settings::delete('latestRelease');
}
2022-09-21 21:50:41 +02:00
}
}
2022-09-21 21:50:41 +02:00
return false;
2022-09-21 21:50:41 +02:00
}
/**
* Fetch releases on Github
2022-11-22 15:15:52 +01:00
*
2022-09-21 21:50:41 +02:00
* @return string|null
*/
protected static function getLatestReleaseData() : string|null
2022-09-21 21:50:41 +02:00
{
$url = config('2fauth.latestReleaseUrl');
2022-09-21 21:50:41 +02:00
try {
$response = Http::retry(3, 100)
->get($url);
2022-11-22 15:15:52 +01:00
2022-09-21 21:50:41 +02:00
if ($response->successful()) {
2022-12-09 10:52:17 +01:00
Settings::set('lastRadarScan', time());
2022-09-21 21:50:41 +02:00
return $response->body();
}
2022-11-22 15:15:52 +01:00
} catch (\Exception $exception) {
Log::error(sprintf('cannot reach %s endpoint', var_export($url, true)));
2022-09-21 21:50:41 +02:00
}
return null;
}
2022-11-22 15:15:52 +01:00
}