<commit_before>import datetime

from django.http import HttpResponse, HttpResponseForbidden
from rapidsms.backends.http import RapidHttpBackend # typo on their part :-/ goes to show how well maintained this code is..
import json, time, sha, base64
import phonenumbers
from models import EnqueuedMessage

class EnvayaSMSBackend(RapidHttpBackend):
    """
    A RapidSMS Backend for EnvayaSMS

    Depends on 

    https://github.com/youngj/EnvayaSMS
    """

    def configure(self, url=None, password=None, max_delay=None, **kwargs):
        self.url = url
        self.password = password
        self.max_delay = max_delay
        super(EnvayaSMSBackend, self).configure(**kwargs)

    def handle_request(self, request):
        self.debug('Request: %s' % request.POST)
        data = request.POST

        params = ','.join('%s=%s' % (k, request.POST[k]) for k in sorted(request.POST.keys()))

        if self.password is not None:
            secure_key = sha.new(','.join((self.url, params, self.password))).digest()
            if base64.b64decode(request.META.get('HTTP_X_REQUEST_SIGNATURE', '')) != secure_key:
                return HttpResponseForbidden(json.dumps({'error': {'message': 'Bad password'}}))

        action = data.get('action', '')
        if action == 'incoming':
            message = self.message(request.POST)
            if message:
                self.route(message)
        elif action == 'outgoing':
            # send back outgoing
            phone_number = request.POST.get('phone_number', '')
            if not phone_number.startswith('+'):
                phone_number = '+%s' % phone_number
            print phone_number
            phone_number = phonenumbers.parse(phone_number)
            messages = EnqueuedMessage.messages_for(phone_number.country_code, self.max_delay)
            events = [{'event': 'send', 'messages': [{'to': data.recipient, 'message': data.message} for data in messages]}]
            messages.delete()

            return HttpResponse(json.dumps({'events': events}), content_type='application/json')
        elif action == 'send_status':
            pass
        elif action == 'device_status':
            pass
        elif action == 'forward_sent':
            pass
        elif action == 'amqp_started':
            pass
        return HttpResponse('{"events": []}', content_type='application/json')

    def message(self, data):
        if data.get('message_type') != 'call': # not sure how to handle incoming calls - ignore?
            sender = data.get('from', '')
            sms = data.get('message', '')
        return super(EnvayaSMSBackend, self).message(sender, sms)

    def send(self, message):
        m = EnqueuedMessage(recipient=message.connection.identity, message=message.text)
        m.save()<commit_msg>Implementing a dummy backend class for outgoing message cycle.<commit_after>from rapidsms.backends.base import BackendBase

class EnvayaSMSBackend(BackendBase):
    '''This handles the outgoing part ONLY'''

    '''def configure(**kwargs):
        print kwargs
        pass;
    '''

    def send(id_, text, identities, context = {}):
        print id
        print text
        print identities
        print context
        pass;
{'fraction_non_alphanumeric': 0.12047073397336637, 'fraction_numerical': 0.0018581604211830288, 'mean_word_length': 2.6251402918069586, 'pattern_counts': {'":': 1, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 1, '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': '2514231', 'n_tokens_mistral': 916, 'n_tokens_neox': 888, 'n_words': 226}