<commit_before>from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.utils.translation import ugettext as _
from django.contrib.sites.models import Site
from django.views.decorators.http import require_POST
from django.utils import simplejson

from ella.ratings.models import *
from ella.ratings.forms import RateForm

current_site = Site.objects.get_current()

UPDOWN = {'up' : 1, 'down' : -1}

def get_response(request, target, message=None):
    if (request.is_ajax()):
        json = simplejson.dumps({'message':message or _('Your rating was succesfully added.')})
        return HttpResponse(json)
    else:
        if message:
            request.user.message_set.create(message=message)

        if 'next' in request.REQUEST and request.REQUEST['next'].startswith('/'):
            url = request.POST['next']
        elif hasattr(target, 'get_absolute_url'):
            url = target.get_absolute_url()
        else:
            url = request.META.get('HTTP_REFERER', '/')
        return HttpResponseRedirect(url)

def do_rate(request, ct, target, plusminus):

    # ANTI-SPAM shortcuts
    if request.user.is_authenticated():
        cook = request.session.get(RATINGS_COOKIE_NAME, [])
        if (ct.id, target.id) in cook:
            return get_response(request, target, _('You have already rated this object.'))
    else:
        # check anti spam cookie
        cook = request.COOKIES.get(RATINGS_COOKIE_NAME, '').split(',')
        if '%s:%s' % (ct.id, target.id) in cook:
            # fail silently
            return get_response(request, target)

    kwa = {'amount' : ANONYMOUS_KARMA}
    if request.user.is_authenticated():
        kwa['user'] = request.user
        if getattr(settings, 'AUTH_PROFILE_MODULE', False):
            profile = request.user.get_profile()
            kwa['amount'] = getattr(profile, 'karma', INITIAL_USER_KARMA)

    kwa['amount'] *= plusminus

    if request.META.has_key('REMOTE_ADDR'):
        kwa['ip_address'] = request.META['REMOTE_ADDR']

    # do the rating
    rt = Rating(target_ct_id=ct.id, target_id=target.id, **kwa)
    rt.save()

    # update anti-spam
    if len(cook) > RATINGS_MAX_COOKIE_LENGTH:
        cook = cook[1:]

    if request.user.is_authenticated():
        cook.append((ct.id, target.id))
        request.session[RATINGS_COOKIE_NAME] = cook
        return get_response(request, target, message=_('Your rating was succesfully added.'))

    cook.append('%s:%s' % (ct.id, target.id))
    expores = datetime.strftime(datetime.utcnow() + timedelta(seconds=RATINGS_MAX_COOKIE_AGE), "%a, %d-%b-%Y %H:%M:%S GMT")
    response =  get_response(request, target)
    response.set_cookie(
            RATINGS_COOKIE_NAME,
            value=','.join(cook),
            max_age=RATINGS_MAX_COOKIE_AGE,
            expires=expores,
            path='/',
            domain=current_site.domain,
            secure=None
)
    return response

def rate_by_value(request, bits, context):
    val = request.POST.get('rating', None)
    if not val:
        raise ValueError('rating field not found in POST')
    plusminus = float(val)
    if not -1 <= plusminus <= 1:
        raise ValueError('rating value should be in <-1, 1>')
    return do_rate(
        request,
        context['content_type'],
        context['object'],
        plusminus
)

@require_POST
def rate_post(request, plusminus=1):
    """
    Add a simple up/down vote for a given object.
    redirect to object's get_absolute_url() on success.

    More granularity can be achieved via setting plusminus to something else than +/-1.

    Params:
        plusminus: rating itself

    Form data:
        POST:<commit_msg>- handle anonymous/logged user cookies same way - moved repeated rating detection to separate function - handle port in domain name - handle localhost domain<commit_after>from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.utils.translation import ugettext as _
from django.contrib.sites.models import Site
from django.views.decorators.http import require_POST
from django.utils import simplejson

from ella.ratings.models import *
from ella.ratings.forms import RateForm

current_site = Site.objects.get_current()

UPDOWN = {'up' : 1, 'down' : -1}

def _get_cookie(request):
    """
    Returns cookie split by ','
    """
    try:
        return request.COOKIES[RATINGS_COOKIE_NAME].split(',')
    except KeyError:
        # Cookie not set
        return []

def get_was_rated(request, ct, target):
    """
    Returns whether object was rated by current user

    Rating can fail later on db query, this checks user cookies
    """
    return '%s:%s' % (ct.id, target.id) in _get_cookie(request)

def set_was_rated(request, response, ct, target):
    """
    Marks target as rated

    Adds object content_type and id to RATINGS_COOKIE_NAME cookie
    """
    cook = _get_cookie(request)
    if len(cook) > RATINGS_MAX_COOKIE_LENGTH:
        cook = cook[1:]
    cook.append('%s:%s' % (ct.id, target.id))
    expires = datetime.strftime(datetime.utcnow() + timedelta(seconds=RATINGS_MAX_COOKIE_AGE), "%a, %d-%b-%Y %H:%M:%S GMT")
    domain = current_site.domain
    if domain.find(':') != -1:
        # Remove possible port from domain
        domain = domain[0:domain.find(':')]
    if domain == 'localhost':
        # Do not set domain at localhost beacause cookie spec
        # requires at least two dots in domain name
        domain = None
    response.set_cookie(RATINGS_COOKIE_NAME, value=','.join(cook),
            max_age=RATINGS_MAX_COOKIE_AGE, expires=expires,  path='/',
            domain=domain, secure=None)


def get_response(request, target, message=None):
    if (request.is_ajax()):
        json = simplejson.dumps({'message':message or _('Your rating was succesfully added.')})
        return HttpResponse(json)
    else:
        if message and request.user.is_authenticated():
            request.user.message_set.create(message=message)

        if 'next' in request.REQUEST and request.REQUEST['next'].startswith('/'):
            url = request.POST['next']
        elif hasattr(target, 'get_absolute_url'):
            url = target.get_absolute_url()
        else:
            url = request.META.get('HTTP_REFERER', '/')
        return HttpResponseRedirect(url)

def do_rate(request, ct, target, plusminus):

    if get_was_rated(request, ct, target):
        return get_response(request, target, _('You have already rated this object.'))

    kwa = {'amount' : ANONYMOUS_KARMA}
    if request.user.is_authenticated():
        kwa['user'] = request.user
        if getattr(settings, 'AUTH_PROFILE_MODULE', False):
            profile = request.user.get_profile()
            kwa['amount'] = getattr(profile, 'karma', INITIAL_USER_KARMA)

    kwa['amount'] *= plusminus

    if request.META.has_key('REMOTE_ADDR'):
        kwa['ip_address'] = request.META['REMOTE_ADDR']

    # Do the rating
    # Rating will not be neccessary added but fail silently
    rt = Rating(target_ct_id=ct.id, target_id=target.id, **kwa)
    rt.save()

    response =  get_response(request, target, message=_('Your rating was succesfully added.'))
    set_was_rated(request, response, ct, target)
    return response

def rate_by_value(request, bits, context):
    val = request.POST.get('rating', None)
    if not val:
        raise ValueError('rating field not found in POST')
    plusminus = float(val)
    if not -1 <= plusminus <= 1:
        raise ValueError('rating value should be in <-1, 1>')
    return do_rate(
        request,
        context['content_type'],
        context['object'],
        plusminus
)

@require_POST
def rate_post(request, plusminus=1):
    """
    Add a simple up/down vote for a given object.
    redirect to object's get_absolute_url() on success.

    More granularity can be achieved via setting plusminus to something else than +/-1.

    Params:
        plusminus: rating itself

    Form data:
        POST:
{'fraction_non_alphanumeric': 0.1157762413576367, 'fraction_numerical': 0.003268384663733501, 'mean_word_length': 3.012102874432678, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5733108', 'n_tokens_mistral': 2507, 'n_tokens_neox': 2420, 'n_words': 636}