Пример #1
0
    def order_deferred_callback(self, widget, ip_side_b, referrer,
                                search_request, callback_planned_for_datetime, phone_number):
        """
        :param widget: callback made from
        :param ip_side_b: client's ip
        :param referrer: site the client has came from
        :param search_request: -
        :param callback_planned_for_datetime: an accurate datetime the callback to be initiated at; should be in the server's timezone
        :return: True or False
        """
        print 'order_deferred_callback', ip_side_b, referrer, search_request, callback_planned_for_datetime, phone_number

        max_delta_sec = 30  # how many seconds is allowed between two deferred callbacks

        if not self.datetime_fits_in_schedule(widget.schedule, callback_planned_for_datetime):
            return False

        # deferred_callbacks_filter = widget.callbacks.filter(
        deferred_callbacks_filter = PendingCallback.filter(
            planned_for_datetime__range=(
                callback_planned_for_datetime - datetime.timedelta(seconds=max_delta_sec),
                callback_planned_for_datetime + datetime.timedelta(seconds=max_delta_sec)),
            callback_status=CALLBACK_STATUS_PLANNED,
        )

        if deferred_callbacks_filter.count() > 0:
            # can't have many deferred callbacks for the same time as we are limited in an
            #  ability to count spent minutes for such cases
            return False

        deferred_callback_info = PendingCallback(
            widget = widget,
            phone_number_side_b = phone_number,
            mtt_callback_call_id = '', 
            ip_side_b = ip_side_b,
            referer = referrer,
            geodata_side_b = ip_to_location(ip_side_b),
            search_request = search_request,
            when = datetime.datetime.now(),
            tracking_history = '',
            callback_status = CALLBACK_STATUS_PLANNED,
            planned_for_datetime = callback_planned_for_datetime,)

        deferred_callback_info.save()
        from tasks import initiate_deferred_callback
        initiate_deferred_callback.schedule(args=(deferred_callback_info,), eta=callback_planned_for_datetime)
        return True
Пример #2
0
    def initiate_callback(phone_number, widget, search_str, rferrer_str, ip_address, pending_callback_id=None):
        """
        Инициирует соединение.
        :param phone_number: телефон клиента
        :param widget: виджет, с которого происходит запрос звонка
        :param search_str: поисковый запрос
        :param rferrer_str: откуда клиент пришёл
        :param ip_address: ip-адрес клиента
        :return:
        """
        
        print 'initiate_callback', phone_number, widget, search_str, rferrer_str, ip_address
        
        try:
            manager = {}
            managers = []
            operators = widget.client.operator_set.all() if widget.related_operators.count() < 1 \
                else widget.related_operators.all()
            for i, operator in enumerate(operators, 1):
                if operator == widget.default_operator:
                    managers.insert(0, {
                        'phone': operator.phone_number,
                        'name': operator.name.encode('utf8').decode('utf8'),
                        'role': operator.position.encode('utf8').decode('utf8'),  # 'Manager', # operator.role,
                        'photo_url': operator.photo_url,
                    })
                    manager = {
                        'phone': operator.phone_number,
                        'name': operator.name.encode('utf8').decode('utf8'),
                        'role': operator.position.encode('utf8').decode('utf8'),  # 'Manager', # operator.role,
                        'photo_url': operator.photo_url,
                    }
                else:
                    managers.append({
                        'phone': operator.phone_number,
                        'name': operator.name.encode('utf8').decode('utf8'),
                        'role': operator.position.encode('utf8').decode('utf8'),  # 'Manager', # operator.role,
                        'photo_url': operator.photo_url,
                    })
            if len(manager) == 0:
                manager = managers[0]
            phoneA = manager['phone']
            phoneB = phone_number
            timeout = widget.time_before_callback_sec
            call_duration = timeout * (len(managers) + 1)
            client_caller_id = widget_settings.CALLFEED_PHONE_NUMBER if widget.operator_incoming_number == Widget.INCOMING_NUMBER_CALLFEED else phoneB
            structs = []
            for i in range(len(managers)):
                m = managers[i]
                structs.append(mtt.MTTProxy.CallbackFollowMeStruct.make(
                    1,
                    int(timeout),
                    str(m['phone'].strip('+')),
                    str(widget.callback_type),
                    m['name']))    
            new_pending_info = None
            if pending_callback_id:
                try:
                    new_pending_info = PendingCallback.objects.get(id=pending_callback_id) 
                    print '        loaded existing PendingCallback (id=%d) : %s' % (new_pending_info.id, new_pending_info)
                except:
                    new_pending_info = None
            if not new_pending_info:
                new_pending_info = PendingCallback(
                    widget = widget,
                    mtt_callback_call_id = '',
                    ip_side_b = ip_address,
                    geodata_side_b = ip_to_location(ip_address),
                    referer = rferrer_str,
                    search_request = search_str,
                    when = datetime.datetime.now(),
                    phone_number_side_b = phone_number,
                    callback_status = CALLBACK_STATUS_STARTED)
                new_pending_info.save()
                pending_callback_id = new_pending_info.id
                print '        new PendingCallback created (id=%d) : %s' % (new_pending_info.id, new_pending_info)
            mttproxy = mtt.MTTProxy(mtt.CUSTOMER_NAME, mtt.LOGIN, mtt.PASSWORD, mtt.api_url)
            mtt_response = mttproxy.makeCallBackCallFollowme(
                mtt.CUSTOMER_NAME,
                b_number=str(phoneB.strip('+')),
                caller_id=str(phoneA.strip('+')),
                callback_url='callfeed.net/tracking/%d' % (new_pending_info.id),
                record_enable=1,
                client_caller_id=str(client_caller_id.strip('+')),
                duration=int(call_duration),
                direction=0,
                caller_description=(u'Соединение абонентов, звонок с номера %s на %s' % (phoneB.strip('+'), phoneA.strip('+'))).encode(locale.getpreferredencoding()),
                callback_follow_me_struct=structs)
            mtt_response_result = mtt_response.get('result', None)
            mtt_response_result['callback_id'] = pending_callback_id 

            if mtt_response_result is None:
                print '        ERROR: makeCallBackCallFollowme returned None'
                return ('error', 'makeCallBackCallFollowme returned None',)
            
            mtt_response_result_callback_id = mtt_response_result.get('callBackCall_id', None)
            if mtt_response_result_callback_id is None:
                print '        ERROR: callBackCall_id is None'
                return ('error', 'callBackCall_id is None',)
                         
            print '        OK! %s' % new_pending_info.mtt_callback_call_id
            return (mtt_response_result, mtt_response.get('message', ''),)
        
        except:
            traceback.print_exc()
            return ('exception', traceback.format_exc(),)