forked from rotembcohen/pokerBuddyApp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
UtilFunctions.js
324 lines (267 loc) · 9.1 KB
/
UtilFunctions.js
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
import React from 'react';
import { AsyncStorage } from 'react-native';
import { NavigationActions } from 'react-navigation';
import { Permissions, Notifications, Constants } from 'expo';
import { APP_VERSION, SERVER_ADDRESS, PASSWORD_HASH_SECRET } from 'react-native-dotenv';
import AppLink from 'react-native-app-link';
var CryptoJS = require("crypto-js");
//TODO: better network error check across the board
export async function fetchFromServer(relative_url,method,body_dict,token=null){
var headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
if (token){
headers['Authorization'] = 'Token ' + token;
}
let content = {};
content['method'] = method;
content['headers'] = headers;
console.log(
"====================="
+ "\n" +"API request type: " + method
+ "\n" + "Relative URL: " + relative_url
+ "\n" + "Headers: " + JSON.stringify(headers)
);
if (method!=='GET'){
let body = JSON.stringify(body_dict);
console.log("Request body: " + body);
content['body'] = body;
}
//TODO: handle promise error
const response = await fetch(SERVER_ADDRESS + relative_url, content);
//TODO: return error that says something
if (response.status / 100 < 4){
console.log("\n"+ "API Response: Status " + response.status + "\nContent: \n"+ response._bodyText);
}else{
console.log("\n"+ "API Error type: " +response.status + "\nContent: \n" + response._bodyText);
}
console.log("\n" + "=====================");
return response;
}
export async function joinGame(game_identifier,token,user){
//current user (whose token it is) might not be the user joining game
//TODO: allow a host to add a different user to the game
valid_identifier = game_identifier.toUpperCase();
if (valid_identifier.length !== 5){
return;
}
const response = await fetchFromServer('games/' + valid_identifier + '/join_game/','POST',{player_id:user.id},token);
//TODO: add error check
if (response.status === 200){
game = JSON.parse(response._bodyText);
await AsyncStorage.setItem('@pokerBuddy:currentGame', game.identifier);
return game;
}else{
return {error:'Game address not found'};
}
}
export async function loginWithCreds(username,password){
var response = null;
try{
response = await fetchFromServer('authenticate/','POST',{
username: username,
password: password,
},null);
}
catch(error){
console.log(error);
response = {status: 500};
}
if (response.status===200){
const responseJson = await response.json();
let token = responseJson.token;
let userObj = responseJson.user;
let user = JSON.stringify(userObj);
//console.log("Recieved token: " + token);
//TODO: remove everything but saving token?
await AsyncStorage.multiSet([['@pokerBuddy:token', token], ['@pokerBuddy:user', user]]);
//navigation.navigate('HomeView',{user: userObj,token:token});
return {token: token, user: userObj, error: 'None'};
}else if (response.status===400){
return {error: 'Wrong username + password combination'};
}else{
return {error:'Server Unavailable'};
}
}
export function backOneScreen(navigation){
const backAction = NavigationActions.back();
navigation.dispatch(backAction);
}
export function resetToScreen(navigation,screen,params=null){
var options = { routeName: screen };
if (params){
options['params'] = params;
}
const resetAction = NavigationActions.reset({
index: 0,
actions: [
NavigationActions.navigate(options)
]
});
navigation.dispatch(resetAction);
}
//TODO: add way to push updates/ or check updates frequently
//TODO: duplicate code!
export async function buy_in(buy_in_amount,game_identifier,token,player_id=null){
const gameObj = await fetchFromServer('games/' + game_identifier + "/buy_in/",'POST',{
amount: Number(buy_in_amount),
player_id: player_id
},token);
if (gameObj.status === 200){
gameString = gameObj._bodyText;
let game = JSON.parse(gameString);
return game;
}
}
export async function leave_game(result_amount,game_identifier,token,player_id=null){
const gameObj = await fetchFromServer('games/' + game_identifier + "/leave_game/",'POST',{
result: Number(result_amount),
player_id: player_id
},token);
if (gameObj.status === 200){
gameString = gameObj._bodyText;
let game = JSON.parse(gameString);
return game;
}
}
export async function user_registration(form,login=true) {
var initResponse = null;
try{
initResponse = await fetchFromServer('users/','POST',form,null);
}
catch(error){
console.log(error);
initResponse = {status: 500};
}
if (login===false){
return {error:'None',user:JSON.parse(initResponse._bodyText)};
}
if (initResponse.status === 201){
//get token
//TODO: fix server so this wont need 2 requests
//TODO: this should behave like fetchFromServer (at lease as far as retrun value)
const response = await loginWithCreds(form.username,form.password);
if (response.error === 'None'){
return {user:response.user,token:response.token,error:'None'};
}else{
return {error:response.error};
}
}
}
//handle push notifications
export async function registerForPushNotificationsAsync(user_id) {
const { existingStatus } = await Permissions.getAsync(Permissions.NOTIFICATIONS);
let finalStatus = existingStatus;
// only ask if permissions have not already been determined, because
// iOS won't necessarily prompt the user a second time.
if (existingStatus !== 'granted') {
// Android remote notification permissions are granted during the app
// install, so this will only ask on iOS
const { status } = await Permissions.askAsync(Permissions.NOTIFICATIONS);
finalStatus = status;
}
// Stop here if the user did not grant permissions
if (finalStatus !== 'granted') {
return;
}
// Get the token that uniquely identifies this device
let token = await Notifications.getExpoPushTokenAsync();
// POST the token to our backend so we can use it to send pushes from there
response = await fetchFromServer('users/'+ user_id +'/push_token/','POST',{
push_token: token,
},null);
if (response.status === 200){
user = await response.json();
return {user: user,error:'None'};
}
return {error:'Server Error'};
}
export async function RedirectToGame(navigation){
const data = await AsyncStorage.multiGet(['@pokerBuddy:token','@pokerBuddy:user','@pokerBuddy:currentGame']);
if (data){
var token = (data[0][1]!==null) ? data[0][1] : null;
var user = (data[1][1]!==null) ? JSON.parse(data[1][1]) : null;
var game_identifier = (data[2][1]!==null) ? data[2][1] : null;
}
//backwards compatibility
//TODO: remove from code versions that are no longer in use
if (token && user){
if (typeof user.app_version === 'undefined'){
//temp app version, cause users with older versions won't have it in their saved user object
user.app_version = "1.2";
}else if (user.app_version === "1.3" || user.app_version === "1.4"){
//latest, do nothing
}else{
console.log("Unknown app version");
}
//update app_version if needed
if (user.app_version !== APP_VERSION){
response = await this.fetchFromServer(
'users/' + user.id + '/update_app_version/',
'POST',
{
app_version:APP_VERSION
},
token
);
user = await response.json();
await AsyncStorage.setItem('@pokerBuddy:user', JSON.stringify(user));
}
}
if (token && user && game_identifier){
//player in middle of a game
game = await this.joinGame(game_identifier,token,user);
if (!game.error || game.error === "None"){
this.resetToScreen(navigation,"GameView",{game: game,user: user,token:token});
return;
}
}
if (token && user){
//player logged in
AsyncStorage.removeItem('@pokerbuddy:currentGame');
this.resetToScreen(navigation,"HomeView",{token:token,user:user});
}else{
//player not authenticated
this.resetToScreen(navigation,"LoginView");
}
//TODO: error handling
}
export function timeout(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
export function getUrlField(variable,prefix) {
let field = '';
if (variable) {
field = prefix + variable;
}
return field;
}
export function useVenmo(method,recipient=null,amount=null,note=null) {
let recipient_field = this.getUrlField(recipient,"&recipients=");
let amount_field = this.getUrlField(amount,"&amount=");
let note_field = this.getUrlField(note,"¬e=");
var url = "venmo://paycharge?txn="+ method + recipient_field + amount_field + note_field;
AppLink.maybeOpenURL(url, { appName: 'Venmo', appStoreId: 'id351727428', playStoreId: 'com.venmo'}).then(() => {
// console.log("app link success");
})
.catch((err) => {
console.log("app link error: ", error);
});
}
export async function updateVenmo(venmo_username,user,token){
const response = await this.fetchFromServer(
'users/' + user.id + '/update_venmo/',
'POST',
{
venmo_username:venmo_username
},
token
);
//TODO: handle errors!
user.venmo_username = venmo_username;
await AsyncStorage.setItem('@pokerBuddy:user', JSON.stringify(user));
}
export function hashPassword(string){
return (CryptoJS.HmacSHA1(string, PASSWORD_HASH_SECRET)).toString();
}