revanced-manager/lib/services/patcher_api.dart

325 lines
9.6 KiB
Dart
Raw Normal View History

2022-08-06 15:04:18 +02:00
import 'dart:io';
import 'package:collection/collection.dart';
import 'package:device_apps/device_apps.dart';
import 'package:flutter/foundation.dart';
2022-08-06 15:04:18 +02:00
import 'package:flutter/services.dart';
2023-10-28 16:19:07 +02:00
import 'package:flutter_file_dialog/flutter_file_dialog.dart';
2022-08-09 01:01:06 +02:00
import 'package:injectable/injectable.dart';
import 'package:install_plugin/install_plugin.dart';
import 'package:path_provider/path_provider.dart';
2022-08-25 01:51:47 +02:00
import 'package:revanced_manager/app/app.locator.dart';
2022-08-06 23:35:35 +02:00
import 'package:revanced_manager/models/patch.dart';
2022-08-14 20:40:34 +02:00
import 'package:revanced_manager/models/patched_application.dart';
2022-08-18 16:33:33 +02:00
import 'package:revanced_manager/services/manager_api.dart';
2022-08-14 20:40:34 +02:00
import 'package:revanced_manager/services/root_api.dart';
2023-10-28 16:19:07 +02:00
import 'package:share_plus/share_plus.dart';
2022-08-06 15:04:18 +02:00
2022-08-09 01:01:06 +02:00
@lazySingleton
class PatcherAPI {
2022-09-12 14:53:34 +02:00
static const patcherChannel =
2023-10-12 02:00:39 +02:00
MethodChannel('app.revanced.manager.flutter/patcher');
2022-08-25 01:51:47 +02:00
final ManagerAPI _managerAPI = locator<ManagerAPI>();
2022-08-18 16:33:33 +02:00
final RootAPI _rootAPI = RootAPI();
late Directory _dataDir;
late Directory _tmpDir;
late File _keyStoreFile;
List<Patch> _patches = [];
List<Patch> _universalPatches = [];
List<String> _compatiblePackages = [];
Map filteredPatches = <String, List<Patch>>{};
File? outFile;
2022-08-09 01:01:06 +02:00
Future<void> initialize() async {
2023-10-04 21:16:56 +02:00
await loadPatches();
await _managerAPI.downloadIntegrations();
final Directory appCache = await getTemporaryDirectory();
_dataDir = await getExternalStorageDirectory() ?? appCache;
_tmpDir = Directory('${appCache.path}/patcher');
_keyStoreFile = File('${_dataDir.path}/revanced-manager.keystore');
cleanPatcher();
}
void cleanPatcher() {
if (_tmpDir.existsSync()) {
_tmpDir.deleteSync(recursive: true);
}
2022-08-19 20:13:43 +02:00
}
List<String> getCompatiblePackages() {
final List<String> compatiblePackages = [];
for (final Patch patch in _patches) {
for (final Package package in patch.compatiblePackages) {
if (!compatiblePackages.contains(package.name)) {
compatiblePackages.add(package.name);
}
}
}
return compatiblePackages;
}
List<Patch> getUniversalPatches() {
2023-10-03 18:54:51 +02:00
return _patches.where((patch) => patch.compatiblePackages.isEmpty).toList();
}
2023-10-04 21:16:56 +02:00
Future<void> loadPatches() async {
try {
if (_patches.isEmpty) {
_patches = await _managerAPI.getPatches();
2022-08-06 15:04:18 +02:00
}
} on Exception catch (e) {
if (kDebugMode) {
print(e);
}
_patches = List.empty();
2022-08-06 15:04:18 +02:00
}
_compatiblePackages = getCompatiblePackages();
_universalPatches = getUniversalPatches();
2022-08-06 15:04:18 +02:00
}
Future<List<ApplicationWithIcon>> getFilteredInstalledApps(
2023-10-12 02:00:39 +02:00
bool showUniversalPatches,) async {
final List<ApplicationWithIcon> filteredApps = [];
final bool allAppsIncluded =
2023-10-03 18:54:51 +02:00
_universalPatches.isNotEmpty && showUniversalPatches;
if (allAppsIncluded) {
final appList = await DeviceApps.getInstalledApplications(
includeAppIcons: true,
onlyAppsWithLaunchIntent: true,
);
2023-10-03 18:54:51 +02:00
for (final app in appList) {
filteredApps.add(app as ApplicationWithIcon);
}
}
for (final packageName in _compatiblePackages) {
try {
if (!filteredApps.any((app) => app.packageName == packageName)) {
final ApplicationWithIcon? app = await DeviceApps.getApp(
packageName,
true,
) as ApplicationWithIcon?;
if (app != null) {
filteredApps.add(app);
}
}
} on Exception catch (e) {
if (kDebugMode) {
print(e);
2022-08-06 15:04:18 +02:00
}
2022-08-17 19:44:27 +02:00
}
}
return filteredApps;
2022-08-17 19:44:27 +02:00
}
List<Patch> getFilteredPatches(String packageName) {
if (!_compatiblePackages.contains(packageName)) {
return _universalPatches;
}
final List<Patch> patches = _patches
.where(
(patch) =>
2023-10-12 02:00:39 +02:00
patch.compatiblePackages.isEmpty ||
!patch.name.contains('settings') &&
patch.compatiblePackages
.any((pack) => pack.name == packageName),
)
.toList();
if (!_managerAPI.areUniversalPatchesEnabled()) {
filteredPatches[packageName] = patches
.where((patch) => patch.compatiblePackages.isNotEmpty)
.toList();
} else {
filteredPatches[packageName] = patches;
}
return filteredPatches[packageName];
}
2023-10-12 02:00:39 +02:00
Future<List<Patch>> getAppliedPatches(List<String> appliedPatches,) async {
return _patches
.where((patch) => appliedPatches.contains(patch.name))
.toList();
}
2023-10-12 02:00:39 +02:00
Future<void> runPatcher(String packageName,
String apkFilePath,
List<Patch> selectedPatches,) async {
2023-04-18 21:51:08 +02:00
final File? integrationsFile = await _managerAPI.downloadIntegrations();
2023-10-12 02:00:39 +02:00
final Map<String, Map<String, dynamic>> options = {};
for (final patch in selectedPatches) {
if (patch.options.isNotEmpty) {
final Map<String, dynamic> patchOptions = {};
for (final option in patch.options) {
final patchOption = _managerAPI.getPatchOption(packageName, patch.name, option.key);
if (patchOption != null) {
patchOptions[patchOption.key] = patchOption.value;
}
}
options[patch.name] = patchOptions;
}
}
2023-10-03 18:54:51 +02:00
if (integrationsFile != null) {
_dataDir.createSync();
_tmpDir.createSync();
final Directory workDir = _tmpDir.createTempSync('tmp-');
final File inputFile = File('${workDir.path}/base.apk');
final File patchedFile = File('${workDir.path}/patched.apk');
outFile = File('${workDir.path}/out.apk');
final Directory cacheDir = Directory('${workDir.path}/cache');
cacheDir.createSync();
final String originalFilePath = apkFilePath;
2023-10-12 02:00:39 +02:00
2022-10-14 20:05:33 +02:00
try {
await patcherChannel.invokeMethod(
'runPatcher',
{
'originalFilePath': originalFilePath,
2022-10-14 20:05:33 +02:00
'inputFilePath': inputFile.path,
'patchedFilePath': patchedFile.path,
'outFilePath': outFile!.path,
2023-10-03 18:54:51 +02:00
'integrationsPath': integrationsFile.path,
2023-04-18 21:51:08 +02:00
'selectedPatches': selectedPatches.map((p) => p.name).toList(),
2023-10-12 02:00:39 +02:00
'options': options,
2022-10-14 20:05:33 +02:00
'cacheDirPath': cacheDir.path,
'keyStoreFilePath': _keyStoreFile.path,
'keystorePassword': _managerAPI.getKeystorePassword(),
2022-10-14 20:05:33 +02:00
},
);
} on Exception catch (e) {
if (kDebugMode) {
print(e);
}
2022-10-14 20:05:33 +02:00
}
}
2023-10-12 02:00:39 +02:00
}
Future<void> stopPatcher() async {
try {
await patcherChannel.invokeMethod('stopPatcher');
} on Exception catch (e) {
if (kDebugMode) {
print(e);
}
}
2023-10-12 02:00:39 +02:00
}
2023-10-12 02:00:39 +02:00
Future<bool> installPatchedFile(PatchedApplication patchedApp) async {
if (outFile != null) {
try {
2023-10-12 02:00:39 +02:00
if (patchedApp.isRooted) {
final bool hasRootPermissions = await _rootAPI.hasRootPermissions();
if (hasRootPermissions) {
return _rootAPI.installApp(
patchedApp.packageName,
patchedApp.apkFilePath,
outFile!.path,
);
}
} else {
final install = await InstallPlugin.installApk(outFile!.path);
return install['isSuccess'];
}
} on Exception catch (e) {
if (kDebugMode) {
print(e);
}
2023-10-12 02:00:39 +02:00
return false;
}
}
2023-10-12 02:00:39 +02:00
return false;
}
2023-10-12 02:00:39 +02:00
void exportPatchedFile(String appName, String version) {
try {
if (outFile != null) {
2023-10-12 02:00:39 +02:00
final String newName = _getFileName(appName, version);
2023-10-28 16:19:07 +02:00
FlutterFileDialog.saveFile(
params: SaveFileDialogParams(
2023-10-12 02:00:39 +02:00
sourceFilePath: outFile!.path,
2023-10-28 16:19:07 +02:00
fileName: newName,
2023-10-12 02:00:39 +02:00
),
);
}
2023-10-12 02:00:39 +02:00
} on Exception catch (e) {
if (kDebugMode) {
print(e);
}
}
2023-10-12 02:00:39 +02:00
}
2023-10-12 02:00:39 +02:00
void sharePatchedFile(String appName, String version) {
try {
if (outFile != null) {
final String newName = _getFileName(appName, version);
final int lastSeparator = outFile!.path.lastIndexOf('/');
final String newPath =
outFile!.path.substring(0, lastSeparator + 1) + newName;
final File shareFile = outFile!.copySync(newPath);
2023-10-28 16:19:07 +02:00
Share.shareXFiles([XFile(shareFile.path)]);
2023-10-12 02:00:39 +02:00
}
} on Exception catch (e) {
if (kDebugMode) {
print(e);
}
2022-08-06 15:04:18 +02:00
}
2023-10-12 02:00:39 +02:00
}
2023-10-12 02:00:39 +02:00
String _getFileName(String appName, String version) {
final String prefix = appName.toLowerCase().replaceAll(' ', '-');
final String newName = '$prefix-revanced_v$version.apk';
return newName;
}
2023-10-12 02:00:39 +02:00
Future<void> exportPatcherLog(String logs) async {
final Directory appCache = await getTemporaryDirectory();
final Directory logDir = Directory('${appCache.path}/logs');
logDir.createSync();
final String dateTime = DateTime.now()
.toIso8601String()
.replaceAll('-', '')
.replaceAll(':', '')
.replaceAll('T', '')
.replaceAll('.', '');
final String fileName = 'revanced-manager_patcher_$dateTime.txt';
final File log = File('${logDir.path}/$fileName');
log.writeAsStringSync(logs);
2023-10-28 16:19:07 +02:00
FlutterFileDialog.saveFile(
params: SaveFileDialogParams(
2023-10-12 02:00:39 +02:00
sourceFilePath: log.path,
2023-10-28 16:19:07 +02:00
fileName: fileName,
2023-10-12 02:00:39 +02:00
),
);
}
2023-10-12 02:00:39 +02:00
String getSuggestedVersion(String packageName) {
final Map<String, int> versions = {};
for (final Patch patch in _patches) {
final Package? package = patch.compatiblePackages.firstWhereOrNull(
(pack) => pack.name == packageName,
);
if (package != null) {
for (final String version in package.versions) {
versions.update(
version,
(value) => versions[version]! + 1,
ifAbsent: () => 1,
);
}
}
}
2023-10-12 02:00:39 +02:00
if (versions.isNotEmpty) {
final entries = versions.entries.toList()
..sort((a, b) => a.value.compareTo(b.value));
versions
..clear()
..addEntries(entries);
versions.removeWhere((key, value) => value != versions.values.last);
return (versions.keys.toList()
..sort()).last;
}
return '';
}}