-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.tsx
More file actions
570 lines (517 loc) · 22.4 KB
/
App.tsx
File metadata and controls
570 lines (517 loc) · 22.4 KB
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
import React, { useState, useEffect, useMemo, useReducer, useContext } from 'react'
import * as Font from 'expo-font'
import * as AuthSession from 'expo-auth-session'
import * as Sentry from 'sentry-expo';
import ReduxThunk from 'redux-thunk'
import { Provider } from 'react-redux'
import { Text, View, Button } from 'react-native'
import AsyncStorage from '@react-native-async-storage/async-storage'
import Toast from 'react-native-toast-message'
import { AppearanceProvider } from 'react-native-appearance'
import { createStore, combineReducers, applyMiddleware } from 'redux'
import { NavigationContainer, DefaultTheme } from '@react-navigation/native'
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'
import { createStackNavigator } from '@react-navigation/stack'
// import NavigatorContainer from './navigation/NavigatorContainer'
import FeedStackScreen from './navigation/FeedStackScreen'
import CollectionStackScreen from './navigation/CollectionStackScreen'
import WantlistStackScreen from './navigation/WantlistStackScreen'
import DiscoverStackScreen from './navigation/DiscoverStackScreen'
import AccountStackScreen from './navigation/AccountStackScreen'
import CustomIcon from './components/CustomIcon/CustomIcon'
import ErrorNotification from './components/Notifications/ErrorNotification'
import AddAlbum from './screens/AddAlbum'
import AddAlbumManually from './screens/AddAlbumManually'
import Colors from './constants/Colors'
import Version from './constants/Version'
import albumsReducer from './store/reducers/albums'
import wantlistReducer from './store/reducers/wantlist'
import { init } from './helpers/db'
import { getData, storeData, removeData, storeObject } from './helpers/storeData'
import makeid from './helpers/nonce'
import { AuthContext } from './utils/authContext';
const CONSUMER_KEY = 'tILfDjLHXNBVjcVQthxa'
const CONSUMER_SECRET = 'KIIXTQskHkIifimxKtedzTKnBSNigSZL'
const timestamp = Date.now()
Sentry.init({
dsn: "https://7626aaf6928942849606598df164dc5a@o109145.ingest.sentry.io/5556382",
enableInExpoDevelopment: true,
enableAutoSessionTracking: true,
debug: true,
});
init()
.then(() => {
console.log('Initialized database')
})
.catch((err) => {
console.error('Initializing db failed 😢', err)
})
const rootReducer = combineReducers({
albums: albumsReducer,
wantlist: wantlistReducer
})
const store = createStore(rootReducer, applyMiddleware(ReduxThunk))
const RootStack = createStackNavigator()
const ScanAlbumStack = createStackNavigator()
const Tab = createBottomTabNavigator()
const MyTheme = {
...DefaultTheme,
colors: {
...DefaultTheme.colors,
background: 'rgb(255, 255, 255)',
text: Colors.grey,
primary: Colors.primaryColor
}
}
const ScanAlbumScreen = () => {
return (
<ScanAlbumStack.Navigator mode="modal">
<ScanAlbumStack.Screen
name="AddAlbum"
component={AddAlbum}
options={({ route, navigation }) => ({
headerTitle: (
<Text
style={{
fontFamily: 'kulimpark-bold'
}}
>
Scan barcode
</Text>
),
headerBackTitleVisible: false,
headerLeft: null,
headerBackImage: () => <CustomIcon name="back" color="#ffffff" style={{ marginLeft: 24 }} />,
headerStyle: {
backgroundColor: Colors.purple,
borderBottomWidth: 0,
borderBottomColor: '#ff2200',
shadowOpacity: 0
},
headerTintColor: '#fff',
headerRight: () => (
<CustomIcon
name="close"
color="#ffffff"
style={{ marginRight: 24 }}
onPress={() => navigation.goBack()}
/>
)
})}
/>
<ScanAlbumStack.Screen
name="AddAlbumManually"
component={AddAlbumManually}
options={({ route, navigation }) => ({
headerTitle: (
<Text
style={{
fontFamily: 'kulimpark-bold'
}}
>
Add manually
</Text>
),
headerBackTitleVisible: false,
headerBackImage: () => <CustomIcon name="back" color="#ffffff" style={{ marginLeft: 24 }} />,
headerStyle: {
backgroundColor: Colors.purple,
borderBottomWidth: 0,
borderBottomColor: '#ff2200',
shadowOpacity: 0
},
headerTintColor: '#fff',
headerRight: () => (
<CustomIcon
name="close"
color="#ffffff"
style={{ marginRight: 24 }}
// onPress={() =>
// route.params.from === 'collection'
// ? navigation.navigate('Collection')
// : navigation.navigate('Wantlist')
// }
/>
)
})}
/>
</ScanAlbumStack.Navigator>
)
}
const MainStackTabNavigtor = () => {
return (
<Tab.Navigator
screenOptions={({ route }) => ({
tabBarIcon: ({ focused, color, size }) => {
let iconName
if (route.name === 'FEED') {
iconName = 'sort'
} else if (route.name === 'COLLECTION') {
iconName = 'lp'
} else if (route.name === 'WANTLIST') {
iconName = 'discover'
} else if (route.name === 'ACCOUNT') {
iconName = 'user'
}
return <CustomIcon name={iconName} color={focused ? Colors.primaryColor : Colors.grey} />
}
})}
tabBarOptions={{
activeTintColor: Colors.primaryColor,
inactiveTintColor: '#8D819D'
}}
>
<Tab.Screen name="FEED" component={FeedStackScreen} />
<Tab.Screen name="COLLECTION" component={CollectionStackScreen} />
<Tab.Screen name="WANTLIST" component={WantlistStackScreen} />
<Tab.Screen name="ACCOUNT" component={AccountStackScreen} />
</Tab.Navigator>
)
}
const MainStackScreen = () => {
return (
<Stack.Navigator screenOptions={{ headerShown: false }}>
<Stack.Screen name="Main" component={MainStackTabNavigtor} />
<Stack.Screen
name="addAlbumModal"
component={ScanAlbumScreen}
options={{ headerShown: false }}
/>
</Stack.Navigator>
)
}
function SplashScreen() {
return (
<View>
<Text>Loading...</Text>
</View>
);
}
function ConnectScreen() {
const { authDiscogs } = useContext(AuthContext);
const toastConfig = {
'error': (internalState) => <ErrorNotification>{internalState.text1}</ErrorNotification>
}
return (
<View style={{ height: '100%' }}>
<Toast config={toastConfig} ref={(ref) => Toast.setRef(ref)} />
<Text>Version: {Version.version}</Text>
<Button title="Connect Discogs account" onPress={() => authDiscogs()} />
</View>
);
}
const Stack = createStackNavigator();
export default function App() {
const [state, dispatch] = useReducer(
(prevState, action) => {
switch (action.type) {
case 'RESTORE_TOKEN':
return {
...prevState,
requestToken: action.requestToken,
requestTokenSecret: action.requestTokenSecret,
authToken: action.token,
authTokenSecret: action.tokenSecret,
userData: action.userData,
isLoading: false,
};
case 'AUTH_DISCOGS_INIT':
return {
...prevState,
isLoading: true,
};
case 'AUTH_DISCOGS_SUCCESS':
return {
...prevState,
requestToken: null,
requestTokenSecret: null,
authToken: action.authToken,
authTokenSecret: action.authTokenSecret,
isSignedIn: true,
isLoading: false,
};
case 'AUTH_DISCOGS_ERROR':
return {
...prevState,
requestToken: null,
requestTokenSecret: null,
userData: null,
isLoading: false,
};
case 'AUTH_REFRESH_TOKENS':
return {
...prevState,
requestToken: action.requestToken,
requestTokenSecret: action.requestTokenSecret,
};
case 'SIGN_OUT':
return {
...prevState,
isSignedIn: false,
requestToken: action.requestToken,
requestTokenSecret: action.requestTokenSecret,
authToken: null,
authTokenSecret: null,
userData: null,
};
}
},
{
isLoading: true,
isSignedIn: false,
requestToken: null,
requestTokenSecret: null,
authToken: null,
authTokenSecret: null,
userData: null,
}
);
const [fontsLoaded, setFontsLoaded] = useState(false)
useEffect(() => {
const loadFonts = async () => {
await Font.loadAsync({
icomoon: require('./assets/fonts/icomoon.ttf'),
'kulimpark-regular': require('./assets/fonts/KulimPark-Regular.ttf'),
'kulimpark-bold': require('./assets/fonts/KulimPark-Bold.ttf')
})
setFontsLoaded(true)
}
loadFonts()
// Fetch the token from storage then navigate to our appropriate place
const bootstrapAsync = async () => {
let requestToken;
let requestTokenSecret;
let authToken;
let authTokenSecret;
let userData;
try {
requestToken = await AsyncStorage.getItem('requestToken');
requestTokenSecret = await AsyncStorage.getItem('requestTokenSecret');
authToken = await AsyncStorage.getItem('authToken');
authTokenSecret = await AsyncStorage.getItem('authTokenSecret');
userData = await AsyncStorage.getItem('userData');
} catch (err) {
// Restoring token failed
Sentry.Native.captureException(new Error(`🚨 ${err}`));
}
if (!requestToken) {
getDiscogsToken();
}
dispatch({ type: 'RESTORE_TOKEN', requestToken: requestToken, requestTokenSecret: requestTokenSecret, token: authToken, tokenSecret: authTokenSecret, userData: userData });
};
bootstrapAsync();
}, [])
const getDiscogsToken = async () => {
let newToken;
let newTokenSecret;
const getToken = async () => {
let response = await fetch('https://api.discogs.com/oauth/request_token', {
method: 'POST',
headers: {
'Content-type': 'application/x-www-form-urlencoded',
Authorization: `OAuth oauth_consumer_key="${CONSUMER_KEY}", oauth_nonce="${makeid(
10
)}", oauth_signature="${CONSUMER_SECRET}&", oauth_signature_method="PLAINTEXT", oauth_timestamp="${timestamp}", oauth_callback="https://auth.expo.io/@paulbremer/vinylooo", oauth_callback_confirmed="true"`
}
})
let data = await response.text()
return data
}
// 2. SEND A GET REQUEST TO THE DISCOGS REQUEST TOKEN URL
await getToken()
.then(async (data) => {
console.log('getDiscogsToken 2# ', data)
const token = data.match('oauth_token=(.*)&oauth_token_secret')[1]
const tokenSecret = data.match('oauth_token_secret=(.*)&oauth_callback_confirmed=true')[1]
storeData('requestToken', token)
storeData('requestTokenSecret', tokenSecret)
newToken = token
newTokenSecret = tokenSecret
})
.catch((err) => Sentry.Native.captureException(new Error(`🚨 ${err}`)))
return { newToken, newTokenSecret }
}
const getIdentity = async (token, secret) => {
console.log('getIdentity', token, secret)
try {
if (token !== null && secret !== null) {
fetch('https://api.discogs.com/oauth/identity', {
method: 'GET',
headers: {
'Content-type': 'application/x-www-form-urlencoded',
Authorization: `OAuth oauth_consumer_key="${CONSUMER_KEY}",oauth_token="${token}", oauth_signature_method="PLAINTEXT",oauth_timestamp="${timestamp}", oauth_nonce="${makeid(
10
)}", oauth_version="1.0", oauth_signature="${CONSUMER_SECRET}%26${secret}`
}
})
.then(async (data) => {
let json = await data.json()
if (json.username) {
storeData('username', json.username)
getUserInfo(token, secret, json.username)
} else {
console.log('heb geen username dus')
Toast.show({ type: 'error', text1: 'No user found', text2: 'This is some something 👋', visibilityTime: 4000, })
storeData('token', '')
storeData('secret', '')
}
})
.catch((err) => Sentry.Native.captureException(new Error(`🚨 ${err}`)))
}
} catch (err) {
Sentry.Native.captureException(new Error(`🚨 ${err}`));
}
}
const getUserInfo = async (token, secret, username) => {
console.log('getUserInfo', token, secret)
try {
if (token !== null && secret !== null) {
fetch(`https://api.discogs.com/users/${username}`, {
method: 'GET',
headers: {
'Content-type': 'application/x-www-form-urlencoded',
Authorization: `OAuth oauth_consumer_key="${CONSUMER_KEY}",oauth_token="${token}", oauth_signature_method="PLAINTEXT",oauth_timestamp="${timestamp}", oauth_nonce="${makeid(
10
)}", oauth_version="1.0", oauth_signature="${CONSUMER_SECRET}%26${secret}`
}
})
.then(async (data) => {
let json = await data.json()
console.log('💪🏼 ', json)
storeObject('userData', json)
// setUserInfo({ ...json, ...userInfo })
// setLoadedUserInfo(true)
// getCollectionValue(token, secret)
})
.catch((err) => Sentry.Native.captureException(new Error(`🚨 ${err}`)))
}
} catch (err) {
Sentry.Native.captureException(new Error(`🚨 ${err}`));
}
}
const discogsAuth = async () => {
if (!state.requestToken) {
dispatch({ type: 'AUTH_DISCOGS_ERROR' })
getDiscogsToken();
Toast.show({
type: 'error', position: 'bottom', topOffset: 0,
bottomOffset: 0, text1: 'No requestToken', text2: 'This is broken, sorry 👋', visibilityTime: 4000,
})
Sentry.Native.captureException(new Error('🚨 No requestToken'));
return
}
// 3. REDIRECT YOUR USER TO THE DISCOGS AUTHORIZE PAGE
let results = await AuthSession.startAsync({
authUrl: `https://discogs.com/oauth/authorize?oauth_token=${state.requestToken}`
})
if (results.type === 'success') {
if (results.params.denied) {
dispatch({ type: 'AUTH_DISCOGS_ERROR' })
const { newToken, newTokenSecret } = await getDiscogsToken();
dispatch({ type: 'AUTH_REFRESH_TOKENS', requestToken: newToken, requestTokenSecret: newTokenSecret });
}
await fetch('https://api.discogs.com/oauth/access_token', {
method: 'POST',
headers: {
'Content-type': 'application/x-www-form-urlencoded',
Authorization: `OAuth oauth_consumer_key="${CONSUMER_KEY}", oauth_nonce="${makeid(
10
)}", oauth_token="${results.params.oauth_token
}", oauth_signature="${CONSUMER_SECRET}&${state.requestTokenSecret}", oauth_signature_method="PLAINTEXT", oauth_timestamp="${timestamp}", oauth_verifier="${results.params.oauth_verifier
}"`
}
})
.then(async (response) => {
let data = await response.text()
console.log('4# ', data)
if (response.status === 200) {
const finalToken = data.match('oauth_token=(.*)&oauth_token_secret')[1]
const finalTokenSecret = data.match('oauth_token_secret=(.*)')[1]
storeData('token', finalToken)
storeData('secret', finalTokenSecret)
await AsyncStorage.setItem('authToken', finalToken);
await AsyncStorage.setItem('authTokenSecret', finalTokenSecret);
await getIdentity(finalToken, finalTokenSecret)
dispatch({ type: 'AUTH_DISCOGS_SUCCESS', authToken: finalToken, authTokenSecret: finalTokenSecret })
}
})
.catch((err) => {
Sentry.Native.captureException(new Error(`🚨 ${err}`));
})
} else {
dispatch({ type: 'AUTH_DISCOGS_ERROR' })
const { newToken, newTokenSecret } = await getDiscogsToken();
dispatch({ type: 'AUTH_REFRESH_TOKENS', requestToken: newToken, requestTokenSecret: newTokenSecret });
}
}
// In a production app, we need to send some data (usually username, password) to server and get a token
// We will also need to handle errors if sign in failed
// After getting token, we need to persist the token using `AsyncStorage`
const authContextValue = useMemo(
() => ({
authDiscogs: async () => {
dispatch({ type: 'AUTH_DISCOGS_INIT' })
await discogsAuth();
},
signOut: async () => {
removeData('requestToken')
removeData('requestTokenSecret')
removeData('authToken')
removeData('authTokenSecret')
removeData('userData')
const { newToken, newTokenSecret } = await getDiscogsToken();
dispatch({ type: 'SIGN_OUT', requestToken: newToken, requestTokenSecret: newTokenSecret });
},
}),
[state],
);
if (!fontsLoaded) {
return (
<View>
<Text>loading...</Text>
</View>
)
}
return (
<AuthContext.Provider value={authContextValue}>
<Provider store={store}>
<NavigationContainer>
<Stack.Navigator mode="modal">
{state.isLoading ? (
<Stack.Screen name="Splash" component={SplashScreen} />
) : state.authToken === null ? (
<Stack.Screen
name="SignIn"
component={ConnectScreen}
options={{
title: 'Connect',
animationTypeForReplace: state.isSignedIn ? 'push' : 'pop',
}}
/>
) : (
<Stack.Screen
name="Main"
component={MainStackScreen}
options={{ headerShown: false }}
/>
)}
</Stack.Navigator>
</NavigationContainer>
</Provider>
</AuthContext.Provider >
// <Provider store={store}>
// <AppearanceProvider>
// <NavigationContainer theme={MyTheme}>
// <RootStack.Navigator mode="modal">
// <RootStack.Screen name="Main" component={MainStackScreen} options={{ headerShown: false }} />
// <RootStack.Screen
// name="addAlbumModal"
// component={ScanAlbumScreen}
// options={{ headerShown: false }}
// />
// </RootStack.Navigator>
// </NavigationContainer>
// </AppearanceProvider>
// </Provider>
)
}