From b5630e007993e9ff5218ec920286f2ea29763090 Mon Sep 17 00:00:00 2001 From: Eldeberen Date: Sat, 20 Feb 2021 17:36:36 +0100 Subject: [PATCH] md: add pclink for users --- app/utils/markdown_extensions/pclinks.py | 34 +++++++++++++++++++++--- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/app/utils/markdown_extensions/pclinks.py b/app/utils/markdown_extensions/pclinks.py index fb533ad..6a68376 100644 --- a/app/utils/markdown_extensions/pclinks.py +++ b/app/utils/markdown_extensions/pclinks.py @@ -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
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