From 3fa45977cc3316a9e05f1c0c06d8ae6e7b5ba073 Mon Sep 17 00:00:00 2001 From: Emre Date: Mon, 20 Mar 2023 21:53:35 +0100 Subject: [PATCH] code smells fix --- src/FLAD/Model/Interface/IdataManager.tsx | 0 src/FLAD/Model/Manager.tsx | 79 --------- src/FLAD/Model/SpotifyToken.tsx | 33 +--- src/FLAD/Model/User.tsx | 1 + src/FLAD/components/AdjustSize.tsx | 2 - src/FLAD/components/AnimatedParalax.tsx | 10 +- src/FLAD/components/Artist.tsx | 5 +- src/FLAD/components/ArtistChip.tsx | 17 +- src/FLAD/components/Card.tsx | 48 +---- src/FLAD/components/CardMusic.tsx | 3 +- src/FLAD/components/CircularProgressBar.tsx | 51 +----- src/FLAD/components/CurrentMusic.tsx | 111 +----------- src/FLAD/components/FladLoadingScreen.tsx | 71 +------- src/FLAD/components/Genre.tsx | 2 +- src/FLAD/components/HalfCircle.tsx | 17 +- src/FLAD/components/HorizontalFlatList.tsx | 16 +- src/FLAD/components/Normalize.tsx | 1 - src/FLAD/components/SelectedCard.tsx | 9 +- src/FLAD/components/button/button.tsx | 16 +- src/FLAD/components/input.tsx | 2 +- src/FLAD/components/littleCard.tsx | 3 +- src/FLAD/model/Music.ts | 7 +- src/FLAD/navigation/AuthNavigation.tsx | 162 ++--------------- src/FLAD/navigation/FavoriteNavigation.tsx | 3 - src/FLAD/navigation/Navigation.tsx | 9 - src/FLAD/navigation/SpotNavigation.tsx | 12 +- src/FLAD/navigation/StartNavigation.tsx | 25 --- src/FLAD/package.json | 8 +- src/FLAD/redux/actions/appActions.ts | 12 +- src/FLAD/redux/actions/spotActions.tsx | 24 +-- src/FLAD/redux/actions/userActions.tsx | 8 +- src/FLAD/redux/reducers/userReducer.tsx | 27 +-- src/FLAD/redux/thunk/authThunk.tsx | 60 +------ src/FLAD/redux/thunk/socialThunk.tsx | 35 ++-- src/FLAD/redux/thunk/spotThunk.tsx | 156 +++++----------- src/FLAD/redux/types/discoverieTypes.tsx | 4 +- src/FLAD/redux/types/favoritesTypes.tsx | 10 +- src/FLAD/redux/types/playlistTypes.tsx | 6 +- src/FLAD/redux/types/spotTypes.tsx | 4 +- src/FLAD/redux/types/spotifyTypes.ts | 2 +- src/FLAD/screens/Favorite.tsx | 25 +-- src/FLAD/screens/LoginPage.tsx | 4 +- src/FLAD/screens/MusicDetail.tsx | 84 +-------- src/FLAD/screens/Register.tsx | 137 +------------- src/FLAD/screens/Setting.tsx | 7 +- src/FLAD/screens/SettingProfil.tsx | 14 +- src/FLAD/screens/SpotDetailsPage.tsx | 167 +----------------- src/FLAD/screens/login.tsx | 87 ++------- src/FLAD/screens/spot.tsx | 150 +--------------- .../Auth/authentificationService.service.tsx | 33 ---- .../services/spotify/IspotifyAuthHandler.ts | 1 - src/FLAD/services/spotify/spotify.service.ts | 102 +---------- .../spotifyRequestHandler/IspotifyService.ts | 3 +- .../spotifyRequestHandler/spotifyRequest.tsx | 14 -- .../spotify/spotifyRequestHandler/utils.tsx | 40 +---- .../services/user/userService.service.tsx | 6 +- 56 files changed, 194 insertions(+), 1751 deletions(-) delete mode 100644 src/FLAD/Model/Interface/IdataManager.tsx delete mode 100644 src/FLAD/services/Auth/authentificationService.service.tsx delete mode 100644 src/FLAD/services/spotify/spotifyRequestHandler/spotifyRequest.tsx diff --git a/src/FLAD/Model/Interface/IdataManager.tsx b/src/FLAD/Model/Interface/IdataManager.tsx deleted file mode 100644 index e69de29..0000000 diff --git a/src/FLAD/Model/Manager.tsx b/src/FLAD/Model/Manager.tsx index cd9d147..4e7f896 100644 --- a/src/FLAD/Model/Manager.tsx +++ b/src/FLAD/Model/Manager.tsx @@ -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 => { - // 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 => { - // 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 => { - // 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; \ No newline at end of file diff --git a/src/FLAD/Model/SpotifyToken.tsx b/src/FLAD/Model/SpotifyToken.tsx index ca6bfe6..1d23524 100644 --- a/src/FLAD/Model/SpotifyToken.tsx +++ b/src/FLAD/Model/SpotifyToken.tsx @@ -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 getAccessToken() async { - // if (DateTime.now().isAfter(_tokenEnd)) { - // await _actualiseToken(); - // } - // return _accessToken; - // } - - // _actualiseToken() async { - // var urlToken = Uri.https('accounts.spotify.com', 'api/token', { - // 'grant_type': 'refresh_token', - // 'refresh_token': _refreshToken, - // 'client_id': ApiSpotifyIdentification.clientId - // }); - // setResponse(await http.post(urlToken, headers: { - // 'Content-Type': 'application/x-www-form-urlencoded' - // })); - // var decodedResponse = jsonDecode(utf8.decode(response.bodyBytes)) as Map; - // _accessToken = decodedResponse['access_token']; - // _setTokenEnd(decodedResponse['expires_in']); - // } } \ No newline at end of file diff --git a/src/FLAD/Model/User.tsx b/src/FLAD/Model/User.tsx index 57baf3b..52c8896 100644 --- a/src/FLAD/Model/User.tsx +++ b/src/FLAD/Model/User.tsx @@ -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; diff --git a/src/FLAD/components/AdjustSize.tsx b/src/FLAD/components/AdjustSize.tsx index 65142a6..842f087 100644 --- a/src/FLAD/components/AdjustSize.tsx +++ b/src/FLAD/components/AdjustSize.tsx @@ -1,5 +1,3 @@ -import React from 'react'; - export default function AdjustSize(Text: String) { const titleLength = Text.length; const minFontSize = 23; diff --git a/src/FLAD/components/AnimatedParalax.tsx b/src/FLAD/components/AnimatedParalax.tsx index 8cf8304..67d530d 100644 --- a/src/FLAD/components/AnimatedParalax.tsx +++ b/src/FLAD/components/AnimatedParalax.tsx @@ -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], diff --git a/src/FLAD/components/Artist.tsx b/src/FLAD/components/Artist.tsx index 35b3540..9f86130 100644 --- a/src/FLAD/components/Artist.tsx +++ b/src/FLAD/components/Artist.tsx @@ -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); diff --git a/src/FLAD/components/ArtistChip.tsx b/src/FLAD/components/ArtistChip.tsx index 3fe22e3..8decee0 100644 --- a/src/FLAD/components/ArtistChip.tsx +++ b/src/FLAD/components/ArtistChip.tsx @@ -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; \ No newline at end of file +export default ArtistChip; \ No newline at end of file diff --git a/src/FLAD/components/Card.tsx b/src/FLAD/components/Card.tsx index f4d6410..cf6903f 100644 --- a/src/FLAD/components/Card.tsx +++ b/src/FLAD/components/Card.tsx @@ -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 ( @@ -189,8 +151,6 @@ const Card = ({ title, image, onSwipe }: CardProps) => { <> 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({ diff --git a/src/FLAD/components/CircularProgressBar.tsx b/src/FLAD/components/CircularProgressBar.tsx index e703147..28f2b34 100644 --- a/src/FLAD/components/CircularProgressBar.tsx +++ b/src/FLAD/components/CircularProgressBar.tsx @@ -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(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 ( <> @@ -58,19 +24,12 @@ const FladInput = ({ background, foreground, progress }: CircularProps) => { - + - + + ); }; -const styles = StyleSheet.create({ - input: { - justifyContent: 'center', - alignItems: 'center', - placeholder: "placeholde" - }, -}) - export default FladInput; \ No newline at end of file diff --git a/src/FLAD/components/CurrentMusic.tsx b/src/FLAD/components/CurrentMusic.tsx index 730c0c8..e120c56 100644 --- a/src/FLAD/components/CurrentMusic.tsx +++ b/src/FLAD/components/CurrentMusic.tsx @@ -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 ( - -// -// -// -// -// -// ); -// } - - -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' }]}> - + ); diff --git a/src/FLAD/components/FladLoadingScreen.tsx b/src/FLAD/components/FladLoadingScreen.tsx index 629be52..7043aa9 100644 --- a/src/FLAD/components/FladLoadingScreen.tsx +++ b/src/FLAD/components/FladLoadingScreen.tsx @@ -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 ( - {/* - */} - - {/* */} ); }; - -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; diff --git a/src/FLAD/components/Genre.tsx b/src/FLAD/components/Genre.tsx index 5a8a79d..53962f6 100644 --- a/src/FLAD/components/Genre.tsx +++ b/src/FLAD/components/Genre.tsx @@ -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"; diff --git a/src/FLAD/components/HalfCircle.tsx b/src/FLAD/components/HalfCircle.tsx index e5fd7bc..f3d98d3 100644 --- a/src/FLAD/components/HalfCircle.tsx +++ b/src/FLAD/components/HalfCircle.tsx @@ -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(false); return ( - + ); }; -const styles = StyleSheet.create({ - input: { - justifyContent: 'center', - alignItems: 'center', - placeholder: "placeholde" - }, -}) export default HalfCirlce; \ No newline at end of file diff --git a/src/FLAD/components/HorizontalFlatList.tsx b/src/FLAD/components/HorizontalFlatList.tsx index b4ddfba..16cd110 100644 --- a/src/FLAD/components/HorizontalFlatList.tsx +++ b/src/FLAD/components/HorizontalFlatList.tsx @@ -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 ( {title} diff --git a/src/FLAD/components/Normalize.tsx b/src/FLAD/components/Normalize.tsx index e663f8d..b328a11 100644 --- a/src/FLAD/components/Normalize.tsx +++ b/src/FLAD/components/Normalize.tsx @@ -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; diff --git a/src/FLAD/components/SelectedCard.tsx b/src/FLAD/components/SelectedCard.tsx index 2c74ce6..8ec8557 100644 --- a/src/FLAD/components/SelectedCard.tsx +++ b/src/FLAD/components/SelectedCard.tsx @@ -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", - - } }); \ No newline at end of file diff --git a/src/FLAD/components/button/button.tsx b/src/FLAD/components/button/button.tsx index 737bba3..fbeedb1 100644 --- a/src/FLAD/components/button/button.tsx +++ b/src/FLAD/components/button/button.tsx @@ -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'; +import { 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; interface ButtonProps { name : string; } diff --git a/src/FLAD/components/input.tsx b/src/FLAD/components/input.tsx index 4f95757..7d22dbe 100644 --- a/src/FLAD/components/input.tsx +++ b/src/FLAD/components/input.tsx @@ -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; diff --git a/src/FLAD/components/littleCard.tsx b/src/FLAD/components/littleCard.tsx index 730e777..1409f93 100644 --- a/src/FLAD/components/littleCard.tsx +++ b/src/FLAD/components/littleCard.tsx @@ -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 ( diff --git a/src/FLAD/model/Music.ts b/src/FLAD/model/Music.ts index 3169f20..639257f 100644 --- a/src/FLAD/model/Music.ts +++ b/src/FLAD/model/Music.ts @@ -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; diff --git a/src/FLAD/navigation/AuthNavigation.tsx b/src/FLAD/navigation/AuthNavigation.tsx index c2f9769..d9b5b4d 100644 --- a/src/FLAD/navigation/AuthNavigation.tsx +++ b/src/FLAD/navigation/AuthNavigation.tsx @@ -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(); - 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,109 +49,30 @@ export default function AuthNavigation() { ChangeDarkMode(); prepare(); }, [appIsReady, tokenProcesed]); - - // const onStackRootView = useCallback(async () => { - - // }, [appIsReady]); useEffect(() => { - + const sendLocationUpdate = async () => { try { //@ts-ignore await dispatch(getCurrentUserMusic(theService)) let { status } = await Location.requestForegroundPermissionsAsync(); - + if (status == 'granted') { console.log(appIsReady) if (true) {// should app is ready - // see deeper the documentation - // const [status, requestPermission] = Location.useBackgroundPermissions(); const locationresp = await Location.getCurrentPositionAsync({}); setLocation(locationresp); // send location to server console.log(locationresp); - // if(locationresp !=location ){ - console.log(location); - const body : Record = { - longitude: locationresp.coords.longitude, - latitude: locationresp.coords.latitude, - currentMusic : currentMusic.id - } - - console.log(tokenSend) - console.log('((((((((((((((((((((()))))))))))))))))))))================================###############'); - console.log('((((((((((((((((((((()))))))))))))))))))))================================###############'); - console.log('((((((((((((((((((((())))))))))))))))))))================================###############'); - console.log(location); - - console.log('(((((((((((((((((((()))))))))))))))))))))================================###############'); console.log('((((((((((((((((((((()))))))))))))))))))))================================###############'); - console.log('((((((((((((((((((((()))))))))))))))))))))================================###############'); - console.log('((((((((((((((((((((()))))))))))))))))))))================================###############'); - console.log('**********************************************************************************') - try { - const resp = await axios({ - url: 'https://flad-api-production.up.railway.app/api/users/nextTo', - method: 'GET', - headers: { - Authorization: `Bearer ${tokenSend}`, - }, - params: { - longitude: locationresp.coords.longitude, - latitude: locationresp.coords.latitude, - currentMusic : currentMusic.id - } - }); - - console.log('(((((((((((((((((((()))))))))))))))))))))================================###############'); - console.log('((((((((((((((((((((())))))))))))))))))))================================###############'); - console.log(resp.status); - console.log('**********************************************************************************') - console.log('**********************************************************************************') - console.log('**********************************************************************************') - - console.log('((((((((((((((((((((()))))))))))))))))))))================================###############'); - console.log('((((((((((((((((((((()))))))))))))))))))))================================###############'); - console.log(resp); - console.log(resp.data); - console.log('((((((((((((((((((((()))))))))))))))))))))================================###############'); - console.log('((((((((((((((((((((()))))))))))))))))))))================================###############'); - console.log('((((((((((((((((((((()))))))))))))))))))))================================###############'); - console.log('=========((((((((((((((((()))))))))))))))))===============================###############'); - - } catch (error) { - console.log('*********************************************************************************************'); - console.log('*********************************************************************************************'); - console.log('********************************************************************************************'); - console.log('*********************************************************************************************'); - console.log('*********************************************************************************************'); - console.log('*********************************************************************************************'); - console.log('*********************************************************************************************'); - console.log(error); - console.log(error.message); - - console.log('*********************************************************************************************'); - console.log('*********************************************************************************************'); - console.log('*********************************************************************************************'); - console.log('*********************************************************************************************'); - console.log('*********************************************************************************************'); - console.log('*********************************************************************************************'); - console.log('*********************************************************************************************'); - - - } - - - - // } - console.log(locationresp); - console.log(currentMusic); - - console.log('Sending location update ================================###############'); - + console.log(location); + const body: Record = { + longitude: locationresp.coords.longitude, + latitude: locationresp.coords.latitude, + currentMusic: currentMusic.id + } } } - 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 ( setAppIsReady(true)}> {isLogin ? ( - /* {userToken != null ? ( */ - // should set the reference to the function in Navigation to realy perform an on ready - // test purpose ) : diff --git a/src/FLAD/navigation/FavoriteNavigation.tsx b/src/FLAD/navigation/FavoriteNavigation.tsx index 7cd3f53..4af03c1 100644 --- a/src/FLAD/navigation/FavoriteNavigation.tsx +++ b/src/FLAD/navigation/FavoriteNavigation.tsx @@ -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'; diff --git a/src/FLAD/navigation/Navigation.tsx b/src/FLAD/navigation/Navigation.tsx index 524ea4a..ebe334f 100644 --- a/src/FLAD/navigation/Navigation.tsx +++ b/src/FLAD/navigation/Navigation.tsx @@ -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) diff --git a/src/FLAD/navigation/SpotNavigation.tsx b/src/FLAD/navigation/SpotNavigation.tsx index c3c6863..c899ce0 100644 --- a/src/FLAD/navigation/SpotNavigation.tsx +++ b/src/FLAD/navigation/SpotNavigation.tsx @@ -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} /> - {/* { - return [route.params.spot.name] - }} - /> */} ) } \ No newline at end of file diff --git a/src/FLAD/navigation/StartNavigation.tsx b/src/FLAD/navigation/StartNavigation.tsx index 8770e9d..c0c755a 100644 --- a/src/FLAD/navigation/StartNavigation.tsx +++ b/src/FLAD/navigation/StartNavigation.tsx @@ -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 ( diff --git a/src/FLAD/package.json b/src/FLAD/package.json index 4c6eda5..22ea1f9 100644 --- a/src/FLAD/package.json +++ b/src/FLAD/package.json @@ -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", diff --git a/src/FLAD/redux/actions/appActions.ts b/src/FLAD/redux/actions/appActions.ts index 71a3e81..243cb74 100644 --- a/src/FLAD/redux/actions/appActions.ts +++ b/src/FLAD/redux/actions/appActions.ts @@ -1,17 +1,15 @@ 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 { - type: favoritesTypes.GET_FAVORITE_MUSICS, - playload: favoritesMusic, - }; + return { + type: favoritesTypes.GET_FAVORITE_MUSICS, + playload: favoritesMusic, + }; } export const addFavoritesMusic = (favoritesMusic: Music) => { return { - type: favoritesTypes.ADD_FAVORITE_MUSICS , + type: favoritesTypes.ADD_FAVORITE_MUSICS, playload: favoritesMusic, }; } diff --git a/src/FLAD/redux/actions/spotActions.tsx b/src/FLAD/redux/actions/spotActions.tsx index 331b6bd..2785034 100644 --- a/src/FLAD/redux/actions/spotActions.tsx +++ b/src/FLAD/redux/actions/spotActions.tsx @@ -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, - }; - } + return { + type: spotTypes.FETCH_SPOT, + playload: spotList, + }; +} - export const setUserCurrentMusic = (currentMusic: Music) => { - return { - type: spotifyTypes.GET_USER_CURRENT_MUSIC, - playload: currentMusic, - }; - } \ No newline at end of file +export const setUserCurrentMusic = (currentMusic: Music) => { + return { + type: spotifyTypes.GET_USER_CURRENT_MUSIC, + playload: currentMusic, + }; +} \ No newline at end of file diff --git a/src/FLAD/redux/actions/userActions.tsx b/src/FLAD/redux/actions/userActions.tsx index 42f175e..b5ea11e 100644 --- a/src/FLAD/redux/actions/userActions.tsx +++ b/src/FLAD/redux/actions/userActions.tsx @@ -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 diff --git a/src/FLAD/redux/reducers/userReducer.tsx b/src/FLAD/redux/reducers/userReducer.tsx index ad28a6e..0ee619e 100644 --- a/src/FLAD/redux/reducers/userReducer.tsx +++ b/src/FLAD/redux/reducers/userReducer.tsx @@ -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, diff --git a/src/FLAD/redux/thunk/authThunk.tsx b/src/FLAD/redux/thunk/authThunk.tsx index f68d286..5e06a38 100644 --- a/src/FLAD/redux/thunk/authThunk.tsx +++ b/src/FLAD/redux/thunk/authThunk.tsx @@ -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); @@ -163,21 +126,4 @@ export const ChangeImageUserCurrent = (value: ImagePicker) => { return async dispatch => { 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); } \ No newline at end of file diff --git a/src/FLAD/redux/thunk/socialThunk.tsx b/src/FLAD/redux/thunk/socialThunk.tsx index a741333..558cc9f 100644 --- a/src/FLAD/redux/thunk/socialThunk.tsx +++ b/src/FLAD/redux/thunk/socialThunk.tsx @@ -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){ - dispatch(true); - } } ).catch(error => { + axios.post("osdj").then(responce => { + if (responce.status == 200) { + dispatch(true); + } + }).catch(error => { console.log("something goes wrong while searching : " + error); - ;}) - - + ; + }) + + }; - } \ No newline at end of file +} \ No newline at end of file diff --git a/src/FLAD/redux/thunk/spotThunk.tsx b/src/FLAD/redux/thunk/spotThunk.tsx index 1e4862b..d85ec69 100644 --- a/src/FLAD/redux/thunk/spotThunk.tsx +++ b/src/FLAD/redux/thunk/spotThunk.tsx @@ -1,87 +1,65 @@ -//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) => { - -//@ts-ignore -return async dispatch => { - try { - - // let { status } = await Location.requestForegroundPermissionsAsync(); - // if (status !== 'granted') { - // setErrorMsg('Permission to access location was denied'); - // return; - // } - - // let location = await Location.getCurrentPositionAsync({}); - // setLocation(location); - // const actualUser = MyApp.controller.getIdDafl(); - // const actualSong = MyApp.controller.getCurrentMusic().id; - // const current = await new Promise((resolve, reject) => { - // Geolocation.getCurrentPosition(resolve, reject); - // }); - +export const getSpotList = (resuestHandler: SpotifyService) => { + //@ts-ignore + return async dispatch => { + try { //@ts-ignore - var userToken : string = await SecureStore.getItemAsync(key); - const headers = { - 'Authorization': 'Bearer ' + userToken}; - const data = await axios.get( - "https://flad-api-production.up.railway.app/api/users/nextTo", - {headers} - ) - if (data.data.token) { - const spotsData: { [userId: string]: string } = {}; + var userToken: string = await SecureStore.getItemAsync(key); + const headers = { + 'Authorization': 'Bearer ' + userToken + }; + const data = await axios.get( + "https://flad-api-production.up.railway.app/api/users/nextTo", + { headers } + ) + if (data.data.token) { + const spotsData: { [userId: string]: string } = {}; + + for (const item of data.data) { + spotsData[item.user] = item.music; + } + const spots = await Promise.all( + Object.entries(spotsData).map(async ([userId, value]) => { + const completeMusic = await resuestHandler.getMusicById(value); + return new Spot(userId, completeMusic); + }) + ); - for (const item of data.data) { - spotsData[item.user] = item.music; - } - const spots = await Promise.all( - Object.entries(spotsData).map(async ([userId, value]) => { - const completeMusic = await resuestHandler.getMusicById(value); - return new Spot(userId, completeMusic); - }) - ); - dispatch(setSpotList(spots)); // our action is called here - } else { + } else { console.log('Login Failed', 'Username or Password is incorrect'); - } + } } catch (error) { - console.log('Error---------', error); + console.log('Error---------', error); } + } } -} -export const getCurrentUserMusic = (resuestHandler : SpotifyService)=> { +export const getCurrentUserMusic = (resuestHandler: SpotifyService) => { //@ts-ignore return async dispatch => { try { - //@ts-ignore + //@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; - // }; - - return resuestHandler.searchMusic(search).then(musics => dispatch((musics))).catch(err => console.log("something goes wrong while searching : " + err)); - +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); -// } -// } -// } \ No newline at end of file +} \ No newline at end of file diff --git a/src/FLAD/redux/types/discoverieTypes.tsx b/src/FLAD/redux/types/discoverieTypes.tsx index b94726f..c20d690 100644 --- a/src/FLAD/redux/types/discoverieTypes.tsx +++ b/src/FLAD/redux/types/discoverieTypes.tsx @@ -1,3 +1,3 @@ export const discoveriesTypes = { - FETCH_DISCOVERIES : 'FETCH_DISCOVERIES', - } \ No newline at end of file + FETCH_DISCOVERIES: 'FETCH_DISCOVERIES', +} \ No newline at end of file diff --git a/src/FLAD/redux/types/favoritesTypes.tsx b/src/FLAD/redux/types/favoritesTypes.tsx index e9c066d..7d747f5 100644 --- a/src/FLAD/redux/types/favoritesTypes.tsx +++ b/src/FLAD/redux/types/favoritesTypes.tsx @@ -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', - } \ No newline at end of file + GET_FAVORITE_MUSICS: 'GET_FAVORITE_MUSICS', + ADD_FAVORITE_MUSICS: 'ADD_FAVORITE_MUSICS', + REMOVE_FAVORITE_MUSICS: 'REMOVE_FAVORITE_MUSICS', +} \ No newline at end of file diff --git a/src/FLAD/redux/types/playlistTypes.tsx b/src/FLAD/redux/types/playlistTypes.tsx index d4a5f0f..4d8c3e4 100644 --- a/src/FLAD/redux/types/playlistTypes.tsx +++ b/src/FLAD/redux/types/playlistTypes.tsx @@ -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', } \ No newline at end of file diff --git a/src/FLAD/redux/types/spotTypes.tsx b/src/FLAD/redux/types/spotTypes.tsx index c4893a5..559d2f0 100644 --- a/src/FLAD/redux/types/spotTypes.tsx +++ b/src/FLAD/redux/types/spotTypes.tsx @@ -1,3 +1,3 @@ export const spotTypes = { - FETCH_SPOT : 'FETCH_SPOT', - } \ No newline at end of file + FETCH_SPOT: 'FETCH_SPOT', +} \ No newline at end of file diff --git a/src/FLAD/redux/types/spotifyTypes.ts b/src/FLAD/redux/types/spotifyTypes.ts index 0f2039b..0b84ebe 100644 --- a/src/FLAD/redux/types/spotifyTypes.ts +++ b/src/FLAD/redux/types/spotifyTypes.ts @@ -1,3 +1,3 @@ export const spotifyTypes = { - GET_USER_CURRENT_MUSIC : 'GET_USER_CURRENT_MUSIC', + GET_USER_CURRENT_MUSIC: 'GET_USER_CURRENT_MUSIC', } \ No newline at end of file diff --git a/src/FLAD/screens/Favorite.tsx b/src/FLAD/screens/Favorite.tsx index 042a6fb..e796f9e 100644 --- a/src/FLAD/screens/Favorite.tsx +++ b/src/FLAD/screens/Favorite.tsx @@ -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([]); - 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, diff --git a/src/FLAD/screens/LoginPage.tsx b/src/FLAD/screens/LoginPage.tsx index 9453f6d..86749d4 100644 --- a/src/FLAD/screens/LoginPage.tsx +++ b/src/FLAD/screens/LoginPage.tsx @@ -18,7 +18,7 @@ export default function loginPage() { const [sound, setSound] = useState(); 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(); diff --git a/src/FLAD/screens/MusicDetail.tsx b/src/FLAD/screens/MusicDetail.tsx index 90a0b36..05821d8 100644 --- a/src/FLAD/screens/MusicDetail.tsx +++ b/src/FLAD/screens/MusicDetail.tsx @@ -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 ( @@ -180,13 +114,7 @@ const MusicDetail = ({ route }) => { uri: currentspot.image, }} > - - {/* */} @@ -194,7 +122,6 @@ const MusicDetail = ({ route }) => { - {/* */} { }} style={[ { - - // width: 370, - // width: 400, width: normalize(429), height: normalize(429), borderRadius: 24, diff --git a/src/FLAD/screens/Register.tsx b/src/FLAD/screens/Register.tsx index a7c7721..7909966 100644 --- a/src/FLAD/screens/Register.tsx +++ b/src/FLAD/screens/Register.tsx @@ -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(); - 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 ( diff --git a/src/FLAD/screens/Setting.tsx b/src/FLAD/screens/Setting.tsx index c5d9185..704c1a1 100644 --- a/src/FLAD/screens/Setting.tsx +++ b/src/FLAD/screens/Setting.tsx @@ -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, diff --git a/src/FLAD/screens/SettingProfil.tsx b/src/FLAD/screens/SettingProfil.tsx index b3caee4..d561f3b 100644 --- a/src/FLAD/screens/SettingProfil.tsx +++ b/src/FLAD/screens/SettingProfil.tsx @@ -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, diff --git a/src/FLAD/screens/SpotDetailsPage.tsx b/src/FLAD/screens/SpotDetailsPage.tsx index de4e0a1..5724794 100644 --- a/src/FLAD/screens/SpotDetailsPage.tsx +++ b/src/FLAD/screens/SpotDetailsPage.tsx @@ -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 ( - {/* */} {