From 851a55cf38be67f70fd7f77443fda353784bc6c2 Mon Sep 17 00:00:00 2001 From: neckfire Date: Fri, 9 Oct 2026 18:34:31 +0200 Subject: [PATCH] =?UTF-8?q?app=20:=20=C3=A9cran=20de=20gestion=20des=20mod?= =?UTF-8?q?s=20via=20Modrinth?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Écran Mods (recherche Modrinth + liste installée) accessible depuis le détail d_un serveur Minecraft - Ajout/retrait réservés aux admins (bouton masqué/averti sinon), via l_API gamepanel - Service API : role(), mods(), searchMods(), addMod(), removeMod() + modèle ModHit --- lib/models.dart | 19 ++ lib/screens/mods_screen.dart | 259 ++++++++++++++++++++++++++ lib/screens/server_detail_screen.dart | 9 + lib/services/api_service.dart | 57 ++++++ 4 files changed, 344 insertions(+) create mode 100644 lib/screens/mods_screen.dart diff --git a/lib/models.dart b/lib/models.dart index 25f9ee6..e09adb9 100644 --- a/lib/models.dart +++ b/lib/models.dart @@ -153,3 +153,22 @@ class ConnectInfo { ); } } + +/// Résultat de recherche Modrinth (proxy backend /api/modrinth/search). +class ModHit { + ModHit({required this.slug, required this.title, this.description, this.downloads, this.iconUrl}); + + final String slug; + final String title; + final String? description; + final int? downloads; + final String? iconUrl; + + factory ModHit.fromJson(Map j) => ModHit( + slug: (j['slug'] as String?) ?? '', + title: (j['title'] as String?) ?? (j['slug'] as String?) ?? '', + description: j['description'] as String?, + downloads: j['downloads'] as int?, + iconUrl: j['icon_url'] as String?, + ); +} diff --git a/lib/screens/mods_screen.dart b/lib/screens/mods_screen.dart new file mode 100644 index 0000000..5934936 --- /dev/null +++ b/lib/screens/mods_screen.dart @@ -0,0 +1,259 @@ +import 'package:flutter/material.dart'; + +import '../models.dart'; +import '../services/api_service.dart'; + +/// Gestion des mods d'un serveur via Modrinth. +/// Lecture pour tous ceux qui ont accès ; ajout/retrait réservés aux admins +/// (le backend renvoie 403 sinon). +class ModsScreen extends StatefulWidget { + const ModsScreen({super.key, required this.api, required this.serverId, required this.serverName}); + + final ApiService api; + final String serverId; + final String serverName; + + @override + State createState() => _ModsScreenState(); +} + +class _ModsScreenState extends State { + bool _loading = true; + String? _error; + bool _isAdmin = false; + List _installed = []; + + final _searchCtrl = TextEditingController(); + bool _searching = false; + List _results = []; + + @override + void initState() { + super.initState(); + _load(); + } + + @override + void dispose() { + _searchCtrl.dispose(); + super.dispose(); + } + + Future _load() async { + setState(() { + _loading = true; + _error = null; + }); + try { + final role = await widget.api.role().catchError((_) => 'member'); + final mods = await widget.api.mods(widget.serverId); + if (!mounted) return; + setState(() { + _isAdmin = role == 'admin'; + _installed = mods; + _loading = false; + }); + } catch (e) { + if (!mounted) return; + setState(() { + _error = '$e'; + _loading = false; + }); + } + } + + Future _search() async { + final q = _searchCtrl.text.trim(); + setState(() => _searching = true); + try { + final hits = await widget.api.searchMods(q, widget.serverId); + if (!mounted) return; + setState(() => _results = hits); + } catch (e) { + _snack('$e'); + } finally { + if (mounted) setState(() => _searching = false); + } + } + + Future _add(ModHit hit) async { + try { + await widget.api.addMod(widget.serverId, hit.slug); + _snack('« ${hit.title} » ajouté — le serveur redémarre (téléchargement au boot).'); + await _load(); + } catch (e) { + _snack('$e'); + } + } + + Future _remove(String slug) async { + final ok = await showDialog( + context: context, + builder: (c) => AlertDialog( + title: Text('Retirer $slug ?'), + content: const Text('Le serveur redémarrera pour appliquer le changement.'), + actions: [ + TextButton(onPressed: () => Navigator.pop(c, false), child: const Text('Annuler')), + FilledButton(onPressed: () => Navigator.pop(c, true), child: const Text('Retirer')), + ], + ), + ); + if (ok != true) return; + try { + await widget.api.removeMod(widget.serverId, slug); + _snack('« $slug » retiré — le serveur redémarre.'); + await _load(); + } catch (e) { + _snack('$e'); + } + } + + void _snack(String m) { + if (mounted) ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(m))); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + appBar: AppBar(title: Text('Mods — ${widget.serverName}')), + body: _loading + ? const Center(child: CircularProgressIndicator()) + : _error != null + ? _ErrorState(message: _error!, onRetry: _load) + : RefreshIndicator( + onRefresh: _load, + child: ListView( + padding: const EdgeInsets.all(16), + children: [ + _InstalledSection( + installed: _installed, + canRemove: _isAdmin, + onRemove: _remove, + ), + const SizedBox(height: 24), + if (_isAdmin) ..._searchSection() else _memberNote(), + ], + ), + ), + ); + } + + Widget _memberNote() => const Card( + child: Padding( + padding: EdgeInsets.all(16), + child: Text('La gestion des mods est réservée aux administrateurs.'), + ), + ); + + List _searchSection() { + return [ + Text('Ajouter depuis Modrinth', style: Theme.of(context).textTheme.titleMedium), + const SizedBox(height: 8), + TextField( + controller: _searchCtrl, + textInputAction: TextInputAction.search, + onSubmitted: (_) => _search(), + decoration: InputDecoration( + hintText: 'Rechercher un mod (compatible avec ce serveur)…', + prefixIcon: const Icon(Icons.search), + suffixIcon: IconButton(icon: const Icon(Icons.arrow_forward), onPressed: _search), + border: const OutlineInputBorder(), + ), + ), + const SizedBox(height: 12), + if (_searching) + const Padding(padding: EdgeInsets.all(24), child: Center(child: CircularProgressIndicator())) + else if (_results.isEmpty) + const Padding( + padding: EdgeInsets.symmetric(vertical: 24), + child: Center(child: Text('Lance une recherche pour trouver des mods.')), + ) + else + ..._results.map(_resultTile), + ]; + } + + Widget _resultTile(ModHit hit) { + final already = _installed.contains(hit.slug); + return Card( + child: ListTile( + leading: hit.iconUrl != null + ? ClipRRect( + borderRadius: BorderRadius.circular(8), + child: Image.network(hit.iconUrl!, width: 40, height: 40, + errorBuilder: (_, __, ___) => const Icon(Icons.extension)), + ) + : const Icon(Icons.extension), + title: Text(hit.title), + subtitle: Text( + hit.description ?? hit.slug, + maxLines: 2, + overflow: TextOverflow.ellipsis, + ), + trailing: already + ? const Chip(label: Text('Installé')) + : FilledButton.tonal(onPressed: () => _add(hit), child: const Text('Ajouter')), + ), + ); + } +} + +class _InstalledSection extends StatelessWidget { + const _InstalledSection({required this.installed, required this.canRemove, required this.onRemove}); + + final List installed; + final bool canRemove; + final void Function(String slug) onRemove; + + static const _core = {'fabric-api', 'fabricloader', 'forge', 'neoforge'}; + + @override + Widget build(BuildContext context) { + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('Mods installés (${installed.length})', style: Theme.of(context).textTheme.titleMedium), + const SizedBox(height: 8), + if (installed.isEmpty) + const Text('Aucun mod.') + else + Wrap( + spacing: 8, + runSpacing: 8, + children: [ + for (final slug in installed) + InputChip( + label: Text(slug), + onDeleted: canRemove && !_core.contains(slug) ? () => onRemove(slug) : null, + ), + ], + ), + ], + ); + } +} + +class _ErrorState extends StatelessWidget { + const _ErrorState({required this.message, required this.onRetry}); + final String message; + final VoidCallback onRetry; + + @override + Widget build(BuildContext context) { + return Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const Icon(Icons.error_outline, size: 40), + const SizedBox(height: 12), + Text(message, textAlign: TextAlign.center), + const SizedBox(height: 16), + FilledButton(onPressed: onRetry, child: const Text('Réessayer')), + ], + ), + ), + ); + } +} diff --git a/lib/screens/server_detail_screen.dart b/lib/screens/server_detail_screen.dart index ef65d02..b82154c 100644 --- a/lib/screens/server_detail_screen.dart +++ b/lib/screens/server_detail_screen.dart @@ -8,6 +8,7 @@ import '../models.dart'; import '../services/api_service.dart'; import '../widgets/connect_card.dart'; import '../widgets/server_map_card.dart'; +import 'mods_screen.dart'; /// Détail d'un serveur : bannière (image importée ou thème), statut, connexion, /// stats d'utilisation (CPU/RAM/réseau) et gestion de l'image (import/suppression). @@ -127,6 +128,14 @@ class _ServerDetailScreenState extends State { appBar: AppBar( title: Text(s.name), actions: [ + if (s.game.toLowerCase().contains('minecraft')) + IconButton( + tooltip: 'Mods', + icon: const Icon(Icons.extension_outlined), + onPressed: () => Navigator.of(context).push(MaterialPageRoute( + builder: (_) => ModsScreen(api: widget.api, serverId: s.id, serverName: s.name), + )), + ), if (s.custom) IconButton( tooltip: 'Supprimer', diff --git a/lib/services/api_service.dart b/lib/services/api_service.dart index 8b2e3df..1d48e65 100644 --- a/lib/services/api_service.dart +++ b/lib/services/api_service.dart @@ -145,6 +145,63 @@ class ApiService { if (res.statusCode == 401) throw UnauthorizedException(); if (res.statusCode >= 400) throw ApiException('Suppression refusée (${res.statusCode})'); } + + // ── Rôle & mods (Modrinth) ────────────────────────────────── + Future role() async { + final base = await baseUrl; + final res = await http.get(Uri.parse('$base/api/me'), headers: await _headers()); + if (res.statusCode == 401) throw UnauthorizedException(); + if (res.statusCode >= 400) throw ApiException('Profil indisponible (${res.statusCode})'); + return (jsonDecode(res.body)['role'] as String?) ?? 'member'; + } + + Future> mods(String id) async { + final base = await baseUrl; + final res = await http.get(Uri.parse('$base/api/servers/$id/mods'), headers: await _headers()); + if (res.statusCode == 401) throw UnauthorizedException(); + if (res.statusCode >= 400) throw ApiException('Mods indisponibles (${res.statusCode})'); + return ((jsonDecode(res.body)['projects'] as List?) ?? const []).cast(); + } + + Future> searchMods(String q, String serverId) async { + final base = await baseUrl; + final uri = Uri.parse('$base/api/modrinth/search') + .replace(queryParameters: {'q': q, 'server_id': serverId}); + final res = await http.get(uri, headers: await _headers()); + if (res.statusCode == 401) throw UnauthorizedException(); + if (res.statusCode >= 400) throw ApiException('Recherche échouée (${res.statusCode})'); + return ((jsonDecode(res.body)['hits'] as List?) ?? const []) + .map((h) => ModHit.fromJson(h as Map)) + .toList(); + } + + Future addMod(String id, String slug) async { + final base = await baseUrl; + final res = await http.post( + Uri.parse('$base/api/servers/$id/mods'), + headers: {...await _headers(), 'Content-Type': 'application/json'}, + body: jsonEncode({'slug': slug}), + ); + if (res.statusCode == 401) throw UnauthorizedException(); + if (res.statusCode == 403) throw ApiException('Réservé aux administrateurs'); + if (res.statusCode >= 400) throw ApiException(_detail(res) ?? 'Ajout refusé (${res.statusCode})'); + } + + Future removeMod(String id, String slug) async { + final base = await baseUrl; + final res = await http.delete(Uri.parse('$base/api/servers/$id/mods/$slug'), headers: await _headers()); + if (res.statusCode == 401) throw UnauthorizedException(); + if (res.statusCode == 403) throw ApiException('Réservé aux administrateurs'); + if (res.statusCode >= 400) throw ApiException(_detail(res) ?? 'Retrait refusé (${res.statusCode})'); + } + + String? _detail(http.Response res) { + try { + return jsonDecode(res.body)['detail']?.toString(); + } catch (_) { + return null; + } + } } class UnauthorizedException implements Exception {}