def test_send_single_sms(self): self.assert_(SMS.objects.count() == 0) send('+32000000001', 'testing message', 'the signature', using='smpp') self.assert_(SMS.objects.count() == 1) sms = SMS.objects.get(pk=1) self.assert_(sms.content == 'testing message') self.assert_(sms.to == '+32000000001') self.assert_(sms.sender == 'the signature'[:len(sms.sender)])
def setUp(self): self.conf = settings.SMSGATEWAY_ACCOUNTS['redistore'] self.rdb = redis.Redis(host=self.conf['host'], port=self.conf['port'], db=self.conf['dbn']) self.assert_(SMS.objects.count() == 0) send('+32000000001', 'testing message', 'the signature', using='redistore') self.assert_(SMS.objects.count() == 1) self.sms = SMS.objects.get(pk=1)
def setUp(self): self.conf = settings.SMSGATEWAY_ACCOUNTS['redistore'] self.rdb = redis.Redis(host=self.conf['host'], port=self.conf['port'], db=self.conf['dbn']) self.assert_(SMS.objects.count() == 0) send(req_data['to'], req_data['msg'], req_data['signature'], using='redistore') self.assert_(SMS.objects.count() == 3) self.smses = SMS.objects.all()
def test_send_multiple_separated_sms(self): self.assert_(SMS.objects.count() == 0) send(req_data['to'], req_data['msg'], req_data['signature'], using='smpp') self.assert_(SMS.objects.count() == 3) smses = SMS.objects.all() for to, sms in zip (req_data['to'].split(';'), smses): self.assert_(sms.to == check_cell_phone_number(to)) self.assert_(sms.content == truncate_sms(req_data['msg'])) self.assertEqual(sms.sender, req_data['signature'][:len(sms.sender)]) self.assert_(sms.backend == 'smpp')
def setUp(self): self.conf = settings.SMSGATEWAY_ACCOUNTS['redistore'] self.rdb = redis.Redis(host=self.conf['host'], port=self.conf['port'], db=self.conf['dbn'], password=self.conf['pwd']) self.assert_(SMS.objects.count() == 0) send(req_data['to'], req_data['msg'], req_data['signature'], using='redistore') self.assert_(SMS.objects.count() == 3) self.smses = SMS.objects.all()
def setUp(self): self.conf = settings.SMSGATEWAY_ACCOUNTS['redistore'] self.rdb = redis.Redis(host=self.conf['host'], port=self.conf['port'], db=self.conf['dbn'], password=self.conf['pwd']) self.assert_(SMS.objects.count() == 0) send('+32000000001', 'testing message', 'the signature', using='redistore') self.assert_(SMS.objects.count() == 1) self.sms = SMS.objects.get(pk=1)
def test_send_multiple_separated_sms(self): self.assert_(SMS.objects.count() == 0) send(req_data['to'], req_data['msg'], req_data['signature'], using='smpp') self.assert_(SMS.objects.count() == 3) smses = SMS.objects.all() for to, sms in zip(req_data['to'].split(';'), smses): self.assert_(sms.to == check_cell_phone_number(to)) self.assert_(sms.content == truncate_sms(req_data['msg'])) self.assertEqual(sms.sender, req_data['signature'][:len(sms.sender)]) self.assert_(sms.backend == 'smpp')
def handle_incoming(self, request, reply_using=None): request_dict = request.POST if request.method == 'POST' else request.GET # Check whether we've gotten a SendDateTime if 'SendDateTime' not in request_dict: return HttpResponse('') # Check whether we've already received this message if SMS.objects.filter(gateway_ref=request_dict['MessageID']).exists(): return HttpResponse('OK') # Parse and process message year, month, day, hour, minute, second, ms = list(map(int, findall(r'(\d+)', request_dict['SendDateTime']))) sms_dict = { 'sent': datetime(year, month, day, hour, minute, second), 'content': request_dict['MsgeContent'], 'sender': check_cell_phone_number(request_dict['SenderGSMNR']), 'to': request_dict['ShortCode'], 'operator': int(request_dict['Operator']), 'gateway_ref': request_dict['MessageID'], 'backend': self.get_slug(), } sms = SMS(**sms_dict) response = self.process_incoming(request, sms) # If necessary, send response SMS if response is not None: signature = get_account(reply_using)['reply_signature'] success = send([sms.sender], response, signature, using=reply_using) # Sending failed, queue SMS if not success: send_queued(sms.sender, response, signature, reply_using) return HttpResponse(response) return HttpResponse('OK')
def backend_debug(request): """ A form to let you send an SMS for debugging purposes. """ context = {} if request.method == 'POST': form = BackendDebugForm(request.POST) if form.is_valid(): success = send( form.cleaned_data['recipients'].split(';'), form.cleaned_data['message'], form.cleaned_data['signature'], form.cleaned_data['account'] ) if success: context.update({'message': u'Text message sent'}) else: context.update({'message': u'Sending failed'}) else: form = BackendDebugForm() context.update({'form': form}) return render_to_response( 'smsgateway/backend_debug.html', context, context_instance=RequestContext(request) )
def backend_debug(request): """ A form to let you send an SMS for debugging purposes. """ context = {} if request.method == 'POST': form = BackendDebugForm(request.POST) if form.is_valid(): success = send(form.cleaned_data['recipients'].split(';'), form.cleaned_data['message'], form.cleaned_data['signature'], form.cleaned_data['account']) if success: context.update({'message': u'Text message sent'}) else: context.update({'message': u'Sending failed'}) else: form = BackendDebugForm() context.update({ 'form': form, 'version': __version__, }) return render(request, 'smsgateway/backend_debug.html', context)
def handle_incoming(self, request, reply_using=None): request_dict = request.POST if request.method == 'POST' else request.GET # Check whether we've got an id if 'id' not in request_dict: return HttpResponse('') # Check whether we've already received this message if SMS.objects.filter(gateway_ref=request_dict['id']).exists(): return HttpResponse('ACK/Jasmin') # Parse and process message sms_dict = { 'sent': datetime.now(), 'content': request_dict['content'], 'sender': check_cell_phone_number(request_dict['from']), 'to': request_dict['to'], 'gateway_ref': request_dict['id'], 'backend': self.get_slug(), } sms = SMS(**sms_dict) response = self.process_incoming(request, sms) # If necessary, send response SMS if response is not None: signature = get_account(reply_using)['reply_signature'] success = send([sms.sender], response, signature, using=reply_using) # Sending failed, queue SMS if not success: send_queued(sms.sender, response, signature, reply_using) return HttpResponse('ACK/Jasmin')
def send_smses(send_deferred=False, backend=None, limit=None): # Get lock so there is only one sms sender at the same time. if send_deferred: lock = FileLock('send_sms_deferred') else: lock = FileLock('send_sms') try: lock.acquire(LOCK_WAIT_TIMEOUT) except AlreadyLocked: logger.info('Could not acquire lock.') return except LockTimeout: logger.info('Lock timed out.') return successes, failures = 0, 0 try: # Get SMSes that need to be sent (deferred or non-deferred) if send_deferred: to_send = QueuedSMS.objects.filter(priority=PRIORITY_DEFERRED) else: to_send = QueuedSMS.objects.exclude(priority=PRIORITY_DEFERRED) if isinstance(limit, int): to_send = to_send[:limit] logger.info("Trying to send %i messages." % to_send.count()) # Send each SMS for sms in to_send: if backend: sms_using = backend else: sms_using = None if sms.using == '__none__' else sms.using if send(sms.to, sms.content, sms.signature, sms_using, sms.reliable): # Successfully sent, remove from queue logger.info("SMS to %s sent." % sms.to) sms.delete() successes += 1 else: # Failed to send, defer SMS logger.info("SMS to %s failed." % sms.to) sms.defer() failures += 1 finally: lock.release() if successes and failures: statsd.gauge('smsgateway.success_rate', successes / failures) else: statsd.gauge('smsgateway.success_rate', 1)
def process_smses(smsk, sms_id, account_slug): smsobj = SMS.objects.get(pk=sms_id) smsbackend = SMSBackend() racc = get_account(account_slug) response = smsbackend.process_incoming(None, smsobj) if response is not None: signature = racc['reply_signature'] # If an SMS account can receive but not send SMSes, # it can specify a preferred reply account reply_account = racc.get('reply_account', account_slug) success = send([smsobj.sender], response, signature, reply_account) if not success: send_queued(smsobj.sender, response, signature, reply_account) task_logger.debug('End processing incoming SMS key: %s', smsk)
def send_smses(send_deferred=False, backend=None): # Get lock so there is only one sms sender at the same time. if send_deferred: lock = FileLock('send_sms_deferred') else: lock = FileLock('send_sms') try: lock.acquire(LOCK_WAIT_TIMEOUT) except AlreadyLocked: logger.info('Could not acquire lock.') return except LockTimeout: logger.info('Lock timed out.') return successes, failures = 0, 0 try: # Get SMSes that need to be sent (deferred or non-deferred) if send_deferred: to_send = QueuedSMS.objects.filter(priority=PRIORITY_DEFERRED) else: to_send = QueuedSMS.objects.exclude(priority=PRIORITY_DEFERRED) logger.info("Trying to send %i messages." % to_send.count()) # Send each SMS for sms in to_send: if backend: sms_using = backend else: sms_using = None if sms.using == '__none__' else sms.using if send(sms.to, sms.content, sms.signature, sms_using, sms.reliable): # Successfully sent, remove from queue logger.info("SMS to %s sent." % sms.to) sms.delete() successes += 1 else: # Failed to send, defer SMS logger.info("SMS to %s failed." % sms.to) sms.defer() failures += 1 finally: lock.release() if successes and failures: statsd.gauge('smsgateway.success_rate', successes / failures) else: statsd.gauge('smsgateway.success_rate', 1)
def _send_smses(send_deferred=False, backend=None, limit=None): # Get lock so there is only one sms sender at the same time. if send_deferred: send_lock_name = 'smsgateway_send_sms_deferred' else: send_lock_name = 'smsgateway_send_sms' with Lock(redis=Redis.from_url(settings.SMSGATEWAY_REDIS_URL), name='smsgateway-' + send_lock_name, blocking_timeout=0): successes, failures = 0, 0 try: # Get SMSes that need to be sent (deferred or non-deferred) if send_deferred: to_send = QueuedSMS.objects.filter(priority=PRIORITY_DEFERRED) else: to_send = QueuedSMS.objects.exclude(priority=PRIORITY_DEFERRED) if isinstance(limit, int): to_send = to_send[:limit] # Send each SMS for sms in to_send: if backend: sms_using = backend else: sms_using = None if sms.using == '__none__' else sms.using if send(sms.to, sms.content, sms.signature, sms_using, sms.reliable): # Successfully sent, remove from queue sms.delete() successes += 1 else: # Failed to send, defer SMS sms.defer() failures += 1 finally: if successes and failures: statsd.gauge('smsgateway.success_rate', successes / failures) else: statsd.gauge('smsgateway.success_rate', 1)
def handle_incoming(self, request, reply_using=None): request_dict = request.POST if request.method == 'POST' else request.GET # Check whether we've gotten a SendDateTime if not 'SendDateTime' in request_dict: return HttpResponse('') # Check whether we've already received this message if SMS.objects.filter(gateway_ref=request_dict['MessageID']).exists(): return HttpResponse('OK') # Parse and process message year, month, day, hour, minute, second, ms = map( int, re.findall(r'(\d+)', request_dict['SendDateTime'])) sms_dict = { 'sent': datetime.datetime(year, month, day, hour, minute, second), 'content': request_dict['MsgeContent'], 'sender': check_cell_phone_number(request_dict['SenderGSMNR']), 'to': request_dict['ShortCode'], 'operator': int(request_dict['Operator']), 'gateway_ref': request_dict['MessageID'], 'backend': self.get_slug(), } sms = SMS(**sms_dict) response = self.process_incoming(request, sms) # If necessary, send response SMS if response is not None: signature = smsgateway.get_account(reply_using)['reply_signature'] success = smsgateway.send([sms.sender], response, signature, using=reply_using) # Sending failed, queue SMS if not success: smsgateway.send_queued(sms.sender, response, signature, reply_using) return HttpResponse(response) return HttpResponse('OK')
def recv_smses(account_slug='redistore'): def _(key): return '%s%s' % (racc['key_prefix'], key) count = 0 racc = get_account(account_slug) rpool = redis.ConnectionPool(host=racc['host'], port=racc['port'], db=racc['dbn']) rconn = redis.Redis(connection_pool=rpool) smsbackend = SMSBackend() logger.info("Processing incoming SMSes for %s", account_slug) while True: smsk = rconn.rpoplpush(_('inq'), _('mvne:inq')) if not rconn.llen(_('mvne:inq')): break count += 1 logger.debug("Processing incoming SMS key: %s", smsk) smsd = rconn.hgetall(smsk) if not smsd: logger.error("SMS key %r is empty", smsk) continue smsd['sent'] = datetime.datetime.strptime(smsd['sent'], inq_ts_fmt) smsd['backend'] = account_slug smsobj = SMS(**smsd) response = smsbackend.process_incoming(None, smsobj) if response is not None: signature = racc['reply_signature'] success = send([smsobj.sender], response, signature, account_slug) if not success: send_queued(smsobj.sender, response, signature, account_slug) if rconn.lrem(_('mvne:inq'), smsk, 1) == 0: logger.error("SMS key %r doesn't exist in %r", smsk, _('mvne:inq')) if not rconn.delete(smsk): logger.error("SMS Hash %r doesn't exist" % smsk) logger.debug("End processing incoming SMS key: %s", smsk) logger.info("End processing incoming SMSes for %s (%d processed)", account_slug, count)
def _send_smses(send_deferred=False, backend=None, limit=None): # Get lock so there is only one sms sender at the same time. if send_deferred: send_lock_name = 'smsgateway_send_sms_deferred' else: send_lock_name = 'smsgateway_send_sms' with NonBlockingLock.objects.acquire_lock(lock_name=send_lock_name): successes, failures = 0, 0 try: # Get SMSes that need to be sent (deferred or non-deferred) if send_deferred: to_send = QueuedSMS.objects.filter(priority=PRIORITY_DEFERRED) else: to_send = QueuedSMS.objects.exclude(priority=PRIORITY_DEFERRED) if isinstance(limit, int): to_send = to_send[:limit] # Send each SMS for sms in to_send: if backend: sms_using = backend else: sms_using = None if sms.using == '__none__' else sms.using if send(sms.to, sms.content, sms.signature, sms_using, sms.reliable): # Successfully sent, remove from queue sms.delete() successes += 1 else: # Failed to send, defer SMS sms.defer() failures += 1 finally: if successes and failures: statsd.gauge('smsgateway.success_rate', successes / failures) else: statsd.gauge('smsgateway.success_rate', 1)