|
4 | 4 | from django.conf import settings |
5 | 5 | from django.contrib.auth.mixins import PermissionRequiredMixin |
6 | 6 | from django.contrib.auth.models import User |
7 | | -from django.db import transaction |
8 | | -from django.http import HttpRequest, HttpResponse, HttpResponseNotFound |
| 7 | +from django.db import IntegrityError, transaction |
| 8 | +from django.http import HttpRequest, HttpResponse, HttpResponseNotFound, JsonResponse |
9 | 9 | from django.shortcuts import redirect, render |
| 10 | +from django.utils.crypto import get_random_string |
10 | 11 | from django.utils.http import url_has_allowed_host_and_scheme |
11 | 12 | from django.views import View |
12 | 13 | from qgis_server_light.interface.common import BBox |
|
46 | 47 | Theme, |
47 | 48 | ThemesJson, |
48 | 49 | ) |
49 | | -from georama.webgis.models import LayerGroupMp, PublishedAsLayerWms, PublishedAsTheme |
| 50 | +from georama.webgis.models import ( |
| 51 | + LayerGroupMp, |
| 52 | + PublishedAsLayerWms, |
| 53 | + PublishedAsTheme, |
| 54 | + UrlShortener, |
| 55 | +) |
50 | 56 | from georama.webgis.models import OgcServer as WebGisOgcServer |
51 | 57 |
|
52 | 58 |
|
@@ -616,3 +622,33 @@ def translation_json(request: HttpRequest): |
616 | 622 | return HttpResponse( |
617 | 623 | json.dumps(translation, indent=2), status=200, content_type="application/json" |
618 | 624 | ) |
| 625 | + |
| 626 | + |
| 627 | +class UrlShortenerCreate(View): |
| 628 | + def post(self, request: HttpRequest): |
| 629 | + url = request.POST.get("url", "").strip() |
| 630 | + if not url: |
| 631 | + return JsonResponse({"error": "Missing URL."}, status=400) |
| 632 | + |
| 633 | + if not url.startswith(settings.WEBGISURL): |
| 634 | + return JsonResponse({"error": "Invalid URL."}, status=400) |
| 635 | + |
| 636 | + while True: |
| 637 | + try: |
| 638 | + short = UrlShortener.objects.create(id=get_random_string(length=6), url=url) |
| 639 | + break |
| 640 | + except IntegrityError: |
| 641 | + continue |
| 642 | + |
| 643 | + short_url = request.build_absolute_uri(f"/webgis/short/get/{short.id}") |
| 644 | + return JsonResponse({"short_url": short_url}, status=201) |
| 645 | + |
| 646 | + |
| 647 | +class UrlShortenerRetrieve(View): |
| 648 | + def get(self, _request: HttpRequest, id: str): |
| 649 | + try: |
| 650 | + short = UrlShortener.objects.get(id=id) |
| 651 | + except UrlShortener.DoesNotExist: |
| 652 | + return JsonResponse({"error": "Not found."}, status=404) |
| 653 | + |
| 654 | + return JsonResponse({"long_url": short.url}, status=200) |
0 commit comments