Exemplo n.º 1
0
def submit__ajax(request):
    url = None
    link_form = None
    if request.GET:
        link_form = LinkSubmitForm(request.GET)
    elif request.POST:
        link_form = LinkSubmitForm(request.POST)

    if link_form:
        if link_form.is_valid():
            url = link_form.cleaned_data['u']
            link = None
            try:
                if settings.SITE_NAME in url:
                    _u = urlparse(url)
                    link = Link.objects.get(pk=base62.to_decimal(_u.path))
                else:
                    link = Link.objects.get(url=url)
            except Link.DoesNotExist:
                pass
            if link == None:
                new_link = Link(url=url)
                new_link.save()
                link = new_link

            return JSONResponse({'url': url,
                                 'short_url': link.short_url(),
                                 'score': link.usage_count,
                                 'submitted': link.date_submitted.strftime('%b %d, %Y')})
        else:
            return JSONResponse({'error':[link_form.error_class.as_text(v) for k, v in link_form.errors.items()]})


    return JSONResponse({'error':'URL submission failed'})
Exemplo n.º 2
0
def submit(request):
    """
    View for submitting a URL to be shortened.  Modified to create a
    session and present that session information in the submit_success
    page so that we can carry the small link from here to the
    add_tag_to_link method.
    """
    lsform = LinkSubmitForm(request.POST)
    tagform = AddTagForm()
    tagurlform = TagURLForm()

    if lsform.is_valid():
        kwargs = {'url': lsform.cleaned_data['url']}
        custom = lsform.cleaned_data['custom']
        if custom:
            # specify an explicit id corresponding to the custom url
            kwargs.update({'id': base62.to_decimal(custom)})
        link = Link.objects.create(**kwargs)
        
        # JPK Need to put session info here, in the list that is
        # passed to the form

        request.session['link_id'] = link.id        
        
        return render(request, 'shortener/submit_success.html', {'link': link; 'tag_form': tagform; 'tag_select_form': tagurlform })
    else:
        return render(request, 'shortener/submit_failed.html', {'link_form': lsform})
Exemplo n.º 3
0
 def test_symmetry_positive_int(self):
     """
     symmetry for encoding/decoding values
     """
     for x in xrange(1000):
         random_int = random.randint(0, sys.maxint)
         encoded_int = base62.from_decimal(random_int)
         self.assertEqual(random_int, base62.to_decimal(encoded_int))
Exemplo n.º 4
0
 def test_symmetry_negative_int(self):
     """
     symmetry for negative numbers
     """
     for x in xrange(1000):
         random_int = random.randint(-1 * sys.maxint - 1, 0)
         encoded_int = base62.from_decimal(random_int)
         self.assertEqual(random_int, base62.to_decimal(encoded_int))
Exemplo n.º 5
0
 def test_symmetry_positive_int(self):
     """
     symmetry for encoding/decoding values
     """
     for x in range(1000):
         random_int = random.randint(0, sys.maxsize)
         encoded_int = base62.from_decimal(random_int)
         self.assertEqual(random_int, base62.to_decimal(encoded_int))
Exemplo n.º 6
0
 def test_symmetry_negative_int(self):
     """
     symmetry for negative numbers
     """
     for x in range(1000):
         random_int = random.randint(-1 * sys.maxsize - 1, 0)
         encoded_int = base62.from_decimal(random_int)
         self.assertEqual(random_int, base62.to_decimal(encoded_int))
Exemplo n.º 7
0
def follow(request, base62_id):
    """
    View which gets the link for the given base62_id value
    and redirects to it.
    """
    link = get_object_or_404(Link, id=base62.to_decimal(base62_id))
    link.usage_count = F('usage_count') + 1
    link.save()
    return HttpResponsePermanentRedirect(link.url)
Exemplo n.º 8
0
def follow(request, base62_id):
    """
    View which gets the link for the given base62_id value
    and redirects to it.
    """
    link = get_object_or_404(Link, id=base62.to_decimal(base62_id))
    link.usage_count = F('usage_count') + 1
    link.save()
    return HttpResponsePermanentRedirect(link.url)
Exemplo n.º 9
0
def info(request, base62_id):
    """
    View which shows information on a particular link
    """
    key = base62.to_decimal(base62_id)
    link = get_object_or_404(Link, pk=key)
    values = default_values(request)
    values["link"] = link
    return render_to_response("shortener/link_info.html", values, context_instance=RequestContext(request))
Exemplo n.º 10
0
def follow(request, base62_id):
    """ 
    View which gets the link for the given base62_id value
    and redirects to it.
    """
    key = base62.to_decimal(base62_id)
    link = get_object_or_404(Link, pk = key)
    link.usage_count += 1
    link.save()
    return http.HttpResponsePermanentRedirect(link.url)
Exemplo n.º 11
0
 def test_short_url_with_custom(self):
     custom = 'python'
     link = Link.objects.create(
         url='http://www.python.org/', id=base62.to_decimal(custom))
     request = self.factory.get(reverse('index'))
     out = Template(
         "{% load shortener_helpers %}"
         "{% short_url link %}"
     ).render(RequestContext(request, {'link': link,}))
     self.assertEqual(
         out, 'http://%s/%s' % (self.HTTP_HOST, link.to_base62()))
Exemplo n.º 12
0
 def test_short_url_with_custom(self):
     """
     the short_url templatetag works with custom links
     """
     custom = 'python'
     link = Link.objects.create(url='http://www.python.org/',
                                id=base62.to_decimal(custom))
     request = self.factory.get(reverse('index'))
     out = Template("{% load shortener_helpers %}"
                    "{% short_url link %}").render(
                        RequestContext(request, {'link': link}))
     self.assertEqual(out,
                      'http://%s/%s' % (self.HTTP_HOST, link.to_base62()))
Exemplo n.º 13
0
def follow(request, base62_id):
    """
    View which gets the link for the given base62_id value
    and redirects to it.  Also saves information about the
    referrer and IP address that originated the request.
    """
    link = get_object_or_404(Link, id=base62.to_decimal(base62_id))
    link.usage_count = F('usage_count') + 1
    link.save()
    
    # JPK: Add code here to record the referrer and IP address
    
    return HttpResponsePermanentRedirect(link.url)
Exemplo n.º 14
0
def submit(request):
    """
    View for submitting a URL to be shortened
    """
    form = LinkSubmitForm(request.POST)
    if form.is_valid():
        kwargs = {'url': form.cleaned_data['url']}
        custom = form.cleaned_data['custom']
        if custom:
            # specify an explicit id corresponding to the custom url
            kwargs.update({'id': base62.to_decimal(custom)})
        link = Link.objects.create(**kwargs)
        return render(request, 'shortener/submit_success.html', {'link': link})
    else:
        return render(request, 'shortener/submit_failed.html', {'link_form': form})
Exemplo n.º 15
0
def submit(request):
    """
    View for submitting a URL to be shortened
    """
    form = LinkSubmitForm(request.POST)
    if form.is_valid():
        kwargs = {'url': form.cleaned_data['url']}
        custom = form.cleaned_data['custom']
        if custom:
            # specify an explicit id corresponding to the custom url
            kwargs.update({'id': base62.to_decimal(custom)})
        link = Link.objects.create(**kwargs)
        return render(request, 'shortener/submit_success.html', {'link': link})
    else:
        return render(request, 'shortener/submit_failed.html',
                      {'link_form': form})
Exemplo n.º 16
0
    def clean_custom(self):
        custom = self.cleaned_data['custom']
        if not custom:
            return

        # they specified a custom url to shorten to. verify that we can decode
        # that shortened form, and that it's not already taken
        try:
            id = base62.to_decimal(custom)
        except DecodingError as e:
            raise forms.ValidationError(e)

        try:
            if Link.objects.filter(id=id).exists():
                raise forms.ValidationError('"%s" is already taken' % custom)
        except OverflowError:
            raise forms.ValidationError(too_long_error)
        return custom
Exemplo n.º 17
0
    def clean_custom(self):
        custom = self.cleaned_data['custom']
        if not custom:
            return

        # they specified a custom url to shorten to. verify that we can decode
        # that shortened form, and that it's not already taken
        try:
            id = base62.to_decimal(custom)
        except DecodingError as e:
            raise forms.ValidationError(e)

        try:
            if Link.objects.filter(id=id).exists():
                raise forms.ValidationError('"%s" is already taken' % custom)
        except OverflowError:
            raise forms.ValidationError(too_long_error)
        return custom
Exemplo n.º 18
0
    def clean_custom(self):
        custom = self.cleaned_data['custom']
        if not custom:
            return

        # test for characters in the requested custom alias that are not
        # available in our base62 enconding
        for char in custom:
            if char not in base62.digits:
                raise forms.ValidationError('Invalid character: "%s"' % char)
        # make sure this custom alias is not alrady taken
        id = base62.to_decimal(custom)
        try:
            if Link.objects.filter(id=id).exists():
                raise forms.ValidationError('"%s" is already taken' % custom)
        except OverflowError:
            raise forms.ValidationError(
                "Your custom name is too long. Are you sure you wanted a "
                "shortening service? :)")
        return custom
Exemplo n.º 19
0
def getFile(request, fileId):
    """
    Called when we get a request for a LittleShoot-shortened link.  This
    resolves to the "real" url and checks if the caller has LittleShoot.  If
    they do, this just redirects the caller to the file.  Otherwise, it
    redirects them to a page prompting them to install LittleShoot.
    """
    logging.info('Handling request to lookup a file: %s', request.REQUEST.items())
    logging.info("File ID: %s", fileId)
    
    keyId = base62.to_decimal(fileId)
    key = db.Key.from_path("Link", keyId)
    
    keyQuery = Link.gql('WHERE __key__ = :1', key)
    links = keyQuery.fetch(1)
    if (len(links) == 0):
        logging.warn("No match for file ID: %s", fileId)
        return HttpResponseNotFound("Could not find a matching file")

    link = links[0]
    link.usageCount += 1
    link.save()
    url = link.url
    logging.info("Link is: %s", url)
        
    littleShootPresent = appChecker.supportsLinks(request)
    if littleShootPresent:
        logging.info('Found LittleShoot')
        return HttpResponseRedirect(url)
    
    else:
        logging.info('Sending to link not installed page...')
        uri = link.url
        title = link.title
        
        return render_to_response('aboutTab.html', 
                                  {'link' : uri, 
                                   'title' : title,
                                   'tabId' : 'forthTab', 'tabJavaScriptClass' : 'AboutTab', 'homeSelected' : True, 'showLinkNotInstalled': True})
Exemplo n.º 20
0
def submit(request):
    """
    View for submitting a URL to be shortened
    """
    form = LinkSubmitForm(request.POST)
    if form.is_valid():
        kwargs = {'url': form.cleaned_data['url']}
        custom = form.cleaned_data['custom']
        if custom:
            # specify an explicit id corresponding to the custom url
            kwargs.update({'id': base62.to_decimal(custom)})
        print(kwargs['url'])
        if kwargs['url'] in [item.url for item in Link.objects.all()]:
            return render(request, 'shortener/submit_failed.html', {'link_form': form})
        
        link = Link.objects.create(**kwargs)
        user = User.objects.order_by('?').first()
        link.submitter = user
        link.save(update_fields=['submitter'])
        return render(request, 'shortener/submit_success.html', {'link': link})
    else:
        return render(request, 'shortener/submit_failed.html', {'link_form': form})
Exemplo n.º 21
0
 def get(self, request, base62_id):
     link = get_object_or_404(Link, id=base62.to_decimal(base62_id))
     link.clicks = link.clicks + 1
     link.save()
     return HttpResponsePermanentRedirect(link.target_url)
Exemplo n.º 22
0
def info(request, base62_id):
    """
    View which shows information on a particular link
    """
    link = get_object_or_404(Link, id=base62.to_decimal(base62_id))
    return render(request, 'shortener/link_info.html', {'link': link})
Exemplo n.º 23
0
 def test_decoding_non_str_fails(self):
     try:
         decoding = base62.to_decimal(sys.maxint)
     except DecodingError, e:
         err = e
Exemplo n.º 24
0
 def test_symmetry_int(self):
     random_int = random.randint(0, sys.maxint)
     encoded_int = base62.from_decimal(random_int)
     self.assertEqual(random_int, base62.to_decimal(encoded_int))
Exemplo n.º 25
0
def info(request, base62_id):
    """
    View which shows information on a particular link
    """
    link = get_object_or_404(Link, id=base62.to_decimal(base62_id))
    return render(request, 'shortener/link_info.html', {'link': link})