Suite travail sur playlist Spotify.
continuous-integration/drone/push Build is passing Details

messagerie_lucas_test
Félix MIELCAREK 2 years ago
parent 9275d363c4
commit d388f4d77e

@ -14,19 +14,23 @@ class Api {
//for web api //for web api
get redirectUri => 'https://daflmusic.000webhostapp.com/callback/'; get redirectUri => 'https://daflmusic.000webhostapp.com/callback/';
final _scopes = final _scopes =
'user-read-playback-state user-read-currently-playing user-read-recently-played'; 'user-read-playback-state user-read-currently-playing user-read-recently-played playlist-modify-public';
late String _state; late String _state;
dynamic _codeVerifier; dynamic _codeVerifier;
dynamic _codeChallenge; dynamic _codeChallenge;
late String _encodedLogs; late String _encodedLogs;
final _tokenType = 'Bearer '; final _tokenType = 'Bearer ';
late http.Response _response; //use _setResponse() as kind of a private setter late http.Response _response; //use _setResponse() as kind of a private setter
final _playlistName = "Dafl's discovery";
//final _playlistName = 'daflmusic';
//from web api //from web api
String? _code; String? _code;
int? _expiresIn; int? _expiresIn;
String? _refreshToken; String? _refreshToken;
String? _accessToken; //use _getToken() as kind of a private getter String? _accessToken; //use _getAccessToken() as kind of a private getter
String? _idUser; //use _getIdUser() as kind of a private getter
//other //other
final _client = http.Client(); final _client = http.Client();
@ -66,14 +70,17 @@ class Api {
} }
_generateCodeChallenge() { _generateCodeChallenge() {
return base64UrlEncode(sha256.convert(utf8.encode(_codeVerifier)).bytes); return base64Encode(sha256.convert(utf8.encode(_codeVerifier)).bytes)
.replaceAll('+', '-')
.replaceAll('/', '_')
.replaceAll('=', '');
} }
//session management //session management
requestUserAuthorization(Uri url) async { requestUserAuthorization(Uri url) async {
if (url.queryParameters['state'] != _state.toString()) { if (url.queryParameters['state'] != _state.toString()) {
throw ApiException(); throw ApiException('state');
} }
_code = url.queryParameters['code']; _code = url.queryParameters['code'];
await _requestAccessToken(); await _requestAccessToken();
@ -111,8 +118,9 @@ class Api {
} }
_setResponse(value) { _setResponse(value) {
if (value.statusCode != 200) { int sc = value.statusCode;
throw ApiException(); if (sc >= 300) {
throw ApiException(sc);
} }
_response = value; _response = value;
} }
@ -172,11 +180,15 @@ class Api {
decodedResponse['album']['images'][0]['url']); decodedResponse['album']['images'][0]['url']);
} }
addToPLaylist() { addToPLaylist(String id) async {
//if playlist DaflMusic doesn't exist var res = await _getPlaylist();
if (!res) {
await _createPlaylist();
}
//TODO : add to playlist
} }
getPlaylist() async { dynamic _getPlaylist() async {
var url = Uri.https('api.spotify.com', 'v1/me/playlists', {'limit': '50'}); var url = Uri.https('api.spotify.com', 'v1/me/playlists', {'limit': '50'});
var token = await _getAccessToken(); var token = await _getAccessToken();
_setResponse(await _client.get(url, headers: <String, String>{ _setResponse(await _client.get(url, headers: <String, String>{
@ -184,9 +196,51 @@ class Api {
'Content-Type': 'application/json' 'Content-Type': 'application/json'
})); }));
var decodedResponse = jsonDecode(utf8.decode(_response.bodyBytes)) as Map; var decodedResponse = jsonDecode(utf8.decode(_response.bodyBytes)) as Map;
dev.log(decodedResponse['items'].toString()); var daflplaylist = decodedResponse['items']
dev.log(decodedResponse['items'] .where((element) => element['name'] == _playlistName)
.where((element) => element['name'] == 'daflmusic') .toList();
.toString()); if (daflplaylist.length == 1) {
return daflplaylist[0]['uri'].substring(
17); //17 char because format is 'spotify:playlist:MYPLAYLISTID'
}
return false;
}
_createPlaylist() async {
var token = await _getAccessToken();
var id = await _getIdUser();
var url = Uri.https('api.spotify.com', 'v1/users/$id/playlists');
_setResponse(await _client.post(url,
headers: <String, String>{
'Accept': 'application/json',
'Authorization': '$_tokenType $token',
'Content-Type': 'application/json'
},
body: jsonEncode(<String, String>{
'name': _playlistName,
'description':
'Retrouvez toutes vos découvertes faites sur DaflMusic 🎵',
'public': 'true'
})));
var decodedResponse = jsonDecode(utf8.decode(_response.bodyBytes)) as Map;
_idUser = decodedResponse['id'];
}
Future<String> _getIdUser() async {
if (_idUser == null) {
await _getIdUserApi();
}
return _idUser!;
}
_getIdUserApi() async {
var url = Uri.https('api.spotify.com', 'v1/me');
var token = await _getAccessToken();
_setResponse(await _client.get(url, headers: <String, String>{
'Authorization': '$_tokenType $token',
'Content-Type': 'application/json'
}));
var decodedResponse = jsonDecode(utf8.decode(_response.bodyBytes)) as Map;
_idUser = decodedResponse['id'];
} }
} }

@ -27,7 +27,9 @@ class MyInAppBrowser extends InAppBrowser {
if (url!.origin + url.path == MyApp.api.redirectUri) { if (url!.origin + url.path == MyApp.api.redirectUri) {
try { try {
await MyApp.api.requestUserAuthorization(url); await MyApp.api.requestUserAuthorization(url);
await MyApp.api.getPlaylist(); //TODO : finir d'implémenter : addToPlaylist
//var id = await MyApp.api.getCurrentlyPlayingTrack();
//await MyApp.api.addToPLaylist(id);
} on ApiException { } on ApiException {
// TODO : add notification to show that an error occured // TODO : add notification to show that an error occured
} finally { } finally {

@ -1,7 +1,13 @@
import 'dart:developer' as dev; import 'dart:developer' as dev;
class ApiException implements Exception { class ApiException implements Exception {
ApiException() { final String mess = 'Api exception raised,';
dev.log('Api exception raised');
ApiException(dynamic code) {
if (code.runtimeType == String) {
dev.log('$mess state verification failed.');
} else {
dev.log('$mess status code : $code.');
}
} }
} }

@ -11,10 +11,6 @@ class User {
late String usernameDafl; late String usernameDafl;
late String passwDafl; late String passwDafl;
//attributes to link with API
late String usernameAPI;
late String passwAPI;
//attributes with Spotify API //attributes with Spotify API
late String _id; late String _id;
late Track track; late Track track;

Loading…
Cancel
Save