-
-
Notifications
You must be signed in to change notification settings - Fork 189
/
memes.py
356 lines (310 loc) · 11.4 KB
/
memes.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
import asyncio
from sanic import Blueprint, response
from sanic.log import logger
from sanic_openapi import doc
from .. import helpers, models, settings, utils
from .templates import generate_url
blueprint = Blueprint("Memes", url_prefix="/images")
@blueprint.get("/")
@doc.summary("List example memes")
@doc.operation("Memes.list")
@doc.consumes(
doc.String(
name="filter", description="Part of the template name or example to match"
),
location="query",
)
@doc.produces(
doc.List({"url": str, "template": str}),
description="Successfully returned a list of example memes",
content_type="application/json",
)
async def index(request):
query = request.args.get("filter", "").lower()
examples = await asyncio.to_thread(helpers.get_example_images, request, query)
return response.json(
[{"url": url, "template": template} for url, template in examples]
)
@blueprint.post("/")
@doc.summary("Create a meme from a template")
@doc.operation("Memes.create")
@doc.consumes(
doc.JsonBody(
{
"template_id": str,
"text_lines": [str],
"style": str,
"extension": str,
"redirect": bool,
}
),
content_type="application/json",
location="body",
)
@doc.response(201, {"url": str}, description="Successfully created a meme")
@doc.response(
400, {"error": str}, description='Required "template_id" missing in request body'
)
@doc.response(404, {"error": str}, description='Specified "template_id" does not exist')
async def create(request):
return await generate_url(request, template_id_required=True)
@blueprint.post("/automatic")
@doc.exclude(not settings.REMOTE_TRACKING_URL)
@doc.summary("Create a meme from word or phrase")
@doc.consumes(
doc.JsonBody({"text": str, "safe": bool, "redirect": bool}),
content_type="application/json",
location="body",
)
@doc.response(201, {"url": str}, description="Successfully created a meme")
@doc.response(
400, {"error": str}, description='Required "text" missing in request body'
)
async def automatic(request):
if request.form:
payload = dict(request.form)
else:
payload = request.json or {}
try:
text = payload["text"]
except KeyError:
return response.json({"error": '"text" is required'}, status=400)
results = await utils.meta.search(request, text, payload.get("safe", True))
logger.info(f"Found {len(results)} result(s)")
if not results:
return response.json({"message": f"No results matched: {text}"}, status=404)
url = utils.urls.normalize(results[0]["image_url"])
logger.info(f"Top result: {url}")
url, _updated = await utils.meta.tokenize(request, url)
if payload.get("redirect", False):
return response.redirect(url)
return response.json({"url": url}, status=201)
@blueprint.post("/custom")
@doc.summary("Create a meme from any image")
@doc.consumes(
doc.JsonBody(
{
"background": str,
"style": str,
"text_lines": [str],
"extension": str,
"redirect": bool,
}
),
content_type="application/json",
location="body",
)
@doc.response(
201, {"url": str}, description="Successfully created a meme from a custom image"
)
async def custom(request):
return await generate_url(request)
@blueprint.get("/custom")
@doc.summary("List popular custom memes")
@doc.operation("Memes.list_custom")
@doc.consumes(
doc.Boolean(name="safe", description="Exclude NSFW results"),
content_type="application/json",
location="query",
)
@doc.consumes(
doc.String(name="filter", description="Part of the meme's text to match"),
location="query",
)
@doc.produces(
doc.List({"url": str}),
description="Successfully returned a list of custom memes",
content_type="application/json",
)
async def list_custom(request):
query = request.args.get("filter", "").lower()
safe = request.args.get("safe", "true").lower() not in {"false", "no"}
results = await utils.meta.search(request, query, safe, mode="results")
logger.info(f"Found {len(results)} result(s)")
if not results:
return response.json({"message": f"No results matched: {query}"}, status=404)
items = []
for result in results:
url = utils.urls.normalize(result["image_url"])
url, _updated = await utils.meta.tokenize(request, url)
items.append({"url": url})
return response.json(items, status=200)
@blueprint.get("/<template_id>.png")
@doc.tag("Templates")
@doc.summary("Display a template background")
@doc.consumes(doc.String(name="template_id"), location="path")
@doc.produces(
doc.File(),
description="Successfully displayed a template background",
content_type="image/png",
)
@doc.response(404, doc.File(), description="Template not found")
@doc.response(415, doc.File(), description="Unable to download image URL")
@doc.response(
422,
doc.File(),
description="Invalid style for template or no image URL specified for custom template",
)
async def blank_png(request, template_id):
return await render_image(request, template_id, ext="png")
@blueprint.get("/<template_id>.jpg")
@doc.tag("Templates")
@doc.summary("Display a template background")
@doc.consumes(doc.String(name="template_id"), location="path")
@doc.produces(
doc.File(),
description="Successfully displayed a template background",
content_type="image/jpeg",
)
@doc.response(404, doc.File(), description="Template not found")
@doc.response(415, doc.File(), description="Unable to download image URL")
@doc.response(
422,
doc.File(),
description="Invalid style for template or no image URL specified for custom template",
)
async def blank_jpg(request, template_id):
return await render_image(request, template_id, ext="jpg")
@blueprint.get("/<template_id>/<text_paths:[\\s\\S]+>.png")
@doc.summary("Display a custom meme")
@doc.consumes(doc.String(name="text_paths"), location="path")
@doc.consumes(doc.String(name="template_id"), location="path")
@doc.produces(
doc.File(),
description="Successfully displayed a custom meme",
content_type="image/png",
)
@doc.response(404, doc.File(), description="Template not found")
@doc.response(414, doc.File(), description="Custom text too long (length >200)")
@doc.response(415, doc.File(), description="Unable to download image URL")
@doc.response(
422,
doc.File(),
description="Invalid style for template or no image URL specified for custom template",
)
async def text_png(request, template_id, text_paths):
slug, updated = utils.text.normalize(text_paths)
if updated:
url = request.app.url_for(
"Memes.text_png",
template_id=template_id,
text_paths=slug,
**request.args,
)
return response.redirect(utils.urls.clean(url), status=301)
url, updated = await utils.meta.tokenize(request, request.url)
if updated:
return response.redirect(url, status=302)
watermark, updated = await utils.meta.get_watermark(request)
if updated:
params = {k: v for k, v in request.args.items() if k != "watermark"}
url = request.app.url_for(
"Memes.text_png",
template_id=template_id,
text_paths=slug,
**params,
)
return response.redirect(utils.urls.clean(url), status=302)
return await render_image(request, template_id, slug, watermark)
@blueprint.get("/<template_id>/<text_paths:[\\s\\S]+>.jpg")
@doc.summary("Display a custom meme")
@doc.consumes(doc.String(name="text_paths"), location="path")
@doc.consumes(doc.String(name="template_id"), location="path")
@doc.produces(
doc.File(),
description="Successfully displayed a custom meme",
content_type="image/jpeg",
)
@doc.response(404, doc.File(), description="Template not found")
@doc.response(414, doc.File(), description="Custom text too long (length >200)")
@doc.response(415, doc.File(), description="Unable to download image URL")
@doc.response(
422,
doc.File(),
description="Invalid style for template or no image URL specified for custom template",
)
async def text_jpg(request, template_id, text_paths):
slug, updated = utils.text.normalize(text_paths)
if updated:
url = request.app.url_for(
"Memes.text_jpg",
template_id=template_id,
text_paths=slug,
**request.args,
)
return response.redirect(utils.urls.clean(url), status=301)
url, updated = await utils.meta.tokenize(request, request.url)
if updated:
return response.redirect(url, status=302)
watermark, updated = await utils.meta.get_watermark(request)
if updated:
params = {k: v for k, v in request.args.items() if k != "watermark"}
url = request.app.url_for(
"Memes.text_jpg",
template_id=template_id,
text_paths=slug,
**params,
)
return response.redirect(utils.urls.clean(url), status=302)
return await render_image(request, template_id, slug, watermark, ext="jpg")
async def render_image(
request,
id: str,
slug: str = "",
watermark: str = "",
ext: str = settings.DEFAULT_EXT,
):
lines = utils.text.decode(slug)
asyncio.create_task(utils.meta.track(request, lines))
status = 200
if len(slug.encode()) > 200:
logger.error(f"Slug too long: {slug}")
slug = slug[:50] + "..."
lines = utils.text.decode(slug)
template = models.Template.objects.get("_error")
style = settings.DEFAULT_STYLE
status = 414
elif id == "custom":
url = utils.urls.arg(request, None, "background", "alt")
if url:
template = await models.Template.create(url)
if not template.image.exists():
logger.error(f"Unable to download image URL: {url}")
template = models.Template.objects.get("_error")
if url != settings.PLACEHOLDER:
status = 415
style = utils.urls.arg(request, settings.DEFAULT_STYLE, "style")
if not utils.urls.schema(style):
style = style.lower()
if not await template.check(style):
if utils.urls.schema(style):
status = 415
elif style != settings.PLACEHOLDER:
status = 422
else:
logger.error("No image URL specified for custom template")
template = models.Template.objects.get("_error")
style = settings.DEFAULT_STYLE
status = 422
else:
template = models.Template.objects.get_or_none(id)
if not template or not template.image.exists():
logger.error(f"No such template: {id}")
template = models.Template.objects.get("_error")
if id != settings.PLACEHOLDER:
status = 404
style = utils.urls.arg(request, settings.DEFAULT_STYLE, "style", "alt")
if not await template.check(style):
if utils.urls.schema(style):
status = 415
elif style != settings.PLACEHOLDER:
status = 422
try:
size = int(request.args.get("width", 0)), int(request.args.get("height", 0))
except ValueError:
size = 0, 0
status = 422
path = await asyncio.to_thread(
utils.images.save, template, lines, watermark, ext=ext, style=style, size=size
)
return await response.file(path, status)