[no bump] Implement telegra.ph media forward
Publish plugin / publish (push) Successful in 3s

Adds a share action to the Instant View photo viewer that downloads the
media and re-sends it from the user's own account with a text_url caption
linking back to the source article.

- src/main.py: hooks PhotoViewer.onPhotoShow, injects the toolbar item
- src/ivmedia.py: resolves the viewer's page block to a TL media object
- src/picker.py: share sheet + comment field (restores focus after the
  keyboard animation, which PhotoViewer.showShareAlert does itself)
- src/sender.py: FileLoader download, cache reuse, re-send with caption
- src/icons.py: IconManager-aware drawable lookup so icon packs apply
- tools/verify_bundle.py: offline checks for URL acceptance, caption
  entity shape and bundled-module isolation

Drops the sample greeting/textutil modules.
This commit is contained in:
lyuksovannyy committed 2026-09-25 00:49:58 +02:00
1 parent bfd0f80c6f
commit 05c5212a8a
10 files changed
+757 -95

No files matched your search

+174 -40
View File
@@ -50,6 +50,7 @@ LOG_LINES: list[str] = []
class BasePlugin:
def __init__(self):
self._settings = {}
self.hooked = []
def get_setting(self, key, default=None):
return self._settings.get(key, default)
@@ -57,8 +58,12 @@ class BasePlugin:
def set_setting(self, key, value):
self._settings[key] = value
def add_on_send_message_hook(self):
pass
def hook_all_methods(self, clazz, name, hook):
self.hooked.append((clazz, name, hook))
return [object()]
def log(self, message):
fake_log(message)
def on_plugin_load(self):
pass
@@ -70,6 +75,10 @@ class BasePlugin:
return []
class MethodHook:
pass
def fake_log(*args, **kwargs):
LOG_LINES.append(" ".join(str(a) for a in args))
@@ -79,17 +88,96 @@ class _SettingsRow:
self.__dict__.update(kwargs)
class FakeAdapter:
"""Stand-in for PhotoViewer.PageBlocksAdapter."""
def __init__(self, page, media=None, file=None, video=False):
self.page = page
self.media = media
self.file = file
self.video = video
def getParentObject(self):
return self.page
def getMedia(self, index):
return self.media
def getFile(self, index):
return self.file
def isVideo(self, index):
return self.video
class FakeWebPage:
def __init__(self, url, display_url=None):
self.url = url
self.display_url = display_url
def install_fakes() -> None:
base_plugin_mod = types.ModuleType("base_plugin")
base_plugin_mod.BasePlugin = BasePlugin
base_plugin_mod.MethodHook = MethodHook
base_plugin_mod.HookResult = HookResult
base_plugin_mod.HookStrategy = HookStrategy
sys.modules["base_plugin"] = base_plugin_mod
android_utils_mod = types.ModuleType("android_utils")
android_utils_mod.log = fake_log
android_utils_mod.run_on_ui_thread = lambda fn, delay=0: fn()
class OnClickListener:
def __init__(self, fn):
self.fn = fn
android_utils_mod.OnClickListener = OnClickListener
sys.modules["android_utils"] = android_utils_mod
hook_utils_mod = types.ModuleType("hook_utils")
hook_utils_mod.find_class = lambda name: FAKE_CLASSES.get(name)
hook_utils_mod.get_private_field = lambda obj, field: getattr(obj, field, None)
sys.modules["hook_utils"] = hook_utils_mod
client_utils_mod = types.ModuleType("client_utils")
client_utils_mod.get_selected_account = lambda: 0
client_utils_mod.get_last_fragment = lambda: None
client_utils_mod.get_send_messages_helper = lambda account=None: None
sys.modules["client_utils"] = client_utils_mod
# `TLRPC.WebPage` is only used for an isinstance() narrowing, so a fake
# class hierarchy is enough to exercise ivmedia.page_of().
tgnet_mod = types.ModuleType("org.telegram.tgnet")
tlrpc = types.SimpleNamespace(
WebPage=FakeWebPage,
# `_link_entities` fills these in as plain attributes, so a bare
# attribute holder reproduces the real TL object closely enough.
TL_messageEntityTextUrl=lambda: types.SimpleNamespace(
offset=0, length=0, url=None
),
)
tgnet_mod.TLRPC = tlrpc
# `java.util.ArrayList` only ever gets add()ed to and iterated.
java_mod = types.ModuleType("java")
java_mod.__path__ = []
java_util_mod = types.ModuleType("java.util")
class ArrayList(list):
def add(self, item):
self.append(item)
return True
java_util_mod.ArrayList = ArrayList
java_mod.util = java_util_mod
sys.modules.setdefault("java", java_mod)
sys.modules["java.util"] = java_util_mod
sys.modules["org.telegram.tgnet"] = tgnet_mod
org_mod = types.ModuleType("org")
org_mod.__path__ = []
sys.modules.setdefault("org", org_mod)
ui_mod = types.ModuleType("ui")
ui_mod.__path__ = []
sys.modules["ui"] = ui_mod
@@ -100,6 +188,26 @@ def install_fakes() -> None:
sys.modules["ui.settings"] = ui_settings_mod
ui_mod.settings = ui_settings_mod
ui_bulletin_mod = types.ModuleType("ui.bulletin")
class BulletinHelper:
shown = []
@classmethod
def show_error(cls, message, fragment=None):
cls.shown.append(("error", message))
@classmethod
def show_success(cls, message, fragment=None):
cls.shown.append(("success", message))
ui_bulletin_mod.BulletinHelper = BulletinHelper
sys.modules["ui.bulletin"] = ui_bulletin_mod
ui_mod.bulletin = ui_bulletin_mod
FAKE_CLASSES = {"org.telegram.ui.PhotoViewer": object()}
class SimpleParams:
def __init__(self, message):
@@ -147,7 +255,7 @@ def main(argv=None) -> int:
source = bundle_path.read_text(encoding="utf-8")
modules_before = set(sys.modules)
ns = {"__name__": "hello_bundle"}
ns = {"__name__": json.loads(PLUGIN_JSON.read_text(encoding="utf-8"))["id"]}
exec(compile(source, str(bundle_path), "exec"), ns)
new_modules = set(sys.modules) - modules_before
@@ -197,59 +305,85 @@ def main(argv=None) -> int:
LOG_LINES.clear()
plugin.on_plugin_load()
check(
"on_plugin_load emits load log line",
any("hello_bundle loaded" in line for line in LOG_LINES),
f"log lines: {LOG_LINES}",
"on_plugin_load hooks PhotoViewer.onPhotoShow",
[name for _c, name, _h in plugin.hooked] == ["onPhotoShow"],
f"hooked: {[n for _c, n, _h in plugin.hooked]}",
)
params = SimpleParams(".hello alice smith")
result = plugin.on_send_message_hook(account=0, params=params)
rows = plugin.create_settings()
check(
"'.hello alice smith' renders greeting",
params.message == "Hello, Alice Smith!",
f"got {params.message!r}",
)
check(
"on_send_message_hook returns MODIFY strategy",
result.strategy == HookStrategy.MODIFY,
f"got {result.strategy}",
"settings expose the any_article switch",
any(getattr(row, "key", None) == "any_article" for row in rows),
f"rows: {[getattr(r, 'key', None) for r in rows]}",
)
plugin.set_setting("template", "{nope}")
params2 = SimpleParams(".hello someone")
plugin.on_send_message_hook(account=0, params=params2)
telegraph = FakeAdapter(FakeWebPage("https://telegra.ph/Some-Article-01-01"))
graph_org = FakeAdapter(FakeWebPage("http://graph.org/x"))
other = FakeAdapter(FakeWebPage("https://example.com/post"))
lookalike = FakeAdapter(FakeWebPage("https://telegra.ph.evil.com/x"))
no_page = FakeAdapter(None)
check(
"bad template produces 'Bad template:' message",
params2.message.startswith("Bad template:"),
f"got {params2.message!r}",
"telegra.ph and graph.org articles are accepted by default",
plugin.allows(telegraph) and plugin.allows(graph_org),
)
check(
"non-telegraph article is rejected by default",
not plugin.allows(other),
)
check(
"host that merely starts with telegra.ph is rejected",
not plugin.allows(lookalike),
)
check(
"adapter without a WebPage parent is rejected",
not plugin.allows(no_page),
)
# main.py imports `render`/`TemplateError` by name, so they live directly
# in the executed namespace — call render() directly to inspect the raised
# traceback (proves linecache registration for bundled, non-file modules).
render = ns.get("render")
template_error = ns.get("TemplateError")
traceback_text = ""
if render is not None and template_error is not None:
try:
render("{nope}", "x")
except template_error:
traceback_text = traceback.format_exc()
plugin.set_setting("any_article", True)
check(
"any_article setting accepts other articles",
plugin.allows(other) and not plugin.allows(no_page),
)
ivmedia = ns.get("ivmedia")
sender = ns.get("sender")
caption = getattr(sender, "CAPTION_TEXT", None)
link_entities = getattr(sender, "_link_entities", None)
entities = link_entities("https://telegra.ph/x") if link_entities else []
entity = entities[0] if entities else None
check(
"render() traceback names src/greeting/template.py",
"src/greeting/template.py" in traceback_text,
f"traceback:\n{traceback_text}",
"caption is a single text_url entity covering the whole caption",
isinstance(caption, str)
and len(caption) > 0
and entity is not None
and entity.offset == 0
and entity.length == len(caption)
and entity.url == "https://telegra.ph/x",
f"got caption={caption!r} entities={entities!r}",
)
media_at = getattr(ivmedia, "media_at", None)
no_media = getattr(ivmedia, "NoMedia", None)
raised = False
traceback_text = ""
if media_at is not None and no_media is not None:
try:
media_at(FakeAdapter(FakeWebPage("https://telegra.ph/x"), media=None), 0)
except no_media:
raised = True
traceback_text = traceback.format_exc()
check("media_at raises NoMedia when the block has no media", raised)
check(
"traceback includes the raising source line text",
"unsupported placeholder" in traceback_text,
"traceback names src/ivmedia.py with its source line",
"src/ivmedia.py" in traceback_text and "no downloadable media" in traceback_text,
f"traceback:\n{traceback_text}",
)
check(
"sys.modules gained no entry for bundled module names",
not ({"greeting", "textutil", "main"} & new_modules),
f"leaked: {({'greeting', 'textutil', 'main'} & new_modules)}",
not ({"icons", "ivmedia", "sender", "picker", "main"} & new_modules),
f"leaked: {({'icons', 'ivmedia', 'sender', 'picker', 'main'} & new_modules)}",
)
if _FAILURES: