generated from exteraGramPlugins/pluginBase
Message Logger: keep own deletions, remove from view, reset marks
Publish plugin / publish (push) Successful in 4s
Publish plugin / publish (push) Successful in 4s
- Delete dialog: "Keep message for myself" checkbox keeps your deletion on this device (marked deleted); unticked, the message is hidden and never restored. Already deleted messages get a plain "Remove from view" dialog (fixes the chat staying dimmed/touch-blocked after it). - "Reset deleted/edited marks" in the chat menu (Plugins) and, for all chats, in the plugin settings. - Fix restored text-only messages showing as empty bubbles (rich text wrappers like links lost their text); missing settings icons. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
bbe4a557a8
commit
0176f7099d
9 files changed
+586
-12
No files matched your search
+80
-3
@@ -115,6 +115,13 @@ def _loaded(fragment, message_id):
|
||||
return False
|
||||
|
||||
|
||||
def jint_index(index):
|
||||
"""ArrayList.remove(int index), not remove(Object)."""
|
||||
from java import jint
|
||||
|
||||
return jint(index)
|
||||
|
||||
|
||||
def _android_peer_id(marked):
|
||||
"""Telethon sender id -> Android peer id (channels are -id)."""
|
||||
marked = int(marked)
|
||||
@@ -141,10 +148,13 @@ def _rich_text(node):
|
||||
value = getattr(node, "text", None)
|
||||
if isinstance(value, str):
|
||||
return value
|
||||
if value is not None: # a wrapper (url, bold, spoiler...): its inner text
|
||||
return _rich_text(value)
|
||||
# textConcat; every RichText carries `texts`, empty unless it concatenates
|
||||
texts = getattr(node, "texts", None)
|
||||
if texts is not None and hasattr(texts, "size"):
|
||||
return "".join(_rich_text(t) for t in java_list(texts))
|
||||
return _rich_text(value)
|
||||
return ""
|
||||
|
||||
|
||||
def _rich_plain_text(rich):
|
||||
@@ -347,6 +357,8 @@ class ChatSync:
|
||||
def _restore(self, fragment, account, dialog_id, chat_id, me, states):
|
||||
for state in states:
|
||||
message_id = int(state["message_id"])
|
||||
if store.is_hidden(account, dialog_id, message_id):
|
||||
continue # the user removed it from view
|
||||
key = (account, dialog_id, message_id)
|
||||
if key in self._restoring:
|
||||
continue
|
||||
@@ -422,7 +434,7 @@ class ChatSync:
|
||||
if strip:
|
||||
_strip_rich_header(rich)
|
||||
plain = _rich_plain_text(rich)
|
||||
if plain is not None:
|
||||
if plain: # never a blank bubble: else it stays rich
|
||||
# Text only: a normal bubble, as the original was.
|
||||
msg.message = plain
|
||||
msg.entities = ArrayList()
|
||||
@@ -495,7 +507,72 @@ class ChatSync:
|
||||
if fragment is not None:
|
||||
on_ui(lambda: self.schedule(fragment), delay_ms)
|
||||
|
||||
def refresh_dialog(self, account, dialog_id, ids):
|
||||
def _open_chat(self, account, dialog_id):
|
||||
"""The ChatActivity showing the dialog: the one last synced, else the
|
||||
screen on top when it is that chat."""
|
||||
fragment = self._fragments.get((account, dialog_id))
|
||||
if fragment is not None:
|
||||
return fragment
|
||||
from client_utils import get_last_fragment
|
||||
|
||||
top = get_last_fragment()
|
||||
try:
|
||||
if (
|
||||
top is not None
|
||||
and int(top.getCurrentAccount()) == account
|
||||
and int(top.getDialogId()) == dialog_id
|
||||
):
|
||||
return top
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
def refresh_dialog(self, account, dialog_id, ids):
|
||||
fragment = self._open_chat(account, dialog_id)
|
||||
if fragment is not None:
|
||||
on_ui(lambda: self.refresh(fragment, set(int(i) for i in ids)))
|
||||
|
||||
def reset(self, account=None, dialog_id=None):
|
||||
"""Forgets the cache of a chat (all chats when None) and redraws and
|
||||
re-checks the open one(s). Returns the number of marks forgotten."""
|
||||
removed = store.reset(account, dialog_id)
|
||||
for (acc, dia), fragment in list(self._fragments.items()):
|
||||
if dialog_id is not None and (acc, dia) != (account, dialog_id):
|
||||
continue
|
||||
|
||||
def redraw(fragment=fragment):
|
||||
adapter = field(fragment, "chatAdapter")
|
||||
if adapter is not None:
|
||||
for m in java_list(field(fragment, "messages")):
|
||||
if m is not None:
|
||||
m.forceUpdate = True
|
||||
adapter.notifyDataSetChanged()
|
||||
self.schedule(fragment)
|
||||
|
||||
on_ui(redraw)
|
||||
return removed
|
||||
|
||||
def drop_from_view(self, account, dialog_id, ids):
|
||||
"""Takes messages out of the open chat's list (UI thread)."""
|
||||
fragment = self._open_chat(account, dialog_id)
|
||||
if fragment is None:
|
||||
return
|
||||
wanted = set(int(i) for i in ids)
|
||||
messages = field(fragment, "messages")
|
||||
if messages is None:
|
||||
return
|
||||
removed = 0
|
||||
for index in range(messages.size() - 1, -1, -1):
|
||||
message = messages.get(index)
|
||||
if message is not None and int(message.getId()) in wanted:
|
||||
messages.remove(jint_index(index))
|
||||
removed += 1
|
||||
try:
|
||||
by_id = field(fragment, "messagesDict")[0]
|
||||
for i in wanted:
|
||||
by_id.remove(int(i))
|
||||
except Exception:
|
||||
pass
|
||||
adapter = field(fragment, "chatAdapter")
|
||||
if removed and adapter is not None:
|
||||
adapter.notifyDataSetChanged()
|
||||
@@ -0,0 +1,316 @@
|
||||
"""The app's "Delete message" dialog, extended:
|
||||
|
||||
- a "Keep message for myself" checkbox: ticked, the deletion goes to Telegram but
|
||||
the message stays on this device, marked deleted (its local removal is
|
||||
filtered out of MessagesStorage.markMessagesAsDeleted and the
|
||||
messagesDeleted notification; the server's echo then counts as someone
|
||||
else's deletion, see hooks/deletes.py). Unticked (default), it is deleted
|
||||
as usual and remembered as hidden, so it is never restored from the
|
||||
logger here;
|
||||
- already deleted (kept) messages get a plain dialog without checkboxes
|
||||
whose button removes them from view (locally only) and hides them.
|
||||
|
||||
AlertsCreator.createDeleteMessagesAlert(fragment, user, chat, encryptedChat,
|
||||
chatInfo, mergeDialogId, selectedMessage, selectedMessages[2], group,
|
||||
topicId, mode, participants, onDelete, hideDim, resourcesProvider) builds and
|
||||
shows the dialog (exteraGram 12.10.6, probed).
|
||||
"""
|
||||
|
||||
import time
|
||||
|
||||
from base_plugin import MethodHook
|
||||
|
||||
import diag
|
||||
import store
|
||||
from jutil import field, hook_methods, java_ints, java_list, on_ui
|
||||
|
||||
ALERTS = "org.telegram.ui.Components.AlertsCreator"
|
||||
_KEEP_SECONDS = 60
|
||||
|
||||
|
||||
def _targets(args):
|
||||
"""MessageObjects the dialog is about."""
|
||||
selected, arrays, group = args[6], args[7], args[8]
|
||||
if selected is not None:
|
||||
if group is not None:
|
||||
return [m for m in java_list(group.messages) if m is not None]
|
||||
return [selected]
|
||||
out = []
|
||||
for array in arrays or []:
|
||||
if array is None:
|
||||
continue
|
||||
for index in range(array.size()):
|
||||
out.append(array.valueAt(index))
|
||||
return [m for m in out if m is not None]
|
||||
|
||||
|
||||
def _key(message):
|
||||
return int(message.currentAccount), int(message.getDialogId()), int(message.getId())
|
||||
|
||||
|
||||
def _deleted(message):
|
||||
return int(message.getId()) > 0 and store.is_deleted(*_key(message))
|
||||
|
||||
|
||||
class DeleteDialog:
|
||||
def __init__(self, plugin, chats):
|
||||
self.plugin = plugin
|
||||
self.chats = chats # hooks/chat.ChatSync
|
||||
self.handles = []
|
||||
self._choice = None # [checked] of the open dialog
|
||||
self._keeping = {} # (account, id) -> monotonic time to keep until
|
||||
|
||||
# filtering a kept deletion out of the local removal
|
||||
|
||||
def keeping(self, account, ids):
|
||||
now = time.monotonic()
|
||||
return [i for i in ids if self._keeping.get((account, i), 0) > now]
|
||||
|
||||
def install(self):
|
||||
dialog = self
|
||||
|
||||
class BeforeAlert(MethodHook):
|
||||
def before_hooked_method(self, param):
|
||||
try:
|
||||
if dialog.before_alert(param):
|
||||
param.setResult(None)
|
||||
except Exception as exc:
|
||||
diag.error("delete_dialog.before", exc)
|
||||
|
||||
def after_hooked_method(self, param):
|
||||
try:
|
||||
dialog.after_alert(param)
|
||||
except Exception as exc:
|
||||
diag.error("delete_dialog.after", exc)
|
||||
|
||||
class BeforeStorage(MethodHook):
|
||||
def before_hooked_method(self, param):
|
||||
try:
|
||||
dialog.filter_storage(param)
|
||||
except Exception as exc:
|
||||
diag.error("delete_dialog.storage", exc)
|
||||
|
||||
class BeforeNotify(MethodHook):
|
||||
def before_hooked_method(self, param):
|
||||
try:
|
||||
dialog.filter_notification(param)
|
||||
except Exception as exc:
|
||||
diag.error("delete_dialog.notify", exc)
|
||||
|
||||
self.handles += hook_methods(
|
||||
self.plugin, ALERTS, "createDeleteMessagesAlert", BeforeAlert()
|
||||
)
|
||||
self.handles += hook_methods(
|
||||
self.plugin,
|
||||
"org.telegram.messenger.MessagesStorage",
|
||||
"markMessagesAsDeleted",
|
||||
BeforeStorage(),
|
||||
)
|
||||
self.handles += hook_methods(
|
||||
self.plugin,
|
||||
"org.telegram.messenger.NotificationCenter",
|
||||
"postNotificationName",
|
||||
BeforeNotify(),
|
||||
)
|
||||
|
||||
def uninstall(self):
|
||||
for handle in self.handles:
|
||||
try:
|
||||
self.plugin.unhook_method(handle)
|
||||
except Exception:
|
||||
pass
|
||||
self.handles = []
|
||||
|
||||
# the dialog
|
||||
|
||||
def before_alert(self, param):
|
||||
"""Already deleted messages only: our own dialog instead (True)."""
|
||||
self._choice = None
|
||||
targets = _targets(param.args)
|
||||
if not targets or not all(_deleted(m) for m in targets):
|
||||
return False
|
||||
on_delete, hide_dim = param.args[12], param.args[13]
|
||||
on_ui(lambda: self._hide_dialog(param.args[0], targets, on_delete, hide_dim))
|
||||
return True
|
||||
|
||||
def after_alert(self, param):
|
||||
"""Adds the "Keep message here" checkbox to the app's dialog."""
|
||||
targets = _targets(param.args)
|
||||
if not targets or all(_deleted(m) for m in targets):
|
||||
return
|
||||
dialog = param.args[0].getVisibleDialog()
|
||||
if dialog is None:
|
||||
return
|
||||
content = _message_column(dialog.getWindow().getDecorView())
|
||||
if content is None:
|
||||
diag.log("delete dialog: no place for the keep checkbox")
|
||||
return
|
||||
from android.widget import LinearLayout
|
||||
from android_utils import OnClickListener
|
||||
from org.telegram.messenger import AndroidUtilities
|
||||
from org.telegram.ui.Cells import CheckBoxCell
|
||||
|
||||
choice = [False]
|
||||
self._choice = choice
|
||||
cell = CheckBoxCell(content.getContext(), 1)
|
||||
cell.setText("Keep message for myself", "", False, False)
|
||||
|
||||
def toggle(_view):
|
||||
choice[0] = not choice[0]
|
||||
cell.setChecked(choice[0], True)
|
||||
|
||||
cell.setOnClickListener(OnClickListener(toggle))
|
||||
params = LinearLayout.LayoutParams(-1, -2)
|
||||
params.topMargin = AndroidUtilities.dp(4)
|
||||
content.addView(cell, params)
|
||||
|
||||
def _hide_dialog(self, fragment, targets, on_delete, hide_dim):
|
||||
from ui.alert import AlertDialogBuilder
|
||||
|
||||
count = len(targets)
|
||||
builder = AlertDialogBuilder(fragment.getParentActivity())
|
||||
builder.set_title("Remove deleted message" + ("s" if count > 1 else ""))
|
||||
builder.set_message(
|
||||
("These messages were" if count > 1 else "This message was")
|
||||
+ " already deleted. Remove "
|
||||
+ ("them" if count > 1 else "it")
|
||||
+ " from view on this device?"
|
||||
)
|
||||
|
||||
def remove(_builder, _which):
|
||||
self._remove_from_view(targets)
|
||||
if on_delete is not None:
|
||||
on_delete.run()
|
||||
|
||||
def dismissed(_builder):
|
||||
# The app dims the chat for its own dialog and undims it when
|
||||
# that closes: without this the chat stays touch-blocked.
|
||||
if hide_dim is not None:
|
||||
hide_dim.run()
|
||||
|
||||
builder.set_positive_button("Remove", remove)
|
||||
builder.set_negative_button("Back")
|
||||
builder.make_button_red(AlertDialogBuilder.BUTTON_POSITIVE)
|
||||
builder.set_on_dismiss_listener(dismissed)
|
||||
builder.show()
|
||||
|
||||
def _remove_from_view(self, targets):
|
||||
"""Removes already deleted messages from this device only."""
|
||||
from java import jboolean, jint, jlong
|
||||
from java.lang import Object
|
||||
from java.util import ArrayList
|
||||
from org.telegram.messenger import ChatObject, MessagesController, MessagesStorage
|
||||
from org.telegram.messenger import NotificationCenter
|
||||
|
||||
by_chat = {}
|
||||
for message in targets:
|
||||
account, dialog_id, message_id = _key(message)
|
||||
by_chat.setdefault((account, dialog_id), []).append(message_id)
|
||||
for (account, dialog_id), ids in by_chat.items():
|
||||
store.hide(account, dialog_id, ids)
|
||||
store.forget_deleted(account, dialog_id, ids)
|
||||
channel_id = 0
|
||||
if dialog_id < 0:
|
||||
chat = MessagesController.getInstance(account).getChat(-dialog_id)
|
||||
if chat is not None and ChatObject.isChannel(chat):
|
||||
channel_id = -dialog_id
|
||||
items = ArrayList()
|
||||
for i in ids:
|
||||
items.add(jint(i))
|
||||
MessagesStorage.getInstance(account).markMessagesAsDeleted(
|
||||
jlong(dialog_id), items, jboolean(True), jboolean(False), jint(0), jint(0)
|
||||
)
|
||||
from java import jarray
|
||||
|
||||
NotificationCenter.getInstance(account).postNotificationName(
|
||||
NotificationCenter.messagesDeleted,
|
||||
jarray(Object)([items, jlong(channel_id), jboolean(False)]),
|
||||
)
|
||||
# The notification removes them where the app tracks them; a
|
||||
# kept message may sit in the open chat's list only.
|
||||
self.chats.drop_from_view(account, dialog_id, ids)
|
||||
diag.log(f"removed from view {dialog_id}: {ids}")
|
||||
|
||||
# the deletion itself
|
||||
|
||||
def apply_choice(self, account, dialog_id, ids):
|
||||
"""The dialog's choice for ids being deleted (MessagesController.
|
||||
deleteMessages, whose overloads call one another: the first call
|
||||
takes the choice, later ones see the kept ids). Returns kept ids."""
|
||||
choice, self._choice = self._choice, None
|
||||
if choice is None:
|
||||
return self.keeping(account, ids)
|
||||
if choice[0]:
|
||||
until = time.monotonic() + _KEEP_SECONDS
|
||||
for i in ids:
|
||||
self._keeping[(account, i)] = until
|
||||
# Marked deleted here; the server's echo is then kept like any
|
||||
# deletion by someone else (hooks/deletes.py).
|
||||
store.mark_deleted(account, dialog_id, ids)
|
||||
diag.log(f"keeping own deletion {dialog_id}: {ids}")
|
||||
return list(ids)
|
||||
store.hide(account, dialog_id, ids)
|
||||
return []
|
||||
|
||||
def filter_storage(self, param):
|
||||
"""markMessagesAsDeleted(dialogId, ArrayList ids, ...): drop kept ids."""
|
||||
args = param.args
|
||||
if len(args) < 2 or not hasattr(args[1], "size"):
|
||||
return
|
||||
account = int(field(param.thisObject, "currentAccount") or 0)
|
||||
kept = set(self.keeping(account, java_ints(args[1])))
|
||||
if not kept:
|
||||
return
|
||||
items = args[1]
|
||||
for index in range(items.size() - 1, -1, -1):
|
||||
if int(items.get(index)) in kept:
|
||||
items.remove(jint_index(index))
|
||||
|
||||
def filter_notification(self, param):
|
||||
"""messagesDeleted with kept ids: those are dropped from it."""
|
||||
from org.telegram.messenger import NotificationCenter
|
||||
|
||||
if int(param.args[0]) != int(NotificationCenter.messagesDeleted):
|
||||
return
|
||||
extra = param.args[1]
|
||||
if extra is None or len(extra) < 1 or not hasattr(extra[0], "size"):
|
||||
return
|
||||
account = int(field(param.thisObject, "currentAccount") or 0)
|
||||
kept = set(self.keeping(account, java_ints(extra[0])))
|
||||
if not kept:
|
||||
return
|
||||
items = extra[0]
|
||||
for index in range(items.size() - 1, -1, -1):
|
||||
if int(items.get(index)) in kept:
|
||||
items.remove(jint_index(index))
|
||||
if items.size() == 0:
|
||||
param.setResult(None)
|
||||
|
||||
|
||||
def jint_index(index):
|
||||
"""ArrayList.remove(int index), not remove(Object)."""
|
||||
from java import jint
|
||||
|
||||
return jint(index)
|
||||
|
||||
|
||||
def _message_column(view):
|
||||
"""The dialog's vertical layout holding its message text (and checkboxes)."""
|
||||
from android.widget import LinearLayout, TextView
|
||||
|
||||
found = []
|
||||
|
||||
def walk(node):
|
||||
if found:
|
||||
return
|
||||
if isinstance(node, TextView):
|
||||
parent = node.getParent()
|
||||
if isinstance(parent, LinearLayout) and parent.getOrientation() == LinearLayout.VERTICAL:
|
||||
found.append(parent)
|
||||
return
|
||||
if hasattr(node, "getChildCount"):
|
||||
for index in range(node.getChildCount()):
|
||||
walk(node.getChildAt(index))
|
||||
|
||||
walk(view)
|
||||
return found[0] if found else None
|
||||
@@ -23,10 +23,11 @@ UPDATES = ("TL_updateDeleteMessages", "TL_updateDeleteChannelMessages")
|
||||
|
||||
|
||||
class Deletes:
|
||||
def __init__(self, plugin, api, chats):
|
||||
def __init__(self, plugin, api, chats, dialog=None):
|
||||
self.plugin = plugin
|
||||
self.api = api
|
||||
self.chats = chats
|
||||
self.dialog = dialog # hooks/delete_dialog.DeleteDialog
|
||||
self.handles = []
|
||||
|
||||
def install(self):
|
||||
@@ -70,6 +71,12 @@ class Deletes:
|
||||
return
|
||||
account = int(field(param.thisObject, "currentAccount") or 0)
|
||||
dialog_id = int(args[3] or 0)
|
||||
kept = self.dialog.apply_choice(account, dialog_id, ids) if self.dialog else []
|
||||
if kept:
|
||||
self.chats.refresh_dialog(account, dialog_id, kept)
|
||||
ids = [i for i in ids if i not in kept]
|
||||
if not ids:
|
||||
return
|
||||
store.note_own_deletion(account, ids)
|
||||
store.forget_deleted(account, dialog_id, ids)
|
||||
|
||||
|
||||
Reference in new issue
Block a user