<commit_before>try:
    import json
except:
    import simplejson as json
    
import hashlib
from datetime import datetime

from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseServerError
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils.translation import ugettext as _
from django.core.urlresolvers import reverse
from django.views.generic.simple import direct_to_template
from django.conf import settings

from commoner.profiles.models import CommonerProfile
from commoner.promocodes.forms import PremiumUpgradeForm 

import models

def invite(request):
    """ Accepts a POST request and transmits an invitation letter and
    code to the recipient who made the contribution """

    if request.method != 'POST': # respond w/ 500 (415 may be more prudent)
        return HttpResponseServerError('Method unavailable')

    # POST should carry a JSON string and an HMAC 
    try:
        # throws KeyError's
        data = request.POST['data']
        hmac = request.POST['hash']

        auth_hash = hashlib.sha1()
        # might want to create another secret for this purpose
        auth_hash.update(settings.INVITE_KEY) 
        auth_hash.update(str(data))
        
        assert auth_hash.hexdigest() == str(hmac) # POST var's are unicode
        
    except:
        return HttpResponseServerError('Cannot verify authenticity of data')

    try:
        contrib = json.loads(data)

        recurring_id = contrib.get('contribution_recur_id', None)
        send_email = bool(int(request.POST.get('send', 1)))
        
        if not models.PromoCode.objects.contribution_is_unique(
            contrib['id'], recurring_id):
            return HttpResponseServerError(
                'Invitation already created')

        if not models.PromoCode.objects.contribution_is_sufficient(
            contrib['total_amount'], (recurring_id > 0) ):
            return HttpResponseServerError('Insufficient amount')
        
        code = models.PromoCode.objects.create_promo_code(
            email=unicode(contrib['email']),
            trxn_id=unicode(contrib['trxn_id']),
            contrib_id=int(contrib['id']),
            send_email=send_email,
            recurring_id=recurring_id,
            )

        return HttpResponse(json.dumps(
            dict(url=reverse('redeem_code', args=[code]))
            ))
        
    except Exception, e:
        return HttpResponseServerError('Invalid data: %s' % e)

@login_required
def account_upgrade(request):

    profile = request.user.get_profile()
    
    """ Process the upgrade form submissions. """
            
    if request.method == "POST":

        form = PremiumUpgradeForm(data=request.POST)

        if form.is_valid():

            promo_code = form.save()
            
            promo = models.PromoCode.objects.mark_as_used(code=xpromo_code.code,
                                                   user=request.user)

            upgrading = profile.free
            
            if upgrading:
                profile.upgrade()
            else:
                profile.renew()
                
            profile.save()
            
            # render to a page detailing what just happened and how long their
            # premium membership will last.
                        
            return render_to_response("promocodes/apply_success.html",
                                      {'profile':profile, 'upgraded':upgrading},<commit_msg>Fixing a typo that was breaking the promo code redeems<commit_after>try:
    import json
except:
    import simplejson as json
    
import hashlib
from datetime import datetime

from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseRedirect, HttpResponseServerError
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils.translation import ugettext as _
from django.core.urlresolvers import reverse
from django.views.generic.simple import direct_to_template
from django.conf import settings

from commoner.profiles.models import CommonerProfile
from commoner.promocodes.forms import PremiumUpgradeForm 

import models

def invite(request):
    """ Accepts a POST request and transmits an invitation letter and
    code to the recipient who made the contribution """

    if request.method != 'POST': # respond w/ 500 (415 may be more prudent)
        return HttpResponseServerError('Method unavailable')

    # POST should carry a JSON string and an HMAC 
    try:
        # throws KeyError's
        data = request.POST['data']
        hmac = request.POST['hash']

        auth_hash = hashlib.sha1()
        # might want to create another secret for this purpose
        auth_hash.update(settings.INVITE_KEY) 
        auth_hash.update(str(data))
        
        assert auth_hash.hexdigest() == str(hmac) # POST var's are unicode
        
    except:
        return HttpResponseServerError('Cannot verify authenticity of data')

    try:
        contrib = json.loads(data)

        recurring_id = contrib.get('contribution_recur_id', None)
        send_email = bool(int(request.POST.get('send', 1)))
        
        if not models.PromoCode.objects.contribution_is_unique(
            contrib['id'], recurring_id):
            return HttpResponseServerError(
                'Invitation already created')

        if not models.PromoCode.objects.contribution_is_sufficient(
            contrib['total_amount'], (recurring_id > 0) ):
            return HttpResponseServerError('Insufficient amount')
        
        code = models.PromoCode.objects.create_promo_code(
            email=unicode(contrib['email']),
            trxn_id=unicode(contrib['trxn_id']),
            contrib_id=int(contrib['id']),
            send_email=send_email,
            recurring_id=recurring_id,
            )

        return HttpResponse(json.dumps(
            dict(url=reverse('redeem_code', args=[code]))
            ))
        
    except Exception, e:
        return HttpResponseServerError('Invalid data: %s' % e)

@login_required
def account_upgrade(request):

    profile = request.user.get_profile()
    
    """ Process the upgrade form submissions. """
            
    if request.method == "POST":

        form = PremiumUpgradeForm(data=request.POST)

        if form.is_valid():

            promo_code = form.save()
            
            promo = models.PromoCode.objects.mark_as_used(code=promo_code.code,
                                                   user=request.user)

            upgrading = profile.free
            
            if upgrading:
                profile.upgrade()
            else:
                profile.renew()
                
            profile.save()
            
            # render to a page detailing what just happened and how long their
            # premium membership will last.
                        
            return render_to_response("promocodes/apply_success.html",
                                      {'profile':profile, 'upgraded':upgrading},
{'fraction_non_alphanumeric': 0.07982137873290539, 'fraction_numerical': 0.0025118615685180016, 'mean_word_length': 2.2606915377616015, 'pattern_counts': {'":': 2, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '950676', 'n_tokens_mistral': 1929, 'n_tokens_neox': 1810, 'n_words': 474}