for merge purpose #15

Merged
emre.kartal merged 1 commits from refresh_token into master 2 years ago

@ -3,6 +3,7 @@ import { Provider } from 'react-redux';
import store from './redux/store';
import AuthNavigation from './navigation/AuthNavigation';
import * as SplashScreen from 'expo-splash-screen';
import SpotifyService from './services/spotify/spotify.service';
SplashScreen.preventAutoHideAsync();
@ -20,4 +21,5 @@ const styles = StyleSheet.create({
flex: 1,
backgroundColor: "#141414",
}
});
});
export const theService = new SpotifyService('BQC0rAGJvxTt4-24P-nda6qP9iXYCql2eApnUAoEbZZkKemJ11cU3Nx-I_tKVX0FwEgFbIbSIuaVvxOapRVJq2z1Htyy3XQ5jIYNsrhrnp3KTCfppamAjxgDTf6khBrNGTxe6CNKBsMhc5IRnphey5Td2zJPvGMwnFFfMQdCtVAVsCNK7kPKlCAaf_kRMAoPn30Qk4RD45XmwtZIwQg7X0J4beGuHSiBf0MRjhsnFEW89GxVm8YuIVwgrDbF3izfPR0AlqS4IMJT5m4pEA72lYEwp1JnSDVsafILzmksaqG-11H3WAsWIENrOIu_j7qNgbvYwmUWXOrYmeWBkQ');

@ -1,4 +1,9 @@
export default class Music {
// export interface MinimalMusic{
// private _id: string;
// private _title: string;
// }
export default class Music{ // : extends MinimalMusic
private _id: string;
private _title: string;
private _bio: string;

@ -9,6 +9,10 @@ import * as SplashScreen from 'expo-splash-screen';
import { View } from 'react-native';
import { getRefreshToken } from '../redux/thunk/authThunk';
import * as Location from 'expo-location';
import { theService } from '../App';
import { getCurrentUserMusic } from '../redux/thunk/spotThunk';
import axios from 'axios';
import Music from '../Model/Music';
// const LOCATION_TASK_NAME = 'flad-background-location-task';
@ -19,11 +23,14 @@ export default function AuthNavigation() {
// const appIsReady: boolean = useSelector(state => state.userReducer.loading);
//@ts-ignore
const isLogin: boolean = useSelector(state => state.userReducer.isLogedIn);
const currentMusic: Music = useSelector(state => state.appReducer.userCurrentMusic);
const tokenSend: string = useSelector(state => state.userReducer.userFladToken);
// const userToken : string = useSelector(state => state.userReducer.userFladToken);
const [appIsReady, setAppIsReady] = useState(false);
const dispatch = useDispatch();
const [location, setLocation] = useState({});
const [location, setLocation] = useState<Location.LocationObject>();
const [errorMsg, setErrorMsg] = useState('');
@ -76,44 +83,126 @@ export default function AuthNavigation() {
// const onStackRootView = useCallback(async () => {
// }, [appIsReady]);
// useEffect(() => {
// const sendLocationUpdate = async () => {
// try {
// let { status } = await Location.requestForegroundPermissionsAsync();
// console.log('Sending location update ================================###############');
// if (status === 'granted') {
// console.log(appIsReady)
// if (true) {// should app is ready
// // see deeper the documentation
// // const [status, requestPermission] = Location.useBackgroundPermissions();
// const locationresp = await Location.getCurrentPositionAsync({});
// setLocation(locationresp);
// // send location to server
// console.log(locationresp);
// if(locationresp !=location ){
// }
// console.log(location);
// }
// }
// else{
// console.log(`Sending location update with error ${status} ================================###############`);
// setErrorMsg('Permission to access location was denied');
// return;
// }
// } catch (error) {
// console.log(error);
// }
// };
// const interval = setInterval(sendLocationUpdate, 5000); // send location updates every 5 seconds
// return () => {
// clearInterval(interval);
// };
// }, []);
useEffect(() => {
const sendLocationUpdate = async () => {
try {
//@ts-ignore
await dispatch(getCurrentUserMusic(theService))
let { status } = await Location.requestForegroundPermissionsAsync();
if (status == 'granted') {
console.log(appIsReady)
if (true) {// should app is ready
// see deeper the documentation
// const [status, requestPermission] = Location.useBackgroundPermissions();
const locationresp = await Location.getCurrentPositionAsync({});
setLocation(locationresp);
// send location to server
console.log(locationresp);
// if(locationresp !=location ){
console.log(location);
const body : Record<string, string | boolean | number | (string | boolean | number)[]> = {
longitude: locationresp.coords.longitude,
latitude: locationresp.coords.latitude,
currentMusic : currentMusic.id
}
console.log(tokenSend)
console.log('((((((((((((((((((((()))))))))))))))))))))================================###############');
console.log('((((((((((((((((((((()))))))))))))))))))))================================###############');
console.log('((((((((((((((((((((())))))))))))))))))))================================###############');
console.log(location);
console.log('(((((((((((((((((((()))))))))))))))))))))================================###############'); console.log('((((((((((((((((((((()))))))))))))))))))))================================###############');
console.log('((((((((((((((((((((()))))))))))))))))))))================================###############');
console.log('((((((((((((((((((((()))))))))))))))))))))================================###############');
console.log('**********************************************************************************')
try {
const resp = await axios({
url: 'https://flad-api-production.up.railway.app/api/users/nextTo',
method: 'GET',
headers: {
Authorization: `Bearer ${tokenSend}`,
},
params: {
longitude: locationresp.coords.longitude,
latitude: locationresp.coords.latitude,
currentMusic : currentMusic.id
}
});
console.log('(((((((((((((((((((()))))))))))))))))))))================================###############');
console.log('((((((((((((((((((((())))))))))))))))))))================================###############');
console.log(resp.status);
console.log('**********************************************************************************')
console.log('**********************************************************************************')
console.log('**********************************************************************************')
console.log('((((((((((((((((((((()))))))))))))))))))))================================###############');
console.log('((((((((((((((((((((()))))))))))))))))))))================================###############');
console.log(resp);
console.log(resp.data);
console.log('((((((((((((((((((((()))))))))))))))))))))================================###############');
console.log('((((((((((((((((((((()))))))))))))))))))))================================###############');
console.log('((((((((((((((((((((()))))))))))))))))))))================================###############');
console.log('=========((((((((((((((((()))))))))))))))))===============================###############');
} catch (error) {
console.log('*********************************************************************************************');
console.log('*********************************************************************************************');
console.log('********************************************************************************************');
console.log('*********************************************************************************************');
console.log('*********************************************************************************************');
console.log('*********************************************************************************************');
console.log('*********************************************************************************************');
console.log(error);
console.log(error.message);
console.log('*********************************************************************************************');
console.log('*********************************************************************************************');
console.log('*********************************************************************************************');
console.log('*********************************************************************************************');
console.log('*********************************************************************************************');
console.log('*********************************************************************************************');
console.log('*********************************************************************************************');
}
// }
console.log(locationresp);
console.log(currentMusic);
console.log('Sending location update ================================###############');
}
}
else{
console.log(`Sending location update with error ${status} ================================###############`);
setErrorMsg('Permission to access location was denied');
return;
}
} catch (error) {
console.log(error);
}
};
const interval = setInterval(sendLocationUpdate, 5000); // send location updates every 5 seconds
return () => {
clearInterval(interval);
};
}, []);
if (tokenProcesed == false) {
return null;
}
// console.log(userToken, "k9 AuthNav")
return (
<SafeAreaProvider onLayout={() => setAppIsReady(true)}>

@ -109,4 +109,4 @@ const styles = StyleSheet.create({
position: 'absolute',
top: 5,
}
})
})

@ -46,7 +46,8 @@
"react-native-web": "~0.18.9",
"react-navigation-shared-element": "^3.1.3",
"react-redux": "^8.0.5",
"redux": "^4.2.1"
"redux": "^4.2.1",
"expo-web-browser": "~12.0.0"
},
"devDependencies": {
"@babel/core": "^7.12.9",

@ -0,0 +1,30 @@
import axios from "axios";
import { Spot } from "../../Model/Spot";
export const likeSpot = async (spot : Spot) => {
//
return async (dispatch) => {
// const fetchAll = async () => {
// const data = await fetch(`https://kanjialive-api.p.rapidapi.com/api/public/search/${search}`, options)
// .then(response => response.json());
// const fetchPromises = data.map(it =>
// fetch(`https://kanjialive-api.p.rapidapi.com/api/public/kanji/${it.kanji.character}`, options)
// .then(detail => detail.json())
// );
// const kanjis = await Promise.all(fetchPromises)
// .then(details => details.map(detail_data => KanjiMapper.ApiJsonToKanji(detail_data)));
// return kanjis;
// };
axios.post("osdj").then( responce => {if(responce.status == 200){
dispatch(true);
} } ).catch(error => {
console.log("something goes wrong while searching : " + error);
;})
};
}

@ -24,6 +24,7 @@ import { LittleCard } from "../components/littleCard";
import { Circle } from "react-native-svg";
import { AntDesign } from '@expo/vector-icons';
import * as SecureStore from 'expo-secure-store';
import { useSelector } from "react-redux";
const halfPi = Math.PI / 2;
@ -42,10 +43,8 @@ const MusicDetail = ({ route }) => {
const sheet = async () => {
SecureStore.getItemAsync('MySecureAuthStateKey').then(result => { setTesttoken(result) });
}
useEffect(() => {
sheet();
getSimilarTrack();
@ -124,6 +123,53 @@ const MusicDetail = ({ route }) => {
};
})
const tokenSend: string = useSelector(state => state.userReducer.userFladToken);
// const maymany = async () => {
// try{
// const resp = await axios({
// url: 'https://flad-api-production.up.railway.app/api/users/nextTo',
// method: 'GET',
// headers: {
// Authorization: `Bearer ${tokenSend}`,
// },
// params:{
// longitude: '12323',
// latitude: '12323',
// currentMusic : '12323'
// }
// });
// console.log("yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy")
// console.log("yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy")
// console.log("yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy")
// console.log("yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy")
// console.log(resp);
// console.log("yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy")
// console.log("yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy")
// console.log("yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy")
// console.log("yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy")
// }
// catch(error){
// console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
// console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
// console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
// console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
// console.log(error);
// console.log(error.message);
// console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
// console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
// console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
// console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
// console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
// console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
// }
// };
return (
<View style={styles.body}>
<View style={styles.backgroundSection}>
@ -146,9 +192,6 @@ const MusicDetail = ({ route }) => {
</View>
<View style={styles.background1}>
<ScrollView style={styles.list} showsVerticalScrollIndicator={false} scrollEventThrottle={4}>
<View style={styles.section1}>
<View style={{ flex: 1, justifyContent: 'flex-start', alignItems: 'center' }}>
{/* <SharedElement id={spot.name} style={{ flex: 1 }}> */}

@ -4,7 +4,6 @@ import { useNavigation } from "@react-navigation/native";
import normalize from '../components/Normalize';
import * as SecureStore from 'expo-secure-store';
import * as AuthSession from 'expo-auth-session';
import * as WebBrowser from 'expo-web-browser';
import { makeRedirectUri, useAuthRequest } from 'expo-auth-session';
import { registerUser } from '../redux/thunk/authThunk';
import { useDispatch } from 'react-redux';
@ -12,6 +11,7 @@ import { Audio } from 'expo-av';
import { CredentialsRegister } from '../redux/actions/userActions';
import { Buffer } from 'buffer';
import SpotifyService from '../services/spotify/spotify.service';
import * as WebBrowser from 'expo-web-browser';
// @ts-ignore
const DismissKeyboard = ({ children }) => (
@ -123,21 +123,28 @@ export default function InscriptionPage() {
console.error(err)
}
}
// const [result2, setResult] = useState(null);
const getAuthorizationCode2 = async () => {
try {
const result = await AuthSession.startAsync({
authUrl: 'https://flad-api-production.up.railway.app/api/spotify/exchange'
})
// let result = await WebBrowser.openBrowserAsync('https://flad-api-production.up.railway.app/api/spotify/exchange');
// setResult(result2);
console.log("=================grant code ==============<");
console.log(result);
// console.log(result2);
console.log("=================grant code ==============<");
return result.params.code;
// return result.params.code;
} catch (err) {
console.error(err)
}
}
const getTokens2 = async () => {
try {
const authorizationCode = await getAuthorizationCode2() //we wrote this function above
@ -257,7 +264,7 @@ export default function InscriptionPage() {
<Image source={require('../assets/icons/icons/lock.png')} style={styles.iconLock} />
</View>
<TouchableOpacity onPress={async () => {
await getTokens();
await getTokens2();
}} style={[styles.buttonSpotify, styles.shadow]}>
<Text style={styles.textIntoButton}>Lier compte</Text>
<Image source={require("../assets/icons/icons/Spotify.png")} style={{ width: normalize(35), height: normalize(35) }} />

@ -11,6 +11,7 @@ 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";
import { theService } from "../App";
interface SpotProps {
spot: { name: string, sourceUrl: string, index: number };
@ -155,8 +156,9 @@ const SpotDetailsPage = ({ route }) => {
const getCurrentTrack = async () => {
try {
const opt: FetchRequest = { headers: Record }
requestor.spotifyFetch(`tracks${id}`,)
// const opt: FetchRequest = { headers: Record }
// requestor.spotifyFetch(`tracks${id}`,)
theService.getMusicById(id)
// var GetTrackOptions = {
// method: 'GET',

@ -134,6 +134,7 @@ export default function SpotPage() {
console.log("====3===" + currentCard.music.title + "======3=========");
dispatch(addFavoritesMusic(music))
// dispatch(likeMusic(currentCard));
// dispatch(addFavoriteMusic(props));
// if (displayIndex == trendingMovies.length - 1) {
// setdisplayIndex(0);

@ -0,0 +1,5 @@
interface IspotifyAuthHandler {
abstract async getUserToken(): Promise<string>;
abstract async getUserTokenFromRefreshToken(): Promise<string>;
}

@ -18,10 +18,18 @@ export class MusicMinimal {
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;
// private spotifyAuthHandler : AuthHandler;
public token: string;
constructor(token: string) {
// this.auth = new AuthManager(this.token);
// this.initialize();
this.token = token;
}
// initialize() {
// this.token = await this.auth.getApiToken(options.token.clientID, options.token.clientSecret);
// }
// get id(){
// return this.identification;
// }
@ -44,8 +52,12 @@ export default class SpotifyService implements IspotifyService {
if (respMusic.status != 200) {
return null;
}
console.log(respMusic.data.items.track.id)
return respMusic.data.items.track.id;
console.log("respMusic.data.items.track.id")
console.log(respMusic.data.item.id)
console.log("respMusic.data.items.track.id")
return respMusic.data.item.id;
}
public async getUserRecentlyPlayedMusic(): Promise<string | null> {
@ -56,6 +68,10 @@ export default class SpotifyService implements IspotifyService {
if (respMusic.data.items.length <= 0) {
return null;
}
console.log("respMusic.data.items[0].track.id");
console.log(respMusic.data.items[0].track.id);
console.log("respMusic.data.items[0].track.id");
return respMusic.data.items[0].track.id;
}
@ -136,7 +152,6 @@ export default class SpotifyService implements IspotifyService {
return respMusic.data.audio_features.tempo;
}
public async addItemToPlayList(playlistId: string, idMusic: string): Promise<void> {
var requestData: string = '/playlists/' + playlistId + '/tracks';
const fetchOptions: FetchOptions = {

@ -3,44 +3,83 @@ import axios, { AxiosError, AxiosResponse } from "axios";
export type Methods = 'GET' | 'POST' | 'DELETE' | 'PUT' | 'PATCH';
export interface FetchOptions {
/** The headers to apply. */
/** The headers that will be applied to the request when sent. */
headers?: Record<string, string>;
/** The method type. */
/** The type of HTTP method being used. */
method?: Methods;
/** Search query parameters. */
/** Parameters used for search queries.*/
params?: Record<string, any>;
/** The json body to send if available. */
/**If present, this refers to the JSON data that will be included in the request body. */
body?: Record<string, string | boolean | number | (string | boolean | number)[]>;
}
export class RequestHandler {
private _version: `v${number}` = 'v1';
private count = 0;
// private token: string;
get version(): string {
return this._version;
}
public async spotifyFetch(url: string, options: FetchOptions = {}, token: string): Promise<AxiosResponse<any, any>> {
console.log(options + "sds=============");
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(")))))))))))))))))))", resp.request, "((((((((((((((((((((");
// console.log(resp, "frfrfrfr");
try {
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
});
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();
}
catch(error : any){
const errorMessage = error.response.data?.error?.message;
if (errorMessage === "Invalid access token" || errorMessage === "The access token expired") {
// if (this.refrechData) {
// await this.refreshToken();
// this.count+=1;
// if (this.count >= 4){
// throw new Error;
// }
// return this.spotifyFetch(url, options,token);
// }
throw new Error;
}
else{
throw new Error;
}
}
}
}
// public async refreshFromMeta() {
// if ('refreshToken' in this.refreshMeta!) {
// this.auth.getUserToken(this.refreshMeta as GetUserTokenOptions)
// .then(context => {
// this.token = context.accessToken;
// if (context.refreshToken) this.refreshMeta!.refreshToken = context.refreshToken;
// new UserClient(this).patchInfo().then(x => {
// this.user = x;
// this.onRefresh();
// });
// });
// } else {
// this.auth.getApiToken(this.refreshMeta!.clientID, this.refreshMeta!.clientSecret)
// .then(token => {
// this.token = token;
// this.onRefresh();
// });
// }
// this.auth = new AuthManager(this.token);
// }
}
export class AuthHandler{
}

Loading…
Cancel
Save