MarseyWorld/files/helpers/sanitize.py

316 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 *
2022-03-22 15:15:19 +00:00
from .patter import pat
2021-10-15 14:08:27 +00:00
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-03-22 15:19:16 +00:00
import requests
2022-02-11 23:32:14 +00:00
2022-02-17 01:30:59 +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
2022-04-15 22:39:17 +00:00
def handler(signum, frame):
print("Timeout!")
raise Exception("Timeout")
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-04-15 22:39:17 +00:00
2022-03-19 18:12:14 +00:00
sanitized = image_check_regex.sub(r'\1', sanitized)
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-04-15 22:39:17 +00:00
sanitized = sanitized.replace('','').replace('','').replace("\ufeff", "").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-04-15 23:06:13 +00:00
sanitized = sanitized.replace(i.group(0), f'''<p><a href="/id/{u.id}"><img loading="lazy" src="/pp/{u.id}">@{u.username}</a>''')
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-03-21 20:56:43 +00:00
sanitized = sub_regex.sub(r'\1<a href="/\2">/\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):
2022-04-16 00:18:41 +00:00
sanitized = sanitized.replace(i.group(0), f'''{i.group(1)}<a href="/id/{u.id}"><img loading="lazy" src="/pp/{u.id}">@{u.username}</a>''')
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
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-03-21 20:56:43 +00:00
if tag.get("src") and not tag["src"].startswith('/pp/'):
2021-10-15 14:08:27 +00:00
tag["loading"] = "lazy"
2021-12-05 01:30:06 +00:00
tag["data-src"] = tag["src"]
2022-03-31 16:28:53 +00:00
tag["src"] = "/assets/images/loading.webp"
2022-01-13 21:15:36 +00:00
tag['alt'] = f'![]({tag["data-src"]})'
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"):
2022-03-21 20:56:43 +00:00
del tag["rel"]
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-04-15 22:39:17 +00:00
sanitized = spoiler_regex.sub(r'<spoiler>\1</spoiler>', 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)
2022-04-16 15:30:35 +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'>")
else: new = old.lower()
2022-04-15 22:39:17 +00:00
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()
2022-04-15 22:39:17 +00:00
remoji = emoji.replace('!','').replace('#','')
golden = ' '
if not edit and random() < 0.0025 and ('marsey' in emoji or emoji in marseys_const2): golden = 'g '
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-04-15 22:39:17 +00:00
new = re.sub(f'(?<!"):{emoji}:', f'<img loading="lazy" data-bs-toggle="tooltip" alt=":{emoji}:" title=":{emoji}:" b {golden}src="/e/{remoji}.webp">', new, flags=re.I|re.A)
2022-01-13 23:44:55 +00:00
if comment: marseys_used.add(emoji)
2022-03-22 15:15:19 +00:00
elif remoji.endswith('pat') and path.isfile(f"files/assets/images/emojis/{remoji.replace('pat','')}.webp"):
pat(remoji.replace('pat',''))
2022-04-15 22:39:17 +00:00
new = re.sub(f'(?<!"):{emoji}:', f'<img loading="lazy" data-bs-toggle="tooltip" alt=":{emoji}:" title=":{emoji}:" b {golden}src="/e/{remoji}.webp">', new, flags=re.I|re.A)
2022-03-29 17:32:36 +00:00
requests.post(f'https://api.cloudflare.com/client/v4/zones/{CF_ZONE}/purge_cache', headers=CF_HEADERS, data={'files': [f"https://{request.host}/e/{emoji}.webp"]}, timeout=5)
2022-03-22 15:15:19 +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-04-15 22:39:17 +00:00
emoji = i.group(1).lower()
golden = ' '
if not edit and random() < 0.0025 and ('marsey' in emoji or emoji in marseys_const2): golden = 'g '
2022-02-11 23:32:14 +00:00
2022-04-15 22:39:17 +00:00
old = emoji
emoji = emoji.replace('!','').replace('#','')
if emoji == 'marseyrandom': emoji = choice(marseys_const2)
2022-02-11 23:32:14 +00:00
2022-03-22 15:15:19 +00:00
if path.isfile(f'files/assets/images/emojis/{emoji}.webp'):
2022-04-15 22:39:17 +00:00
sanitized = re.sub(f'(?<!"):{i.group(1).lower()}:', f'<img loading="lazy" data-bs-toggle="tooltip" alt=":{old}:" title=":{old}:" {golden}src="/e/{emoji}.webp">', sanitized, flags=re.I|re.A)
2022-03-22 15:15:19 +00:00
if comment: marseys_used.add(emoji)
elif emoji.endswith('pat') and path.isfile(f"files/assets/images/emojis/{emoji.replace('pat','')}.webp"):
pat(emoji.replace('pat',''))
2022-04-15 22:39:17 +00:00
sanitized = re.sub(f'(?<!"):{i.group(1).lower()}:', f'<img loading="lazy" data-bs-toggle="tooltip" alt=":!{old}:" title=":!{old}:" {golden}src="/e/{emoji}.webp">', sanitized, flags=re.I|re.A)
2022-03-29 17:32:36 +00:00
requests.post(f'https://api.cloudflare.com/client/v4/zones/{CF_ZONE}/purge_cache', headers=CF_HEADERS, data={'files': [f"https://{request.host}/e/{emoji}.webp"]}, timeout=5)
2021-10-15 14:08:27 +00:00
2022-03-19 11:37:43 +00:00
2022-04-10 18:46:55 +00:00
for rd in ["://reddit.com", "://new.reddit.com", "://www.reddit.com", "://redd.it", "://libredd.it", "://teddit.net"]:
2022-03-19 11:37:43 +00:00
sanitized = sanitized.replace(rd, "://old.reddit.com")
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").replace("https://www.instagram", "https://instagram").replace("https://www.tiktok", "https://tiktok")
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-04-16 14:58:07 +00:00
url = i.group(0)
if url in captured: continue
captured.append(url)
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','')
2022-04-16 14:58:07 +00:00
htmlsource = f'<lite-youtube videoid="{i.group(1)}" params="autoplay=1&modestbranding=1'
2021-12-05 16:44:09 +00:00
if t: htmlsource += f'&start={t}'
htmlsource += '"></lite-youtube>'
2022-04-16 14:58:07 +00:00
sanitized = sanitized.replace(url, htmlsource)
2022-01-18 11:19:32 +00:00
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:
2022-04-15 22:39:17 +00:00
sanitized = video_regex.sub(r'<p><video controls preload="none"><source src="\1"></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-03-24 19:44:12 +00:00
if '#fortune' in sanitized:
sanitized = sanitized.replace('#fortune', '')
2022-03-26 11:38:31 +00:00
sanitized += '\n\n<p>' + choice(FORTUNE_REPLIES) + '</p>'
2022-03-24 19:44:12 +00:00
2022-03-27 14:34:56 +00:00
sanitized = sanitized.replace('&amp;','&')
sanitized = utm_regex.sub('', sanitized)
sanitized = utm_regex2.sub('', sanitized)
2022-04-15 22:39:17 +00:00
sanitized = sanitized.replace('<html><body>','').replace('</body></html>','')
2022-04-16 00:18:41 +00:00
allowed_tags = ['b','blockquote','br','code','del','em','h1','h2','h3','h4','h5','h6','hr','i','li','ol','p','pre','strong','sub','sup','table','tbody','th','thead','td','tr','ul','marquee','a','span','ruby','rp','rt','spoiler','img','lite-youtube']
if not noimages: allowed_tags += ['video','source']
2022-04-15 22:39:17 +00:00
def allowed_attributes(tag, name, value):
if name == 'style': return True
if tag == 'marquee':
if name in ['direction', 'behavior', 'scrollamount']: return True
if name in {'height', 'width'}:
try: value = int(value.replace('px', ''))
except: return False
if 0 < value <= 250: return True
return False
if tag == 'a':
if name == 'href': return True
if name == 'rel' and value == 'nofollow noopener noreferrer': return True
if name == 'target' and value == '_blank': return True
return False
if tag == 'img':
2022-04-16 00:18:41 +00:00
if name in ['src','data-src'] and not value.startswith('/') and noimages: return False
2022-04-15 22:39:17 +00:00
if name == 'loading' and value == 'lazy': return True
if name == 'referrpolicy' and value == 'no-referrer': return True
if name == 'data-bs-toggle' and value == 'tooltip': return True
if name in ['src','data-src','alt','title','g','b']: return True
return False
if tag == 'lite-youtube':
if name == 'params' and value.startswith('autoplay=1&modestbranding=1'): return True
if name == 'videoid': return True
return False
if tag == 'video':
if name == 'controls' and value == '': return True
if name == 'preload' and value == 'none': return True
return False
if tag == 'source':
if name == 'src': return True
return False
2022-04-16 15:30:35 +00:00
if tag == 'p':
if name == 'class' and value == 'mb-0': return True
return False
2022-04-15 22:39:17 +00:00
sanitized = bleach.Cleaner(tags=allowed_tags,
attributes=allowed_attributes,
protocols=['http', 'https'],
2022-04-16 14:58:07 +00:00
styles=['color', 'background-color', 'font-weight', 'text-align']
2022-04-15 22:39:17 +00:00
).clean(sanitized)
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-04-15 22:39:17 +00:00
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-04-15 22:39:17 +00:00
def handler(signum, frame):
print("Timeout!")
raise Exception("Timeout")
signal.signal(signal.SIGALRM, handler)
2022-02-23 05:19:57 +00:00
signal.alarm(1)
2022-02-18 19:12:14 +00:00
2022-04-15 22:39:17 +00:00
title = title.replace('','').replace('','').replace("\ufeff", "").replace("𒐪","").replace("\n", "").replace("\r", "").replace("\t", "").replace("&", "&amp;").replace('<','&lt;').replace('>','&gt;').replace('"', '&quot;').replace("'", "&#039;").strip()
2021-10-21 20:50:00 +00:00
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()
2022-04-15 22:39:17 +00:00
golden = ' '
if not edit and random() < 0.0025 and ('marsey' in emoji or emoji in marseys_const2): golden = 'g '
2021-10-21 20:50:00 +00:00
2022-04-15 22:39:17 +00:00
old = emoji
emoji = emoji.replace('!','').replace('#','')
if emoji == 'marseyrandom': emoji = choice(marseys_const2)
2022-03-22 15:15:19 +00:00
if path.isfile(f'files/assets/images/emojis/{emoji}.webp'):
2022-04-15 22:39:17 +00:00
title = re.sub(f'(?<!"):{old}:', f'<img loading="lazy" data-bs-toggle="tooltip" alt=":{old}:" title=":{old}:" {golden}src="/e/{emoji}.webp">', title, flags=re.I|re.A)
2022-03-22 15:15:19 +00:00
elif emoji.endswith('pat') and path.isfile(f"files/assets/images/emojis/{emoji.replace('pat','')}.webp"):
pat(emoji.replace('pat',''))
2022-04-15 22:39:17 +00:00
title = re.sub(f'(?<!"):{old}:', f'<img loading="lazy" data-bs-toggle="tooltip" alt=":{old}:" title=":{old}:" {golden}src="/e/{emoji}.webp">', title, flags=re.I|re.A)
2022-03-29 17:32:36 +00:00
requests.post(f'https://api.cloudflare.com/client/v4/zones/{CF_ZONE}/purge_cache', headers=CF_HEADERS, data={'files': [f"https://{request.host}/e/{emoji}.webp"]}, timeout=5)
2022-03-22 15:15:19 +00:00
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-04-15 22:39:17 +00:00
def allowed_attributes(tag, name, value):
if tag == 'img':
if name == 'loading' and value == 'lazy': return True
if name == 'data-bs-toggle' and value == 'tooltip': return True
if name in ['src','alt','title','g']: return True
return False
sanitized = bleach.clean(title, tags=['img','del'], attributes=allowed_attributes, protocols=['http','https'])
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