Per app config

This commit is contained in:
Nikhil Badyal
2023-08-05 17:21:16 +05:30
parent b8c8983de8
commit bd5224c1a1
11 changed files with 222 additions and 307 deletions
+35 -121
View File
@@ -1,13 +1,13 @@
"""Revanced Patches."""
import json
import subprocess
import os
from typing import Any, Dict, List, Tuple
from loguru import logger
from requests import Session
from src.app import APP
from src.config import RevancedConfig
from src.utils import AppNotFound, handle_response
from src.utils import AppNotFound, PatchesJsonFailed
class Patches(object):
@@ -50,59 +50,28 @@ class Patches(object):
"ml.docilealligator.infinityforreddit": "infinity",
"me.ccrama.redditslide": "slide",
"com.onelouder.baconreader": "bacon",
"com.google.android.youtube": "youtube",
"com.google.android.apps.youtube.music": "youtube_music",
"com.mgoogle.android.gms": "microg",
}
revanced_app_ids = {
key: (value, "_" + value) for key, value in _revanced_app_ids.items()
}
_revanced_extended_app_ids = {
"com.google.android.youtube": "youtube",
"com.google.android.apps.youtube.music": "youtube_music",
"com.mgoogle.android.gms": "microg",
"com.reddit.frontpage": "reddit",
}
revanced_extended_app_ids = {
key: (value, "_" + value) for key, value in _revanced_extended_app_ids.items()
}
@staticmethod
def support_app() -> Dict[str, str]:
"""Return supported apps."""
return Patches._revanced_app_ids
@staticmethod
def check_java(dry_run: bool) -> None:
"""Check if Java17 is installed."""
try:
if dry_run:
return
jd = subprocess.check_output(
["java", "-version"], stderr=subprocess.STDOUT
).decode("utf-8")
jd = jd[1:-1]
if "Runtime Environment" not in jd:
raise subprocess.CalledProcessError(-1, "java -version")
if "17" not in jd and "20" not in jd:
raise subprocess.CalledProcessError(-1, "java -version")
logger.debug("Cool!! Java is available")
except subprocess.CalledProcessError:
logger.debug("Java>= 17 Must be installed")
exit(-1)
def scrap_patches(self, file_name: str) -> Any:
"""Scrap Patches."""
if os.path.exists(file_name):
with open(file_name) as f:
patches = json.load(f)
return patches
raise PatchesJsonFailed()
# noinspection DuplicatedCode
def fetch_patches(self) -> None:
def fetch_patches(self, config: RevancedConfig, app: APP) -> None:
"""Function to fetch all patches."""
session = Session()
if self.config.dry_run:
logger.debug("fetching all patches from local file")
with open("patches.json") as f:
patches = json.load(f)
else:
url = "https://raw.githubusercontent.com/revanced/revanced-patches/main/patches.json"
logger.debug(f"fetching all patches from {url}")
response = session.get(url)
handle_response(response)
patches = response.json()
patches = self.scrap_patches(
f'{config.temp_folder}/{app.resource["patches_json"]}'
)
for app_name in (self.revanced_app_ids[x][1] for x in self.revanced_app_ids):
setattr(self, app_name, [])
setattr(self, "universal_patch", [])
@@ -122,47 +91,11 @@ class Patches(object):
p["app"] = compatible_package
p["version"] = version[-1] if version else "all"
getattr(self, app_name).append(p)
if self.config.dry_run:
extended_patches = patches
else:
if self.config.build_extended:
url = "https://raw.githubusercontent.com/inotia00/revanced-patches/revanced-extended/patches.json"
else:
url = "https://raw.githubusercontent.com/revanced/revanced-patches/main/patches.json"
response = session.get(url)
handle_response(response)
extended_patches = response.json()
for app_name in (
self.revanced_extended_app_ids[x][1] for x in self.revanced_extended_app_ids
):
setattr(self, app_name, [])
n_patches = len(getattr(self, f"_{app.app_name}"))
app.no_of_patches = n_patches
for patch in extended_patches:
for compatible_package, version in [
(x["name"], x["versions"]) for x in patch["compatiblePackages"]
]:
if compatible_package in self.revanced_extended_app_ids:
app_name = self.revanced_extended_app_ids[compatible_package][1]
p = {x: patch[x] for x in ["name", "description"]}
p["app"] = compatible_package
p["version"] = version[-1] if version else "all"
getattr(self, app_name).append(p)
for app_name, app_id in self.revanced_extended_app_ids.values():
n_patches = len(getattr(self, app_id))
logger.debug(f"Total patches in {app_name} are {n_patches}")
for app_name, app_id in self.revanced_app_ids.values():
n_patches = len(getattr(self, app_id))
logger.debug(f"Total patches in {app_name} are {n_patches}")
n_patches = len(getattr(self, "universal_patch"))
logger.debug(f"Total universal patches are {n_patches}")
def __init__(self, config: RevancedConfig) -> None:
self.config = config
self.check_java(self.config.dry_run)
self.fetch_patches()
if self.config.dry_run:
self.config.apps = list(self._revanced_app_ids.values())
def __init__(self, config: RevancedConfig, app: APP) -> None:
self.fetch_patches(config, app)
def get(self, app: str) -> Tuple[List[Dict[str, str]], str]:
"""Get all patches for the given app.
@@ -170,11 +103,7 @@ class Patches(object):
:param app: Name of the application
:return: Patches
"""
logger.debug("Getting patches for %s" % app)
app_names = {value[0]: value[1] for value in self.revanced_app_ids.values()}
app_names.update(
{value[0]: value[1] for value in self.revanced_extended_app_ids.values()}
)
if not (app_name := app_names.get(app)):
raise AppNotFound(app)
@@ -182,14 +111,13 @@ class Patches(object):
version = "latest"
try:
version = next(i["version"] for i in patches if i["version"] != "all")
logger.debug(f"Recommended Version for patching {app} is {version}")
except StopIteration:
pass
return patches, version
# noinspection IncorrectFormatting
def include_exclude_patch(
self, app: str, parser: Any, patches: List[Dict[str, str]]
self, app: APP, parser: Any, patches: List[Dict[str, str]]
) -> None:
"""Include and exclude patches for a given app.
@@ -197,34 +125,20 @@ class Patches(object):
:param parser: Parser Obj
:param patches: All the patches of a given app
"""
if self.config.build_extended and app in self.config.extended_apps:
excluded_patches = self.config.env.list(
f"EXCLUDE_PATCH_{app}_EXTENDED".upper(), []
)
included_patches = self.config.env.list(
f"INCLUDE_PATCH_{app}_EXTENDED".upper(), []
)
else:
excluded_patches = self.config.env.list(f"EXCLUDE_PATCH_{app}".upper(), [])
included_patches = self.config.env.list(f"INCLUDE_PATCH_{app}".upper(), [])
for patch in patches:
normalized_patch = patch["name"].lower().replace(" ", "-")
parser.include(
normalized_patch
) if normalized_patch not in excluded_patches else parser.exclude(
) if normalized_patch not in app.exclude_request else parser.exclude(
normalized_patch
)
for normalized_patch in included_patches:
for normalized_patch in app.include_request:
parser.include(normalized_patch) if normalized_patch not in getattr(
self, "universal_patch", []
) else ()
excluded = parser.get_excluded_patches()
if excluded:
logger.debug(f"Excluded patches {excluded} for {app}")
else:
logger.debug(f"No excluded patches for {app}")
logger.info(app)
def get_app_configs(self, app: str) -> Tuple[List[Dict[str, str]], str, bool]:
def get_app_configs(self, app: "APP") -> List[Dict[str, str]]:
"""Get Configurations for a given app.
:param app: Name of the application
@@ -232,15 +146,15 @@ class Patches(object):
experimental
"""
experiment = False
total_patches, recommended_version = self.get(app=app)
env_version = self.config.env.str(f"{app}_VERSION".upper(), None)
if env_version:
logger.debug(f"Picked {app} version {env_version} from env.")
total_patches, recommended_version = self.get(app=app.app_name)
if app.app_version:
logger.debug(f"Picked {app} version {app.app_version:} from env.")
if (
env_version == "latest"
or env_version > recommended_version
or env_version < recommended_version
app.app_version == "latest"
or app.app_version > recommended_version
or app.app_version < recommended_version
):
experiment = True
recommended_version = env_version
return total_patches, recommended_version, experiment
recommended_version = app.app_version
app.set_recommended_version(recommended_version, experiment)
return total_patches