
from androguard.core.apk import APK
from androguard.core.dex import DEX
from pathlib import Path
import contextlib

BASE = Path(r"C:\Users\ObjectiveKD\Desktop\CastBridge-EXP02")

APK_FILES = [
    BASE / "WhisperlinkSdk.apk",
    BASE / "WhisperplayCore.apk",
]

OUTPUT = BASE / "ChannelFactoryDetails.txt"

TARGETS = (
    "TExternalSocketFactory",
    "TExternalSecureSocketFactory",
    "TransportFeatures",
    "TExternalCommunicationChannelFactory",
)

RELEVANT_METHODS = {
    "compareTo",
    "getTransportFeatures",
    "getCommunicationChannelId",
    "getServerTransport",
    "getSecureServerTransport",
    "getTransport",
    "getSecureTransport",
    "getConnectionMetadata",
    "getLocalConnInfo",
    "getLocalTransportConnInfo",
    "getServerTransportConnInfo",
    "isChannelReady",
    "start",
    "stop",
    "setupNewRoute",
    "getCurrentInetRoute",
    "getSecureTCPServerSocket",
    "getTCPServerSocket",
}


def dump_method(method):
    print(f"\nMETHOD: {method.get_name()}")
    print(f"SIGNATURE: {method.get_descriptor()}")

    code = method.get_code()

    if code is None:
        print("NO METHOD BODY")
        return

    for instruction in code.get_bc().get_instructions():
        print(
            f"{instruction.get_name():24}"
            f"{instruction.get_output()}"
        )


with OUTPUT.open("w", encoding="utf-8") as out:
    with contextlib.redirect_stdout(out):

        for apk_path in APK_FILES:
            print("\n" + "=" * 90)
            print("APK:", apk_path.name)
            print("=" * 90)

            if not apk_path.exists():
                print("FILE NOT FOUND")
                continue

            try:
                apk = APK(str(apk_path))
                all_classes = []

                for dex_index, dex_bytes in enumerate(apk.get_all_dex()):
                    dex = DEX(dex_bytes)
                    classes = list(dex.get_classes())
                    all_classes.extend(classes)

                class_map = {
                    cls.get_name(): cls
                    for cls in all_classes
                }

                def inherits_target(cls):
                    current = cls
                    visited = set()

                    while current:
                        name = current.get_name()

                        if name in visited:
                            break

                        visited.add(name)

                        if any(
                            target in name
                            for target in TARGETS
                        ):
                            return True

                        parent = current.get_superclassname()
                        current = class_map.get(parent)

                    return False

                for cls in all_classes:
                    name = cls.get_name()
                    superclass = cls.get_superclassname()
                    interfaces = cls.get_interfaces()

                    direct_match = (
                        any(
                            "TExternalCommunicationChannelFactory" in i
                            for i in interfaces
                        )
                    )

                    target_match = (
                        any(target in name for target in TARGETS)
                    )

                    inherited_match = inherits_target(cls)

                    if not (
                        direct_match
                        or target_match
                        or inherited_match
                    ):
                        continue

                    print("\n" + "-" * 90)
                    print("CLASS:", name)
                    print("SUPERCLASS:", superclass)
                    print("INTERFACES:", interfaces)

                    for method in cls.get_methods():
                        method_name = method.get_name()

                        if (
                            "TransportFeatures" in name
                            or method_name in RELEVANT_METHODS
                        ):
                            dump_method(method)

            except Exception as exc:
                print("\nERROR:", repr(exc))

print("Output:", OUTPUT)
