9 Commits
Author SHA1 Message Date
neckfireandClaude Opus 4.8 30786f9706 feat: ajout de serveurs depuis l'app + charte flamme sombre
Build APK / build (push) Successful in 2m49s
- backend: GET /api/containers (liste lisible), POST/DELETE /api/servers
  (serveurs custom persistés en /data/servers.json, mergés aux intégrés),
  champ custom dans le statut.
- app: écran AddServer (form + sélecteur multi-conteneurs filtrable), FAB
  Ajouter, suppression depuis le détail (serveurs custom only).
- thème: palette flamme/chaud sombre (anthracite + orange→rouge), remplace le
  Material violet/teal par défaut (scaffold, appbar, tabs, boutons, FAB, champs).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-13 13:33:22 +02:00
neckfireandClaude Opus 4.8 fb4ab95f13 feat(ui): la carte reprend l'image importée en fond (voile pour lisibilité)
Build APK / build (push) Successful in 2m49s
- ServerCard: fond = image (MemoryImage) + scrim dégradé si présente, sinon
  dégradé thématique ; vignette d'icône masquée quand image de fond.
- servers_screen: fetch des bytes image (cache par id, vidé au refresh) → passe
  à la carte ; plus de FutureBuilder iconUrl inutile.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-13 13:00:10 +02:00
neckfireandClaude Opus 4.8 2862fdd408 feat: écran détail serveur (stats CPU/RAM + image importable RustFS)
Build APK / build (push) Successful in 2m36s
- carte cliquable → ServerDetailScreen : bannière (image ou thème), statut,
  connexion/ouvrir, joueurs/MOTD, jauges CPU/RAM/réseau (docker stats),
  import/suppression d'image (galerie → backend → RustFS).
- api_service: stats(), server(), imageBytes(), uploadImage(), deleteImage().
- deps: image_picker.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-13 12:05:09 +02:00
neckfireandClaude Opus 4.8 a971204b80 fix(ci): signature release réellement appliquée + maj in-app (open_filex)
Build APK / build (push) Successful in 2m28s
- patch_android.py: gère 'signingConfig = signingConfigs.debug' (Flutter 3.24
  utilise le '='), sans quoi le build restait signé en clé debug éphémère
  → signature différente à chaque run → 'conflit' à l'install de MAJ. Échoue
  désormais le build si la ligne n'est pas patchée (garde-fou).
- update_service: télécharge l'APK in-app + lance l'installeur (open_filex),
  fallback navigateur ; barre de progression dans l'écran serveurs.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-13 11:44:54 +02:00
neckfireandClaude Opus 4.8 0257f0fa05 feat(ui): preprod dans un onglet séparé (TabBar Production / Preprod)
Build APK / build (push) Successful in 2m27s
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-13 11:33:12 +02:00
neckfireandClaude Opus 4.8 25890d7bbc feat: section preprod (env prod/preprod) + intégration ANTS (prod+preprod, jeu web)
Build APK / build (push) Successful in 2m27s
- servers groupés par environnement (Production / Preprod) avec en-têtes
- ANTS prod (ants-web) + preprod (ants-web-rd) intégrés : jeu web, bouton Ouvrir
- The Cycle preprod (the-cycle-api-rd) ajouté
- badge PREPROD sur les cartes concernées, thème ANTS (fourmi/ambre)
- supprime le widget_test.dart par défaut (cassé, non compilé dans l'APK)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-13 11:28:22 +02:00
neckfireandClaude Opus 4.8 6b7287cefd fix(auth): retire prompt=login → reconnexion silencieuse (évite le hang passkey WebAuthn en Custom Tab)
Build APK / build (push) Successful in 2m31s
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-13 11:17:35 +02:00
neckfireandClaude Opus 4.8 4a265e0fd2 fix(auth): flutter_web_auth_2 + PKCE manuel (retour OIDC fiable via CallbackActivity)
Build APK / build (push) Successful in 2m28s
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-13 10:56:19 +02:00
neckfireandClaude Opus 4.8 1fe4528b0b fix(auth): App Link HTTPS pour le retour OIDC (Chrome bloque le schéma custom)
Build APK / build (push) Successful in 2m29s
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-13 10:28:04 +02:00
14 changed files with 1349 additions and 146 deletions
+2
View File
@@ -5,6 +5,8 @@ class Config {
// OIDC pocket-id (client public + PKCE)
static const String oidcIssuer = 'https://pocket.nfteam.ovh';
static const String oidcClientId = '83678fb3-9268-42c1-8dcb-0fb141692a6d';
// Schéma custom capté par flutter_web_auth_2 (CallbackActivity dédiée)
static const String oidcScheme = 'nfteam.gamemanager';
static const String oidcRedirect = 'nfteam.gamemanager://oidc';
static const List<String> oidcScopes = ['openid', 'profile', 'email'];
}
+2 -2
View File
@@ -18,9 +18,9 @@ class GameManagerApp extends StatelessWidget {
return MaterialApp(
title: 'GameManager',
debugShowCheckedModeBanner: false,
theme: AppTheme.light(),
theme: AppTheme.dark(),
darkTheme: AppTheme.dark(),
themeMode: ThemeMode.system,
themeMode: ThemeMode.dark,
home: AuthGate(auth: auth, api: api),
);
}
+43
View File
@@ -8,11 +8,16 @@ class GameServer {
final String? subtitle;
final String? connect;
final bool onDemand;
final String env; // prod | preprod
final bool web; // jeu web → bouton « Ouvrir »
final String? openUrl;
final String status; // stopped | starting | running | online | partial
final int? players;
final int? maxPlayers;
final String? motd;
final bool hasIcon;
final bool hasImage;
final bool custom;
const GameServer({
required this.id,
@@ -21,11 +26,16 @@ class GameServer {
this.subtitle,
this.connect,
this.onDemand = false,
this.env = 'prod',
this.web = false,
this.openUrl,
required this.status,
this.players,
this.maxPlayers,
this.motd,
this.hasIcon = false,
this.hasImage = false,
this.custom = false,
});
factory GameServer.fromJson(Map<String, dynamic> json) => GameServer(
@@ -35,15 +45,21 @@ class GameServer {
subtitle: json['subtitle'] as String?,
connect: json['connect'] as String?,
onDemand: json['on_demand'] as bool? ?? false,
env: json['env'] as String? ?? 'prod',
web: json['web'] as bool? ?? false,
openUrl: json['open_url'] as String?,
status: json['status'] as String? ?? 'stopped',
players: json['players'] as int?,
maxPlayers: json['max_players'] as int?,
motd: json['motd'] as String?,
hasIcon: json['has_icon'] as bool? ?? false,
hasImage: json['has_image'] as bool? ?? false,
custom: json['custom'] as bool? ?? false,
);
bool get isUp => status == 'online' || status == 'running';
bool get isBusy => status == 'starting' || status == 'partial';
bool get isPreprod => env == 'preprod';
/// Couleur d'accent thématique par jeu (visuel sans dépendance externe).
({Color start, Color end, IconData icon}) get theme {
@@ -57,6 +73,9 @@ class GameServer {
if (g.contains('cycle')) {
return (start: const Color(0xFF00BCD4), end: const Color(0xFF1A237E), icon: Icons.rocket_launch);
}
if (g.contains('swarm') || g.contains('ants')) {
return (start: const Color(0xFFF9A825), end: const Color(0xFF6D4C00), icon: Icons.bug_report);
}
return (start: const Color(0xFF7E57C2), end: const Color(0xFF311B92), icon: Icons.sports_esports);
}
@@ -68,3 +87,27 @@ class GameServer {
_ => (label: 'Éteint', color: const Color(0xFF8E8E93)),
};
}
/// Conteneur Docker (pour lier un serveur depuis l'app).
class DockerContainer {
DockerContainer({required this.name, required this.image, required this.state});
final String name;
final String image;
final String state;
factory DockerContainer.fromJson(Map<String, dynamic> j) => DockerContainer(
name: j['name'] as String,
image: (j['image'] as String?) ?? '',
state: (j['state'] as String?) ?? '',
);
bool get running => state == 'running';
/// Image sans le registre ni le digest, pour la lisibilité.
/// ex: git.nfteam.ovh/neckfire/the-cycle:preprod → the-cycle:preprod
String get prettyImage {
var s = image.split('/').last;
if (s.length > 34) s = '${s.substring(0, 33)}';
return s;
}
}
+230
View File
@@ -0,0 +1,230 @@
import 'package:flutter/material.dart';
import '../models.dart';
import '../services/api_service.dart';
/// Formulaire d'ajout d'un serveur : infos + sélection du/des conteneur(s)
/// Docker liés (liste lisible : nom + image courte + état).
class AddServerScreen extends StatefulWidget {
const AddServerScreen({super.key, required this.api});
final ApiService api;
@override
State<AddServerScreen> createState() => _AddServerScreenState();
}
class _AddServerScreenState extends State<AddServerScreen> {
final _name = TextEditingController();
final _game = TextEditingController();
final _subtitle = TextEditingController();
final _connect = TextEditingController();
final _openUrl = TextEditingController();
final _minecraft = TextEditingController();
final _search = TextEditingController();
String _env = 'prod';
bool _web = false;
bool _onDemand = false;
final _selected = <String>{};
List<DockerContainer>? _containers;
String? _error;
bool _saving = false;
@override
void initState() {
super.initState();
_loadContainers();
_search.addListener(() => setState(() {}));
}
@override
void dispose() {
for (final c in [_name, _game, _subtitle, _connect, _openUrl, _minecraft, _search]) {
c.dispose();
}
super.dispose();
}
Future<void> _loadContainers() async {
try {
final list = await widget.api.containers();
if (mounted) setState(() => _containers = list);
} catch (e) {
if (mounted) setState(() => _error = '$e');
}
}
Future<void> _save() async {
if (_name.text.trim().isEmpty || _selected.isEmpty) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Nom et au moins un conteneur requis.')),
);
return;
}
setState(() => _saving = true);
try {
await widget.api.createServer({
'name': _name.text.trim(),
'game': _game.text.trim(),
'subtitle': _subtitle.text.trim(),
'env': _env,
'containers': _selected.toList(),
'connect': _web ? _openUrl.text.trim() : _connect.text.trim(),
'web': _web,
'open_url': _web ? _openUrl.text.trim() : null,
'minecraft': _minecraft.text.trim(),
'on_demand': _onDemand,
});
if (mounted) Navigator.pop(context, true);
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('$e')));
setState(() => _saving = false);
}
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Nouveau serveur')),
body: ListView(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 100),
children: [
TextField(
controller: _name,
textCapitalization: TextCapitalization.words,
decoration: const InputDecoration(labelText: 'Nom *', hintText: 'ex: Valheim'),
),
const SizedBox(height: 12),
TextField(
controller: _game,
decoration: const InputDecoration(labelText: 'Jeu', hintText: 'ex: Valheim'),
),
const SizedBox(height: 12),
TextField(
controller: _subtitle,
decoration: const InputDecoration(labelText: 'Sous-titre', hintText: 'ex: serveur privé'),
),
const SizedBox(height: 16),
_envSelector(),
const SizedBox(height: 16),
SwitchListTile(
contentPadding: EdgeInsets.zero,
title: const Text('Jeu web (bouton « Ouvrir »)'),
value: _web,
onChanged: (v) => setState(() => _web = v),
),
if (_web)
TextField(
controller: _openUrl,
keyboardType: TextInputType.url,
decoration: const InputDecoration(labelText: 'URL du jeu', hintText: 'https://…'),
)
else ...[
TextField(
controller: _connect,
decoration: const InputDecoration(labelText: 'Adresse de connexion', hintText: 'ex: jeu.nfteam.ovh'),
),
const SizedBox(height: 12),
TextField(
controller: _minecraft,
decoration: const InputDecoration(
labelText: 'Minecraft host:port (MOTD, optionnel)',
hintText: 'ex: 192.168.1.136:25565',
),
),
],
SwitchListTile(
contentPadding: EdgeInsets.zero,
title: const Text('Serveur à la demande'),
value: _onDemand,
onChanged: (v) => setState(() => _onDemand = v),
),
const Divider(height: 28),
Text('Conteneur(s) lié(s) *', style: Theme.of(context).textTheme.titleMedium),
const SizedBox(height: 8),
_containerPicker(),
],
),
floatingActionButton: FloatingActionButton.extended(
onPressed: _saving ? null : _save,
icon: _saving
? const SizedBox(width: 18, height: 18, child: CircularProgressIndicator(strokeWidth: 2))
: const Icon(Icons.check),
label: const Text('Créer'),
),
);
}
Widget _envSelector() {
return SegmentedButton<String>(
segments: const [
ButtonSegment(value: 'prod', label: Text('Production'), icon: Icon(Icons.public)),
ButtonSegment(value: 'preprod', label: Text('Preprod'), icon: Icon(Icons.science_outlined)),
],
selected: {_env},
onSelectionChanged: (s) => setState(() => _env = s.first),
);
}
Widget _containerPicker() {
if (_error != null) {
return Text('Impossible de charger les conteneurs.\n$_error');
}
if (_containers == null) {
return const Padding(padding: EdgeInsets.all(20), child: Center(child: CircularProgressIndicator()));
}
final q = _search.text.toLowerCase();
final list = _containers!
.where((c) => q.isEmpty || c.name.toLowerCase().contains(q) || c.image.toLowerCase().contains(q))
.toList();
return Column(
children: [
TextField(
controller: _search,
decoration: const InputDecoration(
prefixIcon: Icon(Icons.search),
hintText: 'Filtrer les conteneurs…',
isDense: true,
),
),
const SizedBox(height: 8),
if (_selected.isNotEmpty)
Align(
alignment: Alignment.centerLeft,
child: Text('${_selected.length} sélectionné(s)',
style: Theme.of(context).textTheme.labelMedium),
),
Card(
child: Column(
children: [
for (final c in list)
CheckboxListTile(
dense: true,
value: _selected.contains(c.name),
onChanged: (v) => setState(() {
v == true ? _selected.add(c.name) : _selected.remove(c.name);
}),
title: Text(c.name, style: const TextStyle(fontWeight: FontWeight.w600)),
subtitle: Text(c.prettyImage,
maxLines: 1, overflow: TextOverflow.ellipsis,
style: const TextStyle(fontFamily: 'monospace', fontSize: 11)),
secondary: Container(
width: 10, height: 10,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: c.running ? const Color(0xFF34C759) : const Color(0xFF8E8E93),
),
),
),
if (list.isEmpty)
const Padding(padding: EdgeInsets.all(16), child: Text('Aucun conteneur.')),
],
),
),
],
);
}
}
+342
View File
@@ -0,0 +1,342 @@
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:url_launcher/url_launcher.dart';
import '../models.dart';
import '../services/api_service.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).
class ServerDetailScreen extends StatefulWidget {
const ServerDetailScreen({super.key, required this.server, required this.api});
final GameServer server;
final ApiService api;
@override
State<ServerDetailScreen> createState() => _ServerDetailScreenState();
}
class _ServerDetailScreenState extends State<ServerDetailScreen> {
GameServer get s => _server;
late GameServer _server = widget.server;
Map<String, dynamic>? _stats;
Uint8List? _image;
bool _busy = false;
bool _imgBusy = false;
@override
void initState() {
super.initState();
_load();
}
Future<void> _load() async {
final results = await Future.wait([
widget.api.stats(s.id).catchError((_) => <String, dynamic>{'running': false}),
widget.api.imageBytes(s.id).catchError((_) => null),
widget.api.server(s.id).catchError((_) => _server),
]);
if (!mounted) return;
setState(() {
_stats = results[0] as Map<String, dynamic>;
_image = results[1] as Uint8List?;
_server = results[2] as GameServer;
});
}
Future<void> _toggle() async {
setState(() => _busy = true);
try {
s.isUp ? await widget.api.stop(s.id) : await widget.api.start(s.id);
await Future.delayed(const Duration(seconds: 2));
await _load();
} catch (e) {
_snack('$e');
} finally {
if (mounted) setState(() => _busy = false);
}
}
Future<void> _pickImage() async {
final x = await ImagePicker().pickImage(source: ImageSource.gallery, maxWidth: 1600);
if (x == null) return;
setState(() => _imgBusy = true);
try {
await widget.api.uploadImage(s.id, x.path);
final bytes = await widget.api.imageBytes(s.id);
if (mounted) setState(() => _image = bytes);
} catch (e) {
_snack('$e');
} finally {
if (mounted) setState(() => _imgBusy = false);
}
}
Future<void> _deleteImage() async {
setState(() => _imgBusy = true);
try {
await widget.api.deleteImage(s.id);
if (mounted) setState(() => _image = null);
} catch (e) {
_snack('$e');
} finally {
if (mounted) setState(() => _imgBusy = false);
}
}
Future<void> _confirmDelete() async {
final ok = await showDialog<bool>(
context: context,
builder: (ctx) => AlertDialog(
title: const Text('Supprimer ce serveur ?'),
content: Text('« ${s.name} » sera retiré de l\'app (le conteneur Docker n\'est pas touché).'),
actions: [
TextButton(onPressed: () => Navigator.pop(ctx, false), child: const Text('Annuler')),
FilledButton(onPressed: () => Navigator.pop(ctx, true), child: const Text('Supprimer')),
],
),
);
if (ok != true) return;
try {
await widget.api.deleteServer(s.id);
if (mounted) Navigator.pop(context);
} catch (e) {
_snack('$e');
}
}
void _snack(String m) {
if (mounted) ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(m)));
}
@override
Widget build(BuildContext context) {
final t = s.theme;
final badge = s.statusBadge;
return Scaffold(
appBar: AppBar(
title: Text(s.name),
actions: [
if (s.custom)
IconButton(
tooltip: 'Supprimer',
icon: const Icon(Icons.delete_outline),
onPressed: _confirmDelete,
),
],
),
body: RefreshIndicator(
onRefresh: _load,
child: ListView(
children: [
_banner(t),
Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
_Pill(label: badge.label, color: badge.color),
const SizedBox(width: 8),
_Pill(label: s.isPreprod ? 'Preprod' : 'Production',
color: s.isPreprod ? const Color(0xFFFF9F0A) : const Color(0xFF34C759)),
const Spacer(),
if (s.web && s.openUrl != null)
OutlinedButton.icon(
onPressed: () =>
launchUrl(Uri.parse(s.openUrl!), mode: LaunchMode.externalApplication),
icon: const Icon(Icons.open_in_new, size: 18),
label: const Text('Ouvrir'),
),
],
),
const SizedBox(height: 16),
_toggleButton(),
const SizedBox(height: 20),
if (s.connect != null) _info(Icons.link, 'Connexion', s.connect!),
if (s.status == 'online')
_info(Icons.people, 'Joueurs', '${s.players ?? 0} / ${s.maxPlayers ?? 0}'),
if (s.motd != null) _info(Icons.chat_bubble_outline, 'MOTD', s.motd!),
const SizedBox(height: 20),
_statsCard(),
const SizedBox(height: 20),
_imageCard(),
],
),
),
],
),
),
);
}
Widget _banner(({Color start, Color end, IconData icon}) t) {
return SizedBox(
height: 190,
width: double.infinity,
child: _image != null
? Image.memory(_image!, fit: BoxFit.cover)
: DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft, end: Alignment.bottomRight, colors: [t.start, t.end]),
),
child: Center(child: Icon(t.icon, size: 72, color: Colors.white70)),
),
);
}
Widget _toggleButton() {
return SizedBox(
width: double.infinity,
child: FilledButton.icon(
onPressed: _busy ? null : _toggle,
style: FilledButton.styleFrom(
backgroundColor: s.isUp ? const Color(0xFFB3261E) : const Color(0xFF1B5E20),
padding: const EdgeInsets.symmetric(vertical: 14),
),
icon: _busy
? const SizedBox(width: 18, height: 18, child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white))
: Icon(s.isUp ? Icons.stop : Icons.play_arrow),
label: Text(s.isUp ? 'Éteindre le serveur' : 'Démarrer le serveur'),
),
);
}
Widget _info(IconData icon, String label, String value) {
return Padding(
padding: const EdgeInsets.only(bottom: 12),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(icon, size: 20, color: Theme.of(context).colorScheme.primary),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(label, style: Theme.of(context).textTheme.labelMedium),
Text(value, style: Theme.of(context).textTheme.bodyLarge),
],
),
),
],
),
);
}
Widget _statsCard() {
final st = _stats;
return Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Utilisation', style: Theme.of(context).textTheme.titleMedium),
const SizedBox(height: 12),
if (st == null)
const Center(child: Padding(padding: EdgeInsets.all(8), child: CircularProgressIndicator()))
else if (st['running'] != true)
const Text('Serveur éteint — pas de stats.')
else ...[
_gauge('CPU', (st['cpu_percent'] as num?)?.toDouble() ?? 0,
'${st['cpu_percent']} %'),
const SizedBox(height: 12),
_gauge('RAM', (st['mem_percent'] as num?)?.toDouble() ?? 0,
'${st['mem_used_mb']} Mo${st['mem_limit_mb'] != null ? ' / ${_fmtMb(st['mem_limit_mb'])}' : ''}'),
const SizedBox(height: 12),
Text('Réseau : ↓ ${st['net_rx_mb']} Mo ↑ ${st['net_tx_mb']} Mo',
style: Theme.of(context).textTheme.bodyMedium),
],
],
),
),
);
}
String _fmtMb(dynamic mb) {
final v = (mb as num).toDouble();
return v >= 1024 ? '${(v / 1024).toStringAsFixed(1)} Go' : '${v.round()} Mo';
}
Widget _gauge(String label, double percent, String value) {
final p = (percent / 100).clamp(0.0, 1.0);
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(label, style: const TextStyle(fontWeight: FontWeight.w600)),
Text(value, style: Theme.of(context).textTheme.bodyMedium),
],
),
const SizedBox(height: 6),
ClipRRect(
borderRadius: BorderRadius.circular(6),
child: LinearProgressIndicator(value: p, minHeight: 8),
),
],
);
}
Widget _imageCard() {
return Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Image', style: Theme.of(context).textTheme.titleMedium),
const SizedBox(height: 6),
Text('Screenshot ou visuel du serveur (stocké sur RustFS).',
style: Theme.of(context).textTheme.bodySmall),
const SizedBox(height: 12),
Row(
children: [
FilledButton.tonalIcon(
onPressed: _imgBusy ? null : _pickImage,
icon: _imgBusy
? const SizedBox(width: 16, height: 16, child: CircularProgressIndicator(strokeWidth: 2))
: const Icon(Icons.upload),
label: Text(_image == null ? 'Importer' : 'Remplacer'),
),
const SizedBox(width: 8),
if (_image != null)
OutlinedButton.icon(
onPressed: _imgBusy ? null : _deleteImage,
icon: const Icon(Icons.delete_outline),
label: const Text('Supprimer'),
),
],
),
],
),
),
);
}
}
class _Pill extends StatelessWidget {
const _Pill({required this.label, required this.color});
final String label;
final Color color;
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
decoration: BoxDecoration(
color: color.withOpacity(0.18),
borderRadius: BorderRadius.circular(999),
border: Border.all(color: color),
),
child: Text(label, style: TextStyle(color: color, fontSize: 12, fontWeight: FontWeight.w700)),
);
}
}
+102 -23
View File
@@ -1,3 +1,5 @@
import 'dart:typed_data';
import 'package:flutter/material.dart';
import '../models.dart';
@@ -5,6 +7,8 @@ import '../services/api_service.dart';
import '../services/auth_service.dart';
import '../services/update_service.dart';
import '../widgets/server_card.dart';
import 'add_server_screen.dart';
import 'server_detail_screen.dart';
import 'settings_screen.dart';
class ServersScreen extends StatefulWidget {
@@ -26,6 +30,15 @@ class _ServersScreenState extends State<ServersScreen> {
List<GameServer>? _servers;
String? _error;
final _busy = <String>{};
final _imgCache = <String, Uint8List?>{};
Future<Uint8List?> _image(GameServer s) async {
if (!s.hasImage) return null;
if (_imgCache.containsKey(s.id)) return _imgCache[s.id];
final b = await widget.api.imageBytes(s.id).catchError((_) => null);
_imgCache[s.id] = b;
return b;
}
@override
void initState() {
@@ -40,6 +53,7 @@ class _ServersScreenState extends State<ServersScreen> {
if (mounted) setState(() {
_servers = servers;
_error = null;
_imgCache.clear(); // recharge les images (elles ont pu changer)
});
} on UnauthorizedException {
await widget.auth.logout();
@@ -78,14 +92,42 @@ class _ServersScreenState extends State<ServersScreen> {
],
),
);
if (go == true) {
final ok = await UpdateService(widget.api.baseUrl).apply(info);
if (go != true || !mounted) return;
final progress = ValueNotifier<double?>(0);
showDialog(
context: context,
barrierDismissible: false,
builder: (_) => AlertDialog(
title: const Text('Téléchargement…'),
content: ValueListenableBuilder<double?>(
valueListenable: progress,
builder: (_, p, __) => Column(
mainAxisSize: MainAxisSize.min,
children: [
LinearProgressIndicator(value: p),
const SizedBox(height: 10),
Text(p == null ? '' : '${(p * 100).round()} %'),
],
),
),
),
);
final ok = await UpdateService(widget.api.baseUrl)
.apply(info, onProgress: (p) => progress.value = p);
if (mounted) Navigator.of(context, rootNavigator: true).pop(); // ferme la progression
if (mounted && !ok) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Impossible d\'ouvrir le téléchargement.')),
const SnackBar(content: Text('Mise à jour impossible.')),
);
}
}
Future<void> _openDetail(GameServer s) async {
await Navigator.push(context,
MaterialPageRoute(builder: (_) => ServerDetailScreen(server: s, api: widget.api)));
_refresh();
}
Future<void> _openSettings() async {
@@ -101,21 +143,38 @@ class _ServersScreenState extends State<ServersScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
return DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
title: const Text('Serveurs'),
actions: [
IconButton(onPressed: _openSettings, icon: const Icon(Icons.settings_outlined)),
IconButton(onPressed: _logout, icon: const Icon(Icons.logout)),
],
bottom: const TabBar(
tabs: [
Tab(icon: Icon(Icons.public), text: 'Production'),
Tab(icon: Icon(Icons.science_outlined), text: 'Preprod'),
],
),
),
body: _buildBody(),
floatingActionButton: FloatingActionButton.extended(
onPressed: _openAdd,
icon: const Icon(Icons.add),
label: const Text('Ajouter'),
),
body: RefreshIndicator(
onRefresh: _refresh,
child: _buildBody(),
),
);
}
Future<void> _openAdd() async {
final added = await Navigator.push<bool>(context,
MaterialPageRoute(builder: (_) => AddServerScreen(api: widget.api)));
if (added == true) _refresh();
}
Widget _buildBody() {
if (_error != null && _servers == null) {
return ListView(children: [
@@ -130,22 +189,42 @@ class _ServersScreenState extends State<ServersScreen> {
if (_servers == null) {
return const Center(child: CircularProgressIndicator());
}
return ListView.separated(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 24),
itemCount: _servers!.length,
separatorBuilder: (_, __) => const SizedBox(height: 14),
itemBuilder: (_, i) {
final s = _servers![i];
return FutureBuilder<String>(
future: widget.api.iconUrl(s.id),
builder: (_, snap) => ServerCard(
server: s,
iconUrl: snap.data ?? '',
busy: _busy.contains(s.id),
onToggle: () => _toggle(s),
),
);
},
final prod = _servers!.where((s) => !s.isPreprod).toList();
final preprod = _servers!.where((s) => s.isPreprod).toList();
return TabBarView(
children: [_envList(prod), _envList(preprod)],
);
}
Widget _envList(List<GameServer> list) {
return RefreshIndicator(
onRefresh: _refresh,
child: list.isEmpty
? ListView(children: const [
SizedBox(height: 120),
Center(child: Text('Aucun serveur dans cet environnement.')),
])
: ListView(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 24),
children: list.map(_card).toList(),
),
);
}
Widget _card(GameServer s) => Padding(
padding: const EdgeInsets.only(bottom: 14),
child: FutureBuilder<Uint8List?>(
future: _image(s),
builder: (_, snap) => ServerCard(
server: s,
iconUrl: '',
imageBytes: snap.data,
busy: _busy.contains(s.id),
onToggle: () => _toggle(s),
onTap: () => _openDetail(s),
),
),
);
}
+86
View File
@@ -1,4 +1,5 @@
import 'dart:convert';
import 'dart:typed_data';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
@@ -36,6 +37,55 @@ class ApiService {
return list.map((e) => GameServer.fromJson(e as Map<String, dynamic>)).toList();
}
Future<GameServer> server(String id) async {
final base = await baseUrl;
final res = await http.get(Uri.parse('$base/api/servers/$id'), headers: await _headers());
if (res.statusCode == 401) throw UnauthorizedException();
if (res.statusCode != 200) throw ApiException('Erreur ${res.statusCode}');
return GameServer.fromJson(jsonDecode(res.body) as Map<String, dynamic>);
}
Future<List<DockerContainer>> containers() async {
final base = await baseUrl;
final res = await http.get(Uri.parse('$base/api/containers'), headers: await _headers());
if (res.statusCode == 401) throw UnauthorizedException();
if (res.statusCode != 200) throw ApiException('Erreur ${res.statusCode}');
return (jsonDecode(res.body) as List)
.map((e) => DockerContainer.fromJson(e as Map<String, dynamic>))
.toList();
}
Future<GameServer> createServer(Map<String, dynamic> payload) async {
final base = await baseUrl;
final res = await http.post(
Uri.parse('$base/api/servers'),
headers: {...await _headers(), 'Content-Type': 'application/json'},
body: jsonEncode(payload),
);
if (res.statusCode == 401) throw UnauthorizedException();
if (res.statusCode >= 400) {
throw ApiException(_msg(res.body) ?? 'Création refusée (${res.statusCode})');
}
return GameServer.fromJson(jsonDecode(res.body) as Map<String, dynamic>);
}
Future<void> deleteServer(String id) async {
final base = await baseUrl;
final res = await http.delete(Uri.parse('$base/api/servers/$id'), headers: await _headers());
if (res.statusCode == 401) throw UnauthorizedException();
if (res.statusCode >= 400) {
throw ApiException(_msg(res.body) ?? 'Suppression refusée (${res.statusCode})');
}
}
String? _msg(String body) {
try {
return (jsonDecode(body) as Map<String, dynamic>)['detail'] as String?;
} catch (_) {
return null;
}
}
Future<void> start(String id) => _action(id, 'start');
Future<void> stop(String id) => _action(id, 'stop');
@@ -50,6 +100,42 @@ class ApiService {
}
Future<String> iconUrl(String id) async => '${await baseUrl}/api/servers/$id/icon';
/// Stats d'utilisation du conteneur (CPU/RAM/réseau). `{running:false}` si éteint.
Future<Map<String, dynamic>> stats(String id) async {
final base = await baseUrl;
final res = await http.get(Uri.parse('$base/api/servers/$id/stats'), headers: await _headers());
if (res.statusCode == 401) throw UnauthorizedException();
if (res.statusCode != 200) throw ApiException('Erreur ${res.statusCode}');
return jsonDecode(res.body) as Map<String, dynamic>;
}
/// Image importée du serveur (bytes), null si aucune.
Future<Uint8List?> imageBytes(String id) async {
final base = await baseUrl;
final res = await http.get(Uri.parse('$base/api/servers/$id/image'), headers: await _headers());
if (res.statusCode == 401) throw UnauthorizedException();
if (res.statusCode != 200) return null;
return res.bodyBytes;
}
Future<void> uploadImage(String id, String filePath) async {
final base = await baseUrl;
final token = await _auth.validToken();
final req = http.MultipartRequest('POST', Uri.parse('$base/api/servers/$id/image'))
..headers['Authorization'] = 'Bearer ${token ?? ''}'
..files.add(await http.MultipartFile.fromPath('file', filePath));
final res = await http.Response.fromStream(await req.send());
if (res.statusCode == 401) throw UnauthorizedException();
if (res.statusCode >= 400) throw ApiException('Envoi refusé (${res.statusCode})');
}
Future<void> deleteImage(String id) async {
final base = await baseUrl;
final res = await http.delete(Uri.parse('$base/api/servers/$id/image'), headers: await _headers());
if (res.statusCode == 401) throw UnauthorizedException();
if (res.statusCode >= 400) throw ApiException('Suppression refusée (${res.statusCode})');
}
}
class UnauthorizedException implements Exception {}
+89 -41
View File
@@ -1,67 +1,115 @@
import 'package:flutter_appauth/flutter_appauth.dart';
import 'dart:convert';
import 'dart:math';
import 'package:crypto/crypto.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:flutter_web_auth_2/flutter_web_auth_2.dart';
import 'package:http/http.dart' as http;
import '../config.dart';
/// Authentification OIDC pocket-id (Authorization Code + PKCE, client public).
/// Le jeton d'identité (JWT) est stocké de façon sécurisée et envoyé à l'API.
/// Auth OIDC pocket-id : Authorization Code + PKCE via flutter_web_auth_2
/// (schéma custom capté de façon fiable), échange de token en direct.
class AuthService {
final _appAuth = const FlutterAppAuth();
final _storage = const FlutterSecureStorage();
static const _kIdToken = 'id_token';
static const _kRefresh = 'refresh_token';
static const _kExpiry = 'access_expiry';
static const _kExpiry = 'expiry';
Map<String, dynamic>? _discovery;
Future<Map<String, dynamic>> _disco() async {
_discovery ??= jsonDecode((await http.get(
Uri.parse('${Config.oidcIssuer}/.well-known/openid-configuration'),
))
.body) as Map<String, dynamic>;
return _discovery!;
}
Future<String?> get idToken => _storage.read(key: _kIdToken);
Future<bool> isLoggedIn() async => (await idToken) != null;
String _rand(int n) {
final r = Random.secure();
return base64UrlEncode(List<int>.generate(n, (_) => r.nextInt(256)))
.replaceAll('=', '')
.substring(0, n);
}
Future<bool> login() async {
final result = await _appAuth.authorizeAndExchangeCode(
AuthorizationTokenRequest(
Config.oidcClientId,
Config.oidcRedirect,
issuer: Config.oidcIssuer,
scopes: Config.oidcScopes,
promptValues: ['login'],
),
final disco = await _disco();
final verifier = _rand(64);
final challenge = base64UrlEncode(sha256.convert(ascii.encode(verifier)).bytes)
.replaceAll('=', '');
final state = _rand(24);
final authUrl = Uri.parse(disco['authorization_endpoint'] as String).replace(queryParameters: {
'response_type': 'code',
'client_id': Config.oidcClientId,
'redirect_uri': Config.oidcRedirect,
'scope': Config.oidcScopes.join(' '),
'state': state,
'code_challenge': challenge,
'code_challenge_method': 'S256',
// Pas de prompt=login : on réutilise la session pocket-id (cookie Chrome)
// → reconnexion silencieuse, pas de re-cérémonie passkey (qui plante
// en boucle dans un Custom Tab Android 10).
});
final result = await FlutterWebAuth2.authenticate(
url: authUrl.toString(),
callbackUrlScheme: Config.oidcScheme,
);
if (result.idToken == null) return false;
await _storage.write(key: _kIdToken, value: result.idToken);
await _storage.write(key: _kRefresh, value: result.refreshToken);
await _storage.write(
key: _kExpiry,
value: result.accessTokenExpirationDateTime?.toIso8601String(),
final params = Uri.parse(result).queryParameters;
if (params['state'] != state || params['code'] == null) return false;
final token = await http.post(
Uri.parse(disco['token_endpoint'] as String),
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: {
'grant_type': 'authorization_code',
'code': params['code']!,
'redirect_uri': Config.oidcRedirect,
'client_id': Config.oidcClientId,
'code_verifier': verifier,
},
);
if (token.statusCode != 200) return false;
await _store(jsonDecode(token.body) as Map<String, dynamic>);
return true;
}
/// Rafraîchit le jeton si expiré (via refresh_token), renvoie l'id_token courant.
Future<String?> validToken() async {
final expiry = await _storage.read(key: _kExpiry);
final refresh = await _storage.read(key: _kRefresh);
if (expiry != null && refresh != null) {
final exp = DateTime.tryParse(expiry);
if (exp != null && exp.isBefore(DateTime.now().add(const Duration(seconds: 30)))) {
try {
final r = await _appAuth.token(TokenRequest(
Config.oidcClientId,
Config.oidcRedirect,
issuer: Config.oidcIssuer,
refreshToken: refresh,
scopes: Config.oidcScopes,
));
if (r.idToken != null) {
await _storage.write(key: _kIdToken, value: r.idToken);
await _storage.write(key: _kRefresh, value: r.refreshToken ?? refresh);
Future<void> _store(Map<String, dynamic> t) async {
await _storage.write(key: _kIdToken, value: t['id_token'] as String?);
if (t['refresh_token'] != null) {
await _storage.write(key: _kRefresh, value: t['refresh_token'] as String);
}
final expiresIn = (t['expires_in'] as num?)?.toInt() ?? 3600;
await _storage.write(
key: _kExpiry,
value: r.accessTokenExpirationDateTime?.toIso8601String(),
value: DateTime.now().add(Duration(seconds: expiresIn)).toIso8601String(),
);
}
} catch (_) {/* on garde l'ancien token, l'API renverra 401 si mort */}
}
/// Rafraîchit si expiré, renvoie l'id_token courant.
Future<String?> validToken() async {
final expiry = DateTime.tryParse(await _storage.read(key: _kExpiry) ?? '');
final refresh = await _storage.read(key: _kRefresh);
if (expiry != null && refresh != null &&
expiry.isBefore(DateTime.now().add(const Duration(seconds: 30)))) {
try {
final disco = await _disco();
final r = await http.post(
Uri.parse(disco['token_endpoint'] as String),
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: {
'grant_type': 'refresh_token',
'refresh_token': refresh,
'client_id': Config.oidcClientId,
},
);
if (r.statusCode == 200) await _store(jsonDecode(r.body) as Map<String, dynamic>);
} catch (_) {/* garde l'ancien */}
}
return idToken;
}
+39 -4
View File
@@ -1,12 +1,15 @@
import 'dart:convert';
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:open_filex/open_filex.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:path_provider/path_provider.dart';
import 'package:url_launcher/url_launcher.dart';
/// Vérifie s'il existe une version plus récente (API `/version`) et, si oui,
/// ouvre l'URL de l'APK (le navigateur télécharge, l'utilisateur installe —
/// robuste, sans dépendance de packaging fragile).
/// Détecte une version plus récente (`/version`) et l'installe **in-app** :
/// télécharge l'APK dans le stockage de l'app puis lance l'installeur système
/// (un seul tap « Installer »). Fallback navigateur si l'install directe échoue.
class UpdateService {
UpdateService(this._baseUrl);
final Future<String> _baseUrl;
@@ -31,7 +34,39 @@ class UpdateService {
return null;
}
Future<bool> apply(UpdateInfo info) async {
/// Télécharge l'APK puis lance l'installeur. `onProgress` : 0.0 → 1.0
/// (ou null si la taille est inconnue). Renvoie true si l'installeur s'ouvre.
Future<bool> apply(UpdateInfo info, {void Function(double?)? onProgress}) async {
try {
final dir = await getExternalStorageDirectory() ?? await getTemporaryDirectory();
final file = File('${dir.path}/gamemanager-update.apk');
final req = http.Request('GET', Uri.parse(info.apkUrl));
final resp = await req.send().timeout(const Duration(seconds: 30));
if (resp.statusCode != 200) return _fallback(info);
final total = resp.contentLength ?? 0;
var received = 0;
final sink = file.openWrite();
await for (final chunk in resp.stream) {
sink.add(chunk);
received += chunk.length;
onProgress?.call(total > 0 ? received / total : null);
}
await sink.close();
final result = await OpenFilex.open(
file.path,
type: 'application/vnd.android.package-archive',
);
if (result.type == ResultType.done) return true;
return _fallback(info); // l'installeur n'a pas pris → navigateur
} catch (_) {
return _fallback(info);
}
}
Future<bool> _fallback(UpdateInfo info) async {
final uri = Uri.parse(info.apkUrl);
if (!await canLaunchUrl(uri)) return false;
return launchUrl(uri, mode: LaunchMode.externalApplication);
+97 -11
View File
@@ -1,42 +1,128 @@
import 'package:flutter/material.dart';
/// Thèmes Material 3 (clair + sombre) avec un accent unifié.
/// Thème « flamme / chaud sombre » — anthracite + accents orange→rouge.
/// Remplace la palette Material par défaut (violet/teal).
class AppTheme {
static const _seed = Color(0xFF5E5CE6);
// Palette
static const bg = Color(0xFF14110F); // fond anthracite
static const surface1 = Color(0xFF1F1B18); // cartes / champs
static const surface2 = Color(0xFF262119); // éléments surélevés
static const flame = Color(0xFFFF7A18); // orange accent
static const ember = Color(0xFFFF3D00); // rouge braise
static const ink = Color(0xFFF5EFE9); // texte principal
static const inkMuted = Color(0xFFA89F97); // texte secondaire
static ThemeData light() => _base(Brightness.light);
static ThemeData dark() => _base(Brightness.dark);
static ThemeData light() => dark(); // app pensée sombre → même thème
static ThemeData dark() {
const scheme = ColorScheme(
brightness: Brightness.dark,
primary: flame,
onPrimary: Color(0xFF230F00),
primaryContainer: Color(0xFF3A2410),
onPrimaryContainer: Color(0xFFFFD9B8),
secondary: ember,
onSecondary: Colors.white,
secondaryContainer: Color(0xFF4A1A0A),
onSecondaryContainer: Color(0xFFFFD5C8),
tertiary: Color(0xFFFFB74D),
onTertiary: Color(0xFF241400),
error: Color(0xFFFF6B5E),
onError: Color(0xFF3A0A05),
surface: bg,
onSurface: ink,
surfaceContainerLowest: Color(0xFF0F0D0B),
surfaceContainerLow: surface1,
surfaceContainer: surface1,
surfaceContainerHigh: surface2,
surfaceContainerHighest: Color(0xFF2E2820),
onSurfaceVariant: inkMuted,
outline: Color(0xFF4A433D),
outlineVariant: Color(0xFF332E29),
inverseSurface: ink,
onInverseSurface: bg,
shadow: Colors.black,
scrim: Colors.black,
);
static ThemeData _base(Brightness brightness) {
final scheme = ColorScheme.fromSeed(seedColor: _seed, brightness: brightness);
return ThemeData(
useMaterial3: true,
colorScheme: scheme,
scaffoldBackgroundColor: scheme.surface,
appBarTheme: AppBarTheme(
backgroundColor: scheme.surface,
foregroundColor: scheme.onSurface,
scaffoldBackgroundColor: bg,
canvasColor: bg,
appBarTheme: const AppBarTheme(
backgroundColor: bg,
foregroundColor: ink,
centerTitle: false,
elevation: 0,
scrolledUnderElevation: 0,
titleTextStyle: TextStyle(
color: scheme.onSurface,
color: ink,
fontSize: 24,
fontWeight: FontWeight.w800,
letterSpacing: -0.5,
),
),
cardTheme: CardTheme(
color: surface1,
clipBehavior: Clip.antiAlias,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(22)),
elevation: 0,
),
tabBarTheme: const TabBarTheme(
labelColor: flame,
unselectedLabelColor: inkMuted,
indicatorColor: flame,
dividerColor: Colors.transparent,
labelStyle: TextStyle(fontWeight: FontWeight.w700),
),
filledButtonTheme: FilledButtonThemeData(
style: FilledButton.styleFrom(
backgroundColor: flame,
foregroundColor: const Color(0xFF230F00),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
padding: const EdgeInsets.symmetric(horizontal: 22, vertical: 14),
textStyle: const TextStyle(fontWeight: FontWeight.w700, fontSize: 15),
),
),
outlinedButtonTheme: OutlinedButtonThemeData(
style: OutlinedButton.styleFrom(
foregroundColor: ink,
side: const BorderSide(color: Color(0xFF4A433D)),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
),
),
floatingActionButtonTheme: const FloatingActionButtonThemeData(
backgroundColor: flame,
foregroundColor: Color(0xFF230F00),
),
inputDecorationTheme: InputDecorationTheme(
filled: true,
fillColor: surface1,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(14),
borderSide: BorderSide.none,
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(14),
borderSide: const BorderSide(color: Color(0xFF332E29)),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(14),
borderSide: const BorderSide(color: flame, width: 2),
),
labelStyle: const TextStyle(color: inkMuted),
),
progressIndicatorTheme: const ProgressIndicatorThemeData(
color: flame,
linearTrackColor: Color(0xFF332E29),
),
dividerTheme: const DividerThemeData(color: Color(0xFF332E29)),
snackBarTheme: const SnackBarThemeData(
backgroundColor: surface2,
contentTextStyle: TextStyle(color: ink),
),
dialogTheme: const DialogTheme(backgroundColor: surface1),
chipTheme: const ChipThemeData(backgroundColor: surface2),
);
}
}
+85 -4
View File
@@ -1,4 +1,7 @@
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import '../models.dart';
@@ -9,45 +12,79 @@ class ServerCard extends StatelessWidget {
required this.iconUrl,
required this.busy,
required this.onToggle,
this.onTap,
this.imageBytes,
});
final GameServer server;
final String iconUrl;
final bool busy;
final VoidCallback onToggle;
final VoidCallback? onTap;
final Uint8List? imageBytes;
@override
Widget build(BuildContext context) {
final t = server.theme;
final badge = server.statusBadge;
final hasImg = imageBytes != null;
return Card(
child: Container(
decoration: BoxDecoration(
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: onTap,
child: Ink(
decoration: hasImg
? BoxDecoration(
image: DecorationImage(image: MemoryImage(imageBytes!), fit: BoxFit.cover),
)
: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [t.start, t.end],
),
),
child: Container(
decoration: hasImg
? const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [Color(0x66000000), Color(0xCC000000)],
),
)
: null,
padding: const EdgeInsets.all(18),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
if (!hasImg) ...[
_Icon(server: server, iconUrl: iconUrl, fallback: t.icon),
const SizedBox(width: 14),
],
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(server.name,
Row(
children: [
Flexible(
child: Text(server.name,
style: const TextStyle(
color: Colors.white,
fontSize: 19,
fontWeight: FontWeight.w800),
maxLines: 1,
overflow: TextOverflow.ellipsis),
),
if (server.isPreprod) ...[
const SizedBox(width: 8),
const _Tag(label: 'PREPROD'),
],
],
),
if (server.subtitle != null)
Text(server.subtitle!,
style: TextStyle(
@@ -80,12 +117,18 @@ class ServerCard extends StatelessWidget {
)
else
const Spacer(),
if (server.web && server.openUrl != null) ...[
_OpenButton(url: server.openUrl!),
const SizedBox(width: 8),
],
_ToggleButton(up: server.isUp, busy: busy, onToggle: onToggle),
],
),
],
),
),
),
),
);
}
}
@@ -103,7 +146,7 @@ class _Icon extends StatelessWidget {
child: SizedBox(
width: 52,
height: 52,
child: (server.hasIcon)
child: (server.hasIcon && iconUrl.isNotEmpty)
? Image.network(iconUrl,
fit: BoxFit.cover,
errorBuilder: (_, __, ___) => _fallbackBox())
@@ -118,6 +161,44 @@ class _Icon extends StatelessWidget {
);
}
class _Tag extends StatelessWidget {
const _Tag({required this.label});
final String label;
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 2),
decoration: BoxDecoration(
color: Colors.black.withOpacity(0.28),
borderRadius: BorderRadius.circular(6),
border: Border.all(color: Colors.white.withOpacity(0.5), width: 1),
),
child: Text(label,
style: const TextStyle(
color: Colors.white, fontSize: 10, fontWeight: FontWeight.w800, letterSpacing: 0.6)),
);
}
}
class _OpenButton extends StatelessWidget {
const _OpenButton({required this.url});
final String url;
@override
Widget build(BuildContext context) {
return OutlinedButton.icon(
onPressed: () => launchUrl(Uri.parse(url), mode: LaunchMode.externalApplication),
style: OutlinedButton.styleFrom(
foregroundColor: Colors.white,
side: BorderSide(color: Colors.white.withOpacity(0.7)),
),
icon: const Icon(Icons.open_in_new, size: 18),
label: const Text('Ouvrir'),
);
}
}
class _StatusPill extends StatelessWidget {
const _StatusPill({required this.label, required this.color, required this.pulse});
final String label;
+169 -17
View File
@@ -33,6 +33,22 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.18.0"
cross_file:
dependency: transitive
description:
name: cross_file
sha256: "7caf6a750a0c04effbb52a676dce9a4a592e10ad35c34d6d2d0e4811160d5670"
url: "https://pub.dev"
source: hosted
version: "0.3.4+2"
crypto:
dependency: "direct main"
description:
name: crypto
sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf
url: "https://pub.dev"
source: hosted
version: "3.0.7"
cupertino_icons:
dependency: "direct main"
description:
@@ -41,6 +57,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.0.8"
desktop_webview_window:
dependency: transitive
description:
name: desktop_webview_window
sha256: "57cf20d81689d5cbb1adfd0017e96b669398a669d927906073b0e42fc64111c0"
url: "https://pub.dev"
source: hosted
version: "0.2.3"
ffi:
dependency: transitive
description:
@@ -57,27 +81,43 @@ packages:
url: "https://pub.dev"
source: hosted
version: "7.0.1"
file_selector_linux:
dependency: transitive
description:
name: file_selector_linux
sha256: "54cbbd957e1156d29548c7d9b9ec0c0ebb6de0a90452198683a7d23aed617a33"
url: "https://pub.dev"
source: hosted
version: "0.9.3+2"
file_selector_macos:
dependency: transitive
description:
name: file_selector_macos
sha256: "271ab9986df0c135d45c3cdb6bd0faa5db6f4976d3e4b437cf7d0f258d941bfc"
url: "https://pub.dev"
source: hosted
version: "0.9.4+2"
file_selector_platform_interface:
dependency: transitive
description:
name: file_selector_platform_interface
sha256: a3994c26f10378a039faa11de174d7b78eb8f79e4dd0af2a451410c1a5c3f66b
url: "https://pub.dev"
source: hosted
version: "2.6.2"
file_selector_windows:
dependency: transitive
description:
name: file_selector_windows
sha256: "320fcfb6f33caa90f0b58380489fc5ac05d99ee94b61aa96ec2bff0ba81d3c2b"
url: "https://pub.dev"
source: hosted
version: "0.9.3+4"
flutter:
dependency: "direct main"
description: flutter
source: sdk
version: "0.0.0"
flutter_appauth:
dependency: "direct main"
description:
name: flutter_appauth
sha256: "0aa449d8991f70e7847d55b8bff0890fb41dc62c1d8526337e4073e806813bcb"
url: "https://pub.dev"
source: hosted
version: "8.0.3"
flutter_appauth_platform_interface:
dependency: transitive
description:
name: flutter_appauth_platform_interface
sha256: ccf5e1d8c40dd35b297290b33cc1896648b4b92a2ec3f62a436c62a8eef9a9db
url: "https://pub.dev"
source: hosted
version: "8.0.0"
flutter_lints:
dependency: "direct dev"
description:
@@ -86,6 +126,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "5.0.0"
flutter_plugin_android_lifecycle:
dependency: transitive
description:
name: flutter_plugin_android_lifecycle
sha256: "1c2b787f99bdca1f3718543f81d38aa1b124817dfeb9fb196201bea85b6134bf"
url: "https://pub.dev"
source: hosted
version: "2.0.26"
flutter_secure_storage:
dependency: "direct main"
description:
@@ -134,6 +182,22 @@ packages:
url: "https://pub.dev"
source: hosted
version: "3.1.2"
flutter_web_auth_2:
dependency: "direct main"
description:
name: flutter_web_auth_2
sha256: "3c14babeaa066c371f3a743f204dd0d348b7d42ffa6fae7a9847a521aff33696"
url: "https://pub.dev"
source: hosted
version: "4.1.0"
flutter_web_auth_2_platform_interface:
dependency: transitive
description:
name: flutter_web_auth_2_platform_interface
sha256: c63a472c8070998e4e422f6b34a17070e60782ac442107c70000dd1bed645f4d
url: "https://pub.dev"
source: hosted
version: "4.1.0"
flutter_web_plugins:
dependency: transitive
description: flutter
@@ -155,6 +219,70 @@ packages:
url: "https://pub.dev"
source: hosted
version: "4.0.2"
image_picker:
dependency: "direct main"
description:
name: image_picker
sha256: "021834d9c0c3de46bf0fe40341fa07168407f694d9b2bb18d532dc1261867f7a"
url: "https://pub.dev"
source: hosted
version: "1.1.2"
image_picker_android:
dependency: transitive
description:
name: image_picker_android
sha256: "82652a75e3dd667a91187769a6a2cc81bd8c111bbead698d8e938d2b63e5e89a"
url: "https://pub.dev"
source: hosted
version: "0.8.12+21"
image_picker_for_web:
dependency: transitive
description:
name: image_picker_for_web
sha256: "717eb042ab08c40767684327be06a5d8dbb341fe791d514e4b92c7bbe1b7bb83"
url: "https://pub.dev"
source: hosted
version: "3.0.6"
image_picker_ios:
dependency: transitive
description:
name: image_picker_ios
sha256: "05da758e67bc7839e886b3959848aa6b44ff123ab4b28f67891008afe8ef9100"
url: "https://pub.dev"
source: hosted
version: "0.8.12+2"
image_picker_linux:
dependency: transitive
description:
name: image_picker_linux
sha256: "34a65f6740df08bbbeb0a1abd8e6d32107941fd4868f67a507b25601651022c9"
url: "https://pub.dev"
source: hosted
version: "0.2.1+2"
image_picker_macos:
dependency: transitive
description:
name: image_picker_macos
sha256: "1b90ebbd9dcf98fb6c1d01427e49a55bd96b5d67b8c67cf955d60a5de74207c1"
url: "https://pub.dev"
source: hosted
version: "0.2.1+2"
image_picker_platform_interface:
dependency: transitive
description:
name: image_picker_platform_interface
sha256: "886d57f0be73c4b140004e78b9f28a8914a09e50c2d816bdd0520051a71236a0"
url: "https://pub.dev"
source: hosted
version: "2.10.1"
image_picker_windows:
dependency: transitive
description:
name: image_picker_windows
sha256: "6ad07afc4eb1bc25f3a01084d28520496c4a3bb0cb13685435838167c9dcedeb"
url: "https://pub.dev"
source: hosted
version: "0.2.1+1"
js:
dependency: transitive
description:
@@ -187,6 +315,22 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.15.0"
mime:
dependency: transitive
description:
name: mime
sha256: "41a20518f0cb1256669420fdba0cd90d21561e560ac240f26ef8322e45bb7ed6"
url: "https://pub.dev"
source: hosted
version: "2.0.0"
open_filex:
dependency: "direct main"
description:
name: open_filex
sha256: "9976da61b6a72302cf3b1efbce259200cd40232643a467aac7370addf94d6900"
url: "https://pub.dev"
source: hosted
version: "4.7.0"
package_info_plus:
dependency: "direct main"
description:
@@ -212,7 +356,7 @@ packages:
source: hosted
version: "1.9.1"
path_provider:
dependency: transitive
dependency: "direct main"
description:
name: path_provider
sha256: "50c5dd5b6e1aaf6fb3a78b33f6aa3afca52bf903a8a5298f53101fdaee55bbcd"
@@ -456,6 +600,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "5.10.1"
window_to_front:
dependency: transitive
description:
name: window_to_front
sha256: "14fad8984db4415e2eeb30b04bb77140b180e260d6cb66b26de126a8657a9241"
url: "https://pub.dev"
source: hosted
version: "0.0.4"
xdg_directories:
dependency: transitive
description:
+5 -1
View File
@@ -10,11 +10,15 @@ dependencies:
flutter:
sdk: flutter
http: ^1.2.2
flutter_appauth: ^8.0.0
flutter_web_auth_2: ^4.1.0
crypto: ^3.0.6
flutter_secure_storage: ^9.2.2
shared_preferences: ^2.3.2
package_info_plus: ^8.1.1
url_launcher: ^6.3.1
path_provider: ^2.1.4
open_filex: ^4.5.0
image_picker: ^1.1.2
cupertino_icons: ^1.0.8
dev_dependencies:
+31 -16
View File
@@ -2,7 +2,7 @@
"""Patche le scaffold Android généré par `flutter create` :
- permissions (internet + auto-install APK)
- signature release depuis key.properties
- schéma de redirection OIDC (flutter_appauth)
- CallbackActivity flutter_web_auth_2 (retour OIDC, schéma nfteam.gamemanager)
Lancé dans la CI après `flutter create`. Idempotent."""
import os
import re
@@ -11,7 +11,7 @@ KSPW = os.environ["KSPW"]
ALIAS = os.environ["ALIAS"]
KEYSTORE_PATH = os.environ.get("KEYSTORE_PATH", os.path.abspath("gamemanager.keystore"))
# 1) key.properties (chemin absolu du keystore, robuste peu importe le cwd gradle)
# 1) key.properties (chemin absolu du keystore)
with open("android/key.properties", "w") as f:
f.write(
f"storePassword={KSPW}\n"
@@ -20,7 +20,7 @@ with open("android/key.properties", "w") as f:
f"storeFile={KEYSTORE_PATH}\n"
)
# 2) AndroidManifest : permissions
# 2) AndroidManifest : permissions + CallbackActivity OIDC
man = "android/app/src/main/AndroidManifest.xml"
s = open(man).read()
perms = (
@@ -29,12 +29,25 @@ perms = (
)
if "REQUEST_INSTALL_PACKAGES" not in s:
s = s.replace("<application", perms + " <application", 1)
callback = (
' <activity android:name="com.linusu.flutter_web_auth_2.CallbackActivity" '
'android:exported="true">\n'
' <intent-filter android:label="flutter_web_auth_2">\n'
' <action android:name="android.intent.action.VIEW"/>\n'
' <category android:name="android.intent.category.DEFAULT"/>\n'
' <category android:name="android.intent.category.BROWSABLE"/>\n'
' <data android:scheme="nfteam.gamemanager"/>\n'
' </intent-filter>\n'
' </activity>\n'
)
if "flutter_web_auth_2.CallbackActivity" not in s:
s = s.replace("</application>", callback + " </application>", 1)
open(man, "w").write(s)
# 3) build.gradle : signature + schéma OIDC
# 3) build.gradle : signature release
gr = "android/app/build.gradle"
s = open(gr).read()
# ⚠️ Rien n'est autorisé AVANT le bloc plugins {} → on insère juste avant `android {`
# ⚠️ Rien avant plugins {} → insérer juste avant `android {`
if "keystoreProperties" not in s:
s = s.replace(
"android {",
@@ -44,25 +57,27 @@ if "keystoreProperties" not in s:
'android {',
1,
)
if "appAuthRedirectScheme" not in s:
s = s.replace(
"defaultConfig {",
'defaultConfig {\n manifestPlaceholders += [appAuthRedirectScheme: "nfteam.gamemanager"]',
1,
)
if "signingConfigs {" not in s:
s = re.sub(
r"(\n\s*buildTypes\s*\{)",
'\n signingConfigs {\n'
' release {\n'
' keyAlias keystoreProperties["keyAlias"]\n'
' keyPassword keystoreProperties["keyPassword"]\n'
' storeFile file(keystoreProperties["storeFile"])\n'
' storePassword keystoreProperties["storePassword"]\n'
' keyAlias = keystoreProperties["keyAlias"]\n'
' keyPassword = keystoreProperties["keyPassword"]\n'
' storeFile = file(keystoreProperties["storeFile"])\n'
' storePassword = keystoreProperties["storePassword"]\n'
' }\n }\n\\1',
s,
count=1,
)
# Flutter 3.24 génère `signingConfig = signingConfigs.debug` (AVEC `=`). On gère
# les deux formes pour ne jamais laisser le build release signé en clé debug
# (sinon signature différente à chaque run CI → « conflit » à l'install de MAJ).
before = s
s = s.replace("signingConfig = signingConfigs.debug", "signingConfig = signingConfigs.release")
s = s.replace("signingConfig signingConfigs.debug", "signingConfig signingConfigs.release")
if s == before:
raise SystemExit("patch_android: ERREUR — ligne 'signingConfig ... debug' introuvable, "
"signature release NON appliquée (build annulé)")
open(gr, "w").write(s)
print("patch_android: OK")
print("patch_android: OK (signature release appliquee)")