#coding:utf8 import sys; reload(sys); from SQLHelper import * sys.setdefaultencoding('utf8'); import pickle import json import requests class Action: def __init__(self): self.CONFIG_DIC = {} #存储全局配置文件的信息 self.load_global_config("global_config.txt") self.botId = "" self.userName = "" self.botName = "" self.waiting_str = "" self.listening_str = "" self.http_str = "#actions\r\nname=pivot_httppost\r\nstatus=waiting\r\nstyle=httppost\r\nserviceURL=" \ +self.CONFIG_DIC["serviceURL"] + "\r\nautomatchthreshold=" \ +self.CONFIG_DIC["automatchthreshold"] + "\r\n" self.next_str = "" self.FUNC_MAP = {"action":self.parse_name,"status":self.parse_status,"condition":self.parse_condition ,"conflict":self.parse_conflict,"process":self.parse_process} self.ACTION_HEAD_INFO = ["action","strategythreshold","automatchthreshold" ,"pattern","conflict","importance","style"] self.KEYWORD_UNIT_INFO = ["options","AutoMatchURL"] self.condition_name_list = [] self.sql_helper = SQLHelper() 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 generate_action(self,parameters): flag = 1 try: userName = parameters["userName"]#.encode("utf-8") conditionList = parameters["conditionList"] botName = parameters["botName"] botId = parameters["botId"] condition_name_list = ["process=nextStep="+condition["conditionName"]+"|"+condition["conditionName"]+"=active|" for condition in conditionList] print condition_name_list self.all_nextStep = '\r\n'.join(condition_name_list) for condition in conditionList: conditionName = condition["conditionName"]#.encode("utf-8") questionList = [que["que_start_time"]+":"+que["que_stop_time"]+":"+que["que_sen"]+":base" if que["base"] == 1 else que["que_start_time"]+":"+que["que_stop_time"]+":"+que["que_sen"] for que in condition["questionList"]] questionList_str = '~'.join(questionList) repeatList = condition["repeatList"] active_flag = condition["active"] relation = condition["relationHead"]+","+condition["relationName"]+","+condition["relationTail"]#.encode("utf-8") print conditionName print active_flag for i in range(3): self.insert_action_info(conditionName,active_flag,i) self.insert_condition(conditionName,relation,questionList_str,repeatList,i) self.insert_process(conditionName,repeatList,i) self.waiting_str += "process="+conditionName+"=unknown|pivot_httppost=active|\r\n" #add a extra information for backend config file # if active_flag ; # parameters["activeAction"] = conditionName except KeyError as e: print repr(e) return 2 return flag def save_action(self,parameters,auth): userName = parameters["userName"] botName = parameters["botName"] botName_yhm = parameters["botName_yhm"] botId = parameters["botId"] final_str = self.http_str + self.next_str + self.waiting_str+self.listening_str+"\r\n\r\n\r\n" flag,id = self.post_action(final_str,botId,botName_yhm,parameters["cate"],parameters["cdt_name_ls"],auth) if id != "error": botName = self.sql_helper.query_username_by_userid(id) if flag == 1 and botName != "error": userFile = open("data/"+str(userName)+"-"+str(botName)+"-action.txt",'w') userData = open("data/"+str(userName)+"-"+str(botName)+"-action.data",'w') pickle.dump(parameters,userData) userFile.write(final_str) userFile.close() userData.close() flag = 4 if botName == "error" else flag print "sql_query:",botName return flag def reload_action(self,userName,botName): try: userFile = open("data/"+str(userName)+"-"+str(botName)+"-action.data",'r') ''' actionList = [] action = {} for line in userFile: name = line.strip().split("=")[0] if name == "" : if action != {}: actionList.append(action) action = {} else: self.FUNC_MAP[name](line,action) ''' data = pickle.load(userFile) userFile.close() except IOError: data = [] return {"actionList":data} def parse_name(self,text,action): _,name = text.split("=") action["actionName"] = name def parse_status(self,text,action): _,status = text.split("=") action["status"] = status def parse_conflict(self,text,action): _,conflictStr = text.split("=") conflictList = conflictStr.split(",") action["conflictList"] = [] for conflict in conflictList: action["conflictList"].append(conflict) def parse_condition(self,text,action): condition,relation,question,repeatStr = text.split("|") _,conditionName = condition.split("=") action["conditionName"] = conditionName action["relation"] = relation action["question"] = question repeatList = repeatStr.split(",") action["repeatList"] = [] for repeat in repeatList: repeatDic = {} re,keywords = repeat.split("=") repeatDic["repeatString"] = re repeatDic["repeatKeywords"] = keywords action["repeatList"].append(repeatDic) def parse_process(self,text,action): processStr,nextAction,reply = text.split("|") _,proName,keywords = processStr.split("=") process = {} if action["processList"] == None: action["processList"] = [] process["processName"] = proName process["processKeyWords"] = keywords process["nextAction"] = nextAction process["reply"] = reply action["processList"].append(process) def insert_action_info(self,conditionName,active_flag,flag): if not flag: status = "waiting" if not active_flag else "active" print status self.waiting_str += "\r\n\r\nname=" + conditionName + "\r\nstatus="+status+"\r\nstyle=interrupt\r\n" for key in self.ACTION_HEAD_INFO: if(self.CONFIG_DIC[key] != ""): self.waiting_str += key + "=" + self.CONFIG_DIC[key] + '\r\n' self.waiting_str += "fellow=pivot_httppost\r\n" if flag == 1: status = "listening" self.listening_str += "\r\n\r\nname=" + conditionName + "_listening\r\nstatus="+status+"\r\n" for key in self.ACTION_HEAD_INFO: if(self.CONFIG_DIC[key] != ""): self.listening_str += key + "=" + self.CONFIG_DIC[key] + '\r\n' self.listening_str += "fellow=pivot_httppost\r\n" elif flag ==2: ''' for key in self.ACTION_HEAD_INFO: if(self.CONFIG_DIC[key] != ""): self.http_str += key + "=" + self.CONFIG_DIC[key] + '\r\n' ''' def insert_condition(self,conditionName,relation,questionList,repeatList,flag): if not flag: self.waiting_str += "condition="+conditionName+"::1|"+relation+"|"+questionList+"|" repeat_str = [repeat["repeatString"]+"=+"+repeat["repeatKeywords"] for repeat in repeatList] reS = "~".join(repeat_str) self.waiting_str += reS + "\r\n" if flag == 1: self.listening_str += "condition="+conditionName+"|"+relation+"|"+questionList+"|" repeat_str = [repeat["repeatString"]+"=+"+repeat["repeatKeywords"] for repeat in repeatList] reS = "~".join(repeat_str) self.listening_str += reS + "\r\n" if flag == 2: self.http_str += "reference="+conditionName+"|"+relation+"|"+questionList+"|" repeat_str = [repeat["repeatString"]+"=+"+repeat["repeatKeywords"] for repeat in repeatList] reS = "~".join(repeat_str) self.http_str += reS + "\r\n" def insert_process(self,conditionName,repeatList,flag): if not flag: for repeat in repeatList: self.waiting_str += "process="+conditionName+"=+"+repeat["repeatKeywords"].split('-')[0]+"|pivot_httppost=active|\r\n" elif flag == 1: for repeat in repeatList: self.listening_str += "process="+conditionName+"=+"+repeat["repeatKeywords"].split('-')[0]+"|pivot_httppost=active|\r\n" elif flag == 2: self.next_str += "process=nextStep="+conditionName+"|"+conditionName+"=active|\r\n" def post_action(self,action_str,botId,botName_yhm,cate,cdt_name_ls,auth): url = self.CONFIG_DIC["engine_url"] print action_str botId = "" if botId == "undefined" else int(botId) payload= {'id':botId,'botname':botName_yhm,'actions':action_str,'cate':cate,"cdt_name_ls":cdt_name_ls} headers = {"Authorization":auth} ret= requests.post(url,json=payload,headers=headers) print ret.text return_info = json.loads(ret.text) if(ret.status_code == 200 and return_info["status"] == "Success" and botId == ""): keywords = [keyword+"|"+self.CONFIG_DIC[keyword]+"\r\n" for keyword in self.KEYWORD_UNIT_INFO] text = self.sql_helper.query_keyword_unit_by_userid(return_info["id"]) k_unit_str = text + ''.join(keywords) flag = self.sql_helper.update_keyword_unit_by_userid(return_info["id"],k_unit_str) # flag = self.sql_helper.update_url(return_info["id"],self.CONFIG_DIC["get_info_url"]) return flag,return_info["id"] elif(ret.status_code == 200 and return_info["status"] == "Success" and botId != ""): return 1,return_info["id"] else: return 4,"error"