示例#1
0
文件: api.py 项目: mchampanis/core-hq
def send(msg, delay=True, *args, **kwargs):
    """
    Expected kwargs:
        messaging_token
    """
    phone_number = msg.phone_number
    if phone_number[0] != "+":
        phone_number = "+" + phone_number
    params = urlencode({
        "action" : "create"
       ,"token" : kwargs["messaging_token"]
       ,"numberToDial" : phone_number
       ,"msg" : msg.text
       ,"_send_sms" : "true"
    })
    url = "https://api.tropo.com/1.0/sessions?%s" % params
    response = urlopen(url).read()
    msg.save()
    try:
        # attempt to bill client
        from hqbilling.tasks import bill_client_for_sms
        from hqbilling.models import TropoSMSBillable
        if delay:
            bill_client_for_sms.delay(TropoSMSBillable, msg.get_id, **dict(response=response))
        else:
            bill_client_for_sms(TropoSMSBillable, msg.get_id, **dict(response=response))
    except Exception as e:
        logging.debug("TROPO API contacted, errors in billing. Error: %s" % e)

    return response
示例#2
0
def send(msg, delay=True):
    """
    Sends a message via mach's API
    """
    outgoing_sms_text = clean_outgoing_sms_text(msg.text)
    context = {
        'message': outgoing_sms_text,
        'phone_number': urllib.quote(msg.phone_number),
    }
    url = "%s?%s" % (settings.SMS_GATEWAY_URL, settings.SMS_GATEWAY_PARAMS % context)
    # just opening the url is enough to send the message
    # TODO, check response
    resp = urllib2.urlopen(url).read()
    msg.save()
    try:
        # attempt to bill client
        from hqbilling.tasks import bill_client_for_sms
        from hqbilling.models import MachSMSBillable
        if delay:
            bill_client_for_sms.delay(MachSMSBillable, msg.get_id, **dict(response=resp))
        else:
            bill_client_for_sms(MachSMSBillable, msg.get_id, **dict(response=resp))
    except Exception as e:
        logging.debug("MACH API contacted, errors in billing. Error: %s" % e)

    return resp
示例#3
0
def create_billable_for_sms(msg, backend_api, delay=True, **kwargs):
    try:
        from hqbilling.tasks import bill_client_for_sms
        from hqbilling.models import API_TO_BILLABLE
        billable_class = API_TO_BILLABLE.get(backend_api)
        if delay:
            bill_client_for_sms.delay(billable_class, msg._id, **kwargs)
        else:
            bill_client_for_sms(billable_class, msg._id, **kwargs)
    except Exception as e:
        logging.error("%s backend contacted, but errors in creating billable for incoming message. Error: %s" %
                      (backend_api, e))
示例#4
0
def create_billable_for_sms(msg, backend_api, delay=True, **kwargs):
    try:
        from hqbilling.tasks import bill_client_for_sms
        from hqbilling.models import API_TO_BILLABLE
        msg.save()
        billable_class = API_TO_BILLABLE.get(backend_api)
        if delay:
            bill_client_for_sms.delay(billable_class, msg._id, **kwargs)
        else:
            bill_client_for_sms(billable_class, msg._id, **kwargs)
        from corehq.apps.sms.api import store_billable
        store_billable.delay(msg)
    except Exception as e:
        logging.error(
            "%s backend contacted, but errors in creating billable for incoming message. Error: %s"
            % (backend_api, e))
示例#5
0
文件: api.py 项目: mchampanis/core-hq
def create_from_request(request, delay=True):
    """
    From an inbound request (representing an incoming message), 
    create a message (log) object with the right fields populated.
    """
    sender = request.REQUEST.get(InboundParams.SENDER, "")
    message = request.REQUEST.get(InboundParams.MESSAGE, "")
    timestamp = request.REQUEST.get(InboundParams.TIMESTAMP, "")
    # parse date or default to current utc time
    actual_timestamp = datetime.strptime(timestamp, DATE_FORMAT) \
                            if timestamp else datetime.utcnow()
    
    # not sure yet if this check is valid
    is_unicode = request.REQUEST.get(InboundParams.UDHI, "") == "1"
    if is_unicode:
        message = message.decode("hex").decode("utf_16_be")
    # if you don't have an exact match for either of these fields, save nothing
    domains = domains_for_phone(sender)
    domain = domains[0] if len(domains) == 1 else "" 
    recipients = users_for_phone(sender)
    recipient = recipients[0].get_id if len(recipients) == 1 else "" 
    
    log = SMSLog(couch_recipient=recipient,
                        couch_recipient_doc_type="CouchUser",
                        phone_number=sender,
                        direction=INCOMING,
                        date=actual_timestamp,
                        text=message,
                        domain=domain,
                        backend_api=API_ID)
    log.save()

    try:
        # attempt to bill client
        from hqbilling.tasks import bill_client_for_sms
        from hqbilling.models import UnicelSMSBillable
        if delay:
            bill_client_for_sms.delay(UnicelSMSBillable, log._id)
        else:
            bill_client_for_sms(UnicelSMSBillable, log._id)
    except Exception as e:
        logging.debug("UNICEL API contacted, errors in billing. Error: %s" % e)

    return log
    def testOutgoingInternationalTropoApi(self):
        self.assertEqual(self.tropo_rate_any.conversion_rate, self.usd_rate.conversion)
        msg = SMSLog(domain = self.domain,
            direction = OUTGOING,
            date = datetime.datetime.utcnow(),
            text = self.test_message)
        msg.save()

        if self.sms_config and self.sms_config.get("tropo_int") and self.tropo_backend:
            logging.info("\n\n[Billing - LIVE] Tropo:  Outgoing International SMS Test")
            msg.phone_number = self.sms_config.get("tropo_int")
            msg.save()
            data = self.tropo_backend.send(msg, delay=False)
        else:
            logging.info("\n\n[Billing] Tropo: Outgoing International SMS Test")
            data = "<session><success>true</success><token>faketoken</token><id>aadfg3Aa321gdc8e628df2\n</id></session>"
            msg.phone_number = "+4915253271951"
            msg.save()
            bill_client_for_sms(TropoSMSBillable, msg.get_id, **dict(response=data))

        logging.info("[Billing] Response from TROPO: %s" % data)
        tropo_id = TropoSMSBillable.get_tropo_id(data)
        logging.info("[Billing] TROPO ID: %s" % tropo_id)

        billable_items = TropoSMSBillable.by_domain(self.domain)
        if billable_items:
            billable_item = billable_items[0]
            self.assertEqual(self.tropo_rate_any.base_fee,
                billable_item.billable_amount)
            self.assertEqual(self.tropo_rate_any._id, billable_item.rate_id)
            self.assertEqual(msg._id, billable_item.log_id)
            self.assertEqual(self.tropo_rate_any.conversion_rate, billable_item.conversion_rate)
            self.assertEqual(self.dimagi_surcharge.base_fee, billable_item.dimagi_surcharge)
            self.assertEqual(tropo_id, billable_item.tropo_id)
            billable_item.delete()
            if billable_item.has_error:
                raise Exception("There were recorded errors creating an outgoing International Tropo billing rate: %s" %
                                billable_item.error_message)
        else:
            raise Exception("There were unknown errors creating an outgoing International Tropo billing rate!")
示例#7
0
文件: api.py 项目: mchampanis/core-hq
def send(message, delay=True):
    """
    Send an outbound message using the Unicel API
    """
    config = _config()
    
    phone_number = clean_phone_number(message.phone_number).replace("+", "")
    # these are shared regardless of API
    params = [(OutboundParams.DESTINATION, phone_number),
              (OutboundParams.USERNAME, config["username"]),
              (OutboundParams.PASSWORD, config["password"]),
              (OutboundParams.SENDER, config["sender"])]
    try: 
        text = str(message.text)
        # it's ascii
        params.append((OutboundParams.MESSAGE, text))
    except UnicodeEncodeError:
        params.extend(UNICODE_PARAMS)
        encoded = message.text.encode("utf_16_be").encode("hex").upper()
        params.append((OutboundParams.MESSAGE, encoded))

    try:
        data = urlopen('%s?%s' % (OUTBOUND_URLBASE, urlencode(params))).read()
    except Exception:
        data = None
    message.save()
    try:
        # attempt to bill client
        from hqbilling.tasks import bill_client_for_sms
        from hqbilling.models import UnicelSMSBillable
        if delay:
            bill_client_for_sms.delay(UnicelSMSBillable, message.get_id, **dict(response=data))
        else:
            bill_client_for_sms(UnicelSMSBillable, message.get_id, **dict(response=data))
    except Exception as e:
        logging.debug("UNICEL API contacted, errors in billing. Error: %s" % e)

    return data
    def testOutgoingUnicelApi(self):
        self.assertEqual(self.unicel_rate.conversion_rate, self.usd_rate.conversion)
        msg = SMSLog(domain = self.domain,
            direction = OUTGOING,
            date = datetime.datetime.utcnow(),
            text = self.test_message)
        msg.save()

        if self.sms_config and self.sms_config.get("unicel") and self.unicel_backend:
            logging.info("\n\n[Billing - LIVE] UNICEL: Outgoing SMS Test.")
            msg.phone_number = self.sms_config.get("unicel")
            msg.save()
            data = self.unicel_backend.send(msg, delay=False)
        else:
            logging.info("\n\n[Billing] UNICEL: Outgoing SMS Test")
            data = "successful23541253235"
            msg.phone_number = "+555555555"
            msg.save()
            bill_client_for_sms(UnicelSMSBillable, msg.get_id, **dict(response=data))

        logging.info("Response from UNICEL: %s" % data)

        billable_items = UnicelSMSBillable.by_domain_and_direction(self.domain, OUTGOING)
        if billable_items:
            billable_item = billable_items[0]
            self.assertEqual(self.unicel_rate.base_fee * self.unicel_rate.conversion_rate,
                       billable_item.billable_amount)
            self.assertEqual(self.unicel_rate._id, billable_item.rate_id)
            self.assertEqual(msg._id, billable_item.log_id)
            self.assertEqual(self.unicel_rate.conversion_rate, billable_item.conversion_rate)
            self.assertEqual(self.dimagi_surcharge.base_fee, billable_item.dimagi_surcharge)
            self.assertEqual(data, billable_item.unicel_id)
            if billable_item.has_error:
                raise Exception("There were recorded errors creating an outgoing UNICEL billing rate: %s" %
                                billable_item.error_message)
        else:
            raise Exception("There were unknown errors creating an outgoing UNICEL billing rate!")