md: add pclink for users

This commit is contained in:
Eldeberen 2021-02-20 17:36:36 +01:00
parent 9d08f81342
commit b5630e0079
Signed by untrusted user: Darks
GPG Key ID: 7515644268BE1433
1 changed files with 31 additions and 3 deletions

View File

@ -15,8 +15,9 @@ from markdown.extensions import Extension
from markdown.inlinepatterns import InlineProcessor
import xml.etree.ElementTree as etree
from flask import url_for, render_template
from app.utils.unicode_names import normalize
from app.models.poll import Poll
from app.models.user import Member
class PCLinkExtension(Extension):
def __init__(self, **kwargs):
@ -31,7 +32,7 @@ class PCLinkExtension(Extension):
self.md = md
# append to end of inline patterns
PCLINK_RE = r'\[\[([a-z]+):\W?(\w+)\]\]'
PCLINK_RE = r'\[\[([a-z]+): ?(\w+)\]\]'
pclinkPattern = PCLinksInlineProcessor(PCLINK_RE, self.getConfigs())
pclinkPattern.md = md
md.inlinePatterns.register(pclinkPattern, 'pclink', 75)
@ -43,6 +44,7 @@ class PCLinksInlineProcessor(InlineProcessor):
self.config = config
self.handles = {
'poll': handlePoll,
'user': handleUser,
}
def handleMatch(self, m, data):
@ -55,8 +57,16 @@ class PCLinksInlineProcessor(InlineProcessor):
return a, m.start(0), m.end(0)
# pclinks are links defined as [[type:content_id]]
# To add a custom handle, create a function and add it to processor's handles
# A custom handle takes two arguments:
# - content_id: as defined
# - context: the block in which the link has been found
# It should return:
# - either a string, which will be html-escaped
# - either an xml.etree.ElementTree
def handlePoll(content_id, context):
print(context)
if not context.startswith("[[") or not context.endswith("]]"):
return "[Sondage invalide]"
try:
@ -72,3 +82,21 @@ def handlePoll(content_id, context):
html = render_template('widgets/poll.html', poll=poll)
html = html.replace('\n', '') # Needed to avoid lots of <br> due to etree
return etree.fromstring(html)
def handleUser(content_id, context):
try:
norm = normalize(content_id)
except ValueError:
return "[Nom d'utilisateur invalide]"
member = Member.query.filter_by(norm=norm).first()
if member is None:
return "[Utilisateur non trouvé]"
a = etree.Element('a')
a.text = member.name
a.set('href', url_for('user_by_id', user_id=member.id))
a.set('class', 'profile-link')
return a