rDrama/files/helpers/sanitize.py

371 lines
12 KiB
Python
Raw Normal View History

2021-10-15 14:08:27 +00:00
import bleach
from bs4 import BeautifulSoup
from bleach.linkifier import LinkifyFilter
from functools import partial
from .get import *
from os import path, environ
import re
2022-01-13 00:24:23 +00:00
from mistletoe import markdown
2022-01-12 03:16:49 +00:00
from json import loads, dump
2022-02-11 23:32:14 +00:00
from random import random, choice
2022-02-17 01:30:59 +00:00
import signal
import time
2022-02-11 23:32:14 +00:00
2021-10-15 14:08:27 +00:00
allowed_tags = tags = ['b',
'blockquote',
'br',
'code',
'del',
'em',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'hr',
'i',
'li',
'ol',
'p',
'pre',
'strong',
'sup',
'table',
'tbody',
'th',
'thead',
'td',
'tr',
'ul',
'marquee',
'a',
'img',
'span',
2021-12-09 20:30:14 +00:00
'ruby',
'rp',
'rt',
2021-10-15 14:08:27 +00:00
]
no_images = ['b',
'blockquote',
'br',
'code',
'del',
'em',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'hr',
'i',
'li',
'ol',
'p',
'pre',
'strong',
'sup',
'table',
'tbody',
'th',
'thead',
'td',
'tr',
'ul',
'marquee',
'a',
'span',
2021-12-09 20:30:14 +00:00
'ruby',
'rp',
'rt',
2021-10-15 14:08:27 +00:00
]
2021-11-07 20:57:02 +00:00
def sanitize_marquee(tag, name, value):
if name in allowed_attributes['*'] or name in ['direction', 'behavior', 'scrollamount']: return True
2022-02-23 05:17:03 +00:00
if name in {'height', 'width'}:
2021-11-07 21:08:57 +00:00
try: value = int(value.replace('px', ''))
2021-11-07 20:57:02 +00:00
except: return False
2021-11-09 05:45:12 +00:00
if 0 < value <= 250: return True
2021-11-07 20:57:02 +00:00
return False
allowed_attributes = {
2022-02-23 05:19:57 +00:00
'*': ['href', 'style', 'src', 'class', 'title', 'loading'],
2021-11-07 20:57:02 +00:00
'marquee': sanitize_marquee}
2021-10-15 14:08:27 +00:00
allowed_protocols = ['http', 'https']
2022-02-08 22:30:57 +00:00
allowed_styles = ['color', 'background-color', 'font-weight', 'text-align']
2021-10-15 14:08:27 +00:00
2022-02-17 01:30:59 +00:00
def handler(signum, frame):
print("Forever is over!")
raise Exception("end of time")
2022-01-19 06:20:05 +00:00
def sanitize(sanitized, noimages=False, alert=False, comment=False, edit=False):
2022-01-11 19:46:50 +00:00
2022-02-17 01:30:59 +00:00
signal.signal(signal.SIGALRM, handler)
2022-02-23 05:19:57 +00:00
signal.alarm(1)
2022-02-17 01:30:59 +00:00
2022-01-11 19:46:50 +00:00
sanitized = markdown(sanitized)
2022-03-06 19:03:50 +00:00
sanitized = strikethrough_regex.sub(r'<del>\1</del>', sanitized)
2022-03-17 18:38:14 +00:00
sanitized = sanitized.replace("\ufeff", "").replace("𒐪","").replace("<script","").replace("script>","").replace('','')
2022-01-11 19:46:50 +00:00
if alert:
2022-02-28 23:30:44 +00:00
captured = []
2022-02-28 23:01:57 +00:00
for i in mention_regex2.finditer(sanitized):
2022-02-28 23:30:44 +00:00
if i.group(0) in captured: continue
captured.append(i.group(0))
2022-01-11 19:46:50 +00:00
u = get_user(i.group(1), graceful=True)
if u:
2022-02-23 05:19:57 +00:00
sanitized = sanitized.replace(i.group(0), f'''<p><a href="/id/{u.id}"><img loading="lazy" src="/uid/{u.id}/pic" class="pp20">@{u.username}</a>''', 1)
2022-01-11 19:46:50 +00:00
else:
2022-02-28 23:01:57 +00:00
sanitized = reddit_regex.sub(r'\1<a href="https://old.reddit.com/\2" rel="nofollow noopener noreferrer">/\2</a>', sanitized)
2022-01-11 19:46:50 +00:00
2022-02-28 23:01:57 +00:00
sanitized = sub_regex.sub(r'\1<a href="/\2" rel="nofollow noopener noreferrer">/\2</a>', sanitized)
2022-02-05 18:47:21 +00:00
2022-02-28 23:30:44 +00:00
captured = []
2022-02-26 19:56:58 +00:00
for i in mention_regex.finditer(sanitized):
2022-02-28 23:30:44 +00:00
if i.group(0) in captured: continue
captured.append(i.group(0))
2022-01-11 19:46:50 +00:00
u = get_user(i.group(2), graceful=True)
if u and (not g.v.any_block_exists(u) or g.v.admin_level > 1):
if noimages:
2022-01-17 13:48:12 +00:00
sanitized = sanitized.replace(i.group(0), f'{i.group(1)}<a href="/id/{u.id}">@{u.username}</a>', 1)
2022-01-11 19:46:50 +00:00
else:
2022-02-23 05:19:57 +00:00
sanitized = sanitized.replace(i.group(0), f'''{i.group(1)}<a href="/id/{u.id}"><img loading="lazy" src="/uid/{u.id}/pic" class="pp20">@{u.username}</a>''', 1)
2021-10-15 14:08:27 +00:00
2022-02-28 23:01:57 +00:00
sanitized = imgur_regex.sub(r'\1_d.webp?maxwidth=9999&fidelity=high', sanitized)
2021-10-15 14:08:27 +00:00
if noimages:
sanitized = bleach.Cleaner(tags=no_images,
attributes=allowed_attributes,
protocols=allowed_protocols,
styles=allowed_styles,
filters=[partial(LinkifyFilter,
skip_tags=["pre"],
parse_email=False,
)
]
).clean(sanitized)
else:
sanitized = bleach.Cleaner(tags=allowed_tags,
attributes=allowed_attributes,
protocols=['http', 'https'],
styles=['color','font-weight','transform','-webkit-transform'],
filters=[partial(LinkifyFilter,
skip_tags=["pre"],
parse_email=False,
)
]
).clean(sanitized)
2022-02-24 08:28:13 +00:00
soup = BeautifulSoup(sanitized, 'lxml')
2021-10-15 14:08:27 +00:00
for tag in soup.find_all("img"):
2022-02-03 11:55:54 +00:00
if tag.get("src") and tag.get("class") != ['pp20']:
2021-10-15 14:08:27 +00:00
tag["class"] = "in-comment-image"
tag["loading"] = "lazy"
2021-12-05 01:30:06 +00:00
tag["data-src"] = tag["src"]
2021-12-24 23:00:09 +00:00
tag["src"] = "/static/assets/images/loading.webp"
2022-01-13 21:15:36 +00:00
tag['alt'] = f'![]({tag["data-src"]})'
2022-02-06 10:54:05 +00:00
tag["onclick"] = "expandDesktopImage(this.src);"
2022-01-14 06:40:30 +00:00
tag["data-bs-toggle"] = "modal"
tag["data-bs-target"] = "#expandImageModal"
2022-02-24 09:24:22 +00:00
tag['referrerpolicy'] = "no-referrer"
2021-10-15 14:08:27 +00:00
for tag in soup.find_all("a"):
2021-11-04 14:13:09 +00:00
if tag.get("href"):
2022-01-29 03:55:27 +00:00
if not tag["href"].startswith(SITE_FULL) and not tag["href"].startswith('/') and not tag["href"].startswith(SITE_FULL2):
2021-12-11 17:38:16 +00:00
tag["target"] = "_blank"
tag["rel"] = "nofollow noopener noreferrer"
2021-10-15 14:08:27 +00:00
2022-03-02 00:05:30 +00:00
if fishylinks_regex.fullmatch(str(tag.string)):
try: tag.string = tag["href"]
except: tag.string = ""
2021-10-15 14:08:27 +00:00
sanitized = str(soup)
2022-02-28 23:01:57 +00:00
sanitized = spoiler_regex.sub(r'<span class="spoiler">\1</span>', sanitized)
2021-10-15 14:08:27 +00:00
2022-01-23 23:06:34 +00:00
if comment: marseys_used = set()
2022-01-12 03:16:49 +00:00
2022-02-28 23:30:44 +00:00
emojis = list(emoji_regex.finditer(sanitized))
2022-01-21 21:13:52 +00:00
if len(emojis) > 20: edit = True
2022-02-24 08:28:13 +00:00
captured = []
2022-01-21 20:56:56 +00:00
for i in emojis:
2022-02-24 08:28:13 +00:00
if i.group(0) in captured: continue
captured.append(i.group(0))
2021-10-15 14:08:27 +00:00
old = i.group(0)
2021-11-02 23:18:27 +00:00
if 'marseylong1' in old or 'marseylong2' in old or 'marseyllama1' in old or 'marseyllama2' in old: new = old.lower().replace(">", " class='mb-0'>")
2021-10-15 14:08:27 +00:00
else: new = old.lower()
2022-02-28 23:30:44 +00:00
captured2 = []
for i in emoji_regex2.finditer(new):
if i.group(0) in captured2: continue
captured2.append(i.group(0))
2021-10-15 14:08:27 +00:00
emoji = i.group(1).lower()
2021-12-06 20:02:51 +00:00
if emoji.startswith("#!") or emoji.startswith("!#"):
2022-01-18 00:32:07 +00:00
classes = 'emoji-lg mirrored'
2021-12-06 20:02:51 +00:00
remoji = emoji[2:]
2021-12-03 20:51:16 +00:00
elif emoji.startswith("#"):
2022-01-18 00:32:07 +00:00
classes = 'emoji-lg'
2021-12-03 20:51:16 +00:00
remoji = emoji[1:]
2021-12-15 19:30:26 +00:00
elif emoji.startswith("!"):
2022-01-18 00:32:07 +00:00
classes = 'emoji-md mirrored'
2021-12-15 19:30:26 +00:00
remoji = emoji[1:]
2021-12-03 20:51:16 +00:00
else:
2022-01-18 00:32:07 +00:00
classes = 'emoji-md'
2021-12-03 20:51:16 +00:00
remoji = emoji
2022-03-09 01:44:53 +00:00
if not edit and random() < 0.0025 and ('marsey' in emoji or emoji in marseys_const2): classes += ' golden'
2022-02-11 23:32:14 +00:00
2022-03-09 01:44:53 +00:00
if remoji == 'marseyrandom': remoji = choice(marseys_const2)
2022-01-18 00:32:07 +00:00
2021-12-24 23:09:08 +00:00
if path.isfile(f'files/assets/images/emojis/{remoji}.webp'):
2022-03-05 03:22:38 +00:00
new = re.sub(f'(?<!"):{emoji}:', f'<img loading="lazy" data-bs-toggle="tooltip" alt=":{emoji}:" title=":{emoji}:" class="{classes}" src="/e/{remoji}.webp">', new, flags=re.I|re.A)
2022-01-13 23:44:55 +00:00
if comment: marseys_used.add(emoji)
2021-12-03 20:51:16 +00:00
2021-10-15 14:08:27 +00:00
sanitized = sanitized.replace(old, new)
2022-02-28 23:30:44 +00:00
emojis = list(emoji_regex3.finditer(sanitized))
2022-01-21 21:13:52 +00:00
if len(emojis) > 20: edit = True
2022-02-24 08:28:13 +00:00
captured = []
2022-01-21 20:56:56 +00:00
for i in emojis:
2022-02-24 08:28:13 +00:00
if i.group(0) in captured: continue
captured.append(i.group(0))
2022-02-03 09:08:16 +00:00
emoji = i.group(1).lower().replace('#','')
2021-10-15 14:08:27 +00:00
if emoji.startswith("!"):
emoji = emoji[1:]
2022-01-18 00:32:07 +00:00
classes = 'emoji mirrored'
2022-03-09 01:44:53 +00:00
if not edit and random() < 0.0025 and ('marsey' in emoji or emoji in marseys_const2): classes += ' golden'
2022-02-11 23:32:14 +00:00
2022-02-12 18:38:02 +00:00
old = emoji
2022-03-09 01:44:53 +00:00
if emoji == 'marseyrandom': emoji = choice(marseys_const2)
2022-02-12 18:38:02 +00:00
else: emoji = old
2022-02-11 23:32:14 +00:00
2021-12-24 23:09:08 +00:00
if path.isfile(f'files/assets/images/emojis/{emoji}.webp'):
2022-02-26 18:53:17 +00:00
sanitized = re.sub(f'(?<!"):{i.group(1).lower()}:', f'<img loading="lazy" data-bs-toggle="tooltip" alt=":!{old}:" title=":!{old}:" class="{classes}" src="/e/{emoji}.webp">', sanitized, flags=re.I|re.A)
2022-01-13 23:44:55 +00:00
if comment: marseys_used.add(emoji)
2022-02-12 18:38:02 +00:00
else:
2022-01-18 00:32:07 +00:00
classes = 'emoji'
2022-03-09 01:44:53 +00:00
if not edit and random() < 0.0025 and ('marsey' in emoji or emoji in marseys_const2): classes += ' golden'
2022-02-12 18:38:02 +00:00
old = emoji
2022-03-09 01:44:53 +00:00
if emoji == 'marseyrandom': emoji = choice(marseys_const2)
2022-02-12 18:38:02 +00:00
else: emoji = old
2022-02-11 23:32:14 +00:00
2022-02-12 18:38:02 +00:00
if path.isfile(f'files/assets/images/emojis/{emoji}.webp'):
2022-02-26 18:53:17 +00:00
sanitized = re.sub(f'(?<!"):{i.group(1).lower()}:', f'<img loading="lazy" data-bs-toggle="tooltip" alt=":{old}:" title=":{old}:" class="{classes}" src="/e/{emoji}.webp">', sanitized, flags=re.I|re.A)
2022-02-12 18:38:02 +00:00
if comment: marseys_used.add(emoji)
2021-10-15 14:08:27 +00:00
2022-03-18 19:05:54 +00:00
sanitized = sanitized.replace("nitter.net", "twitter.com").replace("old.reddit.com/gallery", "reddit.com/gallery").replace("https://youtu.be/", "https://youtube.com/watch?v=").replace("https://music.youtube.com/watch?v=", "https://youtube.com/watch?v=").replace("https://streamable.com/", "https://streamable.com/e/").replace("https://youtube.com/shorts/", "https://youtube.com/watch?v=").replace("https://mobile.twitter", "https://twitter").replace("https://m.facebook", "https://facebook").replace("m.wikipedia.org", "wikipedia.org").replace("https://m.youtube", "https://youtube").replace("https://www.youtube", "https://youtube").replace("https://www.twitter", "https://twitter")
2022-03-17 18:38:14 +00:00
if "https://youtube.com/watch?v=" in sanitized: sanitized = sanitized.replace("?t=", "&t=")
2022-02-28 23:30:44 +00:00
captured = []
2022-02-28 23:01:57 +00:00
for i in youtube_regex.finditer(sanitized):
2022-02-28 23:30:44 +00:00
if i.group(0) in captured: continue
captured.append(i.group(0))
2021-10-15 14:08:27 +00:00
url = i.group(1)
2021-12-08 00:55:02 +00:00
yt_id = i.group(2).split('&')[0].split('%')[0]
2021-12-11 17:53:06 +00:00
replacing = f'<a href="{url}" rel="nofollow noopener noreferrer" target="_blank">{url}</a>'
2021-12-05 16:44:09 +00:00
2021-12-08 02:05:29 +00:00
params = parse_qs(urlparse(url.replace('&amp;','&')).query)
2021-12-05 16:44:09 +00:00
t = params.get('t', params.get('start', [0]))[0]
if isinstance(t, str): t = t.replace('s','')
2021-12-31 12:37:42 +00:00
htmlsource = f'<lite-youtube videoid="{yt_id}" params="autoplay=1&modestbranding=1'
2021-12-05 16:44:09 +00:00
if t: htmlsource += f'&start={t}'
htmlsource += '"></lite-youtube>'
2021-10-29 03:33:37 +00:00
sanitized = sanitized.replace(replacing, htmlsource)
2022-01-18 11:19:32 +00:00
2022-03-17 18:38:14 +00:00
for rd in ["://reddit.com", "://new.reddit.com", "://www.reddit.com", "://redd.it", "://libredd.it"]:
sanitized = sanitized.replace(rd, "://old.reddit.com")
2022-02-28 23:01:57 +00:00
sanitized = unlinked_regex.sub(r'\1<a href="\2" rel="nofollow noopener noreferrer" target="_blank">\2</a>', sanitized)
if not noimages:
sanitized = video_regex.sub(r'<p><video controls preload="none" class="embedvid"><source src="\1" type="video/mp4"></video>', sanitized)
2021-10-15 14:08:27 +00:00
2022-01-13 23:44:55 +00:00
if comment:
2022-01-23 23:06:34 +00:00
for marsey in g.db.query(Marsey).filter(Marsey.name.in_(marseys_used)).all():
marsey.count += 1
g.db.add(marsey)
2022-01-12 03:16:49 +00:00
2022-02-17 01:30:59 +00:00
signal.alarm(0)
2021-10-15 14:08:27 +00:00
return sanitized
2021-10-21 20:50:00 +00:00
2022-02-19 21:44:23 +00:00
def handler2(signum, frame):
print("Forever is over!")
raise Exception("end of time")
2022-01-19 06:20:05 +00:00
2022-02-14 02:33:27 +00:00
def filter_emojis_only(title, edit=False, graceful=False):
2021-12-07 23:18:06 +00:00
2022-02-19 21:44:23 +00:00
signal.signal(signal.SIGALRM, handler2)
2022-02-23 05:19:57 +00:00
signal.alarm(1)
2022-02-18 19:12:14 +00:00
2022-03-05 03:22:38 +00:00
title = title.replace("<script","").replace("script>","").replace("&", "&amp;").replace('<','&lt;').replace('>','&gt;').replace('"', '&quot;').replace("'", "&#039;").replace("\ufeff", "").replace("𒐪","").replace('','').replace("\n", "").replace("\r", "").replace("\t", "").strip()
2021-10-21 20:50:00 +00:00
title = bleach.clean(title, tags=[])
2022-02-28 23:30:44 +00:00
emojis = list(emoji_regex4.finditer(title))
2022-01-21 21:13:52 +00:00
if len(emojis) > 20: edit = True
2022-02-24 08:28:13 +00:00
captured = []
2022-01-21 20:56:56 +00:00
for i in emojis:
2022-02-24 08:28:13 +00:00
if i.group(0) in captured: continue
captured.append(i.group(0))
2021-12-10 18:24:35 +00:00
emoji = i.group(1).lower()
2021-10-21 20:50:00 +00:00
if emoji.startswith("!"):
emoji = emoji[1:]
2022-01-18 00:32:07 +00:00
classes = 'emoji mirrored'
2022-03-09 01:44:53 +00:00
if not edit and random() < 0.0025 and ('marsey' in emoji or emoji in marseys_const2): classes += ' golden'
2022-02-11 23:32:14 +00:00
2022-02-12 18:38:02 +00:00
old = emoji
2022-03-09 01:44:53 +00:00
if emoji == 'marseyrandom': emoji = choice(marseys_const2)
2022-02-12 18:38:02 +00:00
else: emoji = old
2022-02-11 23:32:14 +00:00
2021-12-24 23:09:08 +00:00
if path.isfile(f'files/assets/images/emojis/{emoji}.webp'):
2022-02-26 18:53:17 +00:00
title = re.sub(f'(?<!"):!{old}:', f'<img loading="lazy" data-bs-toggle="tooltip" alt=":!{old}:" title=":!{old}:" src="/e/{emoji}.webp" class="{classes}">', title, flags=re.I|re.A)
2022-01-12 03:16:49 +00:00
2022-02-12 18:38:02 +00:00
else:
2022-01-18 00:35:33 +00:00
classes = 'emoji'
2022-03-09 01:44:53 +00:00
if not edit and random() < 0.0025 and ('marsey' in emoji or emoji in marseys_const2): classes += ' golden'
2022-02-11 23:32:14 +00:00
2022-02-12 18:38:02 +00:00
old = emoji
2022-03-09 01:44:53 +00:00
if emoji == 'marseyrandom': emoji = choice(marseys_const2)
2022-02-12 18:38:02 +00:00
else: emoji = old
2022-02-11 23:32:14 +00:00
2022-02-12 18:38:02 +00:00
if path.isfile(f'files/assets/images/emojis/{emoji}.webp'):
2022-02-26 18:53:17 +00:00
title = re.sub(f'(?<!"):{old}:', f'<img loading="lazy" data-bs-toggle="tooltip" alt=":{old}:" title=":{old}:" class="{classes}" src="/e/{emoji}.webp">', title, flags=re.I|re.A)
2022-01-12 03:16:49 +00:00
2022-02-28 23:01:57 +00:00
title = strikethrough_regex.sub(r'<del>\1</del>', title)
2022-02-22 13:00:41 +00:00
2022-02-18 19:12:14 +00:00
signal.alarm(0)
2022-02-14 02:33:27 +00:00
if len(title) > 1500 and not graceful: abort(400)
2021-10-21 20:50:00 +00:00
else: return title