<?phpnamespace App\Cloud;use App\Core\WinZik;use App\Model\Playlist;use App\Model\Text;use JumPHP\Async\Task;use JumPHP\Kernel\Platform;/** * WinZik's cloud, what every interface uses ($wz->cloud()): the account (pseudo + password), the cloud playlist * shared by the PC and the phone, the songs copied from the PC to the phone (the LAN first, else the encrypted relay; * never stored on the server), the lyrics kept in the account, "le mobile la récupère sur YouTube". * AGENTS.md "Cloud" documents the API (states, rows, data shapes) for the interfaces. */final class Cloud{ /** a line of the cloud playlist whose song is not on this device yet */ public const PSEUDO = 'cloud:'; public const HELLO_EVERY = 60.0; public CloudAccount $account; public CloudPlaylist $playlist; public ?CloudLink $link = null; public ?LanShare $lan = null; /** « Lecture synchronisée avec mes appareils » (null: no relay here) */ public ?PlaySync $playSync = null; /** @var array<string, Transfer> entry id => the copy coming here */ public array $transfers = []; /** @var array<string, array{to: string, mode: string, offset: int, size: int, fh: resource|null, since: float, progress: float}> entry id => being sent from here */ public array $sending = []; /** @var array<string, array{url: string, since: float}> entry id => downloaded from YouTube here */ public array $youtubeJobs = []; /** @var list<array{file: string, type: string, ctx: \HashContext|null, fh: resource|null}> files being read (SHA-256) before they go in */ public array $hashing = []; /** @var array<string, array<string, mixed>> entry id => {state, error}: what failed (shown on its line) */ public array $failed = []; /** the copies start by themselves (default on the phone) */ public bool $autoCopy; /** the phone: copies by themselves only on the network of the house (the LAN way): never through the relay on mobile data */ public bool $wifiOnly = true; /** where the songs received go */ public string $receiveDir; /** the last thing worth telling (French), '' none */ public string $message = ''; /** 'off' (no cloud here) | 'signedOut' | 'connecting' | 'online' | 'offline' */ private string $net = 'connecting'; /** @var list<array<string, mixed>> the devices of the account (GET /me), online updated by /hello */ private array $devices = []; /** @var list<string> device ids online (POST /hello) */ private array $online = []; private float $helloClock = 999.0; private bool $helloBusy = false; private float $clock = 0.0; private float $linkExp = 0.0; private bool $linkBusy = false; /** the cloud view: the user's own playlist kept here while $wz->playlist is the cloud's */ private ?Playlist $local = null; /** @var list<string> the items of the cloud view as last made */ private array $built = []; private int $builtGeneration = -1; /** @var array<string, string> entry id => local file whose lyrics go up once the entry is on the server */ private array $lyricsUp = []; /** @var array<string, bool> entry ids whose lyrics were asked */ private array $lyricsAsked = []; /** * @var array<string, array{etag: string, sha: string}>|null entry id => the server's ETag of its lyrics as this * device last sent / got them, and the SHA-1 of the file written here then (var/cloud/lyrics.json): lyrics changed * elsewhere (translated on the PC) come down again, never over lyrics changed here and not sent yet */ private ?array $lyricsTags = null; /** @var array<string, float> entry id => when its lyrics were last looked at again ($clock) */ private array $lyricsChecked = []; public const LYRICS_RECHECK = 120.0; private bool $syncWanted = true; private float $syncClock = 0.0; private string $viewName = 'local'; /** @var array<string, string> local file => YouTube address (var/youtube-sources.json, written by App\Media\YouTube) */ private ?array $ytSources = null; /** * @param \Closure(): \JumPHP\Net\NetSession|null $netFactory the relay (null: no relay here) */ public function __construct(private WinZik $wz, CloudAccount $account, private string $dir, ?\Closure $netFactory = null, ?LanShare $lan = null, ?string $receiveDir = null) { $this->account = $account; $this->playlist = new CloudPlaylist($dir); $this->lan = $lan; $phone = $account->kind === 'phone'; $this->autoCopy = $phone; $this->receiveDir = $receiveDir ?? self::defaultReceiveDir($phone); $settings = WinZik::readJsonFile($dir . '/settings.json'); if (is_array($settings)) { $this->autoCopy = (bool)($settings['autoCopy'] ?? $this->autoCopy); $this->wifiOnly = (bool)($settings['wifiOnly'] ?? true); $this->receiveDir = (string)($settings['receiveDir'] ?? '') ?: $this->receiveDir; $this->viewName = ($settings['view'] ?? 'local') === 'cloud' ? 'cloud' : 'local'; } $synced = !is_array($settings) || (bool)($settings['playSync'] ?? true); if ($netFactory !== null) { $this->link = new CloudLink($netFactory, $account->deviceId, $account->kind); $this->link->onMessage = fn (string $from, array $m) => $this->onMessage($from, $m); $this->link->onChunk = fn (string $from, string $entry, int $offset, string $bytes) => $this->onChunk($from, $entry, $offset, $bytes); $this->playSync = new PlaySync($wz, $this, $this->link); $this->playSync->enabled = $synced; } $account->onSignedOut = fn () => $this->signedOutHere(); $this->net = !$account->enabled() ? 'off' : (!$account->signedIn() ? 'signedOut' : 'connecting'); } /** Music/WinZik/Cloud on a computer, the app's music folder on the phone. */ public static function defaultReceiveDir(bool $phone): string { return \App\Media\MediaDirs::winzik('MUSIC') . ($phone ? '' : '/Cloud'); } public function saveSettings(): void { @mkdir($this->dir, 0777, true); WinZik::writeJsonFile($this->dir . '/settings.json', ['autoCopy' => $this->autoCopy, 'wifiOnly' => $this->wifiOnly, 'receiveDir' => $this->receiveDir, 'view' => $this->viewName, 'playSync' => $this->playSynced()]); } // --- « Lecture synchronisée avec mes appareils » (PlaySync) -------------------------------------------------------- /** This device plays with the others of the account ("Synchronisé", the default) or on its own ("Indépendant"). */ public function playSynced(): bool { return $this->playSync === null || $this->playSync->enabled; } /** Synchronisé / Indépendant, saved in this device's settings. */ public function setPlaySync(bool $on): void { $this->playSync?->setEnabled($on); $this->saveSettings(); } /** the devices playing together now, this one included (0: independent, signed out, not in the room) */ public function syncCount(): int { return $this->signedIn() ? ($this->playSync?->count() ?? 0) : 0; } /** the tiny indicator: « Synchro · 2 appareils », '' when no other device plays with this one */ public function syncLabel(): string { $n = $this->syncCount(); return $n >= 2 ? 'Synchro · ' . $n . ' appareils' : ''; } /** One French line for the account's window and page: synced with whom, who leads, or independent. */ public function syncText(): string { if (!$this->signedIn() || $this->playSync === null) { return ''; } if (!$this->playSynced()) { return 'Indépendant : cet appareil joue seul, sans suivre ni guider les autres.'; } $n = $this->syncCount(); if ($n < 2) { return 'Synchronisé · aucun autre appareil en ligne pour l\'instant'; } $lead = $this->playSync->following() ? ' · ' . $this->deviceLabel($this->playSync->leader) . ' mène la lecture' : ''; return 'Synchronisé · ' . $n . ' appareils' . $lead; } /** The name of a device of the account (its name, else its kind). */ public function deviceLabel(string $deviceId): string { foreach ($this->devices as $d) { if (($d['id'] ?? '') === $deviceId && (string)($d['name'] ?? '') !== '') { return (string)$d['name']; } } return match ($this->link?->devices()[$deviceId] ?? '') { 'phone' => 'Téléphone', 'web' => 'Navigateur', default => 'Ordinateur', }; } // --- the account ----------------------------------------------------------------------------------------------- /** off (no cloud here: no network service) | signedOut | connecting | online | offline (no answer from the server) */ public function state(): string { if (!$this->account->enabled()) { return 'off'; } return $this->account->signedIn() ? $this->net : 'signedOut'; } public function enabled(): bool { return $this->account->enabled(); } public function signedIn(): bool { return $this->account->signedIn(); } public function login(): string { return $this->account->login; } public function deviceId(): string { return $this->account->deviceId; } public function deviceName(): string { return $this->account->deviceName; } /** Settles with {login, recovery}: the recovery code, to show ONCE ("notez ce code"). */ public function signUp(string $login, string $password, ?string $deviceName = null): Task { return $this->entered($this->account->signUp($login, $password, $deviceName)); } /** Settles with {login}. */ public function signIn(string $login, string $password, ?string $deviceName = null): Task { return $this->entered($this->account->signIn($login, $password, $deviceName)); } /** Without the password (the recovery code): settles with {login, recovery} (a new code: show it once). */ public function recover(string $login, string $recovery, string $newPassword, ?string $deviceName = null): Task { return $this->entered($this->account->recover($login, $recovery, $newPassword, $deviceName)); } private function entered(Task $task): Task { $result = new Task(); $task->then(function (array $data) use ($result): void { if ($this->playlist->entries !== [] || $this->playlist->ops !== []) { $this->playlist->clear(); // another account's playlist was here } $this->link?->setDevice($this->account->deviceId); $this->net = 'connecting'; $this->helloClock = 999.0; $this->syncWanted = true; $this->message = ''; $result->settle($data); }, fn (\Throwable $e) => $result->settle(null, $e)); return $result; } /** This device leaves the account: the cloud playlist forgotten here (the songs copied stay in their folder). */ public function signOut(): Task { return $this->account->signOut(); } private function signedOutHere(): void { $this->useView('local'); $this->link?->close(); $this->lan?->close(); $this->closeSending(); foreach ($this->transfers as $t) { $t->offline(); } $this->transfers = []; $this->playlist->clear(); $this->devices = $this->online = []; $this->net = 'signedOut'; } /** * The devices of the account: [{id, name, kind (desktop | phone | web), online (bool), lastSeen (ISO date), * current (this one)}]. refreshDevices() asks the server again. * @return list<array<string, mixed>> */ public function devices(): array { $online = array_flip($this->online); $room = $this->link?->devices() ?? []; return array_map(fn (array $d) => ['online' => isset($online[$d['id'] ?? '']) || isset($room[$d['id'] ?? '']) || !empty($d['current'])] + $d, $this->devices); } public function refreshDevices(): Task { $result = new Task(); $this->account->me()->then(function (array $me) use ($result): void { $this->devices = array_values(array_filter((array)($me['devices'] ?? []), 'is_array')); $result->settle($this->devices()); }, fn (\Throwable $e) => $result->settle(null, $e)); return $result; } /** Signs another device of the account out. */ public function revoke(string $deviceId): Task { $result = new Task(); $this->account->revoke($deviceId)->then(function () use ($deviceId, $result): void { $this->devices = array_values(array_filter($this->devices, fn (array $d) => ($d['id'] ?? '') !== $deviceId)); $result->settle(true); }, fn (\Throwable $e) => $result->settle(null, $e)); return $result; } public function setDeviceName(string $name): void { $name = trim($name); if ($name !== '') { $this->account->deviceName = mb_substr($name, 0, 40); $this->account->save(); } } /** Is a device of the account online (in the room of the relay, or seen by the server less than 150 s ago)? */ public function isOnline(string $deviceId): bool { return ($this->link?->has($deviceId) ?? false) || in_array($deviceId, $this->online, true); } // --- the playlist ---------------------------------------------------------------------------------------------- /** @return list<array<string, mixed>> the entries of the cloud playlist (the server's shape) */ public function entries(): array { return $this->playlist->entries; } /** * What a line of the cloud playlist shows, for every entry in order: * {id, title, artist, duration, size, sha256, source: {type, ...}, lyrics (bool), file (local path or null), * state, progress (0..1), text (French, short)}. * @return list<array<string, mixed>> */ public function rows(): array { $out = []; foreach ($this->playlist->entries as $e) { $id = (string)$e['id']; $s = $this->rowState($id); $out[] = ['id' => $id, 'title' => (string)($e['title'] ?? ''), 'artist' => (string)($e['artist'] ?? ''), 'duration' => (float)($e['duration'] ?? 0), 'size' => (int)($e['size'] ?? 0), 'sha256' => (string)($e['sha256'] ?? ''), 'source' => (array)($e['source'] ?? []), 'lyrics' => (bool)($e['lyrics'] ?? false), 'file' => $this->playlist->fileOf($id)] + $s; } return $out; } /** * The state of an entry on this device: * here (the song is on this device) | sending (this PC sends it now: progress) | copying (coming here: progress) | * waiting (asked the PC, no answer yet) | offline (the PC that has it is not online) | youtube (downloading it from * YouTube here) | absent (not here, nothing going on: fetch() copies it) | error (text says why; fetch() tries again). * @return array{state: string, progress: float, text: string} */ public function rowState(string $id): array { $file = $this->playlist->fileOf($id); if (isset($this->sending[$id])) { $p = $this->sending[$id]['progress']; return ['state' => 'sending', 'progress' => $p, 'text' => 'envoi ' . (int)floor($p * 100) . ' %']; } if ($file !== null) { return ['state' => 'here', 'progress' => 1.0, 'text' => 'sur cet appareil']; } if (isset($this->youtubeJobs[$id])) { return ['state' => 'youtube', 'progress' => 0.0, 'text' => 'YouTube ↓']; } $t = $this->transfers[$id] ?? null; if ($t !== null) { return match ($t->state) { 'lan', 'relay', 'verify' => ['state' => 'copying', 'progress' => $t->progress(), 'text' => 'copie ' . (int)floor($t->progress() * 100) . ' %'], 'offline' => ['state' => 'offline', 'progress' => $t->progress(), 'text' => 'PC hors ligne – en attente'], 'error' => ['state' => 'error', 'progress' => 0.0, 'text' => $t->error], default => ['state' => 'waiting', 'progress' => $t->progress(), 'text' => 'en attente du PC'], }; } if (isset($this->failed[$id])) { return ['state' => 'error', 'progress' => 0.0, 'text' => (string)$this->failed[$id]['error']]; } $e = $this->playlist->entry($id); $source = (array)($e['source'] ?? []); if (($source['type'] ?? '') === 'pc' && !$this->isOnline((string)($source['device'] ?? '')) && ($source['device'] ?? '') !== $this->deviceId()) { return ['state' => 'offline', 'progress' => 0.0, 'text' => 'PC hors ligne']; } return ['state' => 'absent', 'progress' => 0.0, 'text' => ($source['type'] ?? '') === 'youtube' ? 'à récupérer sur YouTube' : 'pas sur cet appareil']; } /** The marker of a line of any playlist: whether its song is in the cloud, and the progress while it is sent (null: not sent now). @return array{cloud: bool, sending: ?float} */ public function fileState(string $file): array { if (self::isPseudo($file)) { return ['cloud' => true, 'sending' => null]; } $path = $this->wz->path($file); foreach ($this->hashing as $h) { if ($h['file'] === $path) { return ['cloud' => true, 'sending' => 0.0]; } } $id = $this->playlist->idOfFile($path); return ['cloud' => $id !== null, 'sending' => $id !== null && isset($this->sending[$id]) ? $this->sending[$id]['progress'] : null]; } /** * "Mettre dans le cloud", the PC sends the MP3: the files go in the cloud playlist (read first: their SHA-256, a * few milliseconds a frame), their lyrics in the account. Returns how many will go. * @param list<string> $files */ public function putFromPc(array $files): int { return $this->queue($files, 'pc'); } /** "Mettre dans le cloud", the phone gets them from YouTube itself (the video's id when WinZik downloaded it, else a search: artist + title). @param list<string> $files */ public function putFromYoutube(array $files): int { return $this->queue($files, 'youtube'); } /** @param list<string> $files */ private function queue(array $files, string $type): int { if (!$this->signedIn()) { $this->message = 'Connectez-vous d\'abord à votre compte (menu : Mon compte cloud).'; return 0; } $n = 0; foreach ($files as $file) { if (self::isPseudo($file)) { continue; } $path = $this->wz->path($file); if (!is_file($path) || $this->playlist->idOfFile($path) !== null) { continue; } foreach ($this->hashing as $h) { if ($h['file'] === $path) { continue 2; } } if ($type === 'youtube' && $this->youtubeSource($path) === null) { continue; } $this->hashing[] = ['file' => $path, 'type' => $type, 'ctx' => null, 'fh' => null]; $n++; } return $n; } /** The YouTube way of a file: its video id when known (imported by WinZik), else a search. @return array{type: string, videoId: string, query: string}|null */ public function youtubeSource(string $file): ?array { $path = $this->wz->path($file); $this->ytSources ??= (static function (string $f): array { $data = WinZik::readJsonFile($f); return is_array($data) ? array_map('strval', array_filter($data, 'is_string')) : []; })($this->wz->storagePath('youtube-sources.json')); $videoId = ''; $url = $this->ytSources[$path] ?? ''; if (preg_match('#(?:v=|youtu\.be/|/shorts/)([A-Za-z0-9_-]{11})#', $url, $m)) { $videoId = $m[1]; } [$tag] = is_file($path) ? $this->wz->describe($path) : [new \App\Model\Id3Tag()]; $query = trim($tag->artist . ' ' . $tag->title); if ($query === '') { $query = trim((string)preg_replace('/[_]+/', ' ', Text::baseName(Text::withoutExtension($path)))); } if ($videoId === '' && $query === '') { return null; } return ['type' => 'youtube', 'videoId' => $videoId, 'query' => mb_substr($query, 0, 200)]; } /** @param list<string> $ids removed from the cloud playlist (on every device; the files stay) */ public function remove(array $ids): void { foreach ($ids as $id) { unset($this->failed[$id], $this->youtubeJobs[$id]); if (isset($this->transfers[$id])) { $this->transfers[$id]->cancel(); unset($this->transfers[$id]); } } $this->playlist->remove($ids); $this->syncWanted = true; } /** Copies an entry to this device now (or again after an error): the LAN first, else the relay. */ public function fetch(string $id, bool $auto = false): void { $e = $this->playlist->entry($id); if ($e === null || $this->playlist->fileOf($id) !== null) { return; } unset($this->failed[$id]); $source = (array)($e['source'] ?? []); if (($source['type'] ?? '') === 'youtube' && $this->wz->youtube !== null && !isset($this->transfers[$id])) { $this->startYoutube($id, $e); return; } $t = $this->transfers[$id] ?? null; if ($t !== null && $t->active()) { return; } $this->transfers[$id] = new Transfer($e, $this->targetOf($e)); $this->transfers[$id]->auto = $auto; $this->asked[$id] = -999.0; } /** A line of the cloud view clicked whose song is not here: its copy starts. */ public function fetchItem(string $item): void { $id = self::idOfPseudo($item); if ($id !== null) { $this->fetch($id); $e = $this->playlist->entry($id); $this->wz->notice('Copie vers cet appareil : ' . trim(($e['artist'] ?? '') . ' - ' . ($e['title'] ?? ''), ' -'), 5); } } /** @param array<string, mixed> $e */ private function targetOf(array $e): string { $name = trim(($e['artist'] ?? '') !== '' ? $e['artist'] . ' - ' . $e['title'] : (string)($e['title'] ?? '')); $name = trim((string)preg_replace('#[\\\\/:*?"<>|\x00-\x1f]+#', ' ', $name)) ?: (string)$e['id']; $name = mb_substr($name, 0, 120); $target = rtrim($this->receiveDir, '/\\') . '/' . $name . '.mp3'; $same = is_file($target) && strtolower((string)($e['sha256'] ?? '')) !== '' && hash_file('sha256', $target) === strtolower((string)$e['sha256']); $taken = false; foreach ($this->transfers as $other => $t) { $taken = $taken || ($other !== $e['id'] && $t->target === $target); // two songs of the same name coming at once } if ((is_file($target) && !$same) || $taken || is_file($target . '.part') && !isset($this->transfers[$e['id']]) && $this->partOfAnother($target, (string)$e['id'])) { $target = rtrim($this->receiveDir, '/\\') . '/' . $name . ' (' . substr((string)$e['id'], 0, 8) . ').mp3'; } return $target; } /** A part file of this name belongs to another entry (its size is more than this one's). */ private function partOfAnother(string $target, string $id): bool { $e = $this->playlist->entry($id); return $e !== null && (int)filesize($target . '.part') > (int)($e['size'] ?? 0); } public static function isPseudo(string $item): bool { return str_starts_with($item, self::PSEUDO); } public static function idOfPseudo(string $item): ?string { return self::isPseudo($item) ? (string)preg_replace('/\.mp3$/', '', substr($item, strlen(self::PSEUDO))) : null; } /** The cloud entry of a line of a playlist (a local file or a cloud line), null: not in the cloud. */ public function entryOfItem(string $item): ?array { $id = self::idOfPseudo($item) ?? $this->playlist->idOfFile($this->wz->path($item)); return $id !== null ? $this->playlist->entry($id) : null; } // --- the two playlists ----------------------------------------------------------------------------------------- /** local ("Ma playlist") | cloud ("Playlist cloud (mon compte)") */ public function view(): string { return $this->local !== null ? 'cloud' : 'local'; } /** Shows the user's own playlist or the cloud's (the player's play list becomes it; the other one is kept). */ public function useView(string $view): void { $wz = $this->wz; if ($view === 'cloud' && $this->local === null && $this->signedIn()) { $this->local = $wz->playlist; $cloud = new Playlist([]); $cloud->shuffle = $this->local->shuffle; $wz->playlist = $cloud; $this->builtGeneration = -1; $this->rebuild(); } elseif ($view !== 'cloud' && $this->local !== null) { $wz->playlist = $this->local; $this->local = null; $this->built = []; } else { return; } $this->viewName = $this->view(); $this->saveSettings(); if (isset($wz->ui['playlist'])) { $wz->ui['playlist']['top'] = 0; } $playing = $wz->player->file; $index = $playing === null ? false : array_search($wz->relative($playing), $wz->playlist->items, true); $wz->playlist->active = $index !== false ? (int)$index : ($wz->playlist->count() > 0 ? 0 : -1); $wz->touch(); } /** The cloud view was the one shown last time (WinZik shows it again at the start). */ public function wantsCloudView(): bool { return $this->viewName === 'cloud'; } /** The user's own playlist while the cloud's is shown (what WinZik saves as its playlist), null in the local view. */ public function localPlaylist(): ?Playlist { return $this->local; } /** The cloud view made again from the entries: the songs here by their path, the others as cloud lines. */ private function rebuild(): void { $wz = $this->wz; if ($this->local === null) { return; } $items = []; foreach ($this->playlist->entries as $e) { $id = (string)$e['id']; $file = $this->playlist->fileOf($id); $items[] = $file !== null ? $wz->relative($file) : self::PSEUDO . $id . '.mp3'; } foreach ($this->hashing as $h) { $items[] = $wz->relative($h['file']); // going in: stays on the list meanwhile } $items = array_values(array_unique($items)); $list = $wz->playlist; if ($items !== $list->items) { $current = $list->current(); $list->items = $items; $at = $current !== null ? array_search($current, $items, true) : false; $list->active = $at !== false ? (int)$at : ($items === [] ? -1 : min(max(0, $list->active), count($items) - 1)); $wz->touch(); } $this->built = $items; $this->builtGeneration = $this->playlist->generation; } /** What the user did to the cloud view (Suppr, +, a line moved) goes to the cloud playlist. */ private function followView(): void { $wz = $this->wz; if ($this->local === null) { return; } $now = $wz->playlist->items; if ($now === $this->built) { if ($this->builtGeneration !== $this->playlist->generation) { $this->rebuild(); } return; } $was = array_flip($this->built); $is = array_flip($now); $removed = []; foreach ($this->built as $item) { if (!isset($is[$item])) { $id = self::idOfPseudo($item) ?? $this->playlist->idOfFile($wz->path($item)); if ($id !== null) { $removed[] = $id; } $path = $wz->path($item); $this->hashing = array_values(array_filter($this->hashing, fn (array $h) => $h['file'] !== $path)); } } $added = []; foreach ($now as $item) { if (!isset($was[$item]) && !self::isPseudo($item) && $this->playlist->idOfFile($wz->path($item)) === null) { $added[] = $item; } } if ($removed !== []) { $this->remove($removed); } if ($added !== []) { $this->putFromPc($added); } if ($removed === [] && $added === [] && count($now) === count($this->built)) { $ids = []; foreach ($now as $item) { $id = self::idOfPseudo($item) ?? $this->playlist->idOfFile($wz->path($item)); if ($id !== null) { $ids[] = $id; } } $this->playlist->order($ids); $this->syncWanted = true; } $this->built = $now; $this->rebuild(); } // --- lyrics ---------------------------------------------------------------------------------------------------- /** The lyrics of a song were saved / changed here (the lyrics editor): they go to the account when it is in the cloud. */ public function lyricsSaved(string $file): void { $id = $this->playlist->idOfFile($this->wz->path($file)); $lyr = $id !== null ? $this->wz->findLyricsFile($file) : null; if ($id === null || $lyr === null) { return; } $this->lyricsUp[$id] = $lyr; if (!($this->playlist->entry($id)['lyrics'] ?? false)) { $this->playlist->update($id, ['lyrics' => true]); $this->syncWanted = true; } } private function tickLyrics(): void { if ($this->net !== 'online' || $this->playlist->ops !== []) { return; } foreach ($this->lyricsUp as $id => $file) { unset($this->lyricsUp[$id]); $text = @file_get_contents($file); if (is_string($text) && $text !== '' && strlen($text) <= 65536) { $utf8 = Text::toUtf8($text); $this->account->putLyrics($id, $utf8)->then(fn () => $this->rememberLyrics($id, CloudAccount::lyricsEtag($utf8), sha1($text)), fn (\Throwable $e) => $this->message = 'Paroles non envoyées : ' . $e->getMessage()); } } // the lyrics of the songs here that have some in the account and none here yet foreach ($this->playlist->entries as $e) { $id = (string)$e['id']; if (empty($e['lyrics']) || isset($this->lyricsAsked[$id]) || ($e['addedBy'] ?? '') === $this->deviceId()) { continue; } $file = $this->playlist->fileOf($id); if ($file === null) { continue; } $this->lyricsAsked[$id] = true; $target = $this->wz->lyricsCachePath($file); if (is_file($target)) { continue; } $this->account->getLyricsIf($id)->then(function (?array $got) use ($target, $id): void { $text = (string)($got['text'] ?? ''); if ($text === '') { return; } @mkdir(dirname($target), 0777, true); @file_put_contents($target, $text); $this->rememberLyrics($id, (string)$got['etag'], sha1($text)); $this->wz->refreshLyrics(); }, fn () => null); } } /** * A song of the cloud opened here: its lyrics in the account looked at again (at most every LYRICS_RECHECK s, a * conditional GET: nothing comes back when they did not change). Changed elsewhere (corrected, translated on the * PC): they replace the copy here, unless this copy was changed here since (it goes up instead). */ public function lyricsCheck(string $file): void { $id = $this->playlist->idOfFile($this->wz->path($file)); $entry = $id !== null ? $this->playlist->entry($id) : null; if ($id === null || empty($entry['lyrics']) || $this->net !== 'online' || isset($this->lyricsUp[$id]) || $this->clock - ($this->lyricsChecked[$id] ?? -999.0) < self::LYRICS_RECHECK) { return; } $this->lyricsChecked[$id] = $this->clock; $known = $this->lyricsTags()[$id] ?? ['etag' => '', 'sha' => '']; $here = $this->wz->findLyricsFile($file); $hereText = $here !== null ? (string)@file_get_contents($here) : ''; if ($hereText !== '' && $known['sha'] !== '' && sha1($hereText) !== $known['sha']) { return; // changed here and not sent: never replaced by the account's } if ($hereText !== '' && $known['etag'] === '') { return; // lyrics of before (no ETag known): the account's are not known to be newer } $target = $this->wz->lyricsCachePath($file); $this->account->getLyricsIf($id, $known['etag'])->then(function (?array $got) use ($id, $target, $file): void { $text = (string)($got['text'] ?? ''); if ($got === null || !$got['changed'] || $text === '') { return; } @mkdir(dirname($target), 0777, true); @file_put_contents($target, $text); $this->rememberLyrics($id, (string)$got['etag'], sha1($text)); $this->wz->forget($file); $this->wz->refreshLyrics(); }, fn () => null); } /** @return array<string, array{etag: string, sha: string}> */ private function lyricsTags(): array { if ($this->lyricsTags === null) { $saved = WinZik::readJsonFile($this->dir . '/lyrics.json'); $this->lyricsTags = []; foreach (is_array($saved) ? $saved : [] as $id => $t) { if (is_array($t)) { $this->lyricsTags[(string)$id] = ['etag' => (string)($t['etag'] ?? ''), 'sha' => (string)($t['sha'] ?? '')]; } } } return $this->lyricsTags; } private function rememberLyrics(string $id, string $etag, string $sha): void { $this->lyricsTags(); $this->lyricsTags[$id] = ['etag' => $etag, 'sha' => $sha]; @mkdir($this->dir, 0777, true); WinZik::writeJsonFile($this->dir . '/lyrics.json', $this->lyricsTags); } // --- each frame ------------------------------------------------------------------------------------------------ public function tick(float $dt): void { $this->clock += $dt; if (!$this->signedIn()) { return; } $this->tickHashing(); $this->tickHello($dt); $this->tickSync($dt); $this->playSync?->observe(); // what the user did here goes out before the others' state comes in $this->link?->poll(); $this->playSync?->tick(); $this->lan?->poll(); $this->tickYoutube(); $this->tickTransfers($dt); $this->tickSending(); $this->tickLyrics(); $this->followView(); } private function tickHello(float $dt): void { $this->helloClock += $dt; if ($this->helloBusy || $this->helloClock < self::HELLO_EVERY) { return; } $this->helloClock = 0.0; $this->helloBusy = true; $this->account->hello()->then(function (array $data): void { $this->helloBusy = false; $this->net = 'online'; $this->online = array_values(array_map(fn ($d) => (string)($d['id'] ?? ''), array_filter((array)($data['online'] ?? []), 'is_array'))); foreach ((array)($data['online'] ?? []) as $d) { if (is_array($d) && !in_array($d['id'] ?? '', array_column($this->devices, 'id'), true)) { $this->devices[] = $d; } } if ((int)($data['playlist']['version'] ?? -1) !== $this->playlist->version) { $this->syncWanted = true; } $this->joinLink(); }, function (\Throwable $e): void { $this->helloBusy = false; if ($this->account->signedIn()) { $this->net = 'offline'; $this->helloClock = self::HELLO_EVERY - 15.0; // again in 15 s } }); } private function joinLink(): void { $link = $this->link; if ($link === null || $this->linkBusy || ($link->state !== 'off' && $link->state !== 'error' && $this->clock < $this->linkExp)) { return; } if ($link->state === 'error' && $this->clock < $this->linkExp) { return; // tried this week: again after its end (or after a sign in) } $this->linkBusy = true; $this->account->link()->then(function (array $data) use ($link): void { $this->linkBusy = false; $this->linkExp = $this->clock + max(60.0, min(7 * 86400.0, (float)($data['expiresIn'] ?? 3600))); $link->join($data); }, function (): void { $this->linkBusy = false; }); } private function tickSync(float $dt): void { $this->syncClock += $dt; if ($this->playlist->syncing || $this->net === 'signedOut' || (!$this->syncWanted && $this->playlist->ops === []) || $this->syncClock < 2.0) { return; } if ($this->net === 'offline' && $this->syncClock < 30.0) { return; } $this->syncClock = 0.0; $this->syncWanted = false; $before = array_column($this->playlist->entries, 'id'); $this->playlist->sync($this->account)->then(function () use ($before): void { $this->net = 'online'; $new = array_values(array_diff(array_column($this->playlist->entries, 'id'), $before)); $this->autoCopies($new); }, function (\Throwable $e): void { if ($e instanceof CloudError && $e->status === 0) { $this->net = 'offline'; } elseif ($e instanceof CloudError && $e->reason !== 'unauthorized' && $e->reason !== 'revoked') { $this->message = $e->getMessage(); } }); } /** Asks the playlist again now (after hello said it changed, or by a button). */ public function sync(): void { $this->syncWanted = true; $this->syncClock = 99.0; } /** @param list<string> $ids new entries: copied by themselves when "Copier automatiquement" is on */ private function autoCopies(array $ids): void { if (!$this->autoCopy) { return; } foreach ($ids as $id) { $e = $this->playlist->entry((string)$id); if ($e !== null && $this->playlist->fileOf((string)$id) === null && ($e['addedBy'] ?? '') !== $this->deviceId() && !isset($this->failed[$id])) { $this->fetch((string)$id, true); } } } /** The files put in the cloud are read (their SHA-256) a few milliseconds a frame, then become entries. */ private function tickHashing(): void { $until = microtime(true) + 0.008; while ($this->hashing !== [] && microtime(true) < $until) { $h = &$this->hashing[0]; if ($h['fh'] === null) { $fh = @fopen($h['file'], 'rb'); if ($fh === false) { array_shift($this->hashing); continue; } $h['fh'] = $fh; $h['ctx'] = hash_init('sha256'); } $read = hash_update_stream($h['ctx'], $h['fh'], 1 << 20); if ($read > 0) { continue; } fclose($h['fh']); $sha = hash_final($h['ctx']); $file = $h['file']; $type = $h['type']; unset($h); array_shift($this->hashing); $this->addEntry($file, $type, $sha); } } private function addEntry(string $file, string $type, string $sha): void { [$tag, $info] = $this->wz->describe($file); $id = self::uuid(); $me = $this->deviceId(); $source = $type === 'youtube' ? ($this->youtubeSource($file) ?? ['type' => 'pc', 'device' => $me]) : ['type' => 'pc', 'device' => $me]; $lyrics = $this->wz->findLyricsFile($file); $entry = ['id' => $id, 'title' => $tag->title !== '' ? $tag->title : Text::baseName(Text::withoutExtension($file)), 'artist' => $tag->artist, 'duration' => round($info->duration, 3), 'size' => (int)filesize($file), 'sha256' => $sha, 'addedBy' => $me, 'source' => $source, 'lyrics' => $lyrics !== null, 'at' => gmdate('Y-m-d\TH:i:s\Z')]; $this->playlist->files[$id] = $file; $this->playlist->add([$entry]); if ($lyrics !== null) { $this->lyricsUp[$id] = $lyrics; } $this->syncWanted = true; $this->syncClock = 99.0; $this->link?->send(['t' => 'push', 'entries' => [$id]]); $this->pushed[] = $id; } /** @var list<string> entries added here not told to the room yet (sent again once the sync wrote them) */ private array $pushed = []; public static function uuid(): string { $b = random_bytes(16); $b[6] = chr((ord($b[6]) & 0x0f) | 0x40); $b[8] = chr((ord($b[8]) & 0x3f) | 0x80); return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($b), 4)); } // --- receiving ------------------------------------------------------------------------------------------------- /** @var array<string, float> entry id => when the PC was last asked */ private array $asked = []; /** @var array<string, float> entry id => when the progress was last told to the PC */ private array $told = []; /** The device that can send an entry: its PC, or (YouTube failed here) any computer of the account online. */ private function senderOf(array $e): ?string { $source = (array)($e['source'] ?? []); if (($source['type'] ?? '') === 'pc') { return (string)($source['device'] ?? ''); } foreach ($this->link?->devices() ?? [] as $device => $kind) { if ($kind === 'desktop') { return $device; } } $by = (string)($e['addedBy'] ?? ''); return $by !== '' ? $by : null; } private function tickTransfers(float $dt): void { foreach ($this->transfers as $id => $t) { $sender = $this->senderOf($t->entry); $t->poll($dt); if ($t->state === 'lan' && ($this->told[$id] ?? 0) + 1.0 < $this->clock && $sender !== null) { $this->told[$id] = $this->clock; $this->link?->send(['t' => 'got', 'entry' => $id, 'bytes' => $t->received], $sender); } if (($t->state === 'waiting' || $t->state === 'lan') && $t->lanFailed && $sender !== null) { // the network of the house did not answer: the relay; a copy started by itself with "Wi-Fi seulement" // waits instead (no LAN = not at home: never the phone's mobile data by itself) $t->lanFailed = false; if ($t->auto && $this->wifiOnly && $this->account->kind === 'phone') { $t->state = 'waiting'; $this->asked[$id] = $this->clock + 40.0; continue; } $t->startRelay(); $this->link?->send(['t' => 'relay', 'entry' => $id, 'offset' => $t->received], $sender); } if ($t->state === 'done') { unset($this->transfers[$id], $this->asked[$id]); $this->playlist->setFile($id, $t->target); $sender !== null && $this->link?->send(['t' => 'thanks', 'entry' => $id], $sender); $this->wz->notice('Copié sur cet appareil : ' . Text::baseName($t->target), 5); continue; } if ($t->state === 'error') { $this->failed[$id] = ['state' => 'error', 'error' => $t->error]; unset($this->transfers[$id]); continue; } $here = $sender !== null && ($this->link?->has($sender) ?? false); if (in_array($t->state, ['waiting', 'offline'], true)) { if (!$here) { $t->offline(); } elseif ($t->state === 'offline' || ($this->asked[$id] ?? -999.0) + Transfer::SILENCE < $this->clock) { $t->state = 'waiting'; $this->asked[$id] = $this->clock; $t->idle = 0.0; $this->link->send(['t' => 'want', 'entry' => $id, 'sha256' => (string)($t->entry['sha256'] ?? ''), 'offset' => $t->received], $sender); } } elseif ($t->state === 'relay' && $t->idle > Transfer::SILENCE) { if (!$here) { $t->offline(); } else { $t->idle = 0.0; $this->link->send(['t' => 'relay', 'entry' => $id, 'offset' => $t->received], $sender); } } } } /** @param array<string, mixed> $m */ private function onMessage(string $from, array $m): void { $id = (string)($m['entry'] ?? ''); switch ($m['t'] ?? '') { case 'play': case 'playAsk': case 'sync': $this->playSync?->received($from, $m); break; case 'want': $this->wanted($from, $id, (int)($m['offset'] ?? 0)); break; case 'relay': $this->startSending($from, $id, (int)($m['offset'] ?? 0)); break; case 'got': if (isset($this->sending[$id])) { $s = &$this->sending[$id]; $s['progress'] = $s['size'] > 0 ? min(1.0, (int)($m['bytes'] ?? 0) / $s['size']) : 0.0; $s['since'] = $this->clock; unset($s); } break; case 'thanks': $this->stopSending($id); $this->lan?->done($id); break; case 'offer': $t = $this->transfers[$id] ?? null; if ($t !== null && in_array($t->state, ['waiting', 'offline'], true)) { $lan = array_values(array_filter((array)($m['lan'] ?? []), 'is_string')); if ($lan !== []) { $t->tryLan($lan); // lanFailed at once when none is usable: the relay next frame } else { $t->lanFailed = true; } } break; case 'nack': $t = $this->transfers[$id] ?? null; if ($t !== null) { if (($m['reason'] ?? '') === 'busy') { $t->state = 'waiting'; $this->asked[$id] = $this->clock; // the PC gets it first (YouTube): asked again later } else { $t->fail('Le PC n\'a plus ce fichier.'); } } break; case 'done': if (isset($this->transfers[$id])) { $this->transfers[$id]->sent(); } break; case 'push': $this->sync(); $this->pending = array_merge($this->pending ?? [], array_map('strval', (array)($m['entries'] ?? []))); break; } } /** @var list<string>|null entries pushed by another device, copied once the playlist read has them */ private ?array $pending = null; private function onChunk(string $from, string $entry, int $offset, string $bytes): void { $t = $this->transfers[$entry] ?? null; if ($t === null) { return; } if (!$t->chunk($offset, $bytes) && $t->state === 'relay') { $this->link?->send(['t' => 'relay', 'entry' => $entry, 'offset' => $t->received], $from); } } // --- sending (the PC) -------------------------------------------------------------------------------------------- /** A device asks for an entry this device has: offered on the LAN (when it can), the relay otherwise. */ private function wanted(string $from, string $id, int $offset): void { $e = $this->playlist->entry($id); $file = $this->playlist->fileOf($id); if ($e === null || $file === null) { if ($e !== null && ($e['source']['type'] ?? '') === 'youtube' && $this->wz->youtube !== null) { $this->startYoutube($id, $e); // the phone could not: this PC gets it (yt-dlp), then sends it $this->link?->send(['t' => 'nack', 'entry' => $id, 'reason' => 'busy'], $from); return; } $this->link?->send(['t' => 'nack', 'entry' => $id, 'reason' => 'missing'], $from); return; } $size = (int)filesize($file); $lan = $this->lan?->offer($file, $id) ?? []; $this->sending[$id] = ['to' => $from, 'mode' => 'lan', 'offset' => $offset, 'size' => $size, 'fh' => null, 'since' => $this->clock, 'progress' => $size > 0 ? min(1.0, $offset / $size) : 0.0]; $this->link?->send(['t' => 'offer', 'entry' => $id, 'size' => $size, 'lan' => $lan, 'exp' => (int)LanShare::TTL], $from); } private function startSending(string $to, string $id, int $offset): void { $file = $this->playlist->fileOf($id); if ($file === null) { $this->link?->send(['t' => 'nack', 'entry' => $id, 'reason' => 'missing'], $to); return; } $this->stopSending($id); $fh = @fopen($file, 'rb'); if ($fh === false) { $this->link?->send(['t' => 'nack', 'entry' => $id, 'reason' => 'missing'], $to); return; } $size = (int)filesize($file); fseek($fh, max(0, min($offset, $size))); $this->sending[$id] = ['to' => $to, 'mode' => 'relay', 'offset' => max(0, min($offset, $size)), 'size' => $size, 'fh' => $fh, 'since' => $this->clock, 'progress' => $size > 0 ? $offset / $size : 0.0]; } /** The relay: a few chunks a frame to each device that asked (the relay keeps the order). */ private function tickSending(): void { foreach ($this->sending as $id => &$s) { if ($s['mode'] === 'relay' && $s['fh'] !== null) { for ($i = 0; $i < 4 && $s['offset'] < $s['size']; $i++) { $bytes = (string)fread($s['fh'], CloudLink::CHUNK_BYTES); if ($bytes === '' || !($this->link?->sendChunk($id, $s['offset'], $bytes, $s['to']) ?? false)) { fseek($s['fh'], $s['offset']); // not sent: again next frame break; } $s['offset'] += strlen($bytes); $s['since'] = $this->clock; } $s['progress'] = $s['size'] > 0 ? $s['offset'] / $s['size'] : 1.0; if ($s['offset'] >= $s['size']) { fclose($s['fh']); $s['fh'] = null; $s['mode'] = 'sent'; $this->link?->send(['t' => 'done', 'entry' => $id], $s['to']); } } if ($this->clock - $s['since'] > 60.0) { $gone[] = $id; // nothing for a minute: given up (the phone asks again when it comes back) } } unset($s); foreach ($gone ?? [] as $id) { $this->stopSending($id); } // entries this PC added, told again to the room once on the server (a phone that read the playlist before) if ($this->pushed !== [] && $this->playlist->ops === [] && !$this->playlist->syncing) { $this->link?->send(['t' => 'push', 'entries' => $this->pushed]); $this->pushed = []; } if ($this->pending !== null && !$this->playlist->syncing) { $ids = array_values(array_filter($this->pending, fn (string $id) => $this->playlist->entry($id) !== null)); $this->autoCopies($ids); $this->pending = count($ids) === count($this->pending) ? null : array_values(array_diff($this->pending, $ids)); if ($this->pending === []) { $this->pending = null; } } } private function stopSending(string $id): void { if (isset($this->sending[$id]['fh']) && is_resource($this->sending[$id]['fh'])) { fclose($this->sending[$id]['fh']); } unset($this->sending[$id]); } private function closeSending(): void { foreach (array_keys($this->sending) as $id) { $this->stopSending($id); } } // --- YouTube --------------------------------------------------------------------------------------------------- /** @param array<string, mixed> $e */ private function startYoutube(string $id, array $e): void { $yt = $this->wz->youtube; if ($yt === null || isset($this->youtubeJobs[$id])) { return; } $source = (array)($e['source'] ?? []); $videoId = (string)($source['videoId'] ?? ''); $url = $videoId !== '' ? 'https://www.youtube.com/watch?v=' . $videoId : 'ytsearch1:' . (string)($source['query'] ?? $e['title'] ?? ''); $yt->download(['id' => $url, 'title' => trim(($e['artist'] ?? '') . ' - ' . ($e['title'] ?? ''), ' -'), 'url' => $url], 'mp3', self::PSEUDO . $id); $this->youtubeJobs[$id] = ['url' => $url, 'since' => $this->clock]; } /** The YouTube downloads of cloud entries: their file once there; failed here: the PC is asked for it. */ private function tickYoutube(): void { $yt = $this->wz->youtube; if ($yt === null) { return; } foreach ($this->youtubeJobs as $id => $job) { $have = $yt->alreadyHave(self::PSEUDO . $id, $job['url']); if ($have !== null && $have !== 'en attente' && is_file($have)) { unset($this->youtubeJobs[$id]); $this->playlist->setFile($id, $have); $this->link?->send(['t' => 'push', 'entries' => [$id]]); // a device that waited for it (the PC fallback) } elseif ($have === null) { unset($this->youtubeJobs[$id]); $e = $this->playlist->entry($id); $sender = $e !== null ? $this->senderOf($e) : null; if ($e !== null && $sender !== null && $sender !== $this->deviceId()) { // YouTube did not give it here: the PC sends it (it has it, or gets it with yt-dlp first) $this->transfers[$id] = new Transfer($e, $this->targetOf($e)); $this->asked[$id] = -999.0; } else { $this->failed[$id] = ['state' => 'error', 'error' => 'YouTube ne l\'a pas donnée']; } } } } // --- the end --------------------------------------------------------------------------------------------------- /** WinZik quits (stopHelpers): the room left, the LAN server closed, the files closed (the parts stay: resumed next time). */ public function stop(): void { $this->closeSending(); $this->lan?->close(); $this->link?->close(); foreach ($this->transfers as $t) { $t->offline(); } $this->playlist->save(); }}