Beispiel #1
0
def login():
    print("Inside stories login")
    requestJson = request.get_json(silent=True)
    resultJson = requestJson
    print("Test.....", requestJson)
    # userName=resultJson['username']
    #passWord=resultJson['password']
    userName = base64.b64decode(resultJson["username"]).decode("utf-8")
    passWord = base64.b64decode(resultJson["password"]).decode("utf-8")
    print("Username ", userName)
    print("Password", passWord)
    #res={"result":" " }
    try:
        print(User.objects)
        user = User.objects.get(userName=userName)
        session.__setattr__('userid', str(user.id))
        session.__setattr__('username', user.userName)
        session.__setattr__('role', user.role)
        #User.objects.get(userName=userName)
        print(user)
    except:
        res = {"response": " invaliduser", "statusCode": "401"}
        return json.dumps(res)
    try:
        User.objects.get(passWord=passWord)
    except:
        res = {
            "response": "Invalid Password Please verify your login details.",
            "statusCode": "401"
        }
        return json.dumps(res)
    print("User Id", user.id)
    userId = user.id
    username = user.userName
    role = user.role

    res = make_response("Setting a cookie")
    res.set_cookie('role', user.role, max_age=60 * 60 * 24 * 365 * 2)

    #print(type(userId.toHexString()))
    #print(type(userId))
    res = {
        "response": "Valid User",
        "userId": str(userId),
        "statusCode": "200",
        "username": str(username),
        "role": str(role)
    }
    print(res)
    return json.dumps(res)
Beispiel #2
0
def sparkapi(botId):
    #session=requests.session()

    print("Bot Id",botId)
    channel=Channel.objects.get(botId=ObjectId(botId))
    print("Channel",channel)
    headers = {"Authorization": "Bearer %s" % channel.botAccessToken, "Content-Type": "application/json"}

    print("Spark APi Call")
    print("Request JSON ",request.json)
    messageId=request.json.get('data').get('id')
    print("Message Id ",messageId)
    roomId=request.json.get('data').get('roomId')
    print("Room Id ",roomId)
    email=request.json.get('data').get('personEmail')
    print("Email ",email)

    if email!=channel.botEmail:
        print("Inside first if")
        print("--------------------------------")
        if(session.__getattribute__('parameterStatus') and len(session.__getattribute__('parameters'))>=0):
            print("?????????????????????????????????")



            #print("In first if Parameter Status", session.__getattribute__('parameterStatus'))
            #print("In first if Parameters ", session.__getattribute__('parameters'));
            #print("Length of parameters ",len(session.__getattribute__('parameters')))
            paramList=list(session.__getattribute__('parameters'))
            tempParamList=list(session.__getattribute__('parameters'))
            paramLength=len(session.__getattribute__('parameters'))
            #print("Lengtrh....",paramLength)
            #print("Param List",paramList)
            #print("Param List type ", type(paramList))

            if(paramLength!=0):
                parameter=paramList[index]
                print(paramList[index].name)

            messageDetails = requests.get(host + "messages/" + messageId, headers=headers)
            print("Message Details JSON ", messageDetails)
            message = messageDetails.json().get('text')
            print("Message ", message)
            paramDict[parameter.name]=message;
            session.__setattr__('finParam',paramDict)
            if(paramLength > 1):
                payload = {"roomId": roomId, "text": paramList[index+1].prompt, "personEmail": email}
                response = requests.request("POST", "https://api.ciscospark.com/v1/messages/",
                                        data=json.dumps(payload),
                                        headers=headers)


            del paramList[index]

            #print("Length111111 ",len(paramList))
            session.__setattr__('parameters',paramList)

            print()
            #print("Dict.....",session.__getattribute__('finParam'))
            #print("Session parameters length??????? ",len(session.__getattribute__('parameters')))
           #     print(paramLength)
            paramListLength = len(paramList)
            if(paramListLength==0):
                print(paramDict)
                print(list(session.__getattribute__('tempparameters')))
                tempParam=list(session.__getattribute__('tempparameters'))
                story = Story.objects.get(id=ObjectId(session.__getattribute__('storyId')))
                if(story.apiTrigger==True):
                    apiDetails= story.apiDetails
                    print("URL ",apiDetails.url)
                    print("Testing..........")
                    print(type(apiDetails.url))
                    apiURL=apiDetails.url
                    #len1=apiURL.find("?")

                    if story.apiDetails.requestType=="GET":
                     actapi =apiURL+"?"+str(tempParam[0].name)+"="+str(paramDict[tempParam[0].name])
                    else:
                        actapi=apiURL
                    print("before Loop", actapi)
                    print("Length13456789",len(tempParam))
                    temParamLen = len(tempParam)
                    if story.apiDetails.requestType == "GET":

                        for i in range(1,temParamLen-1):
                            actapi+=actapi+"&"+str(tempParam[i])+"="+str(paramDict[tempParam[i]])

                        result = callApi(actapi,
                                     story.apiDetails.requestType,
                                     story.apiDetails.jsonData, story.apiDetails.isJson)
                    else:
                        result = callApi(actapi,
                                         story.apiDetails.requestType,
                                         json.dumps(paramDict), story.apiDetails.isJson)

                    print("Before json..........")

                    if is_json(result):
                        resDict = json.loads(result);

                        if isinstance(resDict, dict) and 'listName' in resDict:
                            resDict = resDict['listName']

                        print("Sdfghjhgfc ", resDict)

                        print("Type of redDict ", type(resDict))
                        print("Keys ", resDict.keys());
                        print("Type of keys", type(resDict.keys))
                        print("Values ", resDict.values())
                        print("Type of values", type(resDict.values))

                        for key in resDict.keys():
                            print("Key", key)

                        for value in resDict.values():
                            print("Value", value)

                        print(type(json.dumps(json.loads(result), indent=4, sort_keys=True)))

                        print("Speech Response", story.speechResponse);

                        resStrong = story.speechResponse
                        lis1 = resStrong.splitlines();
                        print(lis1)
                        data = json.loads(result)
                        tempString = ""
                        try:
                            for id in lis1:
                                tempString += "**" + id + "**" + ": "
                                tempString += data[id] + ""
                                tempString += "<br>"
                        except:
                            payload = {"roomId": roomId, "markdown": "JSON could not be parsed Please verify configuration", "personEmail": email}
                            response = requests.request("POST", "https://api.ciscospark.com/v1/messages/",
                                                        data=json.dumps(payload),
                                                        headers=headers)
                            print(response.text)
                            return response.status_code

                        print("Before")
                        print(type(data))
                        print(type(data.keys()))
                        print(data.values())
                        for key in data.keys():
                            print("Key ", key)
                            print("Value", data[key])
                        print("After")
                        # print (json_normalize(data['flight']))

                        session.__setattr__('storyId', '')
                        session.__setattr__('parameterStatus', False)
                        session.__setattr__('parameters', '')
                        print("testtttttttttttttt,..........", session.__getattribute__('storyId'))

                        if (result):
                            payload = {"roomId": roomId, "markdown": tempString, "personEmail": email}
                            response = requests.request("POST", "https://api.ciscospark.com/v1/messages/",
                                                        data=json.dumps(payload),
                                                        headers=headers)
                            print(response.text)
                            return response.status_code
                        session.__setattribute__('tempparameters', '')
                    else:
                        payload = {"roomId": roomId, "markdown": result, "personEmail": email}
                        response = requests.request("POST", "https://api.ciscospark.com/v1/messages/",
                                                    data=json.dumps(payload),
                                                    headers=headers)
                        print(response.text)

                        session.__setattribute__('tempparameters', '')
                        session.__setattr__('storyId', '')
                        session.__setattr__('parameterStatus', False)
                        session.__setattr__('parameters', '')

                        return response.status_code

            #return response.status_code


            print("Updated param list length ",len(paramList))





        else:
            print("++++++++++++++++++===========")
            messageDetails = requests.get(host + "messages/" + messageId, headers=headers)
            print("Message Details JSON ",messageDetails)
            message=messageDetails.json().get('text')
            print("Message ",message)
            intentClassifier = IntentClassifier()
            try:
                storyId = intentClassifier.predict(message)
                story = Story.objects.get(id=ObjectId(storyId))
            except:
                payload = {"roomId": roomId, "text": "Sorry! i cant find your question", "personEmail": email}
                response = requests.request("POST", "https://api.ciscospark.com/v1/messages/",
                                            data=json.dumps(payload),
                                            headers=headers)
                print(response.status_code)
                return response.status_code
            if (story.parameters):
                session.__setattr__('parameterStatus', True)
                session.__setattr__('parameters',story.parameters)
                session.__setattr__('tempparameters',story.parameters)
                session.__setattr__('storyId',storyId)
                for parameter in story.parameters:
                    payload = {"roomId": roomId, "text": str(parameter.prompt),
                               "personEmail": email}
                    response = requests.request("POST", "https://api.ciscospark.com/v1/messages/",
                                                data=json.dumps(payload),
                                                headers=headers)

                    return response.status_code
            elif (story.apiTrigger and not story.parameters):
                print("In else if where parameters=0 and apitrigger true")
                result1 = callApi(story.apiDetails.url,
                                 story.apiDetails.requestType,
                                 story.apiDetails.jsonData, story.apiDetails.isJson)
                print("Before json..........")

                if is_json(result1):

                    resDict = json.loads(result1);

                    if isinstance(resDict, dict) and 'listName' in resDict:
                        resDict = resDict['listName']

                    print("Sdfghjhgfc ", resDict)

                    print("Type of redDict ", type(resDict))
                    print("Keys ", resDict.keys());
                    print("Type of keys", type(resDict.keys))
                    print("Values ", resDict.values())
                    print("Type of values", type(resDict.values))

                    for key in resDict.keys():
                        print("Key", key)

                    for value in resDict.values():
                        print("Value", value)

                    print(type(json.dumps(json.loads(result1), indent=4, sort_keys=True)))

                    print("Speech Response", story.speechResponse);

                    resStrong = story.speechResponse
                    lis1 = resStrong.splitlines();
                    print(lis1)
                    data = json.loads(result1)
                    tempString = ""
                    for id in lis1:
                        tempString += "**" + id + "**" + ": "
                        tempString += str(data[id]) + ""
                        tempString += "<br>"
                    print("Before")
                    print(type(data))
                    print(type(data.keys()))
                    print(data.values())
                    for key in data.keys():
                        print("Key ", key)
                        print("Value", data[key])
                    print("After")

                    if (result1):
                        payload = {"roomId": roomId, "markdown": tempString, "personEmail": email}
                        response = requests.request("POST", "https://api.ciscospark.com/v1/messages/",
                                                    data=json.dumps(payload),
                                                    headers=headers)
                        print(response.text)
                        return response.status_code

                    # print (json_normalize(data['flight']))
                else:
                    payload = {"roomId": roomId, "markdown": result1, "personEmail": email}
                    response = requests.request("POST", "https://api.ciscospark.com/v1/messages/",
                                                data=json.dumps(payload),
                                                headers=headers)
                    print(response.text)
                    return response.status_code

            payload = {"roomId": roomId, "text": story.speechResponse,
                       "personEmail": email}

            response = requests.request("POST", "https://api.ciscospark.com/v1/messages/", data=json.dumps(payload),
                                        headers=headers)
            print("In send message response", response.status_code)

            return response.status_code
        return ""
    elif(email==channel.botEmail and session.__getattribute__('parameterStatus')==True):
        print("in second if Parameter Status",session.__getattribute__('parameterStatus'))
        print("in second ifParameters ",session.__getattribute__('parameters'));
        return ""
    else:
        print("+++++++++++++++++++++++++++")
        return""
Beispiel #3
0
class SilentUndefined(Undefined):
    def _fail_with_undefined_error(self, *args, **kwargs):
        return 'undefined'

    __add__ = __radd__ = __mul__ = __rmul__ = __div__ = __rdiv__ = \
        __truediv__ = __rtruediv__ = __floordiv__ = __rfloordiv__ = \
        __mod__ = __rmod__ = __pos__ = __neg__ = __call__ = \
        __getitem__ = __lt__ = __le__ = __gt__ = __ge__ = __int__ = \
        __float__ = __complex__ = __pow__ = __rpow__ = \
        _fail_with_undefined_error


endpoint = Blueprint('api', __name__, url_prefix='/api')

session = requests.session()
session.__setattr__('parameterStatus', False)

index=0;

paramDict={}


def callApi(url, type, parameters, headerData, isJson=False,isHeader=False ):
    print(url, type, parameters, isJson, isHeader, headerData)

    if "GET" in type:
        if isJson and isHeader:
            print(parameters)
            response = requests.get(url, json=json.loads(parameters),headers=json.loads(headerData))
        elif isJson:
            print(parameters)