import creole from django.conf import settings from django.urls.base import reverse from .help import MYCREOLE_HELP import importlib import os import shutil def get_full_path(rel_path): try: return os.path.join(settings.MYCREOLE_ROOT, *rel_path.split('/')) except AttributeError: raise AttributeError("You need to define a root directory for mycreole in settings.py: MYCREOLE_ROOT") def delete_attachment_target_path(attachment_target_path): shutil.rmtree(get_full_path(attachment_target_path), True) def mycreole_help_pagecontent(): return creole.creole2html(MYCREOLE_HELP) def render_simple(text): return creole.creole2html(text) def render(request, text, attachment_target_path, next_anchor=''): def get_attachment_name(text, state): end_idx = text.index(']]' if state == '[' else '}}') try: split_idx = text.index('|') except ValueError: split_idx = len(text) return text[:min(end_idx, split_idx)] # Call the additional filters before rendering try: ext_filters = settings.MYCREOLE_EXT_FILTERS except AttributeError: pass # No filters defined else: for function_string in ext_filters: m_name, f_name = function_string.rsplit('.', 1) try: mod = importlib.import_module(m_name) except ModuleNotFoundError: pass else: try: func = getattr(mod, f_name) except AttributeError: pass else: text = func(text) if not attachment_target_path.endswith('/'): attachment_target_path += '/' try: render_txt = '' while len(text) > 0: try: link_pos = text.index('[[attachment:') except ValueError: link_pos = len(text) try: embed_pos = text.index('{{attachment:') except ValueError: embed_pos = len(text) pos = min(link_pos, embed_pos) render_txt += text[:pos] text = text[pos + 13:] if link_pos != embed_pos: if link_pos < embed_pos: state = '[' else: state = '{' attachment_name = get_attachment_name(text, state) text = text[len(attachment_name):] rel_path = attachment_target_path + attachment_name if os.path.isfile(get_full_path(rel_path)): render_txt += 2 * state + url_attachment(rel_path) else: render_txt += '[[%s|Upload]]' % url_upload(request, rel_path, next_anchor) text = text[text.index(']]' if state == '[' else '}}') + 2:] return creole.creole2html(render_txt) except: return creole.creole2html(text) def url_delete(request, rel_path, next_anchor=''): nxt = request.GET.get('next', request.get_full_path()) return reverse('mycreole-delete', kwargs={'rel_path': rel_path}) + '?next=%s' % nxt + ('' if not next_anchor else '#%s' % next_anchor) def url_upload(request, rel_path, next_anchor=''): nxt = request.GET.get('next', request.get_full_path()) return reverse('mycreole-upload', kwargs={'rel_path': rel_path}) + '?next=%s' % nxt + ('' if not next_anchor else '#%s' % next_anchor) def url_attachment(rel_path): return reverse('mycreole-attachment', kwargs={'rel_path': rel_path}) def url_manage_uploads(request, rel_path): nxt = request.GET.get('next', request.get_full_path()) return reverse('mycreole-manageuploads', kwargs={'rel_path': rel_path}) + '?next=%s' % nxt