Skip to content

Commit

Permalink
Some fixes
Browse files Browse the repository at this point in the history
- urllib.quote_plus the url attributes
- Match link domain more precisely.
- Image height or width can be individually specified
  • Loading branch information
sayanarijit committed Feb 9, 2024
1 parent 5b5d8cf commit 908cc18
Show file tree
Hide file tree
Showing 6 changed files with 61 additions and 44 deletions.
51 changes: 30 additions & 21 deletions tiptapy/__init__.py
Original file line number Diff line number Diff line change
@@ -1,31 +1,39 @@
import json
import os
import sys
import json
from html import escape
from jinja2 import FileSystemLoader, Environment, select_autoescape
from typing import Dict
from .image import url2mime
from .macros import (make_img_src, build_link_handler,
get_audio_player_block, get_doc_block)

from jinja2 import Environment, FileSystemLoader, select_autoescape

__version__ = '0.17.0'
from .image import url2mime
from .macros import (
build_link_handler,
get_audio_player_block,
get_doc_block,
make_img_src,
quote_plus,
)

__version__ = "0.18.0"

renderers: Dict = {}


def init_env(path, config):
env = Environment(loader=FileSystemLoader(path),
autoescape=select_autoescape(
enabled_extensions=('html')))
env = Environment(
loader=FileSystemLoader(path),
autoescape=select_autoescape(enabled_extensions=("html")),
)
# https://stackoverflow.com/a/6038550
env.globals['url2mime'] = url2mime
env.globals['make_img_src'] = make_img_src
env.globals['handle_links'] = build_link_handler(config)
env.globals["url2mime"] = url2mime
env.globals["make_img_src"] = make_img_src
env.globals["handle_links"] = build_link_handler(config)
# Cause jinja2 `e` filter is not exactly same as html.escape
env.globals['escape'] = escape
env.globals['get_audio_player_block'] = get_audio_player_block
env.globals['get_doc_block'] = get_doc_block
env.globals["escape"] = escape
env.globals["get_audio_player_block"] = get_audio_player_block
env.globals["get_doc_block"] = get_doc_block
env.globals["quote_plus"] = quote_plus

return env

Expand All @@ -40,19 +48,20 @@ def _get_abs_template_path(path_str):


class BaseDoc:

doc_type = 'doc'
templates_path = (_get_abs_template_path('templates'),
_get_abs_template_path('templates/extras'))
doc_type = "doc"
templates_path = (
_get_abs_template_path("templates"),
_get_abs_template_path("templates/extras"),
)
locked = False
# `locked` helps in templates determine to show/hide in anonymous views
# Useful in case where code is referring same template for both protected
# and guest views

def __init__(self, config):
environ = init_env(self.templates_path, config)
self.t = environ.get_template(f'{self.doc_type}.html')
self.t.environment.globals['locked'] = self.locked
self.t = environ.get_template(f"{self.doc_type}.html")
self.t.environment.globals["locked"] = self.locked

def render(self, in_data):
in_data = in_data if isinstance(in_data, dict) else json.loads(in_data)
Expand Down
38 changes: 23 additions & 15 deletions tiptapy/macros.py
Original file line number Diff line number Diff line change
@@ -1,32 +1,36 @@
import pkgutil
from html import escape
from urllib.parse import urlparse
from string import Template
from urllib.parse import quote_plus, urlparse


def make_img_src(attrs):
alt = attrs.get('alt', '').strip()
height = attrs.get('height', '')
width = attrs.get('width', '')
fallback_url = attrs['src']['fallback']
alt = attrs.get("alt", "").strip()
height = attrs.get("height", "")
width = attrs.get("width", "")
fallback_url = quote_plus(attrs["src"]["fallback"]).strip()
image_src = f'img src="{fallback_url}"'
if alt:
image_src += f' alt="{escape(alt)}"'
if height and width:
image_src += f'width="{width}" height="{height}"'
if width:
image_src += f' width="{width}"'
if height:
image_src += f' height="{height}"'

return image_src


def build_link_handler(config):

def handle_links(attrs):

retval = None
if attrs:
url = attrs.get("href") or ""
url = quote_plus(attrs.pop("href", "")).strip()
link = urlparse(url)
if not link.netloc.endswith(config.DOMAIN):
if not (
link.netloc == config.DOMAIN
or link.netloc.endswith(f".{config.DOMAIN}")
):
attrs["href"] = url
attrs["target"] = "_blank"
attrs["rel"] = "noopener nofollow"
retval = " ".join(
Expand All @@ -39,13 +43,17 @@ def handle_links(attrs):

def get_audio_player_block():
audio_player_block = pkgutil.get_data(
__name__, 'templates/stack-audio-player.html').decode()
__name__, "templates/stack-audio-player.html"
).decode()
return audio_player_block


def get_doc_block(ext, fname, size, src):
document_block = pkgutil.get_data(__name__, 'templates/stack-document.html').decode()
document_block = pkgutil.get_data(
__name__, "templates/stack-document.html"
).decode()
document = Template(document_block)
html = document.substitute(fileformat=ext[:4], filename=fname,
filesize=size, filesrc=src)
html = document.substitute(
fileformat=ext[:4], filename=fname, filesize=size, filesrc=src
)
return html
4 changes: 2 additions & 2 deletions tiptapy/templates/extras/audio.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@

<figure class="audio-player-container">
{%- if caption -%}
<div><audio src={{node.attrs.src|trim}}></audio>{{audio_player_block}}</div><figcaption>{{escape(caption)}}</figcaption>
<div><audio src={{node.attrs.src|trim|quote_plus}}></audio>{{audio_player_block}}</div><figcaption>{{escape(caption)}}</figcaption>
{%- else -%}
<div><audio src={{node.attrs.src|trim}}></audio>{{audio_player_block}}</div>
<div><audio src={{node.attrs.src|trim|quote_plus}}></audio>{{audio_player_block}}</div>
{%- endif -%}
</figure>
{%- endif -%}
4 changes: 2 additions & 2 deletions tiptapy/templates/extras/document.html
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{%- set caption = node.attrs.caption|trim -%}
{%- set src = node.attrs.src|trim -%}
{%- set src = node.attrs.src|trim|quote_plus -%}
{%- set size = node.attrs.size|trim -%}
{%- set fname = node.attrs.name|trim -%}
{%- set fname = node.attrs.name|trim|quote_plus -%}
{%- set ext = node.attrs.format|trim -%}
{%- if src and size and fname and ext -%}
{%- set doc_block = get_doc_block(ext, fname, size, src) -%}
Expand Down
4 changes: 2 additions & 2 deletions tiptapy/templates/extras/featuredimage.html
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{%- if node.attrs.src -%}
{%- set image_url = node.attrs.src.image -%}
{%- set image_url = node.attrs.src.image|trim|quote_plus -%}
{%- set image_type = url2mime(image_url) -%}
{%- set fallback_url = node.attrs['src']['fallback'] -%}
{%- set fallback_url = node.attrs.src.fallback|trim|quote_plus -%}
{%- set fallback_type = url2mime(fallback_url) -%}

{%- set caption = node.attrs.caption|trim -%}
Expand Down
4 changes: 2 additions & 2 deletions tiptapy/templates/image.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
{%- set alt = node.attrs.alt|trim -%}
{%- set height = node.attrs.height -%}
{%- set width = node.attrs.width -%}
{%- set image_url = node.attrs.src.image -%}
{%- set image_url = node.attrs.src.image|trim|quote_plus -%}
{%- set image_type = url2mime(image_url) -%}
{%- set fallback_url = node.attrs['src']['fallback'] -%}
{%- set fallback_url = node.attrs.src.fallback|trim|quote_plus -%}
{%- set fallback_type = url2mime(fallback_url) -%}

{%- if image_url or fallback_url -%}
Expand Down

0 comments on commit 908cc18

Please sign in to comment.