-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapp.py
executable file
·103 lines (90 loc) · 4.33 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#!/usr/bin/env python3
"""
Copyright::
+===================================================+
| © 2023 Someguy123 |
| https://github.com/Someguy123 |
+===================================================+
| |
| Fix Mastodon Embeds (FxMastodon) |
| License: MIT X/11 |
| |
| https://github.com/Someguy123/fxmastodon |
| |
| Core Developer(s): |
| |
| (+) Chris (@someguy123) |
| |
+===================================================+
"""
from flask import Flask, render_template, jsonify, request, session, abort, redirect, flash
from privex.loghelper import LogHelper
from os import getenv as env
from privex.helpers import env_bool, empty
import logging
import requests
import lxml.html
DEBUG = env_bool('DEBUG', False)
_lh = LogHelper(__name__, handler_level=logging.DEBUG if DEBUG else logging.WARN)
_lh.add_console_handler()
log = _lh.get_logger()
app = Flask(__name__)
app.config['TEMPLATES_AUTO_RELOAD'] = True
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def handle_embed(path: str):
api_url = "unknown"
try:
p = path.strip('/').split('/')
if len(p) < 2:
return "Invalid Mastodon URL! Must be formatted like: mastodon.social/@username/1234567 or mastodon.social/123456 or @[email protected]/123456"
if len(p) == 2:
dom, mstatus = p
if '@' in dom:
dom = dom.split('@')[-1]
else:
dom, uname, mstatus = p[:3]
api_url = f"https://{dom}/api/v1/statuses/{mstatus}"
try:
r = requests.get(api_url)
r.raise_for_status()
res = r.json()
except Exception as e:
log.error("ERROR while fetching API URL %s - type: %s | message: %s", api_url, type(e), str(e))
return render_template(
'error.html',
status_code=502,
reason=f"Failed to query API for instance {dom} - instance broken/down",
reason_full=f"An error occurred while querying the instance API at {api_url} - most likely either the remote instance is "
f"broken, down, not compatible with FxMastodon, or has blocked FxMastodon's server. "
f"An exception of type {type(e)} has occurred, full details of this can be found in the logs by the administrator",
), 502
media_count = len(res.get('media_attachments', []))
has_media = media_count > 0
content = res.get('content', '')
content = '' if empty(content) else content
if not empty(content):
content = lxml.html.fromstring(content).text_content()
content = f" [{media_count} attachments]\n\n{content}"
data = dict(
full_url=res['uri'],
username=f"@{res['account']['username']}@{dom}",
display_name=res['account']['display_name'],
img_url="" if not has_media else res['media_attachments'][0].get('url', ''),
img_width='0' if not has_media else res['media_attachments'][0].get('meta', {}).get('original', {}).get('width', '0'),
img_height='0' if not has_media else res['media_attachments'][0].get('meta', {}).get('original', {}).get('height', '0'),
post_contents=content,
)
if has_media and res['media_attachments'][0]['type'] in ['gifv', 'gif', 'video']:
return render_template('video.html', **data)
return render_template('image.html', **data)
except Exception as e:
log.exception("An exception has occurred during handle_embed() (api_url: %s) - exception: %s | message: %s", api_url, type(e), str(e))
return render_template(
'error.html',
status_code=500,
reason="UNKNOWN APP ERROR",
reason_full=f"An exception of type {type(e)} has occurred, full details of this can be found in the logs by the administrator",
), 500
if __name__ == '__main__':
app.run(debug=DEBUG)