Skip to content

feat: add device token plugin #777

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Mar 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions packages/plugins/plugin-device-token/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
## [@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)


### Bug Fixes

* 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))

## [@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)


### Bug Fixes

* Firebase custom screen properties ([#707](https://github.com/segmentio/analytics-react-native/issues/707)) ([18b75af](https://github.com/segmentio/analytics-react-native/commit/18b75af1bb38246d75ccbfba06d6d972c6db0339))

## [@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)


### Bug Fixes

* 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))

## [@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)


### Bug Fixes

* 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))

## [@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)


### Features

* 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))


### Bug Fixes

* 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))
21 changes: 21 additions & 0 deletions packages/plugins/plugin-device-token/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2020 Segment

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
101 changes: 101 additions & 0 deletions packages/plugins/plugin-device-token/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
# @segment/analytics-react-native-plugin-device-token

`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.
## Installation

> warning ""
> 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.

Install the dependencies.

Using NPM:
```bash
npm install --save @segment/analytics-react-native-plugin-device-token
@react-native-firebase/app @react-native-firebase/messaging
```

Using Yarn:
```bash
yarn add @segment/analytics-react-native-plugin-device-token
@react-native-firebase/app @react-native-firebase/messaging
```

Run `pod install` after the installation to autolink the Firebase SDK.

> warning ""
> 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.

## Usage


Follow the [instructions for adding plugins](https://github.com/segmentio/analytics-react-native#adding-plugins) on the main Analytics client:

In your code where you initialize the analytics client call the `.add(plugin)` method with an `DeviceTokenPlugin` instance.


```ts
import { createClient } from '@segment/analytics-react-native';

import { FirebasePlugin } from '@segment/analytics-react-native-plugin-device-token';

const segmentClient = createClient({
writeKey: 'SEGMENT_KEY'
});

segmentClient.add({ plugin: new DeviceTokenPlugin() });
```

### updatePermission()

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.

```ts
import messaging from '@react-native-firebase/messaging';
import { DeviceTokenPlugin } from '@segment/analytics-react-native-plugin-device-token'

const deviceTokenPlugin = new DeviceTokenPlugin()

segmentClient.add({plugin: deviceTokenPlugin })

// handle firebase permissions
async handlePermission() {
let permissionStatus = await messaging.requestPermission()

if (permissionStatus) {
deviceTokenPlugin.updatePermission()
}
}
```

## Support

Please use Github issues, Pull Requests, or feel free to reach out to our [support team](https://segment.com/help/).

## Integrating with Segment

Interested in integrating your service with us? Check out our [Partners page](https://segment.com/partners/) for more details.

## License
```
MIT License

Copyright (c) 2021 Segment

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```
3 changes: 3 additions & 0 deletions packages/plugins/plugin-device-token/babel.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
};
16 changes: 16 additions & 0 deletions packages/plugins/plugin-device-token/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const { pathsToModuleNameMapper } = require('ts-jest');
const { compilerOptions } = require('./tsconfig');

module.exports = {
preset: 'react-native',
roots: ['<rootDir>'],
setupFiles: ['../../core/src/__tests__/__helpers__/setup.js'],
testPathIgnorePatterns: ['.../../core/src/__tests__/__helpers__/'],
modulePathIgnorePatterns: ['/lib/'],
transform: {
'^.+\\.tsx?$': 'ts-jest',
},
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
modulePaths: [compilerOptions.baseUrl],
moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths),
};
79 changes: 79 additions & 0 deletions packages/plugins/plugin-device-token/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
{
"name": "@segment/analytics-react-native-plugin-device-token",
"version": "0.1.0",
"description": "The hassle-free way to add Segment analytics to your React-Native app.",
"main": "lib/commonjs/index",
"scripts": {
"build": "bob build",
"test": "jest",
"typescript": "tsc --noEmit",
"clean": "rimraf lib node_modules",
"release": "semantic-release"
},
"keywords": [
"segment",
"react-native",
"ios",
"android"
],
"module": "lib/module/index",
"types": "lib/typescript/src/index.d.ts",
"react-native": "src/index",
"source": "src/index",
"files": [
"src",
"lib",
"android",
"ios",
"cpp",
"segment-analytics-react-native.podspec",
"package.json",
"!src/**/*.e2e.mock.js",
"!**/__tests__",
"!**/__fixtures__",
"!**/__mocks__"
],
"repository": {
"type": "git",
"url": "https://github.com/segmentio/analytics-react-native.git",
"directory": "packages/core"
},
"author": "Segment <[email protected]> (https://segment.com/)",
"license": "MIT",
"bugs": {
"url": "https://github.com/segmentio/analytics-react-native/issues"
},
"homepage": "https://github.com/segmentio/analytics-react-native/tree/master/packages/plugins/plugin-firebase#readme",
"peerDependencies": {
"@react-native-firebase/app": "17.x",
"@segment/analytics-react-native": "*"
},
"devDependencies": {
"@react-native-firebase/messaging": "^17.3.2",
"@semantic-release/changelog": "^6.0.1",
"@semantic-release/commit-analyzer": "^9.0.2",
"@semantic-release/git": "^10.0.1",
"@semantic-release/github": "^8.0.4",
"@semantic-release/npm": "^9.0.1",
"@semantic-release/release-notes-generator": "^10.0.3",
"@types/jest": "^27.0.3",
"conventional-changelog-conventionalcommits": "^5.0.0",
"rimraf": "^3.0.2",
"semantic-release": "^19.0.3",
"semantic-release-monorepo": "^7.0.5",
"ts-jest": "^27.0.7",
"typescript": "^4.4.4"
},
"react-native-builder-bob": {
"source": "src",
"output": "lib",
"targets": [
"commonjs",
"module",
"typescript"
]
},
"engines": {
"node": ">=12"
}
}
3 changes: 3 additions & 0 deletions packages/plugins/plugin-device-token/release.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports = {
extends: ['../../../release.config.js', 'semantic-release-monorepo'],
};
95 changes: 95 additions & 0 deletions packages/plugins/plugin-device-token/src/DeviceTokenPlugin.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import {
PlatformPlugin,
SegmentClient,
PluginType,
ErrorType,
SegmentError,
} from '@segment/analytics-react-native';
import { Platform } from 'react-native';
import messaging from '@react-native-firebase/messaging';
import type { FirebaseMessagingTypes } from '@react-native-firebase/messaging';

export class DeviceTokenPlugin extends PlatformPlugin {
type = PluginType.enrichment;
authStatus: Promise<FirebaseMessagingTypes.AuthorizationStatus | undefined> =
this.checkUserPermission();

async configure(analytics: SegmentClient) {
this.analytics = analytics;
try {
const isAuthorized = await this.authStatus;

if (isAuthorized) {
let token = await this.getDeviceToken();

if (token !== undefined) {
this.setDeviceToken(token);
}
} else {
this.analytics?.logger.warn('Not authorized to retrieve device token');
}
} catch (error) {
this.analytics?.logger.warn(error);
this.analytics?.reportInternalError(
new SegmentError(
ErrorType.PluginError,
'Unable to confirm authorization status',
error
)
);
}
}

private async getDeviceToken(): Promise<string | undefined> {
if (Platform.OS === 'ios') {
return (await messaging().getAPNSToken()) ?? undefined;
}
if (Platform.OS === 'android') {
let deviceToken = (await messaging().getToken()) ?? undefined;
if (deviceToken !== undefined && deviceToken.length > 0) {
return deviceToken;
} else {
return undefined;
}
}
this.analytics?.logger.warn(
'Device token only available on iOS and Android platforms'
);
return undefined;
}

async setDeviceToken(token: string) {
await this.analytics?.context.set({ device: { token: token } });
await this.analytics?.track('Device Token Retrieved');
}

async updatePermissionStatus() {
const isAuthorized = await this.checkUserPermission();

if (isAuthorized) {
let token = await this.getDeviceToken();

if (token !== undefined) {
await this.setDeviceToken(token);
}
}
}

private async checkUserPermission(): Promise<
FirebaseMessagingTypes.AuthorizationStatus | undefined
> {
try {
return await messaging().hasPermission();
} catch (error) {
this.analytics?.logger.warn(error);
this.analytics?.reportInternalError(
new SegmentError(
ErrorType.PluginError,
'Unable to confirm authorization status',
error
)
);
return undefined;
}
}
}
1 change: 1 addition & 0 deletions packages/plugins/plugin-device-token/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './DeviceTokenPlugin';
Loading