repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Migration/Migration1.php | src/Migration/Migration1.php | <?php
namespace App\Migration;
use App\Enum\NamingConvention;
use App\Enum\Setting;
use PDO;
final class Migration1 implements Migration
{
public function migrate(PDO $pdo): void
{
$pdo->exec('create table settings (id integer primary key autoincrement, setting text, value text)');
$pdo->prepare("insert into settings (setting, value) values (?, ?)")->execute([
Setting::NamingConvention->value,
json_encode(NamingConvention::GogSlug->value),
]);
}
public function getVersion(): int
{
return 1;
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Migration/Migration5.php | src/Migration/Migration5.php | <?php
namespace App\Migration;
use PDO;
final readonly class Migration5 implements Migration
{
public function migrate(PDO $pdo): void
{
$pdo->exec('alter table downloads add column gog_game_id integer default null');
}
public function getVersion(): int
{
return 5;
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Migration/Migration.php | src/Migration/Migration.php | <?php
namespace App\Migration;
use PDO;
interface Migration
{
public function migrate(PDO $pdo): void;
public function getVersion(): int;
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Migration/Migration0.php | src/Migration/Migration0.php | <?php
namespace App\Migration;
use PDO;
final class Migration0 implements Migration
{
public function migrate(PDO $pdo): void
{
$pdo->exec('create table migrations (id integer primary key autoincrement, version int, created text)');
$pdo->exec('create table auth (id integer primary key autoincrement, token text, refreshToken text, validUntil text)');
$pdo->exec('create table games (id integer primary key autoincrement, serializedData text)');
}
public function getVersion(): int
{
return 0;
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Migration/Migration2.php | src/Migration/Migration2.php | <?php
namespace App\Migration;
use PDO;
final readonly class Migration2 implements Migration
{
public function migrate(PDO $pdo): void
{
$pdo->exec('create table compressed_file_hashes (compressed string, uncompressed string, UNIQUE(compressed, uncompressed))');
}
public function getVersion(): int
{
return 2;
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Migration/Migration7.php | src/Migration/Migration7.php | <?php
namespace App\Migration;
use PDO;
final readonly class Migration7 implements Migration
{
public function migrate(PDO $pdo): void
{
$pdo->exec("alter table game_extras add md5 text");
}
public function getVersion(): int
{
return 7;
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Migration/Migration8.php | src/Migration/Migration8.php | <?php
namespace App\Migration;
use PDO;
final readonly class Migration8 implements Migration
{
public function migrate(PDO $pdo): void
{
$pdo->exec("alter table downloads add is_patch boolean default false");
}
public function getVersion(): int
{
return 8;
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Migration/Migration4.php | src/Migration/Migration4.php | <?php
namespace App\Migration;
use App\Enum\NamingConvention;
use App\Enum\Setting;
use PDO;
final readonly class Migration4 implements Migration
{
public function migrate(PDO $pdo): void
{
$pdo->exec('alter table games add column slug text default null');
// delete duplicate settings
$pdo->exec('delete from settings where id in (select max(id) from settings group by setting having count(setting) > 1)');
$pdo->exec("alter table settings rename to old_settings");
$pdo->exec('create table settings (id integer primary key autoincrement, setting text, value text, constraint setting_name unique (setting))');
$pdo->exec('insert into settings (setting, value) select setting, value from old_settings');
$pdo->exec('drop table old_settings');
// A new default value has been retroactively added to Migration1.
// The original naming convention is being set here if there isn't one.
// This effectively means that all new installations have the new value while everyone who used the app before
// has the original one.
$pdo->prepare('insert into settings (setting, value) values (?, ?) on conflict(setting) do nothing')->execute([
Setting::NamingConvention->value,
json_encode(NamingConvention::Custom->value),
]);
}
public function getVersion(): int
{
return 4;
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Migration/Migration3.php | src/Migration/Migration3.php | <?php
namespace App\Migration;
use App\DTO\GameDetail;
use PDO;
final readonly class Migration3 implements Migration
{
public function migrate(PDO $pdo): void
{
$originalRows = $pdo->query('select * from games')->fetchAll(PDO::FETCH_ASSOC);
/** @var array<GameDetail> $games */
$games = array_map(
fn (array $row) => unserialize($row['serializedData']),
$originalRows,
);
$pdo->exec('drop table games');
$pdo->exec('create table games (id integer primary key autoincrement, title string, cd_key string, game_id integer, unique (game_id))');
$pdo->exec('create table downloads (
id integer primary key autoincrement,
language string,
platform string,
name string,
size float,
url string,
md5 string,
game_id integer,
foreign key (game_id) references games(id) on delete cascade on update cascade
)');
foreach ($games as $game) {
$pdo->prepare('insert into games (game_id, title, cd_key) values (?, ?, ?)')->execute([
$game->id,
$game->title,
$game->cdKey ?: null,
]);
$rowId = $pdo->lastInsertId();
foreach ($game->downloads as $download) {
$pdo->prepare('insert into downloads (language, platform, name, size, url, md5, game_id) values (?, ?, ?, ?, ?, ?, ?)')->execute([
$download->language,
$download->platform,
$download->name,
$download->size,
$download->url,
$download->md5,
$rowId,
]);
}
}
}
public function getVersion(): int
{
return 3;
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Migration/Migration6.php | src/Migration/Migration6.php | <?php
namespace App\Migration;
use PDO;
final readonly class Migration6 implements Migration
{
public function migrate(PDO $pdo): void
{
$pdo->exec('create table game_extras (
id integer primary key autoincrement,
extra_id integer unique,
name text,
size integer,
url text,
gog_game_id integer,
game_id integer,
foreign key (game_id) references games(id) on delete cascade on update cascade
)');
}
public function getVersion(): int
{
return 6;
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Enum/SizeUnit.php | src/Enum/SizeUnit.php | <?php
namespace App\Enum;
enum SizeUnit: string
{
case Bytes = 'b';
case Kilobytes = 'kb';
case Megabytes = 'mb';
case Gigabytes = 'gb';
case Terabytes = 'tb';
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Enum/S3StorageClass.php | src/Enum/S3StorageClass.php | <?php
namespace App\Enum;
enum S3StorageClass: string
{
case Standard = 'STANDARD';
case ReducedRedundancy = 'REDUCED_REDUNDANCY';
case StandardInfrequentAccess = 'STANDARD_IA';
case OneZoneInfrequentAccess = 'ONEZONE_IA';
case IntelligentTiering = 'INTELLIGENT_TIERING';
case Glacier = 'GLACIER';
case DeepArchive = 'DEEP_ARCHIVE';
case Outposts = 'OUTPOSTS';
case GlacierInstantRetrieval = 'GLACIER_IR';
case SnowballEdge = 'SNOW';
case ExpressOneZone = 'EXPRESS_ONEZONE';
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Enum/MediaType.php | src/Enum/MediaType.php | <?php
namespace App\Enum;
enum MediaType: int
{
case Game = 1;
case Movie = 2;
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Enum/NamingConvention.php | src/Enum/NamingConvention.php | <?php
namespace App\Enum;
enum NamingConvention: string
{
case Custom = 'custom';
case GogSlug = 'gog-slug';
case RomManager = 'rom-manager';
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Enum/Language.php | src/Enum/Language.php | <?php
namespace App\Enum;
enum Language: string
{
case English = 'en';
case Bulgarian = 'bl';
case Russian = 'ru';
case Arabic = 'ar';
case BrazilianPortuguese = 'br';
case Japanese = 'jp';
case Korean = 'ko';
case French = 'fr';
case Chinese = 'cn';
case Czech = 'cz';
case Hungarian = 'hu';
case Portuguese = 'pt';
case Turkish = 'tr';
case Dutch = 'nl';
case Romanian = 'ro';
case Spanish = 'es';
case Polish = 'pl';
case Italian = 'it';
case German = 'de';
case Danish = 'da';
case Swedish = 'sv';
case Finnish = 'fi';
case Norwegian = 'no';
case MexicanSpanish = 'es_mx';
case Icelandic = 'is';
case Ukrainian = 'uk';
case Thai = 'th';
case SimplifiedChinese = 'zh';
public function getLocalName(): string
{
return match ($this) {
self::English => 'English',
self::Bulgarian => 'български',
self::Russian => 'русский',
self::Arabic => 'العربية',
self::BrazilianPortuguese => 'Português do Brasil',
self::Japanese => '日本語',
self::Korean => '한국어',
self::French => 'français',
self::Chinese => '中文(简体)',
self::Czech => 'český',
self::Hungarian => 'magyar',
self::Portuguese => 'português',
self::Turkish => 'Türkçe',
self::Dutch => 'nederlands',
self::Romanian => 'română',
self::Spanish => 'español',
self::Polish => 'polski',
self::Italian => 'italiano',
self::German => 'Deutsch',
self::Danish => 'Dansk',
self::Swedish => 'svenska',
self::Finnish => 'suomi',
self::Norwegian => 'norsk',
self::MexicanSpanish => 'Español (AL)',
self::Icelandic => 'Íslenska',
self::Ukrainian => 'yкраїнська',
self::Thai => 'ไทย',
self::SimplifiedChinese => '中文(繁體)',
};
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Enum/OperatingSystemNumber.php | src/Enum/OperatingSystemNumber.php | <?php
namespace App\Enum;
enum OperatingSystemNumber: int
{
case WindowsXP = 2 ** 0;
case WindowsVista = 2 ** 1;
case Windows7 = 2 ** 2;
case Windows8 = 2 ** 3;
case Windows10 = 2 ** 12;
case Windows11 = 2 ** 14;
case OsX10_6 = 2 ** 4;
case OsX10_7 = 2 ** 5;
case Ubuntu14 = 2 ** 10;
case Ubuntu16 = 2 ** 11;
case Ubuntu18 = 2 ** 13;
case Ubuntu20 = 2 ** 15;
case Ubuntu22 = 2 ** 16;
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Enum/Setting.php | src/Enum/Setting.php | <?php
namespace App\Enum;
use BackedEnum;
use UnitEnum;
enum Setting: string
{
case DownloadPath = 'download-path';
case S3StorageClass = 's3-storage-class';
case NamingConvention = 'naming-convention';
/**
* @return callable(string): bool
*/
public function getValidator(): callable
{
/**
* @param class-string<BackedEnum> $enumClass
*/
$enum = fn (string $enumClass) => fn (string $value) => $enumClass::tryFrom($value) !== null;
return match ($this) {
self::S3StorageClass => $enum(S3StorageClass::class),
self::NamingConvention => $enum(NamingConvention::class),
default => fn () => true,
};
}
/**
* @return array<string>|(callable(): array<string>)|null
*/
public function getValidValues(): array|null|callable
{
/**
* @param class-string<BackedEnum> $enumClass
*/
$enum = fn (string $enumClass) => fn () => array_map(fn (object $class) => $class->value, $enumClass::cases());
return match ($this) {
self::S3StorageClass => $enum(S3StorageClass::class),
self::NamingConvention => $enum(NamingConvention::class),
default => null,
};
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Enum/OperatingSystem.php | src/Enum/OperatingSystem.php | <?php
namespace App\Enum;
enum OperatingSystem: string
{
case Windows = 'windows';
case MacOS = 'mac';
case Linux = 'linux';
public function getAsNumbers(): string
{
$cases = match ($this) {
self::MacOS => [OperatingSystemNumber::OsX10_6, OperatingSystemNumber::OsX10_7],
self::Windows => [
OperatingSystemNumber::WindowsXP,
OperatingSystemNumber::WindowsVista,
OperatingSystemNumber::Windows7,
OperatingSystemNumber::Windows8,
OperatingSystemNumber::Windows10,
OperatingSystemNumber::Windows11,
],
self::Linux => [
OperatingSystemNumber::Ubuntu14,
OperatingSystemNumber::Ubuntu16,
OperatingSystemNumber::Ubuntu18,
OperatingSystemNumber::Ubuntu20,
OperatingSystemNumber::Ubuntu22,
],
};
return implode(',', array_map(fn (OperatingSystemNumber $number) => $number->value, $cases));
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/DependencyInjection/EventCoordinatorCompilerPass.php | src/DependencyInjection/EventCoordinatorCompilerPass.php | <?php
namespace App\DependencyInjection;
use Symfony\Component\Console\Application;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
final readonly class EventCoordinatorCompilerPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
$application = $container->getDefinition(Application::class);
$application->addMethodCall('setDispatcher', [new Reference('event_dispatcher')]);
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/DependencyInjection/CommandLocatorCompilerPass.php | src/DependencyInjection/CommandLocatorCompilerPass.php | <?php
namespace App\DependencyInjection;
use App\Interfaces\SingleCommandInterface;
use function call_user_func;
use function is_a;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
final class CommandLocatorCompilerPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
$application = $container->getDefinition(Application::class);
foreach ($container->getDefinitions() as $name => $definition) {
if (
is_a($definition->getClass(), Command::class, true)
&& !$definition->isAbstract()
&& str_starts_with($definition->getClass(), 'App\\')
) {
$application->addMethodCall('add', [new Reference($name)]);
if (is_a($definition->getClass(), SingleCommandInterface::class, true)) {
$this->setDefaultCommand($definition, $application);
}
}
}
}
private function setDefaultCommand(Definition $definition, Definition $application)
{
$class = $definition->getClass();
$commandName = call_user_func([$class, 'getCommandName']);
$application->addMethodCall('setDefaultCommand', [$commandName, true]);
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Exception/InvalidValueException.php | src/Exception/InvalidValueException.php | <?php
namespace App\Exception;
use Exception;
final class InvalidValueException extends Exception
{
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Exception/UnreadableFileException.php | src/Exception/UnreadableFileException.php | <?php
namespace App\Exception;
use Exception;
final class UnreadableFileException extends Exception
{
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Exception/RetryDownloadForUnmatchingHashException.php | src/Exception/RetryDownloadForUnmatchingHashException.php | <?php
namespace App\Exception;
use RuntimeException;
final class RetryDownloadForUnmatchingHashException extends RuntimeException implements RetryAwareException
{
public function modifyTryNumber(int $tryNumber): int
{
return $tryNumber - 1;
}
public function modifyDelay(int $delay): int
{
return $delay;
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Exception/ExitException.php | src/Exception/ExitException.php | <?php
namespace App\Exception;
use RuntimeException;
use Throwable;
final class ExitException extends RuntimeException
{
public function __construct(string $message = '', int $code = 1, ?Throwable $previous = null)
{
parent::__construct($message, $code, $previous);
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Exception/RetryAwareException.php | src/Exception/RetryAwareException.php | <?php
namespace App\Exception;
interface RetryAwareException
{
public function modifyTryNumber(int $tryNumber): int;
public function modifyDelay(int $delay): int;
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Exception/ForceRetryException.php | src/Exception/ForceRetryException.php | <?php
namespace App\Exception;
use RuntimeException;
final class ForceRetryException extends RuntimeException implements RetryAwareException
{
public function modifyTryNumber(int $tryNumber): int
{
return $tryNumber - 1;
}
public function modifyDelay(int $delay): int
{
return 0;
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Exception/TooManyRetriesException.php | src/Exception/TooManyRetriesException.php | <?php
namespace App\Exception;
use Exception;
use Throwable;
final class TooManyRetriesException extends Exception
{
/**
* @var array<Throwable>
*/
public readonly array $exceptions;
public function __construct(array $exceptions, string $message = "", int $code = 0, ?Throwable $previous = null)
{
parent::__construct($message, $code, $previous);
$this->exceptions = $exceptions;
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Exception/InvalidConfigurationException.php | src/Exception/InvalidConfigurationException.php | <?php
namespace App\Exception;
use RuntimeException;
final class InvalidConfigurationException extends RuntimeException
{
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Exception/AuthorizationException.php | src/Exception/AuthorizationException.php | <?php
namespace App\Exception;
use RuntimeException;
final class AuthorizationException extends RuntimeException
{
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Exception/AuthenticationException.php | src/Exception/AuthenticationException.php | <?php
namespace App\Exception;
use RuntimeException;
final class AuthenticationException extends RuntimeException
{
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Trait/TargetDirectoryTrait.php | src/Trait/TargetDirectoryTrait.php | <?php
namespace App\Trait;
use App\DTO\DownloadableItem;
use App\DTO\GameDetail;
use App\DTO\PlatformSpecificItem;
use App\Enum\NamingConvention;
use App\Enum\OperatingSystem;
use App\Enum\Setting;
use App\Exception\InvalidValueException;
use LogicException;
use Symfony\Component\Console\Input\InputInterface;
trait TargetDirectoryTrait
{
private function getTargetDir(InputInterface $input, GameDetail $game, ?DownloadableItem $download = null, ?string $subdirectory = null, ?NamingConvention $namingScheme = null): string
{
$dir = $input->getArgument('directory')
?? $_ENV['DOWNLOAD_DIRECTORY']
?? $this->persistence->getSetting(Setting::DownloadPath)
?? getcwd()
;
if (PHP_OS_FAMILY === 'Windows') {
if (!preg_match('/^[a-zA-Z]:\\\\/', $dir)) {
$dir = getcwd() . '/' . $dir;
}
} else {
if (!str_starts_with($dir, '/') && !preg_match('@^[0-9a-zA-Z.]+://.+$@', $dir)) {
$dir = getcwd() . '/' . $dir;
}
}
$namingScheme ??= NamingConvention::tryFrom(
$this->persistence->getSetting(Setting::NamingConvention) ?? '',
) ?? NamingConvention::GogSlug;
switch ($namingScheme) {
case NamingConvention::GogSlug:
case NamingConvention::RomManager:
if (!$game->slug) {
throw new InvalidValueException("GOG Downloader is configured to use the GOG slug naming scheme, but the game '{$game->title}' does not have a slug. If you migrated from the previous naming scheme, please run the update command first.");
}
$title = $game->slug;
break;
case NamingConvention::Custom:
$title = preg_replace('@[^a-zA-Z-_0-9.]@', '_', $game->title);
$title = preg_replace('@_{2,}@', '_', $title);
$title = trim($title, '.');
break;
default:
throw new LogicException('Unimplemented naming scheme: ' . $namingScheme->value);
}
if ($namingScheme === NamingConvention::RomManager) {
if (!$download instanceof PlatformSpecificItem) {
$dir .= "/win";
} else {
$os = OperatingSystem::tryFrom($download->platform);
$dir .= '/' . match ($os) {
OperatingSystem::Linux => 'linux',
OperatingSystem::MacOS => 'mac',
OperatingSystem::Windows => 'win',
default => throw new InvalidValueException("Unsupported operating system: {$download->platform}"),
};
}
}
$dir = "{$dir}/{$title}";
if ($subdirectory !== null) {
$dir .= "/{$subdirectory}";
}
return $dir;
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Trait/FilteredGamesResolverTrait.php | src/Trait/FilteredGamesResolverTrait.php | <?php
namespace App\Trait;
use App\DTO\GameInstaller;
use App\DTO\GameDetail;
use App\DTO\OwnedItemInfo;
use App\DTO\SearchFilter;
use App\Enum\Language;
use App\Enum\MediaType;
use App\Enum\OperatingSystem;
use App\Exception\InvalidValueException;
use App\Service\OwnedItemsManager;
use Rikudou\Iterables\Iterables;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use ValueError;
trait FilteredGamesResolverTrait
{
use EnumExceptionParserTrait;
/**
* @return array<Language>
* @throws InvalidValueException
*/
private function getLanguages(InputInterface $input): array
{
try {
return array_map(
fn (string $langCode) => Language::from($langCode),
$input->getOption('language'),
);
} catch (ValueError $e) {
$invalid = $this->getInvalidOption($e);
throw new InvalidValueException(
$invalid
? 'Some of the languages you provided are not valid'
: "The language '{$invalid}' is not a supported language'"
);
}
}
/**
* @return array<OperatingSystem>
* @throws InvalidValueException
*/
private function getOperatingSystems(InputInterface $input): array
{
try {
return array_map(
fn(string $operatingSystem) => OperatingSystem::from($operatingSystem),
$input->getOption('os'),
);
} catch (ValueError $e) {
$invalid = $this->getInvalidOption($e);
throw new InvalidValueException(
$invalid
? 'Some of the operating systems you provided are not valid'
: "The operating system '{$invalid}' is not a valid operating system");
}
}
/**
* @return iterable<GameDetail>
* @throws InvalidValueException
*/
private function getGames(InputInterface $input, OutputInterface $output, OwnedItemsManager $ownedItemsManager): iterable
{
$operatingSystems = $this->getOperatingSystems($input);
$languages = $this->getLanguages($input);
$englishFallback = $input->getOption('language-fallback-english');
$excludeLanguage = Language::tryFrom($input->getOption('exclude-game-with-language') ?? '');
$timeout = $input->getOption('idle-timeout');
$only = $input->getOption('only');
$without = $input->getOption('without');
$filter = new SearchFilter(
operatingSystems: $operatingSystems,
languages: $languages,
);
$iterable = $input->getOption('update')
? Iterables::filter(Iterables::map(
function (OwnedItemInfo $info) use ($ownedItemsManager, $timeout, $output): GameDetail {
if ($output->isVerbose()) {
$output->writeln("Updating metadata for {$info->getTitle()}...");
}
return $ownedItemsManager->getItemDetail($info, $timeout);
},
$ownedItemsManager->getOwnedItems(MediaType::Game, $filter, httpTimeout: $timeout),
))
: $ownedItemsManager->getLocalGameData();
if ($only) {
$iterable = Iterables::filter($iterable, fn (GameDetail $detail) => in_array(
strtolower($detail->title),
array_map(fn (string $title) => strtolower($title), $only),
true,
));
}
if ($without) {
$iterable = Iterables::filter($iterable, fn (GameDetail $detail) => !in_array(
strtolower($detail->title),
array_map(fn (string $title) => strtolower($title), $without),
true,
));
}
if ($excludeLanguage) {
$iterable = Iterables::filter(
$iterable,
fn (GameDetail $detail) => array_find(
$detail->downloads,
fn (GameInstaller $download)
=> $download->language === $excludeLanguage->value || $download->language === $excludeLanguage->getLocalName(),
) === null,
);
}
if ($englishFallback || $languages) {
$iterable = Iterables::map(
function (GameDetail $game) use ($englishFallback, $languages) {
$languageNames = array_map(
fn (Language $language) => $language->getLocalName(),
$languages,
);
$languageCodes = array_map(
fn (Language $language) => $language->value,
$languages,
);
$downloads = array_filter(
$game->downloads,
fn (GameInstaller $download)
=> in_array($download->language, $languageNames, true) || in_array($download->language, $languageCodes, true),
);
if (!count($downloads) && $englishFallback) {
$downloads = array_filter(
$game->downloads,
fn (GameInstaller $download)
=> $download->language === Language::English->value || $download->language === Language::English->getLocalName(),
);
}
return new GameDetail(
id: $game->id,
title: $game->title,
cdKey: $game->cdKey,
downloads: $downloads,
slug: $game->slug,
extras: $game->extras,
);
},
$iterable,
);
}
if ($operatingSystems) {
$iterable = Iterables::map(
function (GameDetail $game) use ($operatingSystems) {
$downloads = array_filter(
$game->downloads,
fn (GameInstaller $download) => in_array($download->platform, array_map(
fn (OperatingSystem $system) => $system->value,
$operatingSystems,
))
);
return new GameDetail(
id: $game->id,
title: $game->title,
cdKey: $game->cdKey,
downloads: $downloads,
slug: $game->slug,
extras: $game->extras,
);
},
$iterable,
);
}
return Iterables::filter(
$iterable,
fn (GameDetail $gameDetail) => count($gameDetail->downloads) > 0,
);
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Trait/EnumExceptionParserTrait.php | src/Trait/EnumExceptionParserTrait.php | <?php
namespace App\Trait;
use ValueError;
trait EnumExceptionParserTrait
{
private function getInvalidOption(ValueError $error): ?string
{
$regex = /** @lang RegExp */ '@^"([^"]+)" is not a valid@';
if (!preg_match($regex, $error->getMessage(), $matches)) {
return null;
}
return $matches[1];
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Trait/CommonOptionsTrait.php | src/Trait/CommonOptionsTrait.php | <?php
namespace App\Trait;
use App\Enum\OperatingSystem;
use Symfony\Component\Console\Input\InputOption;
trait CommonOptionsTrait
{
private function addOsFilterOption(): static
{
$this->addOption(
'os',
'o',
InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY,
'Only games for specified operating system, allowed values: ' . implode(
', ',
array_map(
fn(OperatingSystem $os) => $os->value,
OperatingSystem::cases(),
)
)
);
return $this;
}
private function addLanguageFilterOption(): static
{
$this
->addOption(
'language',
'l',
InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY,
'Only games for specified language. See command "languages" for list of them.',
);
return $this;
}
private function addLanguageFallbackEnglishOption(): static
{
$this
->addOption(
'language-fallback-english',
null,
InputOption::VALUE_NONE,
'Use english versions of games when the specified language is not found.',
);
return $this;
}
private function addUpdateOption(): static
{
$this
->addOption(
'update',
'u',
InputOption::VALUE_NONE,
"If you specify this flag, the local database will be updated along with this command and you don't need to update it separately"
);
return $this;
}
private function addExcludeLanguageOption(): static
{
$this
->addOption(
'exclude-game-with-language',
null,
InputOption::VALUE_REQUIRED,
'Specify a language to exclude. If a game supports this language, it will be skipped.',
);
return $this;
}
private function addHttpRetryOption(): static
{
$this
->addOption(
'retry',
null,
InputOption::VALUE_REQUIRED,
'How many times should each request be retried in case of failure.',
3,
);
return $this;
}
private function addHttpRetryDelayOption(): static
{
$this
->addOption(
'retry-delay',
null,
InputOption::VALUE_REQUIRED,
'The delay in seconds between each retry.',
1,
);
return $this;
}
private function addSkipHttpErrorsOption(): static
{
$this
->addOption(
'skip-errors',
null,
InputOption::VALUE_NONE,
"Skip games that for whatever reason couldn't be fetched"
);
return $this;
}
private function addHttpIdleTimeoutOption(): static
{
$this
->addOption(
'idle-timeout',
null,
InputOption::VALUE_REQUIRED,
'Set the idle timeout in seconds for http requests',
3,
);
return $this;
}
private function addGameNameFilterOption(): static
{
$this
->addOption(
name: 'only',
mode: InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY,
description: 'Only games specified using this flag will be fetched. The flag can be specified multiple times. Case insensitive, exact match.',
);
return $this;
}
private function addExcludeGameNameFilterOption(): static
{
$this
->addOption(
name: 'without',
mode: InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY,
description: "Don't download the games listed using this flag. The flag can be specified multiple times. Case insensitive, exact match.",
);
return $this;
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Trait/MigrationCheckerTrait.php | src/Trait/MigrationCheckerTrait.php | <?php
namespace App\Trait;
use App\Service\Persistence\PersistenceManager;
use Symfony\Component\Console\Output\OutputInterface;
trait MigrationCheckerTrait
{
private function showInfoIfMigrationsAreNeeded(OutputInterface $output, PersistenceManager $persistence): void
{
if (!$persistence->needsMigrating(true)) {
return;
}
$output->writeln("<info>> The database needs migrating after an update, this command might take more time than usual, please don't cancel it in the middle of a migration.</info>");
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Helper/LatelyBoundStringValue.php | src/Helper/LatelyBoundStringValue.php | <?php
namespace App\Helper;
use Closure;
use Stringable;
final class LatelyBoundStringValue implements Stringable
{
private ?string $value = null;
/**
* @var Closure(): string
*/
private readonly Closure $callback;
/**
* @param callable(): string $callback
*/
public function __construct(
callable $callback,
) {
$this->callback = $callback(...);
}
public function __toString()
{
$this->value ??= ($this->callback)();
return $this->value;
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Attribute/SerializedName.php | src/Attribute/SerializedName.php | <?php
namespace App\Attribute;
use Attribute;
#[Attribute(Attribute::TARGET_PROPERTY)]
final class SerializedName
{
public function __construct(
public readonly string $name,
) {
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Attribute/ArrayType.php | src/Attribute/ArrayType.php | <?php
namespace App\Attribute;
#[\Attribute(\Attribute::TARGET_PROPERTY)]
final class ArrayType
{
public function __construct(
public readonly string $type,
) {
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Listener/PreCommandListener.php | src/Listener/PreCommandListener.php | <?php
namespace App\Listener;
use App\Service\NewVersionChecker;
use Symfony\Component\Console\ConsoleEvents;
use Symfony\Component\Console\Event\ConsoleCommandEvent;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
final readonly class PreCommandListener implements EventSubscriberInterface
{
public function __construct(
private NewVersionChecker $newVersionChecker,
#[Autowire('%app.source_repository%')]
private string $repository,
) {
}
public static function getSubscribedEvents(): array
{
return [
ConsoleEvents::COMMAND => 'onConsoleEvent',
];
}
public function onConsoleEvent(ConsoleCommandEvent $event): void
{
if (!$this->newVersionChecker->newVersionAvailable()) {
return;
}
$output = $event->getOutput();
$output->writeln("<fg=black;bg=yellow>There's a new version ({$this->newVersionChecker->getLatestVersion()}) available to download at {$this->repository}/releases/latest</>");
$output->writeln("");
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/DTO/BuildInfoItem.php | src/DTO/BuildInfoItem.php | <?php
namespace App\DTO;
use DateTimeInterface;
final readonly class BuildInfoItem
{
public string $buildId;
public string $productId;
public string $os;
public ?string $branch;
public string $versionName;
/**
* @var array<string>
*/
public array $tags;
public bool $public;
public DateTimeInterface $datePublished;
public int $generation;
public string $link;
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/DTO/DownloadDescription.php | src/DTO/DownloadDescription.php | <?php
use App\DTO\GameInstaller;
class_alias(GameInstaller::class, 'App\DTO\DownloadDescription');
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/DTO/SaveGameFile.php | src/DTO/SaveGameFile.php | <?php
namespace App\DTO;
use App\Attribute\SerializedName;
use DateTimeImmutable;
use DateTimeInterface;
final readonly class SaveGameFile
{
public int $bytes;
#[SerializedName('last_modified')]
public string $lastModified;
public ?string $hash;
public string $name;
#[SerializedName('content_type')]
public string $contentType;
public function isDeleted(): bool
{
return $this->hash === 'aadd86936a80ee8a369579c3926f1b3c';
}
public function getLastModifiedDatetime(): DateTimeInterface
{
return new DateTimeImmutable($this->lastModified);
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/DTO/OAuthCredentials.php | src/DTO/OAuthCredentials.php | <?php
namespace App\DTO;
final readonly class OAuthCredentials
{
public function __construct(
public string $clientId,
public string $clientSecret,
) {
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/DTO/GameInstaller.php | src/DTO/GameInstaller.php | <?php
namespace App\DTO;
final class GameInstaller implements DownloadableItem, PlatformSpecificItem
{
public function __construct(
public readonly string $language,
public readonly string $platform,
public readonly string $name,
public readonly float $size,
public readonly string $url,
public private(set) ?string $md5,
public readonly ?int $gogGameId,
public readonly bool $isPatch = false,
) {
}
public function __unserialize(array $data): void
{
if (is_string($data['gogGameId'])) {
$data['gogGameId'] = (int)$data['gogGameId'];
}
if (!isset($data['isPatch'])) {
$data['isPatch'] = false;
}
foreach ($data as $key => $value) {
$this->$key = $value;
}
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/DTO/Authorization.php | src/DTO/Authorization.php | <?php
namespace App\DTO;
use DateTimeInterface;
final class Authorization
{
public function __construct(
public readonly string $token,
public readonly string $refreshToken,
public readonly DateTimeInterface $validUntil,
) {
}
public function __toString(): string
{
return $this->token;
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/DTO/MovieInfo.php | src/DTO/MovieInfo.php | <?php
namespace App\DTO;
use App\Enum\MediaType;
final class MovieInfo implements OwnedItemInfo
{
public readonly int $id;
public readonly string $title;
public function getId(): int
{
return $this->id;
}
public function getTitle(): string
{
return $this->title;
}
public function getType(): MediaType
{
return MediaType::Movie;
}
public function hasUpdates(): bool
{
return false;
}
public function getSlug(): string
{
return '';
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/DTO/OwnedItemInfo.php | src/DTO/OwnedItemInfo.php | <?php
namespace App\DTO;
use App\Enum\MediaType;
interface OwnedItemInfo
{
public function getId(): int;
public function getTitle(): string;
public function getType(): MediaType;
public function hasUpdates(): bool;
public function getSlug(): string;
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/DTO/MultipleValuesWrapper.php | src/DTO/MultipleValuesWrapper.php | <?php
namespace App\DTO;
use ArrayIterator;
use IteratorAggregate;
use Traversable;
final class MultipleValuesWrapper implements IteratorAggregate
{
private Traversable $iterator;
public function __construct(
Traversable|array $iterator,
) {
if (is_array($iterator)) {
$this->iterator = new ArrayIterator($iterator);
} else {
$this->iterator = $iterator;
}
}
public function getIterator(): Traversable
{
return $this->iterator;
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/DTO/GameDetail.php | src/DTO/GameDetail.php | <?php
namespace App\DTO;
use App\Attribute\ArrayType;
use JetBrains\PhpStorm\Deprecated;
final readonly class GameDetail
{
/**
* @param array<GameInstaller> $downloads
* @param array<GameExtra> $extras
*/
public function __construct(
public int $id,
public string $title,
#[Deprecated]
public string $cdKey,
#[ArrayType(type: GameInstaller::class)]
public array $downloads,
public string $slug,
public array $extras,
) {
}
public function __unserialize(array $data): void
{
$data['extras'] ??= [];
$data['slug'] ??= '';
foreach ($data as $key => $value) {
$this->$key = $value;
}
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/DTO/Url.php | src/DTO/Url.php | <?php
namespace App\DTO;
final class Url
{
public function __construct(
private readonly ?string $scheme = null,
private readonly ?string $host = null,
private readonly ?string $path = null,
private readonly array $query = [],
) {
}
public function __toString(): string
{
$url = '';
if ($this->scheme !== null) {
$url .= "{$this->scheme}://";
}
if ($this->host !== null) {
$url .= $this->host;
}
if ($this->path !== null) {
$url .= "/{$this->path}";
}
if (count($this->query)) {
$url .= sprintf('?%s', http_build_query($this->query));
}
return $url;
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/DTO/PlatformSpecificItem.php | src/DTO/PlatformSpecificItem.php | <?php
namespace App\DTO;
interface PlatformSpecificItem extends DownloadableItem
{
public string $platform { get; }
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/DTO/SaveFileContent.php | src/DTO/SaveFileContent.php | <?php
namespace App\DTO;
final readonly class SaveFileContent
{
public function __construct(
public string $hash,
public string $content,
) {
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/DTO/DownloadableItem.php | src/DTO/DownloadableItem.php | <?php
namespace App\DTO;
interface DownloadableItem
{
public string $name {
get;
}
public string $url {
get;
}
public ?string $md5 {
get;
}
public ?int $gogGameId {
get;
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/DTO/SearchFilter.php | src/DTO/SearchFilter.php | <?php
namespace App\DTO;
use App\Enum\Language;
use App\Enum\OperatingSystem;
final class SearchFilter
{
/**
* @param array<Language>|null $languages
* @param array<OperatingSystem>|null $operatingSystems
*/
public function __construct(
public readonly ?array $operatingSystems = null,
public readonly ?array $languages = null,
public readonly ?string $search = null,
public readonly bool $includeHidden = false,
) {
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/DTO/GameExtra.php | src/DTO/GameExtra.php | <?php
namespace App\DTO;
final class GameExtra implements DownloadableItem
{
public function __construct(
public readonly int $id,
public readonly string $name,
public readonly int $size,
public readonly string $url,
public readonly int $gogGameId,
public private(set) ?string $md5,
) {
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/DTO/GameInfo.php | src/DTO/GameInfo.php | <?php
namespace App\DTO;
use App\Attribute\SerializedName;
use App\Enum\MediaType;
final class GameInfo implements OwnedItemInfo
{
public readonly int $id;
public readonly string $title;
#[SerializedName('updates')]
public readonly ?bool $hasUpdates;
public readonly bool $isNew;
public readonly ?string $slug;
public function getId(): int
{
return $this->id;
}
public function getTitle(): string
{
return $this->title;
}
public function getType(): MediaType
{
return MediaType::Game;
}
public function hasUpdates(): bool
{
return $this->hasUpdates || $this->isNew;
}
public function getSlug(): string
{
return $this->slug ?? '';
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/DTO/Serializer/Property.php | src/DTO/Serializer/Property.php | <?php
namespace App\DTO\Serializer;
final class Property
{
public function __construct(
public readonly string $name,
public readonly string $serializedName,
) {
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/DTO/FileWriter/StreamWrapperFileReference.php | src/DTO/FileWriter/StreamWrapperFileReference.php | <?php
namespace App\DTO\FileWriter;
final class StreamWrapperFileReference
{
/**
* @var resource|null
*/
private $fileHandle = null;
public function __construct(
public readonly string $path,
) {
}
public function __destruct()
{
if (is_resource($this->fileHandle)) {
fclose($this->fileHandle);
}
}
public function write(string $data): void
{
fwrite($this->open(), $data);
}
/**
* @return resource
*/
public function open()
{
if ($this->fileHandle === null) {
$mode = file_exists($this->path) ? 'a+' : 'w+';
if (!is_dir(dirname($this->path))) {
mkdir(dirname($this->path), 0777, true);
}
$this->fileHandle = fopen($this->path, $mode);
}
return $this->fileHandle;
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/DTO/FileWriter/S3FileReference.php | src/DTO/FileWriter/S3FileReference.php | <?php
namespace App\DTO\FileWriter;
use App\Enum\S3StorageClass;
use Aws\S3\S3Client;
final class S3FileReference
{
private const DEFAULT_CHUNK_SIZE = 10 * 1024 * 1024;
private int $partNumber = 0;
private ?string $openedObjectId = null;
private ?S3Client $client = null;
/** @var array<array{PartNumber: int, ETag: string}> */
private array $parts = [];
private string $buffer = '';
private int $chunkSize = 0;
public function __construct(
public readonly string $bucket,
public readonly string $key,
public readonly S3StorageClass $requestedStorageClass,
) {
}
public function __destruct()
{
if ($this->client !== null && $this->openedObjectId !== null) {
$this->client->abortMultipartUpload([
'Bucket' => $this->bucket,
'Key' => $this->key,
'UploadId' => $this->openedObjectId,
]);
}
}
public function open(S3Client $client): void
{
$this->client = $client;
if ($this->openedObjectId === null) {
$this->openedObjectId = $client->createMultipartUpload([
'Bucket' => $this->bucket,
'Key' => $this->key,
'StorageClass' => $this->requestedStorageClass->value,
])->get('UploadId');
}
}
public function writeChunk(S3Client $client, string $data, int $chunkSize, bool $forceWrite = false): void
{
$this->client = $client;
$this->chunkSize = $chunkSize;
if (strlen($this->buffer . $data) < $chunkSize && !$forceWrite) {
$this->buffer .= $data;
return;
}
$data = $this->buffer . $data;
$this->open($client);
$result = $client->uploadPart([
'Body' => substr($data, 0, $chunkSize),
'UploadId' => $this->openedObjectId,
'Bucket' => $this->bucket,
'Key' => $this->key,
'PartNumber' => ++$this->partNumber,
]);
$this->parts[] = [
'PartNumber' => $this->partNumber,
'ETag' => $result['ETag'],
];
$this->buffer = substr($data, $chunkSize);
}
public function finalize(string $hash): void
{
if ($this->client !== null && (count($this->parts) || $this->buffer)) {
while ($this->buffer) {
$this->writeChunk($this->client, $this->buffer, $this->chunkSize ?: self::DEFAULT_CHUNK_SIZE, true);
}
$this->client->completeMultipartUpload([
'UploadId' => $this->openedObjectId,
'Bucket' => $this->bucket,
'Key' => $this->key,
'MultipartUpload' => [
'Parts' => $this->parts,
],
]);
$this->openedObjectId = null;
while (!$this->client->doesObjectExistV2($this->bucket, $this->key)) {
sleep(1);
}
$this->client->putObjectTagging([
'Bucket' => $this->bucket,
'Key' => $this->key,
'Tagging' => [
'TagSet' => [
[
'Key' => 'md5_hash',
'Value' => $hash,
],
],
]
]);
}
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/DTO/FileWriter/ExtractedS3Path.php | src/DTO/FileWriter/ExtractedS3Path.php | <?php
namespace App\DTO\FileWriter;
final readonly class ExtractedS3Path
{
public function __construct(
public string $bucket,
public string $key,
) {
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/DTO/UserData/Checksum.php | src/DTO/UserData/Checksum.php | <?php
namespace App\DTO\UserData;
final readonly class Checksum
{
public function __construct(
public ?string $cart,
public ?string $games,
public ?string $wishlist,
public mixed $reviewsVotes,
public mixed $gamesRating,
) {
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/DTO/UserData/Language.php | src/DTO/UserData/Language.php | <?php
namespace App\DTO\UserData;
final readonly class Language
{
public function __construct(
public string $code,
public string $name,
) {
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/DTO/UserData/Currency.php | src/DTO/UserData/Currency.php | <?php
namespace App\DTO\UserData;
final readonly class Currency
{
public function __construct(
public string $code,
public string $symbol,
) {
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/DTO/UserData/UserData.php | src/DTO/UserData/UserData.php | <?php
namespace App\DTO\UserData;
use SensitiveParameter;
final readonly class UserData
{
/**
* @param array<Currency> $currencies
*/
public function __construct(
public string $country,
public array $currencies,
public Currency $selectedCurrency,
public Language $preferredLanguage,
public string $ratingBrand,
public bool $isLoggedIn,
public Checksum $checksum,
public UpdatesCount $updates,
public string $userId,
public string $username,
public string $galaxyUserId,
#[SensitiveParameter]
public string $email,
public string $avatar,
public WalletBalance $walletBalance,
public PurchasedItemsCount $purchasedItems,
public int $wishlistedItems,
public array $friends,
public array $personalizedProductPrices,
public array $personalizedSeriesPrices,
) {
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/DTO/UserData/WalletBalance.php | src/DTO/UserData/WalletBalance.php | <?php
namespace App\DTO\UserData;
use SensitiveParameter;
final readonly class WalletBalance
{
public function __construct(
public string $currency,
#[SensitiveParameter]
public int $amount,
) {
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/DTO/UserData/PurchasedItemsCount.php | src/DTO/UserData/PurchasedItemsCount.php | <?php
namespace App\DTO\UserData;
final readonly class PurchasedItemsCount
{
public function __construct(
public int $games,
public int $movies,
) {
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/DTO/UserData/UpdatesCount.php | src/DTO/UserData/UpdatesCount.php | <?php
namespace App\DTO\UserData;
final readonly class UpdatesCount
{
public function __construct(
public int $messages,
public int $pendingFriendRequests,
public int $unreadChatMessages,
public int $products,
public int $forum,
public int $total,
) {
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Validator/NonEmptyValidator.php | src/Validator/NonEmptyValidator.php | <?php
namespace App\Validator;
use RuntimeException;
final class NonEmptyValidator
{
public function __invoke(?string $value): string
{
if ($value === null) {
throw new RuntimeException('This value cannot be empty');
}
return $value;
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Service/Iterables.php | src/Service/Iterables.php | <?php
namespace App\Service;
final class Iterables
{
public function map(iterable $iterable, callable $callback): iterable
{
foreach ($iterable as $item) {
yield $callback($item);
}
}
public function filter(iterable $iterable, callable $callback): iterable
{
foreach ($iterable as $item) {
if ($callback($item)) {
yield $item;
}
}
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Service/WebAuthentication.php | src/Service/WebAuthentication.php | <?php
namespace App\Service;
use Symfony\Component\BrowserKit\HttpBrowser;
use Symfony\Component\HttpFoundation\Request;
final class WebAuthentication
{
public const AUTH_URL = 'https://auth.gog.com/auth?client_id=46899977096215655&redirect_uri=https%3A%2F%2Fembed.gog.com%2Fon_login_success%3Forigin%3Dclient&response_type=code&layout=client2';
public function __construct(
private readonly HttpBrowser $browser,
) {
}
public function getCode(string $email, string $password): ?string
{
$this->browser->request(Request::METHOD_GET, self::AUTH_URL);
$response = $this->browser->submitForm('login_login', [
'login[username]' => $email,
'login[password]' => $password,
]);
$url = $response->getUri();
if ($url === null) {
return null;
}
$query = parse_url($url, PHP_URL_QUERY);
if ($query === null) {
return null;
}
parse_str($query, $queryParts);
return $queryParts['code'] ?? null;
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Service/GameMetadataManager.php | src/Service/GameMetadataManager.php | <?php
namespace App\Service;
use App\DTO\Authorization;
use App\DTO\BuildInfoItem;
use App\DTO\GameDetail;
use App\DTO\GameInfo;
use App\DTO\OAuthCredentials;
use DateInterval;
use JsonException;
use Psr\Cache\CacheItemPoolInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Contracts\HttpClient\HttpClientInterface;
final readonly class GameMetadataManager
{
public function __construct(
private HttpClientInterface $httpClient,
private AuthenticationManager $authenticationManager,
private Serializer $serializer,
private CacheItemPoolInterface $cache,
) {
}
public function getGameAccessKey(GameInfo|GameDetail $game): ?Authorization
{
$cacheItem = $this->cache->getItem("game.oauth.access_key.{$game->id}");
if ($cacheItem->isHit()) {
return $cacheItem->get();
}
$oauthData = $this->getGameOAuthCredentials($game);
if ($oauthData === null) {
return null;
}
$result = $this->authenticationManager->getGameAuthorization($oauthData->clientId, $oauthData->clientSecret);
$cacheItem->set($result);
$cacheItem->expiresAt($result->validUntil);
$this->cache->save($cacheItem);
return $result;
}
public function getGameOAuthCredentials(GameInfo|GameDetail $game): ?OAuthCredentials
{
$cacheItem = $this->cache->getItem("game.oauth.credentials.{$game->id}");
if ($cacheItem->isHit()) {
return $cacheItem->get();
}
$builds = $this->getBuildsInfo($game);
if (!count($builds)) {
return null;
}
$response = $this->httpClient->request(
Request::METHOD_GET,
$builds[0]->link,
)->getContent();
try {
$result = json_decode($response, true, flags: JSON_THROW_ON_ERROR);
} catch (JsonException) {
$result = json_decode(zlib_decode($response), true);
}
$clientId = $result['clientId'] ?? null;
$clientSecret = $result['clientSecret'] ?? null;
if ($clientId === null || $clientSecret === null) {
return null;
}
$result = new OAuthCredentials($clientId, $clientSecret);
$cacheItem->set($result);
$cacheItem->expiresAfter(new DateInterval('PT1H'));
$this->cache->save($cacheItem);
return $result;
}
/**
* @return array<BuildInfoItem>
*/
private function getBuildsInfo(GameInfo|GameDetail $game): array
{
$json = json_decode($this->httpClient->request(
Request::METHOD_GET,
"https://content-system.gog.com/products/{$game->id}/os/windows/builds?generation=2"
)->getContent(), true);
return array_map(
fn (array $build) => $this->serializer->deserialize($build, BuildInfoItem::class),
$json['items'],
);
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Service/AuthenticationManager.php | src/Service/AuthenticationManager.php | <?php
namespace App\Service;
use App\DTO\Authorization;
use App\DTO\Url;
use App\DTO\UserData\Checksum;
use App\DTO\UserData\Currency;
use App\DTO\UserData\Language;
use App\DTO\UserData\PurchasedItemsCount;
use App\DTO\UserData\UpdatesCount;
use App\DTO\UserData\UserData;
use App\DTO\UserData\WalletBalance;
use App\Exception\AuthenticationException;
use App\Service\Persistence\PersistenceManager;
use DateInterval;
use DateTimeImmutable;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
final readonly class AuthenticationManager
{
private const AUTH_URL = 'https://auth.gog.com';
public function __construct(
private PersistenceManager $persistence,
private HttpClientInterface $httpClient,
private string $clientId,
) {
}
public function codeLogin(string $code): void
{
try {
$response = $this->httpClient->request(
Request::METHOD_GET,
new Url(host: self::AUTH_URL, path: 'token', query: [
'client_id' => $this->clientId,
'client_secret' => '9d85c43b1482497dbbce61f6e4aa173a433796eeae2ca8c5f6129f2dc4de46d9',
'grant_type' => 'authorization_code',
'code' => $code,
'redirect_uri' => 'https://embed.gog.com/on_login_success?origin=client',
])
);
$json = json_decode($response->getContent(), true);
$result = new Authorization(
$json['access_token'],
$json['refresh_token'],
(new DateTimeImmutable())->add(new DateInterval("PT{$json['expires_in']}S")),
);
$this->persistence->saveAuthorization($result);
} catch (ClientExceptionInterface | ServerExceptionInterface) {
throw new AuthenticationException('Failed to log in using the code, please try again.');
}
}
public function getAuthorization(): Authorization
{
$authorization = $this->persistence->getAuthorization();
if ($authorization === null) {
throw new AuthenticationException('No authorization data are stored. Please login before using this command.');
}
$now = new DateTimeImmutable();
if ($now > $authorization->validUntil) {
$authorization = $this->refreshToken($authorization);
}
return $authorization;
}
public function getUserInfo(): UserData
{
$response = $this->httpClient->request(Request::METHOD_GET, 'https://embed.gog.com/userData.json', [
'auth_bearer' => (string) $this->getAuthorization(),
]);
$json = json_decode($response->getContent(), true, flags: JSON_THROW_ON_ERROR);
// todo update serializer
return new UserData(
country: $json['country'],
currencies: array_map(
fn (array $currency) => new Currency(
code: $currency['code'],
symbol: $currency['symbol'],
),
$json['currencies'],
),
selectedCurrency: new Currency(
code: $json['selectedCurrency']['code'],
symbol: $json['selectedCurrency']['symbol'],
),
preferredLanguage: new Language(
code: $json['preferredLanguage']['code'],
name: $json['preferredLanguage']['name'],
),
ratingBrand: $json['ratingBrand'],
isLoggedIn: $json['isLoggedIn'],
checksum: new Checksum(
cart: $json['checksum']['cart'],
games: $json['checksum']['games'],
wishlist: $json['checksum']['wishlist'],
reviewsVotes: $json['checksum']['reviews_votes'],
gamesRating: $json['checksum']['games_rating'],
),
updates: new UpdatesCount(
messages: $json['updates']['messages'],
pendingFriendRequests: $json['updates']['pendingFriendRequests'],
unreadChatMessages: $json['updates']['unreadChatMessages'],
products: $json['updates']['products'],
forum: $json['updates']['forum'],
total: $json['updates']['total'],
),
userId: $json['userId'],
username: $json['username'],
galaxyUserId: $json['galaxyUserId'],
email: $json['email'],
avatar: $json['avatar'],
walletBalance: new WalletBalance(
currency: $json['walletBalance']['currency'],
amount: $json['walletBalance']['amount'],
),
purchasedItems: new PurchasedItemsCount(
games: $json['purchasedItems']['games'],
movies: $json['purchasedItems']['movies'],
),
wishlistedItems: $json['wishlistedItems'],
friends: $json['friends'],
personalizedProductPrices: $json['personalizedProductPrices'],
personalizedSeriesPrices: $json['personalizedSeriesPrices'],
);
}
public function getGameAuthorization(string $clientId, string $clientSecret): Authorization
{
$json = json_decode($this->httpClient->request(
Request::METHOD_GET,
"https://auth.gog.com/token?client_id={$clientId}&client_secret={$clientSecret}&grant_type=refresh_token&refresh_token={$this->getAuthorization()->refreshToken}&without_new_session=1"
)->getContent(), true);
return new Authorization(
$json['access_token'],
$json['refresh_token'],
(new DateTimeImmutable())->add(new DateInterval("PT{$json['expires_in']}S")),
);
}
private function refreshToken(Authorization $authorization): Authorization
{
try {
$response = $this->httpClient->request(
Request::METHOD_GET,
new Url(host: self::AUTH_URL, path: 'token', query: [
'client_id' => '46899977096215655',
'client_secret' => '9d85c43b1482497dbbce61f6e4aa173a433796eeae2ca8c5f6129f2dc4de46d9',
'grant_type' => 'refresh_token',
'refresh_token' => $authorization->refreshToken,
'redirect_uri' => 'https://embed.gog.com/on_login_success?origin=client',
])
);
$json = json_decode($response->getContent(), true);
$result = new Authorization(
$json['access_token'],
$json['refresh_token'],
(new DateTimeImmutable())->add(new DateInterval("PT{$json['expires_in']}S")),
);
$this->persistence->saveAuthorization($result);
return $result;
} catch (ClientExceptionInterface | ServerExceptionInterface) {
throw new AuthenticationException('Failed to refresh authorization data, please login again.');
}
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Service/OwnedItemsManager.php | src/Service/OwnedItemsManager.php | <?php
namespace App\Service;
use App\DTO\DownloadableItem;
use App\DTO\GameDetail;
use App\DTO\GameInfo;
use App\DTO\MovieInfo;
use App\DTO\OwnedItemInfo;
use App\DTO\SearchFilter;
use App\DTO\Url;
use App\Enum\Language;
use App\Enum\MediaType;
use App\Enum\OperatingSystem;
use App\Exception\AuthorizationException;
use App\Service\Persistence\PersistenceManager;
use DateInterval;
use Exception;
use JsonException;
use Psr\Cache\CacheItemPoolInterface;
use ReflectionException;
use ReflectionProperty;
use SimpleXMLElement;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
final class OwnedItemsManager
{
private const GOG_ACCOUNT_URL = 'https://embed.gog.com/account';
private const GOG_API_URL = 'https://api.gog.com';
public function __construct(
private readonly HttpClientInterface $httpClient,
private readonly AuthenticationManager $authorization,
private readonly Serializer $serializer,
private readonly PersistenceManager $persistence,
private readonly CacheItemPoolInterface $cache,
) {
}
/**
* @param MediaType $mediaType
* @param SearchFilter $filter
* @param int|null $productsCount
*
* @throws ClientExceptionInterface
* @throws JsonException
* @throws RedirectionExceptionInterface
* @throws ReflectionException
* @throws ServerExceptionInterface
* @throws TransportExceptionInterface
*
* @return iterable<OwnedItemInfo>
*/
public function getOwnedItems(
MediaType $mediaType,
SearchFilter $filter = new SearchFilter(),
?int &$productsCount = null,
int $httpTimeout = 3,
): iterable {
$page = 1;
$query = [
'mediaType' => $mediaType->value,
'page' => $page,
'sortBy' => 'title',
'hiddenFlag' => 0,
];
if ($filter->languages !== null) {
$query['language'] = implode(',', array_map(
fn (Language $language): string => $language->value,
$filter->languages,
));
}
if ($filter->operatingSystems !== null) {
$query['system'] = implode(',', array_map(
fn (OperatingSystem $operatingSystem): string => $operatingSystem->getAsNumbers(),
$filter->operatingSystems,
));
}
if ($filter->search !== null) {
$query['search'] = $filter->search;
}
if ($filter->includeHidden) {
unset($query['hiddenFlag']);
}
do {
$response = $this->httpClient->request(
Request::METHOD_GET,
new Url(
host: self::GOG_ACCOUNT_URL,
path: 'getFilteredProducts',
query: $query,
),
[
'auth_bearer' => (string) $this->authorization->getAuthorization(),
'timeout' => $httpTimeout,
]
);
try {
$data = json_decode($response->getContent(), true, flags: JSON_THROW_ON_ERROR);
++$query['page'];
$productsCount = $data['totalProducts'];
} catch (JsonException) {
throw new AuthorizationException('Failed to get list of games, you were probably logged out.');
}
foreach ($data['products'] as $product) {
if ($product['isGame']) {
yield $this->serializer->deserialize($product, GameInfo::class);
}
if ($product['isMovie']) {
yield $this->serializer->deserialize($product, MovieInfo::class);
}
}
} while ($query['page'] <= $data['totalPages']);
}
public function getGameDetailByTitle(string $title): ?GameDetail
{
return array_find(
$this->getLocalGameData(),
fn ($gameDetail) => $gameDetail->title === $title,
);
}
public function getItemDetail(OwnedItemInfo $item, int $httpTimeout = 3, bool $cached = true): ?GameDetail
{
$cacheItem = $cached ? $this->cache->getItem("game_detail.{$item->getType()->value}.{$item->getId()}") : null;
if ($cacheItem?->isHit()) {
return $cacheItem->get();
}
$detail = match ($item->getType()) {
MediaType::Game => $this->getGameDetail($item, $httpTimeout),
MediaType::Movie => $this->getMovieDetail($item, $httpTimeout),
};
$cacheItem?->set($detail);
$cacheItem?->expiresAfter(new DateInterval('PT20M'));
if ($cacheItem) {
$this->cache->save($cacheItem);
}
return $detail;
}
/**
* @param array<GameDetail> $details
*/
public function storeGamesData(array $details): void
{
$this->persistence->storeLocalGameData($details);
}
public function storeSingleGameData(GameDetail $detail): void
{
$this->persistence->storeSingleGameDetail($detail);
}
/**
* @return array<GameDetail>
*/
public function getLocalGameData(): array
{
return $this->persistence->getLocalGameData() ?? [];
}
/**
* @todo move this to deserialization (duplicate requests)
*/
public function getChecksum(DownloadableItem $download, ?GameDetail $game, int $httpTimeout = 3): ?string
{
$parts = explode('/', $download->url);
$id = $parts[array_key_last($parts)];
$gameId = $download->gogGameId ?? $game?->id;
$response = $this->httpClient->request(
Request::METHOD_GET,
new Url(
host: self::GOG_API_URL,
path: "products/{$gameId}",
query: [
'expand' => 'downloads',
]
),
[
'auth_bearer' => (string) $this->authorization->getAuthorization(),
'timeout' => $httpTimeout,
]
);
$data = json_decode($response->getContent(), true)['downloads'];
foreach ($data as $items) {
$targetUrl = array_map(
fn (array $item) => $item['files'],
$items,
);
$targetUrl = array_merge(...$targetUrl);
$targetUrl = array_filter($targetUrl, fn (array $item) => str_ends_with($item['downlink'], $id));
$targetUrl = array_values($targetUrl)[0]['downlink'] ?? null;
if ($targetUrl === null) {
continue;
}
$response = $this->httpClient->request(
Request::METHOD_GET,
$targetUrl,
[
'auth_bearer' => (string) $this->authorization->getAuthorization(),
'timeout' => $httpTimeout,
]
);
$response = json_decode($response->getContent(), true);
$response = $this->httpClient->request(
Request::METHOD_GET,
$response['checksum'],
[
'timeout' => $httpTimeout,
]
);
try {
$response = new SimpleXMLElement($response->getContent());
} catch (ClientExceptionInterface | TransportExceptionInterface | ServerExceptionInterface) {
return null;
} catch (Exception $e) {
if (!str_contains($e->getMessage(), 'String could not be parsed as XML')) {
throw $e;
}
return null;
}
return (string) $response['md5'];
}
return null;
}
private function getGameDetail(OwnedItemInfo $item, int $httpTimeout): ?GameDetail
{
$ownedResponse = $this->httpClient->request(
Request::METHOD_GET,
new Url(
host: self::GOG_ACCOUNT_URL,
path: "gameDetails/{$item->id}.json",
),
[
'auth_bearer' => (string) $this->authorization->getAuthorization(),
'timeout' => $httpTimeout,
]
);
$ownedContent = json_decode($ownedResponse->getContent(), true);
if (isset($ownedContent['isBaseProductMissing']) && $ownedContent['isBaseProductMissing']) {
return null;
}
$ownedDlcTitles = array_map(
fn (array $item) => $item['title'],
$ownedContent['dlcs'],
);
$ownedExtrasTitles = array_map(
fn (array $item) => $item['name'],
$ownedContent['extras'],
);
$generalResponse = $this->httpClient->request(
Request::METHOD_GET,
new Url(
host: self::GOG_API_URL,
path: "products/{$item->id}",
query: [
'expand' => implode(',', [
'downloads',
'expanded_dlcs',
])
]
),
[
'auth_bearer' => (string) $this->authorization->getAuthorization(),
'timeout' => $httpTimeout,
]
);
$generalContent = json_decode($generalResponse->getContent(), true);
$generalContent['expanded_dlcs'] = array_filter(
$generalContent['expanded_dlcs'] ?? [],
fn (array $item) => in_array($item['title'], $ownedDlcTitles, true),
);
$generalContent['downloads']['bonus_content'] = array_filter(
$generalContent['downloads']['bonus_content'] ?? [],
fn (array $item) => in_array($item['name'], $ownedExtrasTitles, true),
);
$detail = $this->serializer->deserialize($generalContent, GameDetail::class, [
'id' => $item->getId(),
'slug' => $item->getSlug(),
]);
foreach ($detail->downloads as $download) {
$this->setMd5($download, $detail, $httpTimeout);
}
foreach ($detail->extras as $extra) {
$this->setMd5($extra, $detail, $httpTimeout);
}
assert($detail instanceof GameDetail);
return $detail;
}
private function getMovieDetail(OwnedItemInfo $item, int $httpTimeout): GameDetail
{
$response = $this->httpClient->request(
Request::METHOD_GET,
new Url(
host: self::GOG_ACCOUNT_URL,
path: "movieDetails/{$item->id}.json",
),
[
'auth_bearer' => (string) $this->authorization->getAuthorization(),
'timeout' => $httpTimeout,
]
);
$detail = $this->serializer->deserialize($response->getContent(), GameDetail::class, [
'id' => $item->getId(),
]);
assert($detail instanceof GameDetail);
return $detail;
}
private function setMd5(DownloadableItem $download, GameDetail $game, int $httpTimeout): void
{
if ($download->md5 !== null) {
return;
}
$md5 = $this->getChecksum($download, $game, $httpTimeout);
if ($md5 === null) {
$md5 = '';
}
$reflection = new ReflectionProperty($download, 'md5');
$reflection->setValue($download, $md5);
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Service/MigrationManager.php | src/Service/MigrationManager.php | <?php
namespace App\Service;
use App\Migration\Migration;
use DateTimeImmutable;
use PDO;
use PDOException;
final class MigrationManager
{
private bool $applied = false;
/**
* @param iterable<Migration> $migrations
*/
public function __construct(
private readonly iterable $migrations,
) {
}
public function apply(PDO $pdo): void
{
if ($this->applied) {
return;
}
foreach ($this->getMigrationsToApply($pdo) as $migration) {
$migration->migrate($pdo);
$statement = $pdo->prepare('INSERT INTO migrations (version, created) VALUES (?, ?)');
$statement->execute([
$migration->getVersion(),
(new DateTimeImmutable())->format('c'),
]);
}
$this->applied = true;
}
public function countUnappliedMigrations(PDO $pdo): int
{
return count($this->getMigrationsToApply($pdo));
}
public function countAllMigrations(): int
{
$migrations = is_countable($this->migrations) ? $this->migrations : [...$this->migrations];
return count($migrations);
}
/**
* @return array<Migration>
*/
private function getMigrationsToApply(PDO $pdo): array
{
$migrations = [...$this->migrations];
usort(
$migrations,
fn (Migration $migration1, Migration $migration2) => $migration1->getVersion() <=> $migration2->getVersion(),
);
return array_filter(
$migrations,
fn (Migration $migration) => !$this->isApplied($migration, $pdo),
);
}
private function isApplied(Migration $migration, PDO $pdo): bool
{
$version = $migration->getVersion();
try {
$result = $pdo->query('select * from migrations order by version desc');
$currentVersion = $result->fetch(PDO::FETCH_ASSOC)['version'];
} catch (PDOException $e) {
if (!str_contains($e->getMessage(), 'no such table')) {
throw $e;
}
$currentVersion = -1;
}
return $version <= $currentVersion;
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Service/NewVersionChecker.php | src/Service/NewVersionChecker.php | <?php
namespace App\Service;
use Symfony\Component\Console\Application;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
final class NewVersionChecker
{
private ?string $cached = null;
public function __construct(
#[Autowire('%app.source_repository%')]
private readonly string $repository,
private readonly Application $application,
private readonly HttpClientInterface $httpClient,
) {
}
public function newVersionAvailable(): bool
{
$current = $this->getCurrentVersion();
if ($current === 'dev-version') {
return false;
}
$latest = $this->getLatestVersion();
return version_compare($current, $latest, '<');
}
public function getLatestVersion(): string
{
if ($this->cached) {
return $this->cached;
}
$url = "{$this->repository}/releases/latest";
try {
$response = $this->httpClient->request(
Request::METHOD_HEAD,
$url,
[
'max_redirects' => 0,
],
);
$location = $response->getHeaders(false)['location'][0] ?? null;
} catch (TransportExceptionInterface|ClientExceptionInterface|RedirectionExceptionInterface|ServerExceptionInterface) {
return '0.0.0';
}
$parts = explode('/', $location);
$last = $parts[array_key_last($parts)];
$this->cached = substr($last, 1);
return $this->cached;
}
private function getCurrentVersion(): string
{
return $this->application->getVersion();
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Service/DownloadManager.php | src/Service/DownloadManager.php | <?php
namespace App\Service;
use App\DTO\DownloadableItem;
use Symfony\Component\HttpClient\Exception\ClientException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\HttpClient\ResponseStreamInterface;
final class DownloadManager
{
private const BASE_URL = 'https://embed.gog.com';
public function __construct(
private readonly HttpClientInterface $httpClient,
private readonly AuthenticationManager $authentication,
) {
}
public function getDownloadUrl(
DownloadableItem $download
): string {
if (str_starts_with($download->url, '/')) {
return self::BASE_URL . $download->url;
}
return $download->url;
}
public function getFilename(
DownloadableItem $download,
int $httpTimeout = 3
): ?string {
$url = $this->getRealDownloadUrl($download, $httpTimeout);
if (!$url) {
return null;
}
return urldecode(pathinfo($url, PATHINFO_BASENAME));
}
public function download(
DownloadableItem $download,
callable $callback,
?int $startAt = null,
int $httpTimeout = 3,
array $curlOptions = [],
): ResponseStreamInterface {
$url = $this->getRealDownloadUrl($download, $httpTimeout);
$headers = [];
if ($startAt !== null) {
$headers['Range'] = "bytes={$startAt}-";
}
$response = $this->httpClient->request(
Request::METHOD_GET,
$url,
[
'on_progress' => $callback,
'auth_bearer' => (string) $this->authentication->getAuthorization(),
'headers' => $headers,
'timeout' => $httpTimeout,
'extra' => [
'curl' => $curlOptions,
],
],
);
return $this->httpClient->stream($response);
}
private function getRealDownloadUrl(
DownloadableItem $download,
int $httpTimeout = 3
): ?string {
if (str_starts_with($download->url, '/')) {
$response = $this->httpClient->request(
Request::METHOD_HEAD,
$this->getDownloadUrl($download),
[
'auth_bearer' => (string) $this->authentication->getAuthorization(),
'max_redirects' => 0,
'timeout' => $httpTimeout,
]
);
return $response->getHeaders(false)['location'][0] ?? null;
}
$response = $this->httpClient->request(
Request::METHOD_GET,
$this->getDownloadUrl($download),
[
'auth_bearer' => (string) $this->authentication->getAuthorization(),
'max_redirects' => 0,
'timeout' => $httpTimeout,
]
);
try {
$content = json_decode($response->getContent(), true);
} catch (ClientException $e) {
if ($e->getResponse()->getStatusCode() !== Response::HTTP_NOT_FOUND) {
throw $e;
}
return null;
}
return $content['downlink'] ?? null;
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Service/RetryService.php | src/Service/RetryService.php | <?php
namespace App\Service;
use App\Exception\RetryAwareException;
use App\Exception\TooManyRetriesException;
use Exception;
use Throwable;
final readonly class RetryService
{
public function __construct(
private bool $debug,
) {
}
/**
* @throws TooManyRetriesException
* @throws Exception
*/
public function retry(callable $callable, int $maxRetries, int $retryDelay, ?array $exceptions = null, ?array $ignoreExceptions = null): void
{
$retries = 0;
$thrown = [];
do {
try {
$callable(count($thrown) ? $thrown[array_key_last($thrown)] : null);
return;
} catch (Exception $e) {
$thrown[] = $e;
++$retries;
if (!$this->matches($e, $exceptions)) {
throw $e;
}
if ($ignoreExceptions && $this->matches($e, $ignoreExceptions)) {
throw $e;
}
if ($e instanceof RetryAwareException) {
$retries = $e->modifyTryNumber($retries);
$tempRetryDelay = $e->modifyDelay($retryDelay);
if ($tempRetryDelay) {
sleep($tempRetryDelay);
}
} else {
sleep($retryDelay);
}
}
} while ($retries < $maxRetries);
if ($this->debug && count($thrown)) {
throw $thrown[array_key_last($thrown)];
}
throw new TooManyRetriesException($thrown, 'The operation has been retried too many times, cancelling');
}
/**
* @param Throwable $e
* @param string[] $exceptions
*
* @return bool
*/
private function matches(Throwable $e, ?array $exceptions): bool
{
if ($exceptions === null) {
return true;
}
foreach ($exceptions as $exception) {
if (is_a($e, $exception)) {
return true;
}
}
return false;
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Service/CloudSavesManager.php | src/Service/CloudSavesManager.php | <?php
namespace App\Service;
use App\DTO\GameDetail;
use App\DTO\GameInfo;
use App\DTO\SaveFileContent;
use App\DTO\SaveGameFile;
use DateInterval;
use Psr\Cache\CacheItemPoolInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Contracts\HttpClient\HttpClientInterface;
final readonly class CloudSavesManager
{
private const BASE_URL = 'https://cloudstorage.gog.com/v1';
public function __construct(
private AuthenticationManager $authenticationManager,
private HttpClientInterface $httpClient,
private GameMetadataManager $gameMetadataManager,
private string $userAgent,
private Serializer $serializer,
private CacheItemPoolInterface $cache,
) {
}
public function supports(GameInfo|GameDetail $game): bool
{
$cacheItem = $this->cache->getItem("game.saves.supported.{$game->id}");
if ($cacheItem->isHit()) {
return $cacheItem->get();
}
$oauth = $this->gameMetadataManager->getGameOAuthCredentials($game);
if ($oauth === null) {
return false;
}
$url = "https://remote-config.gog.com/components/galaxy_client/clients/{$oauth->clientId}?component_version=2.0.43";
$response = $this->httpClient->request(
Request::METHOD_GET,
$url,
);
$json = json_decode($response->getContent(), true);
$supported = ($json['content']['cloudStorage']['quota'] ?? 0) > 0;
$cacheItem->set($supported);
$cacheItem->expiresAfter(new DateInterval('P1D'));
$this->cache->save($cacheItem);
return $supported;
}
/**
* @return array<SaveGameFile>
*/
public function getGameSaves(GameInfo|GameDetail $game, bool $includeDeleted = false): array
{
$oauth = $this->gameMetadataManager->getGameOAuthCredentials($game);
$credentials = $this->gameMetadataManager->getGameAccessKey($game);
$url = sprintf(
'%s/%s/%s',
self::BASE_URL,
$this->authenticationManager->getUserInfo()->galaxyUserId,
$oauth->clientId,
);
$response = $this->httpClient->request(
Request::METHOD_GET,
$url,
[
'auth_bearer' => (string) $credentials,
'headers' => [
'Accept' => 'application/json',
'User-Agent' => "{$this->userAgent} dont_sync_marker/true",
],
],
);
$json = json_decode($response->getContent(), true);
return array_filter(
array_map(
fn (array $saveFile) => $this->serializer->deserialize($saveFile, SaveGameFile::class),
$json,
),
fn (SaveGameFile $saveFile) => $includeDeleted || !$saveFile->isDeleted(),
);
}
public function downloadSave(SaveGameFile $file, GameDetail|GameInfo $game): SaveFileContent
{
$oauth = $this->gameMetadataManager->getGameOAuthCredentials($game);
$credentials = $this->gameMetadataManager->getGameAccessKey($game);
$url = sprintf(
'%s/%s/%s/%s',
self::BASE_URL,
$this->authenticationManager->getUserInfo()->galaxyUserId,
$oauth->clientId,
str_replace('#', '%23', $file->name),
);
$response = $this->httpClient->request(
Request::METHOD_GET,
$url,
[
'auth_bearer' => (string) $credentials,
'headers' => [
'User-Agent' => "{$this->userAgent} dont_sync_marker/true",
'Accept-Encoding' => 'deflate, gzip',
],
],
);
$raw = $response->getContent();
$hash = md5($raw);
return new SaveFileContent(
hash: $hash,
content: gzdecode($raw),
);
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Service/Serializer.php | src/Service/Serializer.php | <?php
namespace App\Service;
use App\Attribute\ArrayType;
use App\Attribute\SerializedName;
use App\DTO\MultipleValuesWrapper;
use App\DTO\Serializer\Property;
use App\Service\Serializer\SerializerNormalizer;
use Error;
use JsonException;
use ReflectionClass;
use ReflectionException;
use ReflectionObject;
use ReflectionProperty;
use Traversable;
final class Serializer
{
/**
* @param iterable<SerializerNormalizer> $normalizers
*/
public function __construct(
private readonly iterable $normalizers,
) {
}
/**
* @template T
*
* @param class-string<T> $targetClass
*
* @throws JsonException
* @throws ReflectionException
*
* @return T|MultipleValuesWrapper
*/
public function deserialize(string|array $json, string $targetClass, array $context = []): object
{
if (is_string($json)) {
$json = json_decode($json, true, flags: JSON_THROW_ON_ERROR);
}
$object = $this->getObject($targetClass);
if ($normalizer = $this->findNormalizer($object)) {
return $normalizer->normalize($json, $context, $this);
} else {
foreach ($this->getProperties($object) as $property) {
$this->setProperty(
$property,
$object,
$json[$property->serializedName] ?? $context[$property->name] ?? null,
);
}
}
return $object;
}
/**
* @template T
*
* @param class-string<T> $targetClass
*
* @throws ReflectionException
*
* @return T
*/
private function getObject(string $targetClass): object
{
try {
$object = new $targetClass;
} catch (Error) {
$reflection = new ReflectionClass($targetClass);
$object = $reflection->newInstanceWithoutConstructor();
}
return $object;
}
/**
* @param object $object
*
* @return iterable<Property>
*/
private function getProperties(object $object): iterable
{
$reflection = new ReflectionObject($object);
foreach ($reflection->getProperties() as $property) {
$attributes = $property->getAttributes(SerializedName::class);
$nameAttribute = null;
if (count($attributes)) {
$nameAttribute = $attributes[array_key_first($attributes)]->newInstance();
assert($nameAttribute instanceof SerializedName);
}
yield new Property(
$property->getName(),
$nameAttribute ? $nameAttribute->name : $property->getName(),
);
}
}
/**
* @throws ReflectionException
*/
private function setProperty(Property $property, object $object, mixed $value): void
{
$reflection = new ReflectionProperty($object, $property->name);
if ($attributes = $reflection->getAttributes(ArrayType::class)) {
$attribute = $attributes[array_key_first($attributes)]->newInstance();
assert($attribute instanceof ArrayType);
if (class_exists($attribute->type)) {
$result = [];
foreach ($value as $item) {
$deserialized = $this->deserialize($item, $attribute->type);
if ($deserialized instanceof MultipleValuesWrapper) {
$result = [...$result, ...$deserialized];
continue;
}
if ($deserialized instanceof Traversable) {
$deserialized = iterator_to_array($item);
}
$result[] = $deserialized;
}
$value = $result;
}
}
if ($value === null && $reflection->getType() && !$reflection->getType()->allowsNull()) {
return;
}
$reflection->setValue($object, $value);
}
private function findNormalizer(object $object): ?SerializerNormalizer
{
foreach ($this->normalizers as $normalizer) {
if ($normalizer->supports($object::class)) {
return $normalizer;
}
}
return null;
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Service/Persistence/PersistenceManagerSqlite.php | src/Service/Persistence/PersistenceManagerSqlite.php | <?php
namespace App\Service\Persistence;
use App\DTO\Authorization;
use App\DTO\GameDetail;
use App\Enum\Setting;
use App\Service\MigrationManager;
use App\Service\Serializer;
use DateTimeImmutable;
use JetBrains\PhpStorm\ExpectedValues;
use PDO;
final class PersistenceManagerSqlite extends AbstractPersistenceManager
{
private const DATABASE = 'gog-downloader.db';
public function __construct(
private readonly MigrationManager $migrationManager,
private readonly Serializer $serializer,
) {
}
public function getAuthorization(): ?Authorization
{
$pdo = $this->getPdo(self::DATABASE);
$this->migrationManager->apply($pdo);
$result = $pdo->query('select * from auth');
if ($result === false) {
return null;
}
$result = $result->fetch(PDO::FETCH_ASSOC);
if ($result === false) {
return null;
}
return new Authorization(
$result['token'],
$result['refreshToken'],
new DateTimeImmutable($result['validUntil']),
);
}
public function saveAuthorization(?Authorization $authorization): self
{
$pdo = $this->getPdo(self::DATABASE);
$this->migrationManager->apply($pdo);
$pdo->exec('DELETE FROM auth');
if ($authorization === null) {
return $this;
}
$prepared = $pdo->prepare('INSERT INTO auth (token, refreshToken, validUntil) VALUES (?, ?, ?)');
$prepared->execute([
$authorization->token,
$authorization->refreshToken,
$authorization->validUntil->format('c'),
]);
return $this;
}
/**
* @param array<GameDetail> $details
*/
public function storeLocalGameData(array $details): void
{
$pdo = $this->getPdo(self::DATABASE);
$this->migrationManager->apply($pdo);
$pdo->exec('DELETE FROM games');
foreach ($details as $detail) {
$this->storeSingleGameDetail($detail);
}
}
/**
* @return array<GameDetail>|null
*/
public function getLocalGameData(): ?array
{
$pdo = $this->getPdo(self::DATABASE);
$this->migrationManager->apply($pdo);
$query = $pdo->query('select * from games');
if ($query === false) {
return null;
}
$result = [];
while ($next = $query->fetch(PDO::FETCH_ASSOC)) {
$downloadsQuery = $pdo->prepare('select * from downloads where game_id = ?');
$downloadsQuery->execute([$next['id']]);
$downloads = $downloadsQuery->fetchAll(PDO::FETCH_ASSOC);
$extrasQuery = $pdo->prepare('select * from game_extras where game_id = ?');
$extrasQuery->execute([$next['id']]);
$extras = $extrasQuery->fetchAll(PDO::FETCH_ASSOC);
$result[] = $this->serializer->deserialize([
'id' => $next['game_id'],
'title' => $next['title'],
'cdKey' => $next['cd_key'] ?? '',
'downloads' => $downloads,
'slug' => $next['slug'] ?? '',
'extras' => $extras,
], GameDetail::class);
}
return $result;
}
public function storeSingleGameDetail(GameDetail $detail): void
{
$pdo = $this->getPdo(self::DATABASE);
$this->migrationManager->apply($pdo);
$pdo->prepare(
'insert into games (title, cd_key, game_id, slug)
VALUES (?, ?, ?, ?)
ON CONFLICT DO UPDATE SET title = excluded.title,
cd_key = excluded.cd_key,
game_id = excluded.game_id,
slug = excluded.slug
'
)->execute([
$detail->title,
$detail->cdKey ?: null,
$detail->id,
$detail->slug,
]);
$query = $pdo->prepare('select id from games where game_id = ?');
$query->execute([$detail->id]);
$id = $query->fetch(PDO::FETCH_ASSOC)['id'];
$pdo->prepare('delete from downloads where game_id = ?')->execute([$id]);
foreach ($detail->downloads as $download) {
$pdo->prepare('insert into downloads (language, platform, name, size, url, md5, game_id, gog_game_id, is_patch) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)')->execute([
$download->language,
$download->platform,
$download->name,
$download->size,
$download->url,
$download->md5,
$id,
$download->gogGameId,
(int) $download->isPatch,
]);
}
foreach ($detail->extras as $extra) {
$pdo->prepare('insert into game_extras (extra_id, name, size, url, gog_game_id, game_id, md5)
values (?, ?, ?, ?, ?, ?, ?)
on conflict (extra_id) do update set name = excluded.name,
size = excluded.size,
url = excluded.url,
gog_game_id = excluded.gog_game_id,
game_id = excluded.game_id,
md5 = excluded.md5
')->execute([
$extra->id,
$extra->name,
$extra->size,
$extra->url,
$extra->gogGameId,
$id,
$extra->md5,
]);
}
}
public function storeSetting(Setting $setting, float|bool|int|string|null $value): void
{
$pdo = $this->getPdo(self::DATABASE);
$this->migrationManager->apply($pdo);
$settingName = $setting->value;
$preparedSelect = $pdo->prepare('select count(id) from settings where setting = ?');
$preparedSelect->bindParam(1, $settingName);
$preparedSelect->execute();
$result = $preparedSelect->fetch(PDO::FETCH_NUM);
if (!$result[0]) {
$prepared = $pdo->prepare('insert into settings (setting, value) VALUES (?, ?)');
$prepared->execute([
$setting->value,
json_encode($value),
]);
} else {
$prepared = $pdo->prepare('update settings set value = ? where setting = ?');
$prepared->execute([
json_encode($value),
$setting->value,
]);
}
}
public function getSetting(Setting $setting): int|string|float|bool|null
{
$pdo = $this->getPdo(self::DATABASE);
$this->migrationManager->apply($pdo);
$settingName = $setting->value;
$prepared = $pdo->prepare('select value from settings where setting = ?');
$prepared->bindParam(1, $settingName);
$prepared->execute();
$result = $prepared->fetch(PDO::FETCH_ASSOC);
return isset($result['value']) ? json_decode($result['value']) : null;
}
public function storeUncompressedHash(string $compressedHash, string $uncompressedHash): void
{
$pdo = $this->getPdo(self::DATABASE);
$this->migrationManager->apply($pdo);
$pdo->prepare('insert or ignore into compressed_file_hashes (compressed, uncompressed) values (?, ?)')->execute([
$compressedHash,
$uncompressedHash,
]);
}
public function getCompressedHash(string $uncompressedHash): ?string
{
$pdo = $this->getPdo(self::DATABASE);
$this->migrationManager->apply($pdo);
$query = $pdo->prepare('select compressed from compressed_file_hashes where uncompressed = ?');
$query->bindParam(1, $uncompressedHash);
$query->execute();
$result = $query->fetch();
return $result['compressed'] ?? null;
}
public function needsMigrating(bool $excludeEmpty = false): bool
{
$pdo = $this->getPdo(self::DATABASE);
$count = $this->migrationManager->countUnappliedMigrations($pdo);
if ($excludeEmpty && $count === $this->migrationManager->countAllMigrations()) {
return false;
}
return $count > 0;
}
private function getPdo(
#[ExpectedValues(valuesFromClass: self::class)]
string $file
): PDO {
$pdo = new PDO("sqlite:{$this->getFullPath($file)}");
$pdo->exec('PRAGMA foreign_keys = ON');
return $pdo;
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Service/Persistence/PersistenceManagerFiles.php | src/Service/Persistence/PersistenceManagerFiles.php | <?php
namespace App\Service\Persistence;
use App\DTO\Authorization;
use App\DTO\GameDetail;
use App\Enum\Setting;
use Error;
use ReflectionObject;
use Stringable;
final class PersistenceManagerFiles extends AbstractPersistenceManager
{
private const AUTH_FILE = 'auth.db';
private const GAME_FILE = 'games.db';
private const SETTINGS_FILE = 'settings.db';
private const HASHES_FILE = 'hashes.db';
public function getAuthorization(): ?Authorization
{
$file = $this->getFullPath(self::AUTH_FILE);
if (!file_exists($file)) {
return null;
}
$content = file_get_contents($file);
if ($content === false) {
return null;
}
return @unserialize($content) ?: null;
}
public function saveAuthorization(?Authorization $authorization): self
{
file_put_contents(
$this->getFullPath(self::AUTH_FILE),
$this->serialize($authorization),
);
return $this;
}
public function storeLocalGameData(array $details): void
{
file_put_contents(
$this->getFullPath(self::GAME_FILE),
$this->serialize($details),
);
}
public function getLocalGameData(): ?array
{
$file = $this->getFullPath(self::GAME_FILE);
if (!file_exists($file)) {
return null;
}
$content = file_get_contents($file);
if ($content === false) {
return null;
}
return @unserialize($content) ?: null;
}
public function storeSingleGameDetail(GameDetail $detail): void
{
$details = $this->getLocalGameData();
$details[] = $detail;
$this->storeLocalGameData($details);
}
public function storeSetting(Setting $setting, float|bool|int|string|null $value): void
{
$file = $this->getFullPath(self::SETTINGS_FILE);
$content = file_exists($file) ? json_decode(file_get_contents($file), true) : [];
$content[$setting->value] = $value;
file_put_contents($file, json_encode($content));
}
public function getSetting(Setting $setting): int|string|float|bool|null
{
$file = $this->getFullPath(self::SETTINGS_FILE);
if (!file_exists($file)) {
return null;
}
$content = json_decode(file_get_contents($file), true);
return $content[$setting->value] ?? null;
}
public function getCompressedHash(string $uncompressedHash): ?string
{
$file = $this->getFullPath(self::HASHES_FILE);
if (!file_exists($file)) {
return null;
}
$content = json_decode(file_get_contents($file), true);
return $content[$uncompressedHash] ?? null;
}
public function storeUncompressedHash(string $compressedHash, string $uncompressedHash): void
{
$file = $this->getFullPath(self::HASHES_FILE);
$content = file_exists($file) ? json_decode(file_get_contents($file), true) : [];
$content[$uncompressedHash] = $compressedHash;
file_put_contents($file, json_encode($content));
}
public function needsMigrating(bool $excludeEmpty = false): bool
{
return false;
}
private function serialize(mixed $itemToSerialize): string
{
return serialize($this->normalize($itemToSerialize));
}
/**
* @template T of mixed
*
* @param T $itemToNormalize
* @return T
*/
private function normalize(mixed $itemToNormalize): mixed
{
if (is_array($itemToNormalize)) {
foreach ($itemToNormalize as $key => $item) {
$itemToNormalize[$key] = $this->normalize($item);
}
return $itemToNormalize;
} else if (is_object($itemToNormalize)) {
$reflection = new ReflectionObject($itemToNormalize);
$copy = $reflection->newInstanceWithoutConstructor();
foreach ($reflection->getProperties() as $property) {
try {
$currentValue = $property->getValue($itemToNormalize);
if ($currentValue instanceof Stringable) {
$currentValue = (string) $currentValue;
} else if (is_array($currentValue)) {
$currentValue = $this->normalize($currentValue);
}
$property->setValue($copy, $currentValue);
} catch (Error) {
continue;
}
}
return $copy;
}
return $itemToNormalize;
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Service/Persistence/PersistenceManager.php | src/Service/Persistence/PersistenceManager.php | <?php
namespace App\Service\Persistence;
use App\DTO\Authorization;
use App\DTO\GameDetail;
use App\Enum\Setting;
interface PersistenceManager
{
public function getAuthorization(): ?Authorization;
public function saveAuthorization(?Authorization $authorization): self;
/**
* @param array<GameDetail> $details
*/
public function storeLocalGameData(array $details): void;
/**
* @return array<GameDetail>|null
*/
public function getLocalGameData(): ?array;
public function storeSingleGameDetail(GameDetail $detail): void;
public function storeSetting(Setting $setting, int|string|float|bool|null $value): void;
public function getSetting(Setting $setting): int|string|float|bool|null;
public function storeUncompressedHash(string $compressedHash, string $uncompressedHash): void;
public function getCompressedHash(string $uncompressedHash): ?string;
public function needsMigrating(bool $excludeEmpty = false): bool;
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Service/Persistence/AbstractPersistenceManager.php | src/Service/Persistence/AbstractPersistenceManager.php | <?php
namespace App\Service\Persistence;
abstract class AbstractPersistenceManager implements PersistenceManager
{
protected function getFullPath(string $file): string
{
return sprintf('%s/%s', $_ENV['CONFIG_DIRECTORY'] ?? getcwd(), $file);
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Service/Serializer/GameDetailNormalizer.php | src/Service/Serializer/GameDetailNormalizer.php | <?php
namespace App\Service\Serializer;
use App\DTO\GameInstaller;
use App\DTO\GameDetail;
use App\DTO\GameExtra;
use App\DTO\MultipleValuesWrapper;
use App\Service\Serializer;
final readonly class GameDetailNormalizer implements SerializerNormalizer
{
public function normalize(array $value, array $context, Serializer $serializer): GameDetail
{
if (!isset($value['downloads']['installers'])) {
$finalDownloads = array_map(
fn (array $download) => $serializer->deserialize($download, GameInstaller::class),
$value['downloads'],
);
} else {
$patches = array_map(
function (array $patch): array {
$patch['is_patch'] = true;
return $patch;
},
$value['downloads']['patches'] ?? [],
);
$sourceDownloads = [
...$value['downloads']['installers'],
...$patches,
...$value['downloads']['language_packs'],
];
$downloads = [];
foreach ($sourceDownloads as $download) {
$download['gogGameId'] = $context['id'];
$downloads[] = $serializer->deserialize($download, GameInstaller::class);
}
foreach ($value['expanded_dlcs'] ?? [] as $dlc) {
foreach ($dlc['downloads']['installers'] as $download) {
$download['gogGameId'] = $dlc['id'];
$downloads[] = $serializer->deserialize($download, GameInstaller::class);
}
}
$finalDownloads = [];
foreach ($downloads as $download) {
if ($download instanceof MultipleValuesWrapper) {
$finalDownloads = [...$finalDownloads, ...$download];
} else {
$finalDownloads[] = $download;
}
}
}
$extras = [];
foreach ($value['extras'] ?? $value['downloads']['bonus_content'] ?? [] as $extra) {
$extra['gogGameId'] ??= $value['id'] ?? $context['id'];
$extras[] = $serializer->deserialize($extra, GameExtra::class);
}
$finalExtras = [];
foreach ($extras as $key => $extra) {
if ($extra instanceof MultipleValuesWrapper) {
unset($extras[$key]);
$finalExtras = [...$finalExtras, ...$extra];
} else {
$finalExtras[] = $extra;
}
}
return new GameDetail(
id: $value['id'] ?? $context['id'],
title: $value['title'],
cdKey: '', // todo
downloads: $finalDownloads,
slug: $value['slug'] ?? $context['slug'],
extras: $finalExtras,
);
}
public function supports(string $class): bool
{
return is_a($class, GameDetail::class, true);
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Service/Serializer/GameInstallerNormalizer.php | src/Service/Serializer/GameInstallerNormalizer.php | <?php
namespace App\Service\Serializer;
use App\DTO\GameInstaller;
use App\DTO\MultipleValuesWrapper;
use App\Service\Serializer;
use ReflectionProperty;
use RuntimeException;
final class GameInstallerNormalizer implements SerializerNormalizer
{
public function __construct(
) {
}
public function normalize(array $value, array $context, Serializer $serializer): MultipleValuesWrapper|GameInstaller
{
if (array_key_exists('version', $value)) {
$results = [];
foreach ($value['files'] as $file) {
$results[] = new GameInstaller(
language: $value['language'],
platform: $value['os'],
name: $value['name'],
size: $file['size'],
url: $file['downlink'],
md5: null,
gogGameId: $value['gogGameId'] ?? null,
isPatch: $value['is_patch'] ?? false,
);
}
return new MultipleValuesWrapper($results);
}
if (isset($value['game_id'])) {
return new GameInstaller(
language: $value['language'],
platform: $value['platform'],
name: $value['name'],
size: $value['size'],
url: $value['url'],
md5: $value['md5'],
gogGameId: $value['gog_game_id'] ?? null,
isPatch: $value['is_patch'] ?? false,
);
}
throw new RuntimeException('Invalid download description');
}
public function supports(string $class): bool
{
return $class === GameInstaller::class;
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Service/Serializer/GameExtraNormalizer.php | src/Service/Serializer/GameExtraNormalizer.php | <?php
namespace App\Service\Serializer;
use App\DTO\GameExtra;
use App\DTO\MultipleValuesWrapper;
use App\Service\OwnedItemsManager;
use App\Service\Serializer;
use ReflectionProperty;
use Symfony\Component\HttpClient\Exception\ClientException;
use Symfony\Component\HttpFoundation\Response;
final readonly class GameExtraNormalizer implements SerializerNormalizer
{
public function __construct(
private OwnedItemsManager $ownedItemsManager,
) {
}
public function normalize(array $value, array $context, Serializer $serializer): MultipleValuesWrapper|GameExtra
{
if (isset($value['total_size'])) {
$result = [];
foreach ($value['files'] as $file) {
$extra = new GameExtra(
id: $value['id'],
name: $value['name'],
size: $file['size'],
url: $file['downlink'],
gogGameId: $value['gogGameId'],
md5: null,
);
try {
$md5 = $this->ownedItemsManager->getChecksum($extra, null, 10);
new ReflectionProperty($extra, 'md5')->setValue($extra, $md5);
} catch (ClientException $e) {
if ($e->getCode() !== Response::HTTP_FORBIDDEN && $e->getCode() !== Response::HTTP_NOT_FOUND) {
throw $e;
}
continue;
}
$result[] = $extra;
}
return new MultipleValuesWrapper($result);
}
return new GameExtra(
id: $value['extra_id'],
name: $value['name'],
size: $value['size'],
url: $value['url'],
gogGameId: $value['gog_game_id'],
md5: $value['md5'],
);
}
public function supports(string $class): bool
{
return is_a($class, GameExtra::class, true);
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Service/Serializer/MultipleValuesNormalizer.php | src/Service/Serializer/MultipleValuesNormalizer.php | <?php
namespace App\Service\Serializer;
use App\DTO\MultipleValuesWrapper;
use App\Service\Serializer;
interface MultipleValuesNormalizer extends SerializerNormalizer
{
public function normalize(array $value, array $context, Serializer $serializer): MultipleValuesWrapper;
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Service/Serializer/SerializerNormalizer.php | src/Service/Serializer/SerializerNormalizer.php | <?php
namespace App\Service\Serializer;
use App\Service\Serializer;
interface SerializerNormalizer
{
public function normalize(array $value, array $context, Serializer $serializer): mixed;
/**
* @param class-string<object> $class
*/
public function supports(string $class): bool;
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Service/FileWriter/FileWriterLocator.php | src/Service/FileWriter/FileWriterLocator.php | <?php
namespace App\Service\FileWriter;
use RuntimeException;
final readonly class FileWriterLocator
{
/**
* @param iterable<FileWriter> $writers
*/
public function __construct(
private iterable $writers,
) {
}
public function getWriter(string $directory): FileWriter
{
foreach ($this->writers as $writer) {
if ($writer->supports($directory)) {
return $writer;
}
}
throw new RuntimeException("There's not handler that knows how to write to the directory '{$directory}'");
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Service/FileWriter/StreamWrapperFileWriter.php | src/Service/FileWriter/StreamWrapperFileWriter.php | <?php
namespace App\Service\FileWriter;
use App\DTO\FileWriter\StreamWrapperFileReference;
use App\Exception\UnreadableFileException;
use HashContext;
use Symfony\Component\DependencyInjection\Attribute\AsTaggedItem;
/**
* @implements FileWriter<StreamWrapperFileReference>
*/
#[AsTaggedItem(priority: -10)]
final readonly class StreamWrapperFileWriter implements FileWriter
{
public function supports(string $path): bool
{
$regex = /** @lang RegExp */ '@^([a-zA-Z0-9.]+)://.+@';
if (!preg_match($regex, $path, $matches)) {
return true;
}
$wrapper = $matches[1];
$availableWrappers = stream_get_wrappers();
return in_array($wrapper, $availableWrappers, true);
}
public function getFileReference(string $path): object
{
return new StreamWrapperFileReference($path);
}
public function exists(string|object $file): bool
{
if (!is_string($file)) {
$file = $file->path;
}
return file_exists($file);
}
public function getSize(object $file): int
{
return filesize($file->path);
}
public function getMd5Hash(object $file): string
{
return md5_file($file->path);
}
public function writeChunk(object $file, string $data, int $chunkSize = self::DEFAULT_CHUNK_SIZE): void
{
$file->write($data);
}
public function createDirectory(string $path): void
{
mkdir($path, recursive: true);
}
public function getMd5HashContext(object $file): HashContext
{
if (!$this->isReadable($file)) {
throw new UnreadableFileException('The file reference is not readable.');
}
$hash = hash_init('md5');
if (!$this->exists($file)) {
return $hash;
}
$handle = $file->open();
rewind($handle);
while (!feof($handle)) {
hash_update($hash, fread($handle, 2 ** 23));
}
return $hash;
}
public function finalizeWriting(object $file, string $hash): void
{
}
public function remove(object $targetFile): void
{
unlink($targetFile->path);
}
public function isReadable(object $targetFile): bool
{
if (!$this->exists($targetFile)) {
return is_readable(dirname($targetFile->path));
}
return is_readable($targetFile->path);
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Service/FileWriter/FileWriter.php | src/Service/FileWriter/FileWriter.php | <?php
namespace App\Service\FileWriter;
use App\Exception\UnreadableFileException;
use HashContext;
use Symfony\Component\DependencyInjection\Attribute\AutoconfigureTag;
/**
* @template T of object
*/
#[AutoconfigureTag(name: 'app.file_writer')]
interface FileWriter
{
public const DEFAULT_CHUNK_SIZE = 2 ** 23;
public function supports(string $path): bool;
/**
* @return T
*/
public function getFileReference(string $path): object;
/**
* @param string|T $file
*/
public function exists(string|object $file): bool;
/**
* @param T $file
*/
public function getSize(object $file): int;
/**
* @param T $file
* @throws UnreadableFileException
*/
public function getMd5Hash(object $file): string;
public function createDirectory(string $path): void;
/**
* @param T $file
*/
public function writeChunk(object $file, string $data, int $chunkSize = self::DEFAULT_CHUNK_SIZE): void;
/**
* @param T $file
* @throws UnreadableFileException
*/
public function getMd5HashContext(object $file): HashContext;
/**
* @param T $file
*/
public function finalizeWriting(object $file, string $hash): void;
/**
* @param T $targetFile
*/
public function remove(object $targetFile): void;
/**
* @param T $targetFile
*/
public function isReadable(object $targetFile): bool;
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Service/FileWriter/S3FileWriter.php | src/Service/FileWriter/S3FileWriter.php | <?php
namespace App\Service\FileWriter;
use App\DTO\FileWriter\ExtractedS3Path;
use App\DTO\FileWriter\S3FileReference;
use App\Enum\S3StorageClass;
use App\Enum\Setting;
use App\Exception\InvalidConfigurationException;
use App\Exception\UnreadableFileException;
use App\Service\Persistence\PersistenceManager;
use Aws\S3\Exception\S3Exception;
use Aws\S3\S3Client;
use GuzzleHttp\Psr7\Stream;
use HashContext;
use LogicException;
/**
* @implements FileWriter<S3FileReference>
*/
final readonly class S3FileWriter implements FileWriter
{
public function __construct(
private S3Client $client,
private PersistenceManager $persistence,
) {
}
public function supports(string $path): bool
{
return str_starts_with($path, 's3://');
}
public function getFileReference(string $path): object
{
$extracted = $this->extractPath($path);
$storageClassRaw = $this->persistence->getSetting(Setting::S3StorageClass);
$storageClass = $storageClassRaw === null ? S3StorageClass::Standard : S3StorageClass::tryFrom($storageClassRaw);
if (!$storageClass) {
throw new InvalidConfigurationException("The configured storage class ({$storageClassRaw}) is not valid, please use one of: " . implode(
', ',
array_map(
fn (S3StorageClass $class) => $class->value,
S3StorageClass::cases(),
)
));
}
return new S3FileReference(
$extracted->bucket,
$extracted->key,
$storageClass,
);
}
public function exists(object|string $file): bool
{
if (!is_object($file)) {
$file = $this->getFileReference($file);
}
try {
return $this->client->doesObjectExistV2($file->bucket, $file->key);
} catch (S3Exception) {
return false;
}
}
public function getSize(object $file): int
{
$object = $this->client->headObject([
'Bucket' => $file->bucket,
'Key' => $file->key,
]);
return $object->get('ContentLength');
}
public function getMd5Hash(object $file): string
{
$object = $this->client->getObjectTagging([
'Bucket' => $file->bucket,
'Key' => $file->key,
]);
return array_find($object->get('TagSet'), function (array $tag): bool {
return $tag['Key'] === 'md5_hash';
})['Value'] ?? hash_final($this->getMd5HashContext($file));
}
public function createDirectory(string $path): void
{
}
public function writeChunk(object $file, string $data, int $chunkSize = self::DEFAULT_CHUNK_SIZE): void
{
$file->writeChunk($this->client, $data, $chunkSize);
}
public function getMd5HashContext(object $file): HashContext
{
if (!$this->isReadable($file)) {
throw new UnreadableFileException('The file reference is not readable.');
}
$hash = hash_init('md5');
if (!$this->exists($file)) {
return $hash;
}
$content = $this->client->getObject([
'Bucket' => $file->bucket,
'Key' => $file->key,
])->get('Body');
assert($content instanceof Stream);
$chunkSize = 2 ** 23;
while (!$content->eof()) {
hash_update($hash, $content->read($chunkSize));
}
return $hash;
}
public function finalizeWriting(object $file, string $hash): void
{
$file->finalize($hash);
}
public function remove(object $targetFile): void
{
$this->client->deleteObject([
'Bucket' => $targetFile->bucket,
'Key' => $targetFile->key,
]);
}
private function extractPath(string $path): ExtractedS3Path
{
$path = substr($path, strlen('s3://'));
$parts = explode('/', $path, 2);
return new ExtractedS3Path($parts[0], $parts[1]);
}
public function isReadable(object $targetFile): bool
{
if (!$this->exists($targetFile)) {
return true;
}
$head = $this->client->headObject([
'Bucket' => $targetFile->bucket,
'Key' => $targetFile->key,
]);
$storageClassName = $head->get('StorageClass') ?: S3StorageClass::Standard->value;
$storageClass = S3StorageClass::tryFrom($storageClassName);
if (!$storageClass) {
throw new LogicException("The remote file '{$targetFile->key}' at bucket '{$targetFile->bucket}' has an unsupported storage class: {$storageClassName}");
}
return in_array($storageClass, [
S3StorageClass::Standard,
S3StorageClass::StandardInfrequentAccess,
S3StorageClass::ExpressOneZone,
S3StorageClass::StandardInfrequentAccess,
S3StorageClass::OneZoneInfrequentAccess,
S3StorageClass::GlacierInstantRetrieval,
], true);
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Service/Factory/PersistenceManagerFactory.php | src/Service/Factory/PersistenceManagerFactory.php | <?php
namespace App\Service\Factory;
use App\Service\MigrationManager;
use App\Service\Persistence\PersistenceManager;
use App\Service\Persistence\PersistenceManagerFiles;
use App\Service\Persistence\PersistenceManagerSqlite;
use App\Service\Serializer;
use PDO;
use SQLite3;
final readonly class PersistenceManagerFactory
{
public function __construct(
private MigrationManager $migrationManager,
private Serializer $serializer,
) {
}
public function getPersistenceManager(): PersistenceManager
{
if (class_exists(PDO::class, false) && class_exists(SQLite3::class, false)) {
return new PersistenceManagerSqlite($this->migrationManager, $this->serializer);
}
return new PersistenceManagerFiles();
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Command/LoginCommand.php | src/Command/LoginCommand.php | <?php
namespace App\Command;
use App\Service\AuthenticationManager;
use App\Service\Persistence\PersistenceManager;
use App\Service\WebAuthentication;
use App\Trait\MigrationCheckerTrait;
use App\Validator\NonEmptyValidator;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
#[AsCommand('login')]
final class LoginCommand extends Command
{
use MigrationCheckerTrait;
public function __construct(
private readonly WebAuthentication $webAuthentication,
private readonly AuthenticationManager $authenticationManager,
private readonly PersistenceManager $persistence,
) {
parent::__construct();
}
protected function configure()
{
$this
->setDescription('Login via email and password. May fail due to recaptcha, prefer code login.')
->addArgument(
'email',
InputArgument::OPTIONAL,
'Email to log in as, if empty will be asked interactively',
)
->addOption(
'password',
null,
InputOption::VALUE_REQUIRED,
"Your password. It's recommended to let the app ask for your password interactively instead of specifying it here."
);
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$this->showInfoIfMigrationsAreNeeded($io, $this->persistence);
$email = $this->getEmail($io, $input);
$password = $this->getPassword($io, $input);
$code = $this->webAuthentication->getCode($email, $password);
if ($code === null) {
$io->error('Failed to login using email and password. Either the credentials are wrong or there was a recaptcha.');
return self::FAILURE;
}
$this->authenticationManager->codeLogin($code);
$io->success('Successfully logged in');
return self::SUCCESS;
}
private function getEmail(SymfonyStyle $io, InputInterface $input): string
{
if ($email = $input->getArgument('email')) {
return $email;
}
return $io->ask('Email', validator: new NonEmptyValidator());
}
private function getPassword(SymfonyStyle $io, InputInterface $input): string
{
if ($password = $input->getOption('password')) {
$io->warning("Don't forget to delete this command from your command history to avoid leaking your password!");
return $password;
}
return $io->askHidden('Password', validator: new NonEmptyValidator());
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Command/LanguagesCommand.php | src/Command/LanguagesCommand.php | <?php
namespace App\Command;
use App\Enum\Language;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
#[AsCommand('languages')]
final class LanguagesCommand extends Command
{
protected function configure()
{
$this
->setDescription('Lists all supported languages')
;
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$rows = [];
foreach (Language::cases() as $case) {
$rows[] = [
$case->value,
$case->name,
$case->getLocalName(),
];
}
$io->writeln('Please use the language code when filtering other commands by language (e.g. en, cz, jp)');
$io->table([
'Code',
'Machine name',
'Local name',
], $rows);
return self::SUCCESS;
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Command/ConfigCommand.php | src/Command/ConfigCommand.php | <?php
namespace App\Command;
use App\Enum\Setting;
use App\Service\Persistence\PersistenceManager;
use App\Trait\MigrationCheckerTrait;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
#[AsCommand('config', description: 'Configure various settings, like default location and so on')]
final class ConfigCommand extends Command
{
use MigrationCheckerTrait;
public function __construct(
private readonly PersistenceManager $persistence,
) {
parent::__construct();
}
protected function configure(): void
{
$possibleSettings = array_map(fn (Setting $setting) => $setting->value, Setting::cases());
$this
->addArgument(
'setting',
InputArgument::OPTIONAL,
'The name of the setting, possible values: ' . implode(', ', $possibleSettings),
null,
array_map(fn (Setting $setting) => $setting->value, Setting::cases()),
)
->addArgument(
'value',
InputArgument::OPTIONAL,
"The new value. If this argument is present a new value gets saved, if it's omitted the current value gets printed. Use a special value 'null' to reset the setting to default."
)
;
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$this->showInfoIfMigrationsAreNeeded($io, $this->persistence);
$settingName = $input->getArgument('setting');
if ($settingName === null) {
$rows = [];
foreach (Setting::cases() as $setting) {
$validValues = $setting->getValidValues();
if (is_callable($validValues)) {
$validValues = $validValues();
}
$rows[] = [
$setting->value,
$this->persistence->getSetting($setting) ?? '<error>-- no value --</error>',
$validValues === null ? '<comment>N/A</comment>' : implode(', ', $validValues),
];
}
$io->table(['Setting', 'Value', 'Valid values'], $rows);
return self::SUCCESS;
}
$setting = Setting::tryFrom($settingName);
if ($setting === null) {
$io->error("Invalid setting: '{$settingName}'");
return self::FAILURE;
}
$value = $input->getArgument('value');
if ($value !== null) {
if ($value === 'null') {
$value = null;
}
$validator = $setting->getValidator();
if (!$validator($value)) {
$io->error("The value '{$value}' is invalid for setting '{$setting->value}'.");
return self::FAILURE;
}
$this->persistence->storeSetting($setting, $value);
$io->success("Setting '{$setting->value}' successfully set.");
return self::SUCCESS;
}
$io->writeln($this->persistence->getSetting($setting) ?? '<error> -- no value -- </error>');
return self::SUCCESS;
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Command/LoginCodeCommand.php | src/Command/LoginCodeCommand.php | <?php
namespace App\Command;
use App\Exception\AuthenticationException;
use App\Service\AuthenticationManager;
use App\Service\Persistence\PersistenceManager;
use App\Service\WebAuthentication;
use App\Trait\MigrationCheckerTrait;
use App\Validator\NonEmptyValidator;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
#[AsCommand('code-login')]
final class LoginCodeCommand extends Command
{
use MigrationCheckerTrait;
public function __construct(
private readonly AuthenticationManager $authenticationManager,
private readonly PersistenceManager $persistence,
) {
parent::__construct();
}
protected function configure(): void
{
$this
->setDescription('Login using a code (for example when two-factor auth or recaptcha is required)')
->addArgument(
'code',
InputArgument::OPTIONAL,
'The login code or url. Treat the code as you would treat a password. Providing the code as an argument is not recommended.'
)
;
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$this->showInfoIfMigrationsAreNeeded($io, $this->persistence);
$io->writeln([
'',
sprintf('Visit %s and log in.', WebAuthentication::AUTH_URL),
"After you're logged in you should be redirected to a blank page, copy the address of the page and paste it here.",
]);
if (!$code = $input->getArgument('code')) {
$code = $io->ask('Code or web address', validator: new NonEmptyValidator());
}
$code = $this->getCode($code);
$this->authenticationManager->codeLogin($code);
$io->success('Logged in successfully.');
return self::SUCCESS;
}
private function getCode(string $code): string
{
if (!str_starts_with($code, 'https://')) {
return $code;
}
$query = parse_url($code, PHP_URL_QUERY);
parse_str($query, $queryParams);
if (!isset($queryParams['code'])) {
throw new AuthenticationException('The URL does not contain a valid code.');
}
return $queryParams['code'];
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Command/DownloadCommand.php | src/Command/DownloadCommand.php | <?php
namespace App\Command;
use App\DTO\GameInstaller;
use App\DTO\GameExtra;
use App\Enum\Language;
use App\Enum\NamingConvention;
use App\Enum\Setting;
use App\Exception\ExitException;
use App\Exception\ForceRetryException;
use App\Exception\InvalidValueException;
use App\Exception\RetryDownloadForUnmatchingHashException;
use App\Exception\TooManyRetriesException;
use App\Exception\UnreadableFileException;
use App\Helper\LatelyBoundStringValue;
use App\Service\DownloadManager;
use App\Service\FileWriter\FileWriterLocator;
use App\Service\Iterables;
use App\Service\OwnedItemsManager;
use App\Service\Persistence\PersistenceManager;
use App\Service\RetryService;
use App\Trait\CommonOptionsTrait;
use App\Trait\EnumExceptionParserTrait;
use App\Trait\FilteredGamesResolverTrait;
use App\Trait\MigrationCheckerTrait;
use App\Trait\TargetDirectoryTrait;
use InvalidArgumentException;
use RuntimeException;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\ProgressBar;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\HttpClient\Exception\ClientException;
use Symfony\Component\HttpFoundation\Response;
use Throwable;
#[AsCommand('download')]
final class DownloadCommand extends Command
{
use TargetDirectoryTrait;
use EnumExceptionParserTrait;
use CommonOptionsTrait;
use FilteredGamesResolverTrait;
use MigrationCheckerTrait;
private bool $canKillSafely = true;
private bool $exitRequested = false;
public function __construct(
private readonly OwnedItemsManager $ownedItemsManager,
private readonly DownloadManager $downloadManager,
private readonly Iterables $iterables,
private readonly RetryService $retryService,
private readonly PersistenceManager $persistence,
private readonly FileWriterLocator $writerLocator,
) {
parent::__construct();
}
protected function configure()
{
$this
->setDescription('Downloads all files from the local database (see update command). Can resume downloads unless --no-verify is specified.')
->addArgument(
'directory',
InputArgument::OPTIONAL,
'The target directory.',
)
->addOption(
'no-verify',
null,
InputOption::VALUE_NONE,
'Set this flag to disable verification of file content before downloading. Disables resuming of downloads.'
)
->addOsFilterOption()
->addLanguageFilterOption()
->addLanguageFallbackEnglishOption()
->addUpdateOption()
->addExcludeLanguageOption()
->addHttpRetryOption()
->addHttpRetryDelayOption()
->addSkipHttpErrorsOption()
->addHttpIdleTimeoutOption()
->addOption(
name: 'chunk-size',
mode: InputOption::VALUE_REQUIRED,
description: 'The chunk size in MB. Some file providers support sending parts of a file, this options sets the size of a single part. Cannot be lower than 5',
default: 10,
)
->addGameNameFilterOption()
->addExcludeGameNameFilterOption()
->addOption(
name: 'bandwidth',
shortcut: 'b',
mode: InputOption::VALUE_REQUIRED,
description: 'Specify the maximum download speed in bytes. You can use the k postfix for kilobytes or m postfix for megabytes (for example 200k or 4m to mean 200 kilobytes and 4 megabytes respectively)',
)
->addOption(
name: 'extras',
shortcut: 'e',
mode: InputOption::VALUE_NONE,
description: 'Whether to include extras or not.',
)
->addOption(
name: 'skip-existing-extras',
mode: InputOption::VALUE_NONE,
description: "Unlike games, extras generally don't have a hash that can be used to check whether the downloaded content is the same as the remote one, meaning by default extras will be downloaded every time, even if they exist. By providing this flag, you will skip existing extras."
)
->addOption(
name: 'no-games',
mode: InputOption::VALUE_NONE,
description: 'Skip downloading games and patches. Should be used with other options like --extras if you want to only download those.'
)
->addOption(
name: 'no-patches',
mode: InputOption::VALUE_NONE,
description: 'Skip downloading patches.',
)
->addOption(
name: 'skip-download',
mode: InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY,
description: 'Skip a download by its name, can be specified multiple times.'
)
->addOption(
name: 'remove-invalid',
mode: InputOption::VALUE_NONE,
description: 'Remove downloaded files that failed hash check and try downloading it again.'
)
;
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$this->showInfoIfMigrationsAreNeeded($io, $this->persistence);
if ($this->persistence->getSetting(Setting::NamingConvention) === NamingConvention::Custom->value) {
$io->warning("You're using the deprecated custom naming convention for game directories. To migrate your game directory to the new naming convention, please use the command 'migrate-naming-scheme'.");
}
try {
$this->handleSignals($io);
$chunkSize = $input->getOption('chunk-size') * 1024 * 1024;
if ($chunkSize < 5 * 1024 * 1024) {
$io->error('The chunk size cannot be lower than 5 MB.');
return self::FAILURE;
}
$this->dispatchSignals();
$englishFallback = $input->getOption('language-fallback-english');
$languages = $this->getLanguages($input);
if ($languages && !in_array(Language::English, $languages, true) && !$englishFallback) {
$io->warning("GOG often has multiple language versions inside the English one. Those game files will be skipped. Specify --language-fallback-english to include English versions if your language's version doesn't exist.");
}
if ($input->getOption('update') && $output->isVerbose()) {
$io->info('The --update flag specified, skipping local database and downloading metadata anew');
}
$timeout = $input->getOption('idle-timeout');
$noVerify = $input->getOption('no-verify');
$skipExistingExtras = $input->getOption('skip-existing-extras');
$iterable = $this->getGames($input, $output, $this->ownedItemsManager);
$downloadsToSkip = $input->getOption('skip-download');
$removeInvalid = $input->getOption('remove-invalid');
$withoutGames = $input->getOption('no-games');
$withoutPatches = $input->getOption('no-patches');
$includeExtras = $input->getOption('extras');
$this->dispatchSignals();
foreach ($iterable as $game) {
$downloads = [];
if (!$withoutGames) {
$downloads = [...$downloads, ...$game->downloads];
}
if ($includeExtras) {
$downloads = [...$downloads, ...$game->extras];
}
if ($withoutPatches) {
$downloads = array_values(array_filter(
$downloads,
fn (GameInstaller|GameExtra $download) => $download instanceof GameExtra || !$download->isPatch,
));
}
foreach ($downloads as $download) {
try {
$this->retryService->retry(function (?Throwable $retryReason) use (
$removeInvalid,
$downloadsToSkip,
$skipExistingExtras,
$chunkSize,
$timeout,
$noVerify,
$game,
$input,
$englishFallback,
$output,
$download,
$io,
) {
assert($download instanceof GameInstaller || $download instanceof GameExtra);
$downloadTag = new LatelyBoundStringValue(function () use ($download, $game) {
if ($download instanceof GameInstaller) {
return "[{$game->title}] {$download->name} ({$download->platform}, {$download->language})";
} else if ($download instanceof GameExtra) {
return "[{$game->title}] {$download->name} (extra)";
}
throw new RuntimeException('Uncovered download type');
});
if (in_array($download->name, $downloadsToSkip, true)) {
if ($output->isVerbose()) {
$io->writeln("{$downloadTag}: Skipping because it's specified using the --skip-download flag");
}
return;
}
$this->canKillSafely = false;
$this->dispatchSignals();
$progress = $io->createProgressBar();
$progress->setMessage('Starting...');
ProgressBar::setPlaceholderFormatterDefinition(
'bytes_current',
$this->getBytesCallable($progress->getProgress(...)),
);
ProgressBar::setPlaceholderFormatterDefinition(
'bytes_total',
$this->getBytesCallable($progress->getMaxSteps(...)),
);
$format = ' %bytes_current% / %bytes_total% [%bar%] %percent:3s%% - %message%';
$progress->setFormat($format);
$targetDir = $this->getTargetDir($input, $game, download: $download);
$writer = $this->writerLocator->getWriter($targetDir);
if (!$writer->exists($targetDir)) {
$writer->createDirectory($targetDir);
}
$filename = $this->downloadManager->getFilename($download, $timeout);
if (!$filename) {
throw new RuntimeException("{$downloadTag}: Failed getting the filename for {$download->name}");
}
if ($download instanceof GameExtra) {
$filename = "extras/{$filename}";
}
$targetFile = $writer->getFileReference("{$targetDir}/{$filename}");
$startAt = null;
if (
(
$download->md5
|| $noVerify
|| ($download instanceof GameExtra && $skipExistingExtras)
)
&& $writer->exists($targetFile)
) {
try {
$md5 = $noVerify ? '' : $writer->getMd5Hash($targetFile);
} catch (UnreadableFileException) {
$io->warning("{$downloadTag}: Tried to get existing hash of {$download->name}, but the file is not readable. It will be downloaded again");
$md5 = '';
}
if (!$noVerify && $download->md5 === $md5) {
if ($output->isVerbose()) {
$io->writeln(
"{$downloadTag}: Skipping because it exists and is valid",
);
}
return;
} elseif ($download instanceof GameExtra && $skipExistingExtras) {
if ($output->isVerbose()) {
$io->writeln("{$downloadTag}: Skipping because it exists (--skip-existing-extras specified, not checking content)");
}
return;
} elseif ($noVerify) {
if ($output->isVerbose()) {
$io->writeln("{$downloadTag}: Skipping because it exists (--no-verify specified, not checking content)");
}
return;
}
$startAt = $writer->isReadable($targetFile) ? $writer->getSize($targetFile) : null;
}
$progress->setMaxSteps(0);
$progress->setProgress(0);
$progress->setMessage($downloadTag);
$curlOptions = [];
if ($input->getOption('bandwidth') && defined('CURLOPT_MAX_RECV_SPEED_LARGE')) {
if (defined('CURLOPT_MAX_RECV_SPEED_LARGE')) {
$curlOptions[CURLOPT_MAX_RECV_SPEED_LARGE] = $this->parseBandwidth($input->getOption('bandwidth'));
} else {
$io->warning("Warning: You have specified a maximum bandwidth, but that's only available if your system has the PHP curl extension installed. Ignoring maximum bandwidth settings.");
}
}
$responses = $this->downloadManager->download(
download: $download,
callback: function (int $current, int $total) use ($startAt, $progress, $output) {
if ($total > 0) {
$progress->setMaxSteps($total + ($startAt ?? 0));
$progress->setProgress($current + ($startAt ?? 0));
}
},
startAt: $startAt,
httpTimeout: $timeout,
curlOptions: $curlOptions,
);
try {
$hash = $writer->getMd5HashContext($targetFile);
} catch (UnreadableFileException) {
$hash = hash_init('md5');
}
try {
foreach ($responses as $response) {
$chunk = $response->getContent();
$writer->writeChunk($targetFile, $chunk, $chunkSize);
hash_update($hash, $chunk);
}
} catch (ClientException $e) {
if ($e->getCode() === Response::HTTP_REQUESTED_RANGE_NOT_SATISFIABLE) {
$writer->remove($targetFile);
throw new ForceRetryException();
}
throw $e;
}
$hash = hash_final($hash);
$writer->finalizeWriting($targetFile, $hash);
if (!$noVerify && $download->md5 && $download->md5 !== $hash) {
if ($removeInvalid && !$retryReason instanceof RetryDownloadForUnmatchingHashException) {
$io->warning("{$downloadTag} failed hash check. The file will be removed and the process retried.");
$writer->remove($targetFile);
throw new RetryDownloadForUnmatchingHashException();
} else if ($removeInvalid) {
$io->warning("{$downloadTag} failed hash check twice, not downloading again.");
} else {
$io->warning("{$downloadTag} failed hash check. The file will be kept as is, specify --remove-invalid if you want to delete such files and retry the download.");
}
}
$progress->finish();
$io->newLine();
}, maxRetries: $input->getOption('retry'), retryDelay: $input->getOption('retry-delay'), ignoreExceptions: [
InvalidValueException::class,
ExitException::class,
]);
} catch (TooManyRetriesException $e) {
if (!$input->getOption('skip-errors')) {
if (!count($e->exceptions)) {
throw $e;
}
throw $e->exceptions[array_key_last($e->exceptions)];
}
$io->note("{$download->name} couldn't be downloaded");
}
}
}
return self::SUCCESS;
} catch (ExitException $e) {
$io->error($e->getMessage());
return $e->getCode();
}
}
private function getBytesCallable(callable $targetMethod): callable
{
return function (ProgressBar $progressBar, OutputInterface $output) use ($targetMethod) {
$coefficient = 1;
$unit = 'B';
$value = $targetMethod();
if (!$output->isVeryVerbose()) {
if ($value > 2**10) {
$coefficient = 2**10;
$unit = 'kB';
}
if ($value > 2**20) {
$coefficient = 2**20;
$unit = 'MB';
}
if ($value > 2**30) {
$coefficient = 2**30;
$unit = 'GB';
}
}
$value = $value / $coefficient;
$value = number_format($value, 2);
return "{$value} {$unit}";
};
}
private function handleSignals(OutputInterface $output): void
{
if (!function_exists('pcntl_signal')) {
return;
}
pcntl_signal(SIGINT, function (int $signal, mixed $signalInfo) use ($output) {
if ($this->canKillSafely || $this->exitRequested) {
if (!$this->canKillSafely) {
throw new ExitException('Application termination has been requested twice, forcing killing');
}
throw new ExitException('Application has been terminated');
}
$this->exitRequested = true;
$output->writeln('');
$output->writeln('Application exit has been requested, the application will stop once the current download finishes. Press CTRL+C again to force exit.');
});
}
private function dispatchSignals(): void
{
if (function_exists('pcntl_signal_dispatch')) {
pcntl_signal_dispatch();
}
if ($this->exitRequested) {
throw new ExitException('Application has been terminated as requested previously.');
}
}
private function parseBandwidth(string $bandwidth): int
{
if (is_numeric($bandwidth)) {
return (int) $bandwidth;
}
$lower = strtolower($bandwidth);
if (str_ends_with($lower, 'kb') || str_ends_with($lower, 'k')) {
$value = (int) $lower;
$value *= 1024;
return $value;
} else if (str_ends_with($lower, 'mb') || str_ends_with($lower, 'm')) {
$value = (int) $lower;
$value *= 1024 * 1024;
return $value;
} else if (str_ends_with($lower, 'b')) {
return (int) $lower;
}
throw new InvalidArgumentException("Unsupported bandwidth format: {$bandwidth}");
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Command/MigrateNamingSchemeCommand.php | src/Command/MigrateNamingSchemeCommand.php | <?php
namespace App\Command;
use App\Enum\NamingConvention;
use App\Enum\Setting;
use App\Service\OwnedItemsManager;
use App\Service\Persistence\PersistenceManager;
use App\Trait\MigrationCheckerTrait;
use App\Trait\TargetDirectoryTrait;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ConfirmationQuestion;
use Symfony\Component\Console\Style\SymfonyStyle;
#[AsCommand('migrate-naming-scheme', description: 'Migrates the GOG naming scheme from the old format to the new one. Migrates both the database and your already downloaded files.')]
final class MigrateNamingSchemeCommand extends Command
{
use TargetDirectoryTrait;
use MigrationCheckerTrait;
public function __construct(
private readonly PersistenceManager $persistence,
private readonly OwnedItemsManager $ownedItemsManager,
) {
parent::__construct();
}
protected function configure(): void
{
$this->setHidden(
!$this->persistence->needsMigrating()
&& $this->persistence->getSetting(Setting::NamingConvention) !== NamingConvention::Custom->value
);
$this->addArgument(
'directory',
InputArgument::OPTIONAL,
'The target directory.',
);
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$this->showInfoIfMigrationsAreNeeded($io, $this->persistence);
$configuredDirectory = $input->getArgument('directory')
?? $_ENV['DOWNLOAD_DIRECTORY']
?? $this->persistence->getSetting(Setting::DownloadPath)
;
if (!$configuredDirectory) {
if (!$input->isInteractive()) {
$io->error('Refusing to do a potentially destructive operation without explicitly setting the target directory, please run this command in an interactive shell.');
return Command::FAILURE;
}
if (!$io->askQuestion(new ConfirmationQuestion('You have not specified any target directory for your downloads, which means the current directory is used. Is that really what you want?', false))) {
return Command::FAILURE;
}
}
$input->setArgument('directory', $configuredDirectory ?? getcwd());
$currentNamingConvention = NamingConvention::tryFrom($this->persistence->getSetting(Setting::NamingConvention)) ?? NamingConvention::GogSlug;
if ($currentNamingConvention !== NamingConvention::Custom) {
if (!$input->isInteractive()) {
$io->error('Refusing to do a potentially destructive operation because the current naming convention is not the expected one, please run this command in an interactive shell.');
return Command::FAILURE;
}
if (!$io->askQuestion(new ConfirmationQuestion("The current naming convention is not set to '" . NamingConvention::Custom->value . "', are you sure you want to run the migrate command?", false))) {
return Command::FAILURE;
}
}
$errors = [];
$games = $this->ownedItemsManager->getLocalGameData();
foreach ($games as $game) {
if (!$game->slug) {
$io->error("To migrate to the new naming scheme, please run the 'update' command first, currently there are no slug data for the game '{$game->title}' (and potentially others)");
return Command::FAILURE;
}
$oldTargetDir = $this->getTargetDir($input, $game, namingScheme: NamingConvention::Custom);
$newTargetDir = $this->getTargetDir($input, $game, namingScheme: NamingConvention::GogSlug);
if (!is_dir($oldTargetDir)) {
continue;
}
if (PHP_OS_FAMILY === 'Windows') {
$suffix = '__MIGRATE__GD';
if (!rename($oldTargetDir, $oldTargetDir . $suffix)) {
$io->error("Failed migrating game '{$game->title}', renaming '{$oldTargetDir}' to a temporary name '{$oldTargetDir}{$suffix}' failed.");
continue;
}
$oldTargetDir .= $suffix;
}
if (rename($oldTargetDir, $newTargetDir)) {
$io->note("Migrated game '{$game->title}' from '{$oldTargetDir}' to '{$newTargetDir}'");
} else {
$io->error("Failed migrating game '{$game->title}', renaming '{$oldTargetDir}' to '{$newTargetDir}' failed.");
$errors[] = $game->title;
}
}
$this->persistence->storeSetting(Setting::NamingConvention, NamingConvention::GogSlug->value);
if (count($errors) > 0) {
$io->error('There were ' . count($errors) . ' errors migrating game data:');
foreach ($errors as $error) {
$io->error(' - ' . $error);
}
return Command::FAILURE;
}
$io->success('All game data were successfully migrated.');
return Command::SUCCESS;
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
RikudouSage/GogDownloader | https://github.com/RikudouSage/GogDownloader/blob/51828fd0d673e8f167e9baaf8636718b27a66950/src/Command/TotalSizeCommand.php | src/Command/TotalSizeCommand.php | <?php
namespace App\Command;
use App\Enum\SizeUnit;
use App\Service\DownloadManager;
use App\Service\OwnedItemsManager;
use App\Service\Persistence\PersistenceManager;
use App\Trait\CommonOptionsTrait;
use App\Trait\FilteredGamesResolverTrait;
use App\Trait\MigrationCheckerTrait;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
#[AsCommand('total-size', description: 'Calculates the total size of all your installers')]
final class TotalSizeCommand extends Command
{
use CommonOptionsTrait;
use FilteredGamesResolverTrait;
use MigrationCheckerTrait;
public function __construct(
private readonly DownloadManager $downloadManager,
private readonly OwnedItemsManager $ownedItemsManager,
private readonly PersistenceManager $persistence,
) {
parent::__construct();
}
protected function configure(): void
{
$unitValues = array_map(
fn (SizeUnit $unit) => $unit->value,
SizeUnit::cases(),
);
$this
->addOsFilterOption()
->addLanguageFilterOption()
->addLanguageFallbackEnglishOption()
->addUpdateOption()
->addExcludeLanguageOption()
->addHttpRetryOption()
->addHttpRetryDelayOption()
->addSkipHttpErrorsOption()
->addHttpIdleTimeoutOption()
->addGameNameFilterOption()
->addExcludeGameNameFilterOption()
->addOption(
name: 'unit',
mode: InputOption::VALUE_REQUIRED,
description: 'The unit to display the size in. Possible values: ' . implode(', ', $unitValues),
default: SizeUnit::Gigabytes->value,
)
->addOption(
name: 'short',
mode: InputOption::VALUE_NONE,
description: 'When this flag is present, only the value is printed, no other text (including warnings) is outputted. Useful for scripting.',
)
->addOption(
'precision',
mode: InputOption::VALUE_REQUIRED,
description: 'How many decimal places should be used when outputting the number',
default: 2,
)
;
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$this->showInfoIfMigrationsAreNeeded($io, $this->persistence);
$games = $this->getGames($input, $output, $this->ownedItemsManager);
$unit = SizeUnit::tryFrom($input->getOption('unit'));
if ($unit === null) {
$io->error("Unsupported unit, please use --help to see list of available units.");
return Command::FAILURE;
}
$short = $input->getOption('short');
$total = 0;
foreach ($games as $game) {
foreach ($game->downloads as $download) {
$total += $download->size;
}
}
$total = $this->formatToUnit($total, $unit);
$formatted = round($total, $input->getOption('precision'));
if ($short) {
$io->writeln($formatted);
} else {
$io->success("The total size of your downloads is: {$formatted} {$unit->name}");
}
return Command::SUCCESS;
}
private function formatToUnit(float $total, SizeUnit $unit): float
{
return match ($unit) {
SizeUnit::Bytes => $total,
SizeUnit::Kilobytes => $total / 1024,
SizeUnit::Megabytes => $total / 1024 / 1024,
SizeUnit::Gigabytes => $total / 1024 / 1024 / 1024,
SizeUnit::Terabytes => $total / 1024 / 1024 / 1024 / 1024,
};
}
}
| php | MIT | 51828fd0d673e8f167e9baaf8636718b27a66950 | 2026-01-05T05:23:42.986854Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.