def process_confirm(from_imsi, code):
    """Process a confirmation request.

    Args:
      from_imsi: sender's IMSI
      code: the input confirmation code string
    """
    # Step one: delete all the confirm codes older than some time.
    db = sqlite3.connect(config_db['pending_transfer_db_path'])
    db.execute("DELETE FROM pending_transfers"
               " WHERE time - ? > 600", (time.time(),))
    db.commit()

    # Step two: check if this (from_imsi, code) combo is valid.
    r = db.execute("SELECT from_acct, to_acct, amount FROM pending_transfers"
                   " WHERE code=? AND from_acct=?", (code, from_imsi))
    res = r.fetchone()
    if res and len(res) == 3:
        from_imsi, to_imsi, amount = res
        from_num = subscriber.get_numbers_from_imsi(from_imsi)[0]
        to_num = subscriber.get_numbers_from_imsi(to_imsi)[0]
        reason = "SMS transfer from %s to %s" % (from_num, to_num)
        # Deduct credit from the sender.
        from_imsi_old_credit = subscriber.get_account_balance(from_imsi)
        from_imsi_new_credit = int(from_imsi_old_credit) - int(amount)
        events.create_transfer_event(from_imsi, from_imsi_old_credit,
                                     from_imsi_new_credit, reason,
                                     from_number=from_num, to_number=to_num)
        subscriber.subtract_credit(from_imsi, str(int(amount)))
        # Add credit to the recipient.
        to_imsi_old_credit = subscriber.get_account_balance(to_imsi)
        to_imsi_new_credit = int(to_imsi_old_credit) + int(amount)
        events.create_transfer_event(to_imsi, to_imsi_old_credit,
                                     to_imsi_new_credit, reason,
                                     from_number=from_num, to_number=to_num)
        subscriber.add_credit(to_imsi, str(int(amount)))
        # Humanize credit strings
        amount_str = freeswitch_strings.humanize_credits(amount)
        to_balance_str = freeswitch_strings.humanize_credits(
                to_imsi_new_credit)
        from_balance_str = freeswitch_strings.humanize_credits(
                from_imsi_new_credit)
        # Let the recipient know they got credit.
        message = gt("You've received %(amount)s credits from %(from_num)s!"
                     " Your new balance is %(new_balance)s.") % {
                     'amount': amount_str, 'from_num': from_num,
                     'new_balance': to_balance_str}
        sms.send(str(to_num), str(config_db['app_number']), str(message))
        # Remove this particular the transfer as it's no longer pending.
        db.execute("DELETE FROM pending_transfers WHERE code=?"
                   " AND from_acct=?", (code, from_imsi))
        db.commit()
        # Tell the sender that the operation succeeded.
        return True, gt("You've transferred %(amount)s to %(to_num)s. "
                        "Your new balance is %(new_balance)s.") % {
                                'amount': amount_str, 'to_num': to_num,
                                'new_balance': from_balance_str}
    return False, gt("That transfer confirmation code doesn't exist"
                     " or has expired.")
Example #2
0
    def adjust_credits(self, data):
        required_fields = ["imsi", "change"]
        if not all([_ in data for _ in required_fields]):
            return web.BadRequest()
        imsi = data["imsi"]
        try:
            change = int(data["change"])
        except ValueError:
            return web.BadRequest()
        old_credit = subscriber.get_account_balance(imsi)
        if change > 0:
            subscriber.add_credit(imsi, str(abs(change)))
        elif change < 0:
            subscriber.subtract_credit(imsi, str(abs(change)))

        new_credit = subscriber.get_account_balance(imsi)

        # Codeship is stupid. These imports break CI and this is an untested
        # method :)
        from core import freeswitch_interconnect, freeswitch_strings

        # Send a confirmation to the subscriber
        number = subscriber.get_caller_id(imsi)
        change_frmt = freeswitch_strings.humanize_credits(change)
        balance_frmt = freeswitch_strings.humanize_credits(new_credit)

        fs_ic = freeswitch_interconnect.freeswitch_ic(self.conf)
        fs_ic.send_to_number(
            number, '000',
            freeswitch_strings.gt(
                "The network operator adjusted your credit by %(change)s. "
                "Your balance is now %(balance)s.") % {
                    'change': change_frmt,
                    'balance': balance_frmt
                })

        # TODO(matt): all credit adjustments are of the kind "add_money," even
        #             if they actually subtract credit.
        reason = 'Update from web UI (add_money)'
        events.create_add_money_event(imsi,
                                      old_credit,
                                      new_credit,
                                      reason,
                                      to_number=number)
        return web.ok()
def fsapi(session, stream, env, arg):
    """
    Args: string of amount

    Does not return anything, but writes to output the value of the formatted
    currency amount"""
    resp = humanize_credits(int(arg))
    consoleLog('info', "endaga_currency FSAPI %s -> %s" % (arg, resp))
    stream.write(str(resp))
def chat(message, arg):
    """
    Arg: string amount

    Does not return anything, but sets the variable "_endaga_ret" to the value
    of the formatted currency string.
    """
    resp = humanize_credits(int(arg))
    consoleLog('info', "endaga_currency Chat %s -> %s" % (arg, resp))
    message.chat_execute('set', '_endaga_ret=%s' % resp)
Example #5
0
def process_transfer(from_imsi, to_imsi, amount):
    """Process a transfer request.

    Args:
      from_imsi: the sender's IMSI
      to_imsi: the recipient's IMSI
      amount: an amount of credit to add (type?)

    Returns:
      boolean indicating success
    """
    # Error when user tries to transfer to his own account
    if from_imsi == to_imsi:
        return False, gt("Transaction Failed. Sharing load to "
                         "your own account is not allowed.")
    from_balance = int(subscriber.get_account_balance(from_imsi))
    # Error when user tries to transfer more credit than they have.
    if not from_balance or from_balance < amount:
        return False, gt("Your account doesn't have sufficient funds for"
                         " the transfer.")
    # Error when user tries to transfer to a non-existent user.
    #       Could be 0!  Need to check if doesn't exist.
    if not to_imsi or (subscriber.get_account_balance(to_imsi) == None):
        return False, gt("The number you're sending to doesn't exist."
                         " Try again.")
    # Add the pending transfer.
    code = ''
    for _ in range(int(config_db['code_length'])):
        code += str(random.randint(0, 9))
    db = sqlite3.connect(config_db['pending_transfer_db_path'])
    db.execute("INSERT INTO pending_transfers VALUES (?, ?, ?, ?, ?)",
               (code, time.time(), from_imsi, to_imsi, amount))
    db.commit()
    db.close()
    to_num = subscriber.get_numbers_from_imsi(to_imsi)[0]
    amount_str = freeswitch_strings.humanize_credits(amount)
    response = gt("Reply to this message with %(code)s to confirm your"
                  " transfer of %(amount)s to %(to_num)s. Code expires in ten"
                  " minutes.") % {
                      'code': code,
                      'amount': amount_str,
                      'to_num': to_num
                  }
    return True, response