Skip to content
This repository was archived by the owner on Apr 26, 2024. It is now read-only.

Replace username picker with a template #9275

Merged
merged 7 commits into from
Feb 1, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Factor build_jinja_env out to a separate module
I want to be able to build jinja envs outside of configs, so pull out a new
function.
  • Loading branch information
richvdh committed Feb 1, 2021
commit 8243ab250a1a87d9d25c5a3d88eca68da6caabcc
39 changes: 4 additions & 35 deletions synapse/config/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,18 +18,18 @@
import argparse
import errno
import os
import time
import urllib.parse
from collections import OrderedDict
from hashlib import sha256
from textwrap import dedent
from typing import Any, Callable, Iterable, List, MutableMapping, Optional
from typing import Any, Iterable, List, MutableMapping, Optional

import attr
import jinja2
import pkg_resources
import yaml

from synapse.util.templates import _create_mxc_to_http_filter, _format_ts_filter


class ConfigError(Exception):
"""Represents a problem parsing the configuration
Expand Down Expand Up @@ -248,6 +248,7 @@ def read_templates(
# Search the custom template directory as well
search_directories.insert(0, custom_template_directory)

# TODO: switch to synapse.util.templates.build_jinja_env
loader = jinja2.FileSystemLoader(search_directories)
env = jinja2.Environment(loader=loader, autoescape=autoescape)

Expand All @@ -267,38 +268,6 @@ def read_templates(
return templates


def _format_ts_filter(value: int, format: str):
return time.strftime(format, time.localtime(value / 1000))


def _create_mxc_to_http_filter(public_baseurl: str) -> Callable:
"""Create and return a jinja2 filter that converts MXC urls to HTTP

Args:
public_baseurl: The public, accessible base URL of the homeserver
"""

def mxc_to_http_filter(value, width, height, resize_method="crop"):
if value[0:6] != "mxc://":
return ""

server_and_media_id = value[6:]
fragment = None
if "#" in server_and_media_id:
server_and_media_id, fragment = server_and_media_id.split("#", 1)
fragment = "#" + fragment

params = {"width": width, "height": height, "method": resize_method}
return "%s_matrix/media/v1/thumbnail/%s?%s%s" % (
public_baseurl,
server_and_media_id,
urllib.parse.urlencode(params),
fragment or "",
)

return mxc_to_http_filter


class RootConfig:
"""
Holder of an application's configuration.
Expand Down
1 change: 1 addition & 0 deletions synapse/rest/consent/consent_resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ def __init__(self, hs):

consent_template_directory = hs.config.user_consent_template_dir

# TODO: switch to synapse.util.templates.build_jinja_env
loader = jinja2.FileSystemLoader(consent_template_directory)
self._jinja_env = jinja2.Environment(
loader=loader, autoescape=jinja2.select_autoescape(["html", "htm", "xml"])
Expand Down
106 changes: 106 additions & 0 deletions synapse/util/templates.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
# -*- coding: utf-8 -*-
# Copyright 2021 The Matrix.org Foundation C.I.C.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Utilities for dealing with jinja2 templates"""

import time
import urllib.parse
from typing import TYPE_CHECKING, Callable, Iterable, Union

import jinja2

if TYPE_CHECKING:
from synapse.config.homeserver import HomeServerConfig


def build_jinja_env(
template_search_directories: Iterable[str],
config: "HomeServerConfig",
autoescape: Union[bool, Callable[[str], bool], None] = None,
) -> jinja2.Environment:
"""Set up a Jinja2 environment to load templates from the given search path

The returned environment defines the following filters:
- format_ts: formats timestamps as strings in the server's local timezone
(XXX: why is that useful??)
- mxc_to_http: converts mxc: uris to http URIs. Args are:
(uri, width, height, resize_method="crop")

and the following global variables:
- server_name: matrix server name

Args:
template_search_directories: directories to search for templates

config: homeserver config, for things like `server_name` and `public_baseurl`

autoescape: whether template variables should be autoescaped. bool, or
a function mapping from template name to bool. Defaults to escaping templates
whose names end in .html, .xml or .htm.

Returns:
jinja environment
"""

if autoescape is None:
autoescape = jinja2.select_autoescape()

loader = jinja2.FileSystemLoader(template_search_directories)
env = jinja2.Environment(loader=loader, autoescape=autoescape)

# Update the environment with our custom filters
env.filters.update(
{
"format_ts": _format_ts_filter,
"mxc_to_http": _create_mxc_to_http_filter(config.public_baseurl),
}
)

# common variables for all templates
env.globals.update({"server_name": config.server_name})

return env


def _create_mxc_to_http_filter(public_baseurl: str) -> Callable:
"""Create and return a jinja2 filter that converts MXC urls to HTTP

Args:
public_baseurl: The public, accessible base URL of the homeserver
"""

def mxc_to_http_filter(value, width, height, resize_method="crop"):
if value[0:6] != "mxc://":
return ""

server_and_media_id = value[6:]
fragment = None
if "#" in server_and_media_id:
server_and_media_id, fragment = server_and_media_id.split("#", 1)
fragment = "#" + fragment

params = {"width": width, "height": height, "method": resize_method}
return "%s_matrix/media/v1/thumbnail/%s?%s%s" % (
public_baseurl,
server_and_media_id,
urllib.parse.urlencode(params),
fragment or "",
)

return mxc_to_http_filter


def _format_ts_filter(value: int, format: str):
return time.strftime(format, time.localtime(value / 1000))