Skip to content

Commit

Permalink
Reuse template from custom image URL
Browse files Browse the repository at this point in the history
  • Loading branch information
jacebrowning committed Oct 24, 2020
1 parent c9f1e3a commit c4a7d2d
Show file tree
Hide file tree
Showing 4 changed files with 13 additions and 5 deletions.
4 changes: 2 additions & 2 deletions app/helpers.py
Expand Up @@ -38,13 +38,13 @@ def configure(app):
app.error_handler = errors.BugsnagErrorHandler()


@cached({}, key=lambda _: settings.SERVER_NAME) # type: ignore
@cached({}, key=lambda x: 0 if settings.DEPLOYED else x) # type: ignore
def get_valid_templates(request) -> List[Dict]:
templates = Template.objects.filter(valid=True, _exclude="_custom")
return [t.jsonify(request.app) for t in templates]


@cached({}, key=lambda _: settings.SERVER_NAME) # type: ignore
@cached({}, key=lambda x: 0 if settings.DEPLOYED else x) # type: ignore
def get_sample_images(request) -> List[Tuple[str, str]]:
return [
(template.build_sample_url(request.app), template.build_self_url(request.app))
Expand Down
7 changes: 4 additions & 3 deletions app/models.py
@@ -1,6 +1,7 @@
import hashlib
from pathlib import Path
from typing import Dict, List, Optional
from urllib.parse import urlparse

import aiofiles
import aiohttp
Expand Down Expand Up @@ -167,14 +168,14 @@ def build_custom_url(

@classmethod
async def create(cls, url: str) -> "Template":
if "memegen.link/images" in url:
parts = urlparse(url)
if "memegen.link" in parts.netloc:
logger.debug(f"Handling builtin template: {url}")
key = url.split("memegen.link/images/")[-1].split(".")[0]
key = parts.path.split(".")[0].split("/")[2]
return cls.objects.get(key)

key = "_custom-" + hashlib.sha1(url.encode()).hexdigest()
template = cls.objects.get_or_create(key, url)

if template.image.exists() and not settings.DEBUG:
logger.info(f"Found background {url} at {template.image}")

Expand Down
1 change: 1 addition & 0 deletions app/tests/test_images.py
Expand Up @@ -138,6 +138,7 @@ def test_text_wrap_when_font_is_too_small(images):
utils.images.save(template, lines, directory=images)


@pytest.mark.slow
def test_descender_vertical_alignment(images):
template = models.Template.objects.get("ptj")
lines = [
Expand Down
6 changes: 6 additions & 0 deletions app/tests/test_models.py
Expand Up @@ -94,3 +94,9 @@ async def it_handles_builtin_templates(expect):
url = "http://api.memegen.link/images/fry.png"
template = await Template.create(url)
expect(template.key) == "fry"

@pytest.mark.asyncio
async def it_handles_custom_image_urls(expect):
url = "http://api.memegen.link/images/fry/test.png"
template = await Template.create(url)
expect(template.key) == "fry"

0 comments on commit c4a7d2d

Please sign in to comment.