Exemple #1
0
    def add_view(self, request, extra_context=None):
        """Override django admin add_view method for checking the dialer
        setting limit

        **Logic Description**:

            * Before adding a contact, check the dialer setting limit if
              applicable to the user. If matched, the user will be 
              redirected to the contact list
        """
        # Check dialer setting limit
        if request.user and request.method == 'POST':
            # check Max Number of subscribers per campaign
            if check_dialer_setting(request, check_for="contact"):
                msg = _("You have too many contacts per campaign. You are allowed a maximum of %(limit)s") \
                % {'limit': dialer_setting_limit(request, limit_for="contact")}
                messages.error(request, msg)

                # campaign limit reached
                common_send_notification(request, '3')
                return HttpResponseRedirect(reverse(
                            "admin:dialer_campaign_contact_changelist"))

        ctx = {}
        return super(ContactAdmin, self).add_view(request, extra_context=ctx)
Exemple #2
0
    def add_view(self, request, extra_context=None):
        """Override django admin add_view method for checking the dialer
        setting limit

        **Logic Description**:

            * Before adding a contact, check the dialer setting limit if
              applicable to the user. If matched, the user will be 
              redirected to the contact list
        """
        # Check dialer setting limit
        if request.user and request.method == 'POST':
            # check Max Number of subscribers per campaign
            if check_dialer_setting(request, check_for="contact"):
                msg = _("You have too many contacts per campaign. You are allowed a maximum of %(limit)s") \
                % {'limit': dialer_setting_limit(request, limit_for="contact")}
                messages.error(request, msg)

                # campaign limit reached
                common_send_notification(request, '3')
                return HttpResponseRedirect(
                    reverse("admin:dialer_campaign_contact_changelist"))

        ctx = {}
        return super(ContactAdmin, self).add_view(request, extra_context=ctx)
Exemple #3
0
    def import_contact(self, request):
        """Add custom method in django admin view to import CSV file of
        Contacts

        **Attributes**:

            * ``form`` - Contact_fileImport
            * ``template`` - admin/dialer_campaign/contact/import_contact.html

        **Logic Description**:

            * Before adding contact, check the dialer setting limit if
              applicable to the user.
            * Add a new contact which will belong to the logged in user
              via csv file & get the result (Upload success & failure
              statistics)

        **Important variable**:

            * total_rows - Total no. of records in the CSV file
            * retail_record_count - No. of records which are imported from
              The CSV file
        """
        # Check dialer setting limit
        if request.user and request.method == 'POST':
            # check Max Number of subscribers per campaign
            if check_dialer_setting(request, check_for="contact"):
                msg = _("You have too many contacts per campaign. You are allowed a maximum of %(limit)s") \
                % {'limit': dialer_setting_limit(request, limit_for="contact")}
                messages.error(request, msg)

                # campaign limit reached
                common_send_notification(request, '3')
                return HttpResponseRedirect(reverse(
                            "admin:dialer_campaign_contact_changelist"))

        opts = Contact._meta
        app_label = opts.app_label
        file_exts = ('.csv', )
        rdr = ''  # will contain CSV data
        msg = ''
        success_import_list = []
        error_import_list = []
        type_error_import_list = []
        if request.method == 'POST':
            form = Contact_fileImport(request.user, request.POST,
                                      request.FILES)
            if form.is_valid():
                # col_no - field name
                #  0     - contact
                #  1     - last_name
                #  2     - first_name
                #  3     - email
                #  4     - description
                #  5     - status
                #  6     - additional_vars
                # To count total rows of CSV file
                records = csv.reader(request.FILES['csv_file'],
                                 delimiter=',', quotechar='"')
                total_rows = len(list(records))

                rdr = csv.reader(request.FILES['csv_file'],
                                 delimiter=',', quotechar='"')
                contact_record_count = 0
                # Read each Row
                for row in rdr:
                    if (row and str(row[0]) > 0):
                        row = striplist(row)
                        try:
                            # check field type
                            int(row[5])

                            phonebook = \
                            Phonebook.objects.get(pk=request.POST['phonebook'])
                            try:
                                # check if prefix is already
                                # existing in the retail plan or not
                                contact = Contact.objects.get(
                                     phonebook_id=phonebook.id,
                                     contact=row[0])
                                msg = _('Contact already exists !!')
                                error_import_list.append(row)
                            except:
                                # if not, insert record
                                Contact.objects.create(
                                      phonebook=phonebook,
                                      contact=row[0],
                                      last_name=row[1],
                                      first_name=row[2],
                                      email=row[3],
                                      description=row[4],
                                      status=int(row[5]),
                                      additional_vars=row[6])
                                contact_record_count = \
                                    contact_record_count + 1
                                msg = \
                                _('%(contact_record_count)s Contact(s) are uploaded, out of %(total_rows)s row(s) !!')\
                                 % {'contact_record_count': contact_record_count,
                                    'total_rows': total_rows}
                                    # (contact_record_count, total_rows)
                                success_import_list.append(row)
                        except:
                            msg = _("Error : invalid value for import! Check import samples.")
                            type_error_import_list.append(row)
        else:
            form = Contact_fileImport(request.user)

        ctx = RequestContext(request, {
        'title': _('Import Contact'),
        'form': form,
        'opts': opts,
        'model_name': opts.object_name.lower(),
        'app_label': _('Dialer_campaign'),
        'rdr': rdr,
        'msg': msg,
        'success_import_list': success_import_list,
        'error_import_list': error_import_list,
        'type_error_import_list': type_error_import_list,
        })
        return render_to_response(
               'admin/dialer_campaign/contact/import_contact.html',
               context_instance=ctx)
    def create(self, request, **kwargs):
        """POST method of CDR_Store API"""
        logger.debug("CDR API authentication called!")
        auth_result = self._meta.authentication.is_authenticated(request)
        if not auth_result is True:
            raise ImmediateHttpResponse(response=http.HttpUnauthorized())

        logger.debug("CDR API authorization called!")
        auth_result = self._meta.authorization.is_authorized(request, object)

        errors = self._meta.validation.is_valid(request)
        logger.debug("CDR API get called from IP %s" % request.META.get("REMOTE_ADDR"))

        if not errors:

            opt_cdr = request.POST.get("cdr")
            # XML parsing doesn't work if you urldecode first
            # decoded_cdr = urllib.unquote(opt_cdr.decode("utf8"))
            decoded_cdr = opt_cdr
            data = {}
            try:
                import xml.etree.ElementTree as ET

                tree = ET.fromstring(decoded_cdr)
                lst = tree.find("variables")
            except:
                logger.debug("Error parse XML")
                raise

            for j in lst:
                if j.tag in CDR_VARIABLES:
                    data[j.tag] = urllib.unquote(j.text.decode("utf8"))
            for element in CDR_VARIABLES:
                if element in data:
                    data[element] = None
                else:
                    logger.debug("%s not found!")

            # TODO: Add tag for newfies in outbound call
            if not "request_uuid" in data or not data["request_uuid"]:
                # CDR not related to plivo
                error_msg = "CDR not related to Newfies/Plivo!"
                logger.error(error_msg)
                raise BadRequest(error_msg)

            # TODO : delay if not find callrequest
            try:
                # plivo add "a_" in front of the uuid
                # for the aleg so we remove the "a_"
                if data["request_uuid"][1:2] == "a_":
                    request_uuid = data["request_uuid"][2:]
                else:
                    request_uuid = data["request_uuid"]
                obj_callrequest = Callrequest.objects.get(request_uuid=request_uuid)
            except:
                # Send notification to admin
                from dialer_campaign.views import common_send_notification
                from django.contrib.auth.models import User

                recipient_list = User.objects.filter(is_superuser=1, is_active=1)
                # send to all admin user
                for recipient in recipient_list:
                    # callrequest_not_found - notification id 8
                    common_send_notification(request, 8, recipient)

                error_msg = "Error, there is no callrequest for " "this uuid %s " % data["request_uuid"]
                logger.error(error_msg, extra={"stack": True})

                raise BadRequest(error_msg)

            # CREATE CDR - VOIP CALL
            create_voipcall(obj_callrequest, request_uuid, data, data_prefix="", leg="a")

            # List of HttpResponse :
            # https://github.com/toastdriven/django-tastypie/blob/master/tastypie/http.py
            logger.debug("CDR API : Result 200")

            object_list = [{"result": "OK"}]
            obj = CustomXmlEmitter()
            return self.create_response(request, obj.render(request, object_list))

        else:
            if len(errors):
                if request:
                    desired_format = self.determine_format(request)
                else:
                    desired_format = self._meta.default_format

                serialized = self.serialize(request, errors, desired_format)
                response = http.HttpBadRequest(content=serialized, content_type=desired_format)
                raise ImmediateHttpResponse(response=response)
Exemple #5
0
    def import_contact(self, request):
        """Add custom method in django admin view to import CSV file of
        Contacts

        **Attributes**:

            * ``form`` - Contact_fileImport
            * ``template`` - admin/dialer_campaign/contact/import_contact.html

        **Logic Description**:

            * Before adding contact, check the dialer setting limit if
              applicable to the user.
            * Add a new contact which will belong to the logged in user
              via csv file & get the result (Upload success & failure
              statistics)

        **Important variable**:

            * total_rows - Total no. of records in the CSV file
            * retail_record_count - No. of records which are imported from
              The CSV file
        """
        # Check dialer setting limit
        if request.user and request.method == 'POST':
            # check Max Number of subscribers per campaign
            if check_dialer_setting(request, check_for="contact"):
                msg = _("You have too many contacts per campaign. You are allowed a maximum of %(limit)s") \
                % {'limit': dialer_setting_limit(request, limit_for="contact")}
                messages.error(request, msg)

                # campaign limit reached
                common_send_notification(request, '3')
                return HttpResponseRedirect(
                    reverse("admin:dialer_campaign_contact_changelist"))

        opts = Contact._meta
        app_label = opts.app_label
        file_exts = ('.csv', )
        rdr = ''  # will contain CSV data
        msg = ''
        success_import_list = []
        error_import_list = []
        type_error_import_list = []
        if request.method == 'POST':
            form = Contact_fileImport(request.user, request.POST,
                                      request.FILES)
            if form.is_valid():
                # col_no - field name
                #  0     - contact
                #  1     - last_name
                #  2     - first_name
                #  3     - email
                #  4     - description
                #  5     - status
                #  6     - additional_vars
                # To count total rows of CSV file
                records = csv.reader(request.FILES['csv_file'],
                                     delimiter=',',
                                     quotechar='"')
                total_rows = len(list(records))

                rdr = csv.reader(request.FILES['csv_file'],
                                 delimiter=',',
                                 quotechar='"')
                contact_record_count = 0
                # Read each Row
                for row in rdr:
                    if (row and str(row[0]) > 0):
                        row = striplist(row)
                        try:
                            # check field type
                            int(row[5])

                            phonebook = \
                            Phonebook.objects.get(pk=request.POST['phonebook'])
                            try:
                                # check if prefix is already
                                # existing in the retail plan or not
                                contact = Contact.objects.get(
                                    phonebook_id=phonebook.id, contact=row[0])
                                msg = _('Contact already exists !!')
                                error_import_list.append(row)
                            except:
                                # if not, insert record
                                Contact.objects.create(phonebook=phonebook,
                                                       contact=row[0],
                                                       last_name=row[1],
                                                       first_name=row[2],
                                                       email=row[3],
                                                       description=row[4],
                                                       status=int(row[5]),
                                                       additional_vars=row[6])
                                contact_record_count = \
                                    contact_record_count + 1
                                msg = \
                                _('%(contact_record_count)s Contact(s) are uploaded, out of %(total_rows)s row(s) !!')\
                                 % {'contact_record_count': contact_record_count,
                                    'total_rows': total_rows}
                                # (contact_record_count, total_rows)
                                success_import_list.append(row)
                        except:
                            msg = _(
                                "Error : invalid value for import! Check import samples."
                            )
                            type_error_import_list.append(row)
        else:
            form = Contact_fileImport(request.user)

        ctx = RequestContext(
            request, {
                'title': _('Import Contact'),
                'form': form,
                'opts': opts,
                'model_name': opts.object_name.lower(),
                'app_label': _('Dialer_campaign'),
                'rdr': rdr,
                'msg': msg,
                'success_import_list': success_import_list,
                'error_import_list': error_import_list,
                'type_error_import_list': type_error_import_list,
            })
        return render_to_response(
            'admin/dialer_campaign/contact/import_contact.html',
            context_instance=ctx)
    def create(self, request, **kwargs):
        """POST method of CDR_Store API"""
        logger.debug('CDR API authentication called!')
        auth_result = self._meta.authentication.is_authenticated(request)
        if not auth_result is True:
            raise ImmediateHttpResponse(response=http.HttpUnauthorized())

        logger.debug('CDR API authorization called!')
        auth_result = self._meta.authorization.is_authorized(request, object)

        errors = self._meta.validation.is_valid(request)
        logger.debug('CDR API get called from IP %s' % request.META.get('REMOTE_ADDR'))

        if not errors:

            opt_cdr = request.POST.get('cdr')
            #XML parsing doesn't work if you urldecode first
            #decoded_cdr = urllib.unquote(opt_cdr.decode("utf8"))
            decoded_cdr = opt_cdr
            data = {}
            try:
                import xml.etree.ElementTree as ET
                tree = ET.fromstring(decoded_cdr)
                lst = tree.find("variables")
            except:
                logger.debug('Error parse XML')
                raise

            for j in lst:
                if j.tag in CDR_VARIABLES:
                    data[j.tag] = urllib.unquote(j.text.decode("utf8"))
            for element in CDR_VARIABLES:
                if element in data:
                    data[element] = None
                else:
                    logger.debug("%s not found!")

            #TODO: Add tag for newfies in outbound call
            if not 'request_uuid' in data or not data['request_uuid']:
                # CDR not related to plivo
                error_msg = 'CDR not related to Newfies/Plivo!'
                logger.error(error_msg)
                raise BadRequest(error_msg)

            #TODO : delay if not find callrequest
            try:
                # plivo add "a_" in front of the uuid
                # for the aleg so we remove the "a_"
                if data['request_uuid'][1:2] == 'a_':
                    request_uuid = data['request_uuid'][2:]
                else:
                    request_uuid = data['request_uuid']
                obj_callrequest = Callrequest.objects.get(
                    request_uuid=request_uuid)
            except:
                # Send notification to admin
                from dialer_campaign.views import common_send_notification
                from django.contrib.auth.models import User
                recipient_list = User.objects.filter(
                    is_superuser=1,
                    is_active=1)
                # send to all admin user
                for recipient in recipient_list:
                    # callrequest_not_found - notification id 8
                    common_send_notification(request, 8, recipient)

                error_msg = "Error, there is no callrequest for "\
                            "this uuid %s " % data['request_uuid']
                logger.error(error_msg, extra={'stack': True})

                raise BadRequest(error_msg)

            # CREATE CDR - VOIP CALL
            create_voipcall(
                obj_callrequest,
                request_uuid,
                data,
                data_prefix='',
                leg='a')

            # List of HttpResponse :
            # https://github.com/toastdriven/django-tastypie/blob/master/tastypie/http.py
            logger.debug('CDR API : Result 200')

            object_list = [{'result': 'OK'}]
            obj = CustomXmlEmitter()
            return self.create_response(request, obj.render(request, object_list))

        else:
            if len(errors):
                if request:
                    desired_format = self.determine_format(request)
                else:
                    desired_format = self._meta.default_format

                serialized = self.serialize(request, errors, desired_format)
                response = http.HttpBadRequest(
                    content=serialized,
                    content_type=desired_format)
                raise ImmediateHttpResponse(response=response)