-
Notifications
You must be signed in to change notification settings - Fork 280
Expand file tree
/
Copy pathBundledResourceCopier.java
More file actions
320 lines (285 loc) Β· 12.5 KB
/
Copy pathBundledResourceCopier.java
File metadata and controls
320 lines (285 loc) Β· 12.5 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
package cn.reactnative.modules.update;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.os.Build;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.zip.ZipEntry;
import java.util.regex.Pattern;
final class BundledResourceCopier {
private static final Pattern VERSION_QUALIFIER_PATTERN = Pattern.compile("-v\\d+(?=/)");
private static final String AAB_BASE_PREFIX = "base/";
private final Context context;
private static final class ResolvedResourceSource {
final int resourceId;
final String assetPath;
final TypedValue typedValue;
ResolvedResourceSource(int resourceId, String assetPath, TypedValue typedValue) {
this.resourceId = resourceId;
this.assetPath = assetPath;
this.typedValue = typedValue;
}
}
BundledResourceCopier(Context context) {
this.context = context.getApplicationContext();
}
void copyFromResource(
HashMap<String, ArrayList<File>> resToCopy,
HashMap<String, Long> crcByFrom
) throws IOException {
ArrayList<String> apkPaths = collectApkPaths();
HashMap<String, ZipEntry> availableEntries = new HashMap<String, ZipEntry>();
HashMap<String, SafeZipFile> zipFileMap = new HashMap<String, SafeZipFile>();
HashMap<String, SafeZipFile> entryToZipFileMap = new HashMap<String, SafeZipFile>();
// Content checksum index: CRC32 -> entry name. Lets us locate a file by
// content when its origin path is not present verbatim on device (e.g.
// APK baseline diff applied on an AAB/split-apk install whose res/
// paths were shortened). First entry for a given crc wins.
HashMap<Long, String> crcToEntryName = new HashMap<Long, String>();
try {
for (String apkPath : apkPaths) {
SafeZipFile zipFile = new SafeZipFile(new File(apkPath));
zipFileMap.put(apkPath, zipFile);
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry ze = entries.nextElement();
String entryName = ze.getName();
if (!availableEntries.containsKey(entryName)) {
availableEntries.put(entryName, ze);
entryToZipFileMap.put(entryName, zipFile);
}
long crc = ze.getCrc();
if (crc != -1L && !crcToEntryName.containsKey(crc)) {
crcToEntryName.put(crc, entryName);
}
}
}
HashMap<String, String> normalizedEntryMap = new HashMap<String, String>();
for (String entryName : availableEntries.keySet()) {
String normalized = normalizeResPath(entryName);
normalizedEntryMap.putIfAbsent(normalized, entryName);
}
SafeZipFile baseZipFile = zipFileMap.get(context.getPackageResourcePath());
HashMap<String, ArrayList<File>> remainingFiles =
new HashMap<String, ArrayList<File>>(resToCopy);
for (String fromPath : new ArrayList<String>(remainingFiles.keySet())) {
ArrayList<File> targets = remainingFiles.get(fromPath);
if (targets == null || targets.isEmpty()) {
continue;
}
ZipEntry entry = availableEntries.get(fromPath);
String actualSourcePath = fromPath;
ResolvedResourceSource resolvedResource = null;
if (entry == null) {
String normalizedFrom = normalizeResPath(fromPath);
String actualEntry = normalizedEntryMap.get(normalizedFrom);
if (actualEntry != null) {
entry = availableEntries.get(actualEntry);
actualSourcePath = actualEntry;
}
}
// Content (CRC32) match: robust across APK/AAB packaging because
// the checksum is over the uncompressed file content, not its
// path. Preferred over the resource-id heuristic below.
if (entry == null && crcByFrom != null) {
Long wantedCrc = crcByFrom.get(fromPath);
if (wantedCrc != null) {
String matchedEntry = crcToEntryName.get(wantedCrc);
if (matchedEntry != null) {
entry = availableEntries.get(matchedEntry);
actualSourcePath = matchedEntry;
}
}
}
if (entry == null) {
resolvedResource = resolveBundledResource(fromPath);
if (resolvedResource != null) {
actualSourcePath = resolvedResource.assetPath;
}
}
if (entry == null && resolvedResource == null) {
continue;
}
File lastTarget = null;
for (File target : targets) {
try {
if (lastTarget != null) {
UpdateFileUtils.copyFile(lastTarget, target);
} else if (entry != null) {
SafeZipFile sourceZipFile = entryToZipFileMap.get(actualSourcePath);
if (sourceZipFile == null) {
sourceZipFile = baseZipFile;
}
sourceZipFile.unzipToFile(entry, target);
} else {
InputStream in = openResolvedResourceStream(resolvedResource);
UpdateFileUtils.copyInputStreamToFile(in, target);
}
lastTarget = target;
} catch (IOException e) {
if (UpdateContext.DEBUG) {
Log.w(
UpdateContext.TAG,
"Failed to copy resource "
+ actualSourcePath
+ " to "
+ target
+ ": "
+ e.getMessage()
);
}
}
}
remainingFiles.remove(fromPath);
}
if (!remainingFiles.isEmpty() && UpdateContext.DEBUG) {
Log.w(
UpdateContext.TAG,
"Skipped " + remainingFiles.size() + " missing bundled resources"
);
}
} finally {
closeZipFiles(zipFileMap);
}
}
private String normalizeResPath(String path) {
String result = path;
if (result.startsWith(AAB_BASE_PREFIX)) {
result = result.substring(AAB_BASE_PREFIX.length());
}
return VERSION_QUALIFIER_PATTERN.matcher(result).replaceAll("");
}
private String extractResourceType(String directoryName) {
int qualifierIndex = directoryName.indexOf('-');
if (qualifierIndex == -1) {
return directoryName;
}
return directoryName.substring(0, qualifierIndex);
}
private String extractResourceName(String fileName) {
if (fileName.endsWith(".9.png")) {
return fileName.substring(0, fileName.length() - ".9.png".length());
}
int extensionIndex = fileName.lastIndexOf('.');
if (extensionIndex == -1) {
return fileName;
}
return fileName.substring(0, extensionIndex);
}
private Integer parseDensityQualifier(String directoryName) {
String[] qualifiers = directoryName.split("-");
for (String qualifier : qualifiers) {
if ("ldpi".equals(qualifier)) {
return DisplayMetrics.DENSITY_LOW;
}
if ("mdpi".equals(qualifier)) {
return DisplayMetrics.DENSITY_MEDIUM;
}
if ("hdpi".equals(qualifier)) {
return DisplayMetrics.DENSITY_HIGH;
}
if ("xhdpi".equals(qualifier)) {
return DisplayMetrics.DENSITY_XHIGH;
}
if ("xxhdpi".equals(qualifier)) {
return DisplayMetrics.DENSITY_XXHIGH;
}
if ("xxxhdpi".equals(qualifier)) {
return DisplayMetrics.DENSITY_XXXHIGH;
}
if ("tvdpi".equals(qualifier)) {
return DisplayMetrics.DENSITY_TV;
}
}
return null;
}
private ResolvedResourceSource resolveBundledResource(String resourcePath) {
String normalizedPath = normalizeResPath(resourcePath);
if (normalizedPath.startsWith("res/")) {
normalizedPath = normalizedPath.substring("res/".length());
}
int slash = normalizedPath.indexOf('/');
if (slash == -1 || slash == normalizedPath.length() - 1) {
return null;
}
String directoryName = normalizedPath.substring(0, slash);
String fileName = normalizedPath.substring(slash + 1);
String resourceType = extractResourceType(directoryName);
String resourceName = extractResourceName(fileName);
if (resourceType == null || resourceType.isEmpty() || resourceName.isEmpty()) {
return null;
}
Resources resources = context.getResources();
int resourceId = resources.getIdentifier(resourceName, resourceType, context.getPackageName());
if (resourceId == 0) {
return null;
}
TypedValue typedValue = new TypedValue();
try {
Integer density = parseDensityQualifier(directoryName);
if (density != null) {
resources.getValueForDensity(resourceId, density, typedValue, true);
} else {
resources.getValue(resourceId, typedValue, true);
}
} catch (Resources.NotFoundException e) {
return null;
}
if (typedValue.string == null) {
return null;
}
String assetPath = typedValue.string.toString();
if (assetPath.startsWith("/")) {
assetPath = assetPath.substring(1);
}
return new ResolvedResourceSource(resourceId, assetPath, typedValue);
}
private InputStream openResolvedResourceStream(ResolvedResourceSource source) throws IOException {
try {
// Use the density-resolved TypedValue so we open the exact variant
// that was requested, instead of openRawResource(id) which would
// fall back to the device's current configuration density.
return context.getResources().openRawResource(source.resourceId, source.typedValue);
} catch (Resources.NotFoundException e) {
throw new IOException("Unable to open resolved resource: " + source.assetPath, e);
}
}
private ArrayList<String> collectApkPaths() {
ArrayList<String> apkPaths = new ArrayList<String>();
apkPaths.add(context.getPackageResourcePath());
try {
ApplicationInfo appInfo =
context.getPackageManager().getApplicationInfo(context.getPackageName(), 0);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && appInfo.splitSourceDirs != null) {
for (String splitPath : appInfo.splitSourceDirs) {
apkPaths.add(splitPath);
}
}
} catch (PackageManager.NameNotFoundException e) {
if (UpdateContext.DEBUG) {
Log.w(UpdateContext.TAG, "Failed to get application info: " + e.getMessage());
}
}
return apkPaths;
}
private void closeZipFiles(HashMap<String, SafeZipFile> zipFileMap) {
for (SafeZipFile zipFile : zipFileMap.values()) {
try {
zipFile.close();
} catch (IOException e) {
if (UpdateContext.DEBUG) {
Log.w(UpdateContext.TAG, "Failed to close zip file", e);
}
}
}
}
}