Esempio n. 1
0
def unregister(smsrequest):
    bb_dbconnector_factory.DBConnectorInterfaceFactory().create(
    ).add_analytics_record("Count", "Command-UNREGISTER",
                           smsrequest.instancename)

    if len(smsrequest.requestcommandlist) < 2:
        return notEnoughDeRegistrationDetails(smsrequest.servicenumber,
                                              smsrequest.requestormobile)

    if len(smsrequest.requestcommandlist) > 2:
        message = "You have provided too many details in your text. Unregister text should be 'UNREGISTER AB125DF'."
        bb_sms_handler.send_sms_notification(smsrequest.servicenumber,
                                             smsrequest.requestormobile,
                                             message)
        return "<Response></Response>"

    try:
        smsrequest.requestorreg = smsrequest.requestcommandlist[1].upper()

        if bb_dbconnector_factory.DBConnectorInterfaceFactory().create(
        ).remove_registration(smsrequest.requestorreg,
                              smsrequest.requestormobile) == 1:
            message = "Car " + smsrequest.requestorreg + " has been unregistered from BlockBuster."
            logger.debug(message)
            bb_sms_handler.send_sms_notification(smsrequest.servicenumber,
                                                 smsrequest.requestormobile,
                                                 message)

        elif bb_dbconnector_factory.DBConnectorInterfaceFactory().create(
        ).remove_registration(smsrequest.requestorreg,
                              smsrequest.requestormobile) == 0:
            message = "Car is not registered to this mobile number."
            logger.debug(message)
            bb_sms_handler.send_sms_notification(smsrequest.servicenumber,
                                                 smsrequest.requestormobile,
                                                 message)

        elif bb_dbconnector_factory.DBConnectorInterfaceFactory().create(
        ).remove_registration(smsrequest.requestorreg,
                              smsrequest.requestormobile) == -1:
            message = "Unable to unregister car " + smsrequest.requestorreg + " - please report the issue."
            logger.error("Unable to unregister car " +
                         smsrequest.requestorreg + ".")
            bb_sms_handler.send_sms_notification(smsrequest.servicenumber,
                                                 smsrequest.requestormobile,
                                                 message)

        else:
            raise Exception("Unable to unregister this car at this time.")
            logger.error("Unable to unregister car at this time.")

    except Exception, e:
        bb_auditlogger.BBAuditLoggerFactory().create().logException(e)
        message = "Unable to unregister car " + smsrequest.requestorreg + " - please report the issue."
        logger.error("Unable to unregister car " + smsrequest.requestorreg +
                     ".")
        bb_sms_handler.send_sms_notification(smsrequest.servicenumber,
                                             smsrequest.requestormobile,
                                             message)
Esempio n. 2
0
def within_operational_period():

    try:
        if not timerestriction:
            return True
    except Exception, e:
        bb_auditlogger.BBAuditLoggerFactory().create().logException(e)
        pass
Esempio n. 3
0
 def get_landline_number_string(reg):
     try:
         alt_contact_text = bb_dbconnector_factory.DBConnectorInterfaceFactory(
         ).create().get_landline_from_reg(reg)
         if alt_contact_text != "":
             return (str(alt_contact_text) + "\n")
         else:
             return ""
     except Exception, e:
         bb_auditlogger.BBAuditLoggerFactory().create().logException(e)
         return ""
Esempio n. 4
0
def cardetailsfromdatabase(requestreg):
    try:
        logger.debug("Retrieving Details From Database For Registration: " +
                     requestreg)
        dict = bb_dbconnector_factory.DBConnectorInterfaceFactory().create(
        ).getCarDetailsAsDictionary(requestreg)
        drivername = dict['FirstName'] + " " + dict['Surname']
        logger.debug("Car Owner Is: " + drivername)
        return "Car " + requestreg + " belongs to " + drivername
    except Exception, e:
        bb_auditlogger.BBAuditLoggerFactory().create().logException(e)
        return ""
Esempio n. 5
0
def get_stats():
    result = bb_api_request_processor.APIRequestProcessor()\
        .service_stats_get()
    bb_auditlogger.BBAuditLoggerFactory().create().logAudit(
        'app', 'GET_STATS', str(result))
    return jsonify(stats=result)
Esempio n. 6
0
def post_inboundsms():
    bb_auditlogger.BBAuditLoggerFactory().create().logAudit(
        'app', 'POST_INBOUNDSMS', request.form['Body'])
    return bb_request_processor.process_twilio_request(request)
Esempio n. 7
0
def get_status():
    status = bb_api_request_processor.APIRequestProcessor().service_status_get(
    )
    bb_auditlogger.BBAuditLoggerFactory().create().logAudit(
        'app', 'GET_STATUS', status)
    return status
Esempio n. 8
0
# 3rd Party Imports
from flask import request, Response, make_response
from flask import jsonify
from functools import wraps

# Local Imports
from blockbuster import app
import bb_auditlogger
from blockbuster import bb_request_processor
from blockbuster import bb_api_request_processor
from blockbuster import bb_security

# Set up auditor
bb_auditlogger.BBAuditLoggerFactory().create().logAudit(
    'app', 'STARTUP', 'Application Startup')


def add_response_headers(headers={}):
    """This decorator adds the headers passed in to the response"""
    def decorator(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            resp = make_response(f(*args, **kwargs))
            h = resp.headers
            for header, value in headers.items():
                h[header] = value
            return resp

        return decorated_function

    return decorator
Esempio n. 9
0
def unblock(SMSTo, SMSFrom, SMSList):
    bb_dbconnector_factory.DBConnectorInterfaceFactory().create(
    ).add_analytics_record("Count", "Command-UNBLOCK", instancename)

    def send_unblock_blockee_messages(service_number, unblocker_number,
                                      blockee_number, blocked_reg,
                                      blocker_name, blockee_name):
        messageblockee = blocker_name + " is no longer blocking your car (" + blocked_reg + ") in."

        bb_sms_handler.send_sms_notification(service_number, blockee_number,
                                             messageblockee)

        #Send a push notification if the user wants it
        subject = "You've been unblocked"
        send_push_notification_if_appropriate(service_number, blockee_number,
                                              subject, messageblockee)

        # Ask the notification handler to send out the appropriate notifications
        bb_notification_handler.send_notifications(blockee_number, subject,
                                                   messageblockee)

    def send_unblock_blocker_message(service_number, unblocker_number,
                                     list_of_names):
        messageblocker = "I've told these people that you've moved: \n\n" + list_of_names
        bb_sms_handler.send_sms_notification(service_number, unblocker_number,
                                             messageblocker)

    # Check whether the UNBLOCK command was sent on its own....
    if len(SMSList) < 2:
        logger.debug('Command: UNBLOCK (no reg)')

        list_of_blocks = bb_dbconnector_factory.DBConnectorInterfaceFactory(
        ).create().get_list_of_blocks_for_blocker(SMSFrom)

        # Check the length of the cursor to see how many active blocks there are
        # If there is at least one active block, process those blocks...
        if len(list_of_blocks) > 0:

            list_of_names = ""
            # Iterate through the cursor and process each active block.
            # Send a message to the blockee, and remove the block.
            for block_item in list_of_blocks:
                a = SMSTo
                b = SMSFrom
                c = block_item['blockee_mobile']
                d = block_item['blocked_reg']
                blocker_name = bb_dbconnector_factory.DBConnectorInterfaceFactory(
                ).create().get_name_from_mobile(b)
                blockee_name = bb_dbconnector_factory.DBConnectorInterfaceFactory(
                ).create().get_name_from_reg(d)
                send_unblock_blockee_messages(a, b, c, d, blocker_name,
                                              blockee_name)
                list_of_names = list_of_names + blockee_name + "\n"
                bb_dbconnector_factory.DBConnectorInterfaceFactory().create(
                ).remove_blocks(b, d)

            # Now send a message to the blocker containing a list of all people who were being blocked.
            send_unblock_blocker_message(SMSTo, SMSFrom, list_of_names)
            return "<Response></Response>"

        # If there are no active blocks, inform the unblocker that there are no active blocks found
        else:
            logger.debug("No active blocks found.")
            bb_sms_handler.send_sms_notification(
                SMSTo, SMSFrom, "You are not currently blocking anyone in.")
            return "<Response></Response>"

    # ... or if a registration plate was specified with the UNBLOCK command
    else:
        try:
            blocked_reg = SMSList[1].upper()
        except Exception, e:
            bb_auditlogger.BBAuditLoggerFactory().create().logException(e)
            logger.warn('No Registration Specified')
            respond_noregistrationspecified(SMSTo, SMSFrom)
            return "<Response></Response>"

        # Search the database for the registration number provided
        if checkifregexists(blocked_reg):
            try:
                dict_blockee = bb_dbconnector_factory.DBConnectorInterfaceFactory().create()\
                    .get_user_dict_from_reg(blocked_reg)
                logger.debug(dict_blockee['Surname'])

            except Exception, e:
                bb_auditlogger.BBAuditLoggerFactory().create().logException(e)
                logger.error("Error retrieving user dictionary from reg \n" +
                             str(e))
                pass

            if dict_blockee['Mobile'] == "" or dict_blockee['Mobile'] is None:
                message = "Sorry - that car belongs to " + dict_blockee['FirstName'] + " " \
                          + dict_blockee['Surname'] + " but they do not have a mobile number registered."
                bb_sms_handler.send_sms_notification(SMSTo, SMSFrom, message)
                return "<Response></Response>"

            try:
                dict_blocker = bb_dbconnector_factory.DBConnectorInterfaceFactory().create()\
                    .get_user_dict_from_mobile(SMSFrom)

                logger.debug(dict_blocker['Surname'])

            except Exception, e:
                bb_auditlogger.BBAuditLoggerFactory().create().logException(e)
                message = "Sorry - please register this mobile number to use this BlockBuster service. \n \n " \
                          "Text '?' for help."

                bb_sms_handler.send_sms_notification(SMSTo, SMSFrom, message)

                return "<Response></Response>"
Esempio n. 10
0
def block(SMSTo, SMSFrom, SMSList):
    bb_dbconnector_factory.DBConnectorInterfaceFactory().create(
    ).add_analytics_record("Count", "Command-BLOCK", instancename)

    # Loop through the registrations provided and add them all to an array
    reg_list = []
    total_elements = len(SMSList)
    # Start at element[1} as we have already established that element[0] contains the command by the face we're here.
    e = 1
    while e < total_elements:
        # Skip elements which have come from multiple spaces between registrations in the message.
        if SMSList[e] == "":
            pass
        else:
            reg_list.append(SMSList[e])
        e += 1

    logger.debug("Number of registrations in list is " + str(len(reg_list)))

    # Check that a registration was actually provided. If not, respond to the user.
    if len(reg_list) < 1:
        return respond_noregistrationspecified(SMSTo, SMSFrom)

    # Now work through each of the registrations in the list, working out what the status is, and triggering a
    # notification message if appropriate. Also build up a list of the statuses so that they can be fed back to
    # the user.
    list_of_blockees = ""

    for registration in reg_list:

        logger.debug("Currently processing " + registration)
        blocked_reg = registration.upper()

        # TODO: Refactor the registered check out of this as this is now done at first receipt of the web request
        try:
            dict_blocker = bb_dbconnector_factory.DBConnectorInterfaceFactory().create()\
                    .get_user_dict_from_mobile(SMSFrom)
            logger.debug("Surname of Blocker is " + dict_blocker['Surname'])

        except Exception, e:
            bb_auditlogger.BBAuditLoggerFactory().create().logException(e)
            message = "Sorry - please register this mobile number to use this BlockBuster service. \n \n " \
                "Text '?' for help."

            # Send message to the blocker to advise them to register in order to use the service.
            bb_sms_handler.send_sms_notification(SMSTo, SMSFrom, message)
            return "<Response></Response>"

        # Search the database for the registration number provided
        if checkifregexists(registration.upper()):
            try:
                dict_blockee = bb_dbconnector_factory.DBConnectorInterfaceFactory().create()\
                    .get_user_dict_from_reg(registration.upper())

                logger.debug("Surname of blockee is " +
                             dict_blockee['Surname'])

            except Exception, e:
                bb_auditlogger.BBAuditLoggerFactory().create().logException(e)
                pass

            # If the blockee does not have a mobile number registered, tell the blocker that they can't be notified,
            # and then continue with the next iteration of the loop.
            if dict_blockee['Mobile'] == '' or dict_blockee['Mobile'] is None:

                list_of_blockees = list_of_blockees + registration.upper() + ": " + "Not Registered (" + dict_blockee['FirstName'] + " " \
                    + dict_blockee['Surname'] + ")\n\n"
                continue

            # Create the message to be sent to the person being blocked in.
            messageblockee = dict_blocker['FirstName'] + " " + dict_blocker['Surname'] + " has blocked in your car " \
                + blocked_reg + ". \n\nText MOVE to ask them to move their car."

            # Send the message to the blockee.
            bb_sms_handler.send_sms_notification(SMSTo, dict_blockee['Mobile'],
                                                 messageblockee)

            #Send a push notification if the user wants it
            subject = "You've been blocked in"
            send_push_notification_if_appropriate(SMSTo,
                                                  dict_blockee['Mobile'],
                                                  subject, messageblockee)

            # Ask the notification handler to send out the appropriate notifications
            bb_notification_handler.send_notifications(dict_blockee['Mobile'],
                                                       subject, messageblockee)

            # Construct the list of blockees
            list_of_blockees = list_of_blockees + registration.upper() + ": " + "Notified (" + dict_blockee['FirstName'] + " " \
                + dict_blockee['Surname'] + ")\n\n"

            # Construct a block record
            block_parameters = {
                "BlockedReg": blocked_reg,
                "BlockeeMobile": dict_blockee['Mobile'],
                "BlockerMobile": SMSFrom
            }

            # Add the block record to the DB
            bb_dbconnector_factory.DBConnectorInterfaceFactory().create(
            ).add_block_record(block_parameters)
Esempio n. 11
0
    def request_single_car_move(reg):

        # Search the database for the registration plate provided
        if checkifregexists(reg):

            # Try and retrieve details from the database for both the blockEE and blockER
            try:
                dict_blocker = bb_dbconnector_factory.DBConnectorInterfaceFactory().create()\
                    .get_user_dict_from_reg(blocking_reg)
                print(dict_blocker)

                dict_blockee = bb_dbconnector_factory.DBConnectorInterfaceFactory().create()\
                    .get_user_dict_from_mobile(requester_number)
                print(dict_blockee)

            except Exception, e:
                bb_auditlogger.BBAuditLoggerFactory().create().logException(e)
                pass

            # If the blocker has a Mobile number (and therefore is registered with BlockBuster) then do this
            if dict_blocker['Mobile'] != "" and dict_blocker['Mobile'] != None:

                # If the blockee is registered with BlockBuster then do this
                if dict_blockee:
                    message = dict_blockee['FirstName'] + " " + dict_blockee['Surname'] + \
                        " needs you to move your car, please.\n\n" \
                        "Text 'OK' to confirm that you have received this."

                    subject = "Please move your car"

                    bb_sms_handler.send_sms_notification(
                        service_number, dict_blocker['Mobile'], message)

                    # Send a push notification if that user wants them
                    send_push_notification_if_appropriate(
                        service_number, dict_blocker['Mobile'], subject,
                        message)

                    # Ask the notification handler to send out the appropriate notifications
                    bb_notification_handler.send_notifications(
                        dict_blocker['Mobile'], subject, message)

                    # Open a move request for that blocker / blockee combination
                    add_move_request(dict_blocker['Mobile'], requester_number)

                    landline_string = get_landline_number_string(blocking_reg)
                    logger.debug(landline_string)

                    blocker_name = dict_blocker[
                        'FirstName'] + " " + dict_blocker['Surname']
                    blocker_mobile = dict_blocker['Mobile']
                    blocker_reg = reg

                    list_of_names = blocker_name + " (" + \
                                    blocker_reg + ")\n" + \
                                    include_mobile_number(blocker_mobile) + \
                                    get_landline_number_string(blocker_reg) + "\n"

                    send_move_blockee_message(service_number, requester_number,
                                              list_of_names)

                # The blockee is not registered with BlockBuster
                # so advise them to register with the service before trying to use it
                else:
                    bb_sms_handler.send_sms_notification(
                        service_number, requester_number,
                        "Sorry - please register this mobile number to use "
                        "this BlockBuster service. \n \n Text '?' for help.")

            # The blockER is not registered with BlockBuster
            # so provide them the name of the car owner
            else:
                bb_sms_handler.send_sms_notification(
                    service_number, requester_number,
                    "Sorry - this car belongs to " +
                    dict_blocker['FirstName'] + " " + dict_blocker['Surname'] +
                    " but they do not have a mobile "
                    "number registered.")
Esempio n. 12
0
def process_twilio_request(request):

    logger.debug(
        '################################ NEW SMS ###############################################'
    )

    if not within_operational_period():
        logger.info("Time restriction mode enabled - ignoring request")
        return "<Response></Response>"

    # Create an instance of an smsrequest object
    smsrequest = bb_types.SMSRequestFactory().create()

    # Extract some information from the http requests
    SMSFrom = str(request.form['From'])
    SMSTo = str(request.form['To'])

    # Strip whitespace from the beginning and end of the body of the message
    SMSBody = str(request.form['Body']).rstrip().lstrip()

    # Populate the smsrequest instance with details of the received request
    smsrequest.requestormobile = str(request.form['From'])
    smsrequest.servicenumber = str(request.form['To'])
    smsrequest.requestbody = str(request.form['Body']).rstrip().lstrip()

    global instancename
    global location
    instancename, location = config_services.identify_service(SMSTo)
    smsrequest.instancename = instancename

    SMSList = combinesplitregistrations(SMSBody, location)
    smsrequest.requestcommandlist = SMSList

    # Set the SMS Service Name to 'Twilio'
    smsservice = "Twilio"
    smsrequest.requestsmsservice = smsservice

    # Add an analytics record for the received request
    bb_dbconnector_factory.DBConnectorInterfaceFactory()\
        .create()\
        .add_analytics_record("Count", "SMS-Receive", instancename)

    # Construct a dictionary containing details for creating a message log entry
    logentry = {
        "Direction":
        "I <----",
        "SMSService":
        smsservice,
        "Command":
        "",
        "Originator":
        SMSFrom,
        "OriginatorName":
        bb_dbconnector_factory.DBConnectorInterfaceFactory().create().
        get_name_from_mobile(SMSFrom),
        "Destination":
        SMSTo,
        "RecipientName":
        instancename,
        "Details":
        SMSBody
    }

    # Construct a dictionary containing details for creating an audit log entry
    audit_entry = "Originator:" + SMSFrom + \
                  ";Receipient:" + SMSTo + \
                  ";Body:" + SMSBody

    # Check the incoming message to see which function has been requested
    commandelement = smsrequest.get_command_element()

    # Define lists of aliases for some of the commands
    start_command_list = ['START']
    help_command_list = ['?']
    move_command_list = ['MOVE', 'M']
    block_command_list = ['BLOCK', 'B']
    unblock_command_list = ['UNBLOCK', 'U']
    unregister_command_list = ['UNREGISTER', 'UR']

    # First, check if the command is one of the following public commands - if so, process the registration.
    if commandelement == "REGISTER":
        logentry['Command'] = "REGISTER"
        bb_dbconnector_factory.DBConnectorInterfaceFactory().create(
        ).add_transaction_record(logentry)
        bb_auditlogger.BBAuditLoggerFactory().create().logAudit(
            'app', 'RCVCMD-REGISTER', audit_entry)
        logger.debug("REGISTER Command Received")
        register(SMSTo, SMSFrom, SMSList, location)
        return "<Response></Response>"

    if commandelement in start_command_list:
        logentry['Command'] = "START"
        bb_dbconnector_factory.DBConnectorInterfaceFactory().create(
        ).add_transaction_record(logentry)
        bb_auditlogger.BBAuditLoggerFactory().create().logAudit(
            'app', 'RCVCMD-START', audit_entry)
        workflow.command_start.go(smsrequest)
        return "<Response></Response>"

    if commandelement in help_command_list:
        logentry['Command'] = "HELP"
        bb_dbconnector_factory.DBConnectorInterfaceFactory().create(
        ).add_transaction_record(logentry)
        bb_auditlogger.BBAuditLoggerFactory().create().logAudit(
            'app', 'RCVCMD-HELP', audit_entry)
        workflow.command_help.go(smsrequest)
        return "<Response></Response>"

    # If not a registration, proceed to check that the requesting user is registered with the service.
    logger.debug("Checking that user is registered...")

    # If the user is not registered, respond asking them to register and write log entries
    if not bb_dbconnector_factory.DBConnectorInterfaceFactory().create()\
            .number_is_registered(smsrequest.requestormobile):

        logger.debug("User is not registered to use this service")
        send_not_registered_SMS(SMSTo, SMSFrom)
        bb_dbconnector_factory.DBConnectorInterfaceFactory().create(
        ).add_transaction_record(logentry)
        bb_auditlogger.BBAuditLoggerFactory().create().logAudit(
            'app', 'NOT-REGISTERED', audit_entry)

        return "<Response></Response>"

    if commandelement in unregister_command_list:
        logger.debug("UNREGISTER Command Received")
        logentry['Command'] = "UNREGISTER"
        bb_dbconnector_factory.DBConnectorInterfaceFactory().create(
        ).add_transaction_record(logentry)
        bb_auditlogger.BBAuditLoggerFactory().create().logAudit(
            'app', 'RCVCMD-UNREGISTER', audit_entry)
        return unregister(smsrequest)

    elif commandelement == "WHOIS":
        logger.debug("WHOIS Command Received")
        logentry['Command'] = "WHOIS"
        bb_dbconnector_factory.DBConnectorInterfaceFactory().create(
        ).add_transaction_record(logentry)
        bb_auditlogger.BBAuditLoggerFactory().create().logAudit(
            'app', 'RCVCMD-WHOIS', audit_entry)
        whois(SMSTo, SMSFrom, SMSList)
        return "<Response></Response>"

    elif commandelement in move_command_list:
        logger.debug("MOVE Command Received")
        logentry['Command'] = "MOVE"
        bb_dbconnector_factory.DBConnectorInterfaceFactory().create(
        ).add_transaction_record(logentry)
        bb_auditlogger.BBAuditLoggerFactory().create().logAudit(
            'app', 'RCVCMD-MOVE', audit_entry)
        return move(SMSTo, SMSFrom, SMSList)

    elif commandelement in block_command_list:
        logger.debug("BLOCK Command Received")
        logentry['Command'] = "BLOCK"
        bb_dbconnector_factory.DBConnectorInterfaceFactory().create(
        ).add_transaction_record(logentry)
        bb_auditlogger.BBAuditLoggerFactory().create().logAudit(
            'app', 'RCVCMD-BLOCK', audit_entry)
        return block(SMSTo, SMSFrom, SMSList)

    elif commandelement in unblock_command_list:
        logger.debug("UNBLOCK Command Received")
        logentry['Command'] = "UNBLOCK"
        bb_dbconnector_factory.DBConnectorInterfaceFactory().create(
        ).add_transaction_record(logentry)
        bb_auditlogger.BBAuditLoggerFactory().create().logAudit(
            'app', 'RCVCMD-UNBLOCK', audit_entry)
        return unblock(SMSTo, SMSFrom, SMSList)

    elif commandelement == "OK":
        logger.debug("MOVE Request Acknowledged")
        logentry['Command'] = "OK"
        bb_dbconnector_factory.DBConnectorInterfaceFactory().create(
        ).add_transaction_record(logentry)
        bb_auditlogger.BBAuditLoggerFactory().create().logAudit(
            'app', 'RCVCMD-ACK', audit_entry)
        acknowledge_move_request(SMSTo, SMSFrom, SMSList)
        return "<Response></Response>"

    elif commandelement == ".":
        logger.debug("STATUS Command Received")
        logentry['Command'] = "STATUS"
        bb_dbconnector_factory.DBConnectorInterfaceFactory().create(
        ).add_transaction_record(logentry)
        bb_auditlogger.BBAuditLoggerFactory().create().logAudit(
            'app', 'RCVCMD-STATUS', audit_entry)
        current_status(smsrequest)
        return "<Response></Response>"

    elif commandelement == "PUSH":
        logger.debug("PUSH Command Received")
        logentry['Command'] = "ADD_PUSHOVER_TOKEN"
        bb_dbconnector_factory.DBConnectorInterfaceFactory().create(
        ).add_transaction_record(logentry)
        bb_auditlogger.BBAuditLoggerFactory().create().logAudit(
            'app', 'RCVCMD-SETTING', audit_entry)
        push(SMSTo, SMSFrom, SMSList)
        return "<Response></Response>"

    elif commandelement == "SET":
        logger.debug("SET Command Received")
        logentry['Command'] = "SETTING"
        bb_dbconnector_factory.DBConnectorInterfaceFactory().create(
        ).add_transaction_record(logentry)
        bb_auditlogger.BBAuditLoggerFactory().create().logAudit(
            'app', 'RCVCMD-SETTING', audit_entry)
        user_settings.setting(SMSTo, SMSFrom, SMSList)
        return "<Response></Response>"

    else:
        logger.debug("Command Not Recognised - Assuming WHOIS")
        logentry['Command'] = "WHOIS"
        bb_dbconnector_factory.DBConnectorInterfaceFactory().create(
        ).add_transaction_record(logentry)
        bb_auditlogger.BBAuditLoggerFactory().create().logAudit(
            'app', 'RCVCMD-WHOIS', audit_entry)

        # Format the registration number so that it is all capitals
        uppercasereg = SMSBody.upper().replace(" ", "")
        logger.debug("Using Registration Plate: " + uppercasereg)
        bb_sms_handler.send_sms_notification(SMSTo, SMSFrom,
                                             cardetails(uppercasereg))
        return "<Response></Response>"
def contact_settings(bb_service_number, user_mobile, sms_list):

    # If the user sends a command of "SET CONTACT MOBILE OFF", mobile number sharing for them will be disabled.
    if len(sms_list) > 3 and sms_list[2].upper() == "MOBILE" and sms_list[3].upper() == "OFF":
        # Log that the user has chosen to disable sharing of their mobile number
        logger.debug("Updating user setting Share_Mobile to OFF")

        # Attempt to disable mobile number sharing for this user - will return a success code of 0 (success) or 1 (fail)
        success_code = bb_dbconnector_factory.DBConnectorInterfaceFactory()\
            .create().disable_mobile_number_sharing(user_mobile)

        if success_code == 0:
            result = "Share Mobile Number is now OFF."
            logger.info("User Setting Updated: Share Mobile OFF")

        elif success_code == 1:
            result = "There was an issue enabling this setting - please contact BlockBuster support."
            logger.error("Error disabling Share Mobile setting for user.")

        bb_sms_handler.send_sms_notification(bb_service_number, user_mobile, result)

        return

    # If the user sends any other command beginning with "SET CONTACT MOBILE"
    # then mobile number sharing will be enabled for them.
    elif sms_list[2].upper() == "MOBILE":
        # Log that the user has chosen to enable sharing of their mobile number
        logger.debug("Updating user setting Share_Mobile to ON")

        # Attempt to enable mobile number sharing for this user - will return a success code of 0 (success) or 1 (fail)
        success_code = bb_dbconnector_factory.DBConnectorInterfaceFactory()\
            .create().enable_mobile_number_sharing(user_mobile)

        if success_code == 0:
            result = "Share Mobile Number is now ON."
            logger.info("User Setting Updated: Share Mobile ON")

        elif success_code == 1:
            result = "There was an issue enabling this setting - please contact BlockBuster support."
            logger.error("Error enabling Share Mobile setting for user.")

        bb_sms_handler.send_sms_notification(bb_service_number, user_mobile, result)

        return

    # If the user sends a "SET CONTACT CLEAR" command
    # erase any alternative contact text that they have set and enable mobile sharing
    elif sms_list[2].upper() == "CLEAR":
        # Log that the user has chosen to enable sharing of their mobile number
        logger.debug("Clearing alternative contact text and enabling mobile sharing")
        bb_auditlogger.BBAuditLoggerFactory().create().logAudit('app',
                                                                'SETTING-CONTACT-CLEAR',
                                                                "Mobile:" + user_mobile)

        # Attempt to enable mobile number sharing for this user - will return a success code of 0 (success) or 1 (fail)
        success_clear = bb_dbconnector_factory.DBConnectorInterfaceFactory()\
            .create().remove_alternative_contact_text(user_mobile)
        success_code = bb_dbconnector_factory.DBConnectorInterfaceFactory()\
            .create().enable_mobile_number_sharing(user_mobile)

        if success_code == 0 and success_clear == 0:
            result = "Your additional contact information has been cleared and mobile number sharing is enabled."
            logger.info("User Setting Updated: Share Mobile ON and Alternative Contact Info CLEARED.")

        elif success_code == 1 or success_clear == 1:
            result = "There was an issue clearing your contact information - please report this issue."
            # TODO: Create a new logError method on the BBAuditLogger and then convert the below
            # BBAuditLogger.BBAuditLoggerFactory().create().logException('app',
            #                                                            'SETTING-CONTACT-CLEAR',
            #                                                            "Mobile:" + user_mobile)

        bb_sms_handler.send_sms_notification(bb_service_number, user_mobile, result)

        return

    else:
        # Assign the alternative text provided by the user to a variable
        alt_text_last_index = (len(sms_list))
        alternative_text = sms_list[2]
        i = 3
        while i < alt_text_last_index:
            alternative_text = alternative_text + " " + sms_list[i]
            i += 1

        # Log that the user has chosen to update their alternative contact information
        logger.info("Updating user setting with alternative contact information.")
        logger.debug("New contact information: " + alternative_text)

        # Call the method in the DAL to update the alternative contact information for that user.
        # Assign the result to a variable.
        success_code = bb_dbconnector_factory.DBConnectorInterfaceFactory()\
            .create()\
            .update_alternative_contact_text(user_mobile, alternative_text)

        if success_code == 0:
            result = "Alternative contact info has been set to:\n\n \"" + alternative_text + "\""

        elif success_code == 1:
            result = "There was an issue setting the alternative contact info - please contact BlockBuster support."

        # Send an SMS to the user confirming that their details have been updated.
        bb_sms_handler.send_sms_notification(bb_service_number, user_mobile, result)

        return