From 00a0327b192ca931b0ee018112fb9b345396f3e1 Mon Sep 17 00:00:00 2001 From: TheAMM Date: Sat, 13 May 2017 23:40:53 +0300 Subject: [PATCH] Format information into a link if possible Fixes issue #24 (am I doing this right?) Supports HTTP(S) and IRC channels (#channel@server.com) --- nyaa/models.py | 25 +++++++++++++++++++++++++ nyaa/templates/view.html | 2 +- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/nyaa/models.py b/nyaa/models.py index 577740a..34fac59 100644 --- a/nyaa/models.py +++ b/nyaa/models.py @@ -7,6 +7,10 @@ from sqlalchemy_utils import ChoiceType, EmailType, PasswordType from werkzeug.security import generate_password_hash, check_password_hash from sqlalchemy_fulltext import FullText +import re +from markupsafe import escape as escape_markup +from urllib.parse import unquote as unquote_url + if app.config['USE_MYSQL']: from sqlalchemy.dialects import mysql BinaryType = mysql.BINARY @@ -94,6 +98,27 @@ class Torrent(db.Model): ''' Returns a UTC POSIX timestamp, as seconds ''' return (self.created_time - UTC_EPOCH).total_seconds() + @property + def information_as_link(self): + ''' Formats the .information into an IRC or HTTP(S) if possible, + otherwise escapes it. ''' + irc_match = re.match(r'^#([a-zA-Z0-9-_]+)@([a-zA-Z0-9-_.:]+)$', self.information) + if irc_match: + # Return a formatted IRC uri + return '#{0}@{1}'.format(*irc_match.groups()) + + url_match = re.match(r'^(https?:\/\/.+?)$', self.information) + if url_match: + url = url_match.group(1) + + invalid_url_characters = '<>"' + # Check if url contains invalid characters + if not any(c in url for c in invalid_url_characters): + return '{1}'.format(url, escape_markup(unquote_url(url))) + # Escaped + return escape_markup(self.information) + + @property def magnet_uri(self): return create_magnet(self) diff --git a/nyaa/templates/view.html b/nyaa/templates/view.html index b2a7c48..5024eeb 100644 --- a/nyaa/templates/view.html +++ b/nyaa/templates/view.html @@ -34,7 +34,7 @@
Information:
{% if torrent.information %} - {{ torrent.information | escape }} + {{ torrent.information_as_link | safe }} {% else %} No information. {% endif%}