<?phpnamespace App\Cloud;use App\Core\WinZik;use JumPHP\Async\Task;/** * The account's playlist: its entries as the server has them (id, title, artist, duration, size, sha256, addedBy, * source {type: pc, device} | {type: youtube, videoId, query}, lyrics, at), which local file each one is on this * device (var/cloud/files.json: never sent), and what this device changed while offline (an operation queue). * * Kept in var/cloud/playlist.json {version, entries, ops}: shown without the network, changed without it. Back online * sync() reads the server's playlist, replays the operations by entry id (add, remove, update, order), writes it with * If-Match: the version read; a 412 (another device wrote in between) replays them on the current one, again. */final class CloudPlaylist{ public int $version = 0; /** @var list<array<string, mixed>> */ public array $entries = []; /** @var list<array<string, mixed>> the changes not written to the server yet */ public array $ops = []; /** @var array<string, string> entry id => local file (absolute path) */ public array $files = []; /** a sync is on its way */ public bool $syncing = false; /** the entries changed (the view is made again) */ public int $generation = 0; public function __construct(private string $dir) { $saved = WinZik::readJsonFile($dir . '/playlist.json'); if (is_array($saved)) { $this->version = (int)($saved['version'] ?? 0); $this->entries = array_values(array_filter((array)($saved['entries'] ?? []), 'is_array')); $this->ops = array_values(array_filter((array)($saved['ops'] ?? []), 'is_array')); } $files = WinZik::readJsonFile($dir . '/files.json'); $this->files = is_array($files) ? array_map('strval', array_filter($files, 'is_string')) : []; } public function save(): void { @mkdir($this->dir, 0777, true); WinZik::writeJsonFile($this->dir . '/playlist.json', ['version' => $this->version, 'entries' => $this->entries, 'ops' => $this->ops]); WinZik::writeJsonFile($this->dir . '/files.json', $this->files); } /** Signed out: nothing of the account stays on this device (the songs copied stay where they are). */ public function clear(): void { [$this->version, $this->entries, $this->ops, $this->files] = [0, [], [], []]; $this->generation++; $this->save(); } // --- the entries --------------------------------------------------------------------------------------------- /** @return array<string, mixed>|null */ public function entry(string $id): ?array { foreach ($this->entries as $e) { if (($e['id'] ?? null) === $id) { return $e; } } return null; } /** The local file of an entry, when it is on this device. */ public function fileOf(string $id): ?string { $file = $this->files[$id] ?? null; return $file !== null && is_file($file) ? $file : null; } public function setFile(string $id, string $file): void { $this->files[$id] = $file; $this->generation++; $this->save(); } /** The entry a local file is (or null). */ public function idOfFile(string $file): ?string { $id = array_search($file, $this->files, true); return is_string($id) && $this->entry($id) !== null ? $id : null; } // --- changes (local at once, queued for the server) ------------------------------------------------------------- /** @param list<array<string, mixed>> $entries */ public function add(array $entries): void { foreach ($entries as $e) { $this->apply($op = ['op' => 'add', 'entry' => $e]); $this->ops[] = $op; } $this->changed(); } /** @param list<string> $ids */ public function remove(array $ids): void { if ($ids === []) { return; } $this->apply($op = ['op' => 'remove', 'ids' => $ids]); $this->ops[] = $op; foreach ($ids as $id) { unset($this->files[$id]); } $this->changed(); } /** @param array<string, mixed> $fields */ public function update(string $id, array $fields): void { $this->apply($op = ['op' => 'update', 'id' => $id, 'fields' => $fields]); $this->ops[] = $op; $this->changed(); } /** @param list<string> $ids the new order (ids not named keep their place after them) */ public function order(array $ids): void { $this->apply($op = ['op' => 'order', 'ids' => $ids]); $this->ops[] = $op; $this->changed(); } private function changed(): void { $this->generation++; $this->save(); } /** @param array<string, mixed> $op */ private function apply(array $op): void { $this->entries = self::replay($this->entries, [$op]); } /** * The operations of this device done again on a list of entries (the server's, newer): by entry id, so the * other devices' changes stay. An add of an id already there replaces it; a remove of a missing id does nothing. * @param list<array<string, mixed>> $entries * @param list<array<string, mixed>> $ops * @return list<array<string, mixed>> */ public static function replay(array $entries, array $ops): array { foreach ($ops as $op) { switch ($op['op'] ?? '') { case 'add': $e = (array)($op['entry'] ?? []); $id = (string)($e['id'] ?? ''); if ($id === '') { break; } $entries = array_values(array_filter($entries, fn (array $x) => ($x['id'] ?? null) !== $id)); $entries[] = $e; break; case 'remove': $gone = array_flip(array_map('strval', (array)($op['ids'] ?? []))); $entries = array_values(array_filter($entries, fn (array $x) => !isset($gone[(string)($x['id'] ?? '')]))); break; case 'update': foreach ($entries as $i => $x) { if (($x['id'] ?? null) === ($op['id'] ?? '')) { $entries[$i] = array_replace($x, (array)($op['fields'] ?? [])); } } break; case 'order': $rank = array_flip(array_map('strval', (array)($op['ids'] ?? []))); $named = array_values(array_filter($entries, fn (array $x) => isset($rank[(string)($x['id'] ?? '')]))); usort($named, fn (array $a, array $b) => $rank[(string)$a['id']] <=> $rank[(string)$b['id']]); $others = array_values(array_filter($entries, fn (array $x) => !isset($rank[(string)($x['id'] ?? '')]))); $entries = [...$named, ...$others]; break; } } return $entries; } // --- the server ------------------------------------------------------------------------------------------------ /** * Reads the server's playlist, replays what this device changed, writes it (If-Match), again on a 412 (5 times at * most). Settles with true when something changed here. */ public function sync(CloudAccount $account): Task { $result = new Task(); if ($this->syncing) { $result->settle(false); return $result; } $this->syncing = true; $account->getPlaylist()->then(function (array $data) use ($account, $result): void { $this->merge($account, (int)($data['version'] ?? 0), self::entriesOf($data), $result, 0); }, function (\Throwable $e) use ($result): void { $this->syncing = false; $result->settle(null, $e); }); return $result; } /** @param list<array<string, mixed>> $server */ private function merge(CloudAccount $account, int $version, array $server, Task $result, int $tries): void { if ($this->ops === []) { $changed = $version !== $this->version || $server !== $this->entries; $this->version = $version; $this->entries = $server; $this->syncing = false; if ($changed) { $this->changed(); } $result->settle($changed); return; } $ops = $this->ops; $wanted = self::replay($server, $ops); $account->putPlaylist($wanted, $version)->then(function (array $data) use ($account, $ops, $result, $tries): void { if (!empty($data['conflict'])) { if ($tries >= 4) { $this->syncing = false; $result->settle(null, new CloudError('La playlist change trop vite sur vos autres appareils : réessayez.', 'conflict', 412)); return; } $this->merge($account, (int)($data['version'] ?? 0), self::entriesOf($data), $result, $tries + 1); return; } // written: the operations sent are done (others may have come meanwhile: kept) $this->ops = array_slice($this->ops, count($ops)); $this->version = (int)($data['version'] ?? $this->version); $this->entries = self::replay(self::entriesOf($data), $this->ops); $this->syncing = false; $this->changed(); $result->settle(true); }, function (\Throwable $e) use ($result): void { $this->syncing = false; $result->settle(null, $e); }); } /** @param array<string, mixed> $data @return list<array<string, mixed>> */ private static function entriesOf(array $data): array { return array_values(array_filter((array)($data['entries'] ?? []), 'is_array')); }}