rDrama/files/helpers/sanitize.py

296 lines
11 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-01-18 00:32:07 +00:00
from random import random
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
2021-11-09 05:45:12 +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 = {
2021-12-09 19:53:38 +00:00
'*': ['href', 'style', 'src', 'class', 'title'],
2021-11-07 20:57:02 +00:00
'marquee': sanitize_marquee}
2021-10-15 14:08:27 +00:00
allowed_protocols = ['http', 'https']
2021-11-04 15:41:18 +00:00
allowed_styles = ['color', 'background-color', 'font-weight', 'transform', '-webkit-transform']
2021-10-15 14:08:27 +00:00
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
sanitized = markdown(sanitized)
sanitized = sanitized.replace("\ufeff", "").replace("𒐪","").replace("<script","").replace('','')
if alert:
for i in re.finditer("<p>@((\w|-){1,25})", sanitized):
u = get_user(i.group(1), graceful=True)
if u:
2022-01-17 13:48:12 +00:00
sanitized = sanitized.replace(i.group(0), f'''<p><a href="/id/{u.id}"><img alt="@{u.username}'s profile picture" loading="lazy" src="/uid/{u.id}/pic" class="pp20">@{u.username}</a>''', 1)
2022-01-11 19:46:50 +00:00
else:
2022-01-21 17:21:46 +00:00
sanitized = re.sub('(^|\s|\n|<p>)\/?((r|u)\/(\w|-){3,25})', 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-01-17 13:48:12 +00:00
for i in re.finditer('(^|\s|\n|<p>)@((\w|-){1,25})', sanitized):
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-01-17 13:48:12 +00:00
sanitized = sanitized.replace(i.group(0), f'''{i.group(1)}<a href="/id/{u.id}"><img alt="@{u.username}'s profile picture" loading="lazy" src="/uid/{u.id}/pic" class="pp20">@{u.username}</a>''', 1)
2021-10-15 14:08:27 +00:00
2022-01-22 01:34:49 +00:00
for i in re.finditer('https://i\.imgur\.com/(([^_]*?)\.(jpg|png|jpeg))(?!</code>)', sanitized):
2022-01-14 02:33:27 +00:00
sanitized = sanitized.replace(i.group(1), i.group(2) + "_d.webp?maxwidth=9999&fidelity=high")
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)
soup = BeautifulSoup(sanitized, features="html.parser")
for tag in soup.find_all("img"):
2021-11-04 21:14:38 +00:00
if tag.get("src") and "pp20" not in tag.get("class", ""):
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-01-15 23:23:36 +00:00
tag["onclick"] = f"expandDesktopImage(this.src);"
2022-01-14 06:40:30 +00:00
tag["data-bs-toggle"] = "modal"
tag["data-bs-target"] = "#expandImageModal"
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-19 09:07:16 +00:00
if not tag["href"].startswith(SITE_FULL) and not tag["href"].startswith('/'):
2021-12-11 17:38:16 +00:00
tag["target"] = "_blank"
tag["rel"] = "nofollow noopener noreferrer"
2021-10-15 14:08:27 +00:00
if re.match("https?://\S+", str(tag.string)):
try: tag.string = tag["href"]
except: tag.string = ""
sanitized = str(soup)
2021-12-10 02:14:18 +00:00
sanitized = re.sub('\|\|(.*?)\|\|', r'<span class="spoiler">\1</span>', sanitized)
2021-10-15 14:08:27 +00:00
2022-01-13 23:44:55 +00:00
if comment:
2022-01-22 14:08:14 +00:00
with open("marseys.json", 'r') as f: marsey_count = loads(f.read())
2022-01-13 23:44:55 +00:00
marseys_used = set()
2022-01-12 03:16:49 +00:00
2022-01-21 21:13:52 +00:00
emojis = list(re.finditer("[^a]>\s*(:[!#]{0,2}\w+:\s*)+<\/", sanitized))
if len(emojis) > 20: edit = True
2022-01-21 20:56:56 +00:00
for i in emojis:
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()
2021-12-08 01:03:57 +00:00
for i in re.finditer('(?<!"):([!#A-Za-z0-9]{1,30}?):', new):
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-01-21 20:56:56 +00:00
if not edit and random() < 0.005 and 'marsey' in emoji: classes += ' golden'
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-01-18 00:32:07 +00:00
new = re.sub(f'(?<!"):{emoji}:', f'<img loading="lazy" data-bs-toggle="tooltip" alt=":{emoji}:" title=":{emoji}:" delay="0" class="{classes}" src="/static/assets/images/emojis/{remoji}.webp" >', new, flags=re.I)
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-01-21 21:13:52 +00:00
emojis = list(re.finditer('(?<!"):([!A-Za-z0-9]{1,30}?):', sanitized))
if len(emojis) > 20: edit = True
2022-01-21 20:56:56 +00:00
for i in emojis:
2021-10-15 14:08:27 +00:00
emoji = i.group(1).lower()
if emoji.startswith("!"):
emoji = emoji[1:]
2022-01-18 00:32:07 +00:00
classes = 'emoji mirrored'
2022-01-21 20:56:56 +00:00
if not edit and random() < 0.005 and 'marsey' in emoji: classes += ' golden'
2021-12-24 23:09:08 +00:00
if path.isfile(f'files/assets/images/emojis/{emoji}.webp'):
2022-01-18 00:32:07 +00:00
sanitized = re.sub(f'(?<!"):!{emoji}:', f'<img loading="lazy" data-bs-toggle="tooltip" alt=":!{emoji}:" title=":!{emoji}:" delay="0" class="{classes}" src="/static/assets/images/emojis/{emoji}.webp">', sanitized, flags=re.I)
2022-01-13 23:44:55 +00:00
if comment: marseys_used.add(emoji)
2021-10-15 14:08:27 +00:00
2021-12-24 23:09:08 +00:00
elif path.isfile(f'files/assets/images/emojis/{emoji}.webp'):
2022-01-18 00:32:07 +00:00
classes = 'emoji'
2022-01-21 20:56:56 +00:00
if not edit and random() < 0.005 and 'marsey' in emoji: classes += ' golden'
2022-01-18 00:32:07 +00:00
sanitized = re.sub(f'(?<!"):{emoji}:', f'<img loading="lazy" data-bs-toggle="tooltip" alt=":{emoji}:" title=":{emoji}:" delay="0" class="{classes}" src="/static/assets/images/emojis/{emoji}.webp">', sanitized, flags=re.I)
2022-01-13 23:44:55 +00:00
if comment: marseys_used.add(emoji)
2021-10-15 14:08:27 +00:00
2021-12-25 20:46:49 +00:00
sanitized = sanitized.replace("https://www.", "https://").replace("https://youtu.be/", "https://youtube.com/watch?v=").replace("https://music.youtube.com/watch?v=", "https://youtube.com/watch?v=").replace("https://open.spotify.com/", "https://open.spotify.com/embed/").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")
2021-10-15 14:08:27 +00:00
2021-12-25 20:46:49 +00:00
if "https://youtube.com/watch?v=" in sanitized: sanitized = sanitized.replace("?t=", "&t=")
2021-12-05 16:44:09 +00:00
2022-01-22 01:34:49 +00:00
for i in re.finditer('" target="_blank">(https://youtube\.com/watch\?v\=(.*?))</a>(?!</code>)', sanitized):
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
if not noimages:
for i in re.finditer('>(https://.*?\.(mp4|webm|mov))</a></p>', sanitized):
sanitized = sanitized.replace(f'<p><a href="{i.group(1)}" rel="nofollow noopener noreferrer" target="_blank">{i.group(1)}</a></p>', f'<p><video controls preload="none" class="embedvid"><source src="{i.group(1)}" type="video/{i.group(2)}"></video>')
for i in re.finditer('<p>(https:.*?\.(mp4|webm|mov))</p>', sanitized):
sanitized = sanitized.replace(i.group(0), f'<p><video controls preload="none" class="embedvid"><source src="{i.group(1)}" type="video/{i.group(2)}"></video>')
2021-10-15 14:08:27 +00:00
2022-01-12 01:19:13 +00:00
for rd in ["://reddit.com", "://new.reddit.com", "://www.reddit.com", "://redd.it", "://libredd.it"]:
sanitized = sanitized.replace(rd, "://old.reddit.com")
2021-10-21 13:02:47 +00:00
sanitized = sanitized.replace("old.reddit.com/gallery", "new.reddit.com/gallery")
2021-11-06 18:10:08 +00:00
sanitized = re.sub(' (https:\/\/[^ <>]*)', r' <a target="_blank" rel="nofollow noopener noreferrer" href="\1">\1</a>', sanitized)
sanitized = re.sub('<p>(https:\/\/[^ <>]*)', r'<p><a target="_blank" rel="nofollow noopener noreferrer" href="\1">\1</a></p>', sanitized)
2021-10-15 14:08:27 +00:00
2022-01-13 23:44:55 +00:00
if comment:
for emoji in marseys_used:
2022-01-22 14:08:14 +00:00
if emoji in marsey_count: marsey_count[emoji]["count"] += 1
with open('marseys.json', 'w') as f: dump(marsey_count, f)
2022-01-12 03:16:49 +00:00
2021-10-15 14:08:27 +00:00
return sanitized
2021-10-21 20:50:00 +00:00
2022-01-19 06:20:05 +00:00
2022-01-21 20:56:56 +00:00
def filter_emojis_only(title, edit=False):
2021-12-07 23:18:06 +00:00
2022-01-21 17:21:46 +00:00
title = title.replace('<','').replace("\n", "").replace("\r", "").replace("\t", "").strip()
2021-10-21 20:50:00 +00:00
title = bleach.clean(title, tags=[])
2022-01-21 21:13:52 +00:00
emojis = list(re.finditer('(?<!"):([!A-Za-z0-9]{1,30}?):', title))
if len(emojis) > 20: edit = True
2022-01-21 20:56:56 +00:00
for i in emojis:
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-01-21 20:56:56 +00:00
if not edit and random() < 0.005 and 'marsey' in emoji: classes += ' golden'
2021-12-24 23:09:08 +00:00
if path.isfile(f'files/assets/images/emojis/{emoji}.webp'):
2022-01-18 00:32:07 +00:00
title = re.sub(f'(?<!"):!{emoji}:', f'<img loading="lazy" data-bs-toggle="tooltip" alt=":!{emoji}:" title=":!{emoji}:" delay="0" src="/static/assets/images/emojis/{emoji}.webp" class="{classes}">', title, flags=re.I)
2022-01-12 03:16:49 +00:00
2021-12-24 23:09:08 +00:00
elif path.isfile(f'files/assets/images/emojis/{emoji}.webp'):
2022-01-18 00:35:33 +00:00
classes = 'emoji'
2022-01-21 20:56:56 +00:00
if not edit and random() < 0.005 and 'marsey' in emoji: classes += ' golden'
2022-01-18 00:32:07 +00:00
title = re.sub(f'(?<!"):{emoji}:', f'<img loading="lazy" data-bs-toggle="tooltip" alt=":{emoji}:" title=":{emoji}:" delay="0" class="{classes}" src="/static/assets/images/emojis/{emoji}.webp">', title, flags=re.I)
2022-01-12 03:16:49 +00:00
2021-10-21 20:50:00 +00:00
if len(title) > 1500: abort(400)
else: return title