FR
apps/winzik / src / Form / MarketForm.php · commit 6576d6f
<?phpnamespace App\Form;use App\Model\Lyrics;use App\Model\Skin;use App\Model\SkinPack;use App\Model\Text;use JumPHP\Gui\Button;use JumPHP\Gui\ComboBox;use JumPHP\Gui\Label;use JumPHP\Gui\ListBox;use JumPHP\Gui\TextBox;/** * The marketplace (jumphp.net /api/apps/winzik/shared): the skins or the lyrics the users of WinZik share. Install one * (a skin goes to var/skins and is put on; lyrics go to var/lyr for the song playing), or send one's own: a skin of * var/skins (made with EDT) as a .zip, the lyrics of the song playing. Params: kind ('skin' | 'lyrics'). * * @property Label $heading * @property TextBox $search * @property Button $find * @property ListBox $items * @property Label $info * @property Button $install * @property ComboBox $mine * @property TextBox $author * @property Button $share * @property Label $status * @property \JumPHP\Gui\ProgressBar $busy * @property Button $quit */final class MarketForm extends WinZikDialog{    public string $kind = 'skin';    /** @var list<array<string, mixed>> */    public array $entries = [];    /** @var list<array{0: string, 1: string}> what can be sent: [label, path] */    private array $own = [];    protected function loaded(array $params = []): void    {        $this->kind = ($params['kind'] ?? 'skin') === 'lyrics' ? 'lyrics' : 'skin';        $this->heading->text = $this->kind === 'skin' ? 'Marketplace des skins' : 'Marketplace des paroles';        $this->author->text = (string)($this->wz->options['author'] ?? '');        $this->entries = [];        $this->items->items = [];        $this->install->enabled = false;        if ($this->kind === 'lyrics' && $this->wz->tag->artist !== '') {            $this->search->text = trim($this->wz->tag->artist . ' ' . $this->wz->tag->title);        } else {            $this->search->text = '';        }        $this->fillOwn();        $this->setFocus($this->search);     // type at once        $market = $this->wz->market();        if ($market === null || !$market->enabled()) {            $this->status->text = 'Pas de marketplace ici : pas de réseau. Vérifiez la connexion, puis rouvrez cette fenêtre.';            foreach ([$this->search, $this->find, $this->items, $this->mine, $this->author, $this->share] as $widget) {                $widget->enabled = false;            }            $this->setFocus($this->quit);            return;        }        $this->onFindClick($this->find);    }    /** What the user may send: their skins (var/skins), or the lyrics of the song playing. */    private function fillOwn(): void    {        $this->own = [];        if ($this->kind === 'skin') {            foreach (Skin::findAll([$this->wz->storagePath('skins')]) as $skin) {                $this->own[] = [$skin->name, $skin->dir];            }            if ($this->own === []) {                $this->status->text = "Pour partager un skin, créez-le d'abord avec l'éditeur de skins (EDT).";            }        } elseif ($this->wz->lyrics !== null && $this->wz->lyricsFile !== '') {            $this->own[] = [Text::baseName($this->wz->lyricsFile), $this->wz->lyricsFile];        }        $this->mine->items = array_map(fn (array $o) => $o[0], $this->own);        $this->mine->props['placeholder'] = $this->kind === 'skin' ? 'aucun skin à partager' : 'pas de paroles à partager';        $this->mine->enabled = $this->own !== [];        $this->author->enabled = $this->own !== [];        $this->mine->selected = $this->own === [] ? -1 : 0;        $this->share->enabled = $this->own !== [];    }    /** Entrée in the pseudo: what was chosen is sent. */    public function onAuthorSubmit(TextBox $sender): void    {        if ($this->share->isEnabled()) {            $this->onShareClick($this->share);        }    }    public function onSearchSubmit(TextBox $sender): void    {        $this->onFindClick($this->find);    }    public function onFindClick(Button $sender): void    {        $market = $this->wz->market();        if ($market === null) {            return;        }        $this->status->text = 'Recherche en cours...';        $this->loading++;        $market->list($this->kind, trim($this->search->text))->then(function (array $items): void {            $this->entries = $items;            $this->items->items = array_map(fn (array $e) => $this->line($e), $items);            $this->items->selected = $items === [] ? -1 : 0;            $this->install->enabled = $items !== [];            $this->status->text = count($items) . ' ' . ($this->kind === 'skin' ? 'skin(s)' : 'parole(s)') . ' sur jumphp.net';            if ($items !== []) {                $this->onItemsChange($this->items, 0, '');            }            $this->loading--;        }, function (\Throwable $e): void {            $this->status->text = 'Marketplace injoignable (' . $e->getMessage() . ') : vérifiez la connexion, puis « Chercher » à nouveau.';            $this->loading--;        });    }    /** @param array<string, mixed> $e */    private function line(array $e): string    {        $what = $this->kind === 'lyrics' && ($e['artist'] ?? '') !== '' ? $e['artist'] . ' - ' . $e['title'] : (string)$e['name'];        return $what . (($e['author'] ?? '') !== '' ? '   par ' . $e['author'] : '') . '   (' . (int)($e['downloads'] ?? 0) . ' téléchargement(s))';    }    public function onItemsChange(ListBox $sender, int $index, string $item): void    {        $e = $this->entries[$index] ?? null;        $this->info->text = $e === null ? '' : sprintf('%s  -  %d Ko  -  %s', $e['name'], max(1, intdiv((int)$e['size'], 1024)), substr((string)$e['at'], 0, 10));    }    public function onItemsActivate(ListBox $sender, int $index, string $item): void    {        $this->onInstallClick($this->install);    }    public function onInstallClick(Button $sender): void    {        $e = $this->entries[(int)$this->items->selected] ?? null;        $market = $this->wz->market();        if ($e === null || $market === null) {            return;        }        $this->status->text = 'Téléchargement de ' . $e['name'] . '...';        $this->loading++;        $market->download($this->kind, (string)$e['id'])->then(function (string $bytes) use ($e): void {            $this->loading--;            $this->kind === 'skin' ? $this->installSkin($e, $bytes) : $this->installLyrics($e, $bytes);        }, function (\Throwable $ex): void {            $this->loading--;            $this->status->text = 'Téléchargement impossible (' . $ex->getMessage() . ') : réessayez dans un instant.';        });    }    /** @param array<string, mixed> $e */    private function installSkin(array $e, string $zip): void    {        $dir = $this->wz->storagePath('skins/' . (\App\Model\SkinDocument::cleanName((string)$e['name']) ?: 'skin-' . $e['id']));        try {            $ok = SkinPack::install($zip, $dir);        } catch (\Throwable) {            $ok = false;        }        if (!$ok || !$this->wz->useSkin($dir)) {            $this->status->text = "Ce fichier n'est pas un skin de WinZik : choisissez-en un autre dans la liste.";            return;        }        $this->wz->save();        $this->status->text = 'Skin « ' . $this->wz->skin->name . ' » installé et mis.';        $this->fillOwn();    }    /** @param array<string, mixed> $e */    private function installLyrics(array $e, string $bytes): void    {        $file = $this->wz->playlist->current();        if ($file === null || Lyrics::parse($bytes) === null) {            $this->status->text = $file === null ? "Lancez d'abord le morceau de ces paroles, puis « Installer »." : "Ce fichier n'est pas un .LYR : choisissez d'autres paroles dans la liste.";            return;        }        // the song's own copy (var/lyr/<name>-<crc32>.lyr): never given to another song of that name        $target = $this->wz->lyricsCachePath($file);        @mkdir(dirname($target), 0777, true);        file_put_contents($target, $bytes);        $this->wz->refreshLyrics();        $this->wz->ui['lyrics']['visible'] = true;        $this->status->text = 'Paroles installées pour ' . Text::baseName($file);        $this->fillOwn();    }    public function onShareClick(Button $sender): void    {        $own = $this->own[(int)$this->mine->selected] ?? null;        $market = $this->wz->market();        if ($own === null || $market === null) {            return;        }        $author = mb_substr(trim($this->author->text), 0, 40);        $this->wz->options['author'] = $author;        if ($this->kind === 'skin') {            $meta = ['name' => $own[0], 'author' => $author, 'ext' => 'zip'];            $bytes = SkinPack::pack($own[1]);        } else {            $tag = $this->wz->tag;            $meta = ['name' => Text::baseName(Text::withoutExtension($own[1])), 'artist' => $tag->artist, 'title' => $tag->title, 'author' => $author, 'ext' => 'lyr'];            $bytes = (string)file_get_contents($own[1]);        }        $this->status->text = 'Envoi de ' . $own[0] . '...';        $market->upload($this->kind, $meta, $bytes)->then(function (array $entry): void {            $this->status->text = '« ' . $entry['name'] . ' » est partagé : tout le monde peut l\'installer.';            $this->onFindClick($this->find);        }, fn (\Throwable $e) => $this->status->text = 'Envoi impossible (' . $e->getMessage() . ') : réessayez dans un instant.');    }    /** requests on their way: the loader runs while there are */    private int $loading = 0;    private float $spin = 0.0;    protected function tick(float $dt): void    {        parent::tick($dt);        $this->busy->props['visible'] = $this->loading > 0;        $this->install->enabled = $this->loading === 0 && isset($this->entries[(int)$this->items->selected]);        if ($this->loading > 0) {            $this->spin = fmod($this->spin + $dt * 90, 100);            $this->busy->value = round($this->spin);        }    }    public function onQuitClick(Button $sender): void    {        $this->wz->save();        $this->close();    }}