-
Notifications
You must be signed in to change notification settings - Fork 0
/
App.tsx
207 lines (190 loc) · 5.51 KB
/
App.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
import React, { useEffect, useReducer } from 'react';
import { ActivityIndicator, StatusBar } from 'react-native';
import { NavigationContainer, DefaultTheme } from '@react-navigation/native';
import { AppearanceProvider } from 'react-native-appearance';
import { SpotifyProvider } from './services/spotifyService';
import AuthNavigator from './navigation/AuthNavigator';
import * as SecureStore from 'expo-secure-store';
import TabNavigator from './navigation/TabNavigator';
import * as AuthSession from 'expo-auth-session';
import { vars } from './env/env';
import { AuthContext } from './context/authContext';
import * as storageService from './services/secureStorageService';
import { enableScreens } from 'react-native-screens';
export default function App() {
const [state, dispatch] = useReducer(
(prevState: any, action: any) => {
switch (action.type) {
case 'RESTORE_TOKEN':
return {
...prevState,
tokenResponse: action.tokenResponse,
isLoading: false,
};
case 'REFRESH_TOKEN':
return {
...prevState,
tokenResponse: action.tokenResponse,
isLoading: false,
};
case 'SIGN_IN':
return {
...prevState,
isSignout: false,
tokenResponse: action.tokenResponse,
};
case 'SIGN_OUT':
return {
...prevState,
isSignout: true,
tokenResponse: null,
};
}
},
{
isLoading: false,
isSignout: false,
tokenResponse: null,
}
);
const discovery = {
authorizationEndpoint: 'https://accounts.spotify.com/authorize',
tokenEndpoint: 'https://accounts.spotify.com/api/token',
};
const requestedScopes = [
'user-read-email',
'playlist-modify-public',
'user-read-recently-played',
'playlist-read-private',
'user-follow-modify',
'user-follow-read',
'playlist-modify-private',
'playlist-read-private',
'playlist-read-collaborative',
'user-top-read',
];
const [request, response, promptAsync] = AuthSession.useAuthRequest(
{
clientId: vars.CLIENT_ID,
scopes: requestedScopes,
// In order to follow the "Authorization Code Flow" to fetch token after authorizationEndpoint
// this must be set to false
usePKCE: false,
// For usage in managed apps using the proxy
redirectUri: AuthSession.makeRedirectUri(),
},
discovery
);
useEffect(() => {
const bootstrapAsync = async () => {
let tokenResponse;
try {
tokenResponse = await storageService.getToken();
// check if token has expired and exchange.
if (isTokenExpired(tokenResponse)) {
console.log('expired');
let test = await refreshAccessToken(tokenResponse);
return;
}
dispatch({ type: 'RESTORE_TOKEN', tokenResponse });
return;
} catch (e) {
console.log(
`Failed to retrieve token, it was not found in local storage: ${e}`
);
}
};
bootstrapAsync();
}, []);
useEffect(() => {
const fetchToken = async () => {
if (response?.type === 'success') {
const { code } = response.params;
try {
let tokenResponse = await fetchAccessToken(code);
let success = await storageService.saveToken(tokenResponse);
if (success) {
dispatch({ type: 'SIGN_IN', tokenResponse });
}
} catch (e) {
console.log('Error fetching access token ', e);
}
}
};
fetchToken();
}, [response]);
const fetchAccessToken = async (code: string) => {
return await AuthSession.exchangeCodeAsync(
{
clientId: vars.CLIENT_ID,
code: code,
redirectUri: AuthSession.makeRedirectUri(),
extraParams: {
client_secret: vars.CLIENT_SECRET,
},
},
discovery
);
};
const refreshAccessToken = async (tokenResponse: AuthSession.TokenResponse) => {
return AuthSession.refreshAsync(
{
refreshToken: tokenResponse.refreshToken,
clientId: vars.CLIENT_ID,
scopes: requestedScopes,
},
discovery
);
};
const isTokenExpired = (
tokenResponse: AuthSession.TokenResponse
): boolean => {
const expireTime = tokenResponse.issuedAt + tokenResponse.expiresIn!;
return expireTime < Math.floor(Date.now() / 1000);
};
const authContext = {
signIn: async (data: any) => {
promptAsync();
},
signOut: async () => {
await SecureStore.deleteItemAsync('accessToken');
dispatch({ type: 'SIGN_OUT' });
},
};
if (state.isLoading) {
// We haven't finished checking forthe token yet
return <ActivityIndicator />;
}
enableScreens();
return (
<AppearanceProvider>
<NavigationContainer theme={SpotifyTheme}>
<StatusBar barStyle="light-content" />
<AuthContext.Provider value={authContext}>
<SpotifyProvider>
{state.tokenResponse == null ? <AuthNavigator /> : <TabNavigator />}
</SpotifyProvider>
</AuthContext.Provider>
</NavigationContainer>
</AppearanceProvider>
);
}
const SpotifyTheme = {
...DefaultTheme,
dark: false,
fontSize: {},
colors: {
...DefaultTheme.colors,
primary: '#ffffff',
secondary: '#212121',
background: '#121212',
card: '#212121',
text: '#ffffff',
border: '#121212',
notification: '#1db954',
},
headerText: {
fontSize: 22,
fontWeight: 'bold',
},
};