Security: Cloud-Auth auf Bearer-JWT umgestellt (IDOR-Luecke geschlossen)

- cloud_service: echter Login gegen baka-auth, Token statt X-API-Key/X-User
- app_config: hartcodierten API-Key-Default entfernt
- download_service + melo_logger: Bearer-Token statt X-API-Key
- navidrome: Passwort in flutter_secure_storage (Keychain/Keystore)
- song: token-haltige stream_url wird nicht mehr in SQLite persistiert
- cloud_screen: Pfad-Traversal beim Download-Dateinamen gefixt (p.basename)
- home_screen: Login-Dialog mit Passwort-Feld, Auto-Sync nutzt restoreLogin
This commit is contained in:
Hermes (Server)
2026-07-31 14:31:12 +02:00
parent 3e9389ab59
commit 9a880b0f21
17 changed files with 1552 additions and 181 deletions
+335
View File
@@ -0,0 +1,335 @@
import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import 'package:just_audio/just_audio.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../utils/farb_theme.dart';
import '../services/cloud_service.dart';
import '../services/melo_logger.dart';
import '../models/song.dart';
import '../database/db_helper.dart';
import '../services/id3_reader.dart';
class CloudScreen extends StatefulWidget {
final CloudService cloud;
final VoidCallback onSongsChanged;
const CloudScreen({super.key, required this.cloud, required this.onSongsChanged});
@override
State<CloudScreen> createState() => _CloudScreenState();
}
class _CloudScreenState extends State<CloudScreen> {
int _serverCount = 0;
bool _ladt = false;
String? _status;
bool _autoSync = true;
int _syncIntervall = 6;
String _aktuellerDownload = '';
int _downloadFortschritt = 0;
int _downloadGesamt = 0;
@override
void initState() {
super.initState();
_ladeStatus();
_ladeSettings();
}
Future<void> _ladeStatus() async {
final p = await SharedPreferences.getInstance();
final nutzer = p.getString('melo_nutzer') ?? '';
await widget.cloud.restoreLogin();
if (nutzer.isEmpty || !widget.cloud.istAngemeldet) {
if (mounted) setState(() { _serverCount = 0; _status = 'Nicht angemeldet'; });
return;
}
final st = await widget.cloud.status();
if (!mounted) return;
setState(() {
_serverCount = st?['total'] ?? 0;
_status = st != null ? 'Verbunden ($nutzer)' : 'Keine Verbindung';
});
}
Future<void> _ladeSettings() async {
final p = await SharedPreferences.getInstance();
if (mounted) setState(() {
_autoSync = p.getBool('cloud_auto') ?? true;
_syncIntervall = p.getInt('cloud_interval') ?? 6;
});
}
Future<void> _upload() async {
setState(() => _ladt = true);
final dir = Directory('${(await getApplicationDocumentsDirectory()).path}/music');
if (!await dir.exists()) {
setState(() { _ladt = false; _status = 'Keine lokalen Songs'; });
return;
}
final files = dir.listSync().whereType<File>().where((f) =>
f.path.endsWith('.mp3') || f.path.endsWith('.m4a'));
int count = 0;
for (final f in files) {
final sid = await widget.cloud.upload(f.path, f.path.split('/').last);
if (sid != null) count++;
}
await _ladeStatus();
if (mounted) {
setState(() { _ladt = false; _status = '$count Songs hochgeladen'; });
MeloLogger().aktion('cloud_upload', {'count': count});
}
}
Future<void> _download() async {
setState(() {
_ladt = true;
_status = null;
_aktuellerDownload = 'Lade Liste...';
_downloadFortschritt = 0;
_downloadGesamt = 0;
});
// Auf Android: Music/Melo (getExternalStorageDirectory)
// Auf iOS: Documents/music (Sandbox, sichtbar in Dateien-App)
String basePath;
if (Platform.isIOS) {
basePath = '${(await getApplicationDocumentsDirectory()).path}/music';
} else {
// Wenn voller Speicherzugriff: Downloads/Melo (sichtbar)
final p = await SharedPreferences.getInstance();
if (p.getBool('manage_storage') == true) {
final d = await getDownloadsDirectory();
basePath = d != null ? '${d.path}/Melo' : '${(await getApplicationDocumentsDirectory()).path}/music';
} else {
final ext = await getExternalStorageDirectory();
basePath = ext != null ? '${ext.path}/Melo' : '${(await getApplicationDocumentsDirectory()).path}/music';
}
}
final dir = Directory(basePath);
if (!await dir.exists()) await dir.create(recursive: true);
final localFiles = dir.listSync().whereType<File>()
.map((f) => f.path.split('/').last).toSet();
final serverSongs = await widget.cloud.listSongs();
// Filter: nur neue Songs
final neue = serverSongs.where((s) {
final title = s['title'].toString();
return !localFiles.contains(title);
}).toList();
if (neue.isEmpty) {
if (mounted) setState(() { _ladt = false; _status = 'Alle Songs bereits lokal'; });
return;
}
setState(() => _downloadGesamt = neue.length);
final db = DbHelper();
for (int i = 0; i < neue.length; i++) {
final song = neue[i];
final title = song['title'].toString();
final sid = song['id'].toString();
// Dateinamen säubern (p.basename verhindert Pfad-Traversal via Titel)
final safeTitle = p.basename(title).replaceAll(RegExp(r'[^\w\s\.-]'), '_').trim();
final dateiName = safeTitle.endsWith('.mp3') || safeTitle.endsWith('.m4a')
? safeTitle : '$safeTitle.mp3';
final dest = '${dir.path}/$dateiName';
if (mounted) setState(() {
_aktuellerDownload = title;
_downloadFortschritt = i + 1;
});
final ok = await widget.cloud.download(sid, dest);
if (ok) {
// Dauer auslesen
int dauer = 0;
try {
final ap = AudioPlayer();
await ap.setFilePath(dest).timeout(const Duration(milliseconds: 2000));
dauer = ap.duration?.inSeconds ?? 0;
await ap.dispose();
} catch (_) {}
// ID3-Metadaten & Cover aus der heruntergeladenen Datei extrahieren
final id3 = Id3Reader.lesen(dest);
String? coverPfad;
if (id3['cover'] != null && id3['cover'] is List<int>) {
try {
final coversDir = Directory('${(await getApplicationDocumentsDirectory()).path}/covers');
if (!await coversDir.exists()) await coversDir.create(recursive: true);
final coverFile = File('${coversDir.path}/cloud_$sid.jpg');
await coverFile.writeAsBytes(id3['cover'] as List<int>);
coverPfad = coverFile.path;
} catch (_) {}
}
try {
await db.songEinfuegen(Song(
titel: (id3['titel'] as String).isNotEmpty
? id3['titel']
: title.replaceAll('.mp3', '').replaceAll('.m4a', ''),
kuenstler: (id3['kuenstler'] as String).isNotEmpty
? id3['kuenstler']
: 'Melo Cloud',
album: id3['album'] ?? '',
dauerSekunden: dauer,
dateiPfad: dest,
coverPfad: coverPfad,
downloadQuelle: 'cloud',
istHeruntergeladen: true,
));
} catch (_) {}
}
}
await _ladeStatus();
widget.onSongsChanged(); // Musik-Tab aktualisieren
if (mounted) {
setState(() {
_ladt = false;
_aktuellerDownload = '';
_status = '${_downloadGesamt} Songs heruntergeladen';
});
MeloLogger().aktion('cloud_download', {'count': _downloadGesamt});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: MeloTheme.schwarz,
appBar: AppBar(
backgroundColor: MeloTheme.dunkel1,
title: const Row(children: [
Text('☁️', style: TextStyle(fontSize: 20)),
SizedBox(width: 8),
Text('Cloud Sync', style: TextStyle(color: Colors.white, fontSize: 18)),
]),
actions: [
IconButton(
icon: const Icon(Icons.refresh, color: Colors.grey, size: 20),
onPressed: _ladeStatus,
),
],
),
body: Padding(
padding: const EdgeInsets.all(20),
child: Column(
children: [
// Status-Karte
Container(
width: double.infinity,
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: MeloTheme.dunkel1,
borderRadius: BorderRadius.circular(12),
border: Border.all(color: MeloTheme.dunkel2),
),
child: Row(
children: [
const Icon(Icons.storage, color: MeloTheme.rot, size: 28),
const SizedBox(width: 12),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('$_serverCount Songs auf Server',
style: const TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.w600)),
Text(_status ?? 'Lädt...',
style: const TextStyle(color: Colors.grey, fontSize: 12)),
],
),
],
),
),
const SizedBox(height: 16),
// Upload / Download
Row(
children: [
Expanded(child: _btn(Icons.upload, 'Upload', _upload)),
const SizedBox(width: 12),
Expanded(child: _btn(Icons.download, 'Download', _download)),
],
),
// Download-Fortschritt
if (_ladt && _aktuellerDownload.isNotEmpty) ...[
const SizedBox(height: 12),
LinearProgressIndicator(
value: _downloadGesamt > 0 ? _downloadFortschritt / _downloadGesamt : null,
backgroundColor: MeloTheme.dunkel2,
valueColor: const AlwaysStoppedAnimation(MeloTheme.rot),
),
const SizedBox(height: 6),
Text(
'$_downloadFortschritt/$_downloadGesamt: $_aktuellerDownload',
style: const TextStyle(color: Colors.grey, fontSize: 12),
maxLines: 2, overflow: TextOverflow.ellipsis,
),
],
if (_status != null && !_ladt)
Padding(
padding: const EdgeInsets.only(top: 8),
child: Text(_status!, style: const TextStyle(color: Colors.grey, fontSize: 13)),
),
const SizedBox(height: 12),
// Sync-Einstellungen
const Divider(color: MeloTheme.dunkel2),
const Align(
alignment: Alignment.centerLeft,
child: Text('⚙ Sync-Einstellungen', style: TextStyle(color: Colors.grey, fontSize: 11)),
),
SwitchListTile(
dense: true,
title: const Text('Auto-Sync', style: TextStyle(color: Colors.white, fontSize: 13)),
value: _autoSync,
activeColor: MeloTheme.rot,
onChanged: (v) async {
setState(() => _autoSync = v);
(await SharedPreferences.getInstance()).setBool('cloud_auto', v);
},
),
Row(
children: ['Manuell', 'Alle 3h', 'Alle 6h', 'Alle 12h'].asMap().entries.map((e) {
final vals = [0, 3, 6, 12];
return Expanded(
child: ChoiceChip(
label: Text(e.value, style: TextStyle(fontSize: 10, color: _syncIntervall == vals[e.key] ? Colors.white : Colors.grey)),
selected: _syncIntervall == vals[e.key],
selectedColor: MeloTheme.rot,
backgroundColor: MeloTheme.dunkel2,
onSelected: (v) async {
setState(() => _syncIntervall = vals[e.key]);
(await SharedPreferences.getInstance()).setInt('cloud_interval', vals[e.key]);
},
),
);
}).toList(),
),
],
),
),
);
}
Widget _btn(IconData icon, String label, VoidCallback onTap) {
return ElevatedButton.icon(
style: ElevatedButton.styleFrom(
backgroundColor: MeloTheme.dunkel1,
padding: const EdgeInsets.symmetric(vertical: 14),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
side: const BorderSide(color: MeloTheme.dunkel2),
),
),
onPressed: _ladt ? null : onTap,
icon: Icon(icon, size: 18, color: MeloTheme.rot),
label: Text(label, style: const TextStyle(color: Colors.white, fontSize: 14)),
);
}
}
+191 -61
View File
@@ -1,9 +1,12 @@
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:just_audio/just_audio.dart';
import '../services/download_service.dart';
import '../services/cloud_service.dart';
import '../utils/farb_theme.dart';
import '../services/melo_logger.dart';
import '../widgets/melo_loader.dart';
class DownloadScreen extends StatefulWidget {
final DownloadService downloader;
@@ -19,18 +22,76 @@ class DownloadScreen extends StatefulWidget {
State<DownloadScreen> createState() => _DownloadScreenState();
}
class _DownloadScreenState extends State<DownloadScreen> {
class _DownloadScreenState extends State<DownloadScreen> with WidgetsBindingObserver {
final _urlController = TextEditingController();
final _cloud = CloudService();
final _previewPlayer = AudioPlayer();
bool _ladt = false;
List<Map<String, dynamic>> _globalSongs = [];
String? _previewSid;
String? _fehler;
String? _erfolg;
String _speicherOrt = 'App-intern';
String _speicherOrt = 'App-intern (Music/)';
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
_previewPlayer.dispose();
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.paused || state == AppLifecycleState.inactive) {
_stopPreview();
}
}
Future<void> _ladeGlobalListe() async {
final songs = await _cloud.globalList();
if (mounted) setState(() => _globalSongs = songs.cast<Map<String, dynamic>>());
}
Future<void> _addFromRegistry(String sid) async {
final ok = await _cloud.download(sid, '/tmp/melo_reg_$sid.mp3');
if (ok && mounted) {
setState(() => _erfolg = 'Song hinzugefügt!');
widget.onSongsChanged();
await _ladeGlobalListe();
}
}
Future<void> _startPreview(String sid) async {
if (_previewSid == sid && _previewPlayer.playing) {
await _stopPreview();
return;
}
_previewSid = sid;
try {
final url = 'http://159.195.51.99:8993/api/cloud/stream/$sid';
await _previewPlayer.setUrl(url);
await _previewPlayer.seek(const Duration(seconds: 11));
await _previewPlayer.play();
Future.delayed(const Duration(seconds: 10), () {
if (_previewSid == sid) _stopPreview();
});
} catch (e) {
MeloLogger().fehler('preview', e);
}
}
Future<void> _stopPreview() async {
_previewSid = null;
await _previewPlayer.stop();
}
bool _speichertInDownloads = false;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
_ladeSpeicherPfad();
_ladeGlobalListe();
}
Future<void> _ladeSpeicherPfad() async {
@@ -63,6 +124,9 @@ class _DownloadScreenState extends State<DownloadScreen> {
const Divider(color: MeloTheme.dunkel2),
_optionTile(ctx, '⬇ Downloads/Melo', 'downloads',
icon: Icons.download),
const Divider(color: MeloTheme.dunkel2),
_optionTile(ctx, '💾 SD-Karte / Extern', 'extern',
icon: Icons.sd_storage),
],
),
),
@@ -82,6 +146,19 @@ class _DownloadScreenState extends State<DownloadScreen> {
_speicherOrt = '⬇ Downloads/Melo';
});
}
} else if (auswahl == 'extern') {
final dirs = await getExternalStorageDirectories();
if (dirs != null && dirs.isNotEmpty) {
final pfad = '${dirs.first.path}/Melo';
await prefs.setBool('download_in_downloads', false);
widget.downloader.setzeSpeicherPfad(pfad);
setState(() {
_speichertInDownloads = false;
_speicherOrt = '💾 ${dirs.first.path.split('/').last}/Melo';
});
} else {
if (mounted) setState(() => _fehler = 'Kein externer Speicher gefunden');
}
} else {
await prefs.setBool('download_in_downloads', false);
widget.downloader.setzeSpeicherPfad('');
@@ -139,7 +216,7 @@ class _DownloadScreenState extends State<DownloadScreen> {
title: const Row(children: [
Icon(Icons.download, color: MeloTheme.rot, size: 20),
SizedBox(width: 8),
Text('Downloads', style: TextStyle(color: Colors.white, fontSize: 18)),
Text('Lied +', style: TextStyle(color: Colors.white, fontSize: 18)),
]),
actions: [
if (_erfolg != null || _fehler != null)
@@ -153,6 +230,67 @@ class _DownloadScreenState extends State<DownloadScreen> {
padding: const EdgeInsets.all(20),
child: Column(
children: [
// ─── Globale Registry (Lied +) ───
if (_globalSongs.isNotEmpty) ...[
Row(children: [
const Icon(Icons.public, color: MeloTheme.rot, size: 16),
const SizedBox(width: 6),
Text('Globale Songs (${_globalSongs.length})',
style: const TextStyle(color: Colors.white70, fontSize: 13, fontWeight: FontWeight.w600)),
const Spacer(),
GestureDetector(
onTap: _ladeGlobalListe,
child: const Icon(Icons.refresh, color: Colors.grey, size: 16),
),
]),
const SizedBox(height: 8),
SizedBox(
height: 100,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: _globalSongs.length,
itemBuilder: (_, i) {
final s = _globalSongs[i];
final sid = s['id']?.toString() ?? '';
final title = s['title']?.toString() ?? '?';
final isPreviewing = _previewSid == sid;
return Container(
width: 140,
margin: const EdgeInsets.only(right: 8),
decoration: BoxDecoration(
color: isPreviewing ? const Color(0xFF2A0000) : MeloTheme.dunkel1,
borderRadius: BorderRadius.circular(10),
border: Border.all(color: isPreviewing ? MeloTheme.rot : MeloTheme.dunkel2),
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(title, style: TextStyle(fontSize: 11, color: Colors.white, fontWeight: FontWeight.w500),
maxLines: 2, overflow: TextOverflow.ellipsis, textAlign: TextAlign.center),
const SizedBox(height: 4),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
GestureDetector(
onTap: () => _startPreview(sid),
child: Icon(isPreviewing ? Icons.stop : Icons.play_arrow,
color: isPreviewing ? Colors.white : MeloTheme.rot, size: 20),
),
const SizedBox(width: 10),
GestureDetector(
onTap: () => _addFromRegistry(sid),
child: const Icon(Icons.add_circle_outline, color: Colors.grey, size: 18),
),
],
),
],
),
);
},
),
),
const Divider(color: MeloTheme.dunkel2),
],
// ─── Zielordner ───
GestureDetector(
onTap: _ladt ? null : _ordnerDialog,
@@ -199,59 +337,59 @@ class _DownloadScreenState extends State<DownloadScreen> {
),
const SizedBox(height: 12),
// ─── Download- & Abbruch-Button ───
Row(
children: [
Expanded(
flex: _ladt ? 3 : 1,
child: SizedBox(
height: 48,
child: ElevatedButton.icon(
onPressed: _ladt ? null : _starteDownload,
icon: _ladt
? const SizedBox(width: 20, height: 20,
child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white))
: const Icon(Icons.download, size: 20),
label: Text(_ladt ? 'Lade herunter...' : '⬇ Download'),
style: ElevatedButton.styleFrom(
backgroundColor: MeloTheme.rot,
foregroundColor: Colors.white,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
),
),
// ─── Animierte Ladeanzeige (während Download) ───
if (_ladt) ...[
MeloLoader(
titel: widget.downloader.aktuellerTitel ?? 'Lade herunter...',
),
const SizedBox(height: 16),
],
// ─── Download-Button ───
SizedBox(
width: double.infinity,
height: 48,
child: ElevatedButton.icon(
onPressed: _ladt ? null : _starteDownload,
icon: _ladt
? const SizedBox(width: 20, height: 20,
child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white))
: const Icon(Icons.download, size: 20),
label: Text(_ladt ? 'Lädt...' : '⬇ Download'),
style: ElevatedButton.styleFrom(
backgroundColor: MeloTheme.rot,
foregroundColor: Colors.white,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
),
),
),
if (_ladt) ...[
const SizedBox(height: 8),
SizedBox(
width: double.infinity,
height: 40,
child: ElevatedButton.icon(
onPressed: _abbrechen,
icon: const Icon(Icons.cancel, size: 18),
label: const Text('Abbrechen'),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.red.shade800,
foregroundColor: Colors.white,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
),
),
if (_ladt) ...[
const SizedBox(width: 8),
Expanded(
flex: 1,
child: SizedBox(
height: 48,
child: ElevatedButton.icon(
onPressed: _abbrechen,
icon: const Icon(Icons.cancel, size: 20),
label: const Text('Stop'),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.red.shade800,
foregroundColor: Colors.white,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
),
),
),
),
],
],
),
),
],
const SizedBox(height: 16),
// ─── Live-Status via ListenableBuilder ───
// ─── Fortschritt ───
if (_ladt)
ListenableBuilder(
listenable: widget.downloader,
builder: (context, _) {
final status = widget.downloader.aktuellerTitel;
final fortschritt = widget.downloader.fortschritt;
if (fortschritt <= 0) return const SizedBox.shrink();
return Container(
width: double.infinity,
padding: const EdgeInsets.all(12),
@@ -260,21 +398,13 @@ class _DownloadScreenState extends State<DownloadScreen> {
borderRadius: BorderRadius.circular(12),
),
child: Column(children: [
if (status != null) ...[
Text(status,
style: const TextStyle(color: Colors.white70, fontSize: 13),
textAlign: TextAlign.center),
],
if (fortschritt > 0) ...[
const SizedBox(height: 8),
LinearProgressIndicator(
value: fortschritt,
color: MeloTheme.rot,
backgroundColor: MeloTheme.dunkel2),
const SizedBox(height: 4),
Text('${(fortschritt * 100).toStringAsFixed(0)}%',
style: const TextStyle(color: Colors.grey, fontSize: 11)),
],
LinearProgressIndicator(
value: fortschritt,
color: MeloTheme.rot,
backgroundColor: MeloTheme.dunkel2),
const SizedBox(height: 4),
Text('${(fortschritt * 100).toStringAsFixed(0)}%',
style: const TextStyle(color: Colors.grey, fontSize: 11)),
]),
);
},
+373 -62
View File
@@ -1,5 +1,7 @@
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import '../database/db_helper.dart';
import '../viewmodels/melo_home_viewmodel.dart';
import '../models/song.dart';
import '../models/playlist.dart';
@@ -12,6 +14,12 @@ import '../widgets/song_tile.dart';
import '../widgets/navidrome_browser.dart';
import '../widgets/playlist_sheet.dart';
import 'download_screen.dart';
import 'cloud_screen.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:permission_handler/permission_handler.dart';
import '../widgets/cloud_einstellungen.dart';
import '../services/cloud_service.dart';
import '../config/app_config.dart';
class MeloHome extends StatefulWidget {
const MeloHome({super.key});
@@ -22,14 +30,142 @@ class MeloHome extends StatefulWidget {
class _MeloHomeState extends State<MeloHome> {
final MeloHomeViewModel _vm = MeloHomeViewModel();
final CloudService _cloud = CloudService();
int _aktiverTab = 0;
String _nutzer = 'Baka'; // Aktueller Nutzer
@override
void initState() {
super.initState();
_ladeNutzer();
_vm.addListener(() => setState(() {}));
_vm.ladeSongs();
}
Future<void> _ladeNutzer() async {
final p = await SharedPreferences.getInstance();
final n = p.getString('melo_nutzer') ?? '';
if (n.isNotEmpty && mounted) {
setState(() => _nutzer = n);
_vm.setzeNutzer(n);
}
}
void _zeigeProfil() {
showDialog(
context: context,
builder: (ctx) => AlertDialog(
backgroundColor: MeloTheme.dunkel1,
title: Row(children: [
const Icon(Icons.person, color: MeloTheme.rot, size: 22),
const SizedBox(width: 8),
Text(_nutzer, style: const TextStyle(color: Colors.white, fontSize: 17)),
]),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
_profilZeile(Icons.music_note, 'Lieder auf Gerät', '${_vm.songs.length}'),
_profilZeile(Icons.cloud, 'Cloud-Server', '${_cloud.status().then((s) => s?['total'] ?? 0)}'),
const Divider(color: MeloTheme.dunkel2),
ListTile(
leading: const Icon(Icons.swap_horiz, color: Colors.grey, size: 18),
title: const Text('Nutzer wechseln', style: TextStyle(color: Colors.white, fontSize: 13)),
onTap: () {
Navigator.pop(ctx);
_nutzerWechseln();
},
),
ListTile(
leading: const Icon(Icons.logout, color: Colors.red, size: 18),
title: const Text('Abmelden', style: TextStyle(color: Colors.red, fontSize: 13)),
onTap: () async {
final p = await SharedPreferences.getInstance();
await p.remove('melo_nutzer');
if (ctx.mounted) Navigator.pop(ctx);
setState(() => _nutzer = '');
},
),
],
),
),
);
}
Widget _profilZeile(IconData icon, String label, String wert) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 6),
child: Row(children: [
Icon(icon, color: MeloTheme.rot, size: 16),
const SizedBox(width: 8),
Expanded(child: Text(label, style: const TextStyle(color: Colors.grey, fontSize: 12))),
Text(wert, style: const TextStyle(color: Colors.white, fontSize: 14, fontWeight: FontWeight.w600)),
]),
);
}
void _nutzerWechseln() {
final ctrl = TextEditingController(text: _nutzer);
final pwCtrl = TextEditingController();
showDialog(
context: context,
builder: (ctx) => AlertDialog(
backgroundColor: MeloTheme.dunkel1,
title: const Text('👤 Anmelden', style: TextStyle(color: Colors.white, fontSize: 15)),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(
controller: ctrl,
autofocus: true,
style: const TextStyle(color: Colors.white),
decoration: const InputDecoration(
hintText: 'Nutzername...',
hintStyle: TextStyle(color: Colors.grey),
border: OutlineInputBorder(),
),
),
const SizedBox(height: 8),
TextField(
controller: pwCtrl,
obscureText: true,
style: const TextStyle(color: Colors.white),
decoration: const InputDecoration(
hintText: 'Passwort...',
hintStyle: TextStyle(color: Colors.grey),
border: OutlineInputBorder(),
),
),
],
),
actions: [
TextButton(onPressed: () => Navigator.pop(ctx), child: const Text('Abbrechen')),
TextButton(
onPressed: () async {
final name = ctrl.text.trim();
final pass = pwCtrl.text;
if (name.isEmpty || pass.isEmpty) return;
final ok = await _vm.cloud.login(name, pass);
if (!ctx.mounted) return;
Navigator.pop(ctx);
if (ok) {
final p = await SharedPreferences.getInstance();
await p.setString('melo_nutzer', name);
if (mounted) setState(() => _nutzer = name);
_vm.setzeNutzer(name);
} else {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('❌ Login fehlgeschlagen Name oder Passwort falsch')));
}
}
},
child: const Text('OK', style: TextStyle(color: MeloTheme.rot)),
),
],
),
);
}
@override
void dispose() {
_vm.dispose();
@@ -89,22 +225,28 @@ class _MeloHomeState extends State<MeloHome> {
final suchModus = teile.length > 1 ? teile[1] : 'Alle';
if (suchtext.isEmpty) return;
// Tag-Namen die zum Suchtext passen
final matchingTags = _vm.tags
.where((t) => t['name'] != 'Alle' && t['name']!.toLowerCase().contains(suchtext))
.map((t) => t['name']!)
.toSet();
final gefiltert = _vm.songs.where((s) {
if (suchModus == 'Titel') return s.titel.toLowerCase().contains(suchtext);
if (suchModus == 'Künstler') return s.kuenstler.toLowerCase().contains(suchtext);
if (suchModus == 'Tag') {
return _vm.tags.any((t) =>
t['name'] != 'Alle' &&
t['name']!.toLowerCase().contains(suchtext) &&
'${s.titel} ${s.kuenstler}'.toLowerCase().contains(t['name']!.toLowerCase()));
return s.tagIds != null && matchingTags.any((name) {
final tag = _vm.tagsMap[name];
return tag != null && s.tagIds!.contains(tag.id);
});
}
// Alle
if (s.titel.toLowerCase().contains(suchtext)) return true;
if (s.kuenstler.toLowerCase().contains(suchtext)) return true;
return _vm.tags.any((t) =>
t['name'] != 'Alle' &&
t['name']!.toLowerCase().contains(suchtext) &&
'${s.titel} ${s.kuenstler}'.toLowerCase().contains(t['name']!.toLowerCase()));
return s.tagIds != null && matchingTags.any((name) {
final tag = _vm.tagsMap[name];
return tag != null && s.tagIds!.contains(tag.id);
});
}).toList();
if (!mounted) return;
showDialog(
@@ -159,30 +301,79 @@ class _MeloHomeState extends State<MeloHome> {
}
void _zeigeServerBrowser() {
if (_vm.navidrome.istVerbunden) {
// Abmelden
_vm.navidrome.setCredentials('', '', '');
_vm.navidromeAlben.clear();
setState(() {});
return;
}
// Verbinden: einfacher Login-Dialog
final urlCtrl = TextEditingController(text: AppConfig.navidromeUrl);
final userCtrl = TextEditingController();
final passCtrl = TextEditingController();
showDialog(
context: context,
builder: (ctx) => AlertDialog(
backgroundColor: MeloTheme.dunkel1,
title: const Text('🌐 Navidrome verbinden', style: TextStyle(color: Colors.white, fontSize: 15)),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(controller: urlCtrl, style: const TextStyle(color: Colors.white),
decoration: const InputDecoration(labelText: 'Server', border: OutlineInputBorder(),
labelStyle: TextStyle(color: Colors.grey))),
const SizedBox(height: 8),
TextField(controller: userCtrl, style: const TextStyle(color: Colors.white),
decoration: const InputDecoration(labelText: 'Benutzer', border: OutlineInputBorder(),
labelStyle: TextStyle(color: Colors.grey))),
const SizedBox(height: 8),
TextField(controller: passCtrl, obscureText: true, style: const TextStyle(color: Colors.white),
decoration: const InputDecoration(labelText: 'Passwort', border: OutlineInputBorder(),
labelStyle: TextStyle(color: Colors.grey))),
],
),
actions: [
TextButton(onPressed: () => Navigator.pop(ctx), child: const Text('Abbrechen')),
TextButton(
onPressed: () async {
_vm.verbindeNavidrome(urlCtrl.text, userCtrl.text, passCtrl.text);
await _vm.ladeNavidromeAlben();
await _vm.navidrome.speichereZugangsdaten(urlCtrl.text, userCtrl.text, passCtrl.text);
if (ctx.mounted) Navigator.pop(ctx);
setState(() {});
},
child: const Text('Verbinden', style: TextStyle(color: MeloTheme.rot)),
),
],
),
);
}
void _zeigePlaylistSheet() {
showModalBottomSheet(
context: context,
backgroundColor: MeloTheme.schwarz,
isScrollControlled: true,
builder: (_) => SizedBox(
height: MediaQuery.of(context).size.height * 0.7,
child: Column(
children: [
Container(
margin: const EdgeInsets.symmetric(vertical: 8),
width: 40, height: 4,
decoration: BoxDecoration(
color: MeloTheme.dunkel2,
borderRadius: BorderRadius.circular(2),
),
),
Expanded(child: NavidromeBrowser(vm: _vm)),
],
),
child: PlaylistSheet(vm: _vm),
),
);
}
void _zeigePlaylistSheet() {
void _songLoeschen(Song song) async {
if (song.id != null) {
final db = DbHelper();
await db.loeschSong(song.id!);
if (song.dateiPfad.isNotEmpty) {
try { await File(song.dateiPfad).delete(); } catch (_) {}
}
_vm.ladeSongs();
}
}
void _zeigePlaylists() {
showModalBottomSheet(
context: context,
backgroundColor: MeloTheme.schwarz,
@@ -252,8 +443,8 @@ class _MeloHomeState extends State<MeloHome> {
);
}
final gesamtMB = _vm.songs.isEmpty ? '0'
: (_vm.songs.fold(0, (int s, Song song) => s + song.groesseBytes) / 1048576).toStringAsFixed(0);
final gesamtMB = _vm.songs.isEmpty ? '0.0'
: (_vm.songs.fold(0, (int s, Song song) => s + song.groesseBytes) / 1048576).toStringAsFixed(1);
final gesamtMin = _vm.songs.isEmpty ? 0
: (_vm.songs.fold(0, (int s, Song song) => s + song.dauerSekunden) / 60).round();
@@ -265,29 +456,13 @@ class _MeloHomeState extends State<MeloHome> {
downloader: _vm.downloader,
onSongsChanged: _vm.ladeSongs,
)
: _aktiverTab == 3
? CloudScreen(cloud: _cloud, onSongsChanged: _vm.ladeSongs)
: Column(
children: [
MeloHeader(onDownload: _zeigeDownloadDialog, onSearch: _zeigeSuche, onServer: _zeigeServerBrowser),
// ─── EIN/AUS: RecentWidget (Zuletzt gehört) ───
// Entferne die Kommentarzeichen um RecentWidget zu aktivieren:
// RecentWidget(songs: _vm.letzteSongs, onPlay: _vm.spieleSong),
StatistikCard(
anzahlSongs: _vm.songs.length,
gesamtMB: gesamtMB,
gesamtMin: gesamtMin,
anzahlFavoriten: _vm.favoritenIds.length,
),
// ─── EIN/AUS: Hidden Message "Seit 2008" ───
// Entferne die Kommentarzeichen um die Botschaft zu aktivieren:
MeloHeader(onDownload: _zeigeDownloadDialog, onSearch: _zeigeSuche, onServer: _zeigeProfil, onSettings: _zeigeEinstellungen),
if (_vm.zeigeBotschaft) _botschaftBanner(),
TagLeiste(
tags: _vm.tags,
aktiveTags: _vm.aktiveTags,
onTagToggled: _vm.toggleTag,
),
// ─── EIN/AUS: TagStatsWidget (Tag-Counts) ───
// Entferne die Kommentarzeichen um TagStatsWidget zu aktivieren:
// TagStatsWidget(tagCounts: _vm.tagCounts),
_tagBereich(),
Expanded(child: _songListe()),
const MiniPlayer(),
const SizedBox(height: 8),
@@ -336,7 +511,9 @@ class _MeloHomeState extends State<MeloHome> {
),
),
Expanded(
child: ListView.builder(
child: songs.isEmpty
? _emptyStateWidget()
: ListView.builder(
padding: const EdgeInsets.fromLTRB(20, 4, 20, 4),
itemCount: songs.length,
itemBuilder: (_, i) => SongTile(
@@ -346,6 +523,7 @@ class _MeloHomeState extends State<MeloHome> {
onPlay: _vm.spieleSong,
onMetadataChanged: _vm.ladeSongs,
onAddToPlaylist: _zeigeAddToPlaylist,
onDelete: _songLoeschen,
),
),
),
@@ -353,6 +531,87 @@ class _MeloHomeState extends State<MeloHome> {
);
}
void _zeigeEinstellungen() {
showDialog(
context: context,
builder: (ctx) => AlertDialog(
backgroundColor: MeloTheme.dunkel1,
title: const Text('⚙ Einstellungen', style: TextStyle(color: Colors.white, fontSize: 16)),
content: Column(
mainAxisSize: MainAxisSize.min,
children: [
// Stats
Container(
padding: const EdgeInsets.all(12),
margin: const EdgeInsets.only(bottom: 12),
decoration: BoxDecoration(color: MeloTheme.dunkel2, borderRadius: BorderRadius.circular(10)),
child: Row(mainAxisAlignment: MainAxisAlignment.spaceAround, children: [
_statWert('${_vm.songs.length}', 'Songs'),
_statWert('${(_vm.songs.fold(0, (int s, Song song) => s + song.groesseBytes) / 1048576).toStringAsFixed(1)} MB', 'Größe'),
_statWert('${(_vm.songs.fold(0, (int s, Song song) => s + song.dauerSekunden) / 60).round()} Min', 'Dauer'),
_statWert('${_vm.favoritenIds.length}', '❤️'),
]),
),
ListTile(
leading: const Icon(Icons.favorite, color: MeloTheme.rot),
title: const Text('Favoriten', style: TextStyle(color: Colors.white)),
subtitle: const Text('Deine Lieblingssongs', style: TextStyle(color: Colors.grey, fontSize: 12)),
onTap: () {
Navigator.pop(ctx);
_vm.aktiveTags = {'★ Favoriten'};
},
),
ListTile(
leading: const Icon(Icons.cloud, color: MeloTheme.rot),
title: const Text('Cloud Sync', style: TextStyle(color: Colors.white)),
subtitle: const Text('Auto-Sync & Einstellungen', style: TextStyle(color: Colors.grey, fontSize: 12)),
onTap: () {
Navigator.pop(ctx);
showDialog(
context: context,
builder: (_) => const CloudEinstellungen(),
);
},
),
ListTile(
leading: const Icon(Icons.dns, color: MeloTheme.rot),
title: const Text('Server verbinden', style: TextStyle(color: Colors.white)),
subtitle: const Text('Navidrome / Musik-Server', style: TextStyle(color: Colors.grey, fontSize: 12)),
onTap: () { Navigator.pop(ctx); _zeigeServerBrowser(); },
),
ListTile(
leading: const Icon(Icons.person, color: MeloTheme.rot),
title: const Text('Profil', style: TextStyle(color: Colors.white)),
subtitle: Text(_nutzer.isEmpty ? 'Nicht angemeldet' : _nutzer, style: const TextStyle(color: Colors.grey, fontSize: 12)),
onTap: () { Navigator.pop(ctx); _zeigeProfil(); },
),
SwitchListTile(
title: const Text('Diagnosedaten senden', style: TextStyle(color: Colors.white, fontSize: 13)),
subtitle: const Text('Absturz-Logs & Nutzungsdaten', style: TextStyle(color: Colors.grey, fontSize: 11)),
value: AppConfig.sendeDiagnosedaten,
activeColor: MeloTheme.rot,
onChanged: (v) {
AppConfig.sendeDiagnosedaten = v;
},
),
if (Platform.isAndroid)
ListTile(
leading: const Icon(Icons.folder_open, color: MeloTheme.rot),
title: const Text('Voller Speicherzugriff', style: TextStyle(color: Colors.white)),
subtitle: const Text('Zum Speichern in Downloads/Music', style: TextStyle(color: Colors.grey, fontSize: 12)),
onTap: () async {
final status = await Permission.manageExternalStorage.request();
if (status.isGranted) {
await SharedPreferences.getInstance().then((p) => p.setBool('manage_storage', true));
}
},
),
],
),
),
);
}
Widget _bottomNav() {
return Container(
decoration: const BoxDecoration(
@@ -363,18 +622,21 @@ class _MeloHomeState extends State<MeloHome> {
backgroundColor: MeloTheme.schwarz,
selectedItemColor: MeloTheme.rot,
unselectedItemColor: MeloTheme.textSekundaer,
currentIndex: _aktiverTab,
currentIndex: _aktiverTab.clamp(0, 3),
onTap: (i) {
setState(() => _aktiverTab = i);
if (i == 2) _zeigePlaylistSheet(); // Tags-Tab → Playlists
if (i == 3) _zeigePlaylistSheet(); // Favoriten-Tab → Playlists
if (i == 0 && _vm.aktiveTags.contains('★ Favoriten')) {
_vm.aktiveTags.clear();
} else if (i == 2) {
// Playlisten öffnen
_zeigePlaylists();
}
},
items: const [
BottomNavigationBarItem(icon: Icon(Icons.music_note, size: 22), label: 'Musik'),
BottomNavigationBarItem(icon: Icon(Icons.download, size: 22), label: 'Downloads'),
BottomNavigationBarItem(icon: Icon(Icons.label, size: 22), label: 'Tags'),
BottomNavigationBarItem(icon: Icon(Icons.favorite, size: 22), label: 'Favoriten'),
BottomNavigationBarItem(icon: Icon(Icons.settings, size: 22), label: 'Einstellungen'),
BottomNavigationBarItem(icon: Icon(Icons.add_circle, size: 22), label: 'Lied +'),
BottomNavigationBarItem(icon: Icon(Icons.queue_music, size: 22), label: 'Playlisten'),
BottomNavigationBarItem(icon: Icon(Icons.cloud, size: 22), label: 'Cloud'),
],
),
);
@@ -411,15 +673,8 @@ class _MeloHomeState extends State<MeloHome> {
const Text('💌', style: TextStyle(fontSize: 20)),
const SizedBox(width: 10),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: const [
Text('Seit 2008',
style: TextStyle(fontSize: 14, fontWeight: FontWeight.w700, color: Colors.white)),
Text('Danke, dass du immer da bist ♥',
style: TextStyle(fontSize: 11, color: MeloTheme.textSekundaer)),
],
),
child: Text(_vm.nutzerBotschaft ?? '🎵 Danke fürs Zuhören!',
style: const TextStyle(fontSize: 13, fontWeight: FontWeight.w600, color: Colors.white)),
),
GestureDetector(
onTap: _vm.botschaftAusblenden,
@@ -430,4 +685,60 @@ class _MeloHomeState extends State<MeloHome> {
),
);
}
/// Leerer Zustand wenn keine Songs in der Bibliothek sind
Widget _emptyStateWidget() {
return Center(
child: Padding(
padding: const EdgeInsets.all(32),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.library_music_outlined, size: 56, color: MeloTheme.rot.withValues(alpha: 0.5)),
const SizedBox(height: 16),
const Text('Noch keine Songs in Melo',
style: TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.w600)),
const SizedBox(height: 8),
const Text('Füge Songs über "Lied +" hinzu, verbinde deinen Server oder starte einen lokalen Scan.',
textAlign: TextAlign.center,
style: TextStyle(color: MeloTheme.textSekundaer, fontSize: 12, height: 1.4)),
const SizedBox(height: 20),
ElevatedButton.icon(
onPressed: _scanMusik,
icon: const Icon(Icons.search, size: 16),
label: const Text('Jetzt Musik scannen'),
style: ElevatedButton.styleFrom(
backgroundColor: MeloTheme.dunkel1,
foregroundColor: Colors.white,
side: const BorderSide(color: MeloTheme.dunkel2),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
),
),
],
),
),
);
}
Widget _tagBereich() {
return AnimatedSize(
duration: const Duration(milliseconds: 200),
child: _tagsOffen
? TagLeiste(
tags: _vm.tags,
aktiveTags: _vm.aktiveTags,
onTagToggled: _vm.toggleTag,
)
: const SizedBox.shrink(),
);
}
Widget _statWert(String wert, String label) {
return Column(children: [
Text(wert, style: const TextStyle(color: Colors.white, fontSize: 15, fontWeight: FontWeight.w700)),
Text(label, style: const TextStyle(color: Colors.grey, fontSize: 10)),
]);
}
bool _tagsOffen = false;
}