Add url preview and open url handler

This commit is contained in:
Paul Nameless 2020-06-12 11:44:34 +08:00
parent e92eb979fa
commit 456a037f77
2 changed files with 39 additions and 1 deletions

View file

@ -70,6 +70,32 @@ class Controller:
self.tg = tg
self.chat_size = 0.5
@bind(msg_handler, ["o"])
def open_url(self):
msg = self.model.current_msg
msg = MsgProxy(msg)
if not msg.is_text:
self.present_error("Does not contain urls")
return
text = msg["content"]["text"]["text"]
urls = []
for entity in msg["content"]["text"]["entities"]:
if entity["type"]["@type"] != "textEntityTypeUrl":
continue
offset = entity["offset"]
length = entity["length"]
url = text[offset : offset + length]
urls.append(url)
if not urls:
self.present_error("No url to open")
return
if len(urls) == 1:
with suspend(self.view) as s:
s.call(f"open -a Firefox '{url}'")
return
with suspend(self.view) as s:
s.run_with_input("urlview", "\n".join(urls))
def format_help(self, bindings):
return "\n".join(
f"{key}\t{fun.__name__}\t{fun.__doc__ or ''}"

View file

@ -14,7 +14,6 @@ log = logging.getLogger(__name__)
MAX_KEYBINDING_LENGTH = 5
MULTICHAR_KEYBINDINGS = (
"gg",
"dd",
"sd",
"sp",
@ -304,11 +303,24 @@ class MsgView:
msg = f"{reply_line}\n{msg}"
return msg
def _format_url(self, msg_proxy: MsgProxy):
if not msg_proxy.is_text or "web_page" not in msg_proxy.msg["content"]:
return ""
web = msg_proxy.msg["content"]["web_page"]
name = web["site_name"]
title = web["title"]
description = web["description"].replace("\n", "")
url = f"\n | {name}: {title}"
if description:
url += f"\n | {description}"
return url
def _format_msg(
self, msg_proxy: MsgProxy, user_id_item: int, width_limit: int
) -> str:
msg = self._parse_msg(msg_proxy)
msg = msg.replace("\n", " ")
msg += self._format_url(msg_proxy)
if reply_to := msg_proxy.reply_msg_id:
msg = self._format_reply_msg(
msg_proxy.chat_id, msg, reply_to, width_limit