passerelle/passerelle/sms/__init__.py

59 lines
2.7 KiB
Python

import logging
import re
from django.utils import six
from django.utils.translation import ugettext_lazy as _
from passerelle.compat import json_loads
from passerelle.utils.api import endpoint
from passerelle.utils.jsonresponse import APIError
class SMSGatewayMixin(object):
category = _('SMS Providers')
documentation_url = 'https://doc-publik.entrouvert.com/admin-fonctionnel/les-tutos/configuration-envoi-sms/'
_can_send_messages_description = _('Sending messages is limited to the following API users:')
@classmethod
def clean_numbers(cls, destinations, default_country_code='33',
default_trunk_prefix='0'): # Yeah France first !
numbers = []
for dest in destinations:
# most gateways needs the number prefixed by the country code, this is
# really unfortunate.
dest = dest.strip()
number = ''.join(re.findall('[0-9]', dest))
if dest.startswith('+'):
number = '00' + number
elif number.startswith('00'):
# assumes 00 is international access code, remove it
pass
elif number.startswith(default_trunk_prefix):
number = '00' + default_country_code + number[len(default_trunk_prefix):]
else:
raise NotImplementedError('phone number %r is unsupported (no '
'international prefix, no local '
'trunk prefix)' % number)
numbers.append(number)
return numbers
@endpoint(perm='can_send_messages', methods=['post'])
def send(self, request, *args, **kwargs):
try:
data = json_loads(request.body)
assert isinstance(data, dict), 'JSON payload is not a dict'
assert 'message' in data, 'missing "message" in JSON payload'
assert 'from' in data, 'missing "from" in JSON payload'
assert 'to' in data, 'missing "to" in JSON payload'
assert isinstance(data['message'], six.text_type), 'message is not a string'
assert isinstance(data['from'], six.text_type), 'from is not a string'
assert all(map(lambda x: isinstance(x, six.text_type), data['to'])), \
'to is not a list of strings'
except (ValueError, AssertionError) as e:
raise APIError('Payload error: %s' % e)
logging.info('sending message %r to %r with sending number %r',
data['message'], data['to'], data['from'])
if 'nostop' in request.GET:
return {'data': self.send_msg(data['message'], data['from'], data['to'], stop=False)}
return {'data': self.send_msg(data['message'], data['from'], data['to'], stop=True)}