-
Notifications
You must be signed in to change notification settings - Fork 85
Expand file tree
/
Copy pathwithAndroidPushNotifications.ts
More file actions
254 lines (226 loc) · 7.56 KB
/
Copy pathwithAndroidPushNotifications.ts
File metadata and controls
254 lines (226 loc) · 7.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
import path from 'path';
import fs from 'fs';
import {
type ConfigPlugin,
withDangerousMod,
withAndroidManifest,
AndroidConfig,
} from '@expo/config-plugins';
import type { AndroidPushFallback, IntercomPluginProps } from './@types';
const SERVICE_CLASS_NAME = 'IntercomFirebaseMessagingService';
/**
* The base class of the generated messaging service decides what happens to
* push messages that are not from Intercom: ExpoFirebaseMessagingService
* forwards them to expo-notifications, the plain FirebaseMessagingService
* ignores them.
*/
const PUSH_FALLBACK_BASE_CLASSES: Record<
AndroidPushFallback,
{ className: string; import: string }
> = {
'expo-notifications': {
className: 'ExpoFirebaseMessagingService',
import:
'import expo.modules.notifications.service.ExpoFirebaseMessagingService',
},
'none': {
className: 'FirebaseMessagingService',
import: 'import com.google.firebase.messaging.FirebaseMessagingService',
},
};
function hasExpoNotifications(): boolean {
try {
require('expo-notifications');
return true;
} catch (e: any) {
return e?.code !== 'MODULE_NOT_FOUND';
}
}
function getPushNotificationsFallback(
props: IntercomPluginProps | undefined
): AndroidPushFallback {
const fallback = props?.androidPushFallback;
if (fallback === undefined) {
return hasExpoNotifications() ? 'expo-notifications' : 'none';
}
if (!Object.hasOwn(PUSH_FALLBACK_BASE_CLASSES, fallback)) {
throw new Error(
`@intercom/intercom-react-native: invalid androidPushFallback "${fallback}". Expected 'expo-notifications' or 'none'.`
);
}
return fallback;
}
/**
* Generates the Kotlin source for the FirebaseMessagingService that
* forwards FCM tokens and Intercom push messages to the Intercom SDK.
* Non-Intercom messages go to the pushFallback handler.
*/
function generateFirebaseServiceKotlin(
packageName: string,
pushFallback: AndroidPushFallback
): string {
const baseClass = PUSH_FALLBACK_BASE_CLASSES[pushFallback];
return `package ${packageName}
${baseClass.import}
import com.google.firebase.messaging.RemoteMessage
import com.intercom.reactnative.IntercomModule
class ${SERVICE_CLASS_NAME} : ${baseClass.className}() {
override fun onNewToken(refreshedToken: String) {
IntercomModule.sendTokenToIntercom(application, refreshedToken)
super.onNewToken(refreshedToken)
}
override fun onMessageReceived(remoteMessage: RemoteMessage) {
if (IntercomModule.isIntercomPush(remoteMessage)) {
IntercomModule.handleRemotePushMessage(application, remoteMessage)
} else {
super.onMessageReceived(remoteMessage)
}
}
}
`;
}
/**
* Uses withDangerousMod to write the Kotlin FirebaseMessagingService file
* into the app's Android source directory, and ensures firebase-messaging
* is on the app module's compile classpath.
*/
const writeFirebaseService: ConfigPlugin<IntercomPluginProps> = (
_config,
props
) =>
withDangerousMod(_config, [
'android',
(config) => {
const packageName = config.android?.package;
if (!packageName) {
throw new Error(
'@intercom/intercom-react-native: android.package must be defined in your Expo config to use Android push notifications.'
);
}
const pushFallback = getPushNotificationsFallback(props);
const projectRoot = config.modRequest.projectRoot;
const packagePath = packageName.replace(/\./g, '/');
const serviceDir = path.join(
projectRoot,
'android',
'app',
'src',
'main',
'java',
packagePath
);
fs.mkdirSync(serviceDir, { recursive: true });
fs.writeFileSync(
path.join(serviceDir, `${SERVICE_CLASS_NAME}.kt`),
generateFirebaseServiceKotlin(packageName, pushFallback),
'utf-8'
);
// The native module declares firebase-messaging as an `implementation`
// dependency, which keeps it private to the library. Since our generated
// service lives in the app module, we need firebase-messaging on the
// app's compile classpath too. We read the version from the native
// module's build.gradle so it stays in sync automatically.
const packageRoot = path.resolve(__dirname, '..', '..', '..');
const nativeBuildGradle = fs.readFileSync(
path.join(packageRoot, 'android', 'build.gradle'),
'utf-8'
);
const versionMatch = nativeBuildGradle.match(
/com\.google\.firebase:firebase-messaging:([\d.]+)/
);
const firebaseMessagingVersion = versionMatch
? versionMatch[1]
: '24.1.2';
const buildGradlePath = path.join(
projectRoot,
'android',
'app',
'build.gradle'
);
const buildGradle = fs.readFileSync(buildGradlePath, 'utf-8');
if (!buildGradle.includes('firebase-messaging')) {
const updatedBuildGradle = buildGradle.replace(
/dependencies\s*\{/,
`dependencies {\n implementation("com.google.firebase:firebase-messaging:${firebaseMessagingVersion}")`
);
fs.writeFileSync(buildGradlePath, updatedBuildGradle, 'utf-8');
}
return config;
},
]);
const registerServiceInManifest: ConfigPlugin<IntercomPluginProps> = (
_config
) =>
withAndroidManifest(_config, (config) => {
const mainApplication = AndroidConfig.Manifest.getMainApplicationOrThrow(
config.modResults
);
const packageName = config.android?.package;
if (!packageName) {
throw new Error(
'@intercom/intercom-react-native: android.package must be defined in your Expo config to use Android push notifications.'
);
}
const serviceName = `.${SERVICE_CLASS_NAME}`;
const existingService = mainApplication.service?.find(
(s) => s.$?.['android:name'] === serviceName
);
const hasExistingFcmService = mainApplication.service?.some(
(s) =>
s.$?.['android:name'] !== serviceName &&
([] as any[])
.concat(s['intent-filter'] ?? [])
.some((f: any) =>
([] as any[])
.concat(f.action ?? [])
.some(
(a: any) =>
a.$?.['android:name'] ===
'com.google.firebase.MESSAGING_EVENT'
)
)
);
if (hasExistingFcmService) {
console.warn(
'@intercom/intercom-react-native: An existing FirebaseMessagingService was found in AndroidManifest.xml. ' +
'Skipping automatic Intercom service registration to avoid conflicts. ' +
'You will need to route Intercom pushes manually using IntercomModule.isIntercomPush() and IntercomModule.handleRemotePushMessage().'
);
return config;
}
if (!existingService) {
if (!mainApplication.service) {
mainApplication.service = [];
}
mainApplication.service.push({
'$': {
'android:name': serviceName,
'android:exported': 'false' as any,
},
'intent-filter': [
{
$: {
'android:priority': '10',
} as any,
action: [
{
$: {
'android:name': 'com.google.firebase.MESSAGING_EVENT',
},
},
],
},
],
} as any);
}
return config;
});
export const withAndroidPushNotifications: ConfigPlugin<IntercomPluginProps> = (
config,
props
) => {
let newConfig = config;
newConfig = writeFirebaseService(newConfig, props);
newConfig = registerServiceInManifest(newConfig, props);
return newConfig;
};