PT
apps/winzik / tests / MobileFeaturesTest.php · commit 6576d6f
<?phpnamespace Tests;use App\Audio\Player;use App\Core\Market;use App\Core\WinZik;use App\Form\MainForm;use App\Form\MobileForm;use App\Media\Process;use App\Media\Tools;use App\Mobile\MobileView;use JumPHP\Async\Task;use JumPHP\Gui\Pointer;use JumPHP\Http\Http;use JumPHP\Http\HttpResponse;use JumPHP\Testing\GameTestCase;/** * The features of the computer brought to the phone (390 x 844 dp): YouTube, Spotify, the karaoke and the lyrics editor, * the films, the tag, the marketplace, the play lists, the Options, the updates of the app, the interface of 2001. * Without network: yt-dlp / ffmpeg, Spotify and the marketplace are fakes that answer at once. */final class MobileFeaturesTest extends GameTestCase{    private MobileForm $form;    private MobileView $view;    private WinZik $wz;    private string $music = '';    private string $videos = '';    private function startPhone(array $params = []): void    {        $this->game->start(MobileForm::class, ['fresh' => true, 'phone' => true] + $params);        $form = $this->game->scene();        self::assertInstanceOf(MobileForm::class, $form);        $this->form = $form;        $view = $form->widget('view');        self::assertInstanceOf(MobileView::class, $view);        $this->view = $view;        $this->wz = $form->winzik();        $this->wz->playlist->shuffle = false;        $this->wz->notice = '';        $this->game->run(3);    }    private function tap(string $id, mixed $data = null, int $frames = 2): void    {        $at = $this->view->at($id, $data);        self::assertNotNull($at, "$id " . json_encode($data) . ' is on the screen (' . implode(', ', $this->view->touchable()) . ')');        $this->form->clickAt($at[0], $at[1]);        $this->game->run($frames);    }    /** The page scrolled until something is on the screen, then tapped. */    private function tapScrolled(string $id, mixed $data = null, int $frames = 2): void    {        $key = 'page:' . $this->view->screen;        for ($i = 0; $i < 40 && $this->view->at($id, $data) === null; $i++) {            $this->view->scroll[$key] = ($this->view->scroll[$key] ?? 0.0) + 120;            $this->game->run(1);        }        $this->tap($id, $data, $frames);    }    private function shot(string $name): void    {        $this->game->run(1);        $file = $this->game->shot($name);        $image = @imagecreatefrompng($file);        if ($image === false) {            return;        }        [$x, $y, $w, $h] = $this->view->screenRect();        $crop = imagecrop($image, ['x' => (int)$x, 'y' => (int)$y, 'width' => (int)round($w), 'height' => (int)round($h)]);        if ($crop !== false) {            imagepng($crop, $file);        }    }    private function back(float $wait = 0.4): void    {        $this->form->key(Pointer::ESCAPE);        $this->game->wait($wait);    }    /** "yt-dlp" and "ffmpeg" that answer at once, as in MediaTest: two results, an MP3, an MP4 and its pictures. */    private function fakeTools(bool $failMp3 = false): void    {        $this->music = $this->wz->storagePath('test/Musique');        $this->videos = $this->wz->storagePath('test/Videos');        $tools = new Tools($this->wz->storagePath('bin'), $this->wz->storagePath('tmp'));        $tools->state = ['yt-dlp' => 'ready', 'ffmpeg' => 'ready'];        $tools->path = ['yt-dlp' => '/fake/yt-dlp', 'ffmpeg' => '/fake/ffmpeg'];        $song = $this->wz->path('assets/music/partage.mp3');        $runner = function (array $cmd) use ($song, $failMp3): Process {            $line = implode(' ', $cmd);            if (in_array('-J', $cmd, true)) {                return Process::finished($cmd, [(string)json_encode(['entries' => [                    ['id' => 'aaa', 'title' => 'Partage (clip officiel)', 'channel' => 'WinZik Band', 'duration' => 199, 'url' => 'https://www.youtube.com/watch?v=aaa'],                    ['id' => 'bbb', 'title' => 'Partage (live)', 'channel' => 'WinZik Band', 'duration' => 3725, 'url' => 'https://www.youtube.com/watch?v=bbb'],                ]])]);            }            if (str_contains($line, '--audio-format mp3')) {                if ($failMp3) {                    return Process::finished($cmd, ['ERROR: ffmpeg introuvable sur ce téléphone'], 1);                }                $name = str_contains($line, 'Mistral') ? 'Renaud - Mistral gagnant' : 'Partage (clip officiel)';                $file = $this->music . '/' . $name . '.mp3';                return Process::finished($cmd, ['[download]  42.0% of 3.10MiB', '[download] 100.0% of 3.10MiB', $file], 0, function () use ($song, $file): void {                    @mkdir(dirname($file), 0777, true);                    copy($song, $file);                });            }            if (str_contains($line, '--merge-output-format mp4')) {                $file = $this->videos . '/Partage (clip officiel).mp4';                return Process::finished($cmd, ['[download] 100.0% of 9MiB', $file], 0, function () use ($file): void {                    @mkdir(dirname($file), 0777, true);                    file_put_contents($file, 'film');                });            }            if (str_ends_with($line, 'audio.wav') || (str_contains($line, 'equalizer=') && str_contains($line, 'pcm_s16le'))) {                return Process::finished($cmd, [], 0, fn () => copy($this->wz->path('assets/music/chaine-hifi.wav'), (string)end($cmd)));            }            if (str_contains($line, '%06d.jpg')) {                // the film's pictures: wide ones (16:9), PNG data                return Process::finished($cmd, [], 0, function () use ($cmd): void {                    foreach ([[220, 60, 90], [60, 200, 120], [60, 90, 220]] as $i => [$r, $g, $b]) {                        $im = imagecreatetruecolor(160, 90);                        imagefill($im, 0, 0, (int)imagecolorallocate($im, $r, $g, $b));                        imagefilledellipse($im, 80, 45, 50, 50, (int)imagecolorallocate($im, 255, 255, 255));                        imagepng($im, sprintf(dirname((string)end($cmd)) . '/%06d.jpg', $i + 1));                    }                });            }            return Process::finished($cmd, [], 1);        };        $this->wz->useMedia($tools, \Closure::fromCallable($runner), $this->music, $this->videos);    }    public function testYouTubeSearchesAndDownloadsAnMp3IntoThePlaylist(): void    {        $this->startPhone();        $this->fakeTools();        $before = $this->wz->playlist->count();        $this->tap('tab', 'more', 15);        $this->tap('goto', 'youtube', 15);        self::assertSame('youtube', $this->view->screen);        $this->tap('field', 'ytQuery');        self::assertTrue($this->view->wantsText(), 'the keyboard of the phone opens');        $this->form->type("partage winzik\n");        $this->game->run(10);        self::assertCount(2, $this->wz->youtube->results);        $this->shot('mobile-youtube');        $this->tapScrolled('ytGet', 0, 20);        self::assertSame($before + 1, $this->wz->playlist->count(), 'the MP3 in the play list');        self::assertFileExists($this->music . '/Partage (clip officiel).mp3');        self::assertSame('done', $this->wz->youtube->jobs[0]['state']);        $this->view->scroll['page:youtube'] = 0;        $this->wz->notice = '';        $this->shot('mobile-youtube-telecharge');        $this->back();        self::assertSame('player', $this->view->screen, 'back: where it came from');    }    public function testADownloadThatFailsSaysWhyAndIsTriedAgain(): void    {        $this->startPhone(['screen' => 'youtube']);        $this->fakeTools(true);        $this->game->run(2);        $this->view->fields['ytQuery'] = 'partage';        $this->tap('ytFind', null, 10);        $this->tapScrolled('ytGet', 1, 10);        $job = $this->wz->youtube->jobs[0];        self::assertSame('error', $job['state']);        self::assertNotSame('', $job['error'], 'what the downloader said');        self::assertNotNull($this->view->at('ytRetry', 0), 'shown with its retry button');        $this->shot('mobile-youtube-erreur');        $this->tapScrolled('ytRetry', 0, 10);        self::assertCount(1, $this->wz->youtube->jobs, 'the same line again, not a second one');        self::assertSame('error', $this->wz->youtube->jobs[0]['state']);        $this->tapScrolled('ytRemove', 0);        self::assertSame([], $this->wz->youtube->jobs);    }    public function testAnMp4IsShownOnTheLecteurThenOnTheWholeScreenTurned(): void    {        $this->startPhone(['screen' => 'youtube']);        $this->fakeTools();        $this->game->run(2);        $this->view->fields['ytQuery'] = 'partage';        $this->tap('ytFind', null, 10);        $this->tap('ytFormat', 'mp4');        self::assertSame('mp4', $this->wz->options['ytFormat']);        $this->tapScrolled('ytGet', 0, 20);        $film = $this->videos . '/Partage (clip officiel).mp4';        $index = array_search($this->wz->relative($film), $this->wz->playlist->items, true);        self::assertIsInt($index, 'the film is in the list');        $this->back();        $this->wz->playIndex($index);        $this->game->run(20);        self::assertTrue($this->wz->playingVideo());        self::assertNotNull($this->wz->videoFrame(), 'a picture of the film');        $this->wz->notice = '';        $this->shot('mobile-video-lecteur');        $this->tap('art', null, 5);        self::assertSame('video', $this->view->screen);        $this->shot('mobile-video-plein-ecran');        $this->game->wait(3.5);        $this->shot('mobile-video-sans-boutons');        $this->tap('videoTap');        $this->tap('play');        self::assertSame(Player::PAUSED, $this->wz->player->state);        $this->back();        self::assertSame('player', $this->view->screen);    }    public function testSpotifyConnectsListsThePlaylistsAndImportsOneThroughYouTube(): void    {        $this->startPhone();        $this->fakeTools();        $this->wz->options['spotifyRefresh'] = 'ref';     // connected before        $this->wz->spotifyRequest = function (string $method, string $url, ?string $body, array $headers): Task {            $json = match (true) {                str_contains($url, '/api/token') => [200, ['access_token' => 'tok', 'expires_in' => 3600, 'refresh_token' => 'ref']],                str_contains($url, '/me/playlists') => [200, ['items' => [['id' => 'p1', 'name' => 'Ma playlist', 'tracks' => ['total' => 1]]], 'next' => null]],                str_contains($url, '/me/tracks') => [200, ['items' => [], 'next' => null]],                str_contains($url, '/playlists/p1/') => [200, ['items' => [['track' => ['type' => 'track', 'name' => 'Mistral gagnant', 'artists' => [['name' => 'Renaud']]]]], 'next' => null]],                default => [500, []],            };            $t = new Task();            $t->settle(new HttpResponse($json[0], (string)json_encode($json[1])));            return $t;        };        // no Client ID: the page says where to get one, typed here        $this->view->go('spotify');        $this->game->run(2);        self::assertNotNull($this->view->at('field', 'spotifyId'));        $this->shot('mobile-spotify-client-id');        $this->tap('field', 'spotifyId');        // an id of its own: WinZik keeps one account per id (SpotifyTest has its own fake)        $this->form->type("client-mobile\n");        $this->game->run(5);        self::assertSame('client-mobile', $this->wz->options['spotifyId']);        $this->game->run(10);        self::assertSame(['Titres likés', 'Ma playlist'], array_column($this->view->spLists, 'name'));        $this->shot('mobile-spotify');        $this->tapScrolled('spImport', 1, 30);        self::assertStringContainsString('1 morceau(x) ajouté(s)', $this->view->spMessage);        self::assertFileExists($this->music . '/Renaud - Mistral gagnant.mp3', 'found on YouTube and downloaded');    }    public function testTheKaraokeLightsTheSyllablesAndTheLyricsCanBeShifted(): void    {        $this->startPhone();        $line = array_search('assets/music/winzik.mp3', $this->wz->playlist->items, true);        self::assertIsInt($line);        $this->wz->playIndex($line);        $this->wz->seek(17.0);        $this->game->wait(1);        self::assertNotNull($this->wz->lyrics);        $this->tap('lyricsBox', null, 5);        self::assertSame('karaoke', $this->view->screen);        $this->game->wait(0.6);        $this->wz->notice = '';        $this->shot('mobile-karaoke');        $first = $this->wz->lyrics->lines[0][0];        $this->tap('lyShift', 1);        self::assertEqualsWithDelta($first + 0.5, $this->wz->lyrics->lines[0][0], 0.01, '+0,5 s: the lyrics later, saved');        $this->tap('lyShift', -1);        self::assertEqualsWithDelta($first, $this->wz->lyrics->lines[0][0], 0.01);        // a tap on a line: the song goes there        $this->tap('karaLine', 1);        self::assertEqualsWithDelta($this->wz->lyrics->lines[1][0] - 0.3, $this->wz->player->position, 0.3);        $this->tap('lyricsMenu', null, 15);        self::assertSame('lyrics', $this->view->sheet);        $this->shot('mobile-paroles');    }    public function testALrcFileBecomesTheLyricsOfTheSong(): void    {        $this->startPhone(['play' => 3]);        $dir = $this->wz->storagePath('test/Paroles');        @mkdir($dir, 0777, true);        file_put_contents("$dir/partage.lrc", "[ar:WinZik]\n[00:01.50]On partage la musique\n[00:04.00]Des paroles qui tombent du ciel\n");        $this->view->openSheet('lyrics');        $this->game->run(15);        $this->tap('lyImport', null, 15);        self::assertSame('add', $this->view->screen);        self::assertSame('lyrics', $this->view->pickMode);        $this->view->folder = $dir;        $this->game->run(2);        $this->shot('mobile-importer-paroles');        $this->tap('file', "$dir/partage.lrc", 5);        self::assertNotNull($this->wz->lyrics);        self::assertSame('On partage la musique', $this->wz->lyrics->lines[0][1]);        self::assertSame('player', $this->view->screen, 'back where it came from');    }    public function testTheEditorGivesEachLineItsMomentWithATap(): void    {        $this->startPhone(['play' => 3]);        $this->view->openSheet('lyrics');        $this->game->run(15);        $this->tap('goto', 'lyricsEdit', 15);        self::assertSame('lyricsEdit', $this->view->screen);        $this->tap('field', 'edText');        $this->view->fields['edText'] = '';        $this->form->type("On partage la musique\nDes paroles qui tombent du ciel\nEt la nuit s'allume");        $this->game->run(2);        $this->shot('mobile-editeur-texte');        $this->tap('edStart', null, 5);        self::assertSame(0, $this->view->edNext);        self::assertSame(Player::PLAYING, $this->wz->player->state);        foreach ([1.0, 1.5, 1.2] as $wait) {            $this->game->wait($wait);            $this->tap('edStamp');        }        self::assertSame(3, $this->view->edNext);        self::assertNotContains(null, $this->view->edTimes);        $this->shot('mobile-editeur-synchro');        $this->tap('edSave', null, 3);        self::assertNotNull($this->wz->lyrics);        self::assertCount(3, $this->wz->lyrics->lines);        self::assertSame('Des paroles qui tombent du ciel', $this->wz->lyrics->lines[1][1]);        self::assertEqualsWithDelta(2.5, $this->wz->lyrics->lines[1][0], 0.4);    }    public function testTheTagIsWrittenWithItsGenreAndItsMarks(): void    {        $this->startPhone(['screen' => 'playlist']);        // a copy of a song (the demo songs stay as they are)        $copy = $this->wz->storagePath('test/tag/chanson.mp3');        @mkdir(dirname($copy), 0777, true);        copy($this->wz->path('assets/music/partage.mp3'), $copy);        $this->wz->addFiles([$copy]);        $line = $this->wz->playlist->count() - 1;        $this->wz->playIndex($line);        $this->game->run(3);        $this->tap('rowMore', $line, 15);        $this->tap('act', 'tag', 5);        self::assertSame('tag', $this->view->screen);        $this->tap('field', 'tagTitle');        $this->view->fields['tagTitle'] = '';        $this->form->type('Chanson du téléphone');        $this->tap('field', 'tagYear');        $this->view->fields['tagYear'] = '';        $this->form->type('2001');        $this->shot('mobile-tag');        $this->tapScrolled('goto', 'genre', 3);        self::assertSame('genre', $this->view->screen);        $this->tapScrolled('genrePick', 17, 3);      // Rock        self::assertSame('tag', $this->view->screen);        $this->tapScrolled('tagHere', 'start');        $this->tapScrolled('tagStar', 4);        $this->tapScrolled('tagSave', null, 3);        self::assertSame('playlist', $this->view->screen);        $tag = \App\Model\Id3Tag::read($copy);        self::assertSame('Chanson du téléphone', $tag->title);        self::assertSame('2001', $tag->year);        $v1 = \App\Model\Id3Tag::parse((string)substr((string)file_get_contents($copy), -128));        self::assertSame(17, $v1->genre, 'the genre in the ID3v1 tag (Form6 of 2001)');        self::assertSame(4, $this->wz->stats()->rating($copy));        self::assertGreaterThan(0.0, $this->wz->bounds($copy)[0], 'the start mark kept');    }    public function testTheMarketplaceInstallsLyricsForTheSongPlaying(): void    {        $this->startPhone(['play' => 3]);        $engine = $this->form->engineOrNull();        self::assertNotNull($engine);        $lyr = "[LYR]\r\n[ 1.5 ]\r\nOn partage la musique\r\n";        $http = new class ($engine->bridge, $lyr) extends Http {            public function __construct(\JumPHP\Bridge\JsBridge $bridge, private string $lyr)            {                parent::__construct($bridge);            }            public function request(string $method, string $url, string|array|null $body = null, array $headers = [], ?float $timeout = null): Task            {                $t = new Task();                $t->settle(str_ends_with($url, '/lyrics/l1') ? new HttpResponse(200, $this->lyr)                    : new HttpResponse(200, (string)json_encode(['items' => [['id' => 'l1', 'name' => 'partage', 'artist' => 'WinZik Band', 'title' => 'Partage',                        'author' => 'Ginette', 'downloads' => 12, 'size' => 60, 'at' => '2026-11-01']]])));                return $t;            }        };        (new \ReflectionProperty(WinZik::class, 'market'))->setValue($this->wz, new Market($http, 'https://market.test'));        $this->tap('tab', 'more', 15);        $this->tap('goto', 'market', 15);        $this->game->run(3);        self::assertCount(1, $this->view->marketEntries);        $this->shot('mobile-marketplace');        $this->tapScrolled('mkInstall', 0, 3);        self::assertNotNull($this->wz->lyrics);        self::assertSame('On partage la musique', $this->wz->lyrics->lines[0][1]);        $this->tap('mkKind', 'skin', 3);        self::assertSame('skin', $this->view->marketKind);    }    public function testThePlaylistIsSavedClearedAndOpenedAgain(): void    {        $this->startPhone(['screen' => 'playlist']);        $items = $this->wz->playlist->items;        $this->tap('headerMore', null, 15);        self::assertSame('playlistMenu', $this->view->sheet);        $this->shot('mobile-playlist-menu');        $this->tap('goto', 'library', 15);        self::assertSame('library', $this->view->screen);        $this->tap('field', 'flsName');        $this->view->fields['flsName'] = '';        $this->form->type("Ma sélection\n");        $this->game->run(2);        $saved = array_values(array_filter($this->view->savedPlaylists(), fn (string $f) => str_ends_with($f, '/Ma sélection.fls')));        self::assertCount(1, $saved);        $this->shot('mobile-playlists-fls');        $this->back();        $this->tap('headerMore', null, 15);        $this->tap('more', 'confirmClear', 15);        $this->shot('mobile-vider');        $this->tap('clearList', null, 20);        self::assertSame(0, $this->wz->playlist->count());        $this->view->go('library');        $this->game->run(2);        $this->tapScrolled('flsOpen', $saved[0], 3);        self::assertSame('playlist', $this->view->screen);        self::assertSame(array_map(fn ($f) => $this->wz->path($f), $items), array_map(fn ($f) => $this->wz->path($f), $this->wz->playlist->items));    }    public function testTheBandsOfTheEqualizerFollowTheFingerAndTheListSortsByArtist(): void    {        $this->startPhone(['play' => 0, 'sheet' => 'eq']);        $this->game->run(15);        $at = $this->view->at('band', 0);        self::assertNotNull($at);        $p = new Pointer();        [$p->x, $p->y, $p->down, $p->held] = [$at[0], $at[1], true, true];        $this->form->handle($p);        $p = new Pointer();        [$p->x, $p->y, $p->held] = [$at[0], $at[1] - 200, true];        $this->form->handle($p);        $p = new Pointer();        [$p->x, $p->y, $p->up] = [$at[0], $at[1] - 200, true];        $this->form->handle($p);        self::assertSame(12.0, $this->wz->eq->bands[0], 'the finger at the top: +12 dB');        $this->back();        $this->view->go('playlist');        $this->game->run(2);        $this->tap('order', 'artist');        self::assertTrue($this->view->byArtist());        $artists = array_map(fn (int $i) => mb_strtolower($this->view->titleOf($i)[1]), $this->view->shownLines());        $known = array_values(array_filter($artists, fn ($a) => $a !== ''));        $sorted = $known;        sort($sorted);        self::assertSame($sorted, $known);    }    public function testAnUpdateOfTheAppIsProposedAndInstalled(): void    {        $this->startPhone();        $fake = new class () {            public bool $installing = false;            public float $progress = 0.0;            /** the shape of WinZik::androidUpdate() */            public function androidUpdate(): array            {                return ['version' => '0.11.0', 'notes' => 'YouTube, Spotify, le karaoké et les vidéos sur le téléphone.', 'size' => 24 << 20,                    'state' => $this->installing ? 'downloading' : 'available', 'progress' => $this->progress, 'error' => ''];            }            public function installAndroidUpdate(): bool            {                $this->installing = true;                $this->progress = 0.4;                return true;            }        };        $this->view->updates = $fake;        $this->game->run(2);        $this->shot('mobile-maj-banniere');        $this->tap('more', 'update', 15);        self::assertSame('update', $this->view->sheet);        $this->shot('mobile-maj');        $this->tap('updateInstall', null, 3);        self::assertTrue($fake->installing);        $this->shot('mobile-maj-telechargement');        self::assertNull($this->view->at('updateInstall'), 'the progress instead of the button');        $this->back();        // Plus tard: the banner goes, until the next version        $fake->installing = false;        $this->tap('more', 'update', 15);        $this->tap('updateLater', null, 15);        self::assertNull($this->view->at('more', 'update'));        // À propos: Rechercher une mise à jour        $this->tap('tab', 'more', 15);        $this->tap('more', 'about', 15);        self::assertNotNull($this->view->at('updateCheck'));    }    public function testTheOriginalInterfaceIsChosenInPlus(): void    {        $this->startPhone();        $this->tap('tab', 'more', 15);        $this->shot('mobile-plus-tout');        $this->tap('original', null, 5);        self::assertSame('original', $this->wz->options['phoneUi']);        $this->game->run(5);        self::assertInstanceOf(MainForm::class, $this->game->scene());    }    public function testTheOptionsKeepTheSpotifyKeysAndTheKaraokeAnimation(): void    {        $this->startPhone(['screen' => 'options']);        $this->tapScrolled('field', 'spotifyId');        $this->form->type("abc123\n");        $this->game->run(2);        self::assertSame('abc123', $this->wz->options['spotifyId']);        $this->view->scroll['page:options'] = 0;        $this->game->run(1);        $this->tapScrolled('karaMode', 'star');        self::assertSame('star', $this->wz->options['karaoke']);        $this->tapScrolled('balance', 1);        self::assertSame(10, $this->wz->player->balance);        $this->shot('mobile-options-spotify');        $this->view->scroll['page:options'] = 0;        $this->tapScrolled('goto', 'skins', 3);        self::assertSame('skins', $this->view->screen);        $this->shot('mobile-skins');    }}