Skip to content

Commit 782a721

Browse files
authored
feat: add device token plugin (#777)
* feat: add device token plugin * chore: remove dev team from xcode proj * chore: refactor for oscar's review * chore: move messaging package back to deps * chore: add additional refactors * chore: refactor getDeviceToken() * chore: add return type to checkUserPermission() * refactor: add try/catch and error handler * chore: update readme * chore: fix readme add awaits --------- Co-authored-by: Alan Charles <[email protected]>
1 parent fda99b0 commit 782a721

File tree

12 files changed

+464
-0
lines changed

12 files changed

+464
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
## [@segment/analytics-react-native-plugin-firebase-v0.3.4](https://github.com/segmentio/analytics-react-native/compare/@segment/analytics-react-native-plugin-firebase-v0.3.3...@segment/analytics-react-native-plugin-firebase-v0.3.4) (2023-02-28)
2+
3+
4+
### Bug Fixes
5+
6+
* add logic to convert traits to strings ([#763](https://github.com/segmentio/analytics-react-native/issues/763)) ([559a3bb](https://github.com/segmentio/analytics-react-native/commit/559a3bb70654faee04546b4f18ed6f340d5712db))
7+
8+
## [@segment/analytics-react-native-plugin-firebase-v0.3.3](https://github.com/segmentio/analytics-react-native/compare/@segment/analytics-react-native-plugin-firebase-v0.3.2...@segment/analytics-react-native-plugin-firebase-v0.3.3) (2022-11-30)
9+
10+
11+
### Bug Fixes
12+
13+
* Firebase custom screen properties ([#707](https://github.com/segmentio/analytics-react-native/issues/707)) ([18b75af](https://github.com/segmentio/analytics-react-native/commit/18b75af1bb38246d75ccbfba06d6d972c6db0339))
14+
15+
## [@segment/analytics-react-native-plugin-firebase-v0.3.2](https://github.com/segmentio/analytics-react-native/compare/@segment/analytics-react-native-plugin-firebase-v0.3.1...@segment/analytics-react-native-plugin-firebase-v0.3.2) (2022-10-07)
16+
17+
18+
### Bug Fixes
19+
20+
* avoids calling Firebase setUserId with undefined value ([#676](https://github.com/segmentio/analytics-react-native/issues/676)) ([076848f](https://github.com/segmentio/analytics-react-native/commit/076848f9fffbd9bcf126805b177f4d62029017b2))
21+
22+
## [@segment/analytics-react-native-plugin-firebase-v0.3.1](https://github.com/segmentio/analytics-react-native/compare/@segment/analytics-react-native-plugin-firebase-v0.3.0...@segment/analytics-react-native-plugin-firebase-v0.3.1) (2022-07-28)
23+
24+
25+
### Bug Fixes
26+
27+
* replace allSettled shim, fix imports from plugins ([#620](https://github.com/segmentio/analytics-react-native/issues/620)) ([18f8ecd](https://github.com/segmentio/analytics-react-native/commit/18f8ecdb291d8c5ecb02e087aa0043df4fc72e97))
28+
29+
## [@segment/analytics-react-native-plugin-firebase-v0.3.0](https://github.com/segmentio/analytics-react-native/compare/@segment/analytics-react-native-plugin-firebase-v0.2.1...@segment/analytics-react-native-plugin-firebase-v0.3.0) (2022-07-15)
30+
31+
32+
### Features
33+
34+
* spin off the queue handling into a reusable plugin ([#502](https://github.com/segmentio/analytics-react-native/issues/502)) ([55d7988](https://github.com/segmentio/analytics-react-native/commit/55d798821163d5a41902a6bc099b1bfcbd853a17))
35+
36+
37+
### Bug Fixes
38+
39+
* map to correct firebase event name/attributes ([#596](https://github.com/segmentio/analytics-react-native/issues/596)) ([e21f541](https://github.com/segmentio/analytics-react-native/commit/e21f541725622135cbe5a3d417689325b8a8d2e3))
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2020 Segment
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
# @segment/analytics-react-native-plugin-device-token
2+
3+
`EnrichmentPlugin` to collect device token values with [Firebase Cloud Messaging](https://firebase.google.com/docs/cloud-messaging). This plugin makes it possible to collect Android's FCM and Apple's APNS device tokens.
4+
## Installation
5+
6+
> warning ""
7+
> This plugin assumes you are using Firebase Cloud Messaging for Android push notifications. If you are strictly using Apple's Push Notification Services, we recommend creating your own enrichment plugin.
8+
9+
Install the dependencies.
10+
11+
Using NPM:
12+
```bash
13+
npm install --save @segment/analytics-react-native-plugin-device-token
14+
@react-native-firebase/app @react-native-firebase/messaging
15+
```
16+
17+
Using Yarn:
18+
```bash
19+
yarn add @segment/analytics-react-native-plugin-device-token
20+
@react-native-firebase/app @react-native-firebase/messaging
21+
```
22+
23+
Run `pod install` after the installation to autolink the Firebase SDK.
24+
25+
> warning ""
26+
> Refer to Apple's [Push Notification Services](https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/sending_notification_requests_to_apns) and [Firebase Cloud Messaging](https://firebase.google.com/docs/cloud-messaging) for additional setup requirements.
27+
28+
## Usage
29+
30+
31+
Follow the [instructions for adding plugins](https://github.com/segmentio/analytics-react-native#adding-plugins) on the main Analytics client:
32+
33+
In your code where you initialize the analytics client call the `.add(plugin)` method with an `DeviceTokenPlugin` instance.
34+
35+
36+
```ts
37+
import { createClient } from '@segment/analytics-react-native';
38+
39+
import { FirebasePlugin } from '@segment/analytics-react-native-plugin-device-token';
40+
41+
const segmentClient = createClient({
42+
writeKey: 'SEGMENT_KEY'
43+
});
44+
45+
segmentClient.add({ plugin: new DeviceTokenPlugin() });
46+
```
47+
48+
### updatePermission()
49+
50+
This plugin only checks to see if permission has been authorized, it does not ask for permissions. You will need to handle permission requests yourself. Once permission has been granted you can call the `updatePermission()` method to begin collecting the device token.
51+
52+
```ts
53+
import messaging from '@react-native-firebase/messaging';
54+
import { DeviceTokenPlugin } from '@segment/analytics-react-native-plugin-device-token'
55+
56+
const deviceTokenPlugin = new DeviceTokenPlugin()
57+
58+
segmentClient.add({plugin: deviceTokenPlugin })
59+
60+
// handle firebase permissions
61+
async handlePermission() {
62+
let permissionStatus = await messaging.requestPermission()
63+
64+
if (permissionStatus) {
65+
deviceTokenPlugin.updatePermission()
66+
}
67+
}
68+
```
69+
70+
## Support
71+
72+
Please use Github issues, Pull Requests, or feel free to reach out to our [support team](https://segment.com/help/).
73+
74+
## Integrating with Segment
75+
76+
Interested in integrating your service with us? Check out our [Partners page](https://segment.com/partners/) for more details.
77+
78+
## License
79+
```
80+
MIT License
81+
82+
Copyright (c) 2021 Segment
83+
84+
Permission is hereby granted, free of charge, to any person obtaining a copy
85+
of this software and associated documentation files (the "Software"), to deal
86+
in the Software without restriction, including without limitation the rights
87+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
88+
copies of the Software, and to permit persons to whom the Software is
89+
furnished to do so, subject to the following conditions:
90+
91+
The above copyright notice and this permission notice shall be included in all
92+
copies or substantial portions of the Software.
93+
94+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
95+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
96+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
97+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
98+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
99+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
100+
SOFTWARE.
101+
```
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
module.exports = {
2+
presets: ['module:metro-react-native-babel-preset'],
3+
};
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
const { pathsToModuleNameMapper } = require('ts-jest');
2+
const { compilerOptions } = require('./tsconfig');
3+
4+
module.exports = {
5+
preset: 'react-native',
6+
roots: ['<rootDir>'],
7+
setupFiles: ['../../core/src/__tests__/__helpers__/setup.js'],
8+
testPathIgnorePatterns: ['.../../core/src/__tests__/__helpers__/'],
9+
modulePathIgnorePatterns: ['/lib/'],
10+
transform: {
11+
'^.+\\.tsx?$': 'ts-jest',
12+
},
13+
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
14+
modulePaths: [compilerOptions.baseUrl],
15+
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths),
16+
};
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
{
2+
"name": "@segment/analytics-react-native-plugin-device-token",
3+
"version": "0.1.0",
4+
"description": "The hassle-free way to add Segment analytics to your React-Native app.",
5+
"main": "lib/commonjs/index",
6+
"scripts": {
7+
"build": "bob build",
8+
"test": "jest",
9+
"typescript": "tsc --noEmit",
10+
"clean": "rimraf lib node_modules",
11+
"release": "semantic-release"
12+
},
13+
"keywords": [
14+
"segment",
15+
"react-native",
16+
"ios",
17+
"android"
18+
],
19+
"module": "lib/module/index",
20+
"types": "lib/typescript/src/index.d.ts",
21+
"react-native": "src/index",
22+
"source": "src/index",
23+
"files": [
24+
"src",
25+
"lib",
26+
"android",
27+
"ios",
28+
"cpp",
29+
"segment-analytics-react-native.podspec",
30+
"package.json",
31+
"!src/**/*.e2e.mock.js",
32+
"!**/__tests__",
33+
"!**/__fixtures__",
34+
"!**/__mocks__"
35+
],
36+
"repository": {
37+
"type": "git",
38+
"url": "https://github.com/segmentio/analytics-react-native.git",
39+
"directory": "packages/core"
40+
},
41+
"author": "Segment <[email protected]> (https://segment.com/)",
42+
"license": "MIT",
43+
"bugs": {
44+
"url": "https://github.com/segmentio/analytics-react-native/issues"
45+
},
46+
"homepage": "https://github.com/segmentio/analytics-react-native/tree/master/packages/plugins/plugin-firebase#readme",
47+
"peerDependencies": {
48+
"@react-native-firebase/app": "17.x",
49+
"@segment/analytics-react-native": "*"
50+
},
51+
"devDependencies": {
52+
"@react-native-firebase/messaging": "^17.3.2",
53+
"@semantic-release/changelog": "^6.0.1",
54+
"@semantic-release/commit-analyzer": "^9.0.2",
55+
"@semantic-release/git": "^10.0.1",
56+
"@semantic-release/github": "^8.0.4",
57+
"@semantic-release/npm": "^9.0.1",
58+
"@semantic-release/release-notes-generator": "^10.0.3",
59+
"@types/jest": "^27.0.3",
60+
"conventional-changelog-conventionalcommits": "^5.0.0",
61+
"rimraf": "^3.0.2",
62+
"semantic-release": "^19.0.3",
63+
"semantic-release-monorepo": "^7.0.5",
64+
"ts-jest": "^27.0.7",
65+
"typescript": "^4.4.4"
66+
},
67+
"react-native-builder-bob": {
68+
"source": "src",
69+
"output": "lib",
70+
"targets": [
71+
"commonjs",
72+
"module",
73+
"typescript"
74+
]
75+
},
76+
"engines": {
77+
"node": ">=12"
78+
}
79+
}
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
module.exports = {
2+
extends: ['../../../release.config.js', 'semantic-release-monorepo'],
3+
};
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
import {
2+
PlatformPlugin,
3+
SegmentClient,
4+
PluginType,
5+
ErrorType,
6+
SegmentError,
7+
} from '@segment/analytics-react-native';
8+
import { Platform } from 'react-native';
9+
import messaging from '@react-native-firebase/messaging';
10+
import type { FirebaseMessagingTypes } from '@react-native-firebase/messaging';
11+
12+
export class DeviceTokenPlugin extends PlatformPlugin {
13+
type = PluginType.enrichment;
14+
authStatus: Promise<FirebaseMessagingTypes.AuthorizationStatus | undefined> =
15+
this.checkUserPermission();
16+
17+
async configure(analytics: SegmentClient) {
18+
this.analytics = analytics;
19+
try {
20+
const isAuthorized = await this.authStatus;
21+
22+
if (isAuthorized) {
23+
let token = await this.getDeviceToken();
24+
25+
if (token !== undefined) {
26+
this.setDeviceToken(token);
27+
}
28+
} else {
29+
this.analytics?.logger.warn('Not authorized to retrieve device token');
30+
}
31+
} catch (error) {
32+
this.analytics?.logger.warn(error);
33+
this.analytics?.reportInternalError(
34+
new SegmentError(
35+
ErrorType.PluginError,
36+
'Unable to confirm authorization status',
37+
error
38+
)
39+
);
40+
}
41+
}
42+
43+
private async getDeviceToken(): Promise<string | undefined> {
44+
if (Platform.OS === 'ios') {
45+
return (await messaging().getAPNSToken()) ?? undefined;
46+
}
47+
if (Platform.OS === 'android') {
48+
let deviceToken = (await messaging().getToken()) ?? undefined;
49+
if (deviceToken !== undefined && deviceToken.length > 0) {
50+
return deviceToken;
51+
} else {
52+
return undefined;
53+
}
54+
}
55+
this.analytics?.logger.warn(
56+
'Device token only available on iOS and Android platforms'
57+
);
58+
return undefined;
59+
}
60+
61+
async setDeviceToken(token: string) {
62+
await this.analytics?.context.set({ device: { token: token } });
63+
await this.analytics?.track('Device Token Retrieved');
64+
}
65+
66+
async updatePermissionStatus() {
67+
const isAuthorized = await this.checkUserPermission();
68+
69+
if (isAuthorized) {
70+
let token = await this.getDeviceToken();
71+
72+
if (token !== undefined) {
73+
await this.setDeviceToken(token);
74+
}
75+
}
76+
}
77+
78+
private async checkUserPermission(): Promise<
79+
FirebaseMessagingTypes.AuthorizationStatus | undefined
80+
> {
81+
try {
82+
return await messaging().hasPermission();
83+
} catch (error) {
84+
this.analytics?.logger.warn(error);
85+
this.analytics?.reportInternalError(
86+
new SegmentError(
87+
ErrorType.PluginError,
88+
'Unable to confirm authorization status',
89+
error
90+
)
91+
);
92+
return undefined;
93+
}
94+
}
95+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export * from './DeviceTokenPlugin';

0 commit comments

Comments
 (0)