tmp = sys_get_temp_dir() . '/winzik-cloud-' . bin2hex(random_bytes(4)); @mkdir($this->tmp, 0777, true); $this->server = new FakeCloudServer(); $this->relay = new FakeRelay(); } protected function tearDown(): void { exec('rm -rf ' . escapeshellarg($this->tmp)); } /** @return array{0: WinZik, 1: Cloud} a device of the account (desktop or phone), signed out */ private function device(string $name, string $kind, bool $lan = false): array { $wz = new WinZik(); $account = new CloudAccount(fn (string $m, string $u, string|array|null $b, array $h) => $this->server->request($m, $u, $b, $h), FakeCloudServer::BASE, "$this->tmp/$name/cloud.json", $kind); $share = null; if ($lan) { $share = new LanShare(); $share->addresses = ['127.0.0.1']; } $cloud = new Cloud($wz, $account, "$this->tmp/$name/cloud", fn () => $this->relay->session(), $share, "$this->tmp/$name/received"); $wz->useCloud($cloud); return [$wz, $cloud]; } /** A song of this test (a copy of the demo song with some bytes of its own: never the demo itself). */ private function song(string $name, int $extra = 0): string { $file = "$this->tmp/pc-music/$name.mp3"; @mkdir(dirname($file), 0777, true); copy(__DIR__ . '/../assets/music/winzik.mp3', $file); if ($extra > 0) { file_put_contents($file, random_bytes($extra), FILE_APPEND); } return $file; } /** @param list $clouds each tick of every device, until $until says yes */ private function frames(array $clouds, \Closure $until, int $max = 4000): void { for ($i = 0; $i < $max; $i++) { foreach ($clouds as $c) { $c->tick(0.05); } if ($until()) { return; } } self::fail('not reached after ' . $max . ' frames'); } private static function value(\JumPHP\Async\Task $task): mixed { self::assertTrue($task->isDone()); if ($task->error() !== null) { throw $task->error(); } return $task->result(); } public function testCreatingAnAccountGivesTheRecoveryCodeOnceAndKeepsTheDeviceToken(): void { [, $pc] = $this->device('pc', 'desktop'); self::assertSame('signedOut', $pc->state()); self::assertSame('Ordinateur', $pc->deviceName(), 'a name with nothing personal in it'); $data = self::value($pc->signUp('Ada', 'motdepasse1')); self::assertSame('ABCD-EFGH-IJKL-MNOP-QRST', $data['recovery']); self::assertTrue($pc->signedIn()); $saved = json_decode((string)file_get_contents("$this->tmp/pc/cloud.json"), true); self::assertStringStartsWith('wzd_', $saved['token']); self::assertArrayNotHasKey('recovery', $saved, 'the recovery code is never kept'); self::assertArrayNotHasKey('Authorization', $this->server->headers[0], 'no token on the sign up'); // the phone: a wrong password, then the right one [, $phone] = $this->device('phone', 'phone'); self::assertSame('Téléphone', $phone->deviceName()); $wrong = $phone->signIn('ada', 'nope'); self::assertSame('Pseudo ou mot de passe incorrect.', $wrong->error()?->getMessage()); self::value($phone->signIn('ada', 'motdepasse1', 'Mon téléphone')); $devices = self::value($phone->refreshDevices()); self::assertSame(['Ordinateur', 'Mon téléphone'], array_column($devices, 'name')); // the PC signs the phone out: its next request finds it revoked, it is signed out by itself $phoneId = $phone->deviceId(); self::value($pc->revoke($phoneId)); $phone->tick(0.05); self::assertSame('signedOut', $phone->state()); self::assertSame('', json_decode((string)file_get_contents("$this->tmp/phone/cloud.json"), true)['token']); } public function testChangesMadeOfflineAreKeptThenMergedByIdAfterAConflict(): void { [, $pc] = $this->device('pc', 'desktop'); self::value($pc->signUp('ada', 'motdepasse1')); $pc->tick(0.05); self::assertSame('online', $pc->state()); $this->server->offline = true; $pc->putFromPc([$this->song('a'), $this->song('b', 100)]); $this->frames([$pc], fn () => count($pc->entries()) === 2 && $pc->state() === 'offline'); self::assertCount(2, $pc->playlist->ops, 'kept to be sent'); self::assertSame(0, count($this->server->accounts['ada']['entries'])); $saved = json_decode((string)file_get_contents("$this->tmp/pc/cloud/playlist.json"), true); self::assertCount(2, $saved['entries'], 'the offline copy is on the disk'); // back online; meanwhile another device wrote: 412, the changes replayed on its version $this->server->offline = false; $this->server->conflicts = 1; $pc->sync(); $this->frames([$pc], fn () => $pc->playlist->ops === [] && !$pc->playlist->syncing, 2000); $server = $this->server->accounts['ada']['entries']; self::assertCount(3, $server, 'nothing lost: the other device\'s entry and both of this one'); self::assertSame("De l'autre appareil", $server[0]['title']); self::assertSame(array_column($server, 'id'), array_column($pc->entries(), 'id')); self::assertContains('PUT /cloud/playlist', $this->server->log); self::assertSame(64, strlen((string)$server[1]['sha256'])); self::assertSame(hash_file('sha256', $this->song('a')), $server[1]['sha256']); // removed here: removed there $pc->remove([$server[0]['id']]); $pc->sync(); $this->frames([$pc], fn () => $pc->playlist->ops === [] && !$pc->playlist->syncing, 2000); self::assertCount(2, $this->server->accounts['ada']['entries']); } public function testTheLanShareGivesAFileThatIsCutThenResumedWhereItWas(): void { $file = $this->song('big', 3 << 20); $share = new LanShare(); $share->addresses = ['127.0.0.1']; $urls = $share->offer($file, 'e1'); self::assertCount(1, $urls); self::assertMatchesRegularExpression('#^http://127\.0\.0\.1:\d+/f/[0-9a-f]{32}$#', $urls[0]); $entry = ['id' => 'e1', 'size' => filesize($file), 'sha256' => hash_file('sha256', $file)]; $target = "$this->tmp/phone/big.mp3"; $t = new Transfer($entry, $target); $t->tryLan($urls); for ($i = 0; $i < 2000 && $t->received < (1 << 20); $i++) { $share->poll(); $t->poll(0.01); } self::assertGreaterThanOrEqual(1 << 20, $t->received); self::assertSame(200, $t->lastStatus); // the PC goes away in the middle: the part stays $share->close(); for ($i = 0; $i < 400 && !$t->lanFailed; $i++) { $t->poll(0.01); } self::assertTrue($t->lanFailed, 'the network way given up after a few tries'); $part = (int)filesize($target . '.part'); self::assertGreaterThan(0, $part); self::assertFileDoesNotExist($target); // it comes back: a new offer, the copy goes on from the part (Range: 206), whole and checked $t2 = new Transfer($entry, $target); self::assertSame($part, $t2->received); $t2->tryLan($share->offer($file, 'e1')); for ($i = 0; $i < 4000 && $t2->state === 'lan'; $i++) { $share->poll(); $t2->poll(0.01); } self::assertSame('done', $t2->state, $t2->error); self::assertSame(206, $t2->lastStatus, 'resumed, not sent again from the start'); self::assertSame(hash_file('sha256', $file), hash_file('sha256', $target)); self::assertFileDoesNotExist($target . '.part'); // an unknown token, another one's address: 404 / nothing $share->done('e1'); self::assertFalse(Transfer::lanUrl('http://8.8.8.8:47610/f/abc'), 'never a server of the Internet'); self::assertFalse(Transfer::lanUrl('https://192.168.1.2/f/abc')); self::assertTrue(Transfer::lanUrl('http://192.168.1.2:47610/f/abc')); $share->close(); } public function testAFileWhoseSha256DoesNotMatchIsThrownAway(): void { $file = $this->song('bad', 1000); $share = new LanShare(); $share->addresses = ['127.0.0.1']; $t = new Transfer(['id' => 'e2', 'size' => filesize($file), 'sha256' => str_repeat('0', 64)], "$this->tmp/phone/bad.mp3"); $t->tryLan($share->offer($file, 'e2')); for ($i = 0; $i < 2000 && $t->active(); $i++) { $share->poll(); $t->poll(0.01); } $share->close(); self::assertSame('error', $t->state); self::assertStringContainsString('SHA-256', $t->error); self::assertFileDoesNotExist("$this->tmp/phone/bad.mp3"); self::assertFileDoesNotExist("$this->tmp/phone/bad.mp3.part"); } public function testMessagesAreSealedWithTheAccountKey(): void { $key = random_bytes(32); $sealed = CloudLink::seal($key, 'bonjour le téléphone'); self::assertStringNotContainsString('bonjour', $sealed); self::assertSame('bonjour le téléphone', CloudLink::open($key, $sealed)); self::assertNull(CloudLink::open(random_bytes(32), $sealed), 'another key: nothing'); $sealed[40] = chr(ord($sealed[40]) ^ 1); self::assertNull(CloudLink::open($key, $sealed), 'changed on the way: refused'); self::assertNotSame(CloudLink::seal($key, 'x'), CloudLink::seal($key, 'x'), 'a fresh nonce each time'); } public function testThePcSendsItsSongToThePhoneThroughTheEncryptedRelayWithItsLyrics(): void { [, $pc] = $this->device('pc', 'desktop'); [$phoneWz, $phone] = $this->device('phone', 'phone'); self::value($pc->signUp('ada', 'motdepasse1')); self::value($phone->signIn('ada', 'motdepasse1')); $phone->wifiOnly = false; // the relay on its own (no LAN here) $song = $this->song('chanson', 200000); file_put_contents(substr($song, 0, -4) . '.lyr', "[00:01.00]Première ligne\n[00:03.00]Deuxième ligne\n"); $this->frames([$pc, $phone], fn () => ($pc->link?->inRoom() ?? false) && ($phone->link?->inRoom() ?? false) && $pc->link->has($phone->deviceId()) && $phone->link->has($pc->deviceId())); self::assertSame(1, $pc->putFromPc([$song])); self::assertTrue($pc->fileState($song)['cloud'], 'marked at once (☁)'); $id = ''; $this->frames([$pc, $phone], function () use ($phone, &$id): bool { $id = (string)($phone->entries()[0]['id'] ?? ''); return $id !== '' && $phone->rowState($id)['state'] === 'copying'; }); self::assertSame('sending', $pc->rowState($id)['state'], 'the PC shows its % while it sends'); $this->frames([$pc, $phone], fn () => $phone->rowState($id)['state'] === 'here'); $received = (string)$phone->playlist->fileOf($id); self::assertSame("$this->tmp/phone/received/WinZik Band - WinZik.mp3", $received, "named after its tag"); self::assertSame(hash_file('sha256', $song), hash_file('sha256', $received)); // the relay saw only ciphertext $plain = substr((string)file_get_contents($song), 50000, 64); foreach ($this->relay->traffic as $message) { self::assertStringNotContainsString($plain, $message); self::assertStringNotContainsString('"want"', $message); } // the lyrics: in the account, then here, in WinZik's own copy of the song's lyrics self::assertStringContainsString('Première ligne', $this->server->accounts['ada']['lyrics'][$id] ?? ''); $this->frames([$pc, $phone], fn () => is_file($phoneWz->lyricsCachePath($received))); self::assertStringContainsString('Deuxième ligne', (string)file_get_contents($phoneWz->lyricsCachePath($received))); @unlink($phoneWz->lyricsCachePath($received)); // the PC stopped sending $this->frames([$pc, $phone], fn () => $pc->rowState($id)['state'] === 'here'); // the PC away: the next one waits ("PC hors ligne") $pc->stop(); $second = $this->song('deux', 10); $this->server->accounts['ada']['entries'][] = ['id' => 'abcdef12-0000-4000-8000-000000000002', 'title' => 'Deux', 'artist' => '', 'duration' => 1, 'size' => filesize($second), 'sha256' => hash_file('sha256', $second), 'addedBy' => $pc->deviceId(), 'source' => ['type' => 'pc', 'device' => $pc->deviceId()], 'lyrics' => false, 'at' => '2026-11-20T10:00:00Z']; $this->server->accounts['ada']['version']++; $phone->sync(); $this->frames([$phone], fn () => $phone->rowState('abcdef12-0000-4000-8000-000000000002')['state'] === 'offline'); self::assertSame('PC hors ligne – en attente', $phone->rowState('abcdef12-0000-4000-8000-000000000002')['text']); } public function testTheTranslationsMadeOnThePcComeDownToThePhoneInItsLyrics(): void { [$pcWz, $pc] = $this->device('pc', 'desktop'); [$phoneWz, $phone] = $this->device('phone', 'phone'); self::value($pc->signUp('ada', 'motdepasse1')); self::value($phone->signIn('ada', 'motdepasse1')); $phone->wifiOnly = false; $song = $this->song('traduite', 1000); file_put_contents(substr($song, 0, -4) . '.lyr', "[LYR]\r\n[NON SYNCHRONISEES]\r\nI walk alone tonight\r\nAnd the city is my friend\r\n"); $this->frames([$pc, $phone], fn () => ($pc->link?->inRoom() ?? false) && ($phone->link?->inRoom() ?? false) && $pc->link->has($phone->deviceId()) && $phone->link->has($pc->deviceId())); self::assertSame(1, $pc->putFromPc([$song])); $id = ''; $this->frames([$pc, $phone], function () use ($phone, &$id): bool { $id = (string)($phone->entries()[0]['id'] ?? ''); return $id !== '' && $phone->rowState($id)['state'] === 'here'; }); $received = (string)$phone->playlist->fileOf($id); $this->frames([$pc, $phone], fn () => is_file($phoneWz->lyricsCachePath($received))); $here = \App\Model\Lyrics::load($phoneWz->lyricsCachePath($received)); self::assertNotNull($here); self::assertFalse($here->synced, 'lyrics without times go through the cloud as they are'); self::assertSame([], $here->translations); // the PC translates them (what translate() saves): up to the account $translated = \App\Model\Lyrics::load($song === '' ? '' : substr($song, 0, -4) . '.lyr'); self::assertNotNull($translated); $translated->setTranslations(['Je marche seul ce soir', 'Et la ville est mon amie'], 'fr'); self::assertNotNull($pcWz->saveLyrics($song, $translated)); $this->frames([$pc, $phone], fn () => str_contains($this->server->accounts['ada']['lyrics'][$id] ?? '', '[TRADUCTION fr]')); // the phone opens the song: its lyrics are looked at again (a conditional GET) and come down with the translation $phone->lyricsCheck($received); $this->frames([$pc, $phone], fn () => str_contains((string)@file_get_contents($phoneWz->lyricsCachePath($received)), '[TRADUCTION fr]')); self::assertTrue($phoneWz->hasTranslation($received, 'fr')); self::assertSame('Et la ville est mon amie', $phoneWz->translations($received)[1]); // looked at again: not changed (304), nothing written $n = count($this->server->log); $phone->tick(\App\Cloud\Cloud::LYRICS_RECHECK + 1); $phone->lyricsCheck($received); self::assertContains('GET /cloud/lyrics/' . $id, array_slice($this->server->log, $n)); // changed on the phone and not sent yet: never replaced file_put_contents($phoneWz->lyricsCachePath($received), "[LYR]\r\n[NON SYNCHRONISEES]\r\nModifiée sur le téléphone\r\n"); $phone->tick(\App\Cloud\Cloud::LYRICS_RECHECK + 1); $phone->lyricsCheck($received); $phone->tick(0.05); self::assertStringContainsString('Modifiée sur le téléphone', (string)file_get_contents($phoneWz->lyricsCachePath($received))); @unlink($phoneWz->lyricsCachePath($received)); @unlink($pcWz->lyricsCachePath($song)); } public function testThePhoneTakesTheSongOnTheHouseNetworkWhenThePcCanShareIt(): void { [, $pc] = $this->device('pc', 'desktop', lan: true); [, $phone] = $this->device('phone', 'phone'); self::value($pc->signUp('ada', 'motdepasse1')); self::value($phone->signIn('ada', 'motdepasse1')); $song = $this->song('maison', 500000); $this->frames([$pc, $phone], fn () => ($phone->link?->has($pc->deviceId()) ?? false) && ($pc->link?->has($phone->deviceId()) ?? false)); $pc->putFromPc([$song]); $id = ''; $this->frames([$pc, $phone], function () use ($phone, &$id): bool { $id = (string)($phone->entries()[0]['id'] ?? ''); return $id !== '' && $phone->rowState($id)['state'] === 'here'; }); self::assertSame(hash_file('sha256', $song), hash_file('sha256', (string)$phone->playlist->fileOf($id))); $chunks = array_filter($this->relay->traffic, fn (string $m) => ord($m[0]) === CloudLink::CHUNK); self::assertSame([], $chunks, 'nothing of the file went through the relay'); $this->frames([$pc, $phone], fn () => !($pc->lan?->isOpen() ?? true)); $pc->stop(); $phone->stop(); } public function testTheCloudViewIsAPlaylistOfItsOwnAndTheUsersListIsKept(): void { [$wz, $pc] = $this->device('pc', 'desktop'); $mine = $this->song('mienne'); $wz->playlist = new \App\Model\Playlist([$mine]); self::value($pc->signUp('ada', 'motdepasse1')); $pc->useView('cloud'); self::assertSame('cloud', $pc->view()); self::assertSame([], $wz->playlist->items); self::assertSame([$mine], $pc->localPlaylist()?->items, 'the user\'s own list is what WinZik keeps'); // added to the cloud view: it goes in the cloud $wz->playlist->add($song = $this->song('nuage', 5)); $this->frames([$pc], fn () => count($pc->entries()) === 1 && $pc->playlist->ops === []); self::assertSame([$song], $wz->playlist->items); // an entry not here: a cloud line $this->server->accounts['ada']['entries'][] = ['id' => 'abcdef12-0000-4000-8000-000000000003', 'title' => 'Ailleurs', 'artist' => 'X', 'duration' => 1, 'size' => 10, 'sha256' => str_repeat('a', 64), 'addedBy' => 'bbbbbbbbbbbb', 'source' => ['type' => 'pc', 'device' => 'bbbbbbbbbbbb'], 'lyrics' => false, 'at' => '2026-11-20T10:00:00Z']; $this->server->accounts['ada']['version']++; $pc->sync(); $this->frames([$pc], fn () => count($wz->playlist->items) === 2); self::assertSame(Cloud::PSEUDO . 'abcdef12-0000-4000-8000-000000000003.mp3', $wz->playlist->items[1]); self::assertSame('offline', $pc->rowState('abcdef12-0000-4000-8000-000000000003')['state']); // Suppr on it: removed from the cloud $wz->playlist->remove([1]); $this->frames([$pc], fn () => count($this->server->accounts['ada']['entries']) === 1); $pc->useView('local'); self::assertSame([$mine], $wz->playlist->items); } public function testASongForYouTubeKnowsItsVideoAndAPhoneWithoutYouTubeGetsItFromThePc(): void { [$pcWz, $pc] = $this->device('pc', 'desktop'); [, $phone] = $this->device('phone', 'phone'); self::value($pc->signUp('ada', 'motdepasse1')); self::value($phone->signIn('ada', 'motdepasse1')); $phone->wifiOnly = false; $song = $this->song('clip', 1000); $sources = $pcWz->storagePath('youtube-sources.json'); @mkdir(dirname($sources), 0777, true); $before = is_file($sources) ? (string)file_get_contents($sources) : null; file_put_contents($sources, (string)json_encode([$song => 'https://www.youtube.com/watch?v=dQw4w9WgXcQ'])); try { self::assertSame(['type' => 'youtube', 'videoId' => 'dQw4w9WgXcQ', 'query' => 'WinZik Band WinZik'], $pc->youtubeSource($song)); self::assertSame(1, $pc->putFromYoutube([$song])); } finally { $before === null ? @unlink($sources) : file_put_contents($sources, $before); } $this->frames([$pc, $phone], fn () => ($this->server->accounts['ada']['entries'][0]['source']['type'] ?? '') === 'youtube'); $id = (string)$this->server->accounts['ada']['entries'][0]['id']; self::assertSame('dQw4w9WgXcQ', $this->server->accounts['ada']['entries'][0]['source']['videoId']); // this phone has no YouTube: the PC (which has the file) sends it $this->frames([$pc, $phone], fn () => $phone->rowState($id)['state'] === 'here'); self::assertSame(hash_file('sha256', $song), hash_file('sha256', (string)$phone->playlist->fileOf($id))); } }