notifly-sdk 1.1.2 → 2.1.0

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/.eslintrc.cjs ADDED
@@ -0,0 +1,40 @@
1
+ module.exports = {
2
+ root: true,
3
+ env: {
4
+ es6: true,
5
+ jest: true,
6
+ node: true,
7
+ 'react-native/react-native': true,
8
+ },
9
+ parser: '@babel/eslint-parser',
10
+ plugins: ['react', 'react-native'],
11
+ extends: ['eslint:recommended', 'plugin:react/recommended'],
12
+ rules: {
13
+ 'react/prop-types': 'off',
14
+ 'react/react-in-jsx-scope': 'off',
15
+ 'no-console': 'off',
16
+ 'no-unused-vars': 'warn',
17
+ 'react-native/no-unused-styles': 'warn',
18
+ 'react-native/split-platform-components': 'warn',
19
+ 'react-native/no-inline-styles': 'warn',
20
+ 'react-native/no-color-literals': 'warn',
21
+ 'react-native/no-raw-text': 'warn',
22
+ },
23
+ settings: {
24
+ react: {
25
+ version: 'detect',
26
+ },
27
+ },
28
+ parserOptions: {
29
+ requireConfigFile: false,
30
+ ecmaVersion: 2021,
31
+ sourceType: 'module',
32
+ ecmaFeatures: {
33
+ jsx: true,
34
+ },
35
+ babelOptions: {
36
+ presets: ['@babel/preset-env', '@babel/preset-react'],
37
+ plugins: ['@babel/plugin-syntax-import-assertions'],
38
+ },
39
+ },
40
+ };
package/README.md CHANGED
@@ -1 +1,33 @@
1
- # notifly-node-package
1
+ # Notifly React Native SDK
2
+
3
+ ![npm](https://img.shields.io/npm/v/notifly-sdk)
4
+ ![Downloads](https://img.shields.io/npm/dt/notifly-sdk)
5
+
6
+ _Notifly SDK for React Native_ is an easy-to-use package for integrating Notifly with your React Native applications. It supports both Android and iOS platforms.
7
+
8
+ ## Installation
9
+
10
+ To install the package, run the following command:
11
+
12
+ ```
13
+ npm install notifly-sdk@latest --save
14
+ ```
15
+
16
+ or
17
+
18
+ ```
19
+ yarn add notifly-sdk@latest
20
+ ```
21
+
22
+ Also, please install the peer dependencies manually:
23
+
24
+ ```
25
+ npm install @react-native-async-storage/async-storage@^1.17.11 @react-native-firebase/app@^16.4.3 @react-native-firebase/messaging@^16.4.3 react-native-device-info@^8.1.4 react-native-modal@^13.0.1 react-native-root-siblings@^4.1.1 react-native-webview@^11.26.1 uuid@^8.3.0
26
+ ```
27
+
28
+ ## Usage
29
+
30
+ Please refer to our official documentation:
31
+
32
+ * [English documentation](https://docs.notifly.tech/client-sdk/react-native)
33
+ * [Korean documentation](https://docs.notifly.tech/ko/client-sdk/react-native)
package/index.js CHANGED
@@ -1,250 +1,118 @@
1
- import messaging from "@react-native-firebase/messaging";
2
- import { Linking, PermissionsAndroid, Platform } from 'react-native';
1
+ import { Linking } from 'react-native';
2
+ import RootSiblings from 'react-native-root-siblings';
3
3
  import AsyncStorage from '@react-native-async-storage/async-storage';
4
- import rnDeviceInfo from 'react-native-device-info';
5
- import { v5 } from 'uuid';
6
- import { NAMESPACE } from './namespace';
4
+ import messaging from '@react-native-firebase/messaging';
5
+ import logEvent from './src/log_event';
6
+ import { setUserProperties, removeUserId } from './src/user';
7
+ import { clickHandler, getSDKVersion, sessionStart } from './src/utils';
8
+ import { showInAppMessage } from './src/in_app_message';
7
9
 
8
10
  exports.trackEvent = logEvent;
9
-
10
- exports.setUserProperties = _setUserProperties
11
-
12
- exports.clickHandler = async function (remoteMessage) {
13
- if (remoteMessage) {
14
- const link = remoteMessage.data?.link
15
- if (link) {
16
- Linking.openURL(link);
17
- }
18
- await logEvent("push_click", { "campaign_id": remoteMessage.data?.campaign_id, "status": "quit" }, null, true);
19
- return;
20
- }
21
- console.warn('[Notifly] clickHandler receives a null remoteMessage.');
22
- }
23
-
11
+ exports.setUserProperties = setUserProperties;
12
+ exports.clickHandler = clickHandler;
13
+
14
+ /**
15
+ * Sets the external user ID for the user.
16
+ *
17
+ * @async
18
+ * @param {string} userID - The external user ID for the user.
19
+ * @returns {Promise<void>} - A promise that resolves when the user ID is set.
20
+ *
21
+ * @example
22
+ * await setUserId('123456789');
23
+ */
24
24
  exports.setUserId = async function (userID) {
25
25
  try {
26
26
  if (userID) {
27
- await _setUserProperties({
27
+ await setUserProperties({
28
28
  external_user_id: userID,
29
- })
29
+ });
30
30
  return;
31
31
  }
32
- await _removeUserId();
32
+ await removeUserId();
33
33
  return;
34
34
  } catch (err) {
35
- console.warn('[Notifly] setUserId Failed.');
35
+ console.warn('[Notifly] setUserId failed.');
36
36
  }
37
- }
37
+ };
38
+
39
+ /**
40
+ * Initializes the Notifly SDK with the given project ID, user name, and password.
41
+ *
42
+ * @async
43
+ * @param {string} prjId - The project ID to use for initialization.
44
+ * @param {string} userName - The user name to use for authentication.
45
+ * @param {string} password - The password to use for authentication.
46
+ * @param {boolean} [useCustomClickHandler=false] - A flag indicating whether to use a custom click handler for push notifications.
47
+ * @returns {Promise<void>} A promise that resolves when initialization is complete, or rejects with an error.
48
+ *
49
+ * @example
50
+ * await initialize('myProjectId', 'myUserName', 'myPassword');
51
+ */
52
+ exports.initialize = async function (prjId, userName, password, useCustomClickHandler = false) {
53
+ try {
54
+ const [, sdkVersion] = await Promise.all([messaging().requestPermission(), getSDKVersion()]);
38
55
 
39
- async function _sessionStart() {
40
- const apiLevel = rnDeviceInfo.getApiLevel(); // only android
41
- const brand = rnDeviceInfo.getBrand(); // apple samsung
42
- const model = rnDeviceInfo.getModel(); // 기종 SM-G960N or iPhone 8
43
- const platform = Platform.OS;
44
- const deviceInfo = await Promise.all([model, brand, apiLevel]);
45
- const openAppEventParams = {
46
- "platform": platform,
47
- "device_model": deviceInfo[0],
48
- "properties": {
49
- "device_brand": deviceInfo[1],
50
- "api_level": deviceInfo[2],
51
- },
52
- }
53
- await logEvent("session_start", openAppEventParams, null, true)
54
- }
56
+ // in-app-message
57
+ const openedInAppWebViewCount = { count: 0 };
58
+ messaging().onMessage((remoteMessage) => {
59
+ new RootSiblings(null).destroy();
60
+ handleInAppMessage(remoteMessage, openedInAppWebViewCount);
61
+ });
55
62
 
56
- exports.initialize = async function (prjId, userName, password) {
57
- try {
58
- await messaging().requestPermission();
63
+ // push
64
+ messaging().onNotificationOpenedApp(handleNotificationOpened);
59
65
 
60
- messaging().onNotificationOpenedApp(async (remoteMessage) => {
61
- const link = remoteMessage.data?.link
62
- if (link) {
63
- Linking.openURL(link);
66
+ // custom push click handler
67
+ if (!useCustomClickHandler) {
68
+ const initialNotification = await messaging().getInitialNotification();
69
+ if (initialNotification) {
70
+ await clickHandler(initialNotification);
64
71
  }
65
- await logEvent("push_click", { "campaign_id": remoteMessage.data.campaign_id, "status": "background" }, null, true);
66
- });
72
+ }
67
73
 
68
- messaging().getToken()
74
+ messaging().getToken();
69
75
 
70
76
  await Promise.all([
71
77
  AsyncStorage.setItem('notiflyProjectId', prjId),
72
78
  AsyncStorage.setItem('notiflyUserName', userName),
73
79
  AsyncStorage.setItem('notiflyUserPassword', password),
74
- ])
75
- await _sessionStart();
80
+ AsyncStorage.setItem('notiflySDKVersion', sdkVersion),
81
+ ]);
82
+ await sessionStart();
76
83
  } catch (err) {
77
- console.warn("[Notifly]: ", err);
78
- }
79
- }
80
-
81
- async function getCognitoIdToken(userName, password) {
82
- const myHeaders = new Headers();
83
- myHeaders.append("X-Amz-Target", "AWSCognitoIdentityProviderService.InitiateAuth");
84
- myHeaders.append("Content-Type", "application/x-amz-json-1.1");
85
-
86
- const raw = `{\n \"AuthFlow\":\"USER_PASSWORD_AUTH\",\n \"AuthParameters\": {\n \"PASSWORD\": \"${password}\",\n \"USERNAME\":\"${userName}\"\n },\n \"ClientId\":\"2pc5pce21ec53csf8chafknqve\"\n}`;
87
-
88
- const requestOptions = {
89
- method: 'POST',
90
- headers: myHeaders,
91
- body: raw,
92
- redirect: 'follow'
93
- };
94
-
95
- const token = fetch("https://cognito-idp.ap-northeast-2.amazonaws.com/", requestOptions)
96
- .then(response => response.text())
97
- .then(result => {
98
- const tokens = JSON.parse(result).AuthenticationResult.IdToken
99
- return tokens;
100
- })
101
- .catch(error => console.warn('[Notifly]: ', error));
102
-
103
- return token;
104
- }
105
-
106
- async function _getNotiflyUserId() {
107
- const encodedUserId = await AsyncStorage.getItem('notiflyUserId');
108
- if (encodedUserId) {
109
- return encodedUserId;
84
+ console.warn('[Notifly]: ', err);
110
85
  }
111
- const [prjId, externalUserId] = await Promise.all([AsyncStorage.getItem('notiflyProjectId'), AsyncStorage.getItem('notiflyExternalUserId')])
112
- let notiflyUserId
113
- if (externalUserId) {
114
- notiflyUserId = v5(`${prjId}${externalUserId}`, NAMESPACE.REGISTERED_USERID).replace(/-/g, '');
115
- } else {
116
- notiflyUserId = v5(`${prjId}${await messaging().getToken()}`, NAMESPACE.UNREGISTERED_USERID).replace(/-/g, '');
117
- }
118
- return notiflyUserId;
119
- }
86
+ };
120
87
 
121
- async function _setUserProperties(params) {
88
+ async function handleInAppMessage(remoteMessage, openedInAppWebViewCount) {
122
89
  try {
123
- if (params.external_user_id) {
124
- const [previousNotiflyUserID, previousExternalUserID] = await Promise.all([
125
- _getNotiflyUserId(),
126
- AsyncStorage.getItem('notiflyExternalUserId')
127
- ]);
128
- params['previous_notifly_user_id'] = previousNotiflyUserID
129
- params['previous_external_user_id'] = previousExternalUserID
130
- await Promise.all([
131
- AsyncStorage.setItem('notiflyExternalUserId', params.external_user_id),
132
- AsyncStorage.removeItem('notiflyUserId'),
133
- ]);
90
+ if (remoteMessage.data?.notifly_message_type === 'in-app-message' && remoteMessage.data.url) {
91
+ showInAppMessage(remoteMessage.data, openedInAppWebViewCount);
134
92
  }
135
- return (await logEvent("set_user_properties", params, null, true));
136
- } catch (err) {
137
- console.warn('[Notifly] Failed to remove userID');
138
- }
139
- }
140
-
141
- async function _removeUserId() {
142
- try {
143
- await Promise.all([AsyncStorage.removeItem('notiflyExternalUserId'), AsyncStorage.removeItem('notiflyUserId')]);
144
- return await logEvent('remove_external_user_id', {}, null, true);
145
93
  } catch (err) {
146
- console.warn('[Notifly] Failed to remove userID');
94
+ console.warn('[Notifly] In-app message handling failed:', err);
147
95
  }
148
96
  }
149
97
 
150
- async function logEvent(eventName, eventParams, segmentation_event_param_keys = null, isInternalEvent = false) {
98
+ async function handleNotificationOpened(remoteMessage) {
151
99
  try {
152
- if (!eventName) {
153
- console.warn('[Notifly]event_name must be provided.');
154
- return;
155
- }
156
- let token;
157
- const [savedCognitoToken, notiflyUserId, externalUserId, prjId, externalDeviceId, osVersion, appVersion] = await Promise.all([
158
- AsyncStorage.getItem('notiflyCognitoIdToken'),
159
- _getNotiflyUserId(),
160
- AsyncStorage.getItem('notiflyExternalUserId'),
161
- AsyncStorage.getItem('notiflyProjectId'),
162
- rnDeviceInfo.getUniqueId(),
163
- rnDeviceInfo.getSystemVersion(),
164
- rnDeviceInfo.getVersion(),
165
- ]);
166
-
167
- const [eventId, notiflyDeviceId, deviceToken] = await Promise.all([
168
- v5(`${notiflyUserId}${eventName}${new Date().valueOf()}`, NAMESPACE.EVENTID).replace(/-/g, ''),
169
- v5(externalDeviceId, NAMESPACE.DEVICEID).replace(/-/g, ''),
170
- messaging().getToken(),
171
- ]);
172
-
173
- if (!savedCognitoToken) {
174
- const [userName, password] = await Promise.all([AsyncStorage.getItem('notiflyUserName'), AsyncStorage.getItem('notiflyUserPassword')])
175
- newToken = await getCognitoIdToken(userName, password);
176
- await AsyncStorage.setItem("notiflyCognitoIdToken", newToken);
177
- token = newToken;
178
- } else {
179
- token = savedCognitoToken;
180
- }
181
-
182
- if (!token || !notiflyUserId || !prjId || !eventId || !externalDeviceId || !notiflyDeviceId || !deviceToken) {
183
- throw new Error("null value");
184
- }
185
- const myHeaders = new Headers();
186
- myHeaders.append("Authorization", token);
187
- myHeaders.append("Content-Type", "application/json");
188
-
189
- const eventDataWithoutExternalUserId = {
190
- "event_params": eventParams,
191
- "id": eventId,
192
- "name": eventName,
193
- "notifly_user_id": notiflyUserId,
194
- "time": parseInt(new Date().valueOf() / 1000),
195
- "notifly_device_id": notiflyDeviceId,
196
- "external_device_id": externalDeviceId,
197
- "device_token": deviceToken,
198
- "is_internal_event": isInternalEvent,
199
- "segmentation_event_param_keys": segmentation_event_param_keys,
200
- "project_id": prjId,
201
- "platform": Platform.OS,
202
- "os_version": osVersion,
203
- "app_version": appVersion,
100
+ const link = remoteMessage.data?.link;
101
+ if (link) {
102
+ Linking.openURL(link);
204
103
  }
205
- const eventData = JSON.stringify(
206
- externalUserId ?
207
- {
208
- ...eventDataWithoutExternalUserId,
209
- "external_user_id": externalUserId,
210
- }
211
- :
212
- eventDataWithoutExternalUserId
104
+ await logEvent(
105
+ 'push_click',
106
+ {
107
+ type: 'message_event',
108
+ channel: 'push-notification',
109
+ campaign_id: remoteMessage.data.campaign_id,
110
+ status: 'background',
111
+ },
112
+ null,
113
+ true
213
114
  );
214
-
215
- const body = JSON.stringify({
216
- "records": [{
217
- "data": eventData,
218
- "partitionKey": notiflyUserId,
219
- }]
220
- })
221
-
222
- const requestOptions = {
223
- method: 'POST',
224
- headers: myHeaders,
225
- body: body,
226
- redirect: 'follow'
227
- };
228
-
229
- const response = await _apiCall("https://12lnng07q2.execute-api.ap-northeast-2.amazonaws.com/prod/records", requestOptions);
230
- const result = JSON.parse(response)
231
- if (result.message == "The incoming token has expired") {
232
- const [userName, password] = await Promise.all([AsyncStorage.getItem('notiflyUserName'), AsyncStorage.getItem('notiflyUserPassword')])
233
- const newToken = await getCognitoIdToken(userName, password);
234
- await AsyncStorage.setItem("notiflyCognitoIdToken", newToken);
235
- await logEvent(eventName, eventParams, segmentation_event_param_keys, isInternalEvent)
236
- }
237
-
238
115
  } catch (err) {
239
- console.warn('[Notifly]Error: err')
240
- if (err == 'Error: null value') {
241
- throw new Error("[Notifly] Fail to log the event. Please retry the initialization.");
242
- }
116
+ console.warn('[Notifly] Notification opened handling failed:', err);
243
117
  }
244
118
  }
245
-
246
- async function _apiCall(apiUrl, requestOptions) {
247
- const result = fetch(apiUrl, requestOptions)
248
- .then(response => response.text());
249
- return result;
250
- }
package/package.json CHANGED
@@ -1,19 +1,35 @@
1
1
  {
2
2
  "name": "notifly-sdk",
3
- "version": "1.1.2",
3
+ "version": "2.1.0",
4
4
  "description": "",
5
5
  "main": "index.js",
6
6
  "scripts": {
7
- "test": "echo \"Error: no test specified\" && exit 1"
7
+ "test": "echo \"Error: no test specified\" && exit 1",
8
+ "pretty": "prettier --write \"**/*.{js,jsx,json}\"",
9
+ "lint": "eslint ."
8
10
  },
9
11
  "peerDependencies": {
10
12
  "@react-native-async-storage/async-storage": "^1.17.11",
11
13
  "@react-native-firebase/app": "^16.4.3",
12
14
  "@react-native-firebase/messaging": "^16.4.3",
13
15
  "react-native-device-info": "^8.1.4",
16
+ "react-native-modal": "^13.0.1",
17
+ "react-native-root-siblings": "^4.1.1",
18
+ "react-native-webview": "^11.26.1",
14
19
  "uuid": "^8.3.0"
15
20
  },
16
21
  "author": "daeseongKim",
17
22
  "license": "ISC",
18
- "type": "module"
23
+ "type": "module",
24
+ "devDependencies": {
25
+ "@babel/core": "^7.21.4",
26
+ "@babel/eslint-parser": "^7.21.3",
27
+ "@babel/plugin-syntax-import-assertions": "^7.20.0",
28
+ "@babel/preset-env": "^7.21.4",
29
+ "@babel/preset-react": "^7.18.6",
30
+ "eslint": "^8.38.0",
31
+ "eslint-plugin-react": "^7.32.2",
32
+ "eslint-plugin-react-native": "^4.0.0",
33
+ "prettier": "^2.8.7"
34
+ }
19
35
  }
package/src/auth.js ADDED
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Fetches a Cognito ID token for the given user name and password.
3
+ *
4
+ * @async
5
+ * @param {string} userName - The user name to use for authentication.
6
+ * @param {string} password - The password to use for authentication.
7
+ * @returns {Promise<string>} A promise that resolves with the Cognito ID token, or rejects with an error.
8
+ *
9
+ * @example
10
+ * const token = await getCognitoIdToken('myUserName', 'myPassword');
11
+ */
12
+ export async function getCognitoIdToken(userName, password) {
13
+ const headers = new Headers({
14
+ 'X-Amz-Target': 'AWSCognitoIdentityProviderService.InitiateAuth',
15
+ 'Content-Type': 'application/x-amz-json-1.1',
16
+ });
17
+
18
+ const body = JSON.stringify({
19
+ AuthFlow: 'USER_PASSWORD_AUTH',
20
+ AuthParameters: {
21
+ PASSWORD: password,
22
+ USERNAME: userName,
23
+ },
24
+ ClientId: '2pc5pce21ec53csf8chafknqve',
25
+ });
26
+
27
+ const requestOptions = {
28
+ method: 'POST',
29
+ headers,
30
+ body,
31
+ redirect: 'follow',
32
+ };
33
+
34
+ try {
35
+ const response = await fetch('https://cognito-idp.ap-northeast-2.amazonaws.com/', requestOptions);
36
+ const result = await response.text();
37
+ const token = JSON.parse(result).AuthenticationResult.IdToken;
38
+ return token;
39
+ } catch (error) {
40
+ console.warn('[Notifly]: ', error);
41
+ }
42
+ }
@@ -0,0 +1,6 @@
1
+ export const NAMESPACE = {
2
+ 'EVENTID': '830b5f7b-e392-43db-a17b-d835f0bcab2b',
3
+ 'REGISTERED_USERID': 'ce7c62f9-e8ae-4009-8fd6-468e9581fa21',
4
+ 'UNREGISTERED_USERID': 'a6446dcf-c057-4de7-a360-56af8659d52f',
5
+ 'DEVICEID': '830848b3-2444-467d-9cd8-3430d2738c57',
6
+ };
@@ -0,0 +1,225 @@
1
+ import { View, Linking, Dimensions } from 'react-native';
2
+ import RootSiblings from 'react-native-root-siblings';
3
+ import Modal from 'react-native-modal';
4
+ import WebView from 'react-native-webview';
5
+ import logEvent from './log_event';
6
+ import { setUserProperties } from './user';
7
+
8
+ /**
9
+ * Displays an in-app message in a modal WebView.
10
+ *
11
+ * @async
12
+ * @param {Object} data - An object containing information about the in-app message to display.
13
+ * @param {Object} openedInAppWebViewCount - An object containing the count of opened in-app web views.
14
+ * @returns {Promise<void>} A promise that resolves when the in-app message has been displayed, or rejects with an error.
15
+ *
16
+ * @example
17
+ * const data = { campaign_id: 'myCampaign', url: 'https://example.com' };
18
+ * const openedInAppWebViewCount = { count: 0 };
19
+ * await showInAppMessage(data, openedInAppWebViewCount);
20
+ */
21
+ export async function showInAppMessage(data, openedInAppWebViewCount) {
22
+ if (openedInAppWebViewCount.count > 0) {
23
+ return;
24
+ }
25
+ if (!(data?.url && data?.modal_properties)) {
26
+ return;
27
+ }
28
+ const modalProperties = JSON.parse(data.modal_properties || '{}');
29
+ const screenWidth = Dimensions.get('window').width;
30
+ const screenHeight = Dimensions.get('window').height;
31
+ const webViewProps = _translateWebviewProps(modalProperties, screenWidth, screenHeight);
32
+ const link = data.url; // default html link for only testing.
33
+ const injectedJavaScript = `
34
+ const button_trigger = document.getElementById('notifly-button-trigger');
35
+ button_trigger.addEventListener('click', function(event){
36
+ if (!event.notifly_button_click_type) return;
37
+ window.ReactNativeWebView.postMessage(JSON.stringify({
38
+ type: event.notifly_button_click_type,
39
+ button_name: event.notifly_button_name,
40
+ link: event.notifly_button_click_link,
41
+ }));
42
+ });
43
+ `;
44
+
45
+ const webviewMessageHandler = (e) => {
46
+ const message = JSON.parse(e.nativeEvent.data);
47
+ if (message.type === 'close') {
48
+ modal.destroy();
49
+ openedInAppWebViewCount.count = openedInAppWebViewCount.count - 1;
50
+ logEvent(
51
+ 'close_button_click',
52
+ {
53
+ type: 'message_event',
54
+ channel: 'in-app-message',
55
+ button_name: message.button_name,
56
+ campaign_id: data.campaign_id,
57
+ },
58
+ null,
59
+ true
60
+ );
61
+ } else if (message.type === 'main_button') {
62
+ logEvent(
63
+ 'main_button_click',
64
+ {
65
+ type: 'message_event',
66
+ channel: 'in-app-message',
67
+ button_name: message.button_name,
68
+ campaign_id: data.campaign_id,
69
+ },
70
+ null,
71
+ true
72
+ );
73
+ if (message.link) {
74
+ modal.destroy();
75
+ openedInAppWebViewCount.count = openedInAppWebViewCount.count - 1;
76
+ Linking.openURL(message.link);
77
+ }
78
+ } else if (message.type === 'hide_in_app_message') {
79
+ modal.destroy();
80
+ openedInAppWebViewCount.count = openedInAppWebViewCount.count - 1;
81
+ logEvent(
82
+ 'hide_in_app_message_button_click',
83
+ {
84
+ type: 'message_event',
85
+ channel: 'in-app-message',
86
+ button_name: message.button_name,
87
+ campaign_id: data.campaign_id,
88
+ },
89
+ null,
90
+ true
91
+ );
92
+ if (modalProperties.template_name) {
93
+ const key = `hide_in_app_message_${modalProperties.template_name}`;
94
+ setUserProperties({
95
+ [key]: true,
96
+ });
97
+ }
98
+ }
99
+ };
100
+
101
+ openedInAppWebViewCount.count = openedInAppWebViewCount.count + 1;
102
+ logEvent(
103
+ 'in_app_message_show',
104
+ { type: 'message_event', channel: 'in-app-message', campaign: data.campaign_id },
105
+ null,
106
+ true
107
+ ); // logging in app messaging delivered
108
+ const modal = new RootSiblings(
109
+ (
110
+ <Modal
111
+ isVisible={true}
112
+ transparent={true}
113
+ onBackdropPress={() => {
114
+ openedInAppWebViewCount.count = openedInAppWebViewCount.count - 1;
115
+ modal.destroy();
116
+ }}
117
+ onBackButtonPress={() => {
118
+ openedInAppWebViewCount.count = openedInAppWebViewCount.count - 1;
119
+ modal.destroy();
120
+ }}
121
+ backdropOpacity={0}
122
+ style={webViewProps.modalStyle}
123
+ >
124
+ <View>
125
+ <View style={webViewProps.viewStyle}>
126
+ <WebView
127
+ originWhitelist={['*']}
128
+ source={{
129
+ uri: link,
130
+ }}
131
+ style={{
132
+ width: screenWidth,
133
+ height: screenHeight,
134
+ }}
135
+ onMessage={webviewMessageHandler}
136
+ javaScriptEnabled={true}
137
+ injectedJavaScript={injectedJavaScript}
138
+ />
139
+ </View>
140
+ </View>
141
+ </Modal>
142
+ )
143
+ );
144
+ }
145
+
146
+ function _translateWebviewProps(modalProps, screenWidth, screenHeight) {
147
+ const modalStyle = {
148
+ margin: 0,
149
+ justifyContent: 'center',
150
+ alignItems: 'center',
151
+ ...(modalProps?.position === 'bottom' && {
152
+ position: 'absolute',
153
+ bottom: 0,
154
+ }),
155
+ };
156
+
157
+ const viewStyle = {
158
+ borderTopLeftRadius: modalProps?.borderTopLeftRadius || 0,
159
+ borderTopRightRadius: modalProps?.borderTopRightRadius || 0,
160
+ borderBottomLeftRadius: modalProps?.borderBottomLeftRadius || 0,
161
+ borderBottomRightRadius: modalProps?.borderBottomRightRadius || 0,
162
+ overflow: 'hidden',
163
+ width: _getViewWidth(modalProps, screenWidth, screenHeight),
164
+ height: _getViewHeight(modalProps, screenWidth, screenHeight),
165
+ justifyContent: 'center',
166
+ alignItems: 'center',
167
+ };
168
+
169
+ return {
170
+ modalStyle,
171
+ viewStyle,
172
+ };
173
+ }
174
+
175
+ function _getViewWidth(modalProps, screenWidth, screenHeight) {
176
+ let viewWidth;
177
+
178
+ if (modalProps.width) {
179
+ viewWidth = modalProps.width;
180
+ } else if (!screenWidth) {
181
+ console.error('screenWidth is not defined');
182
+ viewWidth = '100%';
183
+ } else if (modalProps.width_vw) {
184
+ viewWidth = screenWidth * (modalProps.width_vw / 100);
185
+ } else if (modalProps.width_vh && screenHeight) {
186
+ viewWidth = screenHeight * (modalProps.width_vh / 100);
187
+ } else {
188
+ viewWidth = '100%';
189
+ }
190
+
191
+ if (modalProps.min_width && viewWidth < modalProps.min_width) {
192
+ viewWidth = modalProps.minWidth;
193
+ }
194
+ if (modalProps.max_width && viewWidth > modalProps.max_width) {
195
+ viewWidth = modalProps.maxWidth;
196
+ }
197
+
198
+ return viewWidth;
199
+ }
200
+
201
+ function _getViewHeight(modalProps, screenWidth, screenHeight) {
202
+ let viewHeight;
203
+
204
+ if (modalProps.height) {
205
+ viewHeight = modalProps.height;
206
+ } else if (!screenHeight) {
207
+ console.error('screenHeight is not defined');
208
+ viewHeight = '100%';
209
+ } else if (modalProps.height_vh) {
210
+ viewHeight = screenHeight * (modalProps.height_vh / 100);
211
+ } else if (modalProps.height_vw && screenWidth) {
212
+ viewHeight = screenWidth * (modalProps.height_vw / 100);
213
+ } else {
214
+ viewHeight = '100%';
215
+ }
216
+
217
+ if (modalProps.min_height && viewHeight < modalProps.min_height) {
218
+ viewHeight = modalProps.min_height;
219
+ }
220
+ if (modalProps.max_height && viewHeight > modalProps.max_height) {
221
+ viewHeight = modalProps.max_height;
222
+ }
223
+
224
+ return viewHeight;
225
+ }
@@ -0,0 +1,188 @@
1
+ import { Platform } from 'react-native';
2
+ import rnDeviceInfo from 'react-native-device-info';
3
+ import AsyncStorage from '@react-native-async-storage/async-storage';
4
+ import messaging from '@react-native-firebase/messaging';
5
+ import { v5 as uuidv5 } from 'uuid';
6
+ import { NAMESPACE } from './constant';
7
+ import { getNotiflyUserId } from './utils';
8
+ import { getCognitoIdToken } from './auth';
9
+
10
+ const NOTIFLY_LOG_EVENT_URL = 'https://12lnng07q2.execute-api.ap-northeast-2.amazonaws.com/prod/records';
11
+
12
+ /**
13
+ * Logs an event to Notifly for the current user.
14
+ *
15
+ * @async
16
+ * @param {string} eventName - The name of the event to log.
17
+ * @param {Object} eventParams - The parameters to include in the event log.
18
+ * @param {string[]} [segmentation_event_param_keys=null] - The segmentation event parameter keys.
19
+ * @param {boolean} [isInternalEvent=false] - A flag indicating whether the event is for Notifly internal use.
20
+ * @returns {Promise<void>} A promise that resolves when the event has been logged, or rejects with an error.
21
+ *
22
+ * @example
23
+ * await logEvent('button_clicked', { 'button_name': 'myButton' });
24
+ */
25
+ export default async function logEvent(
26
+ eventName,
27
+ eventParams,
28
+ segmentation_event_param_keys = null,
29
+ isInternalEvent = false
30
+ ) {
31
+ if (!eventName) {
32
+ console.warn('[Notifly] eventName must be provided.');
33
+ return;
34
+ }
35
+
36
+ try {
37
+ const [
38
+ cognitoToken,
39
+ notiflyUserId,
40
+ externalUserId,
41
+ prjId,
42
+ externalDeviceId,
43
+ osVersion,
44
+ appVersion,
45
+ deviceToken,
46
+ sdkVersion,
47
+ ] = await Promise.all([
48
+ AsyncStorage.getItem('notiflyCognitoIdToken'),
49
+ getNotiflyUserId(),
50
+ AsyncStorage.getItem('notiflyExternalUserId'),
51
+ AsyncStorage.getItem('notiflyProjectId'),
52
+ rnDeviceInfo.getUniqueId(),
53
+ rnDeviceInfo.getSystemVersion(),
54
+ rnDeviceInfo.getVersion(),
55
+ messaging().getToken(),
56
+ AsyncStorage.getItem('notiflySdkVersion'),
57
+ ]);
58
+
59
+ const eventId = uuidv5(`${notiflyUserId}${eventName}${new Date().valueOf()}`, NAMESPACE.EVENTID).replace(
60
+ /-/g,
61
+ ''
62
+ );
63
+ const notiflyDeviceId = uuidv5(externalDeviceId, NAMESPACE.DEVICEID).replace(/-/g, '');
64
+
65
+ let token = cognitoToken;
66
+ if (!token) {
67
+ const [userName, password] = await Promise.all([
68
+ AsyncStorage.getItem('notiflyUserName'),
69
+ AsyncStorage.getItem('notiflyUserPassword'),
70
+ ]);
71
+ token = await getCognitoIdToken(userName, password);
72
+ await AsyncStorage.setItem('notiflyCognitoIdToken', token);
73
+ }
74
+
75
+ if (!token || !notiflyUserId || !prjId || !eventId || !externalDeviceId || !notiflyDeviceId || !deviceToken) {
76
+ const requiredParams = [
77
+ 'token',
78
+ 'notiflyUserId',
79
+ 'prjId',
80
+ 'eventId',
81
+ 'externalDeviceId',
82
+ 'notiflyDeviceId',
83
+ 'deviceToken',
84
+ ];
85
+ const missingParam = requiredParams.find((param) => !eval(param));
86
+ throw new Error(`[Notifly] Missing required parameter in logEvent: ${missingParam}`);
87
+ }
88
+
89
+ const body = _getBodyForLogEvent(
90
+ notiflyUserId,
91
+ eventId,
92
+ eventName,
93
+ notiflyDeviceId,
94
+ externalDeviceId,
95
+ deviceToken,
96
+ isInternalEvent,
97
+ segmentation_event_param_keys,
98
+ prjId,
99
+ osVersion,
100
+ appVersion,
101
+ sdkVersion,
102
+ externalUserId,
103
+ eventParams
104
+ );
105
+ const requestOptions = _getRequestOptionsForLogEvent(token, body);
106
+
107
+ const response = await _apiCall(NOTIFLY_LOG_EVENT_URL, requestOptions);
108
+ const result = JSON.parse(response);
109
+
110
+ // If the token is expired, get a new token and retry the logEvent.
111
+ if (result.message == 'The incoming token has expired') {
112
+ const [userName, password] = await Promise.all([
113
+ AsyncStorage.getItem('notiflyUserName'),
114
+ AsyncStorage.getItem('notiflyUserPassword'),
115
+ ]);
116
+ const newToken = await getCognitoIdToken(userName, password);
117
+ await AsyncStorage.setItem('notiflyCognitoIdToken', newToken);
118
+ await logEvent(eventName, eventParams, segmentation_event_param_keys, isInternalEvent);
119
+ }
120
+ } catch (err) {
121
+ console.warn('[Notifly] Failed logging the event. Please retry the initialization. ', err);
122
+ }
123
+ }
124
+
125
+ async function _apiCall(apiUrl, requestOptions) {
126
+ const result = fetch(apiUrl, requestOptions).then((response) => response.text());
127
+ return result;
128
+ }
129
+
130
+ function _getRequestOptionsForLogEvent(token, body) {
131
+ const myHeaders = new Headers();
132
+ myHeaders.append('Authorization', token);
133
+ myHeaders.append('Content-Type', 'application/json');
134
+
135
+ const requestOptions = {
136
+ method: 'POST',
137
+ headers: myHeaders,
138
+ body: body,
139
+ redirect: 'follow',
140
+ };
141
+ return requestOptions;
142
+ }
143
+
144
+ function _getBodyForLogEvent(
145
+ notiflyUserId,
146
+ eventId,
147
+ eventName,
148
+ notiflyDeviceId,
149
+ externalDeviceId,
150
+ deviceToken,
151
+ isInternalEvent,
152
+ segmentation_event_param_keys,
153
+ prjId,
154
+ osVersion,
155
+ appVersion,
156
+ sdkVersion,
157
+ externalUserId,
158
+ eventParams
159
+ ) {
160
+ const eventData = JSON.stringify({
161
+ event_params: eventParams,
162
+ id: eventId,
163
+ name: eventName,
164
+ notifly_user_id: notiflyUserId,
165
+ time: parseInt(new Date().valueOf() / 1000),
166
+ notifly_device_id: notiflyDeviceId,
167
+ external_device_id: externalDeviceId,
168
+ device_token: deviceToken,
169
+ is_internal_event: isInternalEvent,
170
+ segmentation_event_param_keys: segmentation_event_param_keys,
171
+ project_id: prjId,
172
+ platform: Platform.OS,
173
+ os_version: osVersion,
174
+ app_version: appVersion,
175
+ sdk_version: sdkVersion,
176
+ external_user_id: externalUserId || undefined,
177
+ });
178
+
179
+ const body = JSON.stringify({
180
+ 'records': [
181
+ {
182
+ 'data': eventData,
183
+ 'partitionKey': notiflyUserId,
184
+ },
185
+ ],
186
+ });
187
+ return body;
188
+ }
package/src/user.js ADDED
@@ -0,0 +1,51 @@
1
+ import AsyncStorage from '@react-native-async-storage/async-storage';
2
+ import { getNotiflyUserId } from './utils';
3
+ import logEvent from './log_event';
4
+
5
+ /**
6
+ * Sets user properties for the current user.
7
+ *
8
+ * @async
9
+ * @param {Object} params - An object containing the user properties to set.
10
+ * @returns {Promise<void>} A promise that resolves when the user properties have been set, or rejects with an error.
11
+ *
12
+ * @example
13
+ * await setUserProperties({ external_user_id: 'myUserID' });
14
+ */
15
+ export async function setUserProperties(params) {
16
+ try {
17
+ if (params.external_user_id) {
18
+ const [previousNotiflyUserID, previousExternalUserID] = await Promise.all([
19
+ getNotiflyUserId(),
20
+ AsyncStorage.getItem('notiflyExternalUserId'),
21
+ ]);
22
+ await Promise.all([
23
+ AsyncStorage.setItem('notiflyExternalUserId', params.external_user_id),
24
+ AsyncStorage.removeItem('notiflyUserId'),
25
+ ]);
26
+ params['previous_notifly_user_id'] = previousNotiflyUserID;
27
+ params['previous_external_user_id'] = previousExternalUserID;
28
+ }
29
+ return await logEvent('set_user_properties', params, null, true);
30
+ } catch (err) {
31
+ console.warn('[Notifly] Failed to set user properties');
32
+ }
33
+ }
34
+
35
+ /**
36
+ * Removes the external user ID and Notifly user ID from storage.
37
+ *
38
+ * @async
39
+ * @returns {Promise<void>} A promise that resolves when the user IDs have been removed, or rejects with an error.
40
+ *
41
+ * @example
42
+ * await removeUserId();
43
+ */
44
+ export async function removeUserId() {
45
+ try {
46
+ await Promise.all([AsyncStorage.removeItem('notiflyExternalUserId'), AsyncStorage.removeItem('notiflyUserId')]);
47
+ return await logEvent('remove_external_user_id', {}, null, true);
48
+ } catch (err) {
49
+ console.warn('[Notifly] Failed to remove userID');
50
+ }
51
+ }
package/src/utils.js ADDED
@@ -0,0 +1,130 @@
1
+ import { Platform, Linking } from 'react-native';
2
+ import rnDeviceInfo from 'react-native-device-info';
3
+ import AsyncStorage from '@react-native-async-storage/async-storage';
4
+ import messaging from '@react-native-firebase/messaging';
5
+ import { v5 as uuidv5 } from 'uuid';
6
+ import { NAMESPACE } from './constant';
7
+ import logEvent from './log_event';
8
+
9
+ /**
10
+ * Gets the Notifly user ID for the current user.
11
+ *
12
+ * @async
13
+ * @returns {Promise<string>} A promise that resolves with the Notifly user ID, or rejects with an error.
14
+ *
15
+ * @example
16
+ * const notiflyUserId = await getNotiflyUserId();
17
+ */
18
+ export async function getNotiflyUserId() {
19
+ const encodedUserId = await AsyncStorage.getItem('notiflyUserId');
20
+ if (encodedUserId) {
21
+ return encodedUserId;
22
+ }
23
+ const [prjId, externalUserId] = await Promise.all([
24
+ AsyncStorage.getItem('notiflyProjectId'),
25
+ AsyncStorage.getItem('notiflyExternalUserId'),
26
+ ]);
27
+ let notiflyUserId;
28
+ if (externalUserId) {
29
+ notiflyUserId = uuidv5(`${prjId}${externalUserId}`, NAMESPACE.REGISTERED_USERID).replace(/-/g, '');
30
+ } else {
31
+ notiflyUserId = uuidv5(`${prjId}${await messaging().getToken()}`, NAMESPACE.UNREGISTERED_USERID).replace(
32
+ /-/g,
33
+ ''
34
+ );
35
+ }
36
+ return notiflyUserId;
37
+ }
38
+
39
+ /**
40
+ * Logs a 'session_start' event with device information.
41
+ *
42
+ * @async
43
+ * @returns {Promise<void>} A promise that resolves when the event is logged, or rejects with an error.
44
+ *
45
+ * @example
46
+ * await sessionStart();
47
+ */
48
+ export async function sessionStart() {
49
+ const platform = Platform.OS;
50
+ const apiLevelPromise = rnDeviceInfo.getApiLevel();
51
+ const brandPromise = rnDeviceInfo.getBrand();
52
+ const modelPromise = rnDeviceInfo.getModel();
53
+ const userAgentPromise = rnDeviceInfo.getUserAgent();
54
+
55
+ const [deviceModel, deviceBrand, apiLevel, userAgent] = await Promise.all([
56
+ modelPromise,
57
+ brandPromise,
58
+ apiLevelPromise,
59
+ userAgentPromise,
60
+ ]);
61
+
62
+ const openAppEventParams = {
63
+ platform,
64
+ type: 'session_start_event',
65
+ device_model: deviceModel,
66
+ properties: {
67
+ device_brand: deviceBrand,
68
+ api_level: apiLevel,
69
+ user_agent: userAgent,
70
+ },
71
+ };
72
+ await logEvent('session_start', openAppEventParams, null, true);
73
+ }
74
+
75
+ /**
76
+ * Handles a click event on a push notification.
77
+ *
78
+ * @async
79
+ * @function
80
+ * @param {Object} remoteMessage - The remote message object containing the notification data.
81
+ * @returns {Promise<void>} - A promise that resolves when the click event is handled.
82
+ *
83
+ * @example
84
+ * // Usage:
85
+ * const remoteMessage = {
86
+ * data: {
87
+ * link: 'https://example.com',
88
+ * campaign_id: '1234'
89
+ * }
90
+ * };
91
+ * await clickHandler(remoteMessage);
92
+ */
93
+ export async function clickHandler(remoteMessage) {
94
+ if (!remoteMessage) {
95
+ console.warn('[Notifly] clickHandler receives a null remoteMessage.');
96
+ return;
97
+ }
98
+
99
+ try {
100
+ const { data: { link, campaign_id } = {} } = remoteMessage;
101
+
102
+ if (link) {
103
+ Linking.openURL(link);
104
+ }
105
+ await logEvent(
106
+ 'push_click',
107
+ { channel: 'push-notification', type: 'message_event', campaign_id, status: 'quit' },
108
+ null,
109
+ true
110
+ );
111
+ } catch (err) {
112
+ console.warn('[Notifly] custom click handler registration failed.');
113
+ }
114
+ }
115
+
116
+ /**
117
+ * Asynchronously retrieves the SDK version from the package.json file.
118
+ * @async
119
+ * @function getSDKVersion
120
+ * @returns {Promise<string|null>} A promise that resolves to the SDK version (string) if successful, or null in case of error.
121
+ */
122
+ export async function getSDKVersion() {
123
+ try {
124
+ const packageJson = await import('../package.json', { assert: { type: 'json' } });
125
+ return packageJson?.default?.version;
126
+ } catch (error) {
127
+ console.error('Error loading package.json:', error);
128
+ return null;
129
+ }
130
+ }
package/namespace.js DELETED
@@ -1,6 +0,0 @@
1
- export const NAMESPACE = {
2
- "EVENTID": "830b5f7b-e392-43db-a17b-d835f0bcab2b",
3
- "REGISTERED_USERID": "ce7c62f9-e8ae-4009-8fd6-468e9581fa21",
4
- "UNREGISTERED_USERID": "a6446dcf-c057-4de7-a360-56af8659d52f",
5
- "DEVICEID": "830848b3-2444-467d-9cd8-3430d2738c57",
6
- }