From 580af16e72902b4d3d89a00e39aa4b339e21c7f5 Mon Sep 17 00:00:00 2001 From: Benjamin Dauvergne Date: Tue, 18 Jun 2013 16:23:26 +0200 Subject: [PATCH] transports: add SMS transport through passerelle --- portail_citoyen_announces/transports.py | 71 +++++++++++++++++++++++++ 1 file changed, 71 insertions(+) diff --git a/portail_citoyen_announces/transports.py b/portail_citoyen_announces/transports.py index f160f1f..5d4a4e9 100644 --- a/portail_citoyen_announces/transports.py +++ b/portail_citoyen_announces/transports.py @@ -1,5 +1,11 @@ import logging import smtplib +try: + import simplejson as json +except: + import json + +import requests from django.utils.importlib import import_module @@ -74,6 +80,71 @@ class HomepageTransport(object): return (('homepage', _('homepage')),) +class SMSTransport(object): + body_template_list = [ + 'portail_citoyen_announces/{identifier}/body_{category}.txt', + 'portail_citoyen_announces/{identifier}/body.txt', + 'portail_citoyen_announces/body_{category}.txt', + 'portail_citoyen_announces/body.txt', + ] + + def __init__(self, url, from_mobile, login=None, password=None, identifier='sms'): + self.url = url + self.from_mobile = from_mobile + self.login = login + self.password = password + self.identifier = identifier + + def get_choices(self): + return ((self.identifier, self.identifier),) + + def get_subscriptions(self, category): + return models.Subscription.objects.filter(category=category, + transport=self.identifier) + + def get_sms(self, category): + qs = self.get_subscriptions(category) + return qs.values_list('identifier', flat=True).distinct() + + def send(self, announce): + category = announce.category + site = category.site + body_template = get_template(self.body_template_list, + category=category.identifier, identifier=self.identifier) + ctx = Context({ 'announce': announce, 'site': site, 'category': category }) + body = body_template.render(ctx) + sms = self.get_sms(category) + logger.info(u'sending announce %(announce)s through %(mode)s to %(count)s emails', + dict(announce=announce, mode=self.identifier, count=len(sms))) + try: + payload = { + 'message': body, + 'from': self.from_mobile, + 'to': list(sms), + } + response = requests.post(self.url, data=json.dumps(payload)) + json_response = response.json() + if json_response['err'] != 0: + msg = u'unable to send announce "%s" on site "%s": %s' % (announce, + site, json_response) + logger.error(msg) + else: + logger.info('announce %(announce)s sent succesfully', + dict(announce=announce)) + msg = u'ok' + except smtplib.SMTPException, e: + msg = u'unable to send announce "%s" on site "%s": %s' % (announce, + site, e) + logger.error(msg) + except Exception, e: + msg = u'unable to send announce "%s" on site "%s": %s' % (announce, + site, e) + logger.exception(msg) + models.Sent.objects.create( + announce=announce, + transport=self.identifier, + result=msg) + class EmailTransport(object): identifier = 'email'