feat: use provided patches.json to load patches

This commit is contained in:
Alberto Ponces 2022-08-29 17:44:45 +01:00
parent 080ceae784
commit 03b45e0db0
11 changed files with 210 additions and 338 deletions

View file

@ -10,13 +10,7 @@ import app.revanced.manager.utils.zip.ZipFile
import app.revanced.manager.utils.zip.structures.ZipEntry
import app.revanced.patcher.Patcher
import app.revanced.patcher.PatcherOptions
import app.revanced.patcher.data.Data
import app.revanced.patcher.extensions.PatchExtensions.compatiblePackages
import app.revanced.patcher.extensions.PatchExtensions.description
import app.revanced.patcher.extensions.PatchExtensions.include
import app.revanced.patcher.extensions.PatchExtensions.patchName
import app.revanced.patcher.extensions.PatchExtensions.version
import app.revanced.patcher.patch.Patch
import app.revanced.patcher.util.patch.impl.DexPatchBundle
import dalvik.system.DexClassLoader
import io.flutter.embedding.android.FlutterActivity
@ -30,7 +24,6 @@ import java.nio.file.StandardCopyOption
class MainActivity : FlutterActivity() {
private val PATCHER_CHANNEL = "app.revanced.manager/patcher"
private val INSTALLER_CHANNEL = "app.revanced.manager/installer"
private var patches = mutableListOf<Class<out Patch<Data>>>()
private val handler = Handler(Looper.getMainLooper())
private lateinit var installerChannel: MethodChannel
@ -41,27 +34,8 @@ class MainActivity : FlutterActivity() {
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, INSTALLER_CHANNEL)
mainChannel.setMethodCallHandler { call, result ->
when (call.method) {
"loadPatches" -> {
val jarPatchBundlePath = call.argument<String>("jarPatchBundlePath")
val cacheDirPath = call.argument<String>("cacheDirPath")
if (jarPatchBundlePath != null && cacheDirPath != null) {
loadPatches(result, jarPatchBundlePath, cacheDirPath)
} else {
result.notImplemented()
}
}
"getCompatiblePackages" -> getCompatiblePackages(result)
"getFilteredPatches" -> {
val targetPackage = call.argument<String>("targetPackage")
val targetVersion = call.argument<String>("targetVersion")
val ignoreVersion = call.argument<Boolean>("ignoreVersion")
if (targetPackage != null && targetVersion != null && ignoreVersion != null) {
getFilteredPatches(result, targetPackage, targetVersion, ignoreVersion)
} else {
result.notImplemented()
}
}
"runPatcher" -> {
val patchBundleFilePath = call.argument<String>("patchBundleFilePath")
val originalFilePath = call.argument<String>("originalFilePath")
val inputFilePath = call.argument<String>("inputFilePath")
val patchedFilePath = call.argument<String>("patchedFilePath")
@ -71,7 +45,8 @@ class MainActivity : FlutterActivity() {
val cacheDirPath = call.argument<String>("cacheDirPath")
val mergeIntegrations = call.argument<Boolean>("mergeIntegrations")
val resourcePatching = call.argument<Boolean>("resourcePatching")
if (originalFilePath != null &&
if (patchBundleFilePath != null &&
originalFilePath != null &&
inputFilePath != null &&
patchedFilePath != null &&
outFilePath != null &&
@ -83,6 +58,7 @@ class MainActivity : FlutterActivity() {
) {
runPatcher(
result,
patchBundleFilePath,
originalFilePath,
inputFilePath,
patchedFilePath,
@ -102,79 +78,9 @@ class MainActivity : FlutterActivity() {
}
}
fun loadPatches(
result: MethodChannel.Result,
jarPatchBundlePath: String,
cacheDirPath: String
) {
Thread(
Runnable {
patches.addAll(
DexPatchBundle(
jarPatchBundlePath,
DexClassLoader(
jarPatchBundlePath,
cacheDirPath,
null,
javaClass.classLoader
)
)
.loadPatches()
)
handler.post { result.success(null) }
}
)
.start()
}
fun getCompatiblePackages(result: MethodChannel.Result) {
Thread(
Runnable {
val filteredPackages = mutableListOf<String>()
patches.forEach patch@{ patch ->
patch.compatiblePackages?.forEach { pkg ->
filteredPackages.add(pkg.name)
}
}
handler.post { result.success(filteredPackages.distinct()) }
}
)
.start()
}
fun getFilteredPatches(
result: MethodChannel.Result,
targetPackage: String,
targetVersion: String,
ignoreVersion: Boolean
) {
Thread(
Runnable {
val filteredPatches = mutableListOf<Map<String, Any?>>()
patches.forEach patch@{ patch ->
patch.compatiblePackages?.forEach { pkg ->
if (pkg.name == targetPackage &&
(ignoreVersion ||
pkg.versions.isNotEmpty() ||
pkg.versions.contains(targetVersion))
) {
var p = mutableMapOf<String, Any?>()
p.put("name", patch.patchName)
p.put("version", patch.version)
p.put("description", patch.description)
p.put("include", patch.include)
filteredPatches.add(p)
}
}
}
handler.post { result.success(filteredPatches) }
}
)
.start()
}
fun runPatcher(
result: MethodChannel.Result,
patchBundleFilePath: String,
originalFilePath: String,
inputFilePath: String,
patchedFilePath: String,
@ -190,8 +96,19 @@ class MainActivity : FlutterActivity() {
val patchedFile = File(patchedFilePath)
val outFile = File(outFilePath)
val integrations = File(integrationsPath)
val filteredPatches =
patches.filter { patch -> selectedPatches.any { it == patch.patchName } }
val patches =
DexPatchBundle(
patchBundleFilePath,
DexClassLoader(
patchBundleFilePath,
cacheDirPath,
null,
javaClass.classLoader
)
)
.loadPatches()
.filter { patch -> selectedPatches.any { it == patch.patchName } }
Thread(
Runnable {
@ -234,12 +151,16 @@ class MainActivity : FlutterActivity() {
app.revanced.patcher.logging.Logger {
override fun error(msg: String) {
handler.post {
installerChannel.invokeMethod(
installerChannel
.invokeMethod(
"update",
mapOf(
"progress" to 0.2,
"header" to "",
"log" to msg
"progress" to
0.2,
"header" to
"",
"log" to
msg
)
)
}
@ -247,12 +168,16 @@ class MainActivity : FlutterActivity() {
override fun warn(msg: String) {
handler.post {
installerChannel.invokeMethod(
installerChannel
.invokeMethod(
"update",
mapOf(
"progress" to 0.2,
"header" to "",
"log" to msg
"progress" to
0.2,
"header" to
"",
"log" to
msg
)
)
}
@ -260,12 +185,16 @@ class MainActivity : FlutterActivity() {
override fun info(msg: String) {
handler.post {
installerChannel.invokeMethod(
installerChannel
.invokeMethod(
"update",
mapOf(
"progress" to 0.2,
"header" to "",
"log" to msg
"progress" to
0.2,
"header" to
"",
"log" to
msg
)
)
}
@ -273,12 +202,16 @@ class MainActivity : FlutterActivity() {
override fun trace(msg: String) {
handler.post {
installerChannel.invokeMethod(
installerChannel
.invokeMethod(
"update",
mapOf(
"progress" to 0.2,
"header" to "",
"log" to msg
"progress" to
0.2,
"header" to
"",
"log" to
msg
)
)
}
@ -290,11 +223,7 @@ class MainActivity : FlutterActivity() {
handler.post {
installerChannel.invokeMethod(
"update",
mapOf(
"progress" to 0.3,
"header" to "",
"log" to ""
)
mapOf("progress" to 0.3, "header" to "", "log" to "")
)
}
if (mergeIntegrations) {
@ -321,7 +250,7 @@ class MainActivity : FlutterActivity() {
)
)
}
patcher.addPatches(filteredPatches)
patcher.addPatches(patches)
patcher.applyPatches().forEach { (patch, res) ->
if (res.isSuccess) {
val msg = "[success] $patch"
@ -341,11 +270,7 @@ class MainActivity : FlutterActivity() {
handler.post {
installerChannel.invokeMethod(
"update",
mapOf(
"progress" to 0.5,
"header" to "",
"log" to msg
)
mapOf("progress" to 0.5, "header" to "", "log" to msg)
)
}
}

View file

@ -6,6 +6,7 @@ import 'package:revanced_manager/app/app.locator.dart';
import 'package:revanced_manager/app/app.router.dart';
import 'package:revanced_manager/main_viewmodel.dart';
import 'package:revanced_manager/services/manager_api.dart';
import 'package:revanced_manager/services/patcher_api.dart';
import 'package:revanced_manager/theme.dart';
import 'package:revanced_manager/ui/views/home/home_view.dart';
import 'package:revanced_manager/ui/views/patcher/patcher_view.dart';
@ -69,6 +70,7 @@ class MyApp extends StatelessWidget {
Future<Widget> _init() async {
await locator<ManagerAPI>().initialize();
await locator<PatcherAPI>().initialize();
bool? isRooted = locator<ManagerAPI>().isRooted();
if (isRooted != null) {
return const Navigation();

View file

@ -1,15 +1,47 @@
import 'package:json_annotation/json_annotation.dart';
import 'package:revanced_manager/utils/string.dart';
part 'patch.g.dart';
@JsonSerializable()
class Patch {
final String name;
final String simpleName;
final String version;
final String description;
final bool include;
final String version;
final bool excluded;
final List<String> dependencies;
final List<Package> compatiblePackages;
Patch({
required this.name,
required this.simpleName,
required this.version,
required this.description,
required this.include,
required this.version,
required this.excluded,
required this.dependencies,
required this.compatiblePackages,
});
factory Patch.fromJson(Map<String, dynamic> json) => _$PatchFromJson(json);
Map<String, dynamic> toJson() => _$PatchToJson(this);
String getSimpleName() {
return name.replaceAll('-', ' ').split('-').join(' ').toTitleCase();
}
}
@JsonSerializable()
class Package {
final String name;
final List<String> versions;
Package({
required this.name,
required this.versions,
});
factory Package.fromJson(Map<String, dynamic> json) =>
_$PackageFromJson(json);
Map toJson() => _$PackageToJson(this);
}

View file

@ -39,7 +39,7 @@ class PatchedApplication {
factory PatchedApplication.fromJson(Map<String, dynamic> json) =>
_$PatchedApplicationFromJson(json);
Map toJson() => _$PatchedApplicationToJson(this);
Map<String, dynamic> toJson() => _$PatchedApplicationToJson(this);
static Uint8List decodeBase64(String icon) => base64.decode(icon);

View file

@ -6,7 +6,7 @@ import 'package:timeago/timeago.dart';
class GithubAPI {
final GitHub _github = GitHub();
Future<String?> latestReleaseVersion(String org, repoName) async {
Future<String?> latestReleaseVersion(String org, String repoName) async {
try {
var latestRelease = await _github.repositories.getLatestRelease(
RepositorySlug(org, repoName),
@ -20,7 +20,7 @@ class GithubAPI {
Future<File?> latestReleaseFile(
String extension,
String org,
repoName,
String repoName,
) async {
try {
var latestRelease = await _github.repositories.getLatestRelease(
@ -42,7 +42,7 @@ class GithubAPI {
return null;
}
Future<String> latestCommitTime(String org, repoName) async {
Future<String> latestCommitTime(String org, String repoName) async {
try {
var repo = await _github.repositories.getRepository(
RepositorySlug(org, repoName),
@ -55,13 +55,13 @@ class GithubAPI {
}
}
Future<List<Contributor>> getContributors(String org, repoName) async {
Future<List<Contributor>> getContributors(String org, String repoName) async {
return await (_github.repositories.listContributors(
RepositorySlug(org, repoName),
)).toList();
}
Future<List<RepositoryCommit>> getCommits(String org, repoName) async {
Future<List<RepositoryCommit>> getCommits(String org, String repoName) async {
return await (_github.repositories.listCommits(
RepositorySlug(org, repoName),
)).toList();

View file

@ -1,3 +1,4 @@
import 'dart:convert';
import 'dart:io';
import 'package:app_installer/app_installer.dart';
import 'package:device_apps/device_apps.dart';
@ -9,7 +10,6 @@ import 'package:revanced_manager/models/patch.dart';
import 'package:revanced_manager/models/patched_application.dart';
import 'package:revanced_manager/services/manager_api.dart';
import 'package:revanced_manager/services/root_api.dart';
import 'package:revanced_manager/utils/string.dart';
import 'package:share_extend/share_extend.dart';
@lazySingleton
@ -19,195 +19,124 @@ class PatcherAPI {
);
final ManagerAPI _managerAPI = locator<ManagerAPI>();
final RootAPI _rootAPI = RootAPI();
List<Patch> _patches = [];
Directory? _tmpDir;
Directory? _workDir;
Directory? _cacheDir;
File? _jarPatchBundleFile;
File? _integrations;
File? _inputFile;
File? _patchedFile;
File? _outFile;
Future<void> initPatcher() async {
Directory appCache = await getTemporaryDirectory();
_tmpDir = Directory('${appCache.path}/patcher');
_tmpDir!.createSync();
_workDir = _tmpDir!.createTempSync('tmp-');
_inputFile = File('${_workDir!.path}/base.apk');
_patchedFile = File('${_workDir!.path}/patched.apk');
_outFile = File('${_workDir!.path}/out.apk');
_cacheDir = Directory('${_workDir!.path}/cache');
_cacheDir!.createSync();
Future<void> initialize() async {
await _loadPatches();
}
Future<bool> loadPatches() async {
if (_tmpDir == null) {
await initPatcher();
}
if (_jarPatchBundleFile == null) {
_jarPatchBundleFile = await _managerAPI.downloadPatches('.jar');
if (_jarPatchBundleFile != null) {
Future<void> _loadPatches() async {
try {
await patcherChannel.invokeMethod<bool>(
'loadPatches',
{
'jarPatchBundlePath': _jarPatchBundleFile!.path,
'cacheDirPath': _cacheDir!.path,
},
);
if (_patches.isEmpty) {
File? patchJsonFile = await _managerAPI.downloadPatches('.json');
if (patchJsonFile != null) {
List<dynamic> list = json.decode(patchJsonFile.readAsStringSync());
_patches = list.map((patch) => Patch.fromJson(patch)).toList();
}
}
} on Exception {
return false;
_patches = List.empty();
}
}
}
return _jarPatchBundleFile != null;
}
Future<List<ApplicationWithIcon>> getFilteredInstalledApps() async {
List<ApplicationWithIcon> filteredPackages = [];
bool isLoaded = await loadPatches();
if (isLoaded) {
List<ApplicationWithIcon> filteredApps = [];
await _loadPatches();
for (Patch patch in _patches) {
for (Package package in patch.compatiblePackages) {
try {
List<String>? patchesPackages = await patcherChannel
.invokeListMethod<String>('getCompatiblePackages');
if (patchesPackages != null) {
for (String package in patchesPackages) {
try {
ApplicationWithIcon? app = await DeviceApps.getApp(package, true)
if (!filteredApps.any((app) => app.packageName == package.name)) {
ApplicationWithIcon? app =
await DeviceApps.getApp(package.name, true)
as ApplicationWithIcon?;
if (app != null) {
filteredPackages.add(app);
filteredApps.add(app);
}
}
} catch (e) {
continue;
}
}
}
} on Exception {
return List.empty();
}
}
return filteredPackages;
return filteredApps;
}
Future<List<Patch>> getFilteredPatches(
PatchedApplication? selectedApp,
) async {
List<Patch> filteredPatches = [];
if (selectedApp != null) {
bool isLoaded = await loadPatches();
if (isLoaded) {
try {
var patches =
await patcherChannel.invokeListMethod<Map<dynamic, dynamic>>(
'getFilteredPatches',
{
'targetPackage': selectedApp.packageName,
'targetVersion': selectedApp.version,
'ignoreVersion': true,
},
);
if (patches != null) {
for (var patch in patches) {
if (!filteredPatches
.any((element) => element.name == patch['name'])) {
filteredPatches.add(
Patch(
name: patch['name'],
simpleName: (patch['name'] as String)
.replaceAll('-', ' ')
.split('-')
.join(' ')
.toTitleCase(),
version: patch['version'] ?? '?.?.?',
description: patch['description'] ?? 'N/A',
include: patch['include'] ?? true,
),
);
}
}
}
} on Exception {
return List.empty();
}
}
}
return filteredPatches;
Future<List<Patch>> getFilteredPatches(String packageName) async {
await _loadPatches();
return _patches
.where((patch) =>
!patch.name.contains('settings') &&
patch.compatiblePackages.any((pack) => pack.name == packageName))
.toList();
}
Future<List<Patch>> getAppliedPatches(
PatchedApplication? selectedApp,
) async {
List<Patch> appliedPatches = [];
if (selectedApp != null) {
bool isLoaded = await loadPatches();
if (isLoaded) {
try {
var patches =
await patcherChannel.invokeListMethod<Map<dynamic, dynamic>>(
'getFilteredPatches',
{
'targetPackage': selectedApp.packageName,
'targetVersion': selectedApp.version,
'ignoreVersion': true,
},
);
if (patches != null) {
for (var patch in patches) {
if (selectedApp.appliedPatches.contains(patch['name'])) {
appliedPatches.add(
Patch(
name: patch['name'],
simpleName: (patch['name'] as String)
.replaceAll('-', ' ')
.split('-')
.join(' ')
.toTitleCase(),
version: patch['version'] ?? '?.?.?',
description: patch['description'] ?? 'N/A',
include: patch['include'] ?? true,
),
);
}
}
}
} on Exception {
return List.empty();
}
}
}
return appliedPatches;
}
Future<void> mergeIntegrations(bool mergeIntegrations) async {
if (mergeIntegrations) {
_integrations = await _managerAPI.downloadIntegrations('.apk');
} else {
_integrations = null;
}
Future<List<Patch>> getAppliedPatches(List<String> appliedPatches) async {
await _loadPatches();
return _patches
.where((patch) => appliedPatches.contains(patch.name))
.toList();
}
Future<void> runPatcher(
String packageName,
String originalFilePath,
List<Patch> selectedPatches,
bool mergeIntegrations,
bool resourcePatching,
) async {
bool mergeIntegrations = selectedPatches.any(
(patch) => patch.dependencies.contains('integrations'),
);
bool resourcePatching = selectedPatches.any(
(patch) => patch.dependencies.any((dep) => dep.contains('resource-')),
);
bool includeSettings = selectedPatches.any(
(patch) => patch.dependencies.contains('settings'),
);
if (includeSettings) {
try {
Patch settingsPatch = _patches.firstWhere(
(patch) =>
patch.name.contains('settings') &&
patch.compatiblePackages.any((pack) => pack.name == packageName),
);
selectedPatches.add(settingsPatch);
} catch (e) {
// ignore
}
}
File? patchBundleFile = await _managerAPI.downloadPatches('.jar');
File? integrationsFile;
if (mergeIntegrations) {
integrationsFile = await _managerAPI.downloadIntegrations('.apk');
}
if (patchBundleFile != null) {
Directory appCache = await getTemporaryDirectory();
_tmpDir = Directory('${appCache.path}/patcher');
_tmpDir!.createSync();
Directory workDir = _tmpDir!.createTempSync('tmp-');
File inputFile = File('${workDir.path}/base.apk');
File patchedFile = File('${workDir.path}/patched.apk');
_outFile = File('${workDir.path}/out.apk');
Directory cacheDir = Directory('${workDir.path}/cache');
cacheDir.createSync();
await patcherChannel.invokeMethod(
'runPatcher',
{
'patchBundleFilePath': patchBundleFile.path,
'originalFilePath': originalFilePath,
'inputFilePath': _inputFile!.path,
'patchedFilePath': _patchedFile!.path,
'inputFilePath': inputFile.path,
'patchedFilePath': patchedFile.path,
'outFilePath': _outFile!.path,
'integrationsPath': _integrations != null ? _integrations!.path : '',
'integrationsPath': mergeIntegrations ? integrationsFile!.path : '',
'selectedPatches': selectedPatches.map((p) => p.name).toList(),
'cacheDirPath': _cacheDir!.path,
'cacheDirPath': cacheDir.path,
'mergeIntegrations': mergeIntegrations,
'resourcePatching': resourcePatching,
},
);
}
}
Future<bool> installPatchedFile(PatchedApplication patchedApp) async {
if (_outFile != null) {

View file

@ -27,7 +27,6 @@ class HomeViewModel extends BaseViewModel {
Future<void> initialize() async {
await _getPatchedApps();
await _patcherAPI.loadPatches();
await flutterLocalNotificationsPlugin.initialize(
const InitializationSettings(
android: AndroidInitializationSettings('ic_notification'),
@ -45,7 +44,7 @@ class HomeViewModel extends BaseViewModel {
void navigateToPatcher(PatchedApplication app) async {
locator<PatcherViewModel>().selectedApp = app;
locator<PatcherViewModel>().selectedPatches =
await _patcherAPI.getAppliedPatches(app);
await _patcherAPI.getAppliedPatches(app.appliedPatches);
locator<PatcherViewModel>().notifyListeners();
locator<MainViewModel>().setIndex(1);
}

View file

@ -108,22 +108,7 @@ class InstallerViewModel extends BaseViewModel {
}
}
update(0.0, '', 'Creating working directory');
bool mergeIntegrations = false;
bool resourcePatching = false;
if (_app!.packageName == 'com.google.android.youtube') {
mergeIntegrations = true;
resourcePatching = true;
} else if (_app!.packageName ==
'com.google.android.apps.youtube.music') {
resourcePatching = true;
}
await _patcherAPI.mergeIntegrations(mergeIntegrations);
await _patcherAPI.runPatcher(
apkFilePath,
_patches,
mergeIntegrations,
resourcePatching,
);
await _patcherAPI.runPatcher(_app!.packageName, apkFilePath, _patches);
} on Exception {
update(1.0, 'Aborting...', 'An error occurred! Aborting');
}

View file

@ -57,7 +57,7 @@ class _PatchesSelectorViewState extends State<PatchesSelectorView> {
.getQueriedPatches(_query)
.map((patch) => PatchItem(
name: patch.name,
simpleName: patch.simpleName,
simpleName: patch.getSimpleName(),
version: patch.version,
description: patch.description,
isSelected: model.isSelected(patch),

View file

@ -12,11 +12,11 @@ class PatchesSelectorViewModel extends BaseViewModel {
Future<void> initialize() async {
patches.addAll(await _patcherAPI.getFilteredPatches(
locator<PatcherViewModel>().selectedApp,
locator<PatcherViewModel>().selectedApp!.packageName,
));
patches.sort((a, b) => a.simpleName.compareTo(b.simpleName));
patches.sort((a, b) => a.name.compareTo(b.name));
for (Patch p in patches) {
if (p.include) {
if (!p.excluded) {
selectedPatches.add(p);
}
}
@ -56,7 +56,7 @@ class PatchesSelectorViewModel extends BaseViewModel {
.where((patch) =>
query.isEmpty ||
query.length < 2 ||
patch.simpleName.toLowerCase().contains(
patch.name.toLowerCase().contains(
query.toLowerCase(),
))
.toList();

View file

@ -72,7 +72,7 @@ class PatchSelectorCard extends StatelessWidget {
String _getPatchesSelection() {
String text = '';
for (Patch p in locator<PatcherViewModel>().selectedPatches) {
text += '${p.simpleName} (v${p.version})\n';
text += '${p.getSimpleName()} (v${p.version})\n';
}
return text.substring(0, text.length - 1);
}