<commit_before>from django.core.urlresolvers import reverse_lazy
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import redirect
from django.views.generic import View, ListView, CreateView
from django.views.generic.edit import ModelFormMixin
from django.contrib.auth.mixins import LoginRequiredMixin

from rest_framework.parsers import FormParser

from braces.views import CsrfExemptMixin

from twilio.rest import TwilioRestClient

from contacts.models import Contact
from texts.models import Text
from texts.forms import TextForm, NewTextForm

import os


class ProcessHookView(CsrfExemptMixin, View):
    """Processing request from Twilio."""

    def post(self, request, *kwargs):
        parser = FormParser()
        query_dict = parser.parse(request)
        contact = Contact.objects.filter(number=query_dict["From"]).first()
        if not contact:
            contact = Contact(number=query_dict["From"])
            contact.save()
        if contact.number != os.environ["TWILIO_NUMBER"]:
            sender = "them"
        else:
            sender = "you"
        text = Text(sender=sender, contact=contact, body=query_dict["Body"])
        text.save()
        return HttpResponse()


class TextView(LoginRequiredMixin, CreateView):
    """A view for the texts."""

    login_url = '/login/'
    model = Text
    form_class = TextForm
    template_name = "texts/texting.html"

    def get_context_data(self, **kwargs):
        ctx = super(TextView, self).get_context_data(**kwargs)
        ctx['contact'] = Contact.objects.get(pk=self.kwargs.get("pk"))
        # import pdb;pdb.set_trace()
        return ctx

    def post(self, request, *args, **kwargs):
        """Post response."""
        self.object = None
        self.form = self.get_form(self.form_class)

        # Here ou may consider creating a new instance of form_class(),
        # so that the form will come clean.
        text = self.form.save()
        text.sender = 'you'
        text.contact = Contact.objects.get(pk=int(self.kwargs.get('pk')))
        account_sid = os.environ["ACCOUNT_SID"]
        auth_token = os.environ["AUTH_TOKEN"]
        twilio_number = os.environ["TWILIO_NUMBER"]
        client = TwilioRestClient(account_sid, auth_token)
        client.messages.create(
            to=str(text.contact.number),
            from_=twilio_number,
            body=text.body
        )
        text.save()
        return self.get(request, *args, **kwargs)


class NewTextView(LoginRequiredMixin, CreateView):
    """View to create a new contact."""

    login_url = '/login/'
    model = Contact
    form_class = NewTextForm
    template_name = "texts/new_text.html"

    def post(self, request, *args, **kwargs):
        """Post response."""
        self.object = None
        self.form = self.get_form(self.form_class)

        if request.method == "POST":
            number = request.POST['number']
            if len(number) > 11 or number.isalpha():
                return self.get(request, *args, **kwargs)
            number = "+" + number
            if Contact.objects.filter(number=number):
                contact = Contact.objects.filter(number=number).first()
            else:
                contact = Contact(number=number)
                contact.save()
            pk = contact.pk
            return redirect(reverse_lazy('contact_detail', kwargs={'pk': pk}))

        return self.get(request, *args, **kwargs)


class MessageListView(LoginRequiredMixin, ListView):
    """View to show all text message conversations."""

    login_url = '/login/'
    template_name = 'texts/message_list.html'
    context_object_name = "contacts"
    model = Contact

    def get_queryset(self):
        return sorted(Contact.objects.exclude(texts__isnull=True),
                      key=lambda a: a.most_recent_text_id(),
                      reverse=True)<commit_msg>cleaning up redundant code<commit_after>from django.core.urlresolvers import reverse_lazy
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import redirect
from django.views.generic import View, ListView, CreateView
from django.views.generic.edit import ModelFormMixin
from django.contrib.auth.mixins import LoginRequiredMixin

from rest_framework.parsers import FormParser

from braces.views import CsrfExemptMixin

from twilio.rest import TwilioRestClient

from contacts.models import Contact
from texts.models import Text
from texts.forms import TextForm, NewTextForm

import os


class ProcessHookView(CsrfExemptMixin, View):
    """Processing request from Twilio."""

    def post(self, request, *kwargs):
        parser = FormParser()
        query_dict = parser.parse(request)
        contact = Contact.objects.filter(number=query_dict["From"]).first()
        if not contact:
            contact = Contact(number=query_dict["From"])
            contact.save()
        if contact.number != os.environ["TWILIO_NUMBER"]:
            sender = "them"
        else:
            sender = "you"
        text = Text(sender=sender, contact=contact, body=query_dict["Body"])
        text.save()
        return HttpResponse()


class TextView(LoginRequiredMixin, CreateView):
    """A view for the texts."""

    login_url = '/login/'
    model = Text
    form_class = TextForm
    template_name = "texts/texting.html"

    def get_context_data(self, **kwargs):
        ctx = super(TextView, self).get_context_data(**kwargs)
        ctx['contact'] = Contact.objects.get(pk=self.kwargs.get("pk"))
        # import pdb;pdb.set_trace()
        return ctx

    def post(self, request, *args, **kwargs):
        """Post response."""
        self.object = None
        self.form = self.get_form(self.form_class)

        # Here ou may consider creating a new instance of form_class(),
        # so that the form will come clean.
        text = self.form.save()
        text.sender = 'you'
        text.contact = Contact.objects.get(pk=int(self.kwargs.get('pk')))
        account_sid = os.environ["ACCOUNT_SID"]
        auth_token = os.environ["AUTH_TOKEN"]
        twilio_number = os.environ["TWILIO_NUMBER"]
        client = TwilioRestClient(account_sid, auth_token)
        client.messages.create(
            to=str(text.contact.number),
            from_=twilio_number,
            body=text.body
        )
        text.save()
        return self.get(request, *args, **kwargs)


class NewTextView(LoginRequiredMixin, CreateView):
    """View to create a new contact."""

    login_url = '/login/'
    model = Contact
    form_class = NewTextForm
    template_name = "texts/new_text.html"

    def post(self, request, *args, **kwargs):
        """Post response."""
        self.object = None
        self.form = self.get_form(self.form_class)

        number = request.POST['number']
        if len(number) > 11 or number.isalpha():
            return self.get(request, *args, **kwargs)
        number = "+" + number
        if Contact.objects.filter(number=number):
            contact = Contact.objects.filter(number=number).first()
        else:
            contact = Contact(number=number)
            contact.save()
        pk = contact.pk
        return redirect(reverse_lazy('contact_detail', kwargs={'pk': pk}))



class MessageListView(LoginRequiredMixin, ListView):
    """View to show all text message conversations."""

    login_url = '/login/'
    template_name = 'texts/message_list.html'
    context_object_name = "contacts"
    model = Contact

    def get_queryset(self):
        return sorted(Contact.objects.exclude(texts__isnull=True),
                      key=lambda a: a.most_recent_text_id(),
                      reverse=True)
{'fraction_non_alphanumeric': 0.11157455683003129, 'fraction_numerical': 0.0005213764337851929, 'mean_word_length': 2.7320038910505837, 'pattern_counts': {'":': 1, '<': 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': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3586286', 'n_tokens_mistral': 2208, 'n_tokens_neox': 2154, 'n_words': 515}