| 1 |
import json |
| 2 |
import os |
| 3 |
import random |
| 4 |
import secrets |
| 5 |
import subprocess |
| 6 |
import tempfile |
| 7 |
from io import BytesIO |
| 8 |
|
| 9 |
from PIL import Image, ImageDraw, ImageFont |
| 10 |
from ranged_response import RangedFileResponse |
| 11 |
|
| 12 |
from django.core.exceptions import ImproperlyConfigured |
| 13 |
from django.http import Http404, HttpResponse |
| 14 |
|
| 15 |
from captcha.conf import settings |
| 16 |
from captcha.helpers import captcha_audio_url, captcha_image_url |
| 17 |
from captcha.models import CaptchaStore |
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
DISTANCE_FROM_TOP = 4 |
| 22 |
|
| 23 |
|
| 24 |
def getsize(font, text): |
| 25 |
if hasattr(font, "getbbox"): |
| 26 |
_top, _left, _right, _bottom = font.getbbox(text) |
| 27 |
return _right - _left, _bottom - _top |
| 28 |
elif hasattr(font, "getoffset"): |
| 29 |
return tuple([x + y for x, y in zip(font.getsize(text), font.getoffset(text))]) |
| 30 |
else: |
| 31 |
return font.getsize(text) |
| 32 |
|
| 33 |
|
| 34 |
def makeimg(size): |
| 35 |
if settings.CAPTCHA_BACKGROUND_COLOR == "transparent": |
| 36 |
image = Image.new("RGBA", size) |
| 37 |
else: |
| 38 |
image = Image.new("RGB", size, settings.CAPTCHA_BACKGROUND_COLOR) |
| 39 |
return image |
| 40 |
|
| 41 |
|
| 42 |
def add_noise(image): |
| 43 |
draw = ImageDraw.Draw(image) |
| 44 |
|
| 45 |
for f in settings.noise_functions(): |
| 46 |
draw = f(draw, image) |
| 47 |
for f in settings.filter_functions(): |
| 48 |
image = f(image) |
| 49 |
|
| 50 |
return image |
| 51 |
|
| 52 |
|
| 53 |
def _captcha_image(store, scale): |
| 54 |
text = store.challenge |
| 55 |
|
| 56 |
if isinstance(settings.CAPTCHA_FONT_PATH, str): |
| 57 |
fontpath = settings.CAPTCHA_FONT_PATH |
| 58 |
elif isinstance(settings.CAPTCHA_FONT_PATH, (list, tuple)): |
| 59 |
fontpath = random.choice(settings.CAPTCHA_FONT_PATH) |
| 60 |
else: |
| 61 |
raise ImproperlyConfigured( |
| 62 |
"settings.CAPTCHA_FONT_PATH needs to be a path to a font or list of paths to fonts" |
| 63 |
) |
| 64 |
|
| 65 |
if fontpath.lower().strip().endswith("ttf"): |
| 66 |
font = ImageFont.truetype(fontpath, settings.CAPTCHA_FONT_SIZE * scale) |
| 67 |
else: |
| 68 |
font = ImageFont.load(fontpath) |
| 69 |
|
| 70 |
if settings.CAPTCHA_IMAGE_SIZE: |
| 71 |
size = settings.CAPTCHA_IMAGE_SIZE |
| 72 |
else: |
| 73 |
size = getsize(font, text) |
| 74 |
size = (size[0] * 2, int(size[1] * 1.4)) |
| 75 |
|
| 76 |
image = makeimg(size) |
| 77 |
xpos = 2 |
| 78 |
|
| 79 |
charlist = [] |
| 80 |
for char in text: |
| 81 |
if char in settings.CAPTCHA_PUNCTUATION and len(charlist) >= 1: |
| 82 |
charlist[-1] += char |
| 83 |
else: |
| 84 |
charlist.append(char) |
| 85 |
|
| 86 |
if settings.CAPTCHA_ANIMATED: |
| 87 |
frames = [] |
| 88 |
|
| 89 |
for index, char in enumerate(charlist): |
| 90 |
|
| 91 |
|
| 92 |
if settings.CAPTCHA_ANIMATED: |
| 93 |
image = makeimg(size) |
| 94 |
|
| 95 |
fgimage = Image.new( |
| 96 |
"RGB", size, settings.get_letter_color(index, "".join(charlist)) |
| 97 |
) |
| 98 |
charimage = Image.new("L", getsize(font, " %s " % char), "#000000") |
| 99 |
chardraw = ImageDraw.Draw(charimage) |
| 100 |
chardraw.text((0, 0), " %s " % char, font=font, fill="#ffffff") |
| 101 |
if settings.CAPTCHA_LETTER_ROTATION: |
| 102 |
charimage = charimage.rotate( |
| 103 |
random.randrange(*settings.CAPTCHA_LETTER_ROTATION), |
| 104 |
expand=0, |
| 105 |
resample=Image.BICUBIC, |
| 106 |
) |
| 107 |
charimage = charimage.crop(charimage.getbbox()) |
| 108 |
maskimage = Image.new("L", size) |
| 109 |
|
| 110 |
maskimage.paste( |
| 111 |
charimage, |
| 112 |
( |
| 113 |
xpos, |
| 114 |
DISTANCE_FROM_TOP, |
| 115 |
xpos + charimage.size[0], |
| 116 |
DISTANCE_FROM_TOP + charimage.size[1], |
| 117 |
), |
| 118 |
) |
| 119 |
size = maskimage.size |
| 120 |
image = Image.composite(fgimage, image, maskimage) |
| 121 |
xpos = xpos + 2 + charimage.size[0] |
| 122 |
|
| 123 |
|
| 124 |
if settings.CAPTCHA_ANIMATED: |
| 125 |
image = add_noise(image) |
| 126 |
frames.append(image) |
| 127 |
|
| 128 |
if settings.CAPTCHA_ANIMATED: |
| 129 |
for i, frame in enumerate(frames): |
| 130 |
if settings.CAPTCHA_IMAGE_SIZE: |
| 131 |
|
| 132 |
tmpimg = makeimg(size) |
| 133 |
tmpimg.paste( |
| 134 |
frame, |
| 135 |
( |
| 136 |
int((size[0] - xpos) / 2), |
| 137 |
int((size[1] - charimage.size[1]) / 2 - DISTANCE_FROM_TOP), |
| 138 |
), |
| 139 |
) |
| 140 |
frames[i] = tmpimg.crop((0, 0, size[0], size[1])) |
| 141 |
else: |
| 142 |
frames[i] = frame.crop((0, 0, xpos + 1, size[1])) |
| 143 |
|
| 144 |
else: |
| 145 |
if settings.CAPTCHA_IMAGE_SIZE: |
| 146 |
|
| 147 |
tmpimg = makeimg(size) |
| 148 |
tmpimg.paste( |
| 149 |
image, |
| 150 |
( |
| 151 |
int((size[0] - xpos) / 2), |
| 152 |
int((size[1] - charimage.size[1]) / 2 - DISTANCE_FROM_TOP), |
| 153 |
), |
| 154 |
) |
| 155 |
image = tmpimg.crop((0, 0, size[0], size[1])) |
| 156 |
else: |
| 157 |
image = image.crop((0, 0, xpos + 1, size[1])) |
| 158 |
|
| 159 |
out = BytesIO() |
| 160 |
if settings.CAPTCHA_ANIMATED: |
| 161 |
frames[0].save( |
| 162 |
out, |
| 163 |
"AVIF" if settings.CAPTCHA_ANIMATED_USE_AVIF else "GIF", |
| 164 |
save_all=True, |
| 165 |
append_images=frames[1:], |
| 166 |
optimise=False, |
| 167 |
duration=500, |
| 168 |
loop=0, |
| 169 |
disposal=2, |
| 170 |
) |
| 171 |
content_type = ( |
| 172 |
"image/avif" if settings.CAPTCHA_ANIMATED_USE_AVIF else "image/gif" |
| 173 |
) |
| 174 |
|
| 175 |
else: |
| 176 |
image = add_noise(image) |
| 177 |
|
| 178 |
image.save(out, "PNG") |
| 179 |
content_type = "image/png" |
| 180 |
|
| 181 |
out.seek(0) |
| 182 |
response = HttpResponse(content_type=content_type) |
| 183 |
response.write(out.read()) |
| 184 |
response["Content-length"] = out.tell() |
| 185 |
|
| 186 |
return response |
| 187 |
|
| 188 |
|
| 189 |
def captcha_image(request, key, scale=1): |
| 190 |
if scale == 2 and not settings.CAPTCHA_2X_IMAGE: |
| 191 |
raise Http404 |
| 192 |
try: |
| 193 |
store = CaptchaStore.objects.get(hashkey=key) |
| 194 |
except CaptchaStore.DoesNotExist: |
| 195 |
|
| 196 |
return HttpResponse(status=410) |
| 197 |
|
| 198 |
try: |
| 199 |
random.seed(key) |
| 200 |
response = _captcha_image(store, scale) |
| 201 |
|
| 202 |
finally: |
| 203 |
|
| 204 |
|
| 205 |
|
| 206 |
|
| 207 |
|
| 208 |
random.seed() |
| 209 |
|
| 210 |
return response |
| 211 |
|
| 212 |
|
| 213 |
def captcha_audio(request, key): |
| 214 |
if settings.CAPTCHA_FLITE_PATH: |
| 215 |
try: |
| 216 |
store = CaptchaStore.objects.get(hashkey=key) |
| 217 |
except CaptchaStore.DoesNotExist: |
| 218 |
|
| 219 |
return HttpResponse(status=410) |
| 220 |
|
| 221 |
text = store.challenge |
| 222 |
if "captcha.helpers.math_challenge" == settings.CAPTCHA_CHALLENGE_FUNCT: |
| 223 |
text = text.replace("*", "times").replace("-", "minus").replace("+", "plus") |
| 224 |
else: |
| 225 |
text = ", ".join(list(text)) |
| 226 |
path = str( |
| 227 |
os.path.join(tempfile.gettempdir(), f"{key}_{secrets.token_urlsafe(6)}.wav") |
| 228 |
) |
| 229 |
subprocess.run([settings.CAPTCHA_FLITE_PATH, "-t", text, "-o", path]) |
| 230 |
|
| 231 |
|
| 232 |
if settings.CAPTCHA_SOX_PATH: |
| 233 |
try: |
| 234 |
sample_rate = ( |
| 235 |
subprocess.run( |
| 236 |
[settings.CAPTCHA_SOX_PATH, "--i", "-r", path], |
| 237 |
capture_output=True, |
| 238 |
) |
| 239 |
.stdout.decode() |
| 240 |
.strip() |
| 241 |
) |
| 242 |
|
| 243 |
except Exception: |
| 244 |
sample_rate = "8000" |
| 245 |
|
| 246 |
arbnoisepath = str( |
| 247 |
os.path.join( |
| 248 |
tempfile.gettempdir(), |
| 249 |
f"{key}_{secrets.token_urlsafe(6)}_noise.wav", |
| 250 |
) |
| 251 |
) |
| 252 |
subprocess.run( |
| 253 |
[ |
| 254 |
settings.CAPTCHA_SOX_PATH, |
| 255 |
"-r", |
| 256 |
sample_rate, |
| 257 |
"-n", |
| 258 |
arbnoisepath, |
| 259 |
"synth", |
| 260 |
"2", |
| 261 |
"brownnoise", |
| 262 |
"gain", |
| 263 |
"-15", |
| 264 |
] |
| 265 |
) |
| 266 |
mergedpath = str( |
| 267 |
os.path.join( |
| 268 |
tempfile.gettempdir(), |
| 269 |
f"{key}_{secrets.token_urlsafe(6)}_merged.wav", |
| 270 |
) |
| 271 |
) |
| 272 |
subprocess.run( |
| 273 |
[ |
| 274 |
settings.CAPTCHA_SOX_PATH, |
| 275 |
"-m", |
| 276 |
arbnoisepath, |
| 277 |
path, |
| 278 |
"-t", |
| 279 |
"wavpcm", |
| 280 |
"-b", |
| 281 |
"16", |
| 282 |
mergedpath, |
| 283 |
] |
| 284 |
) |
| 285 |
os.remove(arbnoisepath) |
| 286 |
os.remove(path) |
| 287 |
os.rename(mergedpath, path) |
| 288 |
|
| 289 |
if os.path.isfile(path): |
| 290 |
|
| 291 |
temporary_file = tempfile.TemporaryFile() |
| 292 |
with open(path, "rb") as original_file: |
| 293 |
temporary_file.write(original_file.read()) |
| 294 |
temporary_file.seek(0) |
| 295 |
os.remove(path) |
| 296 |
|
| 297 |
response = RangedFileResponse( |
| 298 |
request, temporary_file, content_type="audio/wav" |
| 299 |
) |
| 300 |
response["Content-Disposition"] = 'attachment; filename="{}.wav"'.format( |
| 301 |
key |
| 302 |
) |
| 303 |
return response |
| 304 |
raise Http404 |
| 305 |
|
| 306 |
|
| 307 |
def captcha_refresh(request): |
| 308 |
"""Return json with new captcha for ajax refresh request""" |
| 309 |
if not request.headers.get("x-requested-with") == "XMLHttpRequest": |
| 310 |
raise Http404 |
| 311 |
|
| 312 |
new_key = CaptchaStore.pick() |
| 313 |
to_json_response = { |
| 314 |
"key": new_key, |
| 315 |
"image_url": captcha_image_url(new_key), |
| 316 |
"audio_url": captcha_audio_url(new_key) |
| 317 |
if settings.CAPTCHA_FLITE_PATH |
| 318 |
else None, |
| 319 |
} |
| 320 |
return HttpResponse(json.dumps(to_json_response), content_type="application/json") |