# Path: shortener/links/forms.py
# class BasicLinkForm(forms.ModelForm):
# 
#     class Meta:
#         model = Link
#         fields = ("original_url", "identifier")
# 
#     def clean_original_url(self):
#         url = self.cleaned_data['original_url']
#         if "//" in url[8:]:
#             raise forms.ValidationError("Don't be silly.")
#         try:
#             r = requests.get(url)
#         except requests.exceptions.MissingSchema:
#             raise forms.ValidationError("Please enter a real URL.")
#         if r.status_code not in (200, 301, 302):
#             raise forms.ValidationError("Please enter a working or accessible URL")
#         return url
# 
# Path: shortener/links/models.py
# class Link(TimeStampedModel):
# 
#     original_url = models.CharField(_("URL to be shortened"), max_length=255, unique=True)
#     identifier = models.CharField(_("Identifier"),
#                                     max_length=100,
#                                     blank=True,
#                                     validators=[validate_five_characters],
#                                     db_index=True)
# 
#     def __unicode__(self):
#         return self.original_url
# 
#     @property
#     def count(self):
#         return self.linklog_set.count()
# 
#     def log(self, request):
#         self.linklog_set.create_from_request(
#             link=self,
#             request=request
#         )
# 
#     def get_identifier_url(self):
#         try:
#             return reverse("links:redirect", kwargs={'identifier': self.identifier})
#         except NoReverseMatch:
#             return 'NADA'
# 
#     @property
#     def tiny(self):
#         return base64.encode(self.pk)
# 
#     def get_tiny_url(self):
#         return reverse("links:redirect", kwargs={'identifier': self.tiny})
# 
#     def amazonify(self):
#         url = self.original_url
#         if url.startswith(
#             ("https://amazon.",
#                 "http://amazon.",
#                 "http://amzn.",
#                 "https://amzn.",
#                 "https://www.amazon.",
#                 "http://www.amazon.")
#             ):
#             url = amazonify(url, "mlinar-20")
#         return url


from django.core.urlresolvers import reverse
from django.db.models import Count
from django.db.models import Q
from django.http import Http404
from django.shortcuts import get_object_or_404, redirect
from django.utils.baseconv import base64
from django.utils import timezone
from django.views.generic import (
    RedirectView, ListView, DetailView, FormView
)
from braces.views import LoginRequiredMixin, StaffuserRequiredMixin
from .forms import BasicLinkForm
from .models import Link
from linkmetrics.models import LinkLog
    permanent = True
    query_string = True

    def get_redirect_url(self, **kwargs):
        identifier = self.kwargs['identifier']

        # If identifier includes a link it means we don't need to do a base64
        # decode. Just a fetch based on the identifier
        if '-' in identifier or '_' in identifier or '.' in identifier:
            try:
                link = Link.objects.get(identifier=identifier)
                link.log(self.request)
                return link.original_url
            except Link.DoesNotExist:
                # identifier has '-' or '_' but doesn't evaliate
                pass

        # decode based on the identifier
        pk = base64.decode(identifier)
        try:
            link = Link.objects.get(Q(pk=pk) | Q(identifier=identifier))
        except Link.DoesNotExist:
            raise Http404

        link.log(self.request)
        return link.original_url


class LinkListView(ListView):


# Path: shortener/links/forms.py
# class BasicLinkForm(forms.ModelForm):
# 
#     class Meta:
#         model = Link
#         fields = ("original_url", "identifier")
# 
#     def clean_original_url(self):
#         url = self.cleaned_data['original_url']
#         if "//" in url[8:]:
#             raise forms.ValidationError("Don't be silly.")
#         try:
#             r = requests.get(url)
#         except requests.exceptions.MissingSchema:
#             raise forms.ValidationError("Please enter a real URL.")
#         if r.status_code not in (200, 301, 302):
#             raise forms.ValidationError("Please enter a working or accessible URL")
#         return url
# 
# Path: shortener/links/models.py
# class Link(TimeStampedModel):
# 
#     original_url = models.CharField(_("URL to be shortened"), max_length=255, unique=True)
#     identifier = models.CharField(_("Identifier"),
#                                     max_length=100,
#                                     blank=True,
#                                     validators=[validate_five_characters],
#                                     db_index=True)
# 
#     def __unicode__(self):
#         return self.original_url
# 
#     @property
#     def count(self):
#         return self.linklog_set.count()
# 
#     def log(self, request):
#         self.linklog_set.create_from_request(
#             link=self,
#             request=request
#         )
# 
#     def get_identifier_url(self):
#         try:
#             return reverse("links:redirect", kwargs={'identifier': self.identifier})
#         except NoReverseMatch:
#             return 'NADA'
# 
#     @property
#     def tiny(self):
#         return base64.encode(self.pk)
# 
#     def get_tiny_url(self):
#         return reverse("links:redirect", kwargs={'identifier': self.tiny})
# 
#     def amazonify(self):
#         url = self.original_url
#         if url.startswith(
#             ("https://amazon.",
#                 "http://amazon.",
#                 "http://amzn.",
#                 "https://amzn.",
#                 "https://www.amazon.",
#                 "http://www.amazon.")
#             ):
#             url = amazonify(url, "mlinar-20")
#         return url


# Path: shortener/links/views.py
from django.core.urlresolvers import reverse
from django.db.models import Count
from django.db.models import Q
from django.http import Http404
from django.shortcuts import get_object_or_404, redirect
from django.utils.baseconv import base64
from django.utils import timezone
from django.views.generic import (
    RedirectView, ListView, DetailView, FormView
)
from braces.views import LoginRequiredMixin, StaffuserRequiredMixin
from .forms import BasicLinkForm
from .models import Link
from linkmetrics.models import LinkLog

    permanent = True
    query_string = True

    def get_redirect_url(self, **kwargs):
        identifier = self.kwargs['identifier']

        # If identifier includes a link it means we don't need to do a base64
        # decode. Just a fetch based on the identifier
        if '-' in identifier or '_' in identifier or '.' in identifier:
            try:
                link = Link.objects.get(identifier=identifier)
                link.log(self.request)
                return link.original_url
            except Link.DoesNotExist:
                # identifier has '-' or '_' but doesn't evaliate
                pass

        # decode based on the identifier
        pk = base64.decode(identifier)
        try:
            link = Link.objects.get(Q(pk=pk) | Q(identifier=identifier))
        except Link.DoesNotExist:
            raise Http404

        link.log(self.request)
        return link.original_url


class LinkListView(ListView):


    model = Link