MarseyWorld/files/helpers/sanitize.py

265 lines
9.9 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
site = environ.get("DOMAIN").strip()
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',
]
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-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 = {
'*': ['href', 'style', 'src', 'class', 'title', 'rel', 'data-bs-original-name'],
'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
def sanitize(sanitized, noimages=False):
2021-11-22 13:54:32 +00:00
sanitized = sanitized.replace("\ufeff", "").replace("𒐪","")
2021-10-15 14:08:27 +00:00
2021-12-01 17:25:28 +00:00
for i in re.finditer('https://i\.imgur\.com/(([^_]*?)\.(jpg|png|jpeg))', sanitized):
2021-10-15 14:08:27 +00:00
sanitized = sanitized.replace(i.group(1), i.group(2) + "_d." + i.group(3) + "?maxwidth=9999")
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
2021-11-06 18:10:08 +00:00
if site not in tag["src"] and not tag["src"].startswith('/'): tag["rel"] = "nofollow noopener noreferrer"
2021-10-15 14:08:27 +00:00
tag["class"] = "in-comment-image"
tag["loading"] = "lazy"
tag["data-src"] = tag["src"]
2021-11-11 18:58:09 +00:00
tag["src"] = "/assets/images/loading.webp"
2021-10-15 14:08:27 +00:00
link = soup.new_tag("a")
link["href"] = tag["data-src"]
2021-11-06 18:10:57 +00:00
if site not in link["href"] and not link["href"].startswith('/'): link["rel"] = "nofollow noopener noreferrer"
2021-10-15 14:08:27 +00:00
link["target"] = "_blank"
link["onclick"] = f"expandDesktopImage('{tag['data-src']}');"
link["data-bs-toggle"] = "modal"
link["data-bs-target"] = "#expandImageModal"
tag.wrap(link)
for tag in soup.find_all("a"):
2021-11-04 14:13:09 +00:00
if tag.get("href"):
2021-10-15 14:08:27 +00:00
tag["target"] = "_blank"
2021-11-04 21:14:38 +00:00
if site not in tag["href"] and not tag["href"].startswith('/'): 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)
start = '&lt;s&gt;'
end = '&lt;/s&gt;'
try:
if not session.get("favorite_emojis"): session["favorite_emojis"] = {}
except:
pass
if start in sanitized and end in sanitized and start in sanitized.split(end)[0] and end in sanitized.split(start)[1]: sanitized = sanitized.replace(start, '<span class="spoiler">').replace(end, '</span>')
2021-12-03 20:51:16 +00:00
for i in re.finditer("[^a]>\s*(:[!#]?\w+:\s*)+<\/", sanitized):
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()
for i in re.finditer('(?<!"):([^ ]{1,30}?):', new):
emoji = i.group(1).lower()
if emoji.startswith("!"):
2021-12-04 03:21:03 +00:00
classes = 'class="mirrored lozad" '
2021-12-03 20:51:16 +00:00
remoji = emoji[1:]
elif emoji.startswith("#"):
classes = ""
remoji = emoji[1:]
else:
2021-12-04 03:21:03 +00:00
classes = 'class="lozad" '
2021-12-03 20:51:16 +00:00
remoji = emoji
if path.isfile(f'./files/assets/images/emojis/{remoji}.webp'):
2021-12-04 03:20:02 +00:00
new = re.sub(f'(?<!"):{emoji}:', f'<img loading="lazy" data-bs-toggle="tooltip" alt=":{emoji}:" title=":{emoji}:" delay="0" {classes}src="http://{site}/assets/images/emojis/{remoji}.webp" width="48px" height="48px">', new)
2021-12-03 20:51:16 +00:00
2021-12-03 21:06:47 +00:00
if remoji in session["favorite_emojis"]: session["favorite_emojis"][remoji] += 1
else: session["favorite_emojis"][remoji] = 1
2021-12-03 20:51:16 +00:00
2021-10-15 14:08:27 +00:00
sanitized = sanitized.replace(old, new)
for i in re.finditer('(?<!"):([^ ]{1,30}?):', sanitized):
emoji = i.group(1).lower()
if emoji.startswith("!"):
emoji = emoji[1:]
if path.isfile(f'./files/assets/images/emojis/{emoji}.webp'):
2021-12-04 03:21:40 +00:00
sanitized = re.sub(f'(?<!"):!{emoji}:', f'<img loading="lazy" data-bs-toggle="tooltip" alt=":!{emoji}:" title=":!{emoji}:" delay="0" class="mirrored lozad" src="http://{site}/assets/images/emojis/{emoji}.webp" width="28px" height="28px">', sanitized)
2021-10-15 14:08:27 +00:00
if emoji in session["favorite_emojis"]: session["favorite_emojis"][emoji] += 1
else: session["favorite_emojis"][emoji] = 1
elif path.isfile(f'./files/assets/images/emojis/{emoji}.webp'):
2021-12-04 03:21:40 +00:00
sanitized = re.sub(f'(?<!"):{emoji}:', f'<img loading="lazy" data-bs-toggle="tooltip" alt=":{emoji}:" title=":{emoji}:" delay="0" class="lozad" src="http://{site}/assets/images/emojis/{emoji}.webp" width="28px" height="28px">', sanitized)
2021-10-15 14:08:27 +00:00
if emoji in session["favorite_emojis"]: session["favorite_emojis"][emoji] += 1
else: session["favorite_emojis"][emoji] = 1
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("https://m.wikipedia", "https://wikipedia").replace("https://m.youtube", "https://youtube")
2021-12-01 17:25:28 +00:00
for i in re.finditer('" target="_blank">(https://youtube\.com/watch\?v\=.*?)</a>', sanitized):
2021-10-15 14:08:27 +00:00
url = i.group(1)
replacing = f'<a href="{url}" rel="nofollow noopener noreferrer" target="_blank">{url}</a>'
2021-10-29 03:33:37 +00:00
url = url.replace("watch?v=", "embed/").replace("&amp;t", "?start").replace("?t", "?start")
url = re.sub('(\?start=([0-9]*?))s', r'\1', url)
2021-10-17 16:27:15 +00:00
htmlsource = f'<iframe class="embedvid" loading="lazy" src="{url}" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>'
2021-10-29 03:33:37 +00:00
sanitized = sanitized.replace(replacing, htmlsource)
2021-12-01 17:25:28 +00:00
for i in re.finditer('<a href="(https://streamable\.com/e/.*?)"', sanitized):
2021-10-15 14:08:27 +00:00
url = i.group(1)
replacing = f'<a href="{url}" rel="nofollow noopener noreferrer" target="_blank">{url}</a>'
2021-10-17 16:27:15 +00:00
htmlsource = f'<iframe class="embedvid" loading="lazy" src="{url}" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>'
2021-10-15 14:08:27 +00:00
sanitized = sanitized.replace(replacing, htmlsource)
for i in re.finditer('<p>(https:.*?\.mp4)</p>', sanitized):
2021-10-17 16:27:15 +00:00
sanitized = sanitized.replace(i.group(0), f'<p><video controls loop preload="metadata" class="embedvid"><source src="{i.group(1)}" type="video/mp4"></video>')
2021-10-15 14:08:27 +00:00
2021-12-01 17:25:28 +00:00
for i in re.finditer('<a href="(https://open\.spotify\.com/embed/.*?)"', sanitized):
2021-10-15 14:08:27 +00:00
url = i.group(1)
replacing = f'<a href="{url}" rel="nofollow noopener noreferrer" target="_blank">{url}</a>'
2021-10-17 16:27:15 +00:00
htmlsource = f'<iframe src="{url}" class="spotify" frameBorder="0" allowtransparency="true" allow="encrypted-media"></iframe>'
2021-10-15 14:08:27 +00:00
sanitized = sanitized.replace(replacing, htmlsource)
for rd in ["https://reddit.com/", "https://new.reddit.com/", "https://www.reddit.com/", "https://redd.it/"]:
sanitized = sanitized.replace(rd, "https://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
return sanitized
2021-10-21 20:50:00 +00:00
def filter_title(title):
title = title.strip()
title = title.replace("\n", "")
title = title.replace("\r", "")
title = title.replace("\t", "")
title = bleach.clean(title, tags=[])
for i in re.finditer('(?<!"):([^ ]{1,30}?):', title):
emoji = i.group(1)
if emoji.startswith("!"):
emoji = emoji[1:]
if path.isfile(f'./files/assets/images/emojis/{emoji}.webp'):
title = re.sub(f'(?<!"):!{emoji}:', f'<img loading="lazy" data-bs-toggle="tooltip" alt=":!{emoji}:" title=":!{emoji}:" delay="0" height=30 src="http://{site}/assets/images/emojis/{emoji}.webp" class="mirrored">', title)
elif path.isfile(f'./files/assets/images/emojis/{emoji}.webp'):
title = re.sub(f'(?<!"):{emoji}:', f'<img loading="lazy" data-bs-toggle="tooltip" alt=":{emoji}:" title=":{emoji}:" delay="0" height=30 src="http://{site}/assets/images/emojis/{emoji}.webp">', title)
if len(title) > 1500: abort(400)
else: return title