@appzung/react-native-code-push 6.3.1 → 7.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/CodePush.js +10 -7
  2. package/CodePush.podspec +2 -2
  3. package/README.md +35 -21
  4. package/SECURITY.md +41 -0
  5. package/android/app/src/main/java/com/microsoft/codepush/react/CodePushNativeModule.java +10 -0
  6. package/android/app/src/main/java/com/microsoft/codepush/react/CodePushUpdateManager.java +14 -0
  7. package/android/app/src/main/java/com/microsoft/codepush/react/FileUtils.java +8 -9
  8. package/android/app/src/main/java/com/microsoft/codepush/react/TLSSocketFactory.java +72 -0
  9. package/android/codepush.gradle +11 -8
  10. package/docs/multi-deployment-testing-android.md +1 -1
  11. package/docs/multi-deployment-testing-ios.md +1 -1
  12. package/docs/setup-android.md +7 -6
  13. package/docs/setup-ios.md +5 -5
  14. package/docs/setup-windows.md +37 -4
  15. package/ios/CodePush/CodePush.m +26 -11
  16. package/ios/CodePush/CodePushUpdateUtils.m +1 -1
  17. package/ios/CodePush.xcodeproj/project.pbxproj +2 -2
  18. package/package.json +16 -16
  19. package/windows/CodePush/CodePush.def +3 -0
  20. package/windows/CodePush/CodePush.vcxproj +199 -0
  21. package/windows/CodePush/CodePush.vcxproj.filters +91 -0
  22. package/windows/CodePush/CodePushConfig.cpp +104 -0
  23. package/windows/CodePush/CodePushConfig.h +66 -0
  24. package/windows/CodePush/CodePushConfig.idl +12 -0
  25. package/windows/CodePush/CodePushDownloadHandler.cpp +73 -0
  26. package/windows/CodePush/CodePushDownloadHandler.h +32 -0
  27. package/windows/CodePush/CodePushNativeModule.cpp +934 -0
  28. package/windows/CodePush/CodePushNativeModule.h +247 -0
  29. package/windows/CodePush/CodePushPackage.cpp +456 -0
  30. package/windows/CodePush/CodePushPackage.h +49 -0
  31. package/windows/CodePush/CodePushTelemetryManager.cpp +213 -0
  32. package/windows/CodePush/CodePushTelemetryManager.h +29 -0
  33. package/windows/CodePush/CodePushUpdateUtils.cpp +86 -0
  34. package/windows/CodePush/CodePushUpdateUtils.h +38 -0
  35. package/windows/CodePush/CodePushUtils.cpp +29 -0
  36. package/windows/CodePush/CodePushUtils.h +18 -0
  37. package/windows/CodePush/FileUtils.cpp +131 -0
  38. package/windows/CodePush/FileUtils.h +28 -0
  39. package/windows/CodePush/PropertySheet.props +16 -0
  40. package/windows/CodePush/ReactPackageProvider.cpp +15 -0
  41. package/windows/CodePush/ReactPackageProvider.h +22 -0
  42. package/windows/CodePush/ReactPackageProvider.idl +9 -0
  43. package/windows/CodePush/miniz/LICENSE +22 -0
  44. package/windows/CodePush/miniz/miniz.c +7657 -0
  45. package/windows/CodePush/miniz/miniz.h +1338 -0
  46. package/windows/CodePush/miniz/readme.md +37 -0
  47. package/windows/CodePush/packages.config +4 -0
  48. package/windows/CodePush/pch.cpp +1 -0
  49. package/windows/CodePush/pch.h +4 -0
  50. package/{windows → windows-legacy}/CodePush/CodePush.csproj +1 -1
  51. package/{windows → windows-legacy}/CodePush.Net46/packages.config +1 -1
  52. package/windows-legacy/CodePush.Net46.Test/ApplicationDataContainerTest.cs +105 -0
  53. package/windows-legacy/CodePush.Net46.Test/CodePush.Net46.Test.csproj +137 -0
  54. package/windows-legacy/CodePush.Net46.Test/Properties/AssemblyInfo.cs +36 -0
  55. package/windows-legacy/CodePush.Net46.Test/TelemetryManagerTest.cs +117 -0
  56. package/windows-legacy/CodePush.Net46.Test/app.config +11 -0
  57. package/windows-legacy/CodePush.Net46.Test/packages.config +4 -0
  58. /package/{windows → windows-legacy}/CodePush/CodePushUtils.cs +0 -0
  59. /package/{windows → windows-legacy}/CodePush/FileUtils.cs +0 -0
  60. /package/{windows → windows-legacy}/CodePush/Properties/AssemblyInfo.cs +0 -0
  61. /package/{windows → windows-legacy}/CodePush/Properties/CodePush.rd.xml +0 -0
  62. /package/{windows → windows-legacy}/CodePush/UpdateManager.cs +0 -0
  63. /package/{windows → windows-legacy}/CodePush/UpdateUtils.cs +0 -0
  64. /package/{windows → windows-legacy}/CodePush.Net46/Adapters/Http/HttpProgress.cs +0 -0
  65. /package/{windows → windows-legacy}/CodePush.Net46/Adapters/Storage/ApplicationDataContainer.cs +0 -0
  66. /package/{windows → windows-legacy}/CodePush.Net46/CodePush.Net46.csproj +0 -0
  67. /package/{windows → windows-legacy}/CodePush.Net46/CodePushUtils.cs +0 -0
  68. /package/{windows → windows-legacy}/CodePush.Net46/FileUtils.cs +0 -0
  69. /package/{windows → windows-legacy}/CodePush.Net46/Properties/AssemblyInfo.cs +0 -0
  70. /package/{windows → windows-legacy}/CodePush.Net46/UpdateManager.cs +0 -0
  71. /package/{windows → windows-legacy}/CodePush.Net46/UpdateUtils.cs +0 -0
  72. /package/{windows → windows-legacy}/CodePush.Shared/CodePush.Shared.projitems +0 -0
  73. /package/{windows → windows-legacy}/CodePush.Shared/CodePush.Shared.shproj +0 -0
  74. /package/{windows → windows-legacy}/CodePush.Shared/CodePushConstants.cs +0 -0
  75. /package/{windows → windows-legacy}/CodePush.Shared/CodePushNativeModule.cs +0 -0
  76. /package/{windows → windows-legacy}/CodePush.Shared/CodePushReactPackage.cs +0 -0
  77. /package/{windows → windows-legacy}/CodePush.Shared/CodePushUtils.cs +0 -0
  78. /package/{windows → windows-legacy}/CodePush.Shared/InstallMode.cs +0 -0
  79. /package/{windows → windows-legacy}/CodePush.Shared/MinimumBackgroundListener.cs +0 -0
  80. /package/{windows → windows-legacy}/CodePush.Shared/SettingsManager.cs +0 -0
  81. /package/{windows → windows-legacy}/CodePush.Shared/TelemetryManager.cs +0 -0
  82. /package/{windows → windows-legacy}/CodePush.Shared/UpdateState.cs +0 -0
@@ -0,0 +1,934 @@
1
+ // Copyright (c) Microsoft Corporation.
2
+ // Licensed under the MIT License.
3
+
4
+ #include "pch.h"
5
+
6
+ #include "CodePushNativeModule.h"
7
+ #include "CodePushUtils.h"
8
+ #include "CodePushUpdateUtils.h"
9
+ #include "CodePushPackage.h"
10
+ #include "CodePushTelemetryManager.h"
11
+ #include "CodePushConfig.h"
12
+ #include "CodePushUtils.h"
13
+
14
+ #include <string_view>
15
+
16
+ #include "miniz/miniz.h"
17
+
18
+ #include "winrt/Windows.ApplicationModel.h"
19
+ #include "winrt/Windows.Data.Json.h"
20
+ #include "winrt/Windows.Storage.FileProperties.h"
21
+
22
+ #include "ReactPackageProvider.h"
23
+
24
+ namespace Microsoft::CodePush::ReactNative
25
+ {
26
+ using namespace winrt;
27
+ using namespace winrt::Microsoft::ReactNative;
28
+ using namespace Windows::Data::Json;
29
+ using namespace Windows::Storage;
30
+ using namespace Windows::Foundation;
31
+
32
+ ReactNativeHost CodePushNativeModule::s_host{};
33
+ CodePushNativeModule::CodePushInstallMode CodePushNativeModule::s_installMode{};
34
+ bool CodePushNativeModule::isRunningBinaryVersion{ false };
35
+ bool CodePushNativeModule::needToReportRollback{ false };
36
+ /*static*/ bool CodePushNativeModule::s_initialized{ false };
37
+ /*static*/ hstring CodePushNativeModule::s_javaScriptBundleFileName{ L"index.windows" };
38
+
39
+ /*static*/ IAsyncOperation<StorageFile> CodePushNativeModule::GetBinaryBundleAsync()
40
+ {
41
+ auto appXFolder{ Windows::ApplicationModel::Package::Current().InstalledLocation() };
42
+ auto bundleFolder{ (co_await appXFolder.TryGetItemAsync(L"Bundle")).try_as<StorageFolder>() };
43
+ if (bundleFolder == nullptr)
44
+ {
45
+ co_return nullptr;
46
+ }
47
+
48
+ auto bundleFile{ (co_await bundleFolder.TryGetItemAsync(s_javaScriptBundleFileName + BundleExtension)).try_as<StorageFile>() };
49
+ co_return bundleFile;
50
+ }
51
+
52
+ /*static*/ IAsyncOperation<StorageFile> CodePushNativeModule::GetBundleFileAsync()
53
+ {
54
+ auto bundleFileName{ s_host.InstanceSettings().JavaScriptBundleFile() };
55
+ if (!bundleFileName.empty())
56
+ {
57
+ s_javaScriptBundleFileName = bundleFileName;
58
+ }
59
+
60
+ auto packageBundle{ co_await CodePushPackage::GetCurrentPackageBundleAsync() };
61
+ auto binaryBundle{ co_await GetBinaryBundleAsync() };
62
+
63
+ if (packageBundle == nullptr)
64
+ {
65
+ CodePushUtils::LogBundleUrl(binaryBundle);
66
+ isRunningBinaryVersion = true;
67
+ co_return binaryBundle;
68
+ }
69
+
70
+ auto binaryAppVersion{ CodePushConfig::Current().GetAppVersion() };
71
+ auto currentPackageMetadata{ co_await CodePushPackage::GetCurrentPackageAsync() };
72
+ if (currentPackageMetadata == nullptr)
73
+ {
74
+ CodePushUtils::LogBundleUrl(binaryBundle);
75
+ isRunningBinaryVersion = true;
76
+ co_return binaryBundle;
77
+ }
78
+
79
+ auto packageDate{ currentPackageMetadata.GetNamedString(BinaryBundleDateKey, L"") };
80
+ auto packageAppVersion{ currentPackageMetadata.GetNamedString(AppVersionKey, L"") };
81
+
82
+ if ((co_await CodePushUpdateUtils::ModifiedDateStringOfFileAsync(binaryBundle)) == packageDate && binaryAppVersion == packageAppVersion)
83
+ {
84
+ // Return package file because it is newer than the JS bundle in the AppX folder
85
+ CodePushUtils::LogBundleUrl(packageBundle);
86
+ isRunningBinaryVersion = false;
87
+ co_return packageBundle;
88
+ }
89
+ else
90
+ {
91
+ auto isRelease{ false };
92
+ #ifndef _DEBUG
93
+ isRelease = true;
94
+ #endif
95
+
96
+ if (isRelease || binaryAppVersion != packageAppVersion)
97
+ {
98
+ co_await ClearUpdatesStaticAsync();
99
+ }
100
+
101
+ CodePushUtils::LogBundleUrl(binaryBundle);
102
+ isRunningBinaryVersion = true;
103
+ co_return binaryBundle;
104
+ }
105
+ }
106
+
107
+ /*static*/ IAsyncOperation<StorageFolder> CodePushNativeModule::GetBundleAssetsFolderAsync()
108
+ {
109
+ auto appXFolder{ Windows::ApplicationModel::Package::Current().InstalledLocation() };
110
+ auto bundleFolder{ (co_await appXFolder.TryGetItemAsync(L"Bundle")).try_as<StorageFolder>() };
111
+ if (bundleFolder != nullptr)
112
+ {
113
+ auto bundleAssetsFolder{ (co_await bundleFolder.TryGetItemAsync(CodePushUpdateUtils::AssetsFolderName)).try_as<StorageFolder>() };
114
+ co_return bundleAssetsFolder;
115
+ }
116
+ co_return nullptr;
117
+ }
118
+
119
+ // Rather than store files in the library files, CodePush for ReactNativeWindows will use AppData folders.
120
+ /*static*/ StorageFolder CodePushNativeModule::GetLocalStorageFolder()
121
+ {
122
+ return ApplicationData::Current().LocalFolder();
123
+ }
124
+
125
+ /*static*/ ApplicationDataContainer CodePushNativeModule::GetLocalSettings()
126
+ {
127
+ return ApplicationData::Current().LocalSettings();
128
+ }
129
+
130
+ void CodePushNativeModule::OverrideAppVersion(std::wstring_view appVersion)
131
+ {
132
+ CodePushConfig::Current().SetAppVersion(appVersion);
133
+ }
134
+
135
+ void CodePushNativeModule::SetDeploymentKey(std::wstring_view deploymentKey)
136
+ {
137
+ CodePushConfig::Current().SetDeploymentKey(deploymentKey);
138
+ }
139
+
140
+ /*
141
+ * This method checks to see whether a specific package hash
142
+ * has previously failed installation.
143
+ */
144
+ bool CodePushNativeModule::IsFailedHash(std::wstring_view packageHash)
145
+ {
146
+ auto localSettings{ GetLocalSettings() };
147
+ auto failedUpdatesData{ localSettings.Values().TryLookup(FailedUpdatesKey) };
148
+ if (failedUpdatesData == nullptr)
149
+ {
150
+ return false;
151
+ }
152
+ auto failedUpdatesString{ unbox_value<hstring>(failedUpdatesData) };
153
+ JsonArray failedUpdates;
154
+ auto success{ JsonArray::TryParse(failedUpdatesString, failedUpdates) };
155
+ if (!success || packageHash.empty())
156
+ {
157
+ return false;
158
+ }
159
+ else
160
+ {
161
+ for (const auto& failedPackage : failedUpdates)
162
+ {
163
+ // We don't have to worry about backwards compatability, but just to be safe...
164
+ if (failedPackage.ValueType() == JsonValueType::Object)
165
+ {
166
+ auto failedPackageHash{ failedPackage.GetObject().GetNamedString(PackageHashKey) };
167
+ if (packageHash == failedPackageHash)
168
+ {
169
+ return true;
170
+ }
171
+ }
172
+ }
173
+
174
+ return false;
175
+ }
176
+ }
177
+
178
+ /*
179
+ * This method is used to get information about the latest rollback.
180
+ * This information will be used to decide whether the application
181
+ * should ignore the update or not.
182
+ */
183
+ JsonObject CodePushNativeModule::GetRollbackInfo() { return nullptr; }
184
+
185
+ /*
186
+ * This method is used to get the count of rollback for the package
187
+ * using the latest rollback information.
188
+ */
189
+ int CodePushNativeModule::GetRollbackCountForPackage(std::wstring_view packageHash, const JsonObject& latestRollbackInfo)
190
+ {
191
+ auto oldPackageHash{ latestRollbackInfo.GetNamedString(LatestRollbackPackageHashKey, L"null") };
192
+ if (packageHash == oldPackageHash)
193
+ {
194
+ auto oldCount{ latestRollbackInfo.GetNamedNumber(LatestRollbackCountKey, 0) };
195
+ return static_cast<int>(oldCount);
196
+ }
197
+ return 0;
198
+ }
199
+
200
+ /*
201
+ * This method checks to see whether a specific package hash
202
+ * represents a downloaded and installed update, that hasn't
203
+ * been applied yet via an app restart.
204
+ */
205
+ /*static*/ bool CodePushNativeModule::IsPendingUpdate(std::wstring_view packageHash)
206
+ {
207
+ auto localSettings{ GetLocalSettings() };
208
+ auto pendingUpdateData{ localSettings.Values().TryLookup(PendingUpdateKey) };
209
+ if (pendingUpdateData != nullptr)
210
+ {
211
+ auto pendingUpdateString{ unbox_value<hstring>(pendingUpdateData) };
212
+ JsonObject pendingUpdate;
213
+ auto success{ JsonObject::TryParse(pendingUpdateString, pendingUpdate) };
214
+
215
+ // If there is a pending update whose "state" isn't loading, then we consider it "pending".
216
+ // Additionally, if a specific hash was provided, we ensure it matches that of the pending update.
217
+ auto updateIsPending{ success &&
218
+ pendingUpdate != nullptr &&
219
+ pendingUpdate.GetNamedBoolean(PendingUpdateIsLoadingKey, false) == false &&
220
+ (packageHash.empty() || pendingUpdate.GetNamedString(PendingUpdateHashKey, L"null") == packageHash) };
221
+
222
+ return updateIsPending;
223
+ }
224
+ return false;
225
+ }
226
+
227
+ /*
228
+ * This method is used to clear updates that are installed
229
+ * under a different app version and hence don't apply anymore,
230
+ * during a debug run configuration and when React Native Windows is
231
+ * running the JS bundle from the dev server.
232
+ */
233
+ IAsyncAction CodePushNativeModule::ClearDebugUpdates()
234
+ {
235
+ #ifndef BUNDLE
236
+ auto binaryAppVersion{ CodePushConfig::Current().GetAppVersion() };
237
+ auto currentPackageMetadata{ co_await CodePushPackage::GetCurrentPackageAsync() };
238
+ if (currentPackageMetadata != nullptr)
239
+ {
240
+ auto packageAppVersion{ currentPackageMetadata.GetNamedString(AppVersionKey, L"") };
241
+ if (binaryAppVersion.empty() || binaryAppVersion != packageAppVersion)
242
+ {
243
+ co_await ClearUpdatesStaticAsync();
244
+ }
245
+ }
246
+ #endif
247
+ co_return;
248
+ }
249
+
250
+ /*static*/ IAsyncAction CodePushNativeModule::ClearUpdatesStaticAsync()
251
+ {
252
+ co_await CodePushPackage::ClearUpdatesAsync();
253
+ RemovePendingUpdate();
254
+ RemoveFailedUpdates();
255
+ }
256
+
257
+ void CodePushNativeModule::DispatchDownloadProgressEvent()
258
+ {
259
+ // Notify the script-side about the progress
260
+ m_context.CallJSFunction(
261
+ L"RCTDeviceEventEmitter",
262
+ L"emit",
263
+ L"CodePushDownloadProgress",
264
+ JSValueObject{
265
+ {"totalBytes", m_latestExpectedContentLength },
266
+ {"receivedBytes", m_latestReceivedContentLength } });
267
+ }
268
+
269
+ /*static*/ IAsyncAction CodePushNativeModule::LoadBundle()
270
+ {
271
+ if (!s_host.InstanceSettings().UseWebDebugger())
272
+ {
273
+ auto bundleFile{ co_await GetBundleFileAsync() };
274
+ if (bundleFile != nullptr)
275
+ {
276
+ std::wstring_view bundlePath{ bundleFile.Path() };
277
+ hstring bundleRootPath{ bundlePath.substr(0, bundlePath.rfind('\\')) };
278
+ s_host.InstanceSettings().BundleRootPath(bundleRootPath);
279
+ }
280
+ }
281
+
282
+ s_host.ReloadInstance();
283
+ // The instance will call Initialize() upon reloading this module
284
+ }
285
+
286
+ /*
287
+ * This method is used when an update has failed installation
288
+ * and the app needs to be rolled back to the previous bundle.
289
+ * This method is automatically called when the rollback timer
290
+ * expires without the app indicating whether the update succeeded,
291
+ * and therefore, it shouldn't be called directly.
292
+ */
293
+ IAsyncAction CodePushNativeModule::RollbackPackage()
294
+ {
295
+ auto failedPackage{ co_await CodePushPackage::GetCurrentPackageAsync() };
296
+ if (failedPackage == nullptr)
297
+ {
298
+ CodePushUtils::Log(L"Attempted to perform a rollback when there is no current update.");
299
+ }
300
+ else
301
+ {
302
+ SaveFailedUpdate(failedPackage);
303
+ }
304
+
305
+ // Rollback to the previous version and de-register the new update
306
+ co_await CodePushPackage::RollbackPackage();
307
+ RemovePendingUpdate();
308
+ co_await LoadBundle();
309
+ }
310
+
311
+ /*
312
+ * This method is used to clear away failed updates in the event that
313
+ * a new app store binary is installed.
314
+ */
315
+
316
+ /*static*/ void CodePushNativeModule::RemoveFailedUpdates()
317
+ {
318
+ auto localSettings{ GetLocalSettings() };
319
+ localSettings.Values().TryRemove(FailedUpdatesKey);
320
+ }
321
+
322
+ /*
323
+ * This method is used to register the fact that a pending
324
+ * update succeeded and therefore can be removed.
325
+ */
326
+ /*static*/ void CodePushNativeModule::RemovePendingUpdate()
327
+ {
328
+ // remove pending update from LocalSettings
329
+ auto localSettings{ GetLocalSettings() };
330
+ localSettings.Values().TryRemove(PendingUpdateKey);
331
+ }
332
+
333
+ IAsyncAction CodePushNativeModule::RestartAppInternal(bool onlyIfUpdateIsPending)
334
+ {
335
+ if (m_restartInProgress)
336
+ {
337
+ CodePushUtils::Log(L"Restart request queued until the current restart is completed.");
338
+ m_restartQueue.push_back(onlyIfUpdateIsPending);
339
+ }
340
+ else if (!m_allowed)
341
+ {
342
+ CodePushUtils::Log(L"Restart request queued until restarts are re-allowed.");
343
+ m_restartQueue.push_back(onlyIfUpdateIsPending);
344
+ co_return;
345
+ }
346
+
347
+ m_restartInProgress = true;
348
+ if (!onlyIfUpdateIsPending || IsPendingUpdate(L""))
349
+ {
350
+ co_await LoadBundle();
351
+ CodePushUtils::Log(L"Restarting app.");
352
+ co_return;
353
+ }
354
+
355
+ m_restartInProgress = false;
356
+ if (m_restartQueue.size() > 0)
357
+ {
358
+ auto buf{ m_restartQueue[0] };
359
+ m_restartQueue.erase(m_restartQueue.begin());
360
+ co_await RestartAppInternal(buf);
361
+ }
362
+ }
363
+
364
+ /*
365
+ * When an update failed to apply, this method can be called
366
+ * to store its hash so that it can be ignored on future
367
+ * attempts to check the server for an update.
368
+ */
369
+ void CodePushNativeModule::SaveFailedUpdate(JsonObject& failedPackage)
370
+ {
371
+ if (IsFailedHash(failedPackage.GetNamedString(PackageHashKey)))
372
+ {
373
+ return;
374
+ }
375
+
376
+ auto localSettings{ GetLocalSettings() };
377
+ auto failedUpdates{ localSettings.Values().TryLookup(FailedUpdatesKey).try_as<JsonArray>() };
378
+ if (failedUpdates == nullptr)
379
+ {
380
+ failedUpdates = JsonArray{};
381
+ }
382
+
383
+ failedUpdates.Append(failedPackage);
384
+ localSettings.Values().Insert(FailedUpdatesKey, box_value(failedUpdates.Stringify()));
385
+ }
386
+
387
+ /*
388
+ * When an update is installed whose mode isn't Immediate, this method
389
+ * can be called to store the pending update's metadata (e.g. packageHash)
390
+ * so that it can be used when the actual update application occurs at a later point.
391
+ */
392
+ void CodePushNativeModule::SavePendingUpdate(std::wstring_view packageHash, bool isLoading)
393
+ {
394
+ // Since we're not restarting, we need to store the fact that the update
395
+ // was installed, but hasn't yet become "active".
396
+ auto localSettings{ GetLocalSettings() };
397
+ JsonObject pendingUpdate{};
398
+ pendingUpdate.Insert(PendingUpdateHashKey, JsonValue::CreateStringValue(packageHash));
399
+ pendingUpdate.Insert(PendingUpdateIsLoadingKey, JsonValue::CreateBooleanValue(isLoading));
400
+ localSettings.Values().Insert(PendingUpdateKey, box_value(pendingUpdate.Stringify()));
401
+ }
402
+
403
+ /*static*/ void CodePushNativeModule::SetHost(const ReactNativeHost& host)
404
+ {
405
+ s_host = host;
406
+ }
407
+
408
+ void CodePushNativeModule::Initialize(ReactContext const& reactContext) noexcept
409
+ {
410
+ m_context = reactContext;
411
+ InitializeUpdateAfterRestart();
412
+ }
413
+
414
+ void CodePushNativeModule::GetConstants(winrt::Microsoft::ReactNative::ReactConstantProvider& constants) noexcept
415
+ {
416
+ constants.Add(L"codePushInstallModeImmediate", CodePushInstallMode::Immediate);
417
+ constants.Add(L"codePushInstallModeOnNextRestart", CodePushInstallMode::OnNextRestart);
418
+ constants.Add(L"codePushInstallModeOnNextResume", CodePushInstallMode::OnNextResume);
419
+ constants.Add(L"codePushInstallModeOnNextSuspend", CodePushInstallMode::OnNextSuspend);
420
+
421
+ constants.Add(L"codePushUpdateStateRunning", CodePushUpdateState::Running);
422
+ constants.Add(L"codePushUpdateStatePending", CodePushUpdateState::Pending);
423
+ constants.Add(L"codePushUpdateStateLatest", CodePushUpdateState::Latest);
424
+ }
425
+
426
+ /*
427
+ * This is native-side of the RemotePackage.download method
428
+ */
429
+ fire_and_forget CodePushNativeModule::DownloadUpdateAsync(JsonObject updatePackage, bool notifyProgress, ReactPromise<IJsonValue> promise) noexcept
430
+ {
431
+ auto binaryBundle{ co_await GetBinaryBundleAsync() };
432
+ if (binaryBundle != nullptr)
433
+ {
434
+ auto modifiedDate{ co_await CodePushUpdateUtils::ModifiedDateStringOfFileAsync(binaryBundle) };
435
+ updatePackage.Insert(BinaryBundleDateKey, JsonValue::CreateStringValue(modifiedDate));
436
+ }
437
+
438
+ auto publicKey{ CodePushConfig::Current().GetPublicKey() };
439
+
440
+ try
441
+ {
442
+ co_await CodePushPackage::DownloadPackageAsync(
443
+ updatePackage,
444
+ s_javaScriptBundleFileName + BundleExtension,
445
+ /* publicKey */ publicKey,
446
+ /* progressCallback */ [=](int64_t expectedContentLength, int64_t receivedContentLength) {
447
+ // React-Native-Windows doesn't have a frame observer to my knowledge.
448
+ if (notifyProgress)
449
+ {
450
+ m_latestExpectedContentLength = expectedContentLength;
451
+ m_latestReceivedContentLength = receivedContentLength;
452
+ DispatchDownloadProgressEvent();
453
+ }
454
+ });
455
+ }
456
+ catch (const hresult_error& ex)
457
+ {
458
+ SaveFailedUpdate(updatePackage);
459
+
460
+ m_didUpdateProgress = false;
461
+ promise.Reject(ex.message().c_str());
462
+ }
463
+
464
+ auto newPackage{ co_await CodePushPackage::GetPackageAsync(updatePackage.GetNamedString(PackageHashKey)) };
465
+ if (newPackage == nullptr)
466
+ {
467
+ promise.Reject(L"An error has occurred retreiving the downloaded package.");
468
+ }
469
+ else
470
+ {
471
+ promise.Resolve(newPackage);
472
+ }
473
+
474
+ co_return;
475
+ }
476
+
477
+ /*
478
+ * This is the native side of the CodePush.getConfiguration method. It isn't
479
+ * currently exposed via the "react-native-code-push" module, and is used
480
+ * internally only by the CodePush.checkForUpdate method in order to get the
481
+ * app version, as well as the deployment key that was configured in App.cpp.
482
+ */
483
+ fire_and_forget CodePushNativeModule::GetConfiguration(ReactPromise<IJsonValue> promise) noexcept
484
+ {
485
+ auto configuration{ CodePushConfig::Current().GetConfiguration() };
486
+ if (isRunningBinaryVersion)
487
+ {
488
+ auto errorMessage{ L"Error: Package hashing is currently unimplemented. Binary hash was not obtained." };
489
+ auto error{ hresult_error(E_NOTIMPL, errorMessage) };
490
+ CodePushUtils::Log(error);
491
+ CodePushUtils::Log(L"Error obtaining hash for binary contents.");
492
+ promise.Resolve(configuration);
493
+ co_return;
494
+ }
495
+ promise.Resolve(configuration);
496
+ }
497
+
498
+ /*
499
+ * This method is the native side of the CodePush.getUpdateMetadata method.
500
+ */
501
+ fire_and_forget CodePushNativeModule::GetUpdateMetadataAsync(CodePushUpdateState updateState, ReactPromise<IJsonValue> promise) noexcept
502
+ {
503
+ auto package{ co_await CodePushPackage::GetCurrentPackageAsync() };
504
+ if (package == nullptr)
505
+ {
506
+ // The app hasn't downloaded any CodePush updates yet,
507
+ // so we simply return nil regardless if the user
508
+ // wanted to retrieve the pending or running update.
509
+ promise.Resolve(JsonValue::CreateNullValue());
510
+ co_return;
511
+ }
512
+
513
+ // We have a CodePush update, so let's see if it's currently in a pending state.
514
+ bool currentUpdateIsPending{ IsPendingUpdate(package.GetNamedString(PackageHashKey)) };
515
+
516
+ if (updateState == CodePushUpdateState::Pending && !currentUpdateIsPending) {
517
+ // The caller wanted a pending update
518
+ // but there isn't currently one.
519
+ promise.Resolve(JsonValue::CreateNullValue());
520
+ }
521
+ else if (updateState == CodePushUpdateState::Running && currentUpdateIsPending) {
522
+ // The caller wants the running update, but the current
523
+ // one is pending, so we need to grab the previous.
524
+ promise.Resolve(co_await CodePushPackage::GetPreviousPackageAsync());
525
+ }
526
+ else {
527
+ // The current package satisfies the request:
528
+ // 1) Caller wanted a pending, and there is a pending update
529
+ // 2) Caller wanted the running update, and there isn't a pending
530
+ // 3) Caller wants the latest update, regardless if it's pending or not
531
+ if (isRunningBinaryVersion) {
532
+ // This only matters in Debug builds. Since we do not clear "outdated" updates,
533
+ // we need to indicate to the JS side that somehow we have a current update on
534
+ // disk that is not actually running.
535
+ package.Insert(L"_isDebugOnly", JsonValue::CreateBooleanValue(true));
536
+ }
537
+
538
+ // Enable differentiating pending vs. non-pending updates
539
+ package.Insert(PackageIsPendingKey, JsonValue::CreateBooleanValue(currentUpdateIsPending));
540
+ promise.Resolve(package);
541
+ }
542
+ co_return;
543
+ }
544
+
545
+ /*
546
+ * This method is the native side of the LocalPackage.install method.
547
+ */
548
+ fire_and_forget CodePushNativeModule::InstallUpdateAsync(JsonObject updatePackage, CodePushInstallMode installMode, int minimumBackgroundDuration, ReactPromise<void> promise) noexcept
549
+ {
550
+ try
551
+ {
552
+ co_await CodePushPackage::InstallPackageAsync(updatePackage, IsPendingUpdate(L""));
553
+ }
554
+ catch (const hresult_error& ex)
555
+ {
556
+ promise.Reject(ex.message().c_str());
557
+ co_return;
558
+ }
559
+ SavePendingUpdate(updatePackage.GetNamedString(PackageHashKey), false);
560
+ s_installMode = installMode;
561
+ if (s_installMode == CodePushInstallMode::OnNextResume || s_installMode == CodePushInstallMode::OnNextSuspend) {
562
+ // Essentially, for RNW, InstallMode is currently always Immediate
563
+ auto errorMessage{ L"Error: ON_NEXT_RESUME and ON_NEXT_SUSPEND install modes are not currently supported." };
564
+ hresult_error error{ E_NOTIMPL, errorMessage };
565
+ CodePushUtils::Log(error);
566
+ throw error;
567
+ }
568
+
569
+ // Signal to JS that the update has been applied.
570
+ promise.Resolve();
571
+ co_return;
572
+ }
573
+
574
+ /*
575
+ * This method isn't publicly exposed via the "react-native-code-push"
576
+ * module, and is only used internally to populate the RemotePackage.failedInstall property.
577
+ */
578
+ void CodePushNativeModule::IsFailedUpdate(std::wstring packageHash, ReactPromise<bool> promise) noexcept
579
+ {
580
+ auto isFailedHash{ IsFailedHash(packageHash) };
581
+ promise.Resolve(isFailedHash);
582
+ }
583
+
584
+ /*
585
+ * This method is used to save information about the latest rollback.
586
+ * This information will be used to decide whether the application
587
+ * should ignore the update or not.
588
+ */
589
+ void CodePushNativeModule::SetLatestRollbackInfo(std::wstring packageHash) noexcept
590
+ {
591
+ if (packageHash.empty())
592
+ {
593
+ return;
594
+ }
595
+
596
+ auto localSettings{ GetLocalSettings() };
597
+ JsonObject latestRollbackInfo;
598
+ auto res{ localSettings.Values().TryLookup(LatestRollbackInfoKey) };
599
+ if (res != nullptr)
600
+ {
601
+ auto infoString{ unbox_value<hstring>(res) };
602
+ JsonObject::TryParse(infoString, latestRollbackInfo);
603
+ }
604
+
605
+ auto initialRollbackCount{ GetRollbackCountForPackage(packageHash, latestRollbackInfo) };
606
+ auto count{ initialRollbackCount + 1 };
607
+ auto currentTimeMillis{ clock::to_time_t(clock::now()) * 1000 };
608
+
609
+ latestRollbackInfo.Insert(LatestRollbackCountKey, JsonValue::CreateNumberValue(count));
610
+ latestRollbackInfo.Insert(LatestRollbackTimeKey, JsonValue::CreateNumberValue(static_cast<double>(currentTimeMillis)));
611
+ latestRollbackInfo.Insert(LatestRollbackPackageHashKey, JsonValue::CreateStringValue(packageHash));
612
+
613
+ localSettings.Values().Insert(LatestRollbackInfoKey, box_value(latestRollbackInfo.Stringify()));
614
+ }
615
+
616
+ /*
617
+ * This method is used when the app is started to either
618
+ * initialize a pending update or rollback a faulty update
619
+ * to the previous version.
620
+ */
621
+ IAsyncAction CodePushNativeModule::InitializeUpdateAfterRestart()
622
+ {
623
+ if (s_host.InstanceSettings().UseWebDebugger())
624
+ {
625
+ co_await ClearDebugUpdates();
626
+ }
627
+
628
+ auto localSettings{ GetLocalSettings() };
629
+ auto pendingUpdateData{ localSettings.Values().TryLookup(PendingUpdateKey) };
630
+ if (pendingUpdateData != nullptr)
631
+ {
632
+ auto pendingUpdateString{ unbox_value<hstring>(pendingUpdateData) };
633
+ JsonObject pendingUpdate;
634
+ auto success{ JsonObject::TryParse(pendingUpdateString, pendingUpdate) };
635
+ if (success)
636
+ {
637
+ m_isFirstRunAfterUpdate = true;
638
+ auto updateIsLoading{ pendingUpdate.GetNamedBoolean(PendingUpdateIsLoadingKey, false) };
639
+ if (updateIsLoading)
640
+ {
641
+ // Pending update was initialized, but notifyApplicationReady was not called.
642
+ // Therefore, deduce that it is a broken update and rollback.
643
+ CodePushUtils::Log(L"Update did not finish loading the last time, rolling back to a previous version.");
644
+ needToReportRollback = true;
645
+ co_await RollbackPackage();
646
+ }
647
+ else
648
+ {
649
+ // Mark that we tried to initialize the new update, so that if it crashes,
650
+ // we will know that we need to rollback when the app next starts.
651
+ SavePendingUpdate(pendingUpdate.GetNamedString(PendingUpdateHashKey, L""), true);
652
+ }
653
+ }
654
+ }
655
+ }
656
+
657
+ /*
658
+ * This method is used to get information about the latest rollback.
659
+ * This information will be used to decide whether the application
660
+ * should ignore the update or not.
661
+ */
662
+ void CodePushNativeModule::GetLatestRollbackInfo(ReactPromise<IJsonValue> promise) noexcept
663
+ {
664
+ auto localSettings{ GetLocalSettings() };
665
+ auto res{ localSettings.Values().TryLookup(LatestRollbackInfoKey) };
666
+ auto infoString{ unbox_value<hstring>(res) };
667
+ JsonObject latestRollbackInfo;
668
+ auto success{ JsonObject::TryParse(infoString, latestRollbackInfo) };
669
+ if (success)
670
+ {
671
+ promise.Resolve(latestRollbackInfo);
672
+ }
673
+ else
674
+ {
675
+ promise.Resolve(JsonValue::CreateNullValue());
676
+ }
677
+ }
678
+
679
+ /*
680
+ * This method isn't publicly exposed via the "react-native-code-push"
681
+ * module, and is only used internally to populate the LocalPackage.isFirstRun property.
682
+ */
683
+ fire_and_forget CodePushNativeModule::IsFirstRun(std::wstring packageHash, ReactPromise<bool> promise) noexcept
684
+ {
685
+ auto isFirstRun = m_isFirstRunAfterUpdate
686
+ && !packageHash.empty()
687
+ && packageHash == co_await CodePushPackage::GetCurrentPackageHashAsync();
688
+
689
+ promise.Resolve(isFirstRun);
690
+ }
691
+
692
+ /*
693
+ * This method is the native side of the CodePush.notifyApplicationReady() method.
694
+ */
695
+ void CodePushNativeModule::NotifyApplicationReady(ReactPromise<IJsonValue> promise) noexcept
696
+ {
697
+ RemovePendingUpdate();
698
+ promise.Resolve(JsonValue::CreateNullValue());
699
+ }
700
+
701
+ void CodePushNativeModule::Allow(ReactPromise<JSValue> promise) noexcept
702
+ {
703
+ CodePushUtils::Log(L"Re-allowing restarts.");
704
+ m_allowed = true;
705
+
706
+ if (m_restartQueue.size() > 0)
707
+ {
708
+ CodePushUtils::Log(L"Executing pending restart.");
709
+ auto buf{ m_restartQueue[0] };
710
+ m_restartQueue.erase(m_restartQueue.begin());
711
+ RestartAppInternal(buf);
712
+ }
713
+
714
+ promise.Resolve(JSValue::Null);
715
+ }
716
+
717
+ void CodePushNativeModule::ClearPendingRestart() noexcept
718
+ {
719
+ m_restartQueue.clear();
720
+ }
721
+
722
+ void CodePushNativeModule::Disallow(ReactPromise<JSValue> promise) noexcept
723
+ {
724
+ CodePushUtils::Log(L"Disallowing restarts.");
725
+ m_allowed = false;
726
+ promise.Resolve(JSValue::Null);
727
+ }
728
+
729
+ /*
730
+ * This method is the native side of the CodePush.restartApp() method.
731
+ */
732
+ fire_and_forget CodePushNativeModule::RestartApp(bool onlyIfUpdateIsPending, ReactPromise<JSValue> promise) noexcept
733
+ {
734
+ co_await RestartAppInternal(onlyIfUpdateIsPending);
735
+ promise.Resolve(JSValue::Null);
736
+ }
737
+
738
+ /*
739
+ * This method clears CodePush's downloaded updates.
740
+ * It is needed to switch to a different deployment if the current deployment is more recent.
741
+ * Note: we don�t recommend to use this method in scenarios other than that (CodePush will call this method
742
+ * automatically when needed in other cases) as it could lead to unpredictable behavior.
743
+ */
744
+ fire_and_forget CodePushNativeModule::ClearUpdates() noexcept
745
+ {
746
+ co_await ClearUpdatesStaticAsync();
747
+ }
748
+
749
+ /*
750
+ * This method is the native side of the CodePush.downloadAndReplaceCurrentBundle()
751
+ * method, which replaces the current bundle with the one downloaded from
752
+ * removeBundleUrl. It is only to be used during tests and no-ops if the test
753
+ * configuration flag is not set.
754
+ */
755
+ fire_and_forget CodePushNativeModule::DownloadAndReplaceCurrentBundle(std::wstring remoteBundleUrl) noexcept
756
+ {
757
+ auto errorMessage{ L"Error: DownloadAndReplaceCurrentBundle is not currently implmented" };
758
+ hresult_error error{ E_NOTIMPL, errorMessage };
759
+ CodePushUtils::Log(error);
760
+ throw error;
761
+ }
762
+
763
+ /*
764
+ * This method is checks if a new status update exists (new version was installed,
765
+ * or an update failed) and return its details (version label, status).
766
+ */
767
+ fire_and_forget CodePushNativeModule::GetNewStatusReportAsync(ReactPromise<IJsonValue> promise) noexcept
768
+ {
769
+ if (needToReportRollback)
770
+ {
771
+ needToReportRollback = false;
772
+ auto localSettings{ GetLocalSettings() };
773
+ auto failedUpdatesData{ localSettings.Values().TryLookup(FailedUpdatesKey) };
774
+ if (failedUpdatesData != nullptr)
775
+ {
776
+ auto failedUpdatesString{ unbox_value<hstring>(failedUpdatesData) };
777
+ JsonArray failedUpdates;
778
+ auto success{ JsonArray::TryParse(failedUpdatesString, failedUpdates) };
779
+ if (success)
780
+ {
781
+ auto lastFailedPackage{ failedUpdates.GetObjectAt(failedUpdates.Size() - 1) };
782
+ if (lastFailedPackage != nullptr)
783
+ {
784
+ promise.Resolve(CodePushTelemetryManager::GetRollbackReport(lastFailedPackage));
785
+ co_return;
786
+ }
787
+ }
788
+ }
789
+ }
790
+ else if (m_isFirstRunAfterUpdate)
791
+ {
792
+ auto currentPackage = co_await CodePushPackage::GetCurrentPackageAsync();
793
+ if (currentPackage != nullptr)
794
+ {
795
+ promise.Resolve(CodePushTelemetryManager::GetUpdateReport(currentPackage));
796
+ co_return;
797
+ }
798
+ }
799
+ else if (isRunningBinaryVersion)
800
+ {
801
+ auto appVersionString{ CodePushConfig::Current().GetAppVersion() };
802
+ promise.Resolve(CodePushTelemetryManager::GetBinaryUpdateReport(appVersionString));
803
+ co_return;
804
+ }
805
+ else
806
+ {
807
+ auto retryStatusReport{ CodePushTelemetryManager::GetRetryStatusReport() };
808
+ if (retryStatusReport != nullptr)
809
+ {
810
+ promise.Resolve(retryStatusReport);
811
+ co_return;
812
+ }
813
+ }
814
+
815
+ promise.Resolve(JsonValue::CreateNullValue());
816
+ co_return;
817
+ }
818
+
819
+ void CodePushNativeModule::RecordStatusReported(JsonObject statusReport) noexcept
820
+ {
821
+ CodePushTelemetryManager::RecordStatusReported(statusReport);
822
+ }
823
+
824
+ void CodePushNativeModule::SaveStatusReportForRetry(JsonObject statusReport) noexcept
825
+ {
826
+ CodePushTelemetryManager::SaveStatusReportForRetry(statusReport);
827
+ }
828
+
829
+ } // namespace CodePush
830
+
831
+ // Helper functions for reading and sending JsonValues to and from JavaScript
832
+ namespace winrt::Microsoft::ReactNative
833
+ {
834
+ using namespace winrt::Windows::Data::Json;
835
+
836
+ void WriteValue(IJSValueWriter const& writer, IJsonValue const& value) noexcept
837
+ {
838
+ if (value == nullptr)
839
+ {
840
+ writer.WriteNull();
841
+ }
842
+ else
843
+ {
844
+ switch (value.ValueType())
845
+ {
846
+ case JsonValueType::Object:
847
+ writer.WriteObjectBegin();
848
+ for (const auto& pair : value.GetObject())
849
+ {
850
+ writer.WritePropertyName(pair.Key());
851
+ WriteValue(writer, pair.Value());
852
+ }
853
+ writer.WriteObjectEnd();
854
+ break;
855
+ case JsonValueType::Array:
856
+ writer.WriteArrayBegin();
857
+ for (const auto& elem : value.GetArray())
858
+ {
859
+ WriteValue(writer, elem);
860
+ }
861
+ writer.WriteArrayEnd();
862
+ break;
863
+ case JsonValueType::Boolean:
864
+ writer.WriteBoolean(value.GetBoolean());
865
+ break;
866
+ case JsonValueType::Number:
867
+ writer.WriteDouble(value.GetNumber());
868
+ break;
869
+ case JsonValueType::String:
870
+ writer.WriteString(value.GetString());
871
+ break;
872
+ case JsonValueType::Null:
873
+ writer.WriteNull();
874
+ break;
875
+ }
876
+ }
877
+ }
878
+
879
+ void ReadValue(IJSValueReader const& reader, /*out*/ JsonObject& value) noexcept
880
+ {
881
+ if (reader.ValueType() == JSValueType::Object)
882
+ {
883
+ hstring propertyName;
884
+ while (reader.GetNextObjectProperty(propertyName))
885
+ {
886
+ value.Insert(propertyName, ReadValue<IJsonValue>(reader));
887
+ }
888
+ }
889
+ }
890
+
891
+ void ReadValue(IJSValueReader const& reader, /*out*/ IJsonValue& value) noexcept
892
+ {
893
+ if (reader.ValueType() == JSValueType::Object)
894
+ {
895
+ JsonObject valueObject;
896
+ hstring propertyName;
897
+ while (reader.GetNextObjectProperty(propertyName))
898
+ {
899
+ valueObject.Insert(propertyName, ReadValue<IJsonValue>(reader));
900
+ }
901
+ value = valueObject;
902
+ }
903
+ else if (reader.ValueType() == JSValueType::Array)
904
+ {
905
+ JsonArray valueArray;
906
+ while (reader.GetNextArrayItem())
907
+ {
908
+ valueArray.Append(ReadValue<IJsonValue>(reader));
909
+ }
910
+ value = valueArray;
911
+ }
912
+ else
913
+ {
914
+ switch (reader.ValueType())
915
+ {
916
+ case JSValueType::Boolean:
917
+ value = JsonValue::CreateBooleanValue(reader.GetBoolean());
918
+ break;
919
+ case JSValueType::Double:
920
+ value = JsonValue::CreateNumberValue(reader.GetDouble());
921
+ break;
922
+ case JSValueType::Int64:
923
+ value = JsonValue::CreateNumberValue(static_cast<double>(reader.GetInt64()));
924
+ break;
925
+ case JSValueType::String:
926
+ value = JsonValue::CreateStringValue(reader.GetString());
927
+ break;
928
+ case JSValueType::Null:
929
+ value = JsonValue::CreateNullValue();
930
+ break;
931
+ }
932
+ }
933
+ }
934
+ }