Exemplo n.º 1
0
    def send(self, msg, delay=True, *args, **kwargs):
        phone_number = strip_plus(msg.phone_number)
        if not phone_number.startswith("63"):
            raise MegamobileException(
                "Only Filipino phone numbers are supported")
        phone_number = phone_number[2:]

        text = msg.text.encode("utf-8")

        pid = None
        if msg.in_reply_to:
            original_msg = SMSLog.get(msg.in_reply_to)
            pid = getattr(original_msg, "megamobile_pid", None)
        pid = pid or DEFAULT_PID
        setattr(msg, "megamobile_pid", pid)
        msg.save()

        params = urlencode({
            "pid": pid,
            "cel": phone_number,
            "msg": text,
            "src": self.source_identifier,
        })
        api_account_name = quote(self.api_account_name)
        url = "http://api.mymegamobile.com/%s?%s" % (api_account_name, params)
        response = urlopen(url, timeout=settings.SMS_GATEWAY_TIMEOUT).read()
Exemplo n.º 2
0
    def send_sms(self, msg, delay=True, *args, **kwargs):
        phone_number = strip_plus(msg.phone_number)
        if not phone_number.startswith("63"):
            raise MegamobileException("Only Filipino phone numbers are supported")
        phone_number = phone_number[2:]

        text = msg.text.encode("utf-8")

        pid = None
        if msg.in_reply_to:
            original_msg = SMSLog.get(msg.in_reply_to)
            pid = getattr(original_msg, "megamobile_pid", None)
        pid = pid or DEFAULT_PID
        setattr(msg, "megamobile_pid", pid)
        msg.save()

        params = urlencode({
            "pid" : pid,
            "cel" : phone_number,
            "msg" : text,
            "src" : self.source_identifier,
        })
        api_account_name = quote(self.api_account_name)
        url = "http://api.mymegamobile.com/%s?%s" % (api_account_name, params)
        response = urlopen(url, timeout=settings.SMS_GATEWAY_TIMEOUT).read()
    def handle(self, *args, **options):
        num_sms = 0

        start_datetime = datetime.datetime(*str_to_int_tuple(args[0:6]))
        end_datetime = datetime.datetime(*str_to_int_tuple(args[6:12]))

        for domain in Domain.get_all():
            key = [domain.name, 'SMSLog']
            sms_docs = SMSLog.get_db().view('sms/by_domain',
                                            reduce=False,
                                            startkey=key + [start_datetime.isoformat()],
                                            endkey=key + [end_datetime.isoformat(), {}],
            )

            for sms_doc in sms_docs:
                sms_log = SMSLog.get(sms_doc['id'])
                if options.get('create', False):
                    SmsBillable.create(sms_log)
                    print 'Created billable for SMSLog %s in domain %s from %s' \
                          % (sms_doc['id'], domain.name, sms_log.date)
                else:
                    print 'Found SMSLog %s in domain %s from %s' \
                          % (sms_doc['id'], domain.name, sms_log.date)
                num_sms += 1

        print 'Number of SMSs in datetime range: %d' % num_sms
Exemplo n.º 4
0
 def handle(self, *args, **options):
     billables_created = 0
     for domain in Domain.get_all():
         key = [domain.name, 'SMSLog']
         start_date = [datetime.datetime(2014, 1, 1).isoformat()]
         end_date = [datetime.datetime(2014, 1, 24).isoformat()]
         sms_docs = SMSLog.get_db().view('sms/by_domain',
                                         reduce=False,
                                         startkey=key + start_date,
                                         endkey=key + end_date + [{}])
         for sms_doc in sms_docs:
             sms_log = SMSLog.get(sms_doc['id'])
             try:
                 if sms_log.phone_number is not None:
                     parse_phone_number(sms_log.phone_number)
             except PhoneNumberParseException:
                 billables = SmsBillable.objects.filter(log_id=sms_log._id)
                 if len(billables) == 0:
                     SmsBillable.create(sms_log)
                     billables_created += 1
                     print 'created SmsBillable for invalid number %s in domain %s, id=%s'\
                           % (sms_log.phone_number, domain.name, sms_log._id)
                 elif len(billables) > 1:
                     print "Warning: >1 SmsBillable exists for SMSLog with id=%" % sms_log._id
     print 'Number of SmsBillables created: %d' % billables_created
     print 'Completed retrobilling.'
Exemplo n.º 5
0
def process_sms(message_id):
    """
    message_id - _id of an SMSLog entry
    """
    # Note that Redis error/exception notifications go out from the
    # run_sms_queue command, so no need to send them out here
    # otherwise we'd get too many emails.
    rcache = cache_core.get_redis_default_cache()
    if not isinstance(rcache, RedisCache):
        return
    try:
        client = rcache.raw_client
    except NotImplementedError:
        return

    utcnow = datetime.utcnow()
    # Prevent more than one task from processing this SMS, just in case
    # the message got enqueued twice.
    message_lock = get_lock(client, "sms-queue-processing-%s" % message_id)

    if message_lock.acquire(blocking=False):
        msg = SMSLog.get(message_id)

        if message_is_stale(msg, utcnow):
            msg.set_system_error(ERROR_MESSAGE_IS_STALE)
            message_lock.release()
            return

        if msg.direction == OUTGOING:
            domain_object = Domain.get_by_name(msg.domain, strict=True)
            if handle_domain_specific_delays(msg, domain_object, utcnow):
                message_lock.release()
                return

        requeue = False
        # Process inbound SMS from a single contact one at a time
        recipient_block = msg.direction == INCOMING
        if (isinstance(msg.processed, bool)
            and not msg.processed
            and not msg.error
            and msg.datetime_to_process < utcnow):
            if recipient_block:
                recipient_lock = get_lock(client, 
                    "sms-queue-recipient-phone-%s" % msg.phone_number)
                recipient_lock.acquire(blocking=True)

            if msg.direction == OUTGOING:
                requeue = handle_outgoing(msg)
            elif msg.direction == INCOMING:
                handle_incoming(msg)
            else:
                msg.set_system_error(ERROR_INVALID_DIRECTION)

            if recipient_block:
                recipient_lock.release()
        message_lock.release()
        if requeue:
            process_sms.delay(message_id)
Exemplo n.º 6
0
def process_sms(message_id):
    """
    message_id - _id of an SMSLog entry
    """
    # Note that Redis error/exception notifications go out from the
    # run_sms_queue command, so no need to send them out here
    # otherwise we'd get too many emails.
    rcache = cache_core.get_redis_default_cache()
    if not isinstance(rcache, RedisCache):
        return
    try:
        client = rcache.raw_client
    except NotImplementedError:
        return

    utcnow = datetime.utcnow()
    # Prevent more than one task from processing this SMS, just in case
    # the message got enqueued twice.
    message_lock = get_lock(client, "sms-queue-processing-%s" % message_id)

    if message_lock.acquire(blocking=False):
        msg = SMSLog.get(message_id)

        if message_is_stale(msg, utcnow):
            set_error(msg, ERROR_MESSAGE_IS_STALE)
            message_lock.release()
            return

        if msg.direction == OUTGOING:
            domain_object = Domain.get_by_name(msg.domain, strict=True)
            if handle_domain_specific_delays(msg, domain_object, utcnow):
                message_lock.release()
                return

        requeue = False
        # Process inbound SMS from a single contact one at a time
        recipient_block = msg.direction == INCOMING
        if (isinstance(msg.processed, bool)
            and not msg.processed
            and not msg.error
            and msg.datetime_to_process < utcnow):
            if recipient_block:
                recipient_lock = get_lock(client, 
                    "sms-queue-recipient-phone-%s" % msg.phone_number)
                recipient_lock.acquire(blocking=True)

            if msg.direction == OUTGOING:
                requeue = handle_outgoing(msg)
            elif msg.direction == INCOMING:
                handle_incoming(msg)
            else:
                set_error(msg, ERROR_INVALID_DIRECTION)

            if recipient_block:
                recipient_lock.release()
        message_lock.release()
        if requeue:
            process_sms.delay(message_id)
 def handle(self, *args, **options):
     missing_domain_billables = SmsBillable.objects.filter(
         Q(domain=u'') | Q(domain=None))
     for billable in missing_domain_billables:
         msg_log = SMSLog.get(billable.log_id)
         billable.domain = msg_log.domain
         if billable.domain:
             billable.save()
             print "Updated Billable from %s for domain %s" % (
                 billable.date_created, billable.domain)
         else:
             print "could not find a domain in SMSLog %s." % billable.log_id
Exemplo n.º 8
0
def process_sms(message_id):
    """
    message_id - _id of an SMSLog entry
    """
    client = get_redis_client()
    utcnow = datetime.utcnow()
    # Prevent more than one task from processing this SMS, just in case
    # the message got enqueued twice.
    message_lock = get_lock(client, "sms-queue-processing-%s" % message_id)

    if message_lock.acquire(blocking=False):
        msg = SMSLog.get(message_id)

        if message_is_stale(msg, utcnow):
            msg.set_system_error(SMS.ERROR_MESSAGE_IS_STALE)
            release_lock(message_lock, True)
            return

        if msg.direction == OUTGOING:
            if msg.domain:
                domain_object = Domain.get_by_name(msg.domain, strict=True)
            else:
                domain_object = None
            if domain_object and handle_domain_specific_delays(msg, domain_object, utcnow):
                release_lock(message_lock, True)
                return

        requeue = False
        # Process inbound SMS from a single contact one at a time
        recipient_block = msg.direction == INCOMING
        if (isinstance(msg.processed, bool)
            and not msg.processed
            and not msg.error
            and msg.datetime_to_process < utcnow):
            if recipient_block:
                recipient_lock = get_lock(client, 
                    "sms-queue-recipient-phone-%s" % msg.phone_number)
                recipient_lock.acquire(blocking=True)

            if msg.direction == OUTGOING:
                requeue = handle_outgoing(msg)
            elif msg.direction == INCOMING:
                handle_incoming(msg)
            else:
                msg.set_system_error(SMS.ERROR_INVALID_DIRECTION)

            if recipient_block:
                release_lock(recipient_lock, True)

        release_lock(message_lock, True)
        if requeue:
            process_sms.delay(message_id)
Exemplo n.º 9
0
def process_sms(message_id):
    """
    message_id - _id of an SMSLog entry
    """
    client = get_redis_client()
    utcnow = datetime.utcnow()
    # Prevent more than one task from processing this SMS, just in case
    # the message got enqueued twice.
    message_lock = get_lock(client, "sms-queue-processing-%s" % message_id)

    if message_lock.acquire(blocking=False):
        msg = SMSLog.get(message_id)

        if message_is_stale(msg, utcnow):
            msg.set_system_error(SMS.ERROR_MESSAGE_IS_STALE)
            release_lock(message_lock, True)
            return

        if msg.direction == OUTGOING:
            if msg.domain:
                domain_object = Domain.get_by_name(msg.domain, strict=True)
            else:
                domain_object = None
            if domain_object and handle_domain_specific_delays(msg, domain_object, utcnow):
                release_lock(message_lock, True)
                return

        requeue = False
        # Process inbound SMS from a single contact one at a time
        recipient_block = msg.direction == INCOMING
        if (isinstance(msg.processed, bool)
            and not msg.processed
            and not msg.error
            and msg.datetime_to_process < utcnow):
            if recipient_block:
                recipient_lock = get_lock(client, 
                    "sms-queue-recipient-phone-%s" % msg.phone_number)
                recipient_lock.acquire(blocking=True)

            if msg.direction == OUTGOING:
                requeue = handle_outgoing(msg)
            elif msg.direction == INCOMING:
                handle_incoming(msg)
            else:
                msg.set_system_error(SMS.ERROR_INVALID_DIRECTION)

            if recipient_block:
                release_lock(recipient_lock, True)

        release_lock(message_lock, True)
        if requeue:
            process_sms.delay(message_id)
 def handle(self, *args, **options):
     missing_domain_billables = SmsBillable.objects.filter(
         Q(domain=u'') | Q(domain=None)
     )
     for billable in missing_domain_billables:
         msg_log = SMSLog.get(billable.log_id)
         billable.domain = msg_log.domain
         if billable.domain:
             billable.save()
             print "Updated Billable from %s for domain %s" % (
                 billable.date_created, billable.domain
             )
         else:
             print "could not find a domain in SMSLog %s." % billable.log_id
def post(data):
    client = Client()
    response = client.post('/unicel/in/', data)
    message_id = json.loads(response.content)['message_id']
    return response, SMSLog.get(message_id)