code smells fix
continuous-integration/drone/push Build is passing Details

backup_V2
Emre KARTAL 2 years ago
parent 4a9468b21b
commit 3fa45977cc

@ -1,4 +1,3 @@
import { useState } from "react";
import SpotifyService from "../services/spotify/spotify.service";
class Manager {
@ -7,11 +6,6 @@ class Manager {
spotifyService = new SpotifyService();
userService = new userService();
private currentUser = useState(null);
constructor() {
}
// spotify methods
apiAuthorization(url: string) {
this.spotifyService.apiAuthorization(url);
@ -35,79 +29,6 @@ class Manager {
this.spotifyService.playTrack(id);
}
////////////////////////////////////////////
// private readonly getTaskById: RequestHandler = async (
// req: Request,
// res: Response,
// next: NextFunction
// ): Promise<Response | void> => {
// try {
// const id = req.params.taskId;
// const userId = req.params.userId;
// const data = await this.Taskservice.getTaskById(id, userId);
// res.status(201).send(data);
// }
// catch(error){
// next(new HttpException(400, 'Cannot create post'));
// }
// }
// private delete = async (
// req: Request,
// res: Response,
// next: NextFunction
// ): Promise<Response | void> => {
// try {
// const id = req.params.taskId;
// const userId = req.params.userId;
// await this.Taskservice.DeleteTask(id, userId);
// return res.status(200).send({ status: "Success", msg: "Data Removed" });
// } catch (error) {
// next(new HttpException(400, 'Cannot create post'));
// }
// };
// private updateTask = async (
// req: Request,
// res: Response,
// next: NextFunction
// ): Promise<Response | void> => {
// try {
// const taskId = req.params.taskId;
// const userId = req.params.userId;
// const reqBody:CreateTaskReqBody = Object.assign({}, req.body);
// const updatedTask = await this.Taskservice.UpdateTask(
// // req.auth!.uid,
// taskId,
// userId,
// // firebase.auth().currentUser.getIdToken()
// reqBody.nom,
// reqBody.description,
// reqBody.logo,
// reqBody.duration,
// reqBody.done,
// // reqBody.tags,
// reqBody.repepat,
// reqBody.deb,
// reqBody.fin
// );
// // res.send('Success add');
// // res.status(201).json({ task });
// res.status(204).send(`Update a new contact: ${updatedTask}`);
// } catch (error) {
// console.log(error);
// next(new HttpException(403, 'Cannot create post'));
// }
// };
}
export default Manager;

@ -1,34 +1,5 @@
class TokenSpotify {
String _accessToken;
final String _refreshToken;
_accessToken: string;
_refreshToken: string;
late DateTime _tokenEnd;
// TokenSpotify(this._accessToken, this._refreshToken, int expiresIn) {
// _setTokenEnd(expiresIn);
// }
// _setTokenEnd(int expiresIn) {
// _tokenEnd = DateTime.now().add(Duration(seconds: expiresIn));
// }
// Future<String> 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: <String, String>{
// 'Content-Type': 'application/x-www-form-urlencoded'
// }));
// var decodedResponse = jsonDecode(utf8.decode(response.bodyBytes)) as Map;
// _accessToken = decodedResponse['access_token'];
// _setTokenEnd(decodedResponse['expires_in']);
// }
}

@ -6,6 +6,7 @@ export class User {
private _createdAt: Date;
private _name: string;
public image: string = require('../assets/images/jul.png');
//constructors
constructor(idFlad: string, idSpotify: string, email: string, createdAt: Date, name: string, image: string) {
this._name = name;

@ -1,5 +1,3 @@
import React from 'react';
export default function AdjustSize(Text: String) {
const titleLength = Text.length;
const minFontSize = 23;

@ -1,16 +1,12 @@
import { View, useWindowDimensions } from "react-native";
import Animated, { interpolate, SensorType, useAnimatedSensor, useAnimatedStyle, withTiming } from "react-native-reanimated";
import { View } from "react-native";
import Animated, { interpolate, SensorType, useAnimatedSensor, useAnimatedStyle } from "react-native-reanimated";
interface SpotProps {
spot: { name: string, sourceUrl: string, index: number };
}
const halfPi = Math.PI / 2;
const AnimatedParalax = ({ }) => {
const { width, height } = useWindowDimensions();
const sensor = useAnimatedSensor(SensorType.ROTATION);
const styleAniamatedImage = useAnimatedStyle(() => {
const { yaw, pitch, roll } = sensor.sensor.value;
const { pitch, roll } = sensor.sensor.value;
const verticalAxis = interpolate(
pitch,
[-halfPi, halfPi],

@ -9,8 +9,8 @@ const { width } = Dimensions.get("window");
const SIZE = width / 3;
import { Feather as Icon } from "@expo/vector-icons";
import Music from "../Model/Music";
import { State, TapGestureHandler } from "react-native-gesture-handler";
import { useRef, useState } from "react";
import { State } from "react-native-gesture-handler";
import { useState } from "react";
interface ArtistProps {
@ -25,7 +25,6 @@ export const Artist = ({ artist, onPress }: ArtistProps) => {
alert('Hey single tap!');
}
};
const doubleTapRef = useRef(null);
const [selected, setSeleted] = useState(false);
const onS = () => {
setSeleted(!selected);

@ -1,5 +1,6 @@
import { useCallback, useState } from 'react';
import { View, StyleSheet, Text, Image, Pressable, Linking, Alert } from 'react-native'
import { useCallback } from 'react';
import { View, Text, Image, Pressable, Linking, Alert } from 'react-native'
import Artist from '../Model/Artist';
interface ArtistChipProps {
backgroundColor: string;
@ -8,12 +9,9 @@ interface ArtistChipProps {
const ArtistChip = ({ artist }: ArtistChipProps) => {
const handlePress = useCallback(async () => {
// Checking if the link is supported for links with custom URL scheme.
const supported = await Linking.canOpenURL(artist.url);
if (supported) {
// Opening the link with some app, if the URL scheme is "http" the web link should be opened
// by some browser in the mobile
await Linking.openURL(artist.url);
} else {
Alert.alert(`Don't know how to open this URL: ${artist.url}`);
@ -39,12 +37,5 @@ const ArtistChip = ({ artist }: ArtistChipProps) => {
);
};
const styles = StyleSheet.create({
input: {
justifyContent: 'center',
alignItems: 'center',
placeholder: "placeholde"
},
})
export default HalfCirlce;
export default ArtistChip;

@ -1,15 +1,12 @@
import { View, Image, Dimensions, StyleSheet } from 'react-native'
import React from 'react'
import Animated, { Extrapolate, interpolate, runOnJS, useAnimatedGestureHandler, useAnimatedStyle, useSharedValue, withSpring } from 'react-native-reanimated';
import Animated, { interpolate, runOnJS, useAnimatedGestureHandler, useAnimatedStyle, useSharedValue, withSpring } from 'react-native-reanimated';
import normalize from '../components/Normalize';
import { PanGestureHandler, PanGestureHandlerGestureEvent } from 'react-native-gesture-handler';
const SCREEN_WIDTH = Dimensions.get('window').width
const SCREEN_HEIGHT = Dimensions.get('window').height
// const width = wWidht *0.75;
// const height = wWidht * (465/264);
// const borderRadius = 24;
interface CardProps {
title: string;
image: any;
@ -20,7 +17,7 @@ type ContextType = {
translateY: number;
};
const Card = ({ title, image, onSwipe }: CardProps) => {
const Card = ({ image, onSwipe }: CardProps) => {
const translateX = useSharedValue(0);
const translateY = useSharedValue(0);
@ -38,20 +35,15 @@ const Card = ({ title, image, onSwipe }: CardProps) => {
translateY.value = event.translationY + context.translateY;
},
onEnd: (event, context) => {
console.log(translateX.value - translateY.value);
// console.log(translateY.value);
// translateX.value = withSpring(0);
// translateY.value = withSpring(snapPoint(translateY.value,velocityY, snapPoints ))
onEnd: () => {
if (translateX.value > 160) {
console.log("translateX2");
runOnJS(onSwipe)("right");
} else if (translateX.value < -160) {
runOnJS(onSwipe)("left");
// onSwipe("left");
} else if (translateY.value > 250) {
runOnJS(onSwipe)("down");
// onSwipe("left");
}
else {
@ -119,19 +111,6 @@ const Card = ({ title, image, onSwipe }: CardProps) => {
const horizontalThreshold = SCREEN_WIDTH * 0.65;
const rotateStyle = useAnimatedStyle(() => {
const rot = interpolate
(translateX.value,
[-SCREEN_WIDTH / 2, 0, SCREEN_WIDTH / 2],
[30, 0, 30],
Extrapolate.CLAMP);
return {
transform: [{ rotate: `${rot}deg` }, {
translateX: withSpring(translateX.value),
}],
};
});
const styleCardsNew = useAnimatedStyle(() => {
const factor = 1;
const rot = interpolate
@ -151,23 +130,6 @@ const Card = ({ title, image, onSwipe }: CardProps) => {
};
});
// Calculate the distance of the card from its starting position
const rStyle = useAnimatedStyle(() => {
return {
transform: [
{
translateX: translateX.value,
},
{
translateY: translateY.value,
},
],
};
});
console.log('==========================================', SCREEN_WIDTH / 4, "===============================");
return (
<View>
<PanGestureHandler onGestureEvent={onGestureEvent}>
@ -189,8 +151,6 @@ const Card = ({ title, image, onSwipe }: CardProps) => {
<>
<Animated.View
style={[{
// transform: [{ rotate: "30deg" }],
elevation: 100,
position: "absolute",
zIndex: 1000,

@ -1,6 +1,5 @@
import React from 'react';
import { StyleSheet, Text, View, Image } from 'react-native';
import { SharedElement } from 'react-navigation-shared-element';
import { useSelector } from 'react-redux';
import { GraphicalCharterDark } from '../assets/GraphicalCharterDark';
import { GraphicalCharterLight } from '../assets/GraphicalCharterLight';
@ -16,9 +15,9 @@ type CustomCardMusic = { //Props
export default function CardMusic(CBP: CustomCardMusic) {
// @ts-ignore
const isDark = useSelector(state => state.userReducer.dark);
const style = isDark ? GraphicalCharterDark : GraphicalCharterLight;
const currentMusic = useSelector(state => state.appReducer.currentMusic);
const source = typeof CBP.image === 'string' ? { uri: CBP.image } : CBP.image;
const styles = StyleSheet.create({

@ -1,6 +1,5 @@
import { useState } from 'react';
import { View, Text, Image, PanResponder, Dimensions, StyleSheet, ImageBackground, Button, Pressable, TextInput } from 'react-native'
import Animated, { interpolate, lessThan, multiply, useAnimatedStyle } from 'react-native-reanimated';
import { View, StyleSheet } from 'react-native'
import Animated, { lessThan, multiply } from 'react-native-reanimated';
import HalfCirlce from './HalfCircle';
interface CircularProps {
@ -12,42 +11,9 @@ interface CircularProps {
const PI = Math.PI;
const FladInput = ({ background, foreground, progress }: CircularProps) => {
const [focused, setFocused] = useState<boolean>(false);
const theta = multiply(progress, 2 * PI);
const rotateTop = theta;
const opacity = lessThan(theta, PI);
const rotateAnimation = useAnimatedStyle(() => {
const rotate = interpolate
(theta,
[PI, 2 * PI],
[0, PI]);
return {
...StyleSheet.absoluteFillObject,
transform: [
{ rotate: rotate },
{ translateX: RADUIS / 2 },
{ translateY: RADUIS / 2 }
],
};
});
const rotateAnimation2 = useAnimatedStyle(() => {
const rotate = interpolate
(theta,
[PI, 2 * PI],
[0, PI]);
return {
...StyleSheet.absoluteFillObject,
transform: [
{ rotate: theta },
{ translateX: RADUIS / 2 },
{ translateY: RADUIS / 2 }
],
};
});
return (
<>
<View style={{ zIndex: 1 }}>
@ -58,19 +24,12 @@ const FladInput = ({ background, foreground, progress }: CircularProps) => {
</View>
<View style={{ transform: [{ rotate: '180%' }] }}>
<HalfCirlce backgroundColor={background} />
<Animated.View style={{}}>
<Animated.View>
<HalfCirlce backgroundColor={background} />
</Animated.View> </View>
</Animated.View>
</View>
</>
);
};
const styles = StyleSheet.create({
input: {
justifyContent: 'center',
alignItems: 'center',
placeholder: "placeholde"
},
})
export default FladInput;

@ -1,111 +1,8 @@
// import React, { useEffect, useRef } from 'react';
// import { StyleSheet, Text, View , Image } from 'react-native';
// import Animated, { useAnimatedStyle, useSharedValue, withTiming } from 'react-native-reanimated';
// import { SharedElement } from 'react-navigation-shared-element';
// import { useSelector } from 'react-redux';
// import normalize from '../components/Normalize';
// import SpotifyService from '../services/spotify/spotify.service';
// export default function CurrentMusic() {
// const animatedStyle = useAnimatedStyle(() => {
// return {
// transform: [
// { scale: withTiming(139.929, { duration: 1000 }) }
// ]
// }
// });
// const centerX = useSharedValue(0);
// const centerY = useSharedValue(0);
// const scale = useSharedValue(0);
// const width = useSharedValue(0);
// const height = useSharedValue(0);
// const rippleOpacity = useSharedValue(1);
// const rStyle = useAnimatedStyle(() => {
// const circleRadius = Math.sqrt(width.value ** 2 + height.value ** 2);
// const translateX = centerX.value - circleRadius;
// const translateY = centerY.value - circleRadius;
// return {
// width: circleRadius * 2,
// height: circleRadius * 2,
// borderRadius: circleRadius,
// opacity: rippleOpacity.value,
// backgroundColor: 'rgba(0,0,0,0.2)',
// position: 'absolute',
// top: 0,
// left: 0,
// transform: [
// { translateX },
// { translateY },
// {
// scale: scale.value,
// },
// ],
// };
// });
// useEffect(() => {
// // withTiming, withSpring
// rippleOpacity.value = 1;
// scale.value = withTiming(1, { duration: 1000 });
// }, [rippleOpacity,scale]);
// return (
// <View style={{
// width: 200,
// height: 200,
// backgroundColor: 'white',
// alignItems: 'center',
// justifyContent: 'center',
// borderRadius: 25,
// // iOS
// shadowOpacity: 0.2,
// shadowOffset: { width: 0, height: 0 },
// shadowRadius: 20,
// // Android
// elevation: 2,
// }}>
// <Animated.View style={[{
// width: 200,
// height: 200,
// backgroundColor: 'white',
// alignItems: 'center',
// justifyContent: 'center',
// borderRadius: 25,
// // iOS
// shadowOpacity: 0.2,
// shadowOffset: { width: 0, height: 0 },
// shadowRadius: 20,
// // Android
// elevation: 2,
// }, { overflow: 'hidden' }]}>
// <Animated.View style={rStyle} />
// </Animated.View>
// </View>
// );
// }
import React, { useEffect, useRef } from 'react';
import { StyleSheet, Text, View, Image } from 'react-native';
import Animated, { useAnimatedStyle, useDerivedValue, useSharedValue, withSpring, withTiming } from 'react-native-reanimated';
import { SharedElement } from 'react-navigation-shared-element';
import { useSelector } from 'react-redux';
import normalize from '../components/Normalize';
import SpotifyService from '../services/spotify/spotify.service';
import React from 'react';
import { View } from 'react-native';
import Animated from 'react-native-reanimated';
export default function CurrentMusic() {
const transition = useDerivedValue(() => {
return withSpring(value.value);
});
return (
@ -137,7 +34,7 @@ export default function CurrentMusic() {
// Android
elevation: 2,
}, { overflow: 'hidden' }]}>
<Animated.View style={rStyle} />
<Animated.View />
</Animated.View>
</View>
);

@ -1,16 +1,6 @@
import { View, Text, Image, Dimensions, StyleSheet } from 'react-native'
import React, { useEffect, useRef, useState } from 'react'
import Animated, { Extrapolate, interpolate, runOnJS, useAnimatedGestureHandler, useAnimatedStyle, useSharedValue, withRepeat, withSpring, withTiming } from 'react-native-reanimated';
import { PanGestureHandler, PanGestureHandlerGestureEvent } from 'react-native-gesture-handler';
import * as Haptics from 'expo-haptics';
const { width: wWidht } = Dimensions.get("window");
const SCREEN_HEIGHT = Dimensions.get('window').height
const SCREEN_WIDTH = Dimensions.get('window').width
// const width = wWidht *0.75;
// const height = wWidht * (465/264);
// const borderRadius = 24;
import { View } from 'react-native'
import React, { useEffect } from 'react'
import Animated, { interpolate, useAnimatedStyle, useSharedValue, withRepeat, withTiming } from 'react-native-reanimated';
const size = 100
const FladLoading = () => {
@ -23,35 +13,6 @@ const FladLoading = () => {
progresse.value = withRepeat(withTiming(0.01, { duration: 750 }), -1, true);
}, [progresse]);
const breatheStyle = useAnimatedStyle(() => {
const borderRange = interpolate
(progresse.value,
[0, 1],
[(0 * size) / 2, (1 * size) / 2],
);
return {
justifyContent: 'center',
alignItems: 'center',
width: size,
height: size,
shadowColor: "#DA1D1D",
shadowOffset: { width: 0, height: 0 },
shadowOpacity: 1,
shadowRadius: borderRange,
};
});
const breatheStyle2 = useAnimatedStyle(() => {
const borderRange = interpolate
(progresse.value,
[0, 1],
[(0 * size) / 2, (1 * size) / 2],
);
return {
borderRadius: borderRange,
};
});
const breatheStyleSquare = useAnimatedStyle(() => {
const borderRange = interpolate
@ -73,42 +34,16 @@ const FladLoading = () => {
};
});
return (
<View style={{ justifyContent: 'center', alignItems: 'center' }}>
<Animated.View style={[{ backgroundColor: '#B40404', justifyContent: 'center', alignItems: 'center' }, breatheStyleSquare]}>
<Animated.Image source={require('../assets/icons/icon.png')} style={[{ height: size, width: size, borderColor: '#fff', borderRadius: size / 2 }]} />
</Animated.View>
{/* <Animated.View style={[ {backgroundColor : 'green'},breatheStyleSquare]}>
</Animated.View> */}
{/* <Image source={require('../assets/icons/Spotify_-_Animation_1.gif')}/> */}
</View>
);
};
const styles = StyleSheet.create({
card: {
justifyContent: 'center',
alignItems: 'center',
},
image: {
borderRadius: 24,
resizeMode: 'stretch',
},
container: {
flex: 1,
width: '100%',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
}
})
export default FladLoading;

@ -1,5 +1,5 @@
import { useState } from "react";
import { FlatList, ScrollView } from "react-native";
import { ScrollView } from "react-native";
import Music from "../Model/Music";
import { Artist } from "./Artist";
import { StyleSheet } from "react-native";

@ -1,33 +1,24 @@
import { useState } from 'react';
import { View, StyleSheet } from 'react-native'
import { View } from 'react-native'
interface HalfCirlceProps {
backgroundColor: string;
}
const HalfCirlce = ({ backgroundColor }: HalfCirlceProps) => {
const [focused, setFocused] = useState<boolean>(false);
return (
<View style={{
width: RADUIS * 2,
height: RADUIS * 2,
width: RADIUS * 2,
height: RADIUS * 2,
overflow: "hidden",
}}>
<View style={{ backgroundColor: backgroundColor, width: RADUIS * 2, height: RADUIS * 2, borderRadius: RADUIS, }}>
<View style={{ backgroundColor: backgroundColor, width: RADIUS * 2, height: RADIUS * 2, borderRadius: RADIUS, }}>
</View>
</View>
);
};
const styles = StyleSheet.create({
input: {
justifyContent: 'center',
alignItems: 'center',
placeholder: "placeholde"
},
})
export default HalfCirlce;

@ -1,17 +1,4 @@
import { View, StyleSheet, Dimensions, Text, Image, Pressable, TouchableWithoutFeedback, TouchableOpacity, TouchableHighlight, FlatList } from "react-native";
import Animated, {
Layout,
Transition,
ZoomIn,
ZoomOut,
} from "react-native-reanimated";
const { width } = Dimensions.get("window");
const SIZE = width / 3;
import { Feather as Icon } from "@expo/vector-icons";
import Music from "../Model/Music";
import { State, TapGestureHandler } from "react-native-gesture-handler";
import { useRef, useState } from "react";
import { View, StyleSheet, Text, FlatList } from "react-native";
import { RenderCellProps } from "./littleCard";
@ -23,7 +10,6 @@ interface HorizontalFlatListProps {
}
export const HorizontalFlatList = ({ title, data, children: RenderCell }: HorizontalFlatListProps) => {
return (
<View style={styles.similarSection}>
<Text style={styles.similarTitle} >{title}</Text>

@ -2,7 +2,6 @@ import { Dimensions, Platform, PixelRatio } from 'react-native';
const {
width: SCREEN_WIDTH,
height: SCREEN_HEIGHT,
} = Dimensions.get('window');
const scale = SCREEN_WIDTH / 480;

@ -1,7 +1,6 @@
import { View, StyleSheet, Dimensions, Image, Pressable, TouchableWithoutFeedback, TouchableOpacity, TouchableHighlight } from "react-native";
import { View, StyleSheet, Dimensions, TouchableOpacity } from "react-native";
import Animated, {
Layout,
Transition,
ZoomIn,
ZoomOut,
} from "react-native-reanimated";
@ -10,14 +9,12 @@ const { width } = Dimensions.get("window");
const SIZE = width / 3;
import { Feather as Icon } from "@expo/vector-icons";
import Music from "../Model/Music";
import { State, TapGestureHandler } from "react-native-gesture-handler";
import { useRef, useState } from "react";
import { useState } from "react";
interface SelectedCardProps {
artist: Music;
onPress: () => void;
// cheepPosition: string ;(direction: "left" | "right" | "down")
}
export const SelectedCard = ({ artist, onPress }: SelectedCardProps) => {
const [selected, setSeleted] = useState(false);
@ -68,7 +65,5 @@ const styles = StyleSheet.create({
backgroundColor: "white",
borderRadius: 100,
alignItems: "center",
}
});

@ -1,18 +1,8 @@
import { View, Text, Image , Dimensions, StyleSheet, Pressable } from 'react-native'
import React, { useRef, useState } from 'react'
import Animated,{ Extrapolate, interpolate, useAnimatedGestureHandler, useAnimatedStyle, useSharedValue, withSpring } from 'react-native-reanimated';
import { PanGestureHandler, PanGestureHandlerGestureEvent } from 'react-native-gesture-handler';
import * as Haptics from 'expo-haptics';
import { Image , StyleSheet, Pressable } from 'react-native'
import React from 'react'
import Icons from '../../assets/icons/icons/icon';
import Rive, { Fit, RiveRef } from 'rive-react-native';
const {width : wWidht} = Dimensions.get("window");
const SCREEN_HEIGHT = Dimensions.get('window').height
const SCREEN_WIDTH = Dimensions.get('window').width
// const width = wWidht *0.75;
// const height = wWidht * (465/264);
// const borderRadius = 24;
import { RiveRef } from 'rive-react-native';
interface ButtonProps {
name : string;
}

@ -1,5 +1,5 @@
import { useState } from 'react';
import { View, Text, Image, Animated, PanResponder, Dimensions, StyleSheet, ImageBackground, Button, Pressable, TextInput } from 'react-native'
import { View, Text, StyleSheet, TextInput } from 'react-native'
interface InputProps {
name: string;

@ -1,11 +1,10 @@
import { TouchableOpacity, ScrollView, View, Text, StyleSheet, Image, SafeAreaView, FlatList, Animated } from 'react-native';
import { View, Text, StyleSheet, Image } from 'react-native';
export interface RenderCellProps {
image: string;
title: string;
}
export const LittleCard = (props: RenderCellProps) => {
console.log('===============' + props.image + props.title + '==ok============');
return (
<View style={styles.similarContainer}>
<Image source={{ uri: props.image }} style={styles.similarPoster}></Image>

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

@ -1,78 +1,36 @@
import Navigation from './Navigation';
import { StyleSheet, SafeAreaView, AsyncStorage } from 'react-native';
import { AsyncStorage } from 'react-native';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import StartNavigation from './StartNavigation';
import { Provider, useDispatch, useSelector } from 'react-redux';
import store from '../redux/store';
import { useCallback, useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useEffect, useState } from 'react';
import * as SplashScreen from 'expo-splash-screen';
import { View } from 'react-native';
import { ChangeMode, 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';
export default function AuthNavigation() {
//@ts-ignore
const tokenProcesed: boolean = useSelector(state => state.userReducer.loading);
// //@ts-ignore
// const appIsReady: boolean = useSelector(state => state.userReducer.loading);
//@ts-ignore
const isLogin: boolean = useSelector(state => state.userReducer.isLogedIn);
//@ts-ignore
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<Location.LocationObject>();
const [errorMsg, setErrorMsg] = useState('');
// // seems background task but not optimized
// TaskManager.defineTask(LOCATION_TASK_NAME, async ({ data, error }) => {
// if (error) {
// console.log(error);
// return;
// }
// if (data) {
// const { locations } = data;
// // send location updates to server
// console.log(locations);
// }
// });
// const startLocationUpdates = async () => {
// try {
// await Location.startLocationUpdatesAsync(LOCATION_TASK_NAME, {
// accuracy: Location.Accuracy.Balanced,
// timeInterval: 5000, // send location updates every 5 seconds
// foregroundService: {
// notificationTitle: 'Location tracking',
// notificationBody: 'Location tracking is active.',
// },
// });
// } catch (error) {
// console.log(error);
// }
// };
// useEffect(() => {
// startLocationUpdates();
// return () => {
// Location.stopLocationUpdatesAsync(LOCATION_TASK_NAME);
// };
// }, []);
const [setErrorMsg] = useState('');
async function prepare() {
//@ts-ignore
await dispatch(getRefreshToken())
if (tokenProcesed && appIsReady) {
await SplashScreen.hideAsync();
} // await SplashScreen.hideAsync();
}
}
async function ChangeDarkMode() {
@ -91,10 +49,6 @@ export default function AuthNavigation() {
ChangeDarkMode();
prepare();
}, [appIsReady, tokenProcesed]);
// const onStackRootView = useCallback(async () => {
// }, [appIsReady]);
useEffect(() => {
const sendLocationUpdate = async () => {
@ -106,94 +60,19 @@ export default function AuthNavigation() {
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)[]> = {
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('*********************************************************************************************');
currentMusic: currentMusic.id
}
// }
console.log(locationresp);
console.log(currentMusic);
console.log('Sending location update ================================###############');
}
}
else{
console.log(`Sending location update with error ${status} ================================###############`);
else {
setErrorMsg('Permission to access location was denied');
return;
}
@ -201,7 +80,7 @@ export default function AuthNavigation() {
console.log(error);
}
};
const interval = setInterval(sendLocationUpdate, 5000); // send location updates every 5 seconds
const interval = setInterval(sendLocationUpdate, 5000);
return () => {
clearInterval(interval);
};
@ -210,18 +89,9 @@ export default function AuthNavigation() {
return null;
}
// console.log(userToken, "k9 AuthNav")
return (
<SafeAreaProvider onLayout={() => setAppIsReady(true)}>
{isLogin ? (
/* {userToken != null ? ( */
// should set the reference to the function in Navigation to realy perform an on ready
// test purpose
<Navigation />
) :
<StartNavigation />

@ -1,9 +1,6 @@
import React from 'react';
import Favorite from '../screens/Favorite';
import { createStackNavigator } from '@react-navigation/stack';
import { ArtistLayout } from '../components/Genre';
import MusicDetail from '../screens/MusicDetail';
import InfoScreen from '../screens/testPage';
import { createSharedElementStackNavigator } from 'react-navigation-shared-element';
import CurrentMusic from '../components/CurrentMusic';

@ -10,14 +10,11 @@ import normalize from '../components/Normalize';
import FontAwesome from 'react-native-vector-icons/FontAwesome';
import SpotNavigation from './SpotNavigation';
import Login from '../screens/login';
import FladLoading from '../components/FladLoadingScreen';
import { useDispatch, useSelector } from 'react-redux';
import { getFavoritesMusic } from '../redux/actions/appActions';
import { GraphicalCharterDark } from '../assets/GraphicalCharterDark';
import { GraphicalCharterLight } from '../assets/GraphicalCharterLight';
import { getCurrentUserMusic } from '../redux/thunk/spotThunk';
import SpotifyService from '../services/spotify/spotify.service';
// import { fetchFavoritesMusic } from '../redux/thunk/spotThunk';
export default function Navigation() {
const isDark = useSelector(state => state.userReducer.dark);
@ -35,12 +32,6 @@ export default function Navigation() {
//@ts-ignore
const favoritesMusicLength: number = useSelector(state => state.appReducer.favoriteMusic.length);
const dispatch = useDispatch();
// useEffect(() => {
// const loadFavoritesMusics = async () => {
// await dispatch(fetchFavoritesMusic());
// };
// loadFavoritesMusics();
// }, [dispatch]);
const token = "BQBNdaYRkD3GAOFASk8uc-l72zVwQeQ0sFB4GJnkBGudsJHnuAXd4eIWb78gbFLKZeBoHrWpHxMeSmqvHk75Utg9fsOJp7XyJfm-tAlgGhUQ-xiUM8rXTpa9k3M40BMSnujPDrap_O1ChCyGhBWYVHDd2t67qY0NVDvCJ4Qz7LucJJdgu1BN838qXTScQV90zriO8lp6Rjx6SsWov_fMZTyadzxebYIiQ-VDQDs63gUordThas-jFlAHLgJlqPhVOHJ1WaZt-_oLhgY3fk4bhORkyeAFZVRTnjw38A70b0eZU3ziQkOYW6w7kN__tzgP5gis0Y8mEIiUyTnyuQ"
const sheet = async () => {
const service = new SpotifyService(token)

@ -1,9 +1,6 @@
import React, { Component } from 'react';
import FavoritePage from '../screens/favorite';
import React from 'react';
import { createStackNavigator } from '@react-navigation/stack';
import SpotPage from '../screens/spot'
import { createSharedElementStackNavigator } from "react-navigation-shared-element";
import SpotDetailsPage from '../screens/SpotDetailsPage';
import MusicDetail from '../screens/MusicDetail';
@ -27,13 +24,6 @@ export default function SpotNavigation() {
name="DetailsSpot"
component={MusicDetail}
/>
{/* <Stack.Screen
name="DetailsSpot"
component={SpotDetailsPage}
sharedElements={(route) => {
return [route.params.spot.name]
}}
/> */}
</Stack.Navigator>
)
}

@ -4,33 +4,8 @@ import Register from '../screens/Register';
import Onboarding from '../components/Onboarding';
import { createStackNavigator } from '@react-navigation/stack';
import { NavigationContainer } from '@react-navigation/native';
import { useDispatch, useSelector } from 'react-redux';
import * as SplashScreen from 'expo-splash-screen';
import { getRefreshToken } from '../redux/thunk/authThunk';
import { ArtistLayout } from '../components/Genre';
export default function StartNavigation() {
// //@ts-ignore
// const appIsReady : boolean = useSelector(state => state.userReducer.loading);
// const dispatch = useDispatch();
// useEffect(() => {
// async function prepare() {
// //@ts-ignore
// await dispatch(getRefreshToken());
// }
// prepare();
// }, [dispatch]);
// const onStackRootView = useCallback(async () => {
// if (appIsReady) {
// await SplashScreen.hideAsync();
// }
// }, [appIsReady]);
// if (!appIsReady) {
// return null;
// }
const Stack = createStackNavigator();
return (
<NavigationContainer>

@ -19,13 +19,13 @@
"axios": "^1.2.6",
"buffer": "^6.0.3",
"expo": "~47.0.12",
"expo-asset": "^8.7.0",
"expo-asset": "~8.7.0",
"expo-auth-session": "~3.8.0",
"expo-av": "~13.0.3",
"expo-blur": "~12.0.1",
"expo-cli": "^6.3.0",
"expo-haptics": "~12.0.1",
"expo-image-picker": "^14.1.1",
"expo-image-picker": "~14.0.2",
"expo-linear-gradient": "~12.0.1",
"expo-location": "~15.0.1",
"expo-random": "~13.0.0",
@ -39,9 +39,9 @@
"react-native-gesture-handler": "~2.8.0",
"react-native-modal": "^13.0.1",
"react-native-reanimated": "~2.12.0",
"react-native-safe-area-context": "^4.4.1",
"react-native-safe-area-context": "4.4.1",
"react-native-screens": "~3.18.0",
"react-native-shared-element": "^0.8.8",
"react-native-shared-element": "0.8.4",
"react-native-svg": "13.4.0",
"react-native-vector-icons": "^9.2.0",
"react-native-web": "~0.18.9",

@ -1,7 +1,5 @@
import Music from "../../Model/Music";
import { Spot } from "../../Model/Spot";
import { favoritesTypes } from "../types/favoritesTypes";
import {spotTypes} from "../types/spotTypes";
export const getFavoritesMusic = (favoritesMusic: Music[]) => {
return {
@ -11,7 +9,7 @@ export const getFavoritesMusic = (favoritesMusic: Music[]) => {
}
export const addFavoritesMusic = (favoritesMusic: Music) => {
return {
type: favoritesTypes.ADD_FAVORITE_MUSICS ,
type: favoritesTypes.ADD_FAVORITE_MUSICS,
playload: favoritesMusic,
};
}

@ -1,18 +1,18 @@
import Music from "../../Model/Music";
import { Spot } from "../../Model/Spot";
import { spotifyTypes } from "../types/spotifyTypes";
import {spotTypes} from "../types/spotTypes";
import { spotTypes } from "../types/spotTypes";
export const setSpotList = (spotList: Spot[]) => {
return {
type: spotTypes.FETCH_SPOT,
playload: spotList,
};
}
}
export const setUserCurrentMusic = (currentMusic: Music) => {
export const setUserCurrentMusic = (currentMusic: Music) => {
return {
type: spotifyTypes.GET_USER_CURRENT_MUSIC,
playload: currentMusic,
};
}
}

@ -13,14 +13,8 @@ export interface CredentialsRegister {
idFlad: string,
idSpotify: string
}
// export const setLoggedInState = loggedInState => (
// {
// type: types.SET_LOGGED_IN_STATE,
// loggedInState,
// }
// );
export const setLoginState = (userJson: any) => {
const user = new User(userJson.data.idFlad,userJson.data.idSpotify,userJson.data.email,new Date(),userJson.data.name, require('../../assets/images/jul.png'));
const user = new User(userJson.data.idFlad, userJson.data.idSpotify, userJson.data.email, new Date(), userJson.data.name, require('../../assets/images/jul.png'));
return {
type: userTypes.LOGIN,
playload: user

@ -1,10 +1,11 @@
import AsyncStorage from '@react-native-async-storage/async-storage';
import { User } from "../../Model/User";
import { userTypes } from "../types/userTypes";
const initialState = {
loading: false,
user: User, // for user object
userFladToken: "", // for storing the JWT
user: User,
userFladToken: "",
userSpotifyToken: null,
error: null,
isLogedIn: false,
@ -15,11 +16,8 @@ const initialState = {
const userReducer = (state = initialState, action: any) => {
switch (action.type) {
// just for the navigation and speciafly use
// and
case userTypes.RESTORE_TOKEN:
const resp = (action.playload == "" ? false : true)
console.log(resp, "si il ya le tokennen ou passssssssssss")
return {
...state,
userFladToken: action.playload,
@ -27,12 +25,7 @@ const userReducer = (state = initialState, action: any) => {
isLogedIn: resp,
};
case userTypes.LOGIN:
AsyncStorage.setItem('dark', JSON.stringify(false)).then(() => {
console.log('La nouvelle clé et sa valeur ont été créées dans le localstorage');
});
console.log("++++++++++++++++++++++++++++++++++++++userRducer+++++++++++++++++++++++++++++3");
console.log(action.playload, "LOOGGIIINN");
console.log("++++++++++++++++++++++++++++++++++++++userRducer+++++++++++++++++++++++++++++3");
AsyncStorage.setItem('dark', JSON.stringify(false)).then(() => { });
return {
...state,
user: action.playload,
@ -41,13 +34,7 @@ const userReducer = (state = initialState, action: any) => {
dark: false
};
case userTypes.SIGNUP:
AsyncStorage.setItem('dark', JSON.stringify(false)).then(() => {
console.log('La nouvelle clé et sa valeur ont été créées dans le localstorage');
});
console.log("++++++++++++++++++++++++++++++++++++++userRducer+++++++++++++++++++++++++++++3");
console.log(action.playload, "SIGNNNNNUUUUPPPPPPP");
console.log("++++++++++++++++++++++++++++++++++++++userRducer+++++++++++++++++++++++++++++3");
AsyncStorage.setItem('dark', JSON.stringify(false)).then(() => { });
return {
...state,
user: action.playload,
@ -56,9 +43,7 @@ const userReducer = (state = initialState, action: any) => {
dark: false
};
case userTypes.USER_LOGOUT:
AsyncStorage.removeItem('dark').then(() => {
console.log('La clé a été supprimée du localstorage');
});
AsyncStorage.removeItem('dark').then(() => { });
return {
...state,
user: null,

@ -1,14 +1,8 @@
//Define your action creators that will be responsible for asynchronous operations
import axios from "axios";
import { json } from "express";
import { useEffect } from "react";
import { API_URL } from "../../fladConfig";
import { Credentials, CredentialsRegister, restoreToken, setLoginState, UserLogout, userChangeMode, userSignUp, ChangeErrorLogin, ChangeErrorSignup } from "../actions/userActions";
import * as SecureStore from 'expo-secure-store';
import { User } from "../../Model/User";
import { UserFactory } from "../../Model/factory/UserFactory";
import * as ImagePicker from 'expo-image-picker';
const key = 'userToken';
@ -16,8 +10,6 @@ export const registerUser = (resgisterCredential: CredentialsRegister) => {
//@ts-ignore
return async dispatch => {
try {
console.log(resgisterCredential);
const config = {
headers: {
'Content-Type': 'application/json',
@ -32,7 +24,6 @@ export const registerUser = (resgisterCredential: CredentialsRegister) => {
if (resp.data.token) {
console.log(resp.data.token);
const token = resp.data.token;
// await SecureStore.setItemAsync(key, token);
const headers = {
'Authorization': 'Bearer ' + token
};
@ -40,23 +31,12 @@ export const registerUser = (resgisterCredential: CredentialsRegister) => {
"https://flad-api-production.up.railway.app/api/users",
{ headers }
)
dispatch(userSignUp(UserFactory.JsonToModel(user.data))); // our action is called here
// console.log(user.data);
// dispatch(setLoginState(user.data) ); // our action is called here
dispatch(userSignUp(UserFactory.JsonToModel(user.data)));
} else {
console.log('Login Failed', 'Username or Password is incorrect');
}
// if (resp.data.msg === 'success') { // response success checking logic could differ
// await SecureStore.setItemAsync(key, resp.data.token);
// dispatch(setLoginState(resp.data.user) ); // our action is called here
// } else {
// console.log('Login Failed', 'Username or Password is incorrect');
// }
} catch (error) {
console.log('Error---------', error);
dispatch(ChangeErrorSignup())
}
}
@ -73,19 +53,13 @@ export const userLogin = (loginCredential: Credentials) => {
'Content-Type': 'application/json',
},
}
// const resppp = await axios.get(`${API_URL}/toto`);
// console.log(resppp.data, "sddsd");
const resp = await axios.post(
"https://flad-api-production.up.railway.app/api/users/login",
loginCredential,
config
)
console.log("====================================================================================")
console.log(resp.data)
console.log("====================================================================================")
if (resp.data.token) {
console.log(resp.data.token);
const token = resp.data.token;
await SecureStore.setItemAsync(key, token);
const headers = {
@ -96,17 +70,15 @@ export const userLogin = (loginCredential: Credentials) => {
"https://flad-api-production.up.railway.app/api/users",
{ headers }
)
// dispatch(setLoginState(resp.data.user) ); // our action is called here
console.log(user.data);
dispatch(setLoginState(user.data)); // our action is called here
dispatch(setLoginState(user.data));
} else {
console.log('Login Failed', 'Username or Password is incorrect');
}
} catch (error) {
dispatch(ChangeErrorLogin())
console.log('Error---------', error);
}
}
}
@ -118,19 +90,10 @@ export const getRefreshToken = () => {
let userToken: string | null = await SecureStore.getItemAsync(key);
if (userToken) {
console.log("==========key2 ==================");
console.log(userToken);
console.log("==========key ==================");
console.log("==========on devrais être laaaa ==================");
dispatch(restoreToken(userToken));
} else {
console.log("==========OOOOOORRRRRRRRHHHHHHHHHH ==================");
const empty = "";
dispatch(restoreToken(empty));
console.log("merddee");
}
} catch (e) {
console.log('Error---------', e);
@ -164,20 +127,3 @@ export const ChangeImageUserCurrent = (value: ImagePicker) => {
dispatch(userChangeImage(value));
}
}
// const logIn = (email, password) => {
// const action = (dispatch) => {
// if (email === user.email && password === user.password) {
// dispatch(setLoggedInState(true));
// return true;
// }
// dispatch(setLoggedInState(false));
// return false;
// };
// return action;
// };
// better
async function save(key: string, value: string) {
await SecureStore.setItemAsync(key, value);
}

@ -1,30 +1,17 @@
import axios from "axios";
import { Spot } from "../../Model/Spot";
export const likeSpot = async (spot : 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){
axios.post("osdj").then(responce => {
if (responce.status == 200) {
dispatch(true);
} } ).catch(error => {
}
}).catch(error => {
console.log("something goes wrong while searching : " + error);
;})
;
})
};
}
}

@ -1,52 +1,30 @@
//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";
import Music from "../../Model/Music";
import { getFavoritesMusic } from "../actions/appActions";
const key = 'userToken';
export type CreateSpotReqBody = {
id : string;
name : string;
artist : string;
linkCover : string;
user : string;
id: string;
name: string;
artist: string;
linkCover: string;
user: string;
}
export const getSpotList = (resuestHandler : SpotifyService) => {
export const getSpotList = (resuestHandler: SpotifyService) => {
//@ts-ignore
return async dispatch => {
//@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<Position>((resolve, reject) => {
// Geolocation.getCurrentPosition(resolve, reject);
// });
//@ts-ignore
var userToken : string = await SecureStore.getItemAsync(key);
var userToken: string = await SecureStore.getItemAsync(key);
const headers = {
'Authorization': 'Bearer ' + userToken};
'Authorization': 'Bearer ' + userToken
};
const data = await axios.get(
"https://flad-api-production.up.railway.app/api/users/nextTo",
{headers}
{ headers }
)
if (data.data.token) {
const spotsData: { [userId: string]: string } = {};
@ -69,19 +47,19 @@ return async dispatch => {
} catch (error) {
console.log('Error---------', error);
}
}
}
}
export const getCurrentUserMusic = (resuestHandler : SpotifyService)=> {
export const getCurrentUserMusic = (resuestHandler: SpotifyService) => {
//@ts-ignore
return async dispatch => {
try {
//@ts-ignore
var currentTrackResponse = await resuestHandler.getUserCurrentMusic();
if (!currentTrackResponse){
if (!currentTrackResponse) {
const recentlyTrackResponse = await resuestHandler.getUserRecentlyPlayedMusic();
if(!recentlyTrackResponse){
if (!recentlyTrackResponse) {
throw new Error;
}else{
} else {
currentTrackResponse = recentlyTrackResponse;
}
}
@ -93,59 +71,9 @@ export const getCurrentUserMusic = (resuestHandler : SpotifyService)=> {
}
}
}
export const searchMusic = async (resuestHandler : SpotifyService,search: string) => {
//
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;
// };
export const searchMusic = async (resuestHandler: SpotifyService, search: string) => {
return async (dispatch) => {
return resuestHandler.searchMusic(search).then(musics => dispatch((musics))).catch(err => console.log("something goes wrong while searching : " + err));
};
}
// export const fetchFavoritesMusic = () => {
// //@ts-ignore
// return async dispatch => {
// const MovieList: Music[] = [
// // new Music("La pharmacie", "Jul",require("../assets/images/jul.png")),
// // new Music("Deux frères", "PNL", require("../assets/images/pnl.png")),
// new Music("Bambina", "PNL", "https://upload.wikimedia.org/wikipedia/en/a/a0/PNL_-_Dans_la_l%C3%A9gende.png"),
// new Music("Stratos", "Kekra", "https://images.genius.com/ddc9cadedd1d4cef0860aaa85af9cd46.705x705x1.png"),
// new Music("Autobahn", "Sch", "https://images.genius.com/83b6c98680d38bde1571f6b4093244b5.1000x1000x1.jpg"),
// 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"),
// ] ;
// dispatch(getFavoritesMusic(MovieList));
// }
// }
// export const getSpotList = () => {
// return async dispatch => {
// try {
// const spotPromise = await fetch(`${API_URL}/spotify/spot`);
// const spotJson = await spotPromise.json();
// const spotList: Spot[] = spotJson.map(spot => {
// } );
// dispatch(setNounoursList(spotList));
// } catch (error) {
// console.log('Error---------', error);
// }
// }
// }

@ -1,3 +1,3 @@
export const discoveriesTypes = {
FETCH_DISCOVERIES : 'FETCH_DISCOVERIES',
}
FETCH_DISCOVERIES: 'FETCH_DISCOVERIES',
}

@ -1,7 +1,5 @@
export const favoritesTypes = {
GET_FAVORITE_MUSICS : 'GET_FAVORITE_MUSICS',
ADD_FAVORITE_MUSICS : 'ADD_FAVORITE_MUSICS',
REMOVE_FAVORITE_MUSICS : 'REMOVE_FAVORITE_MUSICS',
}
GET_FAVORITE_MUSICS: 'GET_FAVORITE_MUSICS',
ADD_FAVORITE_MUSICS: 'ADD_FAVORITE_MUSICS',
REMOVE_FAVORITE_MUSICS: 'REMOVE_FAVORITE_MUSICS',
}

@ -1,5 +1,5 @@
export const playlistTypes = {
FETCH_USER_PLAYLISTS : 'FETCH_SPOT',
SAVE_IN_FLAD_PLAYLIST : 'SAVE_IN_FLAD_PLAYLIST',
FETCH_FLAD_PLAYLIST : 'FETCH_SPOT',
FETCH_USER_PLAYLISTS: 'FETCH_SPOT',
SAVE_IN_FLAD_PLAYLIST: 'SAVE_IN_FLAD_PLAYLIST',
FETCH_FLAD_PLAYLIST: 'FETCH_SPOT',
}

@ -1,3 +1,3 @@
export const spotTypes = {
FETCH_SPOT : 'FETCH_SPOT',
}
FETCH_SPOT: 'FETCH_SPOT',
}

@ -1,3 +1,3 @@
export const spotifyTypes = {
GET_USER_CURRENT_MUSIC : 'GET_USER_CURRENT_MUSIC',
GET_USER_CURRENT_MUSIC: 'GET_USER_CURRENT_MUSIC',
}

@ -1,18 +1,16 @@
import React, { useEffect, useState } from 'react';
import React from 'react';
import { Image, StyleSheet, Text, View, FlatList, ScrollView, TouchableOpacity, TouchableHighlight, SafeAreaView } from 'react-native';
import CardMusic from '../components/CardMusic';
import normalize from '../components/Normalize';
import Music from '../Model/Music'
import FladyComponent from '../components/FladyComponent';
import { useNavigation } from "@react-navigation/native";
import { useDispatch, useSelector } from 'react-redux';
import { getFavoritesMusic } from '../redux/actions/appActions';
import { useSelector } from 'react-redux';
import { SharedElement } from 'react-navigation-shared-element';
import { GraphicalCharterDark } from '../assets/GraphicalCharterDark';
import { GraphicalCharterLight } from '../assets/GraphicalCharterLight';
export default function favoritePage() {
const dispatch = useDispatch();
//Dark Mode
const isDark = useSelector(state => state.userReducer.dark);
const style = isDark ? GraphicalCharterDark : GraphicalCharterLight;
@ -29,25 +27,6 @@ export default function favoritePage() {
const navigueToDetail = (music: any) => {
navigation.navigate("MusicDetail", { "music": music })
};
// to do
const [filteredDataSource, setFilteredDataSource] = useState<Music[]>([]);
const [search, setSearch] = useState('');
const searchMusic = (text: string) => {
if (text) {
const newData = favoritesMusic.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);
}
};
const styles = StyleSheet.create({
mainSafeArea: {
flex: 1,

@ -18,7 +18,7 @@ export default function loginPage() {
const [sound, setSound] = useState<Audio.Sound>();
const [rememberMe, setRememberMe] = useState(false);
const navigation = useNavigation();
// @ts-ignore
const failedLogin = useSelector(state => state.userReducer.failedLogin);
const [username, setUsername] = useState('');
@ -29,8 +29,6 @@ export default function loginPage() {
require('../assets/sounds/Click.mp3')
);
setSound(sound);
console.log('Playing Sound');
await sound.playAsync();
}
const dispatch = useDispatch();

@ -1,28 +1,17 @@
import { NavigationProp, RouteProp, useNavigation } from "@react-navigation/native";
import { View, Text, Image, StyleSheet, Dimensions, useWindowDimensions, Button, TouchableOpacity, ScrollView, Pressable } from "react-native";
import Animated, { interpolate, SensorType, useAnimatedSensor, useAnimatedStyle, useDerivedValue, useSharedValue, Value, withSpring, withTiming } from "react-native-reanimated";
import { BlurView } from 'expo-blur';
import qs from "qs";
import axios from "axios";
import { Buffer } from 'buffer';
import { useNavigation } from "@react-navigation/native";
import { View, Text, Image, StyleSheet, TouchableOpacity, ScrollView, Pressable } from "react-native";
import Animated, { interpolate, SensorType, useAnimatedSensor, useAnimatedStyle, withSpring } from "react-native-reanimated";
import { Audio } from 'expo-av';
import { useEffect, useState } from "react";
import normalize from '../components/Normalize';
import { State, TapGestureHandler } from "react-native-gesture-handler";
import { RequestHandler } from "../services/spotify/spotifyRequestHandler/utils";
import { FetchRequest } from "expo-auth-session/build/Fetch";
import Music from "../Model/Music";
import SpotifyService from "../services/spotify/spotify.service";
import { SharedElement } from "react-navigation-shared-element";
import { SafeAreaView } from "react-native-safe-area-context";
import { LinearGradient } from "expo-linear-gradient";
import Icons from "../assets/icons/icons/icon";
import FontAwesome from 'react-native-vector-icons/FontAwesome';
import { Feather as Icon } from "@expo/vector-icons";
import { HorizontalFlatList } from "../components/HorizontalFlatList";
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";
@ -50,13 +39,6 @@ const MusicDetail = ({ route }) => {
getSimilarTrack();
}, [testtoken]);
// const getSimilarTrack = async () => {
// const service = new SpotifyService(testtoken);
// const simularMusic = await service.getSimilarTrack(currentspot.id, 5, 'FR');
// console.log("suggesstd", simularMusic)
// setSimularMusic(simularMusic);
// }
const getSimilarTrack = async () => {
try {
const service = new SpotifyService(testtoken);
@ -65,7 +47,6 @@ const MusicDetail = ({ route }) => {
setSimularMusic(simularMusic);
} catch (error) {
console.error('Error ================ in getSimilarTrack', error);
// Handle the error here.
}
}
@ -123,53 +104,6 @@ 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}>
@ -180,13 +114,7 @@ const MusicDetail = ({ route }) => {
uri: currentspot.image,
}}
></Image>
{/* <LinearGradient
// Background Linear Gradient
colors={['rgba(0,0,0,0.8)', 'transparent']}
/> */}
<LinearGradient style={styles.gradientFade}
// Button Linear Gradient
colors={['rgba(56,56,56,0)', 'rgba(14,14,14,1)']}>
</LinearGradient>
</View>
@ -194,7 +122,6 @@ const MusicDetail = ({ route }) => {
<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 }}> */}
<View>
<Animated.Image
@ -203,9 +130,6 @@ const MusicDetail = ({ route }) => {
}}
style={[
{
// width: 370,
// width: 400,
width: normalize(429),
height: normalize(429),
borderRadius: 24,

@ -9,8 +9,6 @@ import { registerUser } from '../redux/thunk/authThunk';
import { useDispatch, useSelector } from 'react-redux';
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
@ -34,35 +32,26 @@ async function save(key: string, value: string) {
await SecureStore.setItemAsync(key, value);
}
export default function InscriptionPage() {
const [sound, setSound] = useState<Audio.Sound>();
const [rememberMe, setRememberMe] = useState(false);
const navigation = useNavigation();
const [spotifyToken, setSpotifyToken] = useState('');
const [spotifyID, setSpotifyIds] = useState('')
const failedSignup = useSelector(state => state.userReducer.failedSignup);
async function playSound() {
console.log('Loading Sound');
const { sound } = await Audio.Sound.createAsync(
require('../assets/sounds/Click.mp3')
);
setSound(sound);
console.log('Playing Sound');
await sound.playAsync();
}
const [username, setUsername] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const toggleRememberMe = () => {
setRememberMe(!rememberMe);
}
//spotify auth
const [request, response, promptAsync] = useAuthRequest(
const [response] = useAuthRequest(
{
responseType: AuthSession.ResponseType.Token,
clientId: '1f1e34e4b6ba48b388469dba80202b10',
@ -99,66 +88,12 @@ export default function InscriptionPage() {
dispatch(registerUser(credentials))
playSound()
}
const scopesArr = ['user-read-private', 'user-read-email', 'user-read-playback-state', 'user-read-currently-playing', 'user-read-recently-played', 'playlist-modify-public', 'ugc-image-upload', 'user-modify-playback-state'];
const scopes = scopesArr.join(' ');
//work so use this for my implementation
const getAuthorizationCode = async () => {
try {
const redirectUrl = "https://auth.expo.io/@anonymous/FLAD-7eafd441-fd6b-4fb6-924c-ec2b0ed5ce6d"; //this will be something like https://auth.expo.io/@your-username/your-app-slug
const result = await AuthSession.startAsync({
authUrl:
'https://accounts.spotify.com/authorize' +
'?response_type=code' +
'&client_id=' +
"1f1e34e4b6ba48b388469dba80202b10" +
(scopes ? '&scope=' + encodeURIComponent(scopes) : '') +
'&redirect_uri=' +
encodeURIComponent(redirectUrl),
})
console.log("=================grant code ==============<");
console.log(result);
console.log("=================grant code ==============<");
return result.params.code;
} catch (err) {
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;
} catch (err) {
console.error(err)
}
}
const getTokens2 = async () => {
try {
const authorizationCode = await getAuthorizationCode2() //we wrote this function above
console.log(authorizationCode, "shhhhhhhhhhhhhheeeeeeeeeeeeeeeetttttttttttt");
const response = await fetch('https://flad-api-production.up.railway.app/api/spotify/callback');
const responseJson = await response.json();
console.log(responseJson, "okkkkkkkkkkkkkkk");
// destructure the response and rename the properties to be in camelCase to satisfy my linter ;)
const {
access_token: accessToken,
refresh_token: refreshToken,
expires_in: expiresIn,
} = responseJson;
await setSpotifyToken(accessToken);
@ -168,76 +103,6 @@ export default function InscriptionPage() {
console.error(err);
}
}
const getTokens = async () => {
try {
const authorizationCode = await getAuthorizationCode() //we wrote this function above
console.log(authorizationCode, "shhhhhhhhhhhhhheeeeeeeeeeeeeeeetttttttttttt");
const response = await fetch('https://accounts.spotify.com/api/token', {
method: 'POST',
headers: {
Authorization: 'Basic ' + (Buffer.from('1f1e34e4b6ba48b388469dba80202b10' + ':' + '779371c6d4994a68b8dd6e84b0873c82').toString('base64')),
'Content-Type': 'application/x-www-form-urlencoded',
},
body: `grant_type=authorization_code&code=${authorizationCode}&redirect_uri=https://auth.expo.io/@anonymous/FLAD-7eafd441-fd6b-4fb6-924c-ec2b0ed5ce6d`,
});
const responseJson = await response.json();
console.log(responseJson, "okkkkkkkkkkkkkkk");
// destructure the response and rename the properties to be in camelCase to satisfy my linter ;)
const {
access_token: accessToken,
refresh_token: refreshToken,
expires_in: expiresIn,
} = responseJson;
await setSpotifyToken(accessToken);
save(MY_SECURE_AUTH_STATE_KEY, accessToken);
testService(accessToken);
console.log(spotifyToken);
} catch (err) {
console.error(err);
}
}
const testService = async (token: string) => {
try {
const serviceTest = new SpotifyService(token);
console.log("==============Test Service 1 ============");
const respSearch = await serviceTest.searchMusic("Parapluie Tiakola");
console.log("===================repoonce=========================");
console.log(respSearch);
console.log("============================================");
console.log("==============Test Service 2 ============");
const respFull = await serviceTest.getMusicById(respSearch[0].id);
console.log("===================repoonce=========================");
console.log(respFull);
console.log("============================================");
console.log("==============Test Service 3 ============");
const respSimilar = await serviceTest.getSimilarTrack(respSearch[0].id);
console.log("===================repoonce=========================");
console.log(respSimilar);
console.log("============================================");
console.log("==============Test Service 4 ============");
const respCurrent = await serviceTest.getUserCurrentMusic();
console.log("===================repoonce=========================");
console.log(respCurrent);
console.log("============================================");
console.log("==============Test Service 5 ============");
const respRecently = await serviceTest.getUserRecentlyPlayedMusic();
console.log("===================repoonce=========================");
console.log(respRecently);
console.log("============================================");
} catch (error) {
console.log("==============Test Service Error============");
console.error(error);
console.log("============================================");
}
}
return (
<DismissKeyboard>
<View style={styles.container}>

@ -1,4 +1,4 @@
import React, { useEffect, useRef, useState } from 'react';
import React, { useRef, useState } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { View, StyleSheet, Text, Image, TouchableWithoutFeedback, Keyboard, TouchableOpacity, SafeAreaView } from 'react-native';
import { Svg, Path } from 'react-native-svg';
@ -11,8 +11,6 @@ import { ChangeMode, DeleteToken } from '../redux/thunk/authThunk';
import { useSelector } from 'react-redux';
import { GraphicalCharterDark } from '../assets/GraphicalCharterDark';
import { GraphicalCharterLight } from '../assets/GraphicalCharterLight';
import SpotifyService from '../services/spotify/spotify.service';
import { getCurrentUserMusic } from '../redux/thunk/spotThunk';
// @ts-ignore
const DismissKeyboard = ({ children }) => (
@ -67,9 +65,8 @@ export default function Setting() {
const toggleLocalisation =
() => setIsCheckedLocalisation(value => !value);
//Style
//Style
const styles = StyleSheet.create({
mainSafeArea: {
flex: 1,

@ -11,7 +11,6 @@ import * as ImagePicker from 'expo-image-picker';
import { SafeAreaView } from 'react-native-safe-area-context';
import { GraphicalCharterDark } from '../assets/GraphicalCharterDark';
import { GraphicalCharterLight } from '../assets/GraphicalCharterLight';
import AsyncStorage from '@react-native-async-storage/async-storage';
// @ts-ignore
const DismissKeyboard = ({ children }) => (
@ -22,15 +21,12 @@ const DismissKeyboard = ({ children }) => (
export default function SettingProfil() {
//Dark Mode
const dispatch = useDispatch();
// @ts-ignore
const isDark = useSelector(state => state.userReducer.dark);
// @ts-ignore
const UserCurrent = useSelector(state => state.userReducer.user);
const style = isDark ? GraphicalCharterDark : GraphicalCharterLight;
const navigation = useNavigation();
const [currentIndex, setCurrentIndex] = useState(0);
const [isModalVisible, setIsModalVisible] = React.useState(false);
useEffect(() => {
@ -38,13 +34,9 @@ export default function SettingProfil() {
});
const handleModal = () => setIsModalVisible(() => !isModalVisible);
// @ts-ignore
const viewableItemsChanged = useRef(({ viewableItems }) => {
setCurrentIndex(viewableItems[0].index);
}).current;
const pickImage = async () => {
// No permissions request is necessary for launching the image library
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,

@ -1,31 +1,17 @@
import { SharedElement } from "react-navigation-shared-element";
import { NavigationProp, RouteProp } from "@react-navigation/native";
import { View, Text, Image, StyleSheet, Dimensions, useWindowDimensions, Button, TouchableOpacity, SafeAreaView } from "react-native";
import Animated, { interpolate, SensorType, useAnimatedSensor, useAnimatedStyle, useDerivedValue, useSharedValue, Value, withSpring, withTiming } from "react-native-reanimated";
import { BlurView } from 'expo-blur';
import qs from "qs";
import axios from "axios";
import { Buffer } from 'buffer';
import { View, Text, StyleSheet, Button, TouchableOpacity, SafeAreaView } from "react-native";
import Animated, { interpolate, SensorType, useAnimatedSensor, useAnimatedStyle, useSharedValue, withSpring } from "react-native-reanimated";
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";
import { theService } from "../App";
interface SpotProps {
spot: { name: string, sourceUrl: string, index: number };
}
const halfPi = Math.PI / 2;
// const {width : wWidht} = Dimensions.get("window");
//@ts-ignore
const SpotDetailsPage = ({ route }) => {
const { width, height } = useWindowDimensions();
console.log(route);
const spot: { name: string, sourceUrl: string, index: number } = route.params.spot;
const [currentspot, setCurrentspot] = useState(spot);
const [currentspot] = useState(spot);
const [sound, setSound] = useState(null);
const [isPlaying, setIsPlaying] = useState(false);
@ -34,51 +20,10 @@ const SpotDetailsPage = ({ route }) => {
loader.value = isPlaying ? 1 : 0
}, [isPlaying, loader]);
const transition = useDerivedValue(() => {
return withTiming(loader.value, { duration: 1000 })
}
)
// const styleAniamatedButton = useAnimatedStyle(() => {
// const verticalAxis =interpolate(
// transition.value,
// [0,1],
// [circumference, 0]
// )
// return {
// top : withSpring( verticalAxis),
// left : withSpring(horizontalAxis),
// };
// })
const trackPreviewUrl = 'https://p.scdn.co/mp3-preview/08ef3b9d6dbd6bab233f5e9ca564091902767f71?cid=774b29d4f13844c495f206cafdad9c86';
const playTrackPreview = async () => {
console.log("===============================================================================================================");
console.log('get in Sound');
const { sound } = await Audio.Sound.createAsync({ uri: trackPreviewUrl });
//@ts-ignore
setSound(sound);
console.log('Playing Sound');
await sound.playAsync();
setIsPlaying(true);
// const soundObject = new Audio.Sound();
// try {
// await soundObject.loadAsync({ uri: trackPreviewUrl });
// await soundObject.playAsync();
// setIsPlaying(true);
// } catch (error) {
// console.log('Error loading sound:', error);
// }
};
const handlePlaySound = async () => {
if (sound === null) {
const { sound: newSound } = await Audio.Sound.createAsync(
@ -104,22 +49,16 @@ const SpotDetailsPage = ({ route }) => {
};
useEffect(() => {
return sound ? () => {
console.log('Unloading Sound');
//@ts-ignore
sound.unloadAsync();
}
: undefined;
}, [sound]);
// useEffect(() => {
// if(isPlaying){
// }
// })
console.log(spot);
const sensor = useAnimatedSensor(SensorType.ROTATION);
const styleAniamatedImage = useAnimatedStyle(() => {
const { yaw, pitch, roll } = sensor.sensor.value;
const { pitch, roll } = sensor.sensor.value;
const verticalAxis = interpolate(
pitch,
[-halfPi, halfPi],
@ -136,92 +75,19 @@ const SpotDetailsPage = ({ route }) => {
};
})
const CLIENT_ID = "1f1e34e4b6ba48b388469dba80202b10";
const CLIENT_SECRET = "779371c6d4994a68b8dd6e84b0873c82";
const spotify = "BQA2IAFZ-7ta4-_4_Uqdcdrqi_peE6Hlf1jwxFqjXTbwes0z8xgVGx0rE3zv4cQlusd1ILJhRwkxzPsL1YakzSvCxaTI1P7kOzBrrMqlkDgk4vlFvzLjScB0hBLULbpZyn3ylgx4RyZBEWfmc24wZPQOsrJU58AYCveA52UxYVSIc_Frr7LZyRmwjzGB68MPZeBD"
var authOptions = {
method: 'GET',
url: 'https://api.spotify.com/v1/me/player/currently-playing',
headers: {
'Authorization': 'Bearer ' + spotify,
'Content-Type': 'application/json',
'market': 'FR',
},
json: true
};
var id = '0cFS3AMF9Lhj3CNoFvwjvY'
const requestor = new RequestHandler()
const getCurrentTrack = async () => {
try {
// const opt: FetchRequest = { headers: Record }
// requestor.spotifyFetch(`tracks${id}`,)
theService.getMusicById(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;
// 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;
// var GetTrackOptions = {
// method: 'GET',
// url: 'https://api.spotify.com/v1/tracks/'+id,
// headers: {
// 'Authorization': 'Bearer ' + spotify,
// 'Content-Type' : 'application/json',
// 'market' : 'FR',
// },
// json: true
// };
// console.log("============");
// const music = await axios(GetTrackOptions);
// console.log("================================"+music.data+ "================================");
// currentspot.sourceUrl = music.data.images[0];
// setCurrentspot(currentspot);
// })
// const response = await fetch('https://api.spotify.com/v1/me', {
// method: 'GET',
// headers: {
// Authorization: 'Bearer ' + spotify,
// 'Content-Type': 'application/json',
// },
// });
// response.json()
// destructure the response and rename the properties to be in camelCase to satisfy my linter ;)
} catch (err) {
console.error(err);
}
}
const animationState = new Value(State.UNDETERMINED);
return (
<SafeAreaView style={styles.mainSafeArea}>
<View style={{ flex: 1, justifyContent: 'flex-start', alignItems: 'center' }}>
{/* <SharedElement id={spot.name} style={{ flex: 1 }}> */}
<View style={{ borderWidth: 1, borderColor: 'red' }}>
<Animated.Image
@ -242,15 +108,9 @@ const SpotDetailsPage = ({ route }) => {
<Button title="Current Track"
onPress={() => {
getCurrentTrack()
// promptAsync();
}}
/>
</View>
{/* Button */}
{/* <TapGestureHandler {...gestureHandler}> */}
<Animated.View>
<TouchableOpacity style={{
backgroundColor: '#1DB954',
@ -271,25 +131,6 @@ const SpotDetailsPage = ({ route }) => {
</Text>
</TouchableOpacity>
</Animated.View>
{/* </TapGestureHandler> */}
{/* Button */}
{/* <View style={detailRadicalStyle.container}>
<Text style={detailRadicalStyle.radicalText}>{props.character}</Text>
<SvgXml
xml={props.icon
.replace(/fill="#[0-9a-f]{6}"/g, `fill=${detailRadicalStyle.svg.color}`)}
width="30"
height="30"
opacity={0.5}
style={detailRadicalStyle.radicalIcon}
/>
</View> */}
{/* </SharedElement> */}
</View>
</SafeAreaView>

@ -1,53 +1,31 @@
import { View, Text, Image, Animated, PanResponder, Dimensions, StyleSheet, ImageBackground, Button, Pressable, Touchable, TouchableOpacity, Modal, SafeAreaView, TextInput, Platform } from 'react-native'
import React, { useCallback, useEffect, useRef, useState, useTransition } from 'react'
import { LinearGradient } from 'expo-linear-gradient';
import * as Haptics from 'expo-haptics';
import { View, Text, StyleSheet, Button, Platform } from 'react-native'
import React from 'react'
import * as AuthSession from 'expo-auth-session';
import Card from '../components/Card';
import axios from 'axios';
import { cards as cardArray } from '../data/data'
import FladButton from '../components/button/button';
import * as WebBrowser from 'expo-web-browser';
import { makeRedirectUri, useAuthRequest } from 'expo-auth-session';
import { Buffer } from 'buffer';
const SCREEN_WIDTH = Dimensions.get('window').width
import * as SecureStore from 'expo-secure-store';
interface LoginProps {
}
interface Params {
[key: string]: string;
}
interface Profile {
display_name: string;
email: string;
id: string;
}
//generate random string
export const MY_SECURE_AUTH_STATE_KEY = 'MySecureAuthStateKey';
export const MY_SECURE_AUTH_STATE_KEY = 'MySecureAuthStateKey'
WebBrowser.maybeCompleteAuthSession();
WebBrowser.maybeCompleteAuthSession()
// Endpoint
const discovery = {
authorizationEndpoint: 'https://accounts.spotify.com/authorize',
tokenEndpoint: 'https://accounts.spotify.com/api/token',
};
// save the spotifyToken
async function save(key: string, value: string) {
await SecureStore.setItemAsync(key, value);
await SecureStore.setItemAsync(key, value)
}
export default function Login() {
// const [advice, setAdvice] = useState("dd");
// there we use implicit grant flow
const [request, response, promptAsync] = useAuthRequest(
const [request] = useAuthRequest(
{
responseType: AuthSession.ResponseType.Token,
clientId: '1f1e34e4b6ba48b388469dba80202b10',
@ -62,44 +40,12 @@ export default function Login() {
discovery
);
const getAdvice = async () => {
axios.get("http://localhost:8080/api/spotify/exchange")
.then(response => {
console.log(response.data.message);
// setAdvice(response.data.message);
}).catch(function (error) {
console.log(error);
});
};
React.useEffect(() => {
if (response && response.type === 'success') {
console.log(response);
console.log("========================code=====================");
console.log(response.params.code)
console.log("=============================================");
console.log("========================acess=====================");
console.log(response.params.access_token)
console.log("=============================================");
const auth = response.params.access_token;
const storageValue = JSON.stringify(auth);
if (Platform.OS !== 'web') {
// Securely store the auth on your device
// save(MY_SECURE_AUTH_STATE_KEY, storageValue);
}
}
}, [response]);
const scopesArr = ['user-read-private', 'user-read-email', 'user-read-playback-state', 'user-read-currently-playing', 'user-read-recently-played', 'playlist-modify-public', 'ugc-image-upload', 'user-modify-playback-state'];
const scopes = scopesArr.join(' ');
//work so use this for my implementation
const getAuthorizationCode = async () => {
try {
const redirectUrl = "https://auth.expo.io/@anonymous/FLAD-7eafd441-fd6b-4fb6-924c-ec2b0ed5ce6d"; //this will be something like https://auth.expo.io/@your-username/your-app-slug
const redirectUrl = "https://auth.expo.io/@anonymous/FLAD-7eafd441-fd6b-4fb6-924c-ec2b0ed5ce6d"
const result = await AuthSession.startAsync({
authUrl:
'https://accounts.spotify.com/authorize' +
@ -110,7 +56,6 @@ export default function Login() {
'&redirect_uri=' +
encodeURIComponent(redirectUrl),
})
console.log(result);
return result.params.code;
} catch (err) {
console.error(err)
@ -118,8 +63,7 @@ export default function Login() {
}
const getTokens = async () => {
try {
const authorizationCode = await getAuthorizationCode() //we wrote this function above
console.log(authorizationCode, "shhhhhhhhhhhhhheeeeeeeeeeeeeeeetttttttttttt");
const authorizationCode = await getAuthorizationCode()
const response = await fetch('https://accounts.spotify.com/api/token', {
method: 'POST',
headers: {
@ -128,17 +72,9 @@ export default function Login() {
},
body: `grant_type=authorization_code&code=${authorizationCode}&redirect_uri=https://auth.expo.io/@anonymous/FLAD-7eafd441-fd6b-4fb6-924c-ec2b0ed5ce6d`,
});
const responseJson = await response.json();
console.log(responseJson.access_token, "okkkkkkkkkkkkkkk");
// destructure the response and rename the properties to be in camelCase to satisfy my linter ;)
const {
access_token: accessToken,
refresh_token: refreshToken,
expires_in: expiresIn,
} = responseJson;
const responseJson = await response.json()
} catch (err) {
console.error(err);
console.error(err)
}
}
return (
@ -147,7 +83,6 @@ export default function Login() {
<Button disabled={!request} title="Login"
onPress={() => {
getTokens()
// promptAsync();
}}
/>
</View>

@ -1,96 +1,21 @@
import { View, Text, Image, PanResponder, Dimensions, StyleSheet, ImageBackground, Button, Pressable, TouchableOpacity, SafeAreaView } from 'react-native'
import React, { useCallback, useEffect, useRef, useState, useTransition } from 'react'
import { View, Text, Dimensions, StyleSheet, ImageBackground, Pressable, TouchableOpacity, SafeAreaView } from 'react-native'
import React, { useCallback, useRef, useState } from 'react'
import { LinearGradient } from 'expo-linear-gradient';
import * as Haptics from 'expo-haptics';
import Animated from 'react-native-reanimated';
import Card from '../components/Card';
import { cards as cardArray, spotArray2 } from '../data/data'
import FladButton from '../components/button/button';
import axios from 'axios';
import AdjustSize from '../components/AdjustSize';
import * as SecureStore from 'expo-secure-store';
import { MY_SECURE_AUTH_STATE_KEY } from './login';
import * as AuthSession from 'expo-auth-session';
import normalize from '../components/Normalize';
import * as Location from 'expo-location';
import Icons from '../assets/icons/icons/icon';
import LottieView from 'lottie-react-native'
import Lotties from '../assets/lottie/Lottie';
import FladLoading from '../components/FladLoadingScreen';
import { SharedElement } from 'react-navigation-shared-element';
import { useNavigation } from '@react-navigation/native';
import Music from '../Model/Music';
import { addFavoritesMusic } from '../redux/actions/appActions';
import { useDispatch } from 'react-redux';
import { Spot } from '../Model/Spot';
type LocationData = {
latitude: number;
longitude: number;
timestamp: number;
}
interface NearbyUser {
id: number;
name: string;
latitude: number;
longitude: number;
}
async function getUserData(accessToken: string) {
axios.get("https://api.spotify.com/v1/me",
{
headers: {
'Authorization': 'Bearer ' + accessToken,
"Content-Type": "application/json"
}
})
.then(response => {
if (response && response.statusText === 'success') {
console.log(response.data.message);
const userData = JSON.stringify(response.data);
const userId = response.data.id;
return { userId, userData }
}
})
.catch(function (error) {
console.log(error);
});
};
// async function sendUserLoc(accessToken : string) {
// axios.get("https://api.spotify.com/v1/me",
// {
// headers: {
// 'Authorization': 'Bearer ' + accessToken,
// "Content-Type" : "application/json"
// }})
// .then(response =>
// {
// if (response && response.statusText === 'success') {
// console.log(response.data.message);
// const userData = JSON.stringify(response.data);
// const userId = response.data.id;}
// })
// .catch(function (error) {
// console.log(error);
// });
// };
async function getValueFor(key: string): Promise<string | null> {
let result = await SecureStore.getItemAsync(key);
if (result) {
alert("🔐 Here's your value 🔐 \n" + result);
} else {
alert('No values stored under that key.');
}
return result;
}
export default function SpotPage() {
const [cards, setCards] = useState(spotArray2);
const [currentCard, setcurrentCard] = useState(cards[cards.length - 1]);
@ -98,9 +23,7 @@ export default function SpotPage() {
if (direction === 'right') {
// Swiped right
console.log("====2===" + currentCard.music.title + "======2=========");
addLike(currentCard.music);
console.log('Swiped right');
} else if (direction === 'left') {
// Swiped left
console.log('Swiped left');
@ -114,14 +37,9 @@ export default function SpotPage() {
setCards(cards.filter((_, i) => i !== index));
setcurrentCard(cards[index - 1]);
}, 3);
// setCards(cards.filter((_, i) => i !== index));
// setcurrentCard(cards[index-1]);
};
const likeButtonref = useRef<LottieView>(null);
const dislikeButtonref = useRef<LottieView>(null);
const discoveryButtonref = useRef<LottieView>(null);
const onLike = useCallback(() => {
likeButtonref.current?.reset();
likeButtonref.current?.play(0, 55);
@ -131,77 +49,15 @@ export default function SpotPage() {
function addLike(music: Music) {
onLike();
console.log("====3===" + currentCard.music.title + "======3=========");
dispatch(addFavoritesMusic(music))
// dispatch(likeMusic(currentCard));
// dispatch(addFavoriteMusic(props));
// if (displayIndex == trendingMovies.length - 1) {
// setdisplayIndex(0);
// swiper.swipeLeft();
// }
}
// const hapti = (() => {
// Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Heavy)
// getValueFor(MY_SECURE_AUTH_STATE_KEY)
// .then(key => { (key != null) ? getUserData(key) :console.log("error key is nullll") } ) ;
// // Haptics.NotificationFeedbackType.Success
// });
////////////////////////////////////////////////////////////////
// const [locationData, setLocationData] = useState<LocationData>();
// const [prevLocationData, setPrevLocationData] = useState<LocationData>();
// const [nearbyUsers, setNearbyUsers] = useState<NearbyUser[]>([]);
// const [currentMusic, setCurrentMusic] = useState<string>("");
// async function getLocation() {
// var { status } = await Location.requestForegroundPermissionsAsync();
// if (status !== 'granted') {
// console.log('Permission to access location was denied');
// return;
// }
// let currentLocation = await Location.getCurrentPositionAsync({});
// setLocationData({
// latitude: currentLocation.coords.latitude,
// longitude: currentLocation.coords.longitude,
// timestamp: currentLocation.timestamp
// });
// };
// async function sendLocationToServer() {
// getLocation();
// if (!locationData) return;
// if (prevLocationData && locationData.latitude === prevLocationData.latitude && locationData.longitude === prevLocationData.longitude) {
// return;
// }
// try {
// const response = await axios.post(
// 'http://localhost/api/users/david/nextToMe',
// locationData
// );
// if (response.status !== 200) {
// throw new Error('Failed to send location to server');
// }
// setPrevLocationData(locationData);
// setNearbyUsers(response.data);
// } catch (error) {
// console.error(error);
// }
// };
// setInterval(sendLocationToServer, 30000)
const navigator = useNavigation();
const { width: wWidht } = Dimensions.get("window");
const hapti = (card: Spot) => {
Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Heavy)
navigator.navigate("DetailsSpot", { "music": card.music })
// Haptics.NotificationFeedbackType.Success
};
return (
@ -251,13 +107,11 @@ export default function SpotPage() {
<View key={card.userSpotifyId} style={{ position: 'absolute' }} >
<Pressable onLongPress={() => { hapti(card) }} >
{/* <SharedElement id={card.name}> */}
<Card
title={card.music.title}
image={card.music.image}
onSwipe={(direction) => { onSwipe(index, direction) }}
/>
{/* </SharedElement> */}
</Pressable>
</View>
))

@ -1,33 +0,0 @@
export class AuthentificationService {
constructor(private auth: Auth, private http: HttpClient) { }
name = "toto";
async register({ email, password }) {
try {
const user = await createUserWithEmailAndPassword(this.auth, email, password);
return user;
} catch (e) {
return null;
}
}
async login({ email, password }) {
// should for all method use a cloud function to creata user
try {
const user = await signInWithEmailAndPassword(this.auth, email, password);
return user;
} catch (e) {
return null;
}
}
logout() {
return signOut(this.auth);
}
}

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

@ -18,26 +18,12 @@ 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 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;
// }
// async apiAuth(url : string) {
// await this.identification.setCode(url);
// // this.request = ApiSpotifyRequests(await this.identification.createToken());
// }
public async getMusicById(idMusic: string): Promise<Music> {
var requestData: string = '/tracks/' + idMusic;
const respMusic = await this.spotifyRequestHandler.spotifyFetch(requestData, undefined, this.token);
@ -52,9 +38,6 @@ export default class SpotifyService implements IspotifyService {
if (respMusic.status != 200) {
return null;
}
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;
@ -68,15 +51,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;
}
public async playMusic(idMusic: string): Promise<void> {
var requestData: string = '/me/player/play';
const fetchOptions: FetchOptions = {
method: 'PUT',
body: {
@ -84,18 +62,6 @@ export default class SpotifyService implements IspotifyService {
position_ms: 0
}
};
const respMusic = await this.spotifyRequestHandler.spotifyFetch(requestData, fetchOptions, this.token);
// need to handle when
// if (respMusic.status != 200) {
// if (respMusic.status == 400 && respMusic.data.message =='need to use Spotify premium'){
// }
// }
// if(respMusic){
// console.log(respMusic);
// console.log(respMusic.data);
// }
return;
}
@ -116,11 +82,7 @@ export default class SpotifyService implements IspotifyService {
return [];
}
const tracks = tracksData.map((trackData: any) => {
// const { id, name, artists, album } = trackData;
return MusicFactory.mapFromSpotifyTrack(trackData)
// const artistNames = artists.map((artist: any) => artist.name).join(', ');
// const linkCover = album?.images[0]?.url || '';
// return new Music(id, name, artistNames, linkCover);
});
return tracks;
}
@ -165,71 +127,16 @@ export default class SpotifyService implements IspotifyService {
return;
}
public async createPlayList(userId: string, name?: string, description?: string): Promise<void> {
var requestData: string = '/users/' + encodeURIComponent(userId) + '/playlists';
const fetchOptions: FetchOptions = {
method: 'POST',
body: {
"public": false,
"name": name || "New Flad Playlist",
"description": description || "New Flad Playlist",
}
};
const respMusic = await this.spotifyRequestHandler.spotifyFetch(requestData, fetchOptions, this.token);
console.log(respMusic.data);
return;
}
// public async getSimilarTrack(musicId : string,limit : number =1,market? : string): Promise<Music[]>{
// var requestData :string = '/recommendations' +
// '?limit=' +limit+
// '&market=FR' +
// "&seed_tracks=" + musicId;
// const fetchOptions: FetchOptions = {
// method: 'GET',
// body: {
// seed_tracks: musicId,
// market: "FR",
// limit: 1,
// }
// };
// console.log('222222222221baaaaaaaaaaaaahhhhhhhhhhhh LAaa chp gros ' + musicId);
// const respSimilarMusic = await this.spotifyRequestHandler.spotifyFetch(requestData,undefined,this.token);
// console.log(respSimilarMusic.status+'baaaaaaaaaaaaahhhhhhhhhhhh LAaa chp gros');
// console.log(respSimilarMusic.data+'baaaaaaaaaaaaahhhhhhhhhhhh LAaa chp gros2');
// /// if respSimilarMusic == null || respSimilarMusic.data.count == 0 =>
// const similars : Music[]= respSimilarMusic.data.tracks.map(async (trackData: any) => {
// // const { id, name, artists, album } = trackData;
// console.log(trackData.id);
// if(trackData.id){
// const data = await this.getMusicById(trackData.id);
// return data;
// }
// // return MusicFactory.mapFromSpotifyTrack(trackData)
// // const artistNames = artists.map((artist: any) => artist.name).join(', ');
// // const linkCover = album?.images[0]?.url || '';
// // return new Music(id, name, artistNames, linkCover);
// });
// console.log(similars+'################################################');
// return similars;
// }
public async getSimilarTrack(musicId: string, limit: number = 1, market?: string): Promise<Music[]> {
const requestData: string = '/recommendations/' +
'?limit=' + limit +
'&market=FR' +
'&seed_tracks=' + musicId;
console.log(musicId, "=============ouioui=================")
var respSimilarMusic;
try {
console.log("=======================1=========", requestData, this.token)
respSimilarMusic = await this.spotifyRequestHandler.spotifyFetch(requestData, {}, this.token);
} catch (error) {
console.log(error, "===================================spot Service");
console.log(error);
}
if (!respSimilarMusic || !respSimilarMusic.data.tracks) {
return [];
@ -245,16 +152,11 @@ export default class SpotifyService implements IspotifyService {
)
return similars.filter((music: Music | undefined) => !!music) as Music[];
// return similars;
}
async getSpotifyCredentials() {
const res = await axios.get(this.API_URL)
// then verify error
const spotifyCredentials = res.data;
return spotifyCredentials
}

@ -1,4 +1,3 @@
interface IspotifyService {
getMusicById(idMusic : string): Promise<any>;
getMusicById(idMusic: string): Promise<any>;
}

@ -1,14 +0,0 @@
// import { Linking } from 'react-native';
// export class SpotifyRequest {
// constructor() {
// }
// }

@ -1,4 +1,4 @@
import axios, { AxiosError, AxiosResponse } from "axios";
import axios, { AxiosResponse } from "axios";
export type Methods = 'GET' | 'POST' | 'DELETE' | 'PUT' | 'PATCH';
@ -15,14 +15,11 @@ export interface FetchOptions {
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=============");
try {
const resp = await axios({
url: `https://api.spotify.com/${this.version}${url}`,
@ -40,14 +37,6 @@ export class RequestHandler {
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{
@ -55,31 +44,6 @@ export class RequestHandler {
}
}
}
// 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{
}
export class AuthHandler{}

@ -2,14 +2,14 @@ import { AuthentificationService } from "../Auth/authentificationService.service
export class UserService {
constructor(private auth: AuthentificationService) {}
constructor(private auth: AuthentificationService) { }
getUserProfile() {
const user = this.auth.currentUser;
const userDocRef = doc(this.firestore, `User/${user.uid}`);
return docData(userDocRef);
}
async uploadName(name: string, email : string) {
async uploadName(name: string, email: string) {
try {
} catch (e) {

Loading…
Cancel
Save