Commits

Victor Gavro  committed 9ad60df

added command-line functions, fixed minor errors

  • Participants
  • Parent commits 0000dbe

Comments (0)

Files changed (5)

     else:
       result = []
       for args in datatuple:
-        result.append(backend.send_sms(*args,sender=sender,callback_url=callback_url))
+        result.append(
+          backend.send_sms(args[0],args[1],args[2],sender=sender,callback_url=callback_url)
+        )
       return result
   except:
     if not fail_silently:
 def get_sms_status(sms_ids,fail_silently=False):
   try:
     return backend.get_sms_status(sms_ids)
-  if not fail_silently:
-    raise
+  except:
+    if not fail_silently:
+      raise
 
 def sms_callback(request):
   return backend.sms_callback(request)

File constants.py

 #Status only for models - to save into db messages that was\n't
 STATUS_LOCAL_QUEUED = 1
 #Message queued on server
-STATUS_QUEUED = 1
+STATUS_QUEUED = 6
 #Message was not sent, and never will be
-STATUS_CANCELED = 2
+STATUS_CANCELED = 7
 #Message is sent ok, but status unknown
-STATUS_SENT = 3
+STATUS_SENT = 2
 #Message delivered to recipient
-STATUS_DELIVERED = 4
+STATUS_DELIVERED = 3
 #Message undelivered to recipient
-STATUS_UNDELIVERED = 5
+STATUS_UNDELIVERED = 4
 #Message was sent, but requesting status expired
-STATUS_EXPIRED = 6
+STATUS_EXPIRED = 5
 

File management/commands/sms_mass_send.py

 from django.core.management.base import BaseCommand, CommandError
-from example.polls.models import Poll
+from optparse import make_option
+from smsgate.models import Sms
 
 class Command(BaseCommand):
-  args = '<poll_id poll_id ...>'
-  help = 'Closes the specified poll for voting'
+  help = 'Mass send local queue of sms messages.\nIf you want to resend processed early messages, see --sms_statuses option.'
+  option_list = BaseCommand.option_list + (
+    make_option('--sms_statuses',
+      metavar='STATUS_LIST',
+      dest='sms_statuses',
+      default='1',
+      help='Specify comma separated sms statuses ids (see smsgate.constants module)'),
+    )
 
   def handle(self, *args, **options):
-    for poll_id in args:
-      try:
-        poll = Poll.objects.get(pk=int(poll_id))
-      except Poll.DoesNotExist:
-        raise CommandError('Poll "%s" does not exist' % poll_id)
+    statuses = map(int,options['sms_statuses'].split(','))
+    mass_sent_data = Sms.mass_send(statuses)
+    print '%s messages sent.' % len(mass_sent_data)
 
-      poll.opened = False
-      poll.save()
-
-      self.stdout.write('Successfully closed poll "%s"\n' % poll_id)
-
+#coding:utf8
 from smsgate import settings
 from smsgate import send_sms, send_mass_sms
+from smsgate.constants import *
 from django.db import models
 from datetime import datetime
 
 class Sms(models.Model):
-  text = models.TextField('SMS text',validators=[validate_text,])
+  text = models.TextField('SMS text')
   sender = models.CharField(max_length=32,default=settings.SENDER)
 
   def __unicode__(self):
     return self.text
 
-  def send(self, resend=False,resend_statuses=(STATUS_QUEUED,STATUS_CANCELED,STATUS_UNDELIVERED),recipients=None):
+  def send(self,statuses=(STATUS_QUEUED,),recipients=None):
     if recipients == None:
-      if resend:
-        filter = {'status__in': resend_statuses}
-      else:
-        filter = {'status': STATUS_QUEUED}
-      recipients = self.recipients.filter(status=STATUS_QUEUED)
+      recipients = self.recipients.filter(status__in=statuses)
     sent_data = send_sms(
       self.text,
       [r.phone for r in recipients],
       sms.send(recipients=recipients)
 
   @classmethod
-  def mass_send(cls,resend=False,resend_statuses=(STATUS_QUEUED,STATUS_CANCELED,STATUS_UNDELIVERED)):
-    if resend:
-      filter = {'smsrecipient__status__in': resend_statuses}
-    else:
-      filter = {'smsrecipient__status': STATUS_QUEUED}
-
+  def mass_send(cls,statuses=(STATUS_QUEUED,),set_processed=True):
+    filter = {'recipients__status__in': statuses}
     datatuple = []
     recipients_lists = []
     for sms in Sms.objects.filter(**filter).distinct():
       recipients_lists.append(recipients)
 
     mass_sent_data = sms_mass_send(datatuple,callback=settings.CALLBACK_URL)
-    for x,sent_data in enumerate(mass_sent_data):
-      recipients = recipients_lists[x]
-      for n,(sms_id,status,status_text) in enumerate(sent_data):
-        recipients[n].set_processed(sms_id,status,status_text,save=True)
+
+    if set_processed:
+      #setting statuses and messages of sms
+      for x,sent_data in enumerate(mass_sent_data):
+        recipients = recipients_lists[x]
+        for n,(sms_id,status,status_text) in enumerate(sent_data):
+          recipients[n].set_processed(sms_id,status,status_text,save=True)
+
+    return mass_sent_data
 
 class SmsRecipient(models.Model):
   STATUS_CHOICES = (
     (STATUS_UNDELIVERED, u'Не доставлено'),
     (STATUS_EXPIRED, u'Срок доставки истек'),
   )
-  phone = PhoneField()
+  phone = models.CharField(max_length=13)
   sms_id = models.CharField(max_length=32,editable=False)
   status = models.SmallIntegerField(choices=STATUS_CHOICES,default=STATUS_QUEUED,editable=False)
   queued_time = models.DateTimeField(default=datetime.now,editable=False)
 
   class Meta:
     unique_together = (('phone','sms'),)
-    ordering = ('-queued_time')
+    ordering = (('-queued_time'),)
 
   def __unicode__(self):
     return u'%s: %s' % (self.id,self.phone)
       self.set_status(get_sms_status((self.sms_id)),save=save)
 
   @classmethod
-  def get_statuses(cls,statuses=(STATUS_SENT,)):
+  def get_statuses(cls,statuses=(STATUS_SENT,),set_status=True):
     today = date.today()
     recipients = []
     for obj in cls.objects.filter(status__in=statuses):
       elif obj.sms_id:
         recipients.append(obj)
     fetched_statuses = get_sms_status([r.sms_id for r in recipients])
-    for n,status in enumerate(fetched_statuses):
-      recipients[n].set_status(status,save=True)
+    if set_status:
+      for n,status in enumerate(fetched_statuses):
+        recipients[n].set_status(status,save=True)
+    return fetched_statuses
   HTTP_TIMEOUT = None
 
 ADMINS_PHONES = _get('ADMINS_PHONES',())
-MANAGERS_PHONES _get('MANAGERS_PHONES',())
+MANAGERS_PHONES = _get('MANAGERS_PHONES',())