# coding:utf8 import requests import pickle import json from SQLHelper import SQLHelper_chat, SQLHelper_data # from Action import * import sys import os from collections import defaultdict reload(sys) sys.setdefaultencoding('utf8') class BackgroundConfig(): ''' 根据post的参数保存成配置文件的形式 ''' def __init__(self): self.config_string = "" self.CONFIG_DIC = {} # 存储全局配置文件的信息 self.load_global_config("global_config.txt") self.sql_helper = SQLHelper_chat() self.data_helper = SQLHelper_data() def load_global_config(self, engine_config_file): config = open(engine_config_file, 'r') for line in config: if line.strip() == "": continue name, value = line.split("|") self.CONFIG_DIC[name] = value.strip() def reload_background_config(self, userName, botName, botId): # 向前端返回后台机器人配置文件 userFile = "data/" + userName + "-" + botName + '-config.data' return_param = {"configList": []} _, config_str = self.data_helper.query_data_by_id(botId) if config_str != "" and config_str != json.dumps(return_param, ensure_ascii=False): return_param = {"configList": json.loads(config_str)} elif os.path.isfile(userFile): try: userFile = open(userFile, 'r') return_param = {"configList": pickle.load(userFile)} userFile.close() except IOError: return_param = {"configList": []} return return_param ''' 保存配置文件 ''' def generate_background_config(self, parameters): flag = 1 try: configList = parameters["configList"] # self.config_string += self.load_extra_user_info(userName, botName, botId) self.config_str = "" for config in configList: config_line = self.generate_single_config(config) if config_line == "error": flag = 2 break self.config_string += config_line print self.config_string, flag except KeyError as e: print repr(e) flag = 2 return flag def save_bg_config(self, parameters): str_j = json.dumps(parameters, ensure_ascii=False) flag = self.data_helper.update_config_by_id(int(parameters["botId"]), str_j) if flag == 3 and self.data_helper.query_data_by_id(parameters["botId"])[1] == str_j: flag = 1 return flag def load_extra_user_info(self, userName, botName, botId): ''' 从用户之前创建的action中获取额外信息,如设为active的action ''' extra_info = "" action_str, _ = self.data_helper.query_data_by_id(botId) user_data = json.loads(action_str) conditionList = user_data["conditionList"] for condition in conditionList: if condition["active"]: extra_info += "-extraInfo-|activeAction|" + condition["conditionName"] + "\n" return extra_info def change_bg_config(self, botId, userName, botName, conditionList): ''' 从数据库中读取用户之前保存的数据,如果存在已经被删除的condition,就将相应信息删除 ''' _, config_str = self.data_helper.query_data_by_id(botId) user_data = json.loads(config_str) if config_str != "" else {"configList": []} condition_name_list = [condition["conditionName"] for condition in conditionList] config_list = user_data["configList"] config_list_new = [] for config in config_list: config["nextStep"] = config["nextStep"] if config["nextStep"] in condition_name_list else "" # currentPremiseList = config["currentPremiseList"] currentPremiseList = [] for premise in config["currentPremiseList"]: if premise["actionName"] in condition_name_list: currentPremiseList.append(premise) else: premise["actionName"] = premise["keywords"] = premise["question"] = "" currentPremiseList.append(premise) historyPremiseList = [] for premise in config["historyPremiseList"]: if premise["actionName"] in condition_name_list: historyPremiseList.append(premise) else: premise["actionName"] = premise["keywords"] = premise["question"] = "" historyPremiseList.append(premise) empty_indicator = [1 if premise["actionName"] == "" else 0 for premise in currentPremiseList] if sum(empty_indicator) == len(currentPremiseList): continue config["currentPremiseList"] = currentPremiseList config["historyPremiseList"] = historyPremiseList config_list_new.append(config) user_data["configList"] = config_list_new self.data_helper.update_config_by_id(botId, json.dumps(user_data, ensure_ascii=False)) return 1 def post_bg_config(self, botName): url= self.CONFIG_DIC["config_update_url"] payload= {'userName': botName, 'config_string': self.config_string} ret= requests.post(url, data=payload) if(ret.status_code == 200): return 1 elif(ret.status_code == 111): return 2 else: return 4 # -------------------------------------------------- # --------------配置文件逐个操作------------------- # ------------------------------------------------- def update_config_old(self, parameters): config_line = self.generate_single_config(parameters["configData"]) botId = parameters["botId"] configId = parameters["configId"] categoryId = parameters["categoryId"] configData = json.dumps(parameters["configData"], ensure_ascii=False) configName = parameters["configData"]["configName"] if "configName" in parameters["configData"] else "" flag = self.data_helper.update_config_by_2id(botId, configId, configData, categoryId, configName) # 获得currentPremiseList中的condition列表 conditionList = [premise["actionName"] for premise in parameters["configData"]["currentPremiseList"]] conditionStr = ','.join(conditionList) return flag, config_line + "|configId=" + str(parameters["configId"]) + "---" + conditionStr def delete_config_old(self, parameters): configId = parameters["configId"] botId = parameters["botId"] flag = self.data_helper.delete_config_by_2id(botId, configId) print "delete", flag return flag, "" def insert_config_old(self, parameters): config_line = self.generate_single_config(parameters["configData"]) botId = parameters["botId"] categoryId = parameters["categoryId"] configData = json.dumps(parameters["configData"], ensure_ascii=False) configName = parameters["configData"]["configName"] if "configName" in parameters["configData"] else "" flag, configId = self.data_helper.insert_config_by_2id(botId, categoryId, configData, configName) # 获得currentPremiseList中的condition列表 conditionList = [premise["actionName"] for premise in parameters["configData"]["currentPremiseList"]] conditionStr = ','.join(conditionList) return configId, config_line + "|configId=" + str(configId) + "---" + conditionStr def insert_config(self, parameters): config_line = self.generate_single_config(parameters["configData"]) botId = parameters["botId"] categoryId = parameters["categoryId"] configData = json.dumps(parameters["configData"], ensure_ascii=False) configName = parameters["configData"]["configName"] if "configName" in parameters["configData"] else "" insert_flag, configId = self.data_helper.insert_config_by_2id(botId, categoryId, configData, configName) # 获得currentPremiseList中的condition列表 conditionList = [premise["actionName"] for premise in parameters["configData"]["currentPremiseList"]] conditionStr = ','.join(conditionList) data = config_line + "|configId=" + str(configId) + "---" + conditionStr if insert_flag ==1: post_flag = self.post_single_config_to_backend( {"type": parameters["type"], "configId": configId, "userName": parameters["botName"], "configData": data}) if post_flag != 1: self.data_helper.delete_config_by_2id(botId, configId) # post失败,数据库回滚 final_flag = post_flag else: final_flag = insert_flag return final_flag, "" def delete_config(self, parameters): bg = parameters["back"] configId = parameters["configId"] botId = parameters["botId"] post_flag = bg.post_single_config_to_backend( {"type": parameters["type"], "configId": configId, "userName": parameters["botName"], "configData": ""}) if post_flag == 1: self.data_helper.delete_config_by_2id(botId, configId) return post_flag, "" def update_config(self, parameters): bg = parameters["back"] config_line = self.generate_single_config(parameters["configData"]) botId = parameters["botId"] configId = parameters["configId"] categoryId = parameters["categoryId"] configData = json.dumps(parameters["configData"], ensure_ascii=False) configName = parameters["configData"]["configName"] if "configName" in parameters["configData"] else "" _, originData = self.data_helper.query_config_by_configId(botId, configId) update_flag = self.data_helper.update_config_by_2id(botId, configId, configData, categoryId, configName) # 获得currentPremiseList中的condition列表 conditionList = [premise["actionName"] for premise in parameters["configData"]["currentPremiseList"]] conditionStr = ','.join(conditionList) data = config_line + "|configId=" + str(configId) + "---" + conditionStr if update_flag ==1: post_flag = bg.post_single_config_to_backend( {"type": parameters["type"], "configId": configId, "userName": parameters["botName"], "configData": data}) print "post_flag", post_flag if post_flag != 1: print "roll back" self.data_helper.update_config_by_2id(botId, configId, originData[0][1], originData[0][2], originData[0][3]) final_flag = post_flag else: final_flag = update_flag return final_flag, "" def query_config(self, parameters): botId = parameters["botId"] categoryId = parameters["categoryId"] configs = [] flag, config_list = self.data_helper.query_config_by_2id(botId, categoryId) # lag, config_list = self.data_helper.query_sleeping_config_by_botId(botId) for config in config_list: configData = json.loads(config[1]) configData["configId"] = config[0] configData["categoryId"] = config[2] configs.append(configData) return flag, configs def insert_category(self, parameters): botId = parameters["botId"] categoryParentId = parameters["categoryParentId"] categoryName = parameters["categoryName"] flag, data = self.data_helper.insert_category_by_2id(botId, categoryParentId, categoryName) return flag, data def update_category(self, parameters): botId = parameters["botId"] categoryId = parameters["categoryId"] newCategoryName = parameters["newCategoryName"] flag = self.data_helper.update_category_by_2id(botId, categoryId, newCategoryName) return flag, "" def query_category(self, parameters): botId = parameters["botId"] categoryTree = self.data_helper.query_category_by_botId(botId) treeMap = defaultdict(lambda: dict()) print categoryTree treeMap[0]["children"] = [] for i in range(len(categoryTree)): categoryId = categoryTree[i][0] categoryParentId = categoryTree[i][1] categoryName = categoryTree[i][2] # categoryId->value # categoryName-> label # 修改名称一遍前段处理 treeMap[categoryId] = {"value": categoryId, "label": categoryName} if "children" not in treeMap[categoryParentId]: treeMap[categoryParentId]["children"] = [] treeMap[categoryParentId]["children"].append(treeMap[categoryId]) return 1, {"category": treeMap[0]["children"]} def delete_category(self, parameters): botId = parameters["botId"] categoryId = parameters["categoryId"] delete_list = [categoryId] categoryTree = self.data_helper.query_category_by_botId(botId) for i in range(len(categoryTree)): categoryId = categoryTree[i][0] categoryParentId = categoryTree[i][1] if categoryParentId in delete_list: delete_list.append(categoryId) flag = self.data_helper.batch_delete_category(botId, delete_list) if flag: flag = self.data_helper.batch_delete_config(botId, delete_list) return flag, "" def post_single_config_to_backend(self, parameters): """ 提交单条配置文件操作到后台 """ try: url= self.CONFIG_DIC["config_update_url"] ret= requests.post(url, data=parameters) print ret.text if(ret.status_code == 200): return 1 elif(ret.status_code == 111): return 2 else: return 3 except Exception as e: print repr(e) return 3 def generate_single_config(self, config): feature = "" currentPremiseList = [] for premise in config["currentPremiseList"]: if premise["actionName"] != "" or premise["keywords"] != "" or premise["question"] != "": currentPremiseList.append(premise) print "remove" historyPremiseList = [] for premise in config["historyPremiseList"]: if premise["actionName"] != "" or premise["keywords"] != "" or premise["question"] != "": historyPremiseList.append(premise) reply = config["reply"].strip() if config["reply"] != "" else " " nextStepList = config["nextStepList"] feature = [] if "configStatus" not in config or config["configStatus"] == 0: status = "waiting" elif config["configStatus"] == 1: status = "sleeping" if currentPremiseList is not [] or historyPremiseList is not []: feature.append("match") if "nextStepStatus" not in config: config["nextStepStatus"] = "return" if config["doPost"]: feature.append("post(" + config["postURL"].strip() + ")") if len(nextStepList) > 1 and config["nextStepStatus"] == "return": feature.append("newNext") elif config["nextStepStatus"] == "activate": feature.append("activate") feature = ','.join(feature) if len(currentPremiseList) == 1 and currentPremiseList[0]["keywords"] == "": return "error" elif currentPremiseList == []: curPreStr = " " else: curPreStr = ','.join([currentPremise["actionName"] + "=+" + currentPremise["keywords"].lstrip("+").split("-")[0] for currentPremise in currentPremiseList]) if historyPremiseList != [] and historyPremiseList[0]["keywords"] != "": hisPreStr = ','.join([historyPremise["actionName"] + "=+" + historyPremise["keywords"].lstrip("+").split("-")[0] for historyPremise in historyPremiseList]) else: hisPreStr = " " if len(nextStepList) == 1: nextStr = str(nextStepList[0]["nextStep"]) if nextStepList[0]['nextStep'] != "" else " " else: nextStr = "" for next in nextStepList: nextStr += "," + str(next["nextStep"]) nextStr += "" if next["except"] == [] else ":" + '-'.join(next["except"]) nextStr = nextStr.lstrip(",") if nextStr != "" else " " config_line = curPreStr + "|" + hisPreStr + "|"\ + feature + "|=>|" + reply + "|nextStep=" + nextStr + "|status=" + status return config_line def query_sleeping_config(self, parameters): flag, data = self.data_helper.query_sleeping_config_by_botId(parameters["botId"]) return flag, data def get_config_text(self, parameters): print "get_config_text, userName:", parameters["botName"] payload = {"userName": parameters["botName"]} url= self.CONFIG_DIC["config_update_url"][:-7] + "getConfig" ret= requests.post(url, data=payload) print "ret.text :", ret.text return ret.text # ------------------------------------------------ # -----------------------------------------------