- É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
This commit is contained in:
@@ -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<String, dynamic> 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?,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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<ModsScreen> createState() => _ModsScreenState();
|
||||
}
|
||||
|
||||
class _ModsScreenState extends State<ModsScreen> {
|
||||
bool _loading = true;
|
||||
String? _error;
|
||||
bool _isAdmin = false;
|
||||
List<String> _installed = [];
|
||||
|
||||
final _searchCtrl = TextEditingController();
|
||||
bool _searching = false;
|
||||
List<ModHit> _results = [];
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_load();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_searchCtrl.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _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<void> _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<void> _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<void> _remove(String slug) async {
|
||||
final ok = await showDialog<bool>(
|
||||
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<Widget> _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<String> 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')),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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<ServerDetailScreen> {
|
||||
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',
|
||||
|
||||
@@ -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<String> 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<List<String>> 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<String>();
|
||||
}
|
||||
|
||||
Future<List<ModHit>> 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<String, dynamic>))
|
||||
.toList();
|
||||
}
|
||||
|
||||
Future<void> 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<void> 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 {}
|
||||
|
||||
Reference in New Issue
Block a user