Commit 87ac273f authored by Jean Michel Rouly's avatar Jean Michel Rouly
Browse files

Merged conflicts

parents aeca678a 818b7d8b
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
import random, string
# Create your models here.
class URL( models.Model ):
"""
This model represents a stored URL redirection rule. Each URL has an
owner, target url, short identifier, click counter, and expiration
date.
"""
owner = models.ForeignKey( User )
date_created = models.DateTimeField( default=timezone.now() )
......@@ -34,16 +39,24 @@ class URL( models.Model ):
if tries > 100:
return None
class RegisteredUser( models.Model ):
"""
This is simply a wrapper model which, if an object exists, indicates
that that user is registered.
"""
username = models.CharField(
blank = False,
max_length = 30,
primary_key = True
)
full_name = models.CharField(
blank = False,
max_length = 100,
)
description = models.TextField( blank=True )
def __unicode__(self):
......
......@@ -2,7 +2,7 @@ from go.models import URL, RegisteredUser
from go.forms import URLForm, SignupForm
from datetime import timedelta
from django.conf import settings
from django.http import Http404
from django.http import Http404, HttpResponseServerError
from django.utils import timezone
from django.contrib.auth.models import User
from django.core.exceptions import PermissionDenied
......@@ -10,21 +10,46 @@ from django.contrib.auth.decorators import login_required
from django.shortcuts import render, get_object_or_404, redirect
import os
##############################################################################
"""
Define useful helper methods here.
"""
def is_registered( user ):
"""
This function checks if a user account has a corresponding RegisteredUser,
thus checking if the user is registered.
"""
try:
registered = RegisteredUser.objects.get( username=user.username )
return True
except RegisteredUser.DoesNotExist:
return False
# Error 404
##############################################################################
"""
Define error page handling here.
"""
def error_404(request):
"""
Error 404 view, in case a url is not found.
"""
return render(request, '404.html', {
},
)
# Error 500
def error_500(request):
"""
Error 500 view, in case a server error occurs.
"""
return render(request, '500.html', {
},
)
......@@ -33,29 +58,59 @@ def qrcode(url):
img = qrcode.make(url)
return img
# Homepage view.
##############################################################################
"""
Define user views here.
"""
@login_required
def index(request):
"""
This view handles the homepage that the user is presented with when
they request '/'. If they're not logged in, they're redirected to
login. If they're logged in but not registered, they're given the
not_registered error page. If they are logged in AND registered, they
get the URL registration form.
"""
# If the user isn't registered, don't give them any leeway.
if not is_registered(request.user):
return render(request, 'not_registered.html')
url_form = URLForm() # unbound form
errors = []
if request.method == 'POST':
url_form = URLForm( request.POST ) # bind dat form
if url_form.is_valid():
# We don't commit the url object yet because we need to add its
# owner, and parse its date field.
url = url_form.save(commit=False)
url.owner = request.user
# If the user entered a short url, it's already been validated,
# so accept it. If they did not, however, then generate a
# random one and use that instead.
short = url_form.cleaned_data.get('short').strip()
if len(short) > 0:
url.short = short
else:
url.short = URL.generate_valid_short()
# If the user didn't enter a short url, generate a random
# one. However, if a random one can't be generated, return
# a 500 server error.
random_short = URL.generate_valid_short()
if random_short is None:
return HttpResponseServerError(
render(request, '500.html', {})
)
else:
url.short = random_short
# Grab the expiration field value. It's currently an unsable
# string value, so we need to parse it into a datetime object
# relative to right now.
expires = url_form.cleaned_data.get('expires')
if expires == URLForm.DAY:
......@@ -67,6 +122,8 @@ def index(request):
else:
pass # leave the field NULL
# Make sure that our new URL object is clean, then save it and
# let's redirect to view this baby.
url.full_clean()
url.save()
return redirect('view', url.short)
......@@ -76,8 +133,13 @@ def index(request):
},
)
# Preview a link.
def view(request, short):
"""
This view allows the user to view details about a URL. Note that they
do not need to be logged in to view info.
"""
url = get_object_or_404(URL, short__iexact = short)
qrcode = qrcode(url)
......@@ -88,22 +150,34 @@ def view(request, short):
},
)
# My-Links page.
@login_required
def my_links(request):
"""
This view displays all the information about all of your URLs. You
obviously need to be logged in to view your URLs.
"""
if not is_registered(request.user):
return render(request, 'not_registered.html')
urls = URL.objects.filter( owner = request.user )
return render(request, 'my_links.html', {
'urls' : urls,
},
)
# Delete link page.
@login_required
def delete(request, short):
"""
This view deletes a URL if you have the permission to. User must be
logged in and registered, and must also be the owner of the URL.
"""
if not is_registered(request.user):
return render(request, 'not_registered.html')
url = get_object_or_404(URL, short__iexact = short )
if url.owner == request.user:
url.delete()
......@@ -111,15 +185,16 @@ def delete(request, short):
else:
raise PermissionDenied()
# About page, static.
def about(request):
return render(request, 'about.html', {
},
)
# Signup page.
def signup(request):
"""
This view presents the user with a registration form. You can register
yourself, or another person.
TODO: Add email notification to sysadmin that a new registration has
occurred.
"""
form = SignupForm()
if request.method == 'POST':
......@@ -129,6 +204,12 @@ def signup(request):
full_name = form.cleaned_data.get('full_name')
description = form.cleaned_data.get('description')
"""
This code simply writes out to a file the registration.
Ideally, we will be sending an administrator an email instead.
But we need an email account to do that.
"""
f = open(os.path.join(settings.MEDIA_ROOT, 'registrations.txt'), 'a')
f.write( str(timezone.now()) )
f.write( str('\n') )
......@@ -147,17 +228,21 @@ def signup(request):
},
)
# Redirection view.
def redirection(request, short):
try:
# case insensitive matching
url = URL.objects.get( short__iexact = short )
except URL.DoesNotExist:
raise Http404("Target URL not found.")
"""
This view redirects a user based on the short URL they requested.
"""
url = get_object_or_404( URL, short__iexact = short )
url.clicks = url.clicks + 1
url.save()
"""
Include server-side tracking because there is no template displayed to
the user which would include javascript tracking.
"""
from piwikapi.tracking import PiwikTracker
from django.conf import settings
piwiktracker = PiwikTracker(settings.PIWIK_SITE_ID, request)
......@@ -165,3 +250,16 @@ def redirection(request, short):
piwiktracker.do_track_page_view('Redirect to %s' % url.target)
return redirect( url.target )
##############################################################################
"""
Define static user views here.
"""
def about(request):
return render(request, 'about.html', {
},
)
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment