<repo_name>Sal-Ali/SMS-Polling<file_sep>/django_polling/application/models.py
from django.db import models

class BaseModel(models.Model):
    class Meta:
        abstract    = True
    
    date_created        = models.DateTimeField(auto_now_add=True)

class Poll(BaseModel):
    question            = models.CharField(max_length=500)
    
    @classmethod
    def get_current(cls):
        try:
            return cls.objects.all().order_by('-id')[0]
        except IndexError, e:
            return None
    
    def total_responses(self):
        return self.response_set.all().count()
    
class Answer(BaseModel):
    poll        = models.ForeignKey(Poll)
    answer_text = models.CharField(max_length=100)
    
    def get_total_responses(self):
        return self.response_set.all().count()

class Response(BaseModel):
    class InvalidAnswerIndexException(Exception): pass

    poll            = models.ForeignKey(Poll)
    mobile_number   = models.CharField(max_length=25, blank=True, null=True)
    answer          = models.ForeignKey(Answer)<file_sep>/django_polling/views.py
from application.models import Poll
from django.shortcuts import render, HttpResponse, get_object_or_404

import simplejson
import time

def admin(request):
    if request.method == "POST":
        question = request.POST.get('question')
        answers = request.POST.get('answers')
        
        if len(question) and len(answers):
            poll = Poll.objects.create(
                question    = question
            )
            
            for answer_text in answers.split("\n"):
                poll.answer_set.create(
                    answer_text     = answer_text
                )

    return render(request, 'admin.html')
    
def home(request):
    return render(request, 'home.html', {
        'recent_polls'  : Poll.objects.all().order_by('-id')[:5]
    })
    
def new_poll_listener(request):
    running_poll = Poll.get_current()
    
    new_poll = None
    
    while True:
        time.sleep(1)
        
        new_poll = Poll.get_current()
        
        if new_poll != running_poll:
            break
    
    return HttpResponse(simplejson.dumps({
        'new_poll'      : True
    }), content_type="application/json")
    
def new_response_listener(request, poll_id):
    poll = get_object_or_404(Poll, id=poll_id)
    
    try:
        recent_response = poll.response_set.all().order_by('-id')[0]
    except IndexError, e:
        recent_response = None
    
    new_response = recent_response
    
    while True:
        time.sleep(1)
        
        try:
            new_response = poll.response_set.all().order_by('-id')[0]
        except IndexError, e:
            pass
        
        if new_response != recent_response:
            break
    
    return HttpResponse(simplejson.dumps({
        'new_response'      : True
    }), content_type="application/json")

def polls_create(request):
    return render(request, 'polls/create.html')

def polls_current(request):
    return render(request, 'polls/current.html', {
        'poll'      : Poll.get_current()
    })

def telapi_inbound_sms(request):
    running_poll = Poll.get_current()
    
    if running_poll:
        answers = running_poll.answer_set.all()
        
        try:
            answer_index = int(request.REQUEST.get('Body')) - 1
            
            answer = answers[answer_index]
            
            running_poll.response_set.create(
                mobile_number   = request.REQUEST.get('From'),
                answer          = answer
            )
        except (TypeError, IndexError), e:
            print e
            pass
            
    return HttpResponse("Saved response")<file_sep>/django_polling/urls.py
from django.conf.urls.defaults import *

# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns('',
    url(r'^polls/create$', 'views.polls_create'),
    url(r'^polls/current$', 'views.polls_current'),
    url(r'^new-poll-listener$', 'views.new_poll_listener'),
    url(r'^poll/(?P<poll_id>\d+)/new-response-listener$', 'views.new_response_listener'),
    url(r'^telapi/inbound/sms$', 'views.telapi_inbound_sms'),
    url(r'^admin$', 'views.admin'),
    url(r'^$', 'views.home'),
)
