-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathBuildPostProcessor.cs
More file actions
384 lines (320 loc) · 14.7 KB
/
Copy pathBuildPostProcessor.cs
File metadata and controls
384 lines (320 loc) · 14.7 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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
/*
* Modified MIT License
*
* Copyright 2023 OneSignal
*
* 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:
*
* 1. The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 2. All copies of substantial portions of the Software may only be used in connection
* with services provided by OneSignal.
*
* 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.
*/
/*
* Testing Notes
* When making any changes please test the following senerios
* 1. Building to a new directory
* 2. Appending. Running a 2nd time
* 2. Appending. Coming from the last released version
* 3. Appending. Coming from a project without OneSignal
*
* In each of the tests ensure the NSE + App Groups work by doing the following:
* 1. Send a notification with Badge set to Increase by 1
* 2. Send a 2nd identical notification
* 3. Observe Badge value on device as 2. (NSE is working)
* 4. Open app and then background it again, Badge value will be cleared.
* 5. Send a 3rd identical notification.
* 6. Observe Badge value is 1. (If it is 3 there is an App Group issue)
*/
#if UNITY_IOS
// Flag if an App Group should created for the main target and the NSE
// Try renaming NOTIFICATION_SERVICE_EXTENSION_TARGET_NAME below first before
// removing ADD_APP_GROUP if you run into Provisioning errors in Xcode that
// can't be fix.
// ADD_APP_GROUP is required for;
// Outcomes, Badge Increment, and possibly for future features
#define ADD_APP_GROUP
using System.IO;
using UnityEditor;
using UnityEditor.iOS.Xcode;
using System.Text.RegularExpressions;
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
using UnityEditor.iOS.Xcode.Extensions;
using UnityDebug = UnityEngine.Debug;
using UnityEditor.Callbacks;
namespace OneSignalSDK.iOS
{
/// <summary>
/// Adds required frameworks to the iOS project, and adds the OneSignalNotificationServiceExtension. Also handles
/// making sure both targets (app and extension service) have the correct dependencies
/// </summary>
public class BuildPostProcessor : IPostprocessBuildWithReport
{
private const string ServiceExtensionTargetName = "OneSignalNotificationServiceExtension";
private const string ServiceExtensionFilename = "NotificationService.swift";
private const string PackageName = "com.onesignal.unitysdk.ios";
private static readonly string PluginLibrariesPath = Path.Combine(
PackageName,
"Runtime",
"Plugins",
"iOS"
);
private static readonly string PluginFilesPath = Path.Combine(
"Packages",
PluginLibrariesPath
);
private string _outputPath;
private string _projectPath;
private readonly PBXProject _project = new PBXProject();
private string _appGroupName => $"group.{PlayerSettings.applicationIdentifier}.onesignal";
/// <summary>
/// must be between 40 and 50 to ensure that it's not overriden by Podfile generation (40) and that it's
/// added before "pod install" (50)
/// </summary>
public int callbackOrder => 45;
/// <summary>
/// Entry for the build post processing necessary to get the OneSignal SDK iOS up and running
/// </summary>
public void OnPostprocessBuild(BuildReport report)
{
if (report.summary.platform != BuildTarget.iOS)
return;
// Load the project
_outputPath = report.summary.outputPath;
_projectPath = PBXProject.GetPBXProjectPath(_outputPath);
_project.ReadFromString(File.ReadAllText(_projectPath));
// Turn on capabilities required by OneSignal
AddProjectCapabilities();
// Add the service extension
AddNotificationServiceExtension();
DisableBitcode();
ConfigureLocationModule();
if (!OneSignalSDK.OneSignalSDKSettings.EffectiveDisableLocation)
AddLocationUsageDescription();
// Save the project back out
File.WriteAllText(_projectPath, _project.WriteToString());
}
/// <summary>
/// Get existing entitlements file if exists or creates a new file, adds it to the project, and returns the path
/// </summary>
private string GetEntitlementsPath(string targetGuid, string targetName)
{
var relativePath = _project.GetBuildPropertyForAnyConfig(
targetGuid,
"CODE_SIGN_ENTITLEMENTS"
);
if (relativePath != null)
{
var fullPath = Path.Combine(_outputPath, relativePath);
if (File.Exists(fullPath))
return fullPath;
}
var entitlementsPath = Path.Combine(
_outputPath,
targetName,
$"{targetName}.entitlements"
);
// make new file
var entitlementsPlist = new PlistDocument();
entitlementsPlist.WriteToFile(entitlementsPath);
// Copy the entitlement file to the xcode project
var entitlementFileName = Path.GetFileName(entitlementsPath);
var relativeDestination = targetName + "/" + entitlementFileName;
// Add the pbx configs to include the entitlements files on the project
_project.AddFile(relativeDestination, entitlementFileName);
_project.SetBuildProperty(targetGuid, "CODE_SIGN_ENTITLEMENTS", relativeDestination);
return relativeDestination;
}
/// <summary>
/// Add the required capabilities and entitlements for OneSignal
/// </summary>
private void AddProjectCapabilities()
{
var targetGuid = _project.GetMainTargetGuid();
var targetName = _project.GetMainTargetName();
var entitlementsPath = GetEntitlementsPath(targetGuid, targetName);
var projCapability = new ProjectCapabilityManager(
_projectPath,
entitlementsPath,
targetName
);
projCapability.AddBackgroundModes(BackgroundModesOptions.RemoteNotifications);
projCapability.AddPushNotifications(false);
projCapability.AddAppGroups(new[] { _appGroupName });
projCapability.WriteToFile();
}
/// <summary>
/// Create and add the notification extension to the project
/// </summary>
private void AddNotificationServiceExtension()
{
#if !UNITY_CLOUD_BUILD
// refresh plist and podfile on appends
ExtensionCreatePlist(_outputPath);
ExtensionAddPodsToTarget();
var extensionGuid = _project.TargetGuidByName(ServiceExtensionTargetName);
// skip target setup if already present
if (!string.IsNullOrEmpty(extensionGuid))
return;
extensionGuid = _project.AddAppExtension(
_project.GetMainTargetGuid(),
ServiceExtensionTargetName,
PlayerSettings.GetApplicationIdentifier(NamedBuildTarget.iOS)
+ "."
+ ServiceExtensionTargetName,
ServiceExtensionTargetName + "/" + "Info.plist" // Unix path as it's used by Xcode
);
ExtensionAddSourceFiles(extensionGuid);
// Makes it so that the extension target is Universal (not just iPhone)
_project.SetBuildProperty(extensionGuid, "TARGETED_DEVICE_FAMILY", "1,2");
_project.SetBuildProperty(extensionGuid, "IPHONEOS_DEPLOYMENT_TARGET", "11.0");
_project.SetBuildProperty(extensionGuid, "SWIFT_VERSION", "5.0");
_project.SetBuildProperty(
extensionGuid,
"DEVELOPMENT_TEAM",
PlayerSettings.iOS.appleDeveloperTeamID
);
_project.SetBuildProperty(extensionGuid, "ENABLE_BITCODE", "NO");
_project.AddBuildProperty(
extensionGuid,
"LIBRARY_SEARCH_PATHS",
$"$(PROJECT_DIR)/Libraries/{PluginLibrariesPath.Replace("\\", "/")}"
);
_project.WriteToFile(_projectPath);
// add capabilities + entitlements
var entitlementsPath = GetEntitlementsPath(extensionGuid, ServiceExtensionTargetName);
var projCapability = new ProjectCapabilityManager(
_projectPath,
entitlementsPath,
ServiceExtensionTargetName
);
projCapability.AddAppGroups(new[] { _appGroupName });
projCapability.WriteToFile();
#endif
}
/// <summary>
/// Add the swift source file required by the notification extension
/// </summary>
private void ExtensionAddSourceFiles(string extensionGuid)
{
var buildPhaseID = _project.AddSourcesBuildPhase(extensionGuid);
var sourcePath = Path.Combine(PluginFilesPath, ServiceExtensionFilename);
var destPathRelative = Path.Combine(
ServiceExtensionTargetName,
ServiceExtensionFilename
);
var destPath = Path.Combine(_outputPath, destPathRelative);
if (!File.Exists(destPath))
FileUtil.CopyFileOrDirectory(
sourcePath.Replace("\\", "/"),
destPath.Replace("\\", "/")
);
var sourceFileGuid = _project.AddFile(destPathRelative, destPathRelative);
_project.AddFileToBuildSection(extensionGuid, buildPhaseID, sourceFileGuid);
}
/// <summary>
/// Create a .plist file for the extension
/// </summary>
/// <remarks>NOTE: File in Xcode project is replaced everytime, never appends</remarks>
private bool ExtensionCreatePlist(string path)
{
var extensionPath = Path.Combine(path, ServiceExtensionTargetName);
Directory.CreateDirectory(extensionPath);
var plistPath = Path.Combine(extensionPath, "Info.plist");
var alreadyExists = File.Exists(plistPath);
var notificationServicePlist = new PlistDocument();
notificationServicePlist.ReadFromFile(Path.Combine(PluginFilesPath, "Info.plist"));
notificationServicePlist.root.SetString(
"CFBundleShortVersionString",
PlayerSettings.bundleVersion
);
notificationServicePlist.root.SetString(
"CFBundleVersion",
PlayerSettings.iOS.buildNumber
);
notificationServicePlist.WriteToFile(plistPath);
return alreadyExists;
}
private void ExtensionAddPodsToTarget()
{
var podfilePath = Path.Combine(_outputPath, "Podfile");
if (!File.Exists(podfilePath))
{
UnityDebug.LogError(
$"Could not find Podfile. {ServiceExtensionFilename} will have errors."
);
return;
}
var podfile = File.ReadAllText(podfilePath);
var podfileRegex = new Regex(
$@"target '{ServiceExtensionTargetName}' do\n pod 'OneSignalXCFramework(?:/OneSignalExtension)?', '(.+)'\nend\n"
);
var requiredVersion = OneSignaliOSDependencies.Version;
var requiredTarget =
$"target '{ServiceExtensionTargetName}' do\n pod 'OneSignalXCFramework/OneSignalExtension', '{requiredVersion}'\nend\n";
if (!podfileRegex.IsMatch(podfile))
podfile += requiredTarget;
else
{
var podfileTarget = podfileRegex.Match(podfile).ToString();
podfile = podfile.Replace(podfileTarget, requiredTarget);
}
// The app, widget, and notification service extension targets each copy the
// OneSignal XCFrameworks. With static frameworks this declares the same output
// file from multiple script phases, which newer Xcode treats as a hard
// "Multiple commands produce" error. Dropping the declared input/output paths
// makes the copy phases run unconditionally and resolves the conflict.
if (!podfile.Contains("disable_input_output_paths"))
podfile = "install! 'cocoapods', :disable_input_output_paths => true\n" + podfile;
File.WriteAllText(podfilePath, podfile);
}
private void ConfigureLocationModule()
{
if (!OneSignalSDK.OneSignalSDKSettings.EffectiveDisableLocation)
return;
_project.AddBuildProperty(
_project.GetUnityFrameworkTargetGuid(),
"GCC_PREPROCESSOR_DEFINITIONS",
"ONESIGNAL_DISABLE_LOCATION=1"
);
}
private void AddLocationUsageDescription()
{
var plistPath = Path.Combine(_outputPath, "Info.plist");
var plist = new PlistDocument();
plist.ReadFromFile(plistPath);
const string key = "NSLocationWhenInUseUsageDescription";
if (plist.root[key] == null)
plist.root.SetString(key, "Your location is used to send relevant content.");
plist.WriteToFile(plistPath);
}
private void DisableBitcode()
{
// Main
var targetGuid = _project.GetMainTargetGuid();
_project.SetBuildProperty(targetGuid, "ENABLE_BITCODE", "NO");
// Unity Tests
var unityTests = _project.TargetGuidByName(PBXProject.GetUnityTestTargetName());
_project.SetBuildProperty(unityTests, "ENABLE_BITCODE", "NO");
// Unity Framework
var unityFramework = _project.GetUnityFrameworkTargetGuid();
_project.SetBuildProperty(unityFramework, "ENABLE_BITCODE", "NO");
}
}
}
#endif