@inngageregistry/inngage-react 2.3.2 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js DELETED
@@ -1,555 +0,0 @@
1
- import { firebase } from '@react-native-firebase/messaging';
2
- import DeviceInfo from "react-native-device-info";
3
- import * as RNLocalize from "react-native-localize";
4
- import { formatDate, subscriptionRequestAdapter, showAlertLink } from "./utils";
5
- import ListenToNotifications, { linkInApp } from "./ListenToNotifications";
6
- import { subscription, eventsApi } from "./inngageApi";
7
- import AsyncStorage from '@react-native-async-storage/async-storage';
8
- import Carousel, { Pagination } from 'react-native-snap-carousel';
9
- import React, { useState, useEffect, useRef } from 'react';
10
-
11
- import {
12
- Platform,
13
- Modal,
14
- View,
15
- Text,
16
- Dimensions,
17
- StyleSheet,
18
- TouchableHighlight,
19
- TouchableOpacity,
20
- Image,
21
- LogBox,
22
- AppRegistry,
23
- ScrollView,
24
- ImageBackground,
25
- Linking
26
- } from "react-native";
27
-
28
-
29
- //-------------- In-APP Component -------------//
30
-
31
-
32
- const SLIDER_WIDTH = Dimensions.get('window').width;
33
- const SLIDER_HEIGHT = Dimensions.get('window').height;
34
- const ITEM_WIDTH = Math.round(SLIDER_WIDTH * 0.8);
35
- const ITEM_HEIGHT = Math.round(SLIDER_HEIGHT * 0.8);
36
-
37
- export const Inapp = (props) => {
38
- const [data, setData] = useState([])
39
- const [ind, setInd] = useState(0)
40
- const [indIm, setIndImg] = useState(0)
41
- const [visible, setVisible] = useState(true)
42
- const [modalImage, setModalImage] = useState(false)
43
- const [bgImage, setbgImage] = useState(undefined)
44
-
45
- const CarouselRef = useRef(null);
46
- const ScrollRef1 = useRef(null);
47
- const ScrollRef2 = useRef(null);
48
- const ScrollRef3 = useRef(null);
49
-
50
-
51
- _renderItem = ({ item, index }) => {
52
- let msg = JSON.parse(item.data.additional_data)
53
- let arrayImgs = []
54
- let indImg = 0
55
-
56
- const checkBG = () => {
57
- if (msg.background_img != '') {
58
- return null
59
- } else {
60
- return msg.background_color
61
- }
62
- }
63
-
64
- const itemStyles = StyleSheet.create({
65
- btn_left: {
66
- backgroundColor: msg.btn_left_bg_color || "#FFFFFF",
67
- height: 40,
68
- width: 100,
69
- alignItems: 'center',
70
- justifyContent: 'center',
71
- marginRight: 20,
72
- marginLeft: 10,
73
- flex: 1
74
- },
75
- btn_right: {
76
- backgroundColor: msg.btn_right_bg_color || "#FFFFFF",
77
- height: 40,
78
- width: 100,
79
- alignItems: 'center',
80
- justifyContent: 'center',
81
- marginRight: 10,
82
- flex: 1
83
- },
84
- btn_left_title: {
85
- color: msg.btn_left_txt_color || "#000000"
86
- },
87
- btn_right_title: {
88
- color: msg.btn_right_txt_color || "#000000"
89
- },
90
- body: {
91
- backgroundColor: checkBG(),
92
- width: '100%',
93
- height: 450,
94
- alignSelf: 'center',
95
- alignItems: 'center',
96
- justifyContent: 'center',
97
- },
98
- bodyText: {
99
- color: msg.body_font_color || "#000000",
100
- textAlign: 'justify',
101
- marginBottom: 10,
102
- fontSize: 15,
103
- marginHorizontal: 10
104
- },
105
- title: {
106
- color: msg.title_font_color || "#000000",
107
- fontWeight: "bold",
108
- fontSize: 18,
109
- marginTop: 40
110
- },
111
- dot: {
112
- backgroundColor: msg.dot_color || "#FFFFFF",
113
- borderRadius: 100,
114
- width: 8,
115
- height: 8,
116
- marginLeft: 5,
117
- elevation: 5,
118
- }
119
- });
120
-
121
- chooseRef = () => {
122
- if (index == 0) {
123
- return ScrollRef1
124
- }
125
- if (index == 1) {
126
- return ScrollRef2
127
- }
128
- if (index == 2) {
129
- return ScrollRef3
130
- }
131
- }
132
-
133
-
134
- pagination = ref => {
135
- return (
136
- <Pagination
137
- dotsLength={arrayImgs.length}
138
- activeDotIndex={indIm}
139
- containerStyle={{ height: 2, padding: 0, margin: 0 }}
140
- renderDots={(activeIndex, total, context) => {
141
- let dots = []
142
- var size = 0
143
- for (let i = 0; i < total; i++) {
144
- if (activeIndex == i) {
145
- size = 13
146
- } else {
147
- size = 8
148
- }
149
- dots.push(
150
- <TouchableOpacity
151
- onPress={() => {
152
- ref.current.scrollTo({ x: i * 220, y: 0, animated: true })
153
- if (i * 220 === 0) {
154
- setIndImg(0)
155
- } else if (i * 220 === 220) {
156
- setIndImg(1)
157
- } else if (i * 220 === 440) {
158
- setIndImg(2)
159
- }
160
- }}
161
- key={i.toString()}
162
- style={[itemStyles.dot, { width: size, height: size }]}
163
- />
164
- )
165
- }
166
- return (
167
- dots
168
- )
169
- }
170
- }
171
- />
172
- );
173
- }
174
-
175
- const handleButton = (title, body, url, type) => {
176
- if (type === '' || url === '') {
177
- return
178
- }
179
- console.log(title, body, url, type)
180
- const openLinkByType = (type, url) => (type === 'deep' ? Linking.openURL(url) : linkInApp(url))
181
-
182
- return Linking.canOpenURL(url).then((supported) => {
183
- if (supported) {
184
- showAlertLink(
185
- title,
186
- body,
187
- `${DeviceInfo.getApplicationName()}`,
188
- `Acessar ${url} ?`,
189
- ).then((response) => { supported && openLinkByType(type, url) })
190
- }
191
- }).catch(console.log)
192
- }
193
-
194
- const imgCarosel = () => {
195
- if (msg.rich_content.carousel == true) {
196
- if (msg.rich_content.img1 != '') {
197
- arrayImgs.push({ url: msg.rich_content.img1 })
198
- }
199
- if (msg.rich_content.img2 != '') {
200
- arrayImgs.push({ url: msg.rich_content.img2 })
201
- }
202
- if (msg.rich_content.img3 != '') {
203
- arrayImgs.push({ url: msg.rich_content.img3 })
204
- }
205
- let arrayElements = arrayImgs.map((item, index) => (
206
- <Image key={index.toString()} style={[props.mediaStyle, { width: 200, height: 200, marginRight: 10 }]} source={{ uri: item.url }} />
207
- ));
208
- return arrayElements
209
- } else if (arrayImgs.length <= 0) {
210
- return (
211
- <Image style={[props.mediaStyle, { width: 200, height: 200 }]} source={{ uri: item.data.picture }} />
212
- )
213
- }
214
- else {
215
- return (
216
- <Image style={[props.mediaStyle, { width: 200, height: 200 }]} source={{ uri: item.data.picture }} />
217
- )
218
- }
219
- }
220
- return (
221
- <View style={[itemStyles.body]}>
222
- <Text style={[itemStyles.title, props.titleStyle]}>{msg.title}</Text>
223
- <ScrollView
224
- ref={chooseRef()}
225
- horizontal
226
- snapToInterval={220}
227
- decelerationRate="fast"
228
- showsHorizontalScrollIndicator={false}
229
- style={{ width: 200, height: 240 }}
230
- contentContainerStyle={{ alignItems: 'center', justifyContent: 'center' }}
231
- onMomentumScrollEnd={(e) => {
232
- if (Math.round(e.nativeEvent.contentOffset.x) === 0
233
- ) {
234
- indImg = 0
235
- setIndImg(indImg)
236
- }
237
- if (Math.round(e.nativeEvent.contentOffset.x) === 220
238
- ) {
239
- indImg = 1
240
- setIndImg(indImg)
241
- }
242
- if (Math.round(e.nativeEvent.contentOffset.x) === 430
243
- ) {
244
- indImg = 2
245
- setIndImg(indImg)
246
- }
247
- }}
248
- >
249
- {imgCarosel()}
250
- </ScrollView>
251
- {
252
- msg.rich_content.carousel == true ?
253
- pagination(chooseRef()) : null
254
-
255
- }
256
- <Text style={[itemStyles.bodyText, props.bodyStyle]}>{msg.body}</Text>
257
- {/* <Text style={[styles.counter, props.counterStyle]}>
258
- {ind + 1} de {data.length} Mensagens
259
- </Text> */}
260
- <View style={{ flexDirection: "row", marginBottom: 0, justifyContent: 'center' }}>
261
- <TouchableOpacity onPress={() => handleButton(msg.title, msg.body, msg.btn_left_action_link, msg.btn_left_action_type)} style={[itemStyles.btn_left, props.buttonLeftStyle]}>
262
- <View>
263
- <Text style={[itemStyles.btn_left_title, props.buttonTitleLeftStyle]}>{msg.btn_left_txt}</Text>
264
- </View>
265
- </TouchableOpacity>
266
- <TouchableOpacity onPress={() => handleButton(msg.title, msg.body, msg.btn_right_action_link, msg.btn_right_action_type)} style={[itemStyles.btn_right, props.buttonRightStyle]}>
267
- <View>
268
- <Text style={[itemStyles.btn_right_title, props.buttonTitleRightStyle]}>{msg.btn_right_txt}</Text>
269
- </View>
270
- </TouchableOpacity>
271
- </View>
272
- </View>
273
- );
274
- }
275
-
276
- useEffect(() => {
277
- onLoad();
278
- }, [])
279
-
280
- onLoad = async () => {
281
- let temp = []
282
- const messages = JSON.parse(await AsyncStorage.getItem('inngage'))
283
- if (messages !== null) {
284
- messages.forEach((el, index) => {
285
- if (!isEmpty(el)) {
286
- temp.push(el)
287
- }
288
- })
289
- let msg = JSON.parse(temp[0].data.additional_data)
290
- if (msg.background_img != '') {
291
- setbgImage({ uri: msg.background_img })
292
- } else {
293
- setbgImage(undefined)
294
- }
295
- setData(temp)
296
- }
297
- }
298
-
299
- handleClose = async () => {
300
- if (props.onClose) {
301
- if (props.onClose.toLowerCase() === 'clear') {
302
- await AsyncStorage.removeItem('inngage');
303
- }
304
- }
305
- setVisible(false)
306
- }
307
-
308
- handleBg = index => {
309
- let msg = JSON.parse(data[index].data.additional_data)
310
- if (msg.background_img != '') {
311
- setbgImage({ uri: msg.background_img })
312
- } else {
313
- setbgImage(undefined)
314
- }
315
- }
316
-
317
- if (data.length > 0) {
318
- return (
319
- <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
320
- <Modal
321
- animationType='slide'
322
- visible={visible}
323
- transparent={true}
324
- style={{ justifyContent: 'center', alignItems: 'center', backgroundColor: 'blue' }}
325
- ><View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
326
- <View style={[styles.styleContainer, props.styleContainer]}>
327
- <ImageBackground style={{ widht: '100%', alignItems: 'center', justifyContent: 'center' }} resizeMode='cover' imageStyle={{ borderRadius: 10, alignSelf: 'stretch', height: 480 }} source={bgImage}>
328
- <TouchableHighlight
329
- onPress={() => handleClose()}
330
- underlayColor='#cccccc'
331
- style={styles.closeButton}
332
- >
333
- <Text style={{ fontWeight: 'bold', color: '#ffffff' }}>
334
- X
335
- </Text>
336
- </TouchableHighlight>
337
- <Carousel
338
- vertical
339
- ref={CarouselRef}
340
- layout={'default'}
341
- layoutCardOffset={10}
342
- data={data}
343
- inactiveSlideOpacity={0}
344
- containerCustomStyle={styles.carouselContainer}
345
- contentContainerCustomStyle={{ justifyContent: 'center' }}
346
- inactiveSlideShift={0}
347
- onSnapToItem={(index) => {
348
- setInd(index);
349
- handleBg(index)
350
- }}
351
- renderItem={(item, index) => _renderItem(item, index, CarouselRef)}
352
- sliderHeight={500}
353
- itemHeight={500}
354
- />
355
- </ImageBackground>
356
- </View>
357
- </View>
358
- </Modal>
359
- </View>
360
- );
361
- } else {
362
- return null
363
- }
364
- };
365
-
366
- const styles = StyleSheet.create({
367
- carouselContainer: {
368
- width: "100%",
369
- marginTop: 10,
370
- },
371
- styleContainer: {
372
- backgroundColor: 'white',
373
- elevation: 10,
374
- borderRadius: 10,
375
- width: SLIDER_WIDTH * 0.8,
376
- height: 480,
377
- },
378
- counter: {
379
- alignSelf: 'center',
380
- marginVertical: 10
381
- },
382
- closeButton: {
383
- position: 'absolute',
384
- alignSelf: 'flex-end',
385
- right: 20,
386
- top: 20,
387
- width: 30,
388
- height: 30,
389
- borderRadius: 20,
390
- backgroundColor: '#00000020',
391
- justifyContent: 'center',
392
- alignItems: 'center',
393
- zIndex: 90,
394
- },
395
- });
396
-
397
-
398
- // Inapp.propTypes = {
399
- // onClose: PropTypes.string,
400
- // leftButtonTitle: PropTypes.string.isRequired,
401
- // rightButtonTitle: PropTypes.string.isRequired,
402
- // };
403
-
404
-
405
- function isEmpty(obj) {
406
- for (var prop in obj) {
407
- if (obj.hasOwnProperty(prop)) {
408
- return false;
409
- }
410
- }
411
-
412
- return JSON.stringify(obj) === JSON.stringify({});
413
- }
414
-
415
- // fetch logger'
416
- // global._fetch = fetch;
417
- // global.fetch = function (uri, options, ...args) {
418
- // return global._fetch(uri, options, ...args).then(response => {
419
- // console.log("Fetch", { request: { uri, options, ...args }, response });
420
- // return response;
421
- // });
422
- // };
423
-
424
- // --- handle background message ------/
425
- const backgroundNotificationHandler = async remoteMessage => {
426
- var messageArray = [];
427
- console.log('Called')
428
- const currentMessages = await AsyncStorage.getItem('messages');
429
- if (currentMessages !== null) {
430
- messageArray = JSON.parse(currentMessages);
431
- }
432
- messageArray.push(remoteMessage);
433
- await AsyncStorage.setItem('messages', JSON.stringify(messageArray));
434
- };
435
-
436
- // --- Get Firebase Access ------/
437
- const getFirebaseAccess = () => {
438
- let firebaseToken = 'W7SAl94Jk6l3w95W9wCgmv3zZ99V5FReNUytdgJUFUvpvZoqXf72'
439
- return new Promise(async (resolve, reject) => {
440
- DeviceInfo.isEmulator().then(isEmulator => {
441
- if (isEmulator && Platform.OS === "ios") {
442
- return resolve(firebaseToken)
443
- }
444
- })
445
- try {
446
- await firebase.messaging().registerDeviceForRemoteMessages()
447
- const permission = await firebase.messaging().hasPermission()
448
- if (!permission) {
449
- try {
450
- await firebase.messaging().requestPermission()
451
- } catch (e) {
452
- console.log(e)
453
- return resolve(firebaseToken)
454
- }
455
- }
456
- try {
457
- firebaseToken = await firebase.messaging().getToken()
458
- } catch (error) {
459
- console.log(error)
460
- return resolve(firebaseToken)
461
- }
462
- return resolve(firebaseToken)
463
- } catch (err) {
464
- console.log(err)
465
- return resolve(firebaseToken)
466
- }
467
- });
468
- };
469
-
470
-
471
- const Inngage = {
472
- // ------------ Get Permission ------------------//
473
- GetPermission: async (props) => {
474
-
475
- try {
476
- LogBox.ignoreLogs(['registerHeadlessTask'])
477
- } catch (e) { }
478
- try {
479
- console.ignoredYellowBox = ['registerHeadlessTask'];
480
- } catch (e) { }
481
- try {
482
- AppRegistry.registerHeadlessTask('ReactNativeFirebaseMessagingHeadlessTask', () => backgroundNotificationHandler)
483
- ListenToNotifications(props);
484
- } catch (e) {
485
- console.error(e);
486
- return { subscribed: false };
487
- }
488
- },
489
- Subscription: async (props) => {
490
- try {
491
- const {
492
- appToken,
493
- dev,
494
- friendlyIdentifier,
495
- customFields,
496
- customData,
497
- phoneNumber,
498
- authKey
499
- } = props;
500
- const respToken = await getFirebaseAccess()
501
-
502
- const locales = RNLocalize.getLocales();
503
-
504
- const os_language = locales && locales.length ? locales[0].languageCode : ''
505
- const device_manufacturer = await DeviceInfo.getManufacturer();
506
- const installTime = await DeviceInfo.getFirstInstallTime();
507
- const lastUpdateTime = await DeviceInfo.getLastUpdateTime();
508
- const app_installed_in = formatDate(installTime);
509
- app_updated_in = formatDate(lastUpdateTime);
510
-
511
- const rawRequest = {
512
- registerSubscriberRequest: {
513
- app_token: appToken,
514
- identifier: friendlyIdentifier,
515
- registration: respToken,
516
- phone_Number: phoneNumber,
517
- platform: DeviceInfo.getSystemName(),
518
- sdk: DeviceInfo.getBuildNumber(),
519
- device_model: DeviceInfo.getModel(),
520
- device_manufacturer,
521
- os_locale: RNLocalize.getCountry(),
522
- os_language,
523
- os_version: DeviceInfo.getReadableVersion(),
524
- app_version: DeviceInfo.getBuildNumber(),
525
- app_installed_in,
526
- app_updated_in,
527
- uuid: DeviceInfo.getUniqueId(),
528
- authKey
529
- }
530
- };
531
-
532
- const request = subscriptionRequestAdapter(rawRequest, customData, customFields)
533
- const subscribe = await subscription(request, dev);
534
- console.log(await subscribe.json())
535
- return subscribe;
536
- } catch (e) {
537
- console.error(e);
538
- return { subscribed: false };
539
- }
540
- },
541
- SendEvent: async (props) => {
542
- const { authKey, newEventRequest } = props
543
- const rawRequest = {
544
- registerSubscriberRequest: {
545
- authKey
546
- },
547
- newEventRequest
548
- }
549
- const subscribe = await eventsApi(rawRequest);
550
- return subscribe
551
- }
552
- }
553
-
554
-
555
- export default Inngage;
package/inngageApi.js DELETED
@@ -1,5 +0,0 @@
1
- import { fetchClient } from './utils'
2
-
3
- export const subscription = (request, dev = false) => fetchClient('POST', request, '/subscription/', !!dev)
4
- export const notificationApi = (request, dev = false) => fetchClient('POST', request, '/notification/', !!dev)
5
- export const eventsApi = (request, dev = false) => fetchClient('POST', request, '/events/newEvent/', !!dev)
package/utils.js DELETED
@@ -1,84 +0,0 @@
1
- import { Alert } from 'react-native'
2
-
3
- const baseUrlHook = {
4
- [false]: 'https://api.inngage.com.br/v1',
5
- [undefined]: 'https://api.inngage.com.br/v1',
6
- [null]: 'https://api.inngage.com.br/v1',
7
- [true]: 'https://apid.inngage.com.br/v1',
8
- }
9
-
10
- const requestConfigFactory = (method, request) => {
11
-
12
- let header = {
13
- Accept: 'application/json',
14
- 'Content-Type': 'application/json',
15
- }
16
- try{
17
- if (request.registerSubscriberRequest.authKey) {
18
- header = {
19
- ...header,
20
- Authorization: request.registerSubscriberRequest.authKey
21
- }
22
- }
23
- }catch(e){
24
- console.log(e)
25
- }
26
- let objToSend = {
27
- method,
28
- body: JSON.stringify(request),
29
- headers: header
30
- }
31
-
32
- return objToSend
33
- }
34
-
35
- export const fetchClient = (method, requestBody, path, isDev = false) => {
36
- return new Promise((resolve) => {
37
- const url = String(baseUrlHook[isDev]).concat(path)
38
- const request = requestConfigFactory(method, requestBody)
39
- console.log(request)
40
- fetch(url, request)
41
- .then(resolve)
42
- .catch(err => console.log('Fetch Error', err))
43
- })
44
- }
45
-
46
- export const formatDate = (timestamp) => {
47
- if (!timestamp) {
48
- return null
49
- }
50
- return new Date(timestamp).toISOString()
51
- }
52
-
53
- export const showAlert = (title, body) => {
54
- Alert.alert(title, body, [{ text: 'OK', onPress: () => console.log('OK Pressed') }], {
55
- cancelable: false,
56
- })
57
- }
58
-
59
- export const showAlertLink = (title, body, appName, link) => {
60
- return new Promise((resolve) => {
61
- Alert.alert(
62
- title,
63
- `${body}\n\n${link}`,
64
- [{ text: 'NO', onPress: () => resolve(false) }, { text: 'OK', onPress: () => resolve(true) }],
65
- { cancelable: false },
66
- )
67
- })
68
- }
69
-
70
- export const subscriptionRequestAdapter = (sdkRequest, useCustomData, customData) => {
71
- if (useCustomData) {
72
- return {
73
- registerSubscriberRequest: {
74
- ...sdkRequest.registerSubscriberRequest,
75
- custom_field: customData
76
- }
77
- }
78
- }
79
- return {
80
- registerSubscriberRequest: {
81
- ...sdkRequest.registerSubscriberRequest
82
- }
83
- };
84
- }