Exemplo n.º 1
0
def main(request, path):
    """Search for a long link matching the `path` and redirect"""

    path = _extract_valid_path(path)

    link = Link.find_by_hash(path)

    redirect_suffix = None

    if link is None:
        # Try to find a matching prefix
        parts = path.split('/', 1)

        if len(parts) == 2:
            path_prefix, redirect_suffix = parts

            # If there was a prefix, we try to find a link again
            link = Link.find_by_hash(path_prefix)

    # Instrumentation
    prefix_tag = 'prefix:' + link.prefix if link else 'Http404'

    statsd.increment('workforus.clicks', tags=[prefix_tag])
    statsd.set('workforus.unique_links', link.hash if link else 'Http404', tags=[prefix_tag])
    statsd.set('workforus.unique_ips', get_client_ip(request), tags=['browser:' + get_browser(request)])

    # 404 if link not found or register a click if the DB is not in readonly mode
    if link is None:
        raise Http404
    elif mongoengine_is_primary():
        link.click()

    # Tweak the redirection link based on the query string, redirection suffix, etc.
    # FIXME: Handle multiple parameters with the same name in the `url`
    query = request.GET.copy()

    if redirect_suffix is not None:
        query[REDIRECT_PARAM_NAME] = redirect_suffix

    if bool(query) and REF_PARAM_NAME not in query:
        # If we specify a non empty query, indicate that the shortener tweaked the url
        query[REF_PARAM_NAME] = REF_PARAM_DEFAULT_VALUE

    target_url = url_append_parameters(
        link.long_url,
        params_to_replace=query,
        defaults={REF_PARAM_NAME: REF_PARAM_DEFAULT_VALUE}
    )

    # Either redirect the user, or load the target page and display it directly
    if link.act_as_proxy:
        return proxy(target_url)

    return redirect(target_url, permanent=True)
Exemplo n.º 2
0
 def test__url_append_parameters(self):
     self.assertEqual(
         url_append_parameters('http://workfor.us', dict(), dict()),
         'http://workfor.us'
     )
     self.assertEqual(
         url_append_parameters('http://workfor.us', {'toto': 'tata'}, dict()),
         'http://workfor.us?toto=tata'
     )
     self.assertEqual(
         url_append_parameters('http://www.theuselessweb.com/', {'foo': 'search'}, {'foo': 'bar'}),
         'http://www.theuselessweb.com/?foo=search'
     )
     self.assertEqual(
         url_append_parameters('http://www.theuselessweb.com?a=1&b=2&z=5', {'foo': 'search'}, {'b': '3'}),
         'http://www.theuselessweb.com?a=1&b=2&z=5&foo=search'
     )
     self.assertEqual(
         url_append_parameters('http://www.theuselessweb.com?foo=4', {'foo': 'search'}, {'c': '42'}),
         'http://www.theuselessweb.com?c=42&foo=search'
     )