-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathuseIterableApp.tsx
More file actions
304 lines (257 loc) · 8.77 KB
/
useIterableApp.tsx
File metadata and controls
304 lines (257 loc) · 8.77 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
import type { StackNavigationProp } from '@react-navigation/stack';
import {
createContext,
useCallback,
useContext,
useState,
type FunctionComponent,
} from 'react';
import { Alert, Platform } from 'react-native';
import {
Iterable,
IterableAction,
IterableConfig,
IterableInAppShowResponse,
IterableLogLevel,
IterableRetryBackoff,
IterableAuthFailureReason,
} from '@iterable/react-native-sdk';
import { Route } from '../constants/routes';
import type { RootStackParamList } from '../types/navigation';
import NativeJwtTokenModule from '../NativeJwtTokenModule';
type Navigation = StackNavigationProp<RootStackParamList>;
interface IterableAppProps {
/** The API key for your Iterable instance */
apiKey?: string;
/** The configuration of the RN SDK */
config: IterableConfig | null;
/**
* Call to initialize the Iterable SDK
* @param navigation - The navigation prop from the screen
* @returns Promise<boolean> Whether the initialization was successful
*/
initialize: (navigation: Navigation) => void;
/** Whether the SDK has been initialized */
isInitialized?: boolean;
/** Is the tab in focus the `Inbox` tab? */
isInboxTab: boolean;
/** Whether the user is logged in */
isLoggedIn?: boolean;
/**
* Call to log in the user
* @returns Promise<boolean> Whether the login was successful
*/
login: () => void;
/** Whether the login is in progress */
loginInProgress?: boolean;
/** Logs the user out */
logout: () => void;
/** Should the iterable inbox return to the list of messages? */
returnToInboxTrigger: boolean;
/** Sets the API key for the user */
setApiKey: (value: string) => void;
/** Sets whether the tab in focus is the `Inbox` tab */
setIsInboxTab: (value: boolean) => void;
/** Sets whether the login is in progress */
setLoginInProgress: (value: boolean) => void;
/** Sets whether the iterable inbox should return to the list of messages */
setReturnToInboxTrigger: (value: boolean) => void;
/** Sets the user ID for the user */
setUserId: (value: string) => void;
/** The user ID for the user */
userId?: string | null;
}
const IterableAppContext = createContext<IterableAppProps>({
apiKey: undefined,
config: null,
initialize: () => undefined,
isInboxTab: false,
isInitialized: false,
isLoggedIn: false,
login: () => undefined,
loginInProgress: false,
logout: () => undefined,
returnToInboxTrigger: false,
setApiKey: () => undefined,
setIsInboxTab: () => undefined,
setLoginInProgress: () => undefined,
setReturnToInboxTrigger: () => undefined,
setUserId: () => undefined,
userId: null,
});
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const getIsEmail = (id: string) => EMAIL_REGEX.test(id);
let lastTimeStamp = 0;
export const IterableAppProvider: FunctionComponent<
React.PropsWithChildren<unknown>
> = ({ children }) => {
const [returnToInboxTrigger, setReturnToInboxTrigger] =
useState<boolean>(false);
const [isInboxTab, setIsInboxTab] = useState<boolean>(false);
const [itblConfig, setItblConfig] = useState<IterableConfig | null>(null);
const [isLoggedIn, setIsLoggedIn] = useState<boolean>(false);
const [isInitialized, setIsInitialized] = useState<boolean>(false);
const [apiKey, setApiKey] = useState<string | undefined>(
process.env.ITBL_API_KEY
);
const [userId, setUserId] = useState<string | null>(
process.env.ITBL_ID ?? null
);
const [loginInProgress, setLoginInProgress] = useState<boolean>(false);
const getUserId = useCallback(() => userId ?? process.env.ITBL_ID, [userId]);
const getJwtToken = useCallback(async () => {
const id = userId ?? process.env.ITBL_ID;
const idType = getIsEmail(id as string) ? 'email' : 'userId';
const secret = process.env.ITBL_JWT_SECRET ?? '';
const duration = 1000 * 60 * 60 * 24; // 1 day in milliseconds
const jwtToken = await NativeJwtTokenModule.generateJwtToken(
secret,
duration,
idType === 'email' ? (id as string) : null, // Email (can be null if userId is provided)
idType === 'userId' ? (id as string) : null // UserId (can be null if email is provided)
);
return jwtToken;
}, [userId]);
const login = useCallback(async () => {
const id = userId ?? process.env.ITBL_ID;
if (!id) return Promise.reject('No User ID or Email set');
setLoginInProgress(true);
const fn = getIsEmail(id) ? Iterable.setEmail : Iterable.setUserId;
let token;
if (process.env.ITBL_IS_JWT_ENABLED === 'true' && process.env.ITBL_JWT_SECRET) {
token = await getJwtToken();
}
fn(id, token);
setIsLoggedIn(true);
setLoginInProgress(false);
return Promise.resolve(true);
}, [getJwtToken, userId]);
const initialize = useCallback(
(navigation: Navigation) => {
logout();
const config = new IterableConfig();
config.inAppDisplayInterval = 1.0; // Min gap between in-apps. No need to set this in production.
config.retryPolicy = {
maxRetry: 5,
retryInterval: 5,
retryBackoff: IterableRetryBackoff.linear,
};
config.enableEmbeddedMessaging = true;
config.onJwtError = (authFailure) => {
console.log('onJwtError', authFailure);
const failureReason =
typeof authFailure.failureReason === 'string'
? authFailure.failureReason
: IterableAuthFailureReason[authFailure.failureReason];
Alert.alert(
`Error fetching JWT: ${failureReason}`,
`Token: ${authFailure.failedAuthToken}`
);
};
config.urlHandler = (url: string) => {
const routeNames = [Route.Commerce, Route.Inbox, Route.User];
for (const route of routeNames) {
if (url.includes(route.toLowerCase())) {
// [MOB-10418](https://iterable.atlassian.net/browse/MOB-10418): Figure out typing for this
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
navigation.navigate(route);
return true;
}
}
return false;
};
config.customActionHandler = (action: IterableAction) => {
Alert.alert('Custom Action Handler', 'actionType: ' + action.type);
return true;
};
config.allowedProtocols = ['app', 'iterable'];
config.logLevel = IterableLogLevel.debug;
config.enableEmbeddedMessaging = true;
config.inAppHandler = () => IterableInAppShowResponse.show;
if (
process.env.ITBL_IS_JWT_ENABLED === 'true' &&
process.env.ITBL_JWT_SECRET
) {
config.authHandler = async () => {
console.group('authHandler');
const now = Date.now();
if (lastTimeStamp !== 0) {
console.log('Time since last call:', now - lastTimeStamp);
}
lastTimeStamp = now;
console.groupEnd();
// return 'InvalidToken'; // Uncomment this to test the failure callback
const token = await getJwtToken();
return token;
};
}
setItblConfig(config);
const key = apiKey ?? process.env.ITBL_API_KEY;
if (!key) {
console.error('No API key found.');
return Promise.resolve(false);
}
// Initialize app
return Iterable.initialize(key, config)
.then((isSuccessful) => {
setIsInitialized(isSuccessful);
if (isSuccessful && getUserId()) {
return login();
}
if (!isSuccessful) {
return Promise.reject('`Iterable.initialize` failed');
}
return isSuccessful;
})
.catch((err) => {
console.error(
'`Iterable.initialize` failed with the following error',
err
);
if (Platform.OS === 'ios' && getUserId()) {
setIsInitialized(true);
return login();
}
setIsInitialized(false);
setLoginInProgress(false);
return Promise.reject(err);
});
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[getUserId, apiKey, login, getJwtToken, userId]
);
const logout = useCallback(() => {
Iterable.setEmail(null);
Iterable.setUserId(null);
Iterable.logout();
lastTimeStamp = 0;
setIsLoggedIn(false);
}, []);
return (
<IterableAppContext.Provider
value={{
apiKey,
config: itblConfig,
initialize,
isInboxTab,
isInitialized,
isLoggedIn,
login,
loginInProgress,
logout,
returnToInboxTrigger,
setApiKey,
setIsInboxTab,
setLoginInProgress,
setReturnToInboxTrigger,
setUserId,
userId,
}}
>
{children}
</IterableAppContext.Provider>
);
};
export const useIterableApp = () => useContext(IterableAppContext);
export default useIterableApp;