2020-03-21 14:43:32 +00:00
|
|
|
# Pyrogram - Telegram MTProto API Client Library for Python
|
2022-01-07 09:23:45 +00:00
|
|
|
# Copyright (C) 2017-present Dan <https://github.com/delivrance>
|
2018-01-23 14:17:48 +00:00
|
|
|
#
|
2020-03-21 14:43:32 +00:00
|
|
|
# This file is part of Pyrogram.
|
2018-01-23 14:17:48 +00:00
|
|
|
#
|
2020-03-21 14:43:32 +00:00
|
|
|
# Pyrogram is free software: you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU Lesser General Public License as published
|
|
|
|
# by the Free Software Foundation, either version 3 of the License, or
|
|
|
|
# (at your option) any later version.
|
2018-01-23 14:17:48 +00:00
|
|
|
#
|
2020-03-21 14:43:32 +00:00
|
|
|
# Pyrogram is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU Lesser General Public License for more details.
|
2018-01-23 14:17:48 +00:00
|
|
|
#
|
2020-03-21 14:43:32 +00:00
|
|
|
# You should have received a copy of the GNU Lesser General Public License
|
|
|
|
# along with Pyrogram. If not, see <http://www.gnu.org/licenses/>.
|
2018-01-23 14:17:48 +00:00
|
|
|
|
2019-06-24 08:07:28 +00:00
|
|
|
import html
|
2019-07-11 02:14:14 +00:00
|
|
|
import logging
|
2018-01-21 23:26:43 +00:00
|
|
|
import re
|
2019-06-24 08:07:28 +00:00
|
|
|
from html.parser import HTMLParser
|
2020-12-20 16:05:17 +00:00
|
|
|
from typing import Optional
|
2018-01-21 23:26:43 +00:00
|
|
|
|
2019-03-26 12:32:30 +00:00
|
|
|
import pyrogram
|
2020-08-22 06:05:05 +00:00
|
|
|
from pyrogram import raw
|
2019-03-26 12:32:30 +00:00
|
|
|
from pyrogram.errors import PeerIdInvalid
|
2019-06-25 03:47:57 +00:00
|
|
|
from . import utils
|
2018-01-21 23:26:43 +00:00
|
|
|
|
2019-09-08 17:24:06 +00:00
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
|
2018-01-21 23:26:43 +00:00
|
|
|
|
2019-06-24 08:07:28 +00:00
|
|
|
class Parser(HTMLParser):
|
2018-01-23 13:43:12 +00:00
|
|
|
MENTION_RE = re.compile(r"tg://user\?id=(\d+)")
|
2018-01-21 23:26:43 +00:00
|
|
|
|
2020-08-22 06:05:05 +00:00
|
|
|
def __init__(self, client: "pyrogram.Client"):
|
2019-06-24 08:07:28 +00:00
|
|
|
super().__init__()
|
|
|
|
|
2019-03-26 12:32:30 +00:00
|
|
|
self.client = client
|
2018-01-21 23:26:43 +00:00
|
|
|
|
2019-06-24 08:07:28 +00:00
|
|
|
self.text = ""
|
|
|
|
self.entities = []
|
2019-06-25 05:08:38 +00:00
|
|
|
self.tag_entities = {}
|
2019-06-24 08:07:28 +00:00
|
|
|
|
|
|
|
def handle_starttag(self, tag, attrs):
|
|
|
|
attrs = dict(attrs)
|
|
|
|
extra = {}
|
|
|
|
|
|
|
|
if tag in ["b", "strong"]:
|
2020-08-22 06:05:05 +00:00
|
|
|
entity = raw.types.MessageEntityBold
|
2019-06-24 08:07:28 +00:00
|
|
|
elif tag in ["i", "em"]:
|
2020-08-22 06:05:05 +00:00
|
|
|
entity = raw.types.MessageEntityItalic
|
2019-06-24 08:07:28 +00:00
|
|
|
elif tag == "u":
|
2020-08-22 06:05:05 +00:00
|
|
|
entity = raw.types.MessageEntityUnderline
|
2019-06-24 08:07:28 +00:00
|
|
|
elif tag in ["s", "del", "strike"]:
|
2020-08-22 06:05:05 +00:00
|
|
|
entity = raw.types.MessageEntityStrike
|
2019-06-24 08:07:28 +00:00
|
|
|
elif tag == "blockquote":
|
2020-08-22 06:05:05 +00:00
|
|
|
entity = raw.types.MessageEntityBlockquote
|
2019-06-24 08:07:28 +00:00
|
|
|
elif tag == "code":
|
2020-08-22 06:05:05 +00:00
|
|
|
entity = raw.types.MessageEntityCode
|
2019-06-24 08:07:28 +00:00
|
|
|
elif tag == "pre":
|
2020-08-22 06:05:05 +00:00
|
|
|
entity = raw.types.MessageEntityPre
|
2019-06-24 08:07:28 +00:00
|
|
|
extra["language"] = ""
|
2021-12-30 08:14:49 +00:00
|
|
|
elif tag == "spoiler":
|
|
|
|
entity = raw.types.MessageEntitySpoiler
|
2019-06-24 08:07:28 +00:00
|
|
|
elif tag == "a":
|
|
|
|
url = attrs.get("href", "")
|
|
|
|
|
|
|
|
mention = Parser.MENTION_RE.match(url)
|
|
|
|
|
|
|
|
if mention:
|
2020-08-22 06:05:05 +00:00
|
|
|
entity = raw.types.InputMessageEntityMentionName
|
2019-06-25 09:47:45 +00:00
|
|
|
extra["user_id"] = int(mention.group(1))
|
2019-06-24 08:07:28 +00:00
|
|
|
else:
|
2020-08-22 06:05:05 +00:00
|
|
|
entity = raw.types.MessageEntityTextUrl
|
2019-06-24 08:07:28 +00:00
|
|
|
extra["url"] = url
|
|
|
|
else:
|
|
|
|
return
|
2018-01-21 23:26:43 +00:00
|
|
|
|
2019-06-25 05:08:38 +00:00
|
|
|
if tag not in self.tag_entities:
|
|
|
|
self.tag_entities[tag] = []
|
|
|
|
|
|
|
|
self.tag_entities[tag].append(entity(offset=len(self.text), length=0, **extra))
|
2018-01-23 13:43:12 +00:00
|
|
|
|
2019-06-24 08:07:28 +00:00
|
|
|
def handle_data(self, data):
|
|
|
|
data = html.unescape(data)
|
2018-01-23 13:43:12 +00:00
|
|
|
|
2019-06-25 05:08:38 +00:00
|
|
|
for entities in self.tag_entities.values():
|
|
|
|
for entity in entities:
|
2019-09-07 10:49:35 +00:00
|
|
|
entity.length += len(data)
|
2019-03-26 12:32:30 +00:00
|
|
|
|
2019-06-24 08:07:28 +00:00
|
|
|
self.text += data
|
2018-01-21 23:26:43 +00:00
|
|
|
|
2019-06-24 08:07:28 +00:00
|
|
|
def handle_endtag(self, tag):
|
2019-06-25 05:41:48 +00:00
|
|
|
try:
|
|
|
|
self.entities.append(self.tag_entities[tag].pop())
|
|
|
|
except (KeyError, IndexError):
|
|
|
|
line, offset = self.getpos()
|
|
|
|
offset += 1
|
|
|
|
|
2021-04-26 14:13:36 +00:00
|
|
|
log.debug(f"Unmatched closing tag </{tag}> at line {line}:{offset}")
|
2019-06-25 05:41:48 +00:00
|
|
|
else:
|
|
|
|
if not self.tag_entities[tag]:
|
|
|
|
self.tag_entities.pop(tag)
|
2019-06-24 08:07:28 +00:00
|
|
|
|
|
|
|
def error(self, message):
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
class HTML:
|
2020-12-20 16:05:17 +00:00
|
|
|
def __init__(self, client: Optional["pyrogram.Client"]):
|
2019-06-24 08:07:28 +00:00
|
|
|
self.client = client
|
|
|
|
|
2020-08-21 05:28:27 +00:00
|
|
|
async def parse(self, text: str):
|
2020-05-28 13:43:42 +00:00
|
|
|
# Strip whitespace characters from the end of the message, but preserve closing tags
|
2021-05-15 16:35:57 +00:00
|
|
|
text = re.sub(r"\s*(</[\w</>]*>)\s*$", r"\1", text)
|
2018-05-11 11:37:49 +00:00
|
|
|
|
2019-06-24 08:07:28 +00:00
|
|
|
parser = Parser(self.client)
|
2020-05-28 13:43:42 +00:00
|
|
|
parser.feed(utils.add_surrogates(text))
|
2019-06-24 12:17:46 +00:00
|
|
|
parser.close()
|
2018-05-11 11:37:49 +00:00
|
|
|
|
2019-06-25 05:41:48 +00:00
|
|
|
if parser.tag_entities:
|
|
|
|
unclosed_tags = []
|
|
|
|
|
|
|
|
for tag, entities in parser.tag_entities.items():
|
2020-08-22 06:05:05 +00:00
|
|
|
unclosed_tags.append(f"<{tag}> (x{len(entities)})")
|
2019-06-25 05:41:48 +00:00
|
|
|
|
2020-08-22 06:05:05 +00:00
|
|
|
log.warning(f"Unclosed tags: {', '.join(unclosed_tags)}")
|
2019-06-25 05:41:48 +00:00
|
|
|
|
2019-06-25 09:47:45 +00:00
|
|
|
entities = []
|
|
|
|
|
|
|
|
for entity in parser.entities:
|
2020-08-22 06:05:05 +00:00
|
|
|
if isinstance(entity, raw.types.InputMessageEntityMentionName):
|
2019-06-25 09:47:45 +00:00
|
|
|
try:
|
2019-06-26 14:06:50 +00:00
|
|
|
if self.client is not None:
|
2020-08-21 05:28:27 +00:00
|
|
|
entity.user_id = await self.client.resolve_peer(entity.user_id)
|
2019-06-25 09:47:45 +00:00
|
|
|
except PeerIdInvalid:
|
|
|
|
continue
|
|
|
|
|
|
|
|
entities.append(entity)
|
|
|
|
|
2020-08-22 06:05:05 +00:00
|
|
|
return {
|
|
|
|
"message": utils.remove_surrogates(parser.text),
|
|
|
|
"entities": sorted(entities, key=lambda e: e.offset)
|
|
|
|
}
|
2019-06-25 08:24:19 +00:00
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def unparse(text: str, entities: list):
|
|
|
|
text = utils.add_surrogates(text)
|
2019-08-07 11:48:21 +00:00
|
|
|
|
|
|
|
entities_offsets = []
|
2019-06-25 08:24:19 +00:00
|
|
|
|
|
|
|
for entity in entities:
|
2019-08-07 11:48:21 +00:00
|
|
|
entity_type = entity.type
|
2019-06-25 08:24:19 +00:00
|
|
|
start = entity.offset
|
|
|
|
end = start + entity.length
|
|
|
|
|
2021-12-30 08:14:49 +00:00
|
|
|
if entity_type in ("bold", "italic", "underline", "strikethrough", "spoiler"):
|
2020-08-22 06:05:05 +00:00
|
|
|
start_tag = f"<{entity_type[0]}>"
|
2020-08-26 17:46:19 +00:00
|
|
|
end_tag = f"</{entity_type[0]}>"
|
2019-08-07 11:48:21 +00:00
|
|
|
elif entity_type in ("code", "pre", "blockquote"):
|
2020-08-22 06:05:05 +00:00
|
|
|
start_tag = f"<{entity_type}>"
|
|
|
|
end_tag = f"</{entity_type}>"
|
2019-08-07 11:48:21 +00:00
|
|
|
elif entity_type == "text_link":
|
|
|
|
url = entity.url
|
2020-08-22 06:05:05 +00:00
|
|
|
start_tag = f'<a href="{url}">'
|
2019-08-07 11:48:21 +00:00
|
|
|
end_tag = "</a>"
|
|
|
|
elif entity_type == "text_mention":
|
|
|
|
user = entity.user
|
2020-08-22 06:05:05 +00:00
|
|
|
start_tag = f'<a href="tg://user?id={user.id}">'
|
2019-08-07 11:48:21 +00:00
|
|
|
end_tag = "</a>"
|
2019-06-25 08:24:19 +00:00
|
|
|
else:
|
|
|
|
continue
|
|
|
|
|
2019-08-07 11:48:21 +00:00
|
|
|
entities_offsets.append((start_tag, start,))
|
|
|
|
entities_offsets.append((end_tag, end,))
|
|
|
|
|
|
|
|
# sorting by offset (desc)
|
|
|
|
entities_offsets.sort(key=lambda x: -x[1])
|
|
|
|
|
|
|
|
for entity, offset in entities_offsets:
|
|
|
|
text = text[:offset] + entity + text[offset:]
|
2019-06-25 08:24:19 +00:00
|
|
|
|
|
|
|
return utils.remove_surrogates(text)
|