HEX
Server: Apache/2.4.52 (Ubuntu)
System: Linux spn-python 5.15.0-89-generic #99-Ubuntu SMP Mon Oct 30 20:42:41 UTC 2023 x86_64
User: arjun (1000)
PHP: 8.1.2-1ubuntu2.20
Disabled: NONE
Upload Files
File: //home/arjun/projects/buyercall_new/buyercall/buyercall/blueprints/sms/tw_sms_inbound.py
"""
Governs the logic of the incoming lead calls and lead/agent interations.

At any given moment the call is in one of the following states:

* 'NEW': New inbound call
* 'CALLBACK': Callback call, agent called first
* 'LEAD_ONHOLD': Lead selected a routing, placed on hold until agent answers
* 'AGENT_ONHOLD': In a scheduled callback, the agent is called first and placed
  on hold.
* 'CALLBACK_PROMPT': Lead has been waiting for a while and is asked if he wants
  to be called back.
* 'ONGOING': Agent answered/call ongoing.
* 'MISSED': Call ended/lead missed.
* 'CAPTURED': Call ended/lead captured.
"""
from __future__ import print_function
import logging

from flask import Blueprint, request

from buyercall.blueprints.filters import format_phone_number
from buyercall.blueprints.block_numbers.models import Block
from buyercall.extensions import csrf, db

log = logging.getLogger(__name__)

tw_sms_inbound = Blueprint(
    'tw_sms_inbound', __name__, template_folder='templates'
)

provider = "twilio"


@tw_sms_inbound.route('/twiml/inbound/message/<int:inbound_id>', methods=['GET', 'POST'])
@csrf.exempt
def lead_inbound_message(inbound_id):
    # First check if the number sending the message is not blocked
    is_number_blocked = Block.blocked(inbound_id, request.form.get('From', ''))
    if is_number_blocked:
        log.info('This phone number: {} was blocked and this '
                 'message: [ {} ] was not sent'.format(request.form.get('From', ''), request.form.get('Body', '')))
        return ''

    from ..phonenumbers.models import Phone
    inbound = Phone.query.filter(Phone.id == inbound_id).first()

    log.info(inbound.friendly_name)
    log.info(inbound.routing_config.get('configSMSSetup'))

    partnership_account_id = inbound.partnership_account_id

    # import partnership information to get partnership id
    from ..partnership.models import Partnership, PartnershipAccount
    partner_account = PartnershipAccount.query \
        .filter(PartnershipAccount.id == partnership_account_id).first()
    # Get the partner id to get relevant twilio credentails with twilio client
    partner = Partnership.query.filter(Partnership.id == partner_account.partnership_id).first()

    info = request.form
    log.info('The sms info is {}'.format(info))

    from buyercall.lib.util_twilio import subaccount_client
    twilio_client = subaccount_client(inbound.partnership_account.subscription.twilio_subaccount_sid, partner.id)
    message_sid = request.form.get('MessageSid', '')
    log.info('message sid is {}'.format(message_sid))
    message_lookup = twilio_client.messages(message_sid).fetch()

    body = request.form.get('Body', '')
    lead = request.form.get('From', '')
    media_url = request.form.get('MediaUrl0', '')

    if media_url:
        # Send a mms using function in tw celery task
        from ..sms.tw_sms_tasks import tw_forward_mms
        tw_forward_mms(inbound_id, body, lead, media_url, message_lookup)
    else:
        # Send a sms using function in tw celery task
        from ..sms.tw_sms_tasks import tw_forward_sms
        tw_forward_sms(inbound_id, body, lead, message_lookup)

    # This checks the phone number SMS settings first and then perform actions based on the sms configuration
    if inbound.routing_config.get('configSMSSetup') and inbound.routing_config.get('SMSAutoReply'):
        from ..sms.views import send_text_message
        text = inbound.routing_config.get('SMSAutoReplyText') + ' Reply STOP to unsubscribe.'
        media_url = inbound.routing_config.get('SMSAutoReplyImageUrl')
        log.info('The image url is {}'.format(media_url))
        send_text_message(inbound_id, lead, text, media_url)
    else:
        log.info('The SMS Auto Reply is turned off for this phone number: {}'.format(inbound.phonenumber))

    # Check if a sms rule one is one and then apply the rule accordingly
    if inbound.routing_config.get('configSMSSetup') and inbound.routing_config.get('SMSRuleOne'):
        text_body = body.lower()
        lead = format_phone_number(request.form.get('From', ''))
        call_agent = inbound.routing_config.get('SMSRuleOneCallAgent')
        keyword = (inbound.routing_config.get('SMSRuleOneKeyword')).lower()
        action = inbound.routing_config.get('SMSRuleOneAction')
        contact = inbound.routing_config.get('SMSRuleOneRecipientType')
        rule_sms_body = inbound.routing_config.get('SMSRuleOneSMSBody')
        rule_sms_agent = inbound.routing_config.get('SMSRuleOneRecipientAgent')
        rule_sms_custom = inbound.routing_config.get('SMSRuleOneRecipientCustom')
        rule_sms_email_body = inbound.routing_config.get('SMSRuleOneEmailBody')
        custom_email_addresses = inbound.routing_config.get('SMSRuleOneEmails')
        email_agent = inbound.routing_config.get('SMSRuleOneEmailAgent')
        if keyword:
            if keyword in text_body:
                log.info('the keyword: {} is in the message'.format(keyword))
                if action == 'call' and contact == 'lead':
                    log.info('the action is: {} and the contact is: {} and the lead number is: {}'.format(
                        action, contact, lead
                    ))
                    from buyercall.blueprints.sms.tw_sms_tasks import sms_rule_call_lead
                    sms_rule_call_lead.delay(inbound_id, lead, call_agent)
                if action == 'sms' and contact == 'lead':
                    from ..sms.views import send_text_message
                    img_url = ''
                    if lead:
                        send_text_message(inbound_id, lead, rule_sms_body, img_url)
                    else:
                        log.warning('There is no lead phone number set to receive the sms rule base sms.'
                                    ' Inbound id: {}'.format(inbound_id))
                if action == 'sms' and contact == 'agent':
                    from ..sms.views import send_text_message
                    from ..agents.models import Agent
                    if rule_sms_agent:
                        agent_no = Agent.query.filter(Agent.id == rule_sms_agent).first()
                        img_url = ''
                        send_text_message(inbound_id, agent_no.phonenumber, rule_sms_body, img_url)
                    else:
                        log.warning('There is no agent set to receive the sms rule base sms. '
                                    'Inbound id: {}'.format(inbound_id))
                if action == 'sms' and contact == 'custom':
                    from ..sms.views import send_text_message
                    if rule_sms_custom:
                        img_url = ''
                        send_text_message(inbound_id, rule_sms_custom, rule_sms_body, img_url)
                    else:
                        log.warning('There is no custom phone number set to receive the sms rule base sms. '
                                    'Inbound id: {}'.format(inbound_id))
                if action == 'unsubscribe' and contact == 'lead':
                    from ..contacts.models import Contact
                    contact_lead = Contact.query.filter(Contact.phonenumber_1 == lead)\
                        .filter(Contact.partnership_account_id == partnership_account_id).first()
                    contact_lead.is_unsubscribe = True
                    db.session.add(contact_lead)
                    db.session.commit()
                if action == 'email' and contact == 'lead':
                    from ..contacts.models import Contact
                    from ..sms.tasks import send_sms_rule_email
                    contact_lead = Contact.query.filter(Contact.phonenumber_1 == lead)\
                        .filter(Contact.partnership_account_id == partnership_account_id).first()
                    if contact_lead.email:
                        send_sms_rule_email(contact_lead.email, contact_lead.firstname, rule_sms_email_body,
                                            partnership_account_id, info)
                    else:
                        log.warning('There is no contact email address for phone number {}'.format(lead))

                if action == 'email' and contact == 'agent':
                    from ..agents.models import Agent
                    from ..sms.tasks import send_sms_rule_email
                    if email_agent:
                        agent = Agent.query.filter(Agent.id == email_agent).first()
                        send_sms_rule_email(agent.email, agent.firstname, rule_sms_email_body,
                                            partnership_account_id, info)
                if action == 'email' and contact == 'custom':
                    from ..sms.tasks import send_sms_rule_email
                    custom_name = ''
                    send_sms_rule_email(custom_email_addresses, custom_name, rule_sms_email_body,
                                        partnership_account_id, info)
    else:
        log.info('The SMS Rule is turned off for this phone number: {}'.format(inbound.phonenumber))

    return ''