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_forms/buyercall/buyercall/blueprints/api2/doc/endpoints/messages.py
import logging

from flask import jsonify, request
from flask_restx import Resource
from sqlalchemy import and_

from buyercall.lib.util_rest import rest_partnership, requires_auth, rest_is_partnership
from buyercall.blueprints.api2.doc import serializers
from buyercall.blueprints.api2.restplus import api
from buyercall.blueprints.sms.views import send_text_message
from buyercall.blueprints.sms.models import Message
from buyercall.blueprints.partnership.models import PartnershipAccount


log = logging.getLogger(__name__)
ns = api.namespace('Messages', description='Operations related to messages.', path='/accounts')


@ns.route('/<int:paid>/messages/<int:mid>')
@api.doc(responses={200: 'OK',
                    400: 'Error performing operation.',
                    401: 'Unauthorized request.'},
         params={'paid': 'The partner account Id',
                 'mid': 'The message Id'})
class ApiMessage(Resource):
    @requires_auth
    def get(self, paid, mid):
        """
        Retrieve a message for a partnership account.

        <p>
        The Messages API GET endpoint should be used to retrieve information on a single text message for
        a specific partner account.
        </p>
        <br />
        <p>
        You will require a partner authentication token, a partner account id and a text message id to make a
        successful request.  A response will
        be returned, similar to the example below, based
        on a successful request:
        <br />
        <br />
        </p>
         <pre class="code-background" style="color: white">
       {
          "message": {
            "body_text": "Thanks for the message. We'll be in touch.",
            "created_on": "2019-03-19 03:17:11",
            "delivery_code": null,
            "delivery_type": null,
            "delivery_description": null,
            "direction": "outbound",
            "from": "+13367394103",
            "id": 19,
            "media_url": "",
            "phone_number_id": 56,
            "status": "sent",
            "to": "+17732909650",
            "updated_on": "2019-03-19 03:17:11",
            "originating_number": "+17732909650"
          }
        }
     </pre>
        """
        if rest_is_partnership and rest_partnership is not None:
            message_list = list()
            partnership_account = PartnershipAccount \
                .query \
                .filter(and_(PartnershipAccount.id == paid, PartnershipAccount.partnership_id == rest_partnership.id)) \
                .first()

            if partnership_account is not None:
                found_message = Message \
                    .query \
                    .filter(and_(Message.partnership_account_id == paid, Message.id == mid)) \
                    .first()

                if found_message is not None:
                    result = {
                        "id": str(found_message.id),
                        "created_on": found_message.interaction_time,
                        "updated_on": found_message.updated_time,
                        "to": found_message.to,
                        "from": found_message.from_,
                        "body_text": found_message.body_text,
                        "media_url": found_message.media_url,
                        "status": found_message.status,
                        "delivery_code": found_message.delivery_code,
                        "delivery_type": found_message.delivery_type,
                        "delivery_description": found_message.delivery_description,
                        "direction": found_message.direction,
                        "phone_number_id": found_message.inbound_id,
                        "originating_number": found_message.originating_number
                    }

                    return jsonify(
                        result
                    )
                else:
                    return api.abort(404, message='Message not found.')
            else:
                return api.abort(400, message='Partnership account not found.')
        else:
            return api.abort(401, message='Unauthorized request.')

"""
# DISABLE ENDPOINT
@ns.route('/<int:paid>/messages')
@api.doc(responses={200: 'OK',
                    400: 'Error performing operation.',
                    401: 'Unauthorized request.'},
         params={'paid': 'The partner account Id'})
"""
class ApiMessages(Resource):
    @requires_auth
    def get(self, paid):
        """
        Retrieves all the messages for a partnership account.

        <p>
        The Messages API GET endpoint should be used to retrieve information on all text messages from all phone numbers
        associated with a partner account.
        </p>
        <br />
        <p>
        You will require a partner authentication token and a partner account id to make a
        successful request. A response will
        be returned, similar to the example below, based
        on a successful request:
        <br />
        <br />
        </p>
         <pre class="code-background" style="color: white">
           {
              "messages": [
                {
                  "body_text": "Are you still interested in this vehicle?",
                  "created_on": "2019-04-04 19:57:54",
                  "delivery_code": null,
                  "delivery_type": null,
                  "delivery_description": null,
                  "direction": "outbound",
                  "from": "+13367394103",
                  "id": 20,
                  "media_url": "https://s3-us-west-2.amazonaws.com/buyercall-logo/logo_buyercall_yellow.png",
                  "phone_number_id": 1,
                  "status": "sent",
                  "to": "+17732909650",
                  "updated_on": "2019-04-04 19:57:54",
                  "originating_number": "+17332909650"
                },
                {
                  "body_text": "Thanks for the message. We'll be in touch.",
                  "created_on": "2019-03-19 03:17:11",
                  "delivery_code": null,
                  "delivery_type": null,
                  "delivery_description": null,
                  "direction": "outbound",
                  "from": "+13367394103",
                  "id": 19,
                  "media_url": "",
                  "phone_number_id": 56,
                  "status": "sent",
                  "to": "+17732909650",
                  "updated_on": "2019-03-19 03:17:11",
                  "originating_number": "+17332909650"
                }
              ]
            }
     </pre>

        """
        if rest_is_partnership and rest_partnership is not None:
            message_list = []
            partnership_account = PartnershipAccount \
                .query \
                .filter(and_(PartnershipAccount.id == paid, PartnershipAccount.partnership_id == rest_partnership.id)) \
                .first()

            if partnership_account is not None:
                messages = Message.query.filter(Message.partnership_account_id == paid).all()

                if messages is not None:
                    for message in messages:
                        add_message = {
                            'id': message.id,
                            'created_on': message.interaction_time,
                            'updated_on': message.updated_time,
                            'to': message.to,
                            'from': message.from_,
                            'body_text': message.body_text,
                            'media_url': message.media_url,
                            'status': message.status,
                            'delivery_code': message.delivery_code,
                            'delivery_type': message.delivery_type,
                            'delivery_description': message.delivery_description,
                            'direction': message.direction,
                            'phone_number_id': message.inbound_id,
                            'originating_number': message.originating_number
                        }
                        message_list.append(add_message)

                return jsonify(
                    messages=message_list
                )
            else:
                return api.abort(400, message='Partnership account not found.')
        else:
            return api.abort(401, message='Unauthorized request.')

    @api.response(200, 'Message successfully sent.')
    @api.expect(serializers.message_phonenumber_add, validate=True)
    @requires_auth
    def post(self, paid):
        """
        Sends a text message to a lead.

        <p>
        The Messages API POST endpoint should be used to send text messages to leads or customers using a provisioned
        phone number associated with a partner account.
        </p>
        <br />
        <p>
         Text messages can be sent using any type, 'priority', 'tracking' or 'mobile', of phone number.
        </p>
        <br />
        <p>
        You will require a partner authentication token, a partner account id as well as a phone number id
        to make a successful request.
        """

        if rest_is_partnership and rest_partnership is not None:
            partnership_account = PartnershipAccount \
                .query \
                .filter(and_(PartnershipAccount.id == paid,
                             PartnershipAccount.partnership_id == rest_partnership.id)) \
                .first()

            if partnership_account is not None:
                received = request.json

                if received is not None:
                    result_media_url = ''
                    result_body = received['body']
                    result_phonenumber_id = received['phone_number_id']
                    result_number = received['number']

                    if 'media' in received:
                        result_media_url = received['media']
                    else:
                        result_media_url = ''

                    try:
                        send_text_message(result_phonenumber_id, result_number, result_body, result_media_url)

                        return True, 204
                    except Exception as e:
                        log.error('Error send message. Error: ' + str(e))
                        return api.abort(code=400, message="Error sending message.")
                else:
                    return api.abort(400)
            else:
                return api.abort(code=400, message="Error sending message. Partnership account not found.")
        else:
            return api.abort(401)