|
| 1 | +import uuid |
| 2 | +from urllib.parse import urlsplit |
| 3 | + |
| 4 | +from workers import Response, WorkerEntrypoint |
| 5 | + |
| 6 | +MAX_CODE_ATTEMPTS = 5 |
| 7 | + |
| 8 | + |
| 9 | +def error(message, status, allow=None): |
| 10 | + headers = {"Allow": allow} if allow else None |
| 11 | + return Response.json({"error": message}, status=status, headers=headers) |
| 12 | + |
| 13 | + |
| 14 | +def is_valid_destination(url): |
| 15 | + try: |
| 16 | + parsed = urlsplit(url) |
| 17 | + hostname = parsed.hostname |
| 18 | + _ = parsed.port |
| 19 | + except ValueError: |
| 20 | + return False |
| 21 | + return parsed.scheme in ("http", "https") and bool(hostname) |
| 22 | + |
| 23 | + |
| 24 | +class Default(WorkerEntrypoint): |
| 25 | + async def fetch(self, request): |
| 26 | + path = urlsplit(request.url).path |
| 27 | + |
| 28 | + if path == "/shorten": |
| 29 | + if request.method != "POST": |
| 30 | + return error("method not allowed", 405, allow="POST") |
| 31 | + return await self.shorten(request) |
| 32 | + |
| 33 | + if request.method != "GET": |
| 34 | + return error("method not allowed", 405, allow="GET") |
| 35 | + |
| 36 | + code = path.lstrip("/") |
| 37 | + if not code or "/" in code: |
| 38 | + return error("not found", 404) |
| 39 | + |
| 40 | + url = await self.env.LINKS.get(code) |
| 41 | + if url is None: |
| 42 | + return error("not found", 404) |
| 43 | + return Response.redirect(url, 302) |
| 44 | + |
| 45 | + async def shorten(self, request): |
| 46 | + try: |
| 47 | + body = await request.json() |
| 48 | + url = body["url"] |
| 49 | + except (KeyError, TypeError, ValueError): |
| 50 | + return error("request body must contain a URL", 400) |
| 51 | + |
| 52 | + if not isinstance(url, str) or not is_valid_destination(url): |
| 53 | + return error("url must be an absolute HTTP(S) URL", 400) |
| 54 | + |
| 55 | + for _ in range(MAX_CODE_ATTEMPTS): |
| 56 | + code = uuid.uuid4().hex[:8] |
| 57 | + |
| 58 | + if await self.env.LINKS.get(code) is not None: |
| 59 | + # Code already exists, try again |
| 60 | + continue |
| 61 | + |
| 62 | + await self.env.LINKS.put(code, url) |
| 63 | + origin = urlsplit(request.url) |
| 64 | + short_url = f"{origin.scheme}://{origin.netloc}/{code}" |
| 65 | + return Response.json( |
| 66 | + {"code": code, "short_url": short_url, "url": url}, status=201 |
| 67 | + ) |
| 68 | + |
| 69 | + return error("could not allocate a short code", 503) |
0 commit comments