image posting is better

This commit is contained in:
iou1name 2018-10-11 12:37:29 -04:00
parent af482c7449
commit bf9b928620
3 changed files with 22 additions and 6 deletions

View File

@ -166,6 +166,7 @@ def text_post(socket, data):
post_text = post_text.replace("\n", "<br>")
# handle image
post_text = handle_img(post_text)
p = Post(
quest=quest,
@ -367,6 +368,7 @@ def edit_post(socket, data):
post_text = post_text.replace("\n", "<br>")
# handle image
post_text = handle_img(post_text)
p.post_text = post_text
p.save()

View File

@ -98,6 +98,10 @@ function edit_post(post_id) {
let post = document.getElementById('questPostData-' + post_id);
let post_text = post.innerHTML.trim();
post_text = post_text.replace(/<br>/g, '\n');
post_text.split('\n').forEach(function(line) {
new_line = line.replace(/<img src="(.*)" title="(.*)">/, '[img title="$2"]$1[/img]');
post_text = post_text.replace(line, new_line);
});
post.innerHTML = '<textarea class="editPostText">' + post_text + '</textarea>';
post.firstElementChild.style.height = post.firstElementChild.scrollHeight + 'px';
document.getElementById('savePost-' + post_id).style.display = 'initial';

View File

@ -30,6 +30,10 @@ def download_img(url):
# TODO: file size limits
# https://stackoverflow.com/questions/22346158/
# TODO: prevent overwriting
url = url.replace('..', '')
if url.startswith(settings.IMG_SVR_URL):
if '/' not in url.replace(settings.IMG_SVR_URL, ''):
return url
try:
res = requests.get(url)
res.raise_for_status()
@ -60,16 +64,22 @@ def handle_img(text, limit=5):
(unlinked) url will be inserted.
"""
# TODO: handle webms
urls = re.findall(r"\[img\](.*?)\[/img\]", text)
urls = re.findall(
r"""\[img(?: title=['"](.*)['"])?\](.*)\[\/img\]""",
text.replace('<br', '\n')
)
urls = urls[:limit]
for ext_url in urls:
for match_pair in urls:
title, ext_url = match_pair
int_url = download_img(ext_url)
if int_url in ["INVALID_URL", "INVALID_MIME_TYPE", "UNKNOWN_ERROR"]:
text = text.replace("[img]" + ext_url + "[/img]", ext_url, 1)
alt_text = os.path.basename(ext_url)
img_tag = f'<img src="{int_url}" title="{alt_text}">'
text = re.sub(r"\[img.*?\[\/img\]", ext_url, text, 1)
if not title:
title = os.path.basename(ext_url)
img_tag = f'<img src="{int_url}" title="{title}">'
text = text.replace("[img]" + ext_url + "[/img]", img_tag, 1)
text = re.sub(r"\[img.*?\[\/img\]", img_tag, text, 1)
return text