diff --git a/src/FLAD/Model/Spot.tsx b/src/FLAD/Model/Spot.tsx index cc8fa6d..46a6f9d 100644 --- a/src/FLAD/Model/Spot.tsx +++ b/src/FLAD/Model/Spot.tsx @@ -1,9 +1,17 @@ +import Music from "./Music"; -class Spot { - private userId : string; - public music : Music; +export class Spot { + private _userId : string; + public _music : Music; constructor(userId : string, music : Music){ - this.userId = userId; - this.music = music; + this._userId = userId; + this._music = music; } + get userSpotifyId(): string { + return this._userId; + } + get idSpotify(): Music { + return this._music; + } + } \ No newline at end of file diff --git a/src/FLAD/Model/SpotifyToken.tsx b/src/FLAD/Model/SpotifyToken.tsx new file mode 100644 index 0000000..d208ef5 --- /dev/null +++ b/src/FLAD/Model/SpotifyToken.tsx @@ -0,0 +1,34 @@ +class TokenSpotify { + String _accessToken; + final String _refreshToken; + late DateTime _tokenEnd; + +// TokenSpotify(this._accessToken, this._refreshToken, int expiresIn) { +// _setTokenEnd(expiresIn); +// } + +// _setTokenEnd(int expiresIn) { +// _tokenEnd = DateTime.now().add(Duration(seconds: expiresIn)); +// } + +// Future getAccessToken() async { +// if (DateTime.now().isAfter(_tokenEnd)) { +// await _actualiseToken(); +// } +// return _accessToken; +// } + +// _actualiseToken() async { +// var urlToken = Uri.https('accounts.spotify.com', 'api/token', { +// 'grant_type': 'refresh_token', +// 'refresh_token': _refreshToken, +// 'client_id': ApiSpotifyIdentification.clientId +// }); +// setResponse(await http.post(urlToken, headers: { +// 'Content-Type': 'application/x-www-form-urlencoded' +// })); +// var decodedResponse = jsonDecode(utf8.decode(response.bodyBytes)) as Map; +// _accessToken = decodedResponse['access_token']; +// _setTokenEnd(decodedResponse['expires_in']); +// } +} \ No newline at end of file diff --git a/src/FLAD/Model/User.tsx b/src/FLAD/Model/User.tsx index 1e7f2bd..d8e6438 100644 --- a/src/FLAD/Model/User.tsx +++ b/src/FLAD/Model/User.tsx @@ -1,9 +1,42 @@ -class User { +export class User { //attributes from DAFL - private idFlad : any;; - private idSpotify : any; + private _idFlad : string; + private _idSpotify : string; + private _email : string; + private _createdAt : Date; + private _name : string; + public image : string = require('../assets/images/jul.png'); //constructors - constructor(){ - + constructor(idFlad : string, idSpotify : string, email : string, createdAt : Date, name : string, image : string){ + this._name = name; + this._idFlad = idFlad; + this._idSpotify = idSpotify; + this._createdAt = createdAt; + this._email = email; + this.image = image; } + + get idFlad(): string { + return this._idFlad; + } + get idSpotify(): string { + return this._idSpotify; + } + get email(): string { + return this._email; + } + get createAt(): Date { + return this._createdAt; + } + get name(): string { + return this._name; + } + + static empty() { + return new User('','','',new Date(),'',require('../assets/images/jul.png')); + } + + toString() { + return 'User : ' + this.idFlad + ', ' + this.name + ', ' + this.idSpotify; + } } \ No newline at end of file diff --git a/src/FLAD/Model/factory/MusicFactory.ts b/src/FLAD/Model/factory/MusicFactory.ts new file mode 100644 index 0000000..1e813c2 --- /dev/null +++ b/src/FLAD/Model/factory/MusicFactory.ts @@ -0,0 +1,12 @@ +import Music from "../Music"; + +export default class MusicFactory { + static mapFromSpotifyTrack(jsonMusic :any ): Music { + const music = new Music( + jsonMusic.id, + jsonMusic.name, + jsonMusic.album.images[0].url + ); + return music; + } + } \ No newline at end of file diff --git a/src/FLAD/Model/factory/UserFactory.tsx b/src/FLAD/Model/factory/UserFactory.tsx new file mode 100644 index 0000000..105b4b0 --- /dev/null +++ b/src/FLAD/Model/factory/UserFactory.tsx @@ -0,0 +1,12 @@ +import { User } from "../User"; + +export class UserFactory { + + public static JsonToModel( jsonUser :any ) : User{ + return new User(jsonUser.idFlad, jsonUser.idSpotify, jsonUser.email, jsonUser.createdAt, jsonUser.name, jsonUser.imageUrl); + } + public static uptade( jsonUser :any ) : User{ + return new User(jsonUser.idFlad, jsonUser.idSpotify, jsonUser.email, jsonUser.createdAt, jsonUser.name, jsonUser.imageUrl); + } + +} \ No newline at end of file diff --git a/src/FLAD/app.json b/src/FLAD/app.json index 86c13a7..8db8416 100644 --- a/src/FLAD/app.json +++ b/src/FLAD/app.json @@ -34,6 +34,14 @@ }, "web": { "favicon": "./assets/icons/favicon.png" - } + }, + "plugins": [ + [ + "expo-location", + { + "locationAlwaysAndWhenInUsePermission": "Allow $(PRODUCT_NAME) to use your location." + } + ] + ] } } diff --git a/src/FLAD/redux/actions/spotActions.tsx b/src/FLAD/redux/actions/spotActions.tsx index 3a64b9a..41fbfa3 100644 --- a/src/FLAD/redux/actions/spotActions.tsx +++ b/src/FLAD/redux/actions/spotActions.tsx @@ -1,8 +1,17 @@ +import Music from "../../Model/Music"; +import { Spot } from "../../Model/Spot"; import {spotTypes} from "../types/spotTypes"; export const setSpotList = (spotList: Spot[]) => { return { type: spotTypes.FETCH_SPOT, - payload: spotList, + playload: spotList, + }; + } + + export const setUserCurrentMusic = (currentMusic: Music) => { + return { + type: spotTypes.FETCH_SPOT, + playload: currentMusic, }; } \ No newline at end of file diff --git a/src/FLAD/redux/reducers/appReducer.tsx b/src/FLAD/redux/reducers/appReducer.tsx index 85db729..c08cc64 100644 --- a/src/FLAD/redux/reducers/appReducer.tsx +++ b/src/FLAD/redux/reducers/appReducer.tsx @@ -1,19 +1,28 @@ +import Music from "../../Model/Music"; +import { Spot } from "../../Model/Spot"; +import { discoveriesTypes } from "../types/discoverieTypes"; +import { favoritesTypes } from "../types/favoritesTypes"; +import { spotifyTypes } from "../types/spotifyTypes"; +import { spotTypes } from "../types/spotTypes"; + const initialState = { - spot: [], - favoriteMusic: [], + spot: [] as Spot[], + favoriteMusic: [] as Music [], + userCurrentMusic : null } const appReducer = (state = initialState, action : any) => { switch (action.type) { - case ADD_FAVORITE_MUSICS: + case favoritesTypes.ADD_FAVORITE_MUSICS: return {...state, favoriteMusic: state.favoriteMusic.push(action.payload)}; - case REMOVE_FAVORITE_MUSICS: + case favoritesTypes.REMOVE_FAVORITE_MUSICS: return {...state, favoriteMusic: state.favoriteMusic}; - case FETCH_SPOT: + case spotTypes.FETCH_SPOT: return {...state, spot: action.payload}; - case FETCH_DISCOVERIES: - - + case discoveriesTypes.FETCH_DISCOVERIES: + return; + case spotifyTypes.GET_USER_CURRENT_MUSIC: + return {...state, userCurrentMusic: action.payload}; default: return state; } diff --git a/src/FLAD/redux/reducers/userReducer.tsx b/src/FLAD/redux/reducers/userReducer.tsx index 015cd9a..421f706 100644 --- a/src/FLAD/redux/reducers/userReducer.tsx +++ b/src/FLAD/redux/reducers/userReducer.tsx @@ -1,7 +1,8 @@ +import { User } from "../../Model/User"; import { userTypes } from "../types/userTypes"; const initialState = { loading: false, - user: {}, // for user object + user: User, // for user object userFladToken: null, // for storing the JWT userSpotifyToken : null, error: null, @@ -13,28 +14,29 @@ const initialState = { // just for the navigation and speciafly use // and case userTypes.RESTORE_TOKEN: - console.log(state.loading, "((((((((((((((((((((((((((((((((((((userRducer))))))))))))))))))))))))))))))))))))"); - - console.log(state.userFladToken, "userRducer"); - console.log(state.loading, "((((((((((((((((((((((((((((((((((((userRducer))))))))))))))))))))))))))))))))))))"); - return { ...state, userFladToken : action.playload, loading: true, // isLogedIn: true, }; - case userTypes.LOGIN: + console.log("++++++++++++++++++++++++++++++++++++++userRducer+++++++++++++++++++++++++++++3"); + console.log(action.playload, "LOOGGIIINN"); + console.log("++++++++++++++++++++++++++++++++++++++userRducer+++++++++++++++++++++++++++++3"); return { ...state, - user :action.payload, + user :action.playload, isLogedIn: true }; case userTypes.SIGNUP: + console.log("++++++++++++++++++++++++++++++++++++++userRducer+++++++++++++++++++++++++++++3"); + + console.log(action.playload, "LOOGGIIINN"); + console.log("++++++++++++++++++++++++++++++++++++++userRducer+++++++++++++++++++++++++++++3"); return { ...state, - user :action.payload, + user :action.playload, isLogedIn: true }; // case USER_SIGNUP: diff --git a/src/FLAD/redux/thunk/authThunk.tsx b/src/FLAD/redux/thunk/authThunk.tsx index 6e70aca..df93371 100644 --- a/src/FLAD/redux/thunk/authThunk.tsx +++ b/src/FLAD/redux/thunk/authThunk.tsx @@ -6,6 +6,8 @@ import { useEffect } from "react"; import { API_URL } from "../../fladConfig"; import { Credentials, CredentialsRegister, restoreToken, setLoginState } from "../actions/userActions"; import * as SecureStore from 'expo-secure-store'; +import { User } from "../../Model/User"; +import { UserFactory } from "../../Model/factory/UserFactory"; const key = 'userToken'; @@ -36,7 +38,7 @@ export const registerUser = ( resgisterCredential : CredentialsRegister) => { "https://flad-api-production.up.railway.app/api/users", {headers} ) - dispatch(setLoginState(resp.data.user) ); // our action is called here + dispatch(setLoginState( UserFactory.JsonToModel(user.data) )); // our action is called here // console.log(user.data); // dispatch(setLoginState(user.data) ); // our action is called here } else { @@ -90,7 +92,7 @@ return async dispatch => { {headers} ) // dispatch(setLoginState(resp.data.user) ); // our action is called here - + console.log(user.data); dispatch(setLoginState(user.data) ); // our action is called here } else { console.log('Login Failed', 'Username or Password is incorrect'); diff --git a/src/FLAD/redux/thunk/spotThunk.tsx b/src/FLAD/redux/thunk/spotThunk.tsx index cbc10bb..907a329 100644 --- a/src/FLAD/redux/thunk/spotThunk.tsx +++ b/src/FLAD/redux/thunk/spotThunk.tsx @@ -1,7 +1,14 @@ //Define your action creators that will be responsible for asynchronous operations +import axios from "axios"; import { API_URL } from "../../fladConfig"; - +import { RequestHandler } from "../../services/spotify/spotifyRequestHandler/utils"; +import * as SecureStore from 'expo-secure-store'; +import { Spot } from "../../Model/Spot"; +import SpotifyService from "../../services/spotify/spotify.service"; +import * as Location from 'expo-location'; +import { setSpotList, setUserCurrentMusic } from "../actions/spotActions"; +const key = 'userToken'; export type CreateSpotReqBody = { id : string; @@ -10,7 +17,80 @@ export type CreateSpotReqBody = { linkCover : string; user : string; } +export const getSpotList = (resuestHandler : SpotifyService) => { +//@ts-ignore +return async dispatch => { + try { + + // let { status } = await Location.requestForegroundPermissionsAsync(); + // if (status !== 'granted') { + // setErrorMsg('Permission to access location was denied'); + // return; + // } + + // let location = await Location.getCurrentPositionAsync({}); + // setLocation(location); + // const actualUser = MyApp.controller.getIdDafl(); + // const actualSong = MyApp.controller.getCurrentMusic().id; + // const current = await new Promise((resolve, reject) => { + // Geolocation.getCurrentPosition(resolve, reject); + // }); + + + //@ts-ignore + var userToken : string = await SecureStore.getItemAsync(key); + const headers = { + 'Authorization': 'Bearer ' + userToken}; + const data = await axios.get( + "https://flad-api-production.up.railway.app/api/users/nextTo", + {headers} + ) + if (data.data.token) { + const spotsData: { [userId: string]: string } = {}; + + for (const item of data.data) { + spotsData[item.user] = item.music; + } + const spots = await Promise.all( + Object.entries(spotsData).map(async ([userId, value]) => { + const completeMusic = await resuestHandler.getMusicById(value); + return new Spot(userId, completeMusic); + }) + ); + + dispatch(setSpotList(spots)); // our action is called here + } else { + console.log('Login Failed', 'Username or Password is incorrect'); + } + + } catch (error) { + console.log('Error---------', error); + } +} +} +export const getCurrentUserMusic = (resuestHandler : SpotifyService)=> { + //@ts-ignore + return async dispatch => { + try { + //@ts-ignore + var currentTrackResponse = await resuestHandler.getUserCurrentMusic(); + if (!currentTrackResponse){ + const recentlyTrackResponse = await resuestHandler.getUserRecentlyPlayedMusic(); + if(!recentlyTrackResponse){ + throw new Error; + }else{ + currentTrackResponse = recentlyTrackResponse; + } + } + const completeMusic = await resuestHandler.getMusicById(currentTrackResponse); + dispatch(setUserCurrentMusic(completeMusic)); + } + catch (error) { + console.log('Error---------', error); + } +} +} // export const getSpotList = () => { // return async dispatch => { // try { diff --git a/src/FLAD/redux/types/discoverieTypes.tsx b/src/FLAD/redux/types/discoverieTypes.tsx new file mode 100644 index 0000000..b94726f --- /dev/null +++ b/src/FLAD/redux/types/discoverieTypes.tsx @@ -0,0 +1,3 @@ +export const discoveriesTypes = { + FETCH_DISCOVERIES : 'FETCH_DISCOVERIES', + } \ No newline at end of file diff --git a/src/FLAD/redux/types/favoritesTypes.tsx b/src/FLAD/redux/types/favoritesTypes.tsx new file mode 100644 index 0000000..3634534 --- /dev/null +++ b/src/FLAD/redux/types/favoritesTypes.tsx @@ -0,0 +1,6 @@ + + +export const favoritesTypes = { + ADD_FAVORITE_MUSICS : 'ADD_FAVORITE_MUSICS', + REMOVE_FAVORITE_MUSICS : 'REMOVE_FAVORITE_MUSICS', + } \ No newline at end of file diff --git a/src/FLAD/redux/types/musicTypes.tsx b/src/FLAD/redux/types/musicTypes.tsx deleted file mode 100644 index e69de29..0000000 diff --git a/src/FLAD/redux/types/playlistTypes.tsx b/src/FLAD/redux/types/playlistTypes.tsx index e69de29..d4a5f0f 100644 --- a/src/FLAD/redux/types/playlistTypes.tsx +++ b/src/FLAD/redux/types/playlistTypes.tsx @@ -0,0 +1,5 @@ +export const playlistTypes = { + FETCH_USER_PLAYLISTS : 'FETCH_SPOT', + SAVE_IN_FLAD_PLAYLIST : 'SAVE_IN_FLAD_PLAYLIST', + FETCH_FLAD_PLAYLIST : 'FETCH_SPOT', +} \ No newline at end of file diff --git a/src/FLAD/redux/types/spotTypes.tsx b/src/FLAD/redux/types/spotTypes.tsx index 9ac6c8f..c4893a5 100644 --- a/src/FLAD/redux/types/spotTypes.tsx +++ b/src/FLAD/redux/types/spotTypes.tsx @@ -1,3 +1,3 @@ export const spotTypes = { - FETCH_SPOT : 'FETCH_NOUNOURS', + FETCH_SPOT : 'FETCH_SPOT', } \ No newline at end of file diff --git a/src/FLAD/redux/types/spotifyTypes.ts b/src/FLAD/redux/types/spotifyTypes.ts new file mode 100644 index 0000000..0f2039b --- /dev/null +++ b/src/FLAD/redux/types/spotifyTypes.ts @@ -0,0 +1,3 @@ +export const spotifyTypes = { + GET_USER_CURRENT_MUSIC : 'GET_USER_CURRENT_MUSIC', +} \ No newline at end of file diff --git a/src/FLAD/screens/SpotDetailsPage.tsx b/src/FLAD/screens/SpotDetailsPage.tsx index a57a37f..841ef4e 100644 --- a/src/FLAD/screens/SpotDetailsPage.tsx +++ b/src/FLAD/screens/SpotDetailsPage.tsx @@ -9,6 +9,8 @@ import { Buffer } from 'buffer'; import { Audio } from 'expo-av'; import { useEffect, useState } from "react"; import { State, TapGestureHandler } from "react-native-gesture-handler"; +import { RequestHandler } from "../services/spotify/spotifyRequestHandler/utils"; +import { FetchRequest } from "expo-auth-session/build/Fetch"; interface SpotProps { spot: { name: string, sourceUrl: string, index : number }; @@ -149,27 +151,32 @@ const SpotDetailsPage = ({ route }) => { }; var id = '0cFS3AMF9Lhj3CNoFvwjvY' + const requestor = new RequestHandler() + const getCurrentTrack = async () => { try { - var GetTrackOptions = { - method: 'GET', - url: 'https://api.spotify.com/v1/tracks/'+id, + const opt : FetchRequest ={headers : Record} + requestor.spotifyFetch(`tracks${id}`,) + + // var GetTrackOptions = { + // method: 'GET', + // url: 'https://api.spotify.com/v1/tracks/'+id, - headers: { - 'Authorization': 'Bearer ' + spotify, - 'Content-Type' : 'application/json', - 'market' : 'FR', - }, - json: true - }; - const resp = await axios(GetTrackOptions) - console.log("============"); - console.log(resp.data.href); - console.log("================================"+resp.data.album.images[0].url+ "================================"); - var tmp = currentspot; + // headers: { + // 'Authorization': 'Bearer ' + spotify, + // 'Content-Type' : 'application/json', + // 'market' : 'FR', + // }, + // json: true + // }; + // const resp = await axios(GetTrackOptions) + // console.log("============"); + // console.log(resp.data.href); + // console.log("================================"+resp.data.album.images[0].url+ "================================"); + // var tmp = currentspot; - tmp.sourceUrl = resp.data.album.images[0].url; - setCurrentspot(tmp); + // tmp.sourceUrl = resp.data.album.images[0].url; + // setCurrentspot(tmp); // await axios(authOptions).then(async (response) =>{ // console.log(response.data.item.preview_url); // const id = response.data.item.id; @@ -207,7 +214,7 @@ const SpotDetailsPage = ({ route }) => { } } const animationState = new Value(State.UNDETERMINED); - + return ( diff --git a/src/FLAD/screens/favoritePage.tsx b/src/FLAD/screens/favoritePage.tsx index 9a7b8b1..9ae736b 100644 --- a/src/FLAD/screens/favoritePage.tsx +++ b/src/FLAD/screens/favoritePage.tsx @@ -1,4 +1,4 @@ -import React, {Component} from 'react'; +import React, {Component, useState} from 'react'; import { Animated, Image,StyleSheet, Text, View, FlatList, ScrollView, TouchableOpacity } from 'react-native'; import CardMusic from '../components/CardMusic'; import normalize from '../components/Normalize'; @@ -17,7 +17,26 @@ export default function favoritePage() { new Music("Freeze Raƫl", "Freeze Corleone", "https://intrld.com/wp-content/uploads/2020/08/freeze-corleone-la-menace-fanto%CC%82me.png"), new Music("Blanka", "PNL", require("../assets/images/pnl.png")), new Music("Kratos", "PNL", "https://upload.wikimedia.org/wikipedia/en/a/a0/PNL_-_Dans_la_l%C3%A9gende.png"), - ] + ] + // to do + const [filteredDataSource, setFilteredDataSource] = useState([]); + const [search, setSearch] = useState(''); + const searchMusic = (text: string) => { + if (text) { + const newData = MUSIC_LIST.filter(function (item: Music) { + const search = item.title + ? item.title.toUpperCase() : ''.toUpperCase(); + const textsearch = text.toUpperCase(); + return search.indexOf(textsearch) > -1; + }); + setFilteredDataSource(newData); + setSearch(text); + } else { + setFilteredDataSource([]); + setSearch(text); + } + }; + return ( diff --git a/src/FLAD/screens/spot.tsx b/src/FLAD/screens/spot.tsx index 7d62b3c..61d6f66 100644 --- a/src/FLAD/screens/spot.tsx +++ b/src/FLAD/screens/spot.tsx @@ -112,6 +112,25 @@ export default function Spot() { likeButtonref.current?.play(0,55); }, []) + +// function addWatchLater(props: Movie) { +// dispatch(addMovieToWatchLater(props)); +// dispatch(removeMovieTrending(props)); +// if (displayIndex == trendingMovies.length - 1) { +// setdisplayIndex(0); +// swiper.swipeLeft(); +// } +// } + +// function addFavourite(props: Movie) { +// dispatch(addMovieToFavourite(props)); +// dispatch(removeMovieTrending(props)); +// if (displayIndex == trendingMovies.length - 1) { +// setdisplayIndex(0); +// swiper.swipeLeft(); +// } +// } + // const hapti = (() => { // Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Heavy) diff --git a/src/FLAD/services/spotify/spotify.service.ts b/src/FLAD/services/spotify/spotify.service.ts index 3500dd8..3e7ce5f 100644 --- a/src/FLAD/services/spotify/spotify.service.ts +++ b/src/FLAD/services/spotify/spotify.service.ts @@ -1,11 +1,14 @@ import axios from "axios"; +import MusicFactory from "../../Model/factory/MusicFactory"; +import Music from "../../Model/Music"; +import { RequestHandler } from "./spotifyRequestHandler/utils"; - -export default class SpotifyService { - private readonly API_URL = "http://localhost:8080/api/spotify/exchange"; - - constructor() { - +export default class SpotifyService implements IspotifyService { + private readonly API_URL = "https://flad-api-production.up.railway.app/api/"; + private spotifyRequestHandler = new RequestHandler(); + private readonly token : string; + constructor(token : string) { + this.token = token; } // get id(){ // return this.identification; @@ -14,7 +17,46 @@ export default class SpotifyService { // async apiAuth(url : string) { // await this.identification.setCode(url); // // this.request = ApiSpotifyRequests(await this.identification.createToken()); - // } + // } + public async getMusicById(idMusic : string): Promise{ + var requestData :string = '/tracks/' + idMusic; + const respMusic = await this.spotifyRequestHandler.spotifyFetch(requestData, undefined,this.token); + if (respMusic.status != 200) { + } + return MusicFactory.mapFromSpotifyTrack(respMusic.data); + } + + public async getUserCurrentMusic(): Promise{ + var requestData :string = '/me/player/currently-playing'; + const respMusic = await this.spotifyRequestHandler.spotifyFetch(requestData, undefined,this.token); + if (respMusic.status != 200) { + return null; + } + return respMusic.data.items.track.id; + } + + public async getUserRecentlyPlayedMusic(): Promise{ + var requestData :string = '/me/player/recently-played'; + const respMusic = await this.spotifyRequestHandler.spotifyFetch(requestData, undefined,this.token); + if (respMusic.status != 200) { + } + if (respMusic.data.items.length <= 0) { + return null; + } + return respMusic.data.items[0].track.id; + } + + public async playMusic(): Promise{ + var requestData :string = '/me/player/recently-played'; + const respMusic = await this.spotifyRequestHandler.spotifyFetch(requestData, undefined,this.token); + if (respMusic.status != 200) { + } + if (respMusic.data.items.length <= 0) { + return null; + } + return respMusic.data.items[0].track.id; + } + async getSpotifyCredentials() { const res = await axios.get(this.API_URL) // then verify error diff --git a/src/FLAD/services/spotify/spotifyRequestHandler/IspotifyService.ts b/src/FLAD/services/spotify/spotifyRequestHandler/IspotifyService.ts new file mode 100644 index 0000000..8f3e829 --- /dev/null +++ b/src/FLAD/services/spotify/spotifyRequestHandler/IspotifyService.ts @@ -0,0 +1,4 @@ +interface IspotifyService { + getMusicById(idMusic : string): Promise; + +} \ No newline at end of file diff --git a/src/FLAD/services/spotify/spotifyRequestHandler/utils.tsx b/src/FLAD/services/spotify/spotifyRequestHandler/utils.tsx new file mode 100644 index 0000000..2addfb7 --- /dev/null +++ b/src/FLAD/services/spotify/spotifyRequestHandler/utils.tsx @@ -0,0 +1,44 @@ +import axios, { AxiosError } from "axios"; + +export type Methods = 'GET' | 'POST' | 'DELETE' | 'PUT' | 'PATCH'; + +export interface FetchOptions { + /** The headers to apply. */ + headers?: Record; + /** The method type. */ + method?: Methods; + /** Search query parameters. */ + params?: Record; + /** The json body to send if available. */ + body?: Record; +} + +export class RequestHandler{ + private _version: `v${number}` = 'v1'; + get version(): string { + return this._version; + } + + public async spotifyFetch(url: string, options: FetchOptions = {}, token: string) { + const resp = await axios({ + url: `https://api.spotify.com/${this.version}${url}`, + method: options.method || 'GET', + params: options.params, + headers: { + Authorization: "Bearer " + token, + Accept: 'application/json', + ...options.headers + }, + data: options.body + }); + console.log() + return resp; + // if ( + // // @ts-ignore + // error.response.data?.error?.message == "Invalid access token" || + // // @ts-ignore + // error.response.data?.error?.message == "The access token expired" && + // this.refreshMeta + // ) await this.refreshFromMeta(); + } +} \ No newline at end of file