def ksr_special_routing(self, r_user):
    if r_user == "SOS":
        KSR.dispatcher.ds_select_dst(self.DSIDS['MEDIASERVERS'], 4)
        KSR.setbflag(self.FLAGS['FLB_NATB'])
        KSR.xlog.xwarn(
            "Pressed SOS button. Redirect to asterisk for recording. DURI set to:$du"
        )
        return True
    elif r_user == "7298886":
        KSR.xlog.xwarn("Zhilservice")
        KSR.seturi("sip:[email protected]")
        # Просто так From нельзя менять.
        KSR.uac.uac_replace_from_uri("sip:[email protected]")
        KSR.setbflag(self.FLAGS['FLB_NATB'])
        return True
    elif r_user == "VR":
        KSR.hdr.append("X-Route-to: VoiceRecognition\r\n")
        KSR.dispatcher.ds_select_dst(self.DSIDS['MEDIASERVERS'], 4)
        KSR.setbflag(self.FLAGS['FLB_NATB'])
        KSR.xlog.xinfo(
            "Call for voice recognition redirected to Asterisk. DURI set to:$du"
        )
        return True
    elif re.search("^instruction", r_user):
        KSR.dispatcher.ds_select_dst(self.DSIDS['MEDIASERVERS'], 4)
        KSR.setbflag(self.FLAGS['FLB_NATB'])
        KSR.xlog.xinfo(
            "Call redirected to mediaserver. DURI set to:$du RURI:$ru")
        return True
    elif re.search("^STP_", r_user):
        KSR.seturi("sip:{}@interphone.is74.ru:5060".format(r_user))
        KSR.hdr.append("X-Route-to: STP\r\n")
        KSR.setbflag(self.FLAGS['FLB_NATB'])
        KSR.xlog.xinfo("Call redirected to Interphone. RURI set to:$ru")
        return True
    elif KSR.pv.getw("$fU").lower() in test_domofones:
        direct_call = False  # Тестовый звонок напрямую на пользователя
        KSR.setbflag(self.FLAGS['FLB_NATB'])
        if direct_call:
            KSR.setuser("id206670")  # Подставить выбранного пользователя
            if self.ksr_x_route_location() == -255:
                exit()
        else:
            KSR.setdsturi(test_asterisk
                          )  # Маршрутизируем в какой либо сервер принудительно
        KSR.setbflag(self.FLAGS['FLB_NATB'])
        KSR.xlog.xinfo(
            "Test call from $fU to $rU apartment. RURI: $ru DURI: $du")
        return True
    elif re.search("^(.+)\.vd\.is74\.ru$", r_user):
        handset = r_user.split('.')
        uri = 'sip:' + handset.pop(0) + '@' + '.'.join(handset)
        KSR.xlog.xinfo(
            "STP call from $fU to $rU, setting RURI to {}".format(uri))
        KSR.seturi(uri)
        # Просто так From нельзя менять.
        KSR.uac.uac_replace_to_uri(uri)
        KSR.setbflag(self.FLAGS['FLB_NATB'])
        return True
    return False
def ksr_route_async_INVITE(self, msg):
    if KSR.hdr.is_present("UUID") < 0:
        uuid = KSR.pv.getw("$uuid(g)")
        KSR.xlog.xinfo(
            "Add hdr UUID: {}. Call from $fU@$fd:$si to $rU".format(uuid))
        KSR.hdr.append("UUID: {}\r\n".format(uuid))
    else:
        uuid = KSR.pv.getw("$hdr(UUID)")

    self.store_uuid(KSR.pv.getw("$ci"), uuid)
    self.manage_call_status(KSR.pv.getw("$fU"), 'put')

    if KSR.isflagset(self.FLAGS['FLT_FROM_ASTERISK']):
        if KSR.hdr.is_present("X-Kamailio-URI") > 0:
            KSR.hdr.append("X-Kamailio-Timestamp: {}\r\n".format(time.time()))
            if KSR.hdr.is_present("X-URI-Type") < 0:
                # Для звонков на aor/location/handset через RUser
                uri_type = KSR.pv.getw("$rU")
            else:
                uri_type = KSR.pv.getvs("$hdr(X-URI-Type)", "location")
            KSR.seturi(
                re.sub(r"(^<|>$)", "", KSR.pv.getw("$hdr(X-Kamailio-URI)")))
            if uri_type == "location":
                if self.ksr_x_route_location() == -255:
                    return -255
            elif uri_type == "handset":
                KSR.xlog.xwarn(
                    "Call to handset. Replace TURI with RURI:{}".format(
                        KSR.pv.getw("$ru")))
                KSR.uac.uac_replace_to_uri(KSR.pv.getw("$ru"))
            else:
                if KSR.nathelper.handle_ruri_alias() > 0:
                    KSR.xlog.xnotice(
                        "Handling RURI alias. DURI:$du RURI:$ru from $fU")
        else:
            KSR.xlog.xnotice("From asterisk returned Unknow number. Drop it")
            KSR.sl.sl_send_reply(404, "Not here")
            return -255
    elif KSR.isflagset(self.FLAGS['FLT_FROM_GW']):
        r = redis.StrictRedis(host='127.0.0.1',
                              port=6379,
                              db=12,
                              decode_responses=True)
        domophone_name = r.get(KSR.pv.getw("$tU"))
        if domophone_name:
            KSR.seturi('sip:' + str(domophone_name) + '@televoip.is74.ru:7777')
            KSR.xlog.xinfo(
                "call from gw to domophone {}".format(domophone_name))
            if self.ksr_x_route_location() == -255:
                KSR.xlog.xerr("Lookup location error")
                return -255
        else:
            KSR.sl.sl_send_reply(404, "user not found")
            KSR.xlog.xinfo("domophone for call from gw not found")
            return -255
    elif not KSR.isflagset(
            self.FLAGS['FLT_TO_SUBSCRIBER']):  # проверяем наличие флага
        if not self.ksr_special_routing(KSR.pv.getw("$rU")):
            # Re-route to asterisk
            KSR.dispatcher.ds_select_dst(self.DSIDS['MEDIASERVERS'], 4)
            KSR.setbflag(self.FLAGS['FLB_NATB'])
            KSR.xlog.xinfo("Unknown number. Send to Asterisk:$du")
    elif KSR.isflagset(self.FLAGS['FLT_FROM_SUBSCRIBER']) and KSR.isflagset(
            self.FLAGS['FLT_TO_SUBSCRIBER']):
        if KSR.pv.getw("$fU") == self.GLOBALS.get('TEST_ACCAUNT', False):
            KSR.xlog.xnotice("Direct call from test accaunt $fU to $rU")
            if self.ksr_x_route_location() == -255:
                KSR.xlog.xerr("Lookup location error")
                return -255
        else:
            # Лучше по максимуму сузить маску для дропа
            KSR.xlog.xwarn(
                "Old LOGIC (dropping request)::Requested user $rU from $fU:$si"
            )
            KSR.sl.sl_send_reply(403, "Forbidden direct call to user")
            KSR.set_drop()
            return -255

    KSR.rr.record_route()

    if self.ksr_route_relay() == -255:
        return -255
    return 1