78 lines
2.7 KiB
Python
78 lines
2.7 KiB
Python
import requests
|
|
import re
|
|
from flask import render_template
|
|
from urllib.parse import urlparse
|
|
|
|
def check_link(link):
|
|
parsed_url = urlparse(link)
|
|
if parsed_url.scheme and parsed_url.netloc:
|
|
return 1
|
|
else:
|
|
print("link not valid (https:// missing??)")
|
|
return -1
|
|
|
|
|
|
def check_response(link):
|
|
"""
|
|
responds 1 if link is ok
|
|
2 if there's conncetion error
|
|
3 if link is invalid (no "http" for example)
|
|
"""
|
|
try:
|
|
response = requests.head(link)
|
|
if response.status_code == 200:
|
|
return 1
|
|
else:
|
|
#TODO drugi statusi code?
|
|
#return "WEIRD", response
|
|
#TODO samo za testiranje
|
|
return f"Error: {response.status_code}"
|
|
except Exception as e:
|
|
print(e)
|
|
return f"Link error: {e}"
|
|
|
|
|
|
# kako vse možne linke embeddat?
|
|
def render_embed_link(cm_username, card, maybe_in, no_in):
|
|
url = card.item_location
|
|
|
|
response = check_response(url)
|
|
if response != 1:
|
|
render_template("embed_link/bad_link.html",
|
|
card=card,
|
|
username=cm_username,
|
|
maybe_in=maybe_in,
|
|
no_in=no_in)
|
|
|
|
if re.match(r'^https?://(www\.)?twitter\.com/.*/status/\d+$', url):
|
|
tweet_id = url.split("/")[-1]
|
|
return render_template("embed_link/twitter_embed.html",
|
|
card=card,
|
|
tweet_id=tweet_id,
|
|
username=cm_username,
|
|
maybe_in=maybe_in,
|
|
no_in=no_in)
|
|
|
|
elif re.match(r'^https?://(www\.)?youtube\.com/watch\?.*v=([-\w]+)', url):
|
|
youtube_id = re.search(r'v=([-\w]+)', url).group(1)
|
|
return render_template("embed_link/youtube_embed.html",
|
|
youtube_id=youtube_id,
|
|
card=card,
|
|
username=cm_username,
|
|
maybe_in=maybe_in,
|
|
no_in=no_in)
|
|
|
|
#TODO kill me wtf about the instances.........
|
|
elif re.match(r'^https?://(www\.)?mastodon\.social/@[a-zA-Z0-9]+/\d+', url):
|
|
username, post_id = url.split("/")[-3:-1]
|
|
return render_template("embed_link/mastodon_embed.html", username=username, post_id=post_id)
|
|
|
|
else:
|
|
#TODO what if iframe fails
|
|
return render_template("embed_link/iframe_embed.html",
|
|
url=url,
|
|
card=card,
|
|
username=cm_username,
|
|
maybe_in=maybe_in,
|
|
no_in=no_in)
|