react-native-bspatch 1.0.0
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.
- package/LICENSE +21 -0
- package/README.md +471 -0
- package/android/build.gradle +100 -0
- package/android/src/main/AndroidManifest.xml +3 -0
- package/android/src/main/java/vn/reactnativebspatch/BsPatchModule.kt +139 -0
- package/android/src/main/java/vn/reactnativebspatch/BsPatchPackage.kt +16 -0
- package/android/src/main/java/vn/reactnativebspatch/OtaBundleResolver.kt +227 -0
- package/cpp/CMakeLists.txt +43 -0
- package/cpp/bsdiff/bspatch.c +194 -0
- package/cpp/bsdiff/bspatch.h +41 -0
- package/cpp/bsdiff/bspatch_wrapper.c +150 -0
- package/cpp/bsdiff/bspatch_wrapper.h +6 -0
- package/cpp/bspatch_jni.cpp +41 -0
- package/cpp/bzip2/LICENSE +42 -0
- package/cpp/bzip2/blocksort.c +1094 -0
- package/cpp/bzip2/bzlib.c +1572 -0
- package/cpp/bzip2/bzlib.h +282 -0
- package/cpp/bzip2/bzlib_private.h +509 -0
- package/cpp/bzip2/compress.c +672 -0
- package/cpp/bzip2/crctable.c +104 -0
- package/cpp/bzip2/decompress.c +652 -0
- package/cpp/bzip2/huffman.c +205 -0
- package/cpp/bzip2/randtable.c +84 -0
- package/ios/OtaBundleResolver.swift +241 -0
- package/ios/RNBsPatch.h +8 -0
- package/ios/RNBsPatch.mm +198 -0
- package/lib/commonjs/NativeBsPatch.js +9 -0
- package/lib/commonjs/NativeBsPatch.js.map +1 -0
- package/lib/commonjs/crypto-js.d.js +2 -0
- package/lib/commonjs/crypto-js.d.js.map +1 -0
- package/lib/commonjs/index.js +90 -0
- package/lib/commonjs/index.js.map +1 -0
- package/lib/commonjs/ota/OtaProvider.js +306 -0
- package/lib/commonjs/ota/OtaProvider.js.map +1 -0
- package/lib/commonjs/ota/otaAssetResolver.js +145 -0
- package/lib/commonjs/ota/otaAssetResolver.js.map +1 -0
- package/lib/commonjs/ota/otaCore.js +736 -0
- package/lib/commonjs/ota/otaCore.js.map +1 -0
- package/lib/commonjs/ota/otaLogger.js +64 -0
- package/lib/commonjs/ota/otaLogger.js.map +1 -0
- package/lib/commonjs/ota/otaMetadata.js +138 -0
- package/lib/commonjs/ota/otaMetadata.js.map +1 -0
- package/lib/commonjs/ota/storage/CustomStorage.js +140 -0
- package/lib/commonjs/ota/storage/CustomStorage.js.map +1 -0
- package/lib/commonjs/ota/storage/GitHubReleaseStorage.js +96 -0
- package/lib/commonjs/ota/storage/GitHubReleaseStorage.js.map +1 -0
- package/lib/commonjs/ota/types.js +39 -0
- package/lib/commonjs/ota/types.js.map +1 -0
- package/lib/commonjs/package.json +1 -0
- package/lib/module/NativeBsPatch.js +5 -0
- package/lib/module/NativeBsPatch.js.map +1 -0
- package/lib/module/crypto-js.d.js +2 -0
- package/lib/module/crypto-js.d.js.map +1 -0
- package/lib/module/index.js +23 -0
- package/lib/module/index.js.map +1 -0
- package/lib/module/ota/OtaProvider.js +299 -0
- package/lib/module/ota/OtaProvider.js.map +1 -0
- package/lib/module/ota/otaAssetResolver.js +138 -0
- package/lib/module/ota/otaAssetResolver.js.map +1 -0
- package/lib/module/ota/otaCore.js +725 -0
- package/lib/module/ota/otaCore.js.map +1 -0
- package/lib/module/ota/otaLogger.js +59 -0
- package/lib/module/ota/otaLogger.js.map +1 -0
- package/lib/module/ota/otaMetadata.js +127 -0
- package/lib/module/ota/otaMetadata.js.map +1 -0
- package/lib/module/ota/storage/CustomStorage.js +134 -0
- package/lib/module/ota/storage/CustomStorage.js.map +1 -0
- package/lib/module/ota/storage/GitHubReleaseStorage.js +90 -0
- package/lib/module/ota/storage/GitHubReleaseStorage.js.map +1 -0
- package/lib/module/ota/types.js +38 -0
- package/lib/module/ota/types.js.map +1 -0
- package/lib/typescript/NativeBsPatch.d.ts +39 -0
- package/lib/typescript/NativeBsPatch.d.ts.map +1 -0
- package/lib/typescript/index.d.ts +15 -0
- package/lib/typescript/index.d.ts.map +1 -0
- package/lib/typescript/ota/OtaProvider.d.ts +10 -0
- package/lib/typescript/ota/OtaProvider.d.ts.map +1 -0
- package/lib/typescript/ota/otaAssetResolver.d.ts +15 -0
- package/lib/typescript/ota/otaAssetResolver.d.ts.map +1 -0
- package/lib/typescript/ota/otaCore.d.ts +109 -0
- package/lib/typescript/ota/otaCore.d.ts.map +1 -0
- package/lib/typescript/ota/otaLogger.d.ts +44 -0
- package/lib/typescript/ota/otaLogger.d.ts.map +1 -0
- package/lib/typescript/ota/otaMetadata.d.ts +46 -0
- package/lib/typescript/ota/otaMetadata.d.ts.map +1 -0
- package/lib/typescript/ota/storage/CustomStorage.d.ts +12 -0
- package/lib/typescript/ota/storage/CustomStorage.d.ts.map +1 -0
- package/lib/typescript/ota/storage/GitHubReleaseStorage.d.ts +20 -0
- package/lib/typescript/ota/storage/GitHubReleaseStorage.d.ts.map +1 -0
- package/lib/typescript/ota/types.d.ts +191 -0
- package/lib/typescript/ota/types.d.ts.map +1 -0
- package/package.json +89 -0
- package/react-native-bspatch.podspec +46 -0
- package/src/NativeBsPatch.ts +52 -0
- package/src/crypto-js.d.ts +1 -0
- package/src/index.ts +29 -0
- package/src/ota/OtaProvider.tsx +399 -0
- package/src/ota/otaAssetResolver.ts +182 -0
- package/src/ota/otaCore.ts +963 -0
- package/src/ota/otaLogger.ts +72 -0
- package/src/ota/otaMetadata.ts +149 -0
- package/src/ota/storage/CustomStorage.ts +143 -0
- package/src/ota/storage/GitHubReleaseStorage.ts +98 -0
- package/src/ota/types.ts +211 -0
- package/tools/bsdiff +0 -0
- package/tools/bsdiff.c +445 -0
- package/tools/bsdiff.h +45 -0
- package/tools/build_ota.sh +457 -0
- package/tools/setup_project.js +273 -0
- package/tools/update_registry.js +145 -0
- package/tools/upload_ota_custom.sh +138 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import NativeBsPatch from './NativeBsPatch';
|
|
2
|
+
|
|
3
|
+
export function applyPatch(
|
|
4
|
+
oldBundlePath: string,
|
|
5
|
+
newBundlePath: string,
|
|
6
|
+
patchPath: string,
|
|
7
|
+
): Promise<boolean> {
|
|
8
|
+
return NativeBsPatch.applyPatch(oldBundlePath, newBundlePath, patchPath);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function markAsHealthy(): void {
|
|
12
|
+
return NativeBsPatch.markAsHealthy();
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function reloadBundle(): void {
|
|
16
|
+
return NativeBsPatch.reloadBundle();
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export * from './ota/otaLogger';
|
|
20
|
+
export * from './ota/OtaProvider';
|
|
21
|
+
export * from './ota/types';
|
|
22
|
+
export { initOtaAssetResolver, resetOtaAssetResolver } from './ota/otaAssetResolver';
|
|
23
|
+
export { GitHubReleaseStorageProvider } from './ota/storage/GitHubReleaseStorage';
|
|
24
|
+
|
|
25
|
+
export default {
|
|
26
|
+
applyPatch,
|
|
27
|
+
reloadBundle,
|
|
28
|
+
markAsHealthy,
|
|
29
|
+
};
|
|
@@ -0,0 +1,399 @@
|
|
|
1
|
+
import React, {
|
|
2
|
+
createContext,
|
|
3
|
+
useCallback,
|
|
4
|
+
useContext,
|
|
5
|
+
useEffect,
|
|
6
|
+
useMemo,
|
|
7
|
+
useRef,
|
|
8
|
+
useState,
|
|
9
|
+
} from 'react';
|
|
10
|
+
import {
|
|
11
|
+
ActivityIndicator,
|
|
12
|
+
AppState,
|
|
13
|
+
AppStateStatus,
|
|
14
|
+
Platform,
|
|
15
|
+
StyleSheet,
|
|
16
|
+
Text,
|
|
17
|
+
View,
|
|
18
|
+
} from 'react-native';
|
|
19
|
+
import ReactNativeBlobUtil from 'react-native-blob-util';
|
|
20
|
+
import NativeBsPatch from '../NativeBsPatch';
|
|
21
|
+
import { initOtaAssetResolver } from './otaAssetResolver';
|
|
22
|
+
import { applyOtaPatchInternal, fetchOtaManifest } from './otaCore';
|
|
23
|
+
import { createOtaLogger, OtaEvent } from './otaLogger';
|
|
24
|
+
import { loadMetadata, markHealthy } from './otaMetadata';
|
|
25
|
+
import {
|
|
26
|
+
OtaConfig,
|
|
27
|
+
OtaMetrics,
|
|
28
|
+
OtaPatch,
|
|
29
|
+
OtaState,
|
|
30
|
+
OtaStatus,
|
|
31
|
+
OtaUpdateMode,
|
|
32
|
+
} from './types';
|
|
33
|
+
|
|
34
|
+
const OtaContext = createContext<OtaState | undefined>(undefined);
|
|
35
|
+
|
|
36
|
+
export function OtaProvider({
|
|
37
|
+
children,
|
|
38
|
+
config,
|
|
39
|
+
loadingView,
|
|
40
|
+
useLoadingView = true,
|
|
41
|
+
}: {
|
|
42
|
+
children: React.ReactNode;
|
|
43
|
+
config: OtaConfig;
|
|
44
|
+
loadingView?: React.ReactNode;
|
|
45
|
+
useLoadingView?: boolean;
|
|
46
|
+
}) {
|
|
47
|
+
const [status, setStatus] = useState<OtaStatus>(OtaStatus.IDLE);
|
|
48
|
+
const [message, setMessage] = useState<string>('Initializing...');
|
|
49
|
+
const [progress, setProgress] = useState<number>(0);
|
|
50
|
+
|
|
51
|
+
const [currentVersion, setCurrentVersion] = useState<number>(
|
|
52
|
+
config.baseAppVersion,
|
|
53
|
+
);
|
|
54
|
+
const [latestVersion, setLatestVersion] = useState<number>(
|
|
55
|
+
config.baseAppVersion,
|
|
56
|
+
);
|
|
57
|
+
const [pendingCount, setPendingCount] = useState<number>(0);
|
|
58
|
+
const [isChecking, setIsChecking] = useState<boolean>(false);
|
|
59
|
+
const [metrics, setMetrics] = useState<OtaMetrics | null>(null);
|
|
60
|
+
const [patches, setPatches] = useState<OtaPatch[]>([]);
|
|
61
|
+
const [isInitialized, setIsInitialized] = useState<boolean>(false);
|
|
62
|
+
|
|
63
|
+
const appState = useRef(AppState.currentState);
|
|
64
|
+
const isCheckingRef = useRef(false);
|
|
65
|
+
const bootstrapDone = useRef(false);
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Core apply update logic — separated so it can be mapped to button clicks
|
|
69
|
+
* OR called automatically by checkUpdates()
|
|
70
|
+
*/
|
|
71
|
+
const executeApplyUpdate = useCallback(
|
|
72
|
+
async (patchList: OtaPatch[], currentVer: number, targetVer: number) => {
|
|
73
|
+
console.log('[OtaProvider] executeApplyUpdate | targetV:', targetVer, 'currentV:', currentVer);
|
|
74
|
+
const directPatch = patchList.find(
|
|
75
|
+
p => p.fromVersion === currentVer &&
|
|
76
|
+
p.toVersion === targetVer &&
|
|
77
|
+
p.platform === Platform.OS,
|
|
78
|
+
);
|
|
79
|
+
|
|
80
|
+
if (!directPatch) {
|
|
81
|
+
console.warn('[OtaProvider] No direct patch found for', currentVer, '->', targetVer);
|
|
82
|
+
setStatus(OtaStatus.ERROR);
|
|
83
|
+
setMessage('No direct upgrade path found.');
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
try {
|
|
88
|
+
setStatus(OtaStatus.DOWNLOADING);
|
|
89
|
+
setProgress(0);
|
|
90
|
+
await applyOtaPatchInternal(
|
|
91
|
+
directPatch,
|
|
92
|
+
config,
|
|
93
|
+
(s: OtaStatus, msg: string, m?: OtaMetrics) => {
|
|
94
|
+
setMessage(msg);
|
|
95
|
+
setStatus(s);
|
|
96
|
+
if (m) {
|
|
97
|
+
setMetrics(m);
|
|
98
|
+
// Initialize asset resolver for the new version immediately
|
|
99
|
+
initOtaAssetResolver(targetVer);
|
|
100
|
+
}
|
|
101
|
+
},
|
|
102
|
+
(percent: number) => {
|
|
103
|
+
setProgress(percent);
|
|
104
|
+
},
|
|
105
|
+
);
|
|
106
|
+
} catch (error) {
|
|
107
|
+
console.error('[OtaProvider] Update error:', error);
|
|
108
|
+
setStatus(OtaStatus.ERROR);
|
|
109
|
+
setMessage(`Update failed: ${(error as Error).message}`);
|
|
110
|
+
}
|
|
111
|
+
},
|
|
112
|
+
[config],
|
|
113
|
+
);
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Exposed method for manual trigger
|
|
117
|
+
*/
|
|
118
|
+
const applyUpdate = useCallback(async () => {
|
|
119
|
+
await executeApplyUpdate(patches, currentVersion, latestVersion);
|
|
120
|
+
}, [executeApplyUpdate, patches, currentVersion, latestVersion]);
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Check for updates from the manifest.
|
|
124
|
+
* Uses a ref to guard against concurrent calls (avoids stale closure).
|
|
125
|
+
*/
|
|
126
|
+
const checkUpdates = useCallback(async () => {
|
|
127
|
+
if (isCheckingRef.current) return;
|
|
128
|
+
isCheckingRef.current = true;
|
|
129
|
+
setIsChecking(true);
|
|
130
|
+
setStatus(OtaStatus.CHECKING);
|
|
131
|
+
setMessage('Checking for updates...');
|
|
132
|
+
|
|
133
|
+
const log = createOtaLogger(config.onEvent);
|
|
134
|
+
log.emit(OtaEvent.CHECK_UPDATE);
|
|
135
|
+
|
|
136
|
+
try {
|
|
137
|
+
const remotePatches = await fetchOtaManifest(config);
|
|
138
|
+
const metadata = await loadMetadata(config.baseAppVersion);
|
|
139
|
+
const localV = metadata.currentVersion;
|
|
140
|
+
console.log('[OtaProvider] checkUpdates | localV:', localV, 'remotePatches count:', remotePatches.length);
|
|
141
|
+
|
|
142
|
+
const platformPatches = remotePatches.filter(p => p.platform === Platform.OS);
|
|
143
|
+
console.log('[OtaProvider] platformPatches count:', platformPatches.length);
|
|
144
|
+
|
|
145
|
+
const maxV =
|
|
146
|
+
platformPatches.length > 0
|
|
147
|
+
? Math.max(...platformPatches.map(p => p.toVersion))
|
|
148
|
+
: localV;
|
|
149
|
+
|
|
150
|
+
console.log('[OtaProvider] latestV determined:', maxV);
|
|
151
|
+
|
|
152
|
+
setPatches(platformPatches);
|
|
153
|
+
setCurrentVersion(localV);
|
|
154
|
+
setLatestVersion(maxV);
|
|
155
|
+
|
|
156
|
+
if (maxV > localV) {
|
|
157
|
+
setPendingCount(1);
|
|
158
|
+
setMessage(`Update available: V${localV} → V${maxV}`);
|
|
159
|
+
setStatus(OtaStatus.UPDATE_AVAILABLE);
|
|
160
|
+
|
|
161
|
+
// Trigger behaviors based on mode
|
|
162
|
+
if (config.updateMode === OtaUpdateMode.BACKGROUND_DOWNLOAD) {
|
|
163
|
+
downloadBackgroundUpdate(platformPatches, localV, maxV);
|
|
164
|
+
} else if (
|
|
165
|
+
config.updateMode === OtaUpdateMode.ON_APP_START ||
|
|
166
|
+
config.updateMode === OtaUpdateMode.ON_APP_FOREGROUND
|
|
167
|
+
) {
|
|
168
|
+
// Auto-apply immediately!
|
|
169
|
+
await executeApplyUpdate(platformPatches, localV, maxV);
|
|
170
|
+
}
|
|
171
|
+
} else {
|
|
172
|
+
setPendingCount(0);
|
|
173
|
+
setMessage(`All systems nominal (V${localV})`);
|
|
174
|
+
setStatus(OtaStatus.UP_TO_DATE);
|
|
175
|
+
}
|
|
176
|
+
} catch (error) {
|
|
177
|
+
setMessage(`Check failed: ${(error as Error).message}`);
|
|
178
|
+
setStatus(OtaStatus.ERROR);
|
|
179
|
+
} finally {
|
|
180
|
+
isCheckingRef.current = false;
|
|
181
|
+
setIsChecking(false);
|
|
182
|
+
}
|
|
183
|
+
}, [config, executeApplyUpdate]);
|
|
184
|
+
|
|
185
|
+
const downloadBackgroundUpdate = async (
|
|
186
|
+
patchList: OtaPatch[],
|
|
187
|
+
localV: number,
|
|
188
|
+
targetV: number,
|
|
189
|
+
) => {
|
|
190
|
+
const directPatch = patchList.find(
|
|
191
|
+
p => p.fromVersion === localV && p.toVersion === targetV,
|
|
192
|
+
);
|
|
193
|
+
if (!directPatch) return;
|
|
194
|
+
|
|
195
|
+
console.warn(
|
|
196
|
+
'[OtaProvider] BACKGROUND_DOWNLOAD mode is not yet implemented. ' +
|
|
197
|
+
'Patches were found but no download occurred. ' +
|
|
198
|
+
'Use MANUAL or ON_APP_START mode for now.',
|
|
199
|
+
);
|
|
200
|
+
};
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Bootstrap: runs once on mount.
|
|
204
|
+
*
|
|
205
|
+
* Lifecycle:
|
|
206
|
+
* 1. Load metadata
|
|
207
|
+
* 2. Check if previous launch failed → rollback if needed
|
|
208
|
+
* 3. Mark current launch as "pending verification" (lastLaunchSuccessful=false)
|
|
209
|
+
* 4. App renders → markAsHealthy() sets it back to true
|
|
210
|
+
* 5. If crash before markAsHealthy → next boot sees false → rollback
|
|
211
|
+
* 6. Check for updates based on updateMode
|
|
212
|
+
*/
|
|
213
|
+
useEffect(() => {
|
|
214
|
+
const bootstrap = async () => {
|
|
215
|
+
// Clean up any pending trash directories from previous resets (non-blocking)
|
|
216
|
+
ReactNativeBlobUtil.fs.ls(ReactNativeBlobUtil.fs.dirs.DocumentDir).then(dirs => {
|
|
217
|
+
for (const dir of dirs) {
|
|
218
|
+
if (dir.startsWith('ota_trash_')) {
|
|
219
|
+
ReactNativeBlobUtil.fs.unlink(`${ReactNativeBlobUtil.fs.dirs.DocumentDir}/${dir}`).catch(() => {});
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}).catch(() => {});
|
|
223
|
+
|
|
224
|
+
const metadata = await loadMetadata(config.baseAppVersion);
|
|
225
|
+
|
|
226
|
+
// Display current version immediately
|
|
227
|
+
setCurrentVersion(metadata.currentVersion);
|
|
228
|
+
|
|
229
|
+
// Initialize asset resolver with current version (if not base)
|
|
230
|
+
if (metadata.currentVersion > config.baseAppVersion) {
|
|
231
|
+
await initOtaAssetResolver(metadata.currentVersion);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
// (Native layer handled crash detection and any necessary rollback)
|
|
235
|
+
// We just mark bootstrap as done
|
|
236
|
+
bootstrapDone.current = true;
|
|
237
|
+
|
|
238
|
+
// Always mark as healthy after a successful JS bootstrap.
|
|
239
|
+
//
|
|
240
|
+
// The native OtaBundleResolver uses its own baseVersion (DEFAULT_BASE_VERSION=1),
|
|
241
|
+
// independent of the JS-side config.baseAppVersion. It marks
|
|
242
|
+
// lastLaunchSuccessful=false before loading ANY OTA bundle (even when
|
|
243
|
+
// JS baseAppVersion has been bumped to match currentVersion). If we only
|
|
244
|
+
// call markAsHealthy when currentVersion > JS baseAppVersion, we miss this
|
|
245
|
+
// case and the native layer will rollback on the very next cold boot.
|
|
246
|
+
//
|
|
247
|
+
// markAsHealthy() is safe to call unconditionally — it's a no-op when
|
|
248
|
+
// the metadata already has lastLaunchSuccessful=true.
|
|
249
|
+
console.log(`[OtaProvider] Marking V${metadata.currentVersion} as healthy`);
|
|
250
|
+
await markAsHealthy();
|
|
251
|
+
|
|
252
|
+
// Mode-based auto-check
|
|
253
|
+
const mode = config.updateMode ?? OtaUpdateMode.MANUAL;
|
|
254
|
+
if (
|
|
255
|
+
mode === OtaUpdateMode.ON_APP_START ||
|
|
256
|
+
mode === OtaUpdateMode.BACKGROUND_DOWNLOAD
|
|
257
|
+
) {
|
|
258
|
+
checkUpdates();
|
|
259
|
+
} else {
|
|
260
|
+
setMessage(`Ready (V${metadata.currentVersion})`);
|
|
261
|
+
setStatus(OtaStatus.UP_TO_DATE);
|
|
262
|
+
}
|
|
263
|
+
};
|
|
264
|
+
|
|
265
|
+
bootstrap().then(() => setIsInitialized(true)).catch(() => {
|
|
266
|
+
// Bootstrap failed: keep UI blocked so user sees the error state.
|
|
267
|
+
// setIsInitialized stays false → isBlocking remains true → the error
|
|
268
|
+
// message is shown via loadingView instead of a silent blank screen.
|
|
269
|
+
});
|
|
270
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
271
|
+
}, []);
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* AppState listener for ON_APP_FOREGROUND mode
|
|
275
|
+
*/
|
|
276
|
+
useEffect(() => {
|
|
277
|
+
const subscription = AppState.addEventListener(
|
|
278
|
+
'change',
|
|
279
|
+
(nextAppState: AppStateStatus) => {
|
|
280
|
+
if (
|
|
281
|
+
appState.current.match(/inactive|background/) &&
|
|
282
|
+
nextAppState === 'active' &&
|
|
283
|
+
bootstrapDone.current
|
|
284
|
+
) {
|
|
285
|
+
const mode = config.updateMode ?? OtaUpdateMode.MANUAL;
|
|
286
|
+
if (mode === OtaUpdateMode.ON_APP_FOREGROUND) {
|
|
287
|
+
checkUpdates();
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
appState.current = nextAppState;
|
|
291
|
+
},
|
|
292
|
+
);
|
|
293
|
+
|
|
294
|
+
return () => {
|
|
295
|
+
subscription.remove();
|
|
296
|
+
};
|
|
297
|
+
}, [config.updateMode, checkUpdates]);
|
|
298
|
+
|
|
299
|
+
const markAsHealthy = async () => {
|
|
300
|
+
const log = createOtaLogger(config.onEvent);
|
|
301
|
+
log.emit(OtaEvent.MARK_HEALTHY);
|
|
302
|
+
await markHealthy(config.baseAppVersion);
|
|
303
|
+
NativeBsPatch.markAsHealthy();
|
|
304
|
+
};
|
|
305
|
+
|
|
306
|
+
const resetToFactory = async () => {
|
|
307
|
+
const log = createOtaLogger(config.onEvent);
|
|
308
|
+
try {
|
|
309
|
+
setStatus(OtaStatus.APPLYING);
|
|
310
|
+
setMessage('Executing system wipe...');
|
|
311
|
+
log.emit(OtaEvent.RESET_FACTORY);
|
|
312
|
+
const otaDir = `${ReactNativeBlobUtil.fs.dirs.DocumentDir}/ota`;
|
|
313
|
+
if (await ReactNativeBlobUtil.fs.exists(otaDir)) {
|
|
314
|
+
// Fast atomic rename to prevent blocking the JS thread during deletion of potentially 1000s of files
|
|
315
|
+
const trashDir = `${ReactNativeBlobUtil.fs.dirs.DocumentDir}/ota_trash_${Date.now()}`;
|
|
316
|
+
await ReactNativeBlobUtil.fs.mv(otaDir, trashDir);
|
|
317
|
+
// Deletion is deferred to the next app bootstrap to prevent blocking the bridge before reload
|
|
318
|
+
}
|
|
319
|
+
setMessage('Reset complete. Core reload initiated...');
|
|
320
|
+
NativeBsPatch.reloadBundle();
|
|
321
|
+
} catch (error) {
|
|
322
|
+
setStatus(OtaStatus.ERROR);
|
|
323
|
+
setMessage(`Reset failed: ${(error as Error).message}`);
|
|
324
|
+
}
|
|
325
|
+
};
|
|
326
|
+
|
|
327
|
+
const value: OtaState = {
|
|
328
|
+
status,
|
|
329
|
+
message,
|
|
330
|
+
progress,
|
|
331
|
+
currentVersion,
|
|
332
|
+
latestVersion,
|
|
333
|
+
pendingCount,
|
|
334
|
+
isChecking,
|
|
335
|
+
metrics,
|
|
336
|
+
applyUpdate,
|
|
337
|
+
resetToFactory,
|
|
338
|
+
markAsHealthy,
|
|
339
|
+
checkUpdate: checkUpdates,
|
|
340
|
+
};
|
|
341
|
+
|
|
342
|
+
// Logic to determine if we should block the UI
|
|
343
|
+
const isBlocking = useMemo(() => {
|
|
344
|
+
return (
|
|
345
|
+
useLoadingView &&
|
|
346
|
+
(!isInitialized ||
|
|
347
|
+
(config.updateMode === OtaUpdateMode.ON_APP_START &&
|
|
348
|
+
(status === OtaStatus.IDLE ||
|
|
349
|
+
status === OtaStatus.CHECKING ||
|
|
350
|
+
status === OtaStatus.DOWNLOADING ||
|
|
351
|
+
status === OtaStatus.APPLYING ||
|
|
352
|
+
status === OtaStatus.UPDATE_AVAILABLE)))
|
|
353
|
+
);
|
|
354
|
+
}, [useLoadingView, isInitialized, config.updateMode, status]);
|
|
355
|
+
|
|
356
|
+
return (
|
|
357
|
+
<OtaContext.Provider value={value}>
|
|
358
|
+
{!isBlocking ? (
|
|
359
|
+
children
|
|
360
|
+
) : loadingView !== undefined ? (
|
|
361
|
+
loadingView
|
|
362
|
+
) : (
|
|
363
|
+
<View style={styles.loadingContainer}>
|
|
364
|
+
<ActivityIndicator size="large" color="#FF00F5" />
|
|
365
|
+
<Text style={styles.loadingText}>{message}</Text>
|
|
366
|
+
{status === OtaStatus.DOWNLOADING || status === OtaStatus.APPLYING ? (
|
|
367
|
+
<Text style={styles.progressText}>{progress.toFixed(1)}%</Text>
|
|
368
|
+
) : null}
|
|
369
|
+
</View>
|
|
370
|
+
)}
|
|
371
|
+
</OtaContext.Provider>
|
|
372
|
+
);
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
export function useOta() {
|
|
376
|
+
const context = useContext(OtaContext);
|
|
377
|
+
if (context === undefined) {
|
|
378
|
+
throw new Error('useOta must be used within an OtaProvider');
|
|
379
|
+
}
|
|
380
|
+
return context;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
const styles = StyleSheet.create({
|
|
384
|
+
loadingContainer: {
|
|
385
|
+
flex: 1,
|
|
386
|
+
justifyContent: 'center',
|
|
387
|
+
alignItems: 'center',
|
|
388
|
+
backgroundColor: '#000',
|
|
389
|
+
},
|
|
390
|
+
loadingText: {
|
|
391
|
+
marginTop: 20,
|
|
392
|
+
color: '#00FFCC',
|
|
393
|
+
fontSize: 16,
|
|
394
|
+
},
|
|
395
|
+
progressText: {
|
|
396
|
+
marginTop: 10,
|
|
397
|
+
color: '#fff',
|
|
398
|
+
},
|
|
399
|
+
});
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
import { Image, Platform } from 'react-native';
|
|
2
|
+
import ReactNativeBlobUtil from 'react-native-blob-util';
|
|
3
|
+
import NativeBsPatch from '../NativeBsPatch';
|
|
4
|
+
|
|
5
|
+
const ASSET_STORE_DIR = `${ReactNativeBlobUtil.fs.dirs.DocumentDir}/ota/assets`;
|
|
6
|
+
|
|
7
|
+
interface AssetMetadata {
|
|
8
|
+
originalPath: string;
|
|
9
|
+
hash: string;
|
|
10
|
+
ext: string;
|
|
11
|
+
isBase?: boolean;
|
|
12
|
+
_normPath: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
interface AssetManifest {
|
|
16
|
+
assets: AssetMetadata[];
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
let assetManifest: AssetManifest | null = null;
|
|
20
|
+
let assetMap: Map<string, AssetMetadata> = new Map();
|
|
21
|
+
let assetList: AssetMetadata[] = [];
|
|
22
|
+
let isPatched = false;
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Internal logger with native bridge integration.
|
|
26
|
+
*/
|
|
27
|
+
const log = (msg: string): void => {
|
|
28
|
+
const formatted = `[otaAssetResolver] ${msg}`;
|
|
29
|
+
console.log(formatted);
|
|
30
|
+
if (NativeBsPatch?.logNative) {
|
|
31
|
+
NativeBsPatch.logNative(formatted);
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Initializes the OTA asset resolver for a specific version.
|
|
37
|
+
* Loads the asset manifest and prepares an O(1) lookup map for intercepted image requests.
|
|
38
|
+
*
|
|
39
|
+
* @param version - The OTA version number to load assets from.
|
|
40
|
+
*/
|
|
41
|
+
export const initOtaAssetResolver = async (version: number): Promise<void> => {
|
|
42
|
+
const otaDir = `${ReactNativeBlobUtil.fs.dirs.DocumentDir}/ota`;
|
|
43
|
+
const versionDir = `${otaDir}/v${version}`;
|
|
44
|
+
const manifestPath = `${versionDir}/asset-manifest-v${version}.json`;
|
|
45
|
+
|
|
46
|
+
try {
|
|
47
|
+
if (await ReactNativeBlobUtil.fs.exists(manifestPath)) {
|
|
48
|
+
const content = await ReactNativeBlobUtil.fs.readFile(
|
|
49
|
+
manifestPath,
|
|
50
|
+
'utf8',
|
|
51
|
+
);
|
|
52
|
+
assetManifest = JSON.parse(content) as AssetManifest;
|
|
53
|
+
|
|
54
|
+
// Pre-compute normalized paths for O(1) lookup to prevent JS thread blocking during render
|
|
55
|
+
const map = new Map<string, AssetMetadata>();
|
|
56
|
+
const list = assetManifest.assets || [];
|
|
57
|
+
list.forEach((a: AssetMetadata) => {
|
|
58
|
+
const normPath = a.originalPath
|
|
59
|
+
.toLowerCase()
|
|
60
|
+
.replace(/\//g, '_')
|
|
61
|
+
.replace(/^(assets_)+/, '');
|
|
62
|
+
a._normPath = normPath; // cache for fast fallback
|
|
63
|
+
map.set(normPath, a);
|
|
64
|
+
});
|
|
65
|
+
assetMap = map;
|
|
66
|
+
assetList = list;
|
|
67
|
+
|
|
68
|
+
log(
|
|
69
|
+
`Initialized version ${version} (${list.length} assets, mapped for O(1) lookup)`,
|
|
70
|
+
);
|
|
71
|
+
patchAssetResolver();
|
|
72
|
+
} else {
|
|
73
|
+
log(`Manifest NOT found at: ${manifestPath}`);
|
|
74
|
+
}
|
|
75
|
+
} catch (e) {
|
|
76
|
+
log(`Failed to load manifest: ${(e as Error).message}`);
|
|
77
|
+
}
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Patches React Native's Image.resolveAssetSource to intercept and redirect
|
|
84
|
+
* asset requests to the locally downloaded OTA asset store.
|
|
85
|
+
*/
|
|
86
|
+
const patchAssetResolver = (): void => {
|
|
87
|
+
if (isPatched) return;
|
|
88
|
+
isPatched = true;
|
|
89
|
+
|
|
90
|
+
const resolveAssetSource = (Image as unknown as {
|
|
91
|
+
resolveAssetSource: {
|
|
92
|
+
setCustomSourceTransformer: (
|
|
93
|
+
transformer: (resolver: {
|
|
94
|
+
defaultAsset: () => { uri: string } | null;
|
|
95
|
+
}) => { uri: string } | null,
|
|
96
|
+
) => void;
|
|
97
|
+
};
|
|
98
|
+
}).resolveAssetSource;
|
|
99
|
+
|
|
100
|
+
if (
|
|
101
|
+
resolveAssetSource &&
|
|
102
|
+
typeof resolveAssetSource.setCustomSourceTransformer === 'function'
|
|
103
|
+
) {
|
|
104
|
+
resolveAssetSource.setCustomSourceTransformer((resolver) => {
|
|
105
|
+
// Get the default resolution result
|
|
106
|
+
const res = resolver.defaultAsset();
|
|
107
|
+
if (!res || !assetManifest) return res;
|
|
108
|
+
|
|
109
|
+
const uri = res.uri;
|
|
110
|
+
|
|
111
|
+
// Skip remote or data URIs
|
|
112
|
+
// Note: We DO NOT skip 'file://' because local bundles use it for relative asset resolution.
|
|
113
|
+
if (!uri || uri.startsWith('http') || uri.startsWith('data')) {
|
|
114
|
+
return res;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const normUri = uri
|
|
118
|
+
.toLowerCase()
|
|
119
|
+
.replace(/\//g, '_')
|
|
120
|
+
.replace(/^(assets_)+/, '');
|
|
121
|
+
|
|
122
|
+
// 1. Fast O(1) Map lookup
|
|
123
|
+
let found = assetMap.get(normUri);
|
|
124
|
+
|
|
125
|
+
// 2. Fallback O(N) fuzzy matching (without regex overhead)
|
|
126
|
+
if (!found) {
|
|
127
|
+
found = assetList.find((a: AssetMetadata) => {
|
|
128
|
+
return (
|
|
129
|
+
a._normPath.endsWith(normUri) ||
|
|
130
|
+
normUri.endsWith(a._normPath)
|
|
131
|
+
);
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
if (found) {
|
|
136
|
+
if (found.isBase) {
|
|
137
|
+
if (Platform.OS === 'ios') {
|
|
138
|
+
// iOS: OTA bundle generates wrong relative paths for base assets, redirect to MainBundleDir
|
|
139
|
+
const finalUri = `file://${ReactNativeBlobUtil.fs.dirs.MainBundleDir}/${found.originalPath}`;
|
|
140
|
+
log(`REDIRECTED (BASE): ${uri} -> (MainBundle: ${finalUri})`);
|
|
141
|
+
return { ...res, uri: finalUri };
|
|
142
|
+
} else {
|
|
143
|
+
// Android: let the default responder load it from apk assets (res.uri is correct)
|
|
144
|
+
return res;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const localPath = `${ASSET_STORE_DIR}/${found.hash}.${found.ext}`;
|
|
149
|
+
// iOS & Android: requires file:// prefix for absolute filesystem paths
|
|
150
|
+
const finalUri = `file://${localPath}`;
|
|
151
|
+
log(`REDIRECTED: ${uri} -> ${found.hash} (Local: ${finalUri})`);
|
|
152
|
+
return { ...res, uri: finalUri };
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// Diagnostic logging for missed assets that appear to be internal resources
|
|
156
|
+
if (uri.includes('assets')) {
|
|
157
|
+
log(`MISS: ${uri} (Not found in manifest)`);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
return res;
|
|
161
|
+
});
|
|
162
|
+
log('Successfully attached CustomSourceTransformer.');
|
|
163
|
+
} else {
|
|
164
|
+
log(
|
|
165
|
+
'ERROR: setCustomSourceTransformer is not available in this React Native version.',
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
};
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Resets the OTA asset resolver state.
|
|
172
|
+
* Call this before a major app upgrade or when unmounting the OTA context.
|
|
173
|
+
* Clears cached manifest data and resets the transformer patch guard so
|
|
174
|
+
* `initOtaAssetResolver` can re-patch cleanly on next call.
|
|
175
|
+
*/
|
|
176
|
+
export const resetOtaAssetResolver = (): void => {
|
|
177
|
+
assetManifest = null;
|
|
178
|
+
assetMap = new Map();
|
|
179
|
+
assetList = [];
|
|
180
|
+
isPatched = false;
|
|
181
|
+
};
|
|
182
|
+
|