2018-08-07 16:55:22 +01:00
|
|
|
from urllib.parse import urlparse
|
2015-01-17 23:54:26 +00:00
|
|
|
from django.shortcuts import render, redirect
|
2015-01-18 01:37:28 +00:00
|
|
|
from django.http import Http404, HttpResponse
|
2015-01-18 15:35:07 +00:00
|
|
|
from django.db.models import F
|
2015-01-18 00:24:13 +00:00
|
|
|
from django.contrib import messages
|
2015-01-17 23:54:26 +00:00
|
|
|
from .models import Link, LinkForm
|
|
|
|
|
2015-01-18 01:37:28 +00:00
|
|
|
|
|
|
|
def get_client_ip(request):
|
2015-01-18 14:55:53 +00:00
|
|
|
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
|
|
|
|
if x_forwarded_for:
|
|
|
|
ip = x_forwarded_for.split(',')[0]
|
|
|
|
else:
|
|
|
|
ip = request.META.get('REMOTE_ADDR')
|
|
|
|
return ip
|
2015-01-18 01:37:28 +00:00
|
|
|
|
|
|
|
|
2015-01-17 23:54:26 +00:00
|
|
|
def catchall(request, id):
|
2015-01-18 14:55:53 +00:00
|
|
|
try:
|
|
|
|
link = Link.objects.get(id=id)
|
|
|
|
parsed = urlparse(link.url)
|
2015-01-18 15:35:07 +00:00
|
|
|
Link.objects.filter(id=id).update(clicks=F('clicks')+1)
|
2015-01-18 14:55:53 +00:00
|
|
|
if parsed.scheme:
|
|
|
|
return redirect(link.url)
|
2025-05-30 09:25:57 +01:00
|
|
|
return redirect("https://" + link.url)
|
2015-01-18 14:55:53 +00:00
|
|
|
except Exception as e:
|
2015-01-18 15:35:07 +00:00
|
|
|
return HttpResponse(e)
|
2015-01-18 14:55:53 +00:00
|
|
|
parsed = urlparse(id)
|
|
|
|
if parsed.netloc:
|
|
|
|
link = Link(url=id, ip=get_client_ip(request))
|
|
|
|
link.save()
|
2025-05-30 09:25:57 +01:00
|
|
|
request.session['short_url'] = "https://" + str(request.get_host()) + "/" + str(link.id)
|
2015-01-18 14:55:53 +00:00
|
|
|
return redirect('/')
|
|
|
|
raise Http404("Link does not exist")
|
2015-01-18 01:37:28 +00:00
|
|
|
|
2015-01-17 23:54:26 +00:00
|
|
|
|
|
|
|
def home(request):
|
2015-01-18 14:55:53 +00:00
|
|
|
context = {'form': LinkForm}
|
|
|
|
if 'short_url' in request.session and request.session['short_url']:
|
|
|
|
context['short_url'] = request.session['short_url']
|
|
|
|
request.session['short_url'] = None
|
|
|
|
if 'url' in request.POST:
|
|
|
|
link = Link(url=request.POST['url'], ip=get_client_ip(request))
|
|
|
|
link.save()
|
2025-05-30 09:25:57 +01:00
|
|
|
request.session['short_url'] = "https://" + request.get_host() + "/" + link.id
|
2015-01-18 14:55:53 +00:00
|
|
|
return redirect('/')
|
|
|
|
return render(request, 'index.html', context)
|