2018-01-22 12:06:11 +03:00
|
|
|
"""
|
|
|
|
Simple HTML -> Telegram entity parser.
|
|
|
|
"""
|
2018-02-15 13:52:46 +03:00
|
|
|
from collections import deque
|
2019-08-04 11:09:23 +03:00
|
|
|
from html import escape
|
2018-01-22 12:06:11 +03:00
|
|
|
from html.parser import HTMLParser
|
2024-06-21 01:06:40 +03:00
|
|
|
from typing import Iterable, Tuple, List
|
2018-01-22 12:06:11 +03:00
|
|
|
|
2023-06-17 14:07:21 +03:00
|
|
|
from ..helpers import add_surrogate, del_surrogate, within_surrogate, strip_text
|
|
|
|
from ..tl import TLObject
|
2018-01-22 12:06:11 +03:00
|
|
|
from ..tl.types import (
|
|
|
|
MessageEntityBold, MessageEntityItalic, MessageEntityCode,
|
|
|
|
MessageEntityPre, MessageEntityEmail, MessageEntityUrl,
|
2019-06-23 22:35:33 +03:00
|
|
|
MessageEntityTextUrl, MessageEntityMentionName,
|
2019-06-24 13:28:14 +03:00
|
|
|
MessageEntityUnderline, MessageEntityStrike, MessageEntityBlockquote,
|
|
|
|
TypeMessageEntity
|
2018-11-19 12:15:56 +03:00
|
|
|
)
|
2018-01-22 12:06:11 +03:00
|
|
|
|
|
|
|
|
|
|
|
class HTMLToTelegramParser(HTMLParser):
|
|
|
|
def __init__(self):
|
|
|
|
super().__init__()
|
|
|
|
self.text = ''
|
|
|
|
self.entities = []
|
|
|
|
self._building_entities = {}
|
|
|
|
self._open_tags = deque()
|
|
|
|
self._open_tags_meta = deque()
|
|
|
|
|
|
|
|
def handle_starttag(self, tag, attrs):
|
|
|
|
self._open_tags.appendleft(tag)
|
|
|
|
self._open_tags_meta.appendleft(None)
|
|
|
|
|
|
|
|
attrs = dict(attrs)
|
|
|
|
EntityType = None
|
|
|
|
args = {}
|
|
|
|
if tag == 'strong' or tag == 'b':
|
|
|
|
EntityType = MessageEntityBold
|
|
|
|
elif tag == 'em' or tag == 'i':
|
|
|
|
EntityType = MessageEntityItalic
|
2019-06-23 22:35:33 +03:00
|
|
|
elif tag == 'u':
|
|
|
|
EntityType = MessageEntityUnderline
|
|
|
|
elif tag == 'del' or tag == 's':
|
|
|
|
EntityType = MessageEntityStrike
|
|
|
|
elif tag == 'blockquote':
|
|
|
|
EntityType = MessageEntityBlockquote
|
2018-01-22 12:06:11 +03:00
|
|
|
elif tag == 'code':
|
|
|
|
try:
|
|
|
|
# If we're in the middle of a <pre> tag, this <code> tag is
|
|
|
|
# probably intended for syntax highlighting.
|
|
|
|
#
|
|
|
|
# Syntax highlighting is set with
|
|
|
|
# <code class='language-...'>codeblock</code>
|
|
|
|
# inside <pre> tags
|
|
|
|
pre = self._building_entities['pre']
|
|
|
|
try:
|
|
|
|
pre.language = attrs['class'][len('language-'):]
|
|
|
|
except KeyError:
|
|
|
|
pass
|
|
|
|
except KeyError:
|
|
|
|
EntityType = MessageEntityCode
|
|
|
|
elif tag == 'pre':
|
|
|
|
EntityType = MessageEntityPre
|
|
|
|
args['language'] = ''
|
|
|
|
elif tag == 'a':
|
|
|
|
try:
|
|
|
|
url = attrs['href']
|
|
|
|
except KeyError:
|
|
|
|
return
|
|
|
|
if url.startswith('mailto:'):
|
|
|
|
url = url[len('mailto:'):]
|
|
|
|
EntityType = MessageEntityEmail
|
|
|
|
else:
|
|
|
|
if self.get_starttag_text() == url:
|
|
|
|
EntityType = MessageEntityUrl
|
|
|
|
else:
|
|
|
|
EntityType = MessageEntityTextUrl
|
2023-06-17 14:07:21 +03:00
|
|
|
args['url'] = del_surrogate(url)
|
2018-01-22 12:06:11 +03:00
|
|
|
url = None
|
|
|
|
self._open_tags_meta.popleft()
|
|
|
|
self._open_tags_meta.appendleft(url)
|
|
|
|
|
|
|
|
if EntityType and tag not in self._building_entities:
|
|
|
|
self._building_entities[tag] = EntityType(
|
|
|
|
offset=len(self.text),
|
|
|
|
# The length will be determined when closing the tag.
|
|
|
|
length=0,
|
|
|
|
**args)
|
|
|
|
|
|
|
|
def handle_data(self, text):
|
|
|
|
previous_tag = self._open_tags[0] if len(self._open_tags) > 0 else ''
|
|
|
|
if previous_tag == 'a':
|
|
|
|
url = self._open_tags_meta[0]
|
|
|
|
if url:
|
|
|
|
text = url
|
|
|
|
|
|
|
|
for tag, entity in self._building_entities.items():
|
2018-11-19 11:20:13 +03:00
|
|
|
entity.length += len(text)
|
2018-01-22 12:06:11 +03:00
|
|
|
|
|
|
|
self.text += text
|
|
|
|
|
|
|
|
def handle_endtag(self, tag):
|
|
|
|
try:
|
|
|
|
self._open_tags.popleft()
|
|
|
|
self._open_tags_meta.popleft()
|
|
|
|
except IndexError:
|
|
|
|
pass
|
|
|
|
entity = self._building_entities.pop(tag, None)
|
|
|
|
if entity:
|
|
|
|
self.entities.append(entity)
|
|
|
|
|
|
|
|
|
2019-06-24 13:28:14 +03:00
|
|
|
def parse(html: str) -> Tuple[str, List[TypeMessageEntity]]:
|
2018-01-22 12:06:11 +03:00
|
|
|
"""
|
|
|
|
Parses the given HTML message and returns its stripped representation
|
|
|
|
plus a list of the MessageEntity's that were found.
|
|
|
|
|
2019-11-10 13:29:43 +03:00
|
|
|
:param html: the message with HTML to be parsed.
|
2018-01-22 12:06:11 +03:00
|
|
|
:return: a tuple consisting of (clean message, [message entities]).
|
|
|
|
"""
|
2018-06-03 14:48:43 +03:00
|
|
|
if not html:
|
|
|
|
return html, []
|
|
|
|
|
2018-01-22 12:06:11 +03:00
|
|
|
parser = HTMLToTelegramParser()
|
2023-06-17 14:07:21 +03:00
|
|
|
parser.feed(add_surrogate(html))
|
|
|
|
text = strip_text(parser.text, parser.entities)
|
2023-12-07 19:25:11 +03:00
|
|
|
parser.entities.reverse()
|
|
|
|
parser.entities.sort(key=lambda entity: entity.offset)
|
2023-06-17 14:07:21 +03:00
|
|
|
return del_surrogate(text), parser.entities
|
|
|
|
|
|
|
|
|
|
|
|
ENTITY_TO_FORMATTER = {
|
|
|
|
MessageEntityBold: ('<strong>', '</strong>'),
|
|
|
|
MessageEntityItalic: ('<em>', '</em>'),
|
|
|
|
MessageEntityCode: ('<code>', '</code>'),
|
|
|
|
MessageEntityUnderline: ('<u>', '</u>'),
|
|
|
|
MessageEntityStrike: ('<del>', '</del>'),
|
|
|
|
MessageEntityBlockquote: ('<blockquote>', '</blockquote>'),
|
|
|
|
MessageEntityPre: lambda e, _: (
|
|
|
|
"<pre>\n"
|
|
|
|
" <code class='language-{}'>\n"
|
|
|
|
" ".format(e.language), "{}\n"
|
|
|
|
" </code>\n"
|
|
|
|
"</pre>"
|
|
|
|
),
|
|
|
|
MessageEntityEmail: lambda _, t: ('<a href="mailto:{}">'.format(t), '</a>'),
|
|
|
|
MessageEntityUrl: lambda _, t: ('<a href="{}">'.format(t), '</a>'),
|
|
|
|
MessageEntityTextUrl: lambda e, _: ('<a href="{}">'.format(escape(e.url)), '</a>'),
|
|
|
|
MessageEntityMentionName: lambda e, _: ('<a href="tg://user?id={}">'.format(e.user_id), '</a>'),
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
def unparse(text: str, entities: Iterable[TypeMessageEntity]) -> str:
|
2018-01-22 12:06:11 +03:00
|
|
|
"""
|
|
|
|
Performs the reverse operation to .parse(), effectively returning HTML
|
|
|
|
given a normal text and its MessageEntity's.
|
|
|
|
|
|
|
|
:param text: the text to be reconverted into HTML.
|
|
|
|
:param entities: the MessageEntity's applied to the text.
|
|
|
|
:return: a HTML representation of the combination of both inputs.
|
|
|
|
"""
|
2019-06-24 13:28:14 +03:00
|
|
|
if not text:
|
2018-01-22 12:06:11 +03:00
|
|
|
return text
|
2019-06-24 13:28:14 +03:00
|
|
|
elif not entities:
|
|
|
|
return escape(text)
|
2018-02-15 13:52:46 +03:00
|
|
|
|
2023-06-17 14:07:21 +03:00
|
|
|
if isinstance(entities, TLObject):
|
|
|
|
entities = (entities,)
|
|
|
|
|
|
|
|
text = add_surrogate(text)
|
|
|
|
insert_at = []
|
2023-09-14 19:52:04 +03:00
|
|
|
for i, entity in enumerate(entities):
|
2023-06-17 14:07:21 +03:00
|
|
|
s = entity.offset
|
|
|
|
e = entity.offset + entity.length
|
|
|
|
delimiter = ENTITY_TO_FORMATTER.get(type(entity), None)
|
|
|
|
if delimiter:
|
|
|
|
if callable(delimiter):
|
|
|
|
delimiter = delimiter(entity, text[s:e])
|
2023-09-14 19:52:04 +03:00
|
|
|
insert_at.append((s, i, delimiter[0]))
|
2023-12-07 19:09:02 +03:00
|
|
|
insert_at.append((e, -i, delimiter[1]))
|
2023-06-17 14:07:21 +03:00
|
|
|
|
2023-09-14 19:52:04 +03:00
|
|
|
insert_at.sort(key=lambda t: (t[0], t[1]))
|
2023-06-17 14:07:21 +03:00
|
|
|
next_escape_bound = len(text)
|
|
|
|
while insert_at:
|
|
|
|
# Same logic as markdown.py
|
2023-09-14 19:52:04 +03:00
|
|
|
at, _, what = insert_at.pop()
|
2023-06-17 14:07:21 +03:00
|
|
|
while within_surrogate(text, at):
|
|
|
|
at += 1
|
|
|
|
|
|
|
|
text = text[:at] + what + escape(text[at:next_escape_bound]) + text[next_escape_bound:]
|
|
|
|
next_escape_bound = at
|
|
|
|
|
|
|
|
text = escape(text[:next_escape_bound]) + text[next_escape_bound:]
|
|
|
|
|
|
|
|
return del_surrogate(text)
|