team-2/CHALLENGE_2/sleepysound/lib/models/spotify_track.dart
2025-08-02 04:16:15 +02:00

122 lines
2.8 KiB
Dart

import 'package:json_annotation/json_annotation.dart';
part 'spotify_track.g.dart';
@JsonSerializable()
class SpotifyTrack {
final String id;
final String name;
final List<SpotifyArtist> artists;
final SpotifyAlbum album;
@JsonKey(name: 'duration_ms')
final int durationMs;
@JsonKey(name: 'external_urls')
final Map<String, String> externalUrls;
@JsonKey(name: 'preview_url')
final String? previewUrl;
SpotifyTrack({
required this.id,
required this.name,
required this.artists,
required this.album,
required this.durationMs,
required this.externalUrls,
this.previewUrl,
});
factory SpotifyTrack.fromJson(Map<String, dynamic> json) =>
_$SpotifyTrackFromJson(json);
Map<String, dynamic> toJson() => _$SpotifyTrackToJson(this);
String get artistNames => artists.map((artist) => artist.name).join(', ');
String get duration {
final minutes = (durationMs / 60000).floor();
final seconds = ((durationMs % 60000) / 1000).floor();
return '$minutes:${seconds.toString().padLeft(2, '0')}';
}
String get imageUrl => album.images.isNotEmpty ? album.images.first.url : '';
}
@JsonSerializable()
class SpotifyArtist {
final String id;
final String name;
SpotifyArtist({
required this.id,
required this.name,
});
factory SpotifyArtist.fromJson(Map<String, dynamic> json) =>
_$SpotifyArtistFromJson(json);
Map<String, dynamic> toJson() => _$SpotifyArtistToJson(this);
}
@JsonSerializable()
class SpotifyAlbum {
final String id;
final String name;
final List<SpotifyImage> images;
SpotifyAlbum({
required this.id,
required this.name,
required this.images,
});
factory SpotifyAlbum.fromJson(Map<String, dynamic> json) =>
_$SpotifyAlbumFromJson(json);
Map<String, dynamic> toJson() => _$SpotifyAlbumToJson(this);
}
@JsonSerializable()
class SpotifyImage {
final int height;
final int width;
final String url;
SpotifyImage({
required this.height,
required this.width,
required this.url,
});
factory SpotifyImage.fromJson(Map<String, dynamic> json) =>
_$SpotifyImageFromJson(json);
Map<String, dynamic> toJson() => _$SpotifyImageToJson(this);
}
@JsonSerializable()
class SpotifySearchResponse {
final SpotifyTracks tracks;
SpotifySearchResponse({required this.tracks});
factory SpotifySearchResponse.fromJson(Map<String, dynamic> json) =>
_$SpotifySearchResponseFromJson(json);
Map<String, dynamic> toJson() => _$SpotifySearchResponseToJson(this);
}
@JsonSerializable()
class SpotifyTracks {
final List<SpotifyTrack> items;
final int total;
SpotifyTracks({
required this.items,
required this.total,
});
factory SpotifyTracks.fromJson(Map<String, dynamic> json) =>
_$SpotifyTracksFromJson(json);
Map<String, dynamic> toJson() => _$SpotifyTracksToJson(this);
}