MusicPlayer/lib/api.dart

58 lines
1.3 KiB
Dart
Raw Normal View History

2022-03-23 18:38:58 +00:00
import 'package:dio/dio.dart';
import 'package:music_web_player/config.dart';
2022-03-24 13:43:28 +00:00
class MusicEntry implements Comparable<MusicEntry> {
2022-03-23 18:38:58 +00:00
final int id;
final String artist;
final String title;
const MusicEntry({
required this.id,
required this.artist,
required this.title,
});
2022-03-23 20:15:29 +00:00
String get coverCacheKey => "cover-$id";
2022-03-24 13:43:28 +00:00
String get fullName => "$artist - $title";
@override
String toString() => "MusicEntry($id, $artist, $title)";
@override
int compareTo(MusicEntry other) {
return fullName.compareTo(other.fullName);
}
2022-03-23 18:38:58 +00:00
}
2022-03-23 20:15:29 +00:00
typedef MusicsList = List<MusicEntry>;
2022-03-23 18:38:58 +00:00
class API {
/// Get the list of music
2022-03-23 20:15:29 +00:00
static Future<MusicsList> getList() async {
2022-03-23 18:38:58 +00:00
final response = await Dio().get(config.apiURL + "/list",
options: Options(headers: {"Token": config.apiToken}));
if (response.statusCode != 200) {
throw Exception("Request failed with status ${response.statusCode} !");
}
2022-03-24 13:43:28 +00:00
final MusicsList list = response.data
2022-03-23 18:38:58 +00:00
.map((r) =>
MusicEntry(id: r["id"], artist: r["artist"], title: r["title"]))
.toList()
.cast<MusicEntry>();
2022-03-24 13:43:28 +00:00
list.sort();
return list;
2022-03-23 18:38:58 +00:00
}
}
2022-03-23 20:15:29 +00:00
extension MusicEntryAPIExt on MusicEntry {
String get coverURL => "${config.apiURL}/cover/$id?token=${config.apiToken}";
2022-03-24 09:57:55 +00:00
String get musicURL =>
"${config.apiURL}/download/$id?token=${config.apiToken}";
2022-03-23 20:15:29 +00:00
}