diff --git a/example/CONTRIBUTING.md b/example/CONTRIBUTING.md new file mode 100644 index 000000000..9127d04e6 --- /dev/null +++ b/example/CONTRIBUTING.md @@ -0,0 +1,37 @@ +# Contributing + +We want this community to be friendly and respectful to each other. Please follow it in all your interactions with the project. + +## Adding Android Packages + +Add necessary Gradle Dependencies + +```sh + implementation project(':segmentanalyticsreactnative') + implementation "com.google.android.gms:play-services-ads-identifier:18.0.1" + implementation project(':analyticsreactnativepluginadvertisingid') +``` + + +Add project to `settings.gradle` + +```sh +include ':analyticsreactnativepluginadvertisingid' +project(':analyticsreactnativepluginadvertisingid').projectDir = new File(rootProject.projectDir, '../../packages/plugins/plugin-advertising-id/android') +``` + +Add package to `MainActivity.java` + +```sh + @Override + protected List getPackages() { + @SuppressWarnings("UnnecessaryLocalVariable") + List packages = new PackageList(this).getPackages(); + // Packages that cannot be autolinked yet can be added manually here, for + // AnalyticsReactNativeExample: + // packages.add(new MyReactNativePackage()); + packages.add(new AnalyticsReactNativePackage()); + packages.add(new AnalyticsReactNativePluginAdvertisingIdPackage()); + return packages; + } +``` \ No newline at end of file diff --git a/example/android/.project b/example/android/.project index 7e90896e9..0ebf640ea 100644 --- a/example/android/.project +++ b/example/android/.project @@ -16,7 +16,7 @@ - 1644522731203 + 0 30 diff --git a/example/android/.settings/org.eclipse.buildship.core.prefs b/example/android/.settings/org.eclipse.buildship.core.prefs index 2be73b529..61544433b 100644 --- a/example/android/.settings/org.eclipse.buildship.core.prefs +++ b/example/android/.settings/org.eclipse.buildship.core.prefs @@ -5,7 +5,7 @@ connection.gradle.distribution=GRADLE_DISTRIBUTION(WRAPPER) connection.project.dir= eclipse.preferences.version=1 gradle.user.home= -java.home=/Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home +java.home=/Library/Java/JavaVirtualMachines/zulu-11.jdk/Contents/Home jvm.arguments= offline.mode=false override.workspace.settings=true diff --git a/example/android/app/build.gradle b/example/android/app/build.gradle index 22b3a9c8d..dce32a96f 100644 --- a/example/android/app/build.gradle +++ b/example/android/app/build.gradle @@ -1,5 +1,5 @@ apply plugin: "com.android.application" -apply plugin: 'com.google.gms.google-services' +// apply plugin: 'com.google.gms.google-services' import com.android.build.OutputFile @@ -210,6 +210,8 @@ dependencies { } implementation project(':segmentanalyticsreactnative') + // implementation "com.google.android.gms:play-services-ads-identifier:18.0.1" + implementation project(':analyticsreactnativepluginadvertisingid') androidTestImplementation('com.wix:detox:+') } diff --git a/example/android/app/google-services.json b/example/android/app/google-services.json deleted file mode 100644 index 472a7701e..000000000 --- a/example/android/app/google-services.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "project_info": { - "project_number": "169668264691", - "firebase_url": "https://segment-rn-analytics-tes-758c9.firebaseio.com", - "project_id": "segment-rn-analytics-tes-758c9", - "storage_bucket": "segment-rn-analytics-tes-758c9.appspot.com" - }, - "client": [ - { - "client_info": { - "mobilesdk_app_id": "1:169668264691:android:3c64b2cb29f7ff3516ed86", - "android_client_info": { - "package_name": "com.example.segmentanalyticsreactnative" - } - }, - "oauth_client": [ - { - "client_id": "169668264691-rv2engndk74jatm8t6v56bqi8dmavd16.apps.googleusercontent.com", - "client_type": 3 - } - ], - "api_key": [ - { - "current_key": "AIzaSyBo2zvlurBAZvKFyFFMf45Nd2FuBGjLn1A" - } - ], - "services": { - "appinvite_service": { - "other_platform_oauth_client": [ - { - "client_id": "169668264691-rv2engndk74jatm8t6v56bqi8dmavd16.apps.googleusercontent.com", - "client_type": 3 - }, - { - "client_id": "169668264691-98m0t8lofv1nja1ki1hvi8j0heb5hesa.apps.googleusercontent.com", - "client_type": 2, - "ios_info": { - "bundle_id": "org.reactjs.native.AnalyticsReactNativeExample" - } - } - ] - } - } - } - ], - "configuration_version": "1" -} \ No newline at end of file diff --git a/example/android/app/src/main/AndroidManifest.xml b/example/android/app/src/main/AndroidManifest.xml index e639aff34..d540db1aa 100644 --- a/example/android/app/src/main/AndroidManifest.xml +++ b/example/android/app/src/main/AndroidManifest.xml @@ -3,7 +3,7 @@ - + + + + android:launchMode="singleTask" + android:exported="true"> diff --git a/example/android/app/src/main/java/com/example/segmentanalyticsreactnative/MainApplication.java b/example/android/app/src/main/java/com/example/segmentanalyticsreactnative/MainApplication.java index 88e0756ae..dfa31af72 100644 --- a/example/android/app/src/main/java/com/example/segmentanalyticsreactnative/MainApplication.java +++ b/example/android/app/src/main/java/com/example/segmentanalyticsreactnative/MainApplication.java @@ -11,6 +11,8 @@ import java.lang.reflect.InvocationTargetException; import java.util.List; import com.segmentanalyticsreactnative.AnalyticsReactNativePackage; +import com.analyticsreactnativepluginadvertisingid.AnalyticsReactNativePluginAdvertisingIdPackage; + public class MainApplication extends Application implements ReactApplication { @@ -26,8 +28,8 @@ protected List getPackages() { List packages = new PackageList(this).getPackages(); // Packages that cannot be autolinked yet can be added manually here, for // AnalyticsReactNativeExample: - // packages.add(new MyReactNativePackage()); packages.add(new AnalyticsReactNativePackage()); + packages.add(new AnalyticsReactNativePluginAdvertisingIdPackage()); return packages; } diff --git a/example/android/build.gradle b/example/android/build.gradle index 771ec5f75..5f30c53de 100644 --- a/example/android/build.gradle +++ b/example/android/build.gradle @@ -5,9 +5,9 @@ buildscript { ext { buildToolsVersion = "30.0.2" minSdkVersion = 21 - compileSdkVersion = 30 - targetSdkVersion = 30 - ndkVersion = "21.4.7075529" + compileSdkVersion = 31 + targetSdkVersion = 31 + ndkVersion = "23.2.8568313" } repositories { google() diff --git a/example/android/settings.gradle b/example/android/settings.gradle index 2dab781a4..4223b9542 100644 --- a/example/android/settings.gradle +++ b/example/android/settings.gradle @@ -4,3 +4,6 @@ include ':app' include ':segmentanalyticsreactnative' project(':segmentanalyticsreactnative').projectDir = new File(rootProject.projectDir, '../../packages/core/android') + +include ':analyticsreactnativepluginadvertisingid' +project(':analyticsreactnativepluginadvertisingid').projectDir = new File(rootProject.projectDir, '../../packages/plugins/plugin-advertising-id/android') diff --git a/example/ios/Podfile.lock b/example/ios/Podfile.lock index 170fbd44b..e55ca8f96 100644 --- a/example/ios/Podfile.lock +++ b/example/ios/Podfile.lock @@ -466,4 +466,4 @@ SPEC CHECKSUMS: PODFILE CHECKSUM: 0c7eb82d495ca56953c50916b7b49e7512632eb6 -COCOAPODS: 1.11.3 +COCOAPODS: 1.11.2 diff --git a/example/src/App.tsx b/example/src/App.tsx index 455bc1bdd..11a0869b1 100644 --- a/example/src/App.tsx +++ b/example/src/App.tsx @@ -33,6 +33,9 @@ import { Logger } from './plugins/Logger'; // @ts-ignore import { AmplitudeSessionPlugin } from '@segment/analytics-react-native-plugin-amplitude-session'; +//@ts-ignore +// import { AdvertisingIdPlugin } from '@segment/analytics-react-native-plugin-advertising-id'; + const segmentClient = createClient({ writeKey: 'WRITE_KEY', trackAppLifecycleEvents: true, @@ -59,6 +62,10 @@ segmentClient.add({ plugin: LoggerPlugin }); segmentClient.add({ plugin: new AmplitudeSessionPlugin() }); +// segmentClient.add({ +// plugin: new AdvertisingIdPlugin(), +// }); + const MainStack = createStackNavigator(); const RootStack = createStackNavigator(); diff --git a/packages/core/android/.settings/org.eclipse.buildship.core.prefs b/packages/core/android/.settings/org.eclipse.buildship.core.prefs index f1d8c7b5f..f15e09281 100644 --- a/packages/core/android/.settings/org.eclipse.buildship.core.prefs +++ b/packages/core/android/.settings/org.eclipse.buildship.core.prefs @@ -1,11 +1,11 @@ arguments= auto.sync=false build.scans.enabled=false -connection.gradle.distribution=GRADLE_DISTRIBUTION(VERSION(7.1.1)) -connection.project.dir=../../../example/android +connection.gradle.distribution=GRADLE_DISTRIBUTION(VERSION(7.4.2)) +connection.project.dir= eclipse.preferences.version=1 gradle.user.home= -java.home=/Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home +java.home=/Library/Java/JavaVirtualMachines/zulu-11.jdk/Contents/Home jvm.arguments= offline.mode=false override.workspace.settings=true diff --git a/packages/core/android/build.gradle b/packages/core/android/build.gradle index b46a3af84..7384f3c32 100644 --- a/packages/core/android/build.gradle +++ b/packages/core/android/build.gradle @@ -17,6 +17,7 @@ buildscript { apply plugin: 'com.android.library' apply plugin: 'kotlin-android' + def getExtOrDefault(name) { return rootProject.ext.has(name) ? rootProject.ext.get(name) : project.properties['AnalyticsReactNative_' + name] } diff --git a/packages/plugins/plugin-advertising-id/CHANGELOG.md b/packages/plugins/plugin-advertising-id/CHANGELOG.md new file mode 100644 index 000000000..e69de29bb diff --git a/packages/plugins/plugin-advertising-id/CONTRIBUTING.md b/packages/plugins/plugin-advertising-id/CONTRIBUTING.md new file mode 100644 index 000000000..967611a2e --- /dev/null +++ b/packages/plugins/plugin-advertising-id/CONTRIBUTING.md @@ -0,0 +1,196 @@ +# Contributing + +We want this community to be friendly and respectful to each other. Please follow it in all your interactions with the project. + +## Development workflow + +To get started with the project, run `yarn` in the root directory to install the required dependencies for each package: + +```sh +yarn +``` + +> While it's possible to use [`npm`](https://github.com/npm/cli), the tooling is built around [`yarn`](https://classic.yarnpkg.com/), so you'll have an easier time if you use `yarn` for development. + +While developing, you can run the [example app](/example/) to test your changes. Any changes you make in your library's JavaScript code will be reflected in the example app without a rebuild. If you change any native code, then you'll need to rebuild the example app. + +To start the packager: + +```sh +yarn example start +``` + +To run the example app on Android: + +```sh +yarn example android +``` + +To run the example app on iOS: + +```sh +yarn example ios +``` + +Make sure your code passes TypeScript and ESLint. Run the following to verify: + +```sh +yarn typescript +yarn lint +``` + +To fix formatting errors, run the following: + +```sh +yarn lint --fix +``` + +Remember to add tests for your change if possible. Run the unit tests by: + +```sh +yarn test +``` + +To edit the Objective-C files, open `example/ios/AnalyticsReactNativePluginAdvertisingIdExample.xcworkspace` in XCode and find the source files at `Pods > Development Pods > react-native-analytics-react-native-plugin-advertising-id`. + +To edit the Kotlin files, open `example/android` in Android studio and find the source files at `reactnativeanalyticsreactnativepluginadvertisingid` under `Android`. + +### Commit message convention + +We follow the [conventional commits specification](https://www.conventionalcommits.org/en) for our commit messages: + +- `fix`: bug fixes, e.g. fix crash due to deprecated method. +- `feat`: new features, e.g. add new method to the module. +- `refactor`: code refactor, e.g. migrate from class components to hooks. +- `docs`: changes into documentation, e.g. add usage example for the module.. +- `test`: adding or updating tests, e.g. add integration tests using detox. +- `chore`: tooling changes, e.g. change CI config. + +Our pre-commit hooks verify that your commit message matches this format when committing. + +### Linting and tests + +[ESLint](https://eslint.org/), [Prettier](https://prettier.io/), [TypeScript](https://www.typescriptlang.org/) + +We use [TypeScript](https://www.typescriptlang.org/) for type checking, [ESLint](https://eslint.org/) with [Prettier](https://prettier.io/) for linting and formatting the code, and [Jest](https://jestjs.io/) for testing. + +Our pre-commit hooks verify that the linter and tests pass when committing. + +### Publishing to npm + +We use [release-it](https://github.com/release-it/release-it) to make it easier to publish new versions. It handles common tasks like bumping version based on semver, creating tags and releases etc. + +To publish new versions, run the following: + +```sh +yarn release +``` + +### Scripts + +The `package.json` file contains various scripts for common tasks: + +- `yarn bootstrap`: setup project by installing all dependencies and pods. +- `yarn typescript`: type-check files with TypeScript. +- `yarn lint`: lint files with ESLint. +- `yarn test`: run unit tests with Jest. +- `yarn example start`: start the Metro server for the example app. +- `yarn example android`: run the example app on Android. +- `yarn example ios`: run the example app on iOS. + +### Sending a pull request + +> **Working on your first pull request?** You can learn how from this _free_ series: [How to Contribute to an Open Source Project on GitHub](https://app.egghead.io/playlists/how-to-contribute-to-an-open-source-project-on-github). + +When you're sending a pull request: + +- Prefer small pull requests focused on one change. +- Verify that linters and tests are passing. +- Review the documentation to make sure it looks good. +- Follow the pull request template when opening a pull request. +- For pull requests that change the API or implementation, discuss with maintainers first by opening an issue. + +## Code of Conduct + +### Our Pledge + +We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. + +### Our Standards + +Examples of behavior that contributes to a positive environment for our community include: + +- Demonstrating empathy and kindness toward other people +- Being respectful of differing opinions, viewpoints, and experiences +- Giving and gracefully accepting constructive feedback +- Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience +- Focusing on what is best not just for us as individuals, but for the overall community + +Examples of unacceptable behavior include: + +- The use of sexualized language or imagery, and sexual attention or + advances of any kind +- Trolling, insulting or derogatory comments, and personal or political attacks +- Public or private harassment +- Publishing others' private information, such as a physical or email + address, without their explicit permission +- Other conduct which could reasonably be considered inappropriate in a + professional setting + +### Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. + +### Scope + +This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. + +### Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at [INSERT CONTACT METHOD]. All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the reporter of any incident. + +### Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: + +#### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. + +#### 2. Warning + +**Community Impact**: A violation through a single incident or series of actions. + +**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. + +#### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. + +#### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within the community. + +### Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, +available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations. diff --git a/packages/plugins/plugin-advertising-id/LICENSE b/packages/plugins/plugin-advertising-id/LICENSE new file mode 100644 index 000000000..4a6ab8896 --- /dev/null +++ b/packages/plugins/plugin-advertising-id/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Alan Charles + +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. diff --git a/packages/plugins/plugin-advertising-id/README.md b/packages/plugins/plugin-advertising-id/README.md new file mode 100644 index 000000000..5dfb3c970 --- /dev/null +++ b/packages/plugins/plugin-advertising-id/README.md @@ -0,0 +1,49 @@ +# @segment/analytics-react-native-plugin-advertising-id + +`EnrichmentPlugin` to collect advertisingId on Android + +## Installation + +Add the package + +```sh +yarn add react-native-analytics-react-native-plugin-advertising-id +``` + +This plugin requires a `compileSdkVersion` of at least 31. + +See [Google Play Services documentation](https://developers.google.com/admob/android/quick-start) for `advertisingId` setup +## Usage + +Follow the instructions for adding plugins on the main Analytics client: + +In your code where you initialize the Analytics client call the `.add(plugin)` method with an `AdvertisingId` instance + +```js +import { createClient } from '@segment/analytics-react-native'; +import { AdvertisingIdPlugin } from '@segment/analytics-react-native-plugin-adjust'; + +const segmentClient = createClient({ + writeKey: 'SEGMENT_KEY' +}); + +//... + +segmentClient.add({ plugin: new AdvertisingIdPlugin() }); +``` + +You will also need to ensure you have added the Application_ID `metadata` tag to your `AndroidManifest.xml` + ``` + + +``` + +## Contributing + +See the [contributing guide](CONTRIBUTING.md) to learn how to contribute to the repository and the development workflow. + +## License + +MIT diff --git a/packages/plugins/plugin-advertising-id/android/build.gradle b/packages/plugins/plugin-advertising-id/android/build.gradle new file mode 100644 index 000000000..716fa89e6 --- /dev/null +++ b/packages/plugins/plugin-advertising-id/android/build.gradle @@ -0,0 +1,132 @@ +buildscript { + // Buildscript is evaluated before everything else so we can't use getExtOrDefault + def kotlin_version = rootProject.ext.has('kotlinVersion') ? rootProject.ext.get('kotlinVersion') : project.properties['AnalyticsReactNativePluginAdvertisingId_kotlinVersion'] + + repositories { + google() + mavenCentral() + jcenter() + } + + dependencies { + classpath 'com.android.tools.build:gradle:3.2.1' + // noinspection DifferentKotlinGradleVersion + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + } +} + +apply plugin: 'com.android.library' +apply plugin: 'kotlin-android' + +def getExtOrDefault(name) { + return rootProject.ext.has(name) ? rootProject.ext.get(name) : project.properties['AnalyticsReactNativePluginAdvertisingId_' + name] +} + +def getExtOrIntegerDefault(name) { + return rootProject.ext.has(name) ? rootProject.ext.get(name) : (project.properties['AnalyticsReactNativePluginAdvertisingId_' + name]).toInteger() +} + +android { + compileSdkVersion getExtOrIntegerDefault('compileSdkVersion') + defaultConfig { + minSdkVersion 31 + targetSdkVersion getExtOrIntegerDefault('targetSdkVersion') + versionCode 1 + versionName "1.0" + + } + + buildTypes { + release { + minifyEnabled false + } + } + lintOptions { + disable 'GradleCompatible' + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } +} + +repositories { + mavenCentral() + jcenter() + google() + + def found = false + def defaultDir = null + def androidSourcesName = 'React Native sources' + + if (rootProject.ext.has('reactNativeAndroidRoot')) { + defaultDir = rootProject.ext.get('reactNativeAndroidRoot') + } else { + defaultDir = new File( + projectDir, + '/../../../node_modules/react-native/android' + ) + } + + if (defaultDir.exists()) { + maven { + url defaultDir.toString() + name androidSourcesName + } + + logger.info(":${project.name}:reactNativeAndroidRoot ${defaultDir.canonicalPath}") + found = true + } else { + def parentDir = rootProject.projectDir + + 1.upto(5, { + if (found) return true + parentDir = parentDir.parentFile + + def androidSourcesDir = new File( + parentDir, + 'node_modules/react-native' + ) + + def androidPrebuiltBinaryDir = new File( + parentDir, + 'node_modules/react-native/android' + ) + + if (androidPrebuiltBinaryDir.exists()) { + maven { + url androidPrebuiltBinaryDir.toString() + name androidSourcesName + } + + logger.info(":${project.name}:reactNativeAndroidRoot ${androidPrebuiltBinaryDir.canonicalPath}") + found = true + } else if (androidSourcesDir.exists()) { + maven { + url androidSourcesDir.toString() + name androidSourcesName + } + + logger.info(":${project.name}:reactNativeAndroidRoot ${androidSourcesDir.canonicalPath}") + found = true + } + }) + } + + if (!found) { + throw new GradleException( + "${project.name}: unable to locate React Native android sources. " + + "Ensure you have you installed React Native as a dependency in your project and try again." + ) + } +} + +def kotlin_version = getExtOrDefault('kotlinVersion') + +dependencies { + // noinspection GradleDynamicVersion + api 'com.facebook.react:react-native:+' + implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" + implementation "com.google.android.gms:play-services-ads-identifier:18.0.1" + implementation project(path: ':segment_sovran-react-native') +} diff --git a/packages/plugins/plugin-advertising-id/android/gradle.properties b/packages/plugins/plugin-advertising-id/android/gradle.properties new file mode 100644 index 000000000..3ce551ad1 --- /dev/null +++ b/packages/plugins/plugin-advertising-id/android/gradle.properties @@ -0,0 +1,3 @@ +AnalyticsReactNativePluginAdvertisingId_kotlinVersion=1.3.50 +AnalyticsReactNativePluginAdvertisingId_compileSdkVersion=31 +AnalyticsReactNativePluginAdvertisingId_targetSdkVersion=31 diff --git a/packages/plugins/plugin-advertising-id/android/src/main/AndroidManifest.xml b/packages/plugins/plugin-advertising-id/android/src/main/AndroidManifest.xml new file mode 100644 index 000000000..60ac1be4f --- /dev/null +++ b/packages/plugins/plugin-advertising-id/android/src/main/AndroidManifest.xml @@ -0,0 +1,4 @@ + + + diff --git a/packages/plugins/plugin-advertising-id/android/src/main/java/com/reactnativeanalyticsreactnativepluginadvertisingid/AnalyticsReactNativePluginAdvertisingIdModule.kt b/packages/plugins/plugin-advertising-id/android/src/main/java/com/reactnativeanalyticsreactnativepluginadvertisingid/AnalyticsReactNativePluginAdvertisingIdModule.kt new file mode 100644 index 000000000..6fdbe45a8 --- /dev/null +++ b/packages/plugins/plugin-advertising-id/android/src/main/java/com/reactnativeanalyticsreactnativepluginadvertisingid/AnalyticsReactNativePluginAdvertisingIdModule.kt @@ -0,0 +1,55 @@ +package com.analyticsreactnativepluginadvertisingid + +import com.facebook.react.bridge.ReactApplicationContext +import com.facebook.react.bridge.ReactContextBaseJavaModule +import com.facebook.react.bridge.ReactMethod +import com.facebook.react.bridge.Promise +import com.facebook.react.ReactApplication +import com.google.android.gms.ads.identifier.AdvertisingIdClient +import com.google.android.gms.common.GooglePlayServicesNotAvailableException; +import com.sovranreactnative.SovranModule +import com.facebook.react.module.annotations.ReactModule +import android.util.Log +import java.io.IOException; + + +@ReactModule(name="AnalyticsReactNativePluginAdvertisingId") +class AnalyticsReactNativePluginAdvertisingIdModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) { + override fun getName(): String { + return "AnalyticsReactNativePluginAdvertisingId" + } + + @ReactMethod + fun getAdvertisingId(promise: Promise) { + val reactContext = (currentActivity?.application as ReactApplication) + ?.reactNativeHost + ?.reactInstanceManager + ?.currentReactContext + + if (reactContext == null) { + promise.resolve(null) + return + } + + try { + val advertisingInfo = AdvertisingIdClient.getAdvertisingIdInfo(reactContext) + val isLimitAdTrackingEnabled = advertisingInfo.isLimitAdTrackingEnabled + + if (isLimitAdTrackingEnabled) { + promise.resolve(null) + } + + val id = advertisingInfo.id + val advertisingId = id.toString() + promise.resolve(advertisingId) + } + catch (e: GooglePlayServicesNotAvailableException) { + Log.d(name, e.toString()) + promise.resolve(null) + } + catch ( e: IOException) { + Log.d(name, e.toString()) + promise.resolve(null) + } + } +} \ No newline at end of file diff --git a/packages/plugins/plugin-advertising-id/android/src/main/java/com/reactnativeanalyticsreactnativepluginadvertisingid/AnalyticsReactNativePluginAdvertisingIdPackage.kt b/packages/plugins/plugin-advertising-id/android/src/main/java/com/reactnativeanalyticsreactnativepluginadvertisingid/AnalyticsReactNativePluginAdvertisingIdPackage.kt new file mode 100644 index 000000000..73b1798ac --- /dev/null +++ b/packages/plugins/plugin-advertising-id/android/src/main/java/com/reactnativeanalyticsreactnativepluginadvertisingid/AnalyticsReactNativePluginAdvertisingIdPackage.kt @@ -0,0 +1,17 @@ +package com.analyticsreactnativepluginadvertisingid + +import com.facebook.react.ReactPackage +import com.facebook.react.bridge.NativeModule +import com.facebook.react.bridge.ReactApplicationContext +import com.facebook.react.uimanager.ViewManager + + +class AnalyticsReactNativePluginAdvertisingIdPackage : ReactPackage { + override fun createNativeModules(reactContext: ReactApplicationContext): List { + return listOf(AnalyticsReactNativePluginAdvertisingIdModule(reactContext)) + } + + override fun createViewManagers(reactContext: ReactApplicationContext): List> { + return emptyList() + } +} diff --git a/packages/plugins/plugin-advertising-id/babel.config.js b/packages/plugins/plugin-advertising-id/babel.config.js new file mode 100644 index 000000000..f842b77fc --- /dev/null +++ b/packages/plugins/plugin-advertising-id/babel.config.js @@ -0,0 +1,3 @@ +module.exports = { + presets: ['module:metro-react-native-babel-preset'], +}; diff --git a/packages/plugins/plugin-advertising-id/jest.config.js b/packages/plugins/plugin-advertising-id/jest.config.js new file mode 100644 index 000000000..ca179a36b --- /dev/null +++ b/packages/plugins/plugin-advertising-id/jest.config.js @@ -0,0 +1,16 @@ +const { pathsToModuleNameMapper } = require('ts-jest/utils'); +const { compilerOptions } = require('./tsconfig'); + +module.exports = { + preset: 'react-native', + roots: [''], + 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), +}; diff --git a/packages/plugins/plugin-advertising-id/package.json b/packages/plugins/plugin-advertising-id/package.json new file mode 100644 index 000000000..1f0ca3297 --- /dev/null +++ b/packages/plugins/plugin-advertising-id/package.json @@ -0,0 +1,77 @@ +{ + "name": "@segment/analytics-react-native-plugin-advertising-id", + "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 (https://segment.com/)", + "license": "MIT", + "bugs": { + "url": "https://github.com/segmentio/analytics-react-native/issues" + }, + "homepage": "https://github.com/segmentio/analytics-react-native#readme", + "peerDependencies": { + "@segment/analytics-react-native": "*" + }, + "devDependencies": { + "@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" + } +} \ No newline at end of file diff --git a/packages/plugins/plugin-advertising-id/release.config.js b/packages/plugins/plugin-advertising-id/release.config.js new file mode 100644 index 000000000..57ec0e5b0 --- /dev/null +++ b/packages/plugins/plugin-advertising-id/release.config.js @@ -0,0 +1,3 @@ +module.exports = { + extends: ['../../../release.config.js', 'semantic-release-monorepo'], +}; diff --git a/packages/plugins/plugin-advertising-id/src/AdvertisingIdPlugin.ts b/packages/plugins/plugin-advertising-id/src/AdvertisingIdPlugin.ts new file mode 100644 index 000000000..2044facc3 --- /dev/null +++ b/packages/plugins/plugin-advertising-id/src/AdvertisingIdPlugin.ts @@ -0,0 +1,33 @@ +//@ts-ignore +import { Plugin, PluginType } from '@segment/analytics-react-native'; +import type { SegmentClient } from '@segment/analytics-react-native/src/analytics'; +import { NativeModules } from 'react-native'; + +export class AdvertisingIdPlugin extends Plugin { + type = PluginType.enrichment; + + configure(analytics: SegmentClient): void { + this.analytics = analytics; + + NativeModules.AnalyticsReactNativePluginAdvertisingId.getAdvertisingId().then( + (id: string) => { + if (id === null) { + analytics.track( + 'LimitAdTrackingEnabled (Google Play Services) is enabled' + ); + } else { + this.setContext(id); + } + } + ); + } + + setContext(id: string) { + this.analytics?.context.set({ + device: { + advertisingId: id, + adTrackingEnabled: true, + }, + }); + } +} diff --git a/packages/plugins/plugin-advertising-id/src/index.ts b/packages/plugins/plugin-advertising-id/src/index.ts new file mode 100644 index 000000000..9fb982b5d --- /dev/null +++ b/packages/plugins/plugin-advertising-id/src/index.ts @@ -0,0 +1 @@ +export * from './AdvertisingIdPlugin'; diff --git a/packages/plugins/plugin-advertising-id/src/types.ts b/packages/plugins/plugin-advertising-id/src/types.ts new file mode 100644 index 000000000..760c8c2c6 --- /dev/null +++ b/packages/plugins/plugin-advertising-id/src/types.ts @@ -0,0 +1,3 @@ +export interface AdvertisingIdData { + id?: string; +} diff --git a/packages/plugins/plugin-advertising-id/tsconfig.json b/packages/plugins/plugin-advertising-id/tsconfig.json new file mode 100644 index 000000000..5695a71a9 --- /dev/null +++ b/packages/plugins/plugin-advertising-id/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../../../tsconfig.json", + "compilerOptions": { + "outDir": "lib/typescript", + "baseUrl": ".", + "paths": { + "@segment/analytics-react-native": ["/../../core/src/index"] + } + }, + "references": [{ "path": "../../core" }] +} diff --git a/packages/plugins/plugin-mixpanel/src/methods/__mocks__/mixpanel-react-native.ts b/packages/plugins/plugin-mixpanel/src/methods/__mocks__/mixpanel-react-native.ts index 6cc68e69a..5a76a3228 100644 --- a/packages/plugins/plugin-mixpanel/src/methods/__mocks__/mixpanel-react-native.ts +++ b/packages/plugins/plugin-mixpanel/src/methods/__mocks__/mixpanel-react-native.ts @@ -40,6 +40,8 @@ export class Mixpanel { reset = jest.fn(); getDistinctId = jest.fn(() => Promise.resolve('mixpanelId')); flush = jest.fn(); + getDeviceId = jest.fn(); + setFlushOnBackground = jest.fn(); } export class People { diff --git a/yarn.lock b/yarn.lock index b49c5cc92..8393353a9 100644 --- a/yarn.lock +++ b/yarn.lock @@ -11112,4 +11112,4 @@ yn@3.1.1: yocto-queue@^0.1.0: version "0.1.0" resolved "https://registry.yarnpkg.com/yocto-queue/-/yocto-queue-0.1.0.tgz#0294eb3dee05028d31ee1a5fa2c556a6aaf10a1b" - integrity sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q== + integrity sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q== \ No newline at end of file