<commit_before># -*- coding: utf-8 -*-

"""
Adds support for texting Indian mobile numbers
"""

from datetime import datetime
from pytz import timezone
import requests
# from urllib2 import urlopen, URLError
# from urllib import urlencode

from flask import current_app, flash, request
from lastuser_core.models import db, SMSMessage, SMS_STATUS
from .. import lastuser_ui

# SMS GupShup sends delivery reports with this timezone
SMSGUPSHUP_TIMEZONE = timezone('Asia/Kolkata')


def send_message(msg):
    if msg.phone_number.startswith('+91'):  # Indian number. Use Exotel
        if len(msg.phone_number) != 13:
            raise ValueError("Invalid Indian mobile number")
        # All okay. Send!
        if not (current_app.config.get('SMS_EXOTEL_SID') and current_app.config.get('SMS_EXOTEL_TOKEN')):
            raise ValueError("This server is not configured to send SMS")
        else:
            sid = current_app.config['SMS_EXOTEL_SID']
            token = current_app.config['SMS_EXOTEL_TOKEN']
            try:
                r = requests.post('https://twilix.exotel.in/v1/Accounts/{sid}/Sms/send.json'.format(sid=sid),
                    auth=(sid, token),
                    data={
                        'From': current_app.config.get('SMS_FROM'),
                        'To': msg.phone_number,
                        'Body': msg.message
                    })
                if r.status_code in (200, 201):
                    # All good
                    jsonresponse = r.json()
                    msg.transaction_id = jsonresponse.get('SMSMessage', {}).get('Sid')
                else:
                    # FIXME: This function should not be sending messages to the UI
                    flash("Message could not be sent", 'danger')
            except requests.ConnectionError:
                flash("The SMS delivery engine is not reachable at the moment. Please try again", 'danger')

        # # TODO: Also check if we have SMS GupShup credentials in settings.py
        # params = urlencode(dict(
        #     method='SendMessage',
        #     send_to=msg.phone_number[1:],  # Number with leading +
        #     msg=msg.message,
        #     msg_type='TEXT',
        #     format='text',<commit_msg>Exotel now returns a list instead of a dict.<commit_after># -*- coding: utf-8 -*-

"""
Adds support for texting Indian mobile numbers
"""

from datetime import datetime
from pytz import timezone
import requests
# from urllib2 import urlopen, URLError
# from urllib import urlencode

from flask import current_app, flash, request
from lastuser_core.models import db, SMSMessage, SMS_STATUS
from .. import lastuser_ui

# SMS GupShup sends delivery reports with this timezone
SMSGUPSHUP_TIMEZONE = timezone('Asia/Kolkata')


def send_message(msg):
    if msg.phone_number.startswith('+91'):  # Indian number. Use Exotel
        if len(msg.phone_number) != 13:
            raise ValueError("Invalid Indian mobile number")
        # All okay. Send!
        if not (current_app.config.get('SMS_EXOTEL_SID') and current_app.config.get('SMS_EXOTEL_TOKEN')):
            raise ValueError("This server is not configured to send SMS")
        else:
            sid = current_app.config['SMS_EXOTEL_SID']
            token = current_app.config['SMS_EXOTEL_TOKEN']
            try:
                r = requests.post('https://twilix.exotel.in/v1/Accounts/{sid}/Sms/send.json'.format(sid=sid),
                    auth=(sid, token),
                    data={
                        'From': current_app.config.get('SMS_FROM'),
                        'To': msg.phone_number,
                        'Body': msg.message
                    })
                if r.status_code in (200, 201):
                    # All good
                    jsonresponse = r.json()
                    if isinstance(jsonresponse, (list, tuple)) and jsonresponse:
                        msg.transaction_id = jsonresponse[0].get('Sid')
                    else:
                        msg.transaction_id = jsonresponse.get('SMSMessage', {}).get('Sid')
                else:
                    # FIXME: This function should not be sending messages to the UI
                    flash("Message could not be sent", 'danger')
            except requests.ConnectionError:
                flash("The SMS delivery engine is not reachable at the moment. Please try again", 'danger')

        # # TODO: Also check if we have SMS GupShup credentials in settings.py
        # params = urlencode(dict(
        #     method='SendMessage',
        #     send_to=msg.phone_number[1:],  # Number with leading +
        #     msg=msg.message,
        #     msg_type='TEXT',
        #     format='text',
{'fraction_non_alphanumeric': 0.10008517887563884, 'fraction_numerical': 0.006175468483816013, 'mean_word_length': 2.007042253521127, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 2, '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': '4004550', 'n_tokens_mistral': 1349, 'n_tokens_neox': 1279, 'n_words': 358}