use of com.android.tools.build.bundletool.io.TempDirectory in project bundletool by google.
the class ConnectedDeviceModeTransparencyChecker method checkTransparency.
public static TransparencyCheckResult checkTransparency(CheckTransparencyCommand command) {
command.getAdbServer().get().init(command.getAdbPath().get());
AdbRunner adbRunner = new AdbRunner(command.getAdbServer().get());
Device adbDevice = getDevice(command.getAdbServer().get(), command.getDeviceId());
// Execute a shell command to retrieve paths to all APKs for the given package name.
AdbShellCommandTask adbShellCommandTask = new AdbShellCommandTask(adbDevice, "pm path " + command.getPackageName().get());
ImmutableList<String> pathsToApksOnDevice = adbShellCommandTask.execute().stream().filter(path -> path.startsWith(APK_PATH_ON_DEVICE_PREFIX)).map(path -> path.substring(APK_PATH_ON_DEVICE_PREFIX.length())).collect(toImmutableList());
if (pathsToApksOnDevice.isEmpty()) {
throw InvalidCommandException.builder().withInternalMessage("No files found for package " + command.getPackageName().get()).build();
}
// Pull APKs to a temporary directory and verify code transparency.
try (TempDirectory tempDir = new TempDirectory("connected-device-transparency-check")) {
Path apksExtractedSubDirectory = tempDir.getPath().resolve("extracted");
Files.createDirectory(apksExtractedSubDirectory);
ImmutableList<FilePullParams> pullParams = createPullParams(pathsToApksOnDevice, apksExtractedSubDirectory);
if (command.getDeviceId().isPresent()) {
adbRunner.run(device -> device.pull(pullParams), command.getDeviceId().get());
} else {
adbRunner.run(device -> device.pull(pullParams));
}
return ApkTransparencyCheckUtils.checkTransparency(pullParams.stream().map(FilePullParams::getDestinationPath).collect(toImmutableList()));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
use of com.android.tools.build.bundletool.io.TempDirectory in project bundletool by google.
the class ApkModeTransparencyChecker method extractAllApksFromZip.
/**
* Returns list of paths to all .apk files extracted from a .zip file.
*/
private static ImmutableList<Path> extractAllApksFromZip(Path zipOfApksPath, TempDirectory tempDirectory) throws IOException {
ImmutableList.Builder<Path> allExtractedApkPaths = ImmutableList.builder();
Path zipExtractedSubDirectory = tempDirectory.getPath().resolve("extracted");
Files.createDirectory(zipExtractedSubDirectory);
try (ZipFile zipOfApks = ZipUtils.openZipFile(zipOfApksPath)) {
ImmutableList<ZipEntry> listOfApksToExtract = zipOfApks.stream().filter(zipEntry -> !zipEntry.isDirectory() && zipEntry.getName().toLowerCase(Locale.ROOT).endsWith(".apk")).collect(toImmutableList());
for (ZipEntry apkToExtract : listOfApksToExtract) {
Path extractedApkPath = zipExtractedSubDirectory.resolve(ZipPath.create(apkToExtract.getName()).toString());
Files.createDirectories(extractedApkPath.getParent());
try (InputStream inputStream = zipOfApks.getInputStream(apkToExtract);
OutputStream outputApk = Files.newOutputStream(extractedApkPath)) {
ByteStreams.copy(inputStream, outputApk);
allExtractedApkPaths.add(extractedApkPath);
}
}
}
return allExtractedApkPaths.build();
}
use of com.android.tools.build.bundletool.io.TempDirectory in project bundletool by google.
the class AppBundleRecompressor method recompressAppBundle.
public void recompressAppBundle(File inputFile, File outputFile) {
try (ZipReader zipReader = ZipReader.createFromFile(inputFile.toPath());
ZipArchive newBundle = new ZipArchive(outputFile);
TempDirectory tempDirectory = new TempDirectory(getClass().getSimpleName())) {
ZipEntrySourceFactory sourceFactory = new ZipEntrySourceFactory(zipReader, tempDirectory);
List<ListenableFuture<ZipEntrySource>> sources = new ArrayList<>();
BundleConfig bundleConfig = extractBundleConfig(zipReader);
ImmutableSet<String> uncompressedAssetsModules = extractModulesWithUncompressedAssets(zipReader, bundleConfig);
CompressionManager compressionManager = new CompressionManager(bundleConfig, uncompressedAssetsModules);
for (Entry entry : zipReader.getEntries().values()) {
CompressionLevel compressionLevel = compressionManager.getCompressionLevel(entry);
// parallelization there either.
if (compressionLevel.equals(SAME_AS_SOURCE) || compressionLevel.equals(NO_COMPRESSION) || entry.getUncompressedSize() < LARGE_ENTRY_SIZE_THRESHOLD_BYTES) {
sources.add(immediateFuture(sourceFactory.create(entry, compressionLevel)));
} else {
sources.add(executor.submit(() -> sourceFactory.create(entry, compressionLevel)));
}
}
// as they're ready.
for (ListenableFuture<ZipEntrySource> sourceFuture : Futures.inCompletionOrder(sources)) {
ZipEntrySource source = Futures.getUnchecked(sourceFuture);
if (source.getCompressionLevel().isCompressed() && source.getCompressedSize() >= source.getUncompressedSize()) {
// No benefit in compressing, leave the file uncompressed.
newBundle.add(sourceFactory.create(source.getEntry(), NO_COMPRESSION));
} else {
newBundle.add(source);
}
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
use of com.android.tools.build.bundletool.io.TempDirectory in project bundletool by google.
the class InstallMultiApksCommand method extractApksFromZip.
/**
* Extract the .apks files from a zip file containing multiple .apks files.
*/
private static ImmutableList<Path> extractApksFromZip(Path zipPath, TempDirectory tempDirectory) throws IOException {
ImmutableList.Builder<Path> extractedApks = ImmutableList.builder();
Path zipExtractedSubDirectory = tempDirectory.getPath().resolve("extracted");
Files.createDirectory(zipExtractedSubDirectory);
try (ZipFile apksArchiveContainer = new ZipFile(zipPath.toFile())) {
ImmutableList<ZipEntry> apksToExtractList = apksArchiveContainer.stream().filter(zipEntry -> !zipEntry.isDirectory() && zipEntry.getName().toLowerCase(Locale.ROOT).endsWith(".apks")).collect(toImmutableList());
for (ZipEntry apksToExtract : apksToExtractList) {
Path extractedApksPath = zipExtractedSubDirectory.resolve(ZipPath.create(apksToExtract.getName()).toString());
Files.createDirectories(extractedApksPath.getParent());
try (InputStream inputStream = apksArchiveContainer.getInputStream(apksToExtract);
OutputStream outputApks = Files.newOutputStream(extractedApksPath)) {
ByteStreams.copy(inputStream, outputApks);
extractedApks.add(extractedApksPath);
}
}
}
return extractedApks.build();
}
use of com.android.tools.build.bundletool.io.TempDirectory in project bundletool by google.
the class InstallMultiApksCommand method execute.
public void execute() throws TimeoutException, IOException {
validateInput();
AdbServer adbServer = getAdbServer();
adbServer.init(getAdbPath());
try (TempDirectory tempDirectory = new TempDirectory()) {
DeviceAnalyzer deviceAnalyzer = new DeviceAnalyzer(adbServer);
DeviceSpec deviceSpec = deviceAnalyzer.getDeviceSpec(getDeviceId());
Device device = deviceAnalyzer.getAndValidateDevice(getDeviceId());
if (getTimeout().isPresent() && !device.getVersion().isGreaterOrEqualThan(Versions.ANDROID_S_API_VERSION)) {
throw InvalidCommandException.builder().withInternalMessage("'%s' flag is supported for Android 12+ devices.", TIMEOUT_MILLIS_FLAG.getName()).build();
}
Path aapt2Dir = tempDirectory.getPath().resolve("aapt2");
Files.createDirectory(aapt2Dir);
Supplier<Aapt2Command> aapt2CommandSupplier = Suppliers.memoize(() -> getOrExtractAapt2Command(aapt2Dir));
ImmutableMap<String, InstalledPackageInfo> existingPackages = getPackagesInstalledOnDevice(device);
ImmutableList<PackagePathVersion> installableApksFilesWithBadgingInfo = getActualApksPaths(tempDirectory).stream().flatMap(apksArchivePath -> stream(apksWithPackageName(apksArchivePath, deviceSpec, aapt2CommandSupplier))).filter(apks -> shouldInstall(apks, existingPackages)).collect(toImmutableList());
ImmutableList<PackagePathVersion> apkFilesToInstall = uniqueApksByPackageName(installableApksFilesWithBadgingInfo).stream().flatMap(apks -> extractApkListFromApks(deviceSpec, apks, Optional.ofNullable(existingPackages.get(apks.getPackageName())), tempDirectory).stream()).collect(toImmutableList());
ImmutableListMultimap<String, String> apkToInstallByPackage = apkFilesToInstall.stream().collect(toImmutableListMultimap(PackagePathVersion::getPackageName, packagePathVersion -> packagePathVersion.getPath().toAbsolutePath().toString()));
if (apkFilesToInstall.isEmpty()) {
logger.warning("No packages found to install! Exiting...");
return;
}
AdbCommand adbCommand = getOrCreateAdbCommand();
ImmutableList<String> commandResults = adbCommand.installMultiPackage(apkToInstallByPackage, getStaged(), getEnableRollback(), getTimeout(), getDeviceId());
logger.info(String.format("Output:\n%s", String.join("\n", commandResults)));
logger.info("Please reboot device to complete installation.");
}
}
Aggregations