Ejemplo n.º 1
0
    def end(self):
        try:
            yield super().end()

            if not self.session_start_ok:
                return

            if self.user_state_at_exclusive_login:
                user = User(self.user_state_at_exclusive_login)
            else:
                user = self.handler.user
                yield user.sync('instances')

            is_teacher = (user.status == 'room')
            is_student = (user.status == 'seat')

            # Room Deassign Course
            # Leave seat
            yield self.end_room_usage(user, is_teacher, is_student)

            # User Deassign Course
            yield user.deassign_course(if_last_instance=is_teacher)

            # Decrease Instances
            # (can modify status and course_id)
            yield user.decrease_instances()

        except:
            raise
Ejemplo n.º 2
0
    def end(self):
        try:
            yield super().end()

            if not self.session_start_ok:
                return

            if self.user_state_at_exclusive_login:
                user = User(
                    self.user_state_at_exclusive_login)
            else:
                user = self.handler.user
                yield user.sync('instances')

            is_teacher = (user.status == 'room')
            is_student = (user.status == 'seat')

            # Room Deassign Course
            # Leave seat
            yield self.end_room_usage(
                user, is_teacher, is_student)

            # User Deassign Course
            yield user.deassign_course(
                if_last_instance=is_teacher)

            # Decrease Instances
            # (can modify status and course_id)
            yield user.decrease_instances()

        except:
            raise
Ejemplo n.º 3
0
def login() -> Any:
    """Login user"""
    # Handle already authenticated
    if current_user.is_authenticated:
        return redirect("/app")

    # Render template as default
    provider = request.args.get("provider", None)
    if provider is None:
        return render_template("login.html")

    # Handle login
    info: Dict = {}
    if provider == "azure":
        if not azure.authorized:
            return redirect(url_for("azure.login"))
        else:
            info = azure.get("/v1.0/me").json()
    else:
        pass

    if info:
        email = info["userPrincipalName"]
        user = User.query.filter_by(email=email).first()
        if user is None:
            user = User(email)

        user.authenticated = True
        db.session.add(user)
        db.session.commit()
        login_user(user, True)
        return redirect("/app")
    return redirect("/login")
Ejemplo n.º 4
0
 def post(self):
     '''
     {
         type: "", # two types: "username" and "email"
         value: "" # the value of username or email
     }
     '''
     # if exists then return True and False otherwise
     data = tornado.escape.json_decode(self.request.body)
     field = data.get('type')
     value = data.get('value')
     if field == 'username':
         try:
             User.get(User.username == value)
             result = False
         except peewee.DoesNotExist:
             result = True
     elif field == 'email':
         try:
             User.get(User.email == value)
             result = False
         except peewee.DoesNotExist:
             result = True
     else:
         result = True
     self.write(dict(result=result))
Ejemplo n.º 5
0
    def sign(self):
        username = self.le_username.text()
        password = self.le_pwd.text()
        password2 = self.le_pwd_again.text()
        if len(username) < 8 or len(password) < 8 or len(password2) < 8:
            self.showmsg("length not enough")
            return
        # username = username.replace(" ", "")
        # password = password.replace(" ", "")
        # password2 = password2.replace(" ", "")
        if password != password2:
            self.showmsg("password do not match")
            return
        # 判断库里是不是有重复的

        if User.select().where(User.username == username).count() != 0:
            self.showmsg("username already registered")
            return
        pwd_md5 = hashlib.md5(password.encode("utf-8")).hexdigest()
        pwd2num = passcoder.Utils.str2num(pwd_md5)  # convert string to num

        # 生成rabin公私钥
        rabin = passcoder.PKSRabin()
        rabin_p, rabin_q, rabin_n = rabin.keygen(512)

        # 使用用户的账号的密码进行保护
        rabin_xor_p = rabin_p ^ pwd2num
        rabin_xor_q = rabin_q ^ pwd2num
        # 生成rsa公私钥
        rsa_sign = passcoder.RsaSign()
        sign_p, sign_q, sign_e, sign_d = rsa_sign.k_gen(32)
        sign_xor_p = sign_p ^ pwd2num
        sign_xor_q = sign_q ^ pwd2num
        sign_xor_e = sign_e ^ pwd2num
        sign_xor_d = sign_d ^ pwd2num
        try:
            # create user
            User.create(username=username,
                        pwd=pwd_md5,
                        rabin_p=str(rabin_xor_p),
                        rabin_q=str(rabin_xor_q),
                        rsa_p=str(sign_xor_p),
                        rsa_q=str(sign_xor_q),
                        rsa_e=str(sign_xor_e),
                        rsa_d=str(sign_xor_d))
            self.le_username.setText("")
            self.le_pwd.setText("")
            self.le_pwd_again.setText("")
            self.showmsg("register success,close and return to  login")
        except Exception as e:
            self.showmsg("register failed:{}".format(e))
            return
Ejemplo n.º 6
0
    def key_regen(self):
        username = self.u_name
        try:
            user = User.select().where(User.username == username).get()
            pwd_md5 = user.pwd
            pwd2num = passcoder.Utils.str2num(pwd_md5)
            # 生成rabin公私钥
            rabin = passcoder.PKSRabin()
            rabin_p, rabin_q, rabin_n = rabin.keygen(512)

            # 使用用户的账号的密码进行保护
            rabin_xor_p = rabin_p ^ pwd2num
            rabin_xor_q = rabin_q ^ pwd2num
            # 生成rsa公私钥
            rsa_sign = passcoder.RsaSign()
            sign_p, sign_q, sign_e, sign_d = rsa_sign.k_gen(32)
            sign_xor_p = sign_p ^ pwd2num
            sign_xor_q = sign_q ^ pwd2num
            sign_xor_e = sign_e ^ pwd2num
            sign_xor_d = sign_d ^ pwd2num

            # save
            user.rabin_p = str(rabin_xor_p)
            user.rabin_q = str(rabin_xor_q)
            user.rsa_p = str(sign_xor_p)
            user.rsa_q = str(sign_xor_q)
            user.rsa_e = str(sign_xor_e)
            user.rsa_d = str(sign_xor_d)
            user.save()
            self.showmsg("key regen success")
        except Exception as e:
            self.showmsg("{}".format(e))
Ejemplo n.º 7
0
    def decrypt_msg(self):
        file_path, _ = QFileDialog.getOpenFileName(self,
                                                   "open public key file",
                                                   r"./", "TXT(*.txt)")
        if len(file_path) == 0 or not os.path.exists(file_path):
            self.showmsg("please select correct file ")
            return
        # 读取file文件
        with open(file_path, "r") as f:
            msg = f.read()
        # 加载rabin的私钥
        user = User.select().where(User.username == self.u_name).get()
        pwd_md5 = user.pwd
        pwd2num = passcoder.Utils.str2num(pwd_md5)
        rabin = passcoder.PKSRabin()
        rabin_xor_p = int(user.rabin_p) ^ pwd2num
        rabin_xor_q = int(user.rabin_q) ^ pwd2num
        decrypted_msg = rabin.decrypt(rabin_xor_p, rabin_xor_q, msg)
        try:
            new_filename = "{}-decrypted-msg.txt".format(
                datetime.datetime.now())
            with open(new_filename, "w+") as f:
                f.write(decrypted_msg)
            self.showmsg("decrypted success,file:{}".format(new_filename))

        except Exception as e:
            self.showmsg("decrypted failed:{}".format(e))
Ejemplo n.º 8
0
 def post(self):
     '''
     request body will be
     {
         "username": "******",
         "password": "******",
         "email": "xxx",
     }
     '''
     data = tornado.escape.json_decode(self.request.body)
     data['join_date'] = datetime.datetime.now()
     try:
         User.create(**data)
         result = True
     except peewee.IntegrityError:
         result = False
     # save to database, return True if successfull otherwise False
     self.write(dict(result=result))
Ejemplo n.º 9
0
    def __init__(self, request, response):

        self.initialize(request, response)
        self.gmailuser = users.get_current_user()
        unauthorize = True
        if self.gmailuser:
            self.user = User.get_active_user_by_email(self.gmailuser.email())
            if self.user and self.user.system_owner:
                unauthorize = False
        if unauthorize:
            self.request_unauthorize(request)
Ejemplo n.º 10
0
    def load_user(self, token):
        try:
            uid = jwt.decode(token, verify=False)['id']
            user = yield User.get(uid)
            jwt.decode(token, user.secret)
            self.handler.user = user

        except NoObjectReturnedFromDB as norfdb:
            ite = jwt.InvalidTokenError(
                'No user was found in the database for '
                'this token.')
            raise ite from norfdb
Ejemplo n.º 11
0
def sample_data(engine):
    session = sessionmaker(bind=engine)()
    session.add_all([
        User(external_id=1,
             name="Owner First",
             imported_at=datetime.datetime.now()),
        User(external_id=2,
             name="Owner second",
             imported_at=datetime.datetime.now()),
        User(external_id=3,
             name="owner THIRD",
             imported_at=datetime.datetime.now()),
    ])

    session.add_all([
        Repository(
            external_id=1,
            name="repos/repo",
            owner_id=1,
            languages="python",
            imported_at=datetime.datetime.now(),
        ),
        Repository(
            external_id=2,
            name="repos/repo_2",
            owner_id=2,
            languages="ruby",
            imported_at=datetime.datetime.now(),
        ),
        Repository(
            external_id=3,
            name="repos/repo_3",
            owner_id=3,
            languages="golang",
            imported_at=datetime.datetime.now(),
        ),
    ])
    session.commit()
    session.close()
Ejemplo n.º 12
0
    def load_user(self, token):
        try:
            uid = jwt.decode(token, verify=False)['id']
            user = yield User.get(uid)
            jwt.decode(token, user.secret)
            self.handler.user = user

        except NoObjectReturnedFromDB as norfdb:
            ite = jwt.InvalidTokenError(
                'No user was found in the database for '
                'this token.'
            )
            raise ite from norfdb
Ejemplo n.º 13
0
    def send_room_courses(self, message):
        """Send current room's courses to the client.

        This method is subscribed to the
        ``courses.room.get`` message type.

        The ``user_id`` field of each course is replaced by
        the ``owner`` field. The ``owner`` field contains
        the name of the user, instead of it's ID.

        :param dict message:
            The client's message that executed this method.

        .. todo::
            *   To get the user's names, only one query
                should be made.
                Like: ``User.get_names(id_list)``
        """
        try:
            courses = yield Course.get_courses_from_ids(
                self.handler.room.courses)

            ids = {c['user_id'] for c in courses}
            names = yield {
                id_: User.get_name(id_) for id_ in ids}

            for course in courses:
                course['owner'] = names[
                    course['user_id']
                ]
                del course['user_id']

            self.pub_subs['w'].send_message(
                {'type': 'courses',
                 'courses': courses})

        except AttributeError:
            if not hasattr(self.handler, 'room') or \
                    self.handler.room is None:
                self.handler.send_room_not_loaded_error(
                    message)

            elif not hasattr(self.handler.room, 'courses'):
                """This should never happen again :P."""
                raise

            else:
                raise
Ejemplo n.º 14
0
    def send_room_courses(self, message):
        """Send current room's courses to the client.

        This method is subscribed to the
        ``courses.room.get`` message type.

        The ``user_id`` field of each course is replaced by
        the ``owner`` field. The ``owner`` field contains
        the name of the user, instead of it's ID.

        :param dict message:
            The client's message that executed this method.

        .. todo::
            *   To get the user's names, only one query
                should be made.
                Like: ``User.get_names(id_list)``
        """
        try:
            courses = yield Course.get_courses_from_ids(
                self.handler.room.courses)

            ids = {c['user_id'] for c in courses}
            names = yield {id_: User.get_name(id_) for id_ in ids}

            for course in courses:
                course['owner'] = names[course['user_id']]
                del course['user_id']

            self.pub_subs['w'].send_message({
                'type': 'courses',
                'courses': courses
            })

        except AttributeError:
            if not hasattr(self.handler, 'room') or \
                    self.handler.room is None:
                self.handler.send_room_not_loaded_error(message)

            elif not hasattr(self.handler.room, 'courses'):
                """This should never happen again :P."""
                raise

            else:
                raise
Ejemplo n.º 15
0
 def post(self):
     """Creates new user"""
     first_name, last_name, email, password, u_type = itemgetter(
         'first_name', 'last_name', 'email', 'password',
         'type')(request.json)
     user_object = User.query.filter_by(email=email).first()
     if user_object:
         return jsonify(message='Email is already in database!'), 400
     hashed_password = bcrypt.hashpw(password.encode('utf-8'),
                                     bcrypt.gensalt())
     new_user = User(first_name=first_name,
                     last_name=last_name,
                     email=email,
                     password=hashed_password.decode('utf-8'),
                     user_type=u_type)
     db.session.add(new_user)
     db.session.commit()
     return jsonify(message='User has been inserted!')
Ejemplo n.º 16
0
    def dl_pubkey(self):
        '''
        download rabin public key
        '''
        try:
            # 设置publickey

            file_path = QFileDialog.getExistingDirectory(
                self, "choose path to save", r"./")
            filename = file_path + convert_path("/{}.pub_rabin".format(
                self.u_name))
            print("文件{}".format(filename))
            # 下载rabin key
            user = User.user = User.select().where(
                User.username == self.u_name).get()
            rabin_p, rabin_q, rsa_p, rsa_q, rsa_e, rsa_d = xor_allkey(
                user.username)

            rsa_sign = passcoder.RsaSign()

            rabin_n = str(rabin_q * rabin_p)

            signer = rsa_sign.sign(rsa_d, rsa_p, rsa_q, rabin_n)

            if KeyUtil.gen_pub_key(user.username, rabin_n, signer, filename):

                # 产生rsa的公钥
                KeyUtil.gen_rsa_pubkey(
                    user.username, str(rsa_e), str(rsa_p * rsa_q), file_path +
                    convert_path("/{}.pub_rsa".format(self.u_name)))
                self.showmsg(
                    "save success,file name:{}.pub_rabin,{}.pub_rsa".format(
                        self.u_name, self.u_name))
            else:
                self.showmsg("save success,file failed.format")

        except Exception as e:
            print(e)
            self.showmsg(e)
Ejemplo n.º 17
0
 def post(self):
     '''
     {
         id: "username or email",
         password: "******"
     }
     '''
     # return True if successfull otherwise False
     data = tornado.escape.json_decode(self.request.body)
     identifier = data.get('id')
     password = data.get('password')
     login = True
     try:
         user = User.get(((User.username == identifier) &
                          (User.password == password)) |
                         ((User.email == identifier) &
                          (User.password == password)))
         now = datetime.datetime.now()
         credential = str(uuid.uuid4())
         try:
             lc = LoginRecord.get(
                 ((LoginRecord.username == user.username) &
                  (LoginRecord.valid == True)))
             lc.valid = False
             lc.save()
         except peewee.DoesNotExist:
             pass
         finally:
             LoginRecord.create(
                 username=user.username,
                 login_date=now,
                 credential=credential)
             self.set_cookie('uid', credential)
     except peewee.DoesNotExist:
         login = False
     if login:
         self.write(dict(result=login, username=user.username))
     else:
         self.write(dict(result=login))
Ejemplo n.º 18
0
 def get(self):
   context = self.get_context
   context['user_list']=User.get_active_user_list()
   
   template = self.get_jinja2_env.get_template('html/base.html')    
   self.response.out.write(template.render(context))      
Ejemplo n.º 19
0
def orsen():
	global manwal_kawnt, storyId, endstory, endstorygen, story_list, turn_count, userid, username, secret_code
	
	#print(json.dumps(request.get_json()))
	requestJson = request.get_json()
	
	focus = requestJson["inputs"][0]#["rawInputs"][0]["query"]
	#print(focus["intent"])
    
    #FOR FILES - OPEN
	dm_fileWriter = open(dialogueLogs+ "/" + date+".txt", "a")
	convo_fileWriter = open(convo_path+ "/" + date+".txt", "a")
	ie_fileWriter = open(information_path+ "/" + date+".txt", "a")
	
	#When the app invocation starts, create storyid and greet the user and reset reprompt count
	if focus["intent"] == "actions.intent.MAIN":
		storyId = storyId + 1
		print("STORY ID ",storyId)
		new_world(storyId)
		#reset reprompt count
		manwal_kawnt = 0
		turn_count = 5 #change back to 0
		story_list = []
		#greet user (app.ask)
		data = {"conversationToken":"{\"state\":null,\"data\":{}}","expectUserResponse":True,"expectedInputs":[{"inputPrompt":{"initialPrompts":[{"textToSpeech":"Hi! What's your name?"}],"noInputPrompts":[{"textToSpeech":tts,"displayText":dt}]},"possibleIntents":[{"intent":"actions.intent.TEXT"}]}]}
        
		#FOR 
		convo_fileWriter.write(date + "\n")
		ie_fileWriter.write(date + "\n")
		dm_fileWriter.write(date + "\n")
		convo_fileWriter.write("ORSEN: Hi! What's your name?" + "\n")

	elif focus["intent"] == "actions.intent.GIVE_IDEA_ORSEN":
		data = {"conversationToken":"{\"state\":null,\"data\":{}}","expectUserResponse":True,"expectedInputs":[{"inputPrompt":{"initialPrompts":[{"textToSpeech":"Okay, I will give you a hint"}],"noInputPrompts":[{"textToSpeech":tts,"displayText":dt}]},"possibleIntents":[{"intent":"actions.intent.TEXT"}]}]}
        
        #FOR FILES
		convo_fileWriter.write("ORSEN: Okay, I will give you a hint" + "\n")
	
	
	#When there is no input: ask the user (prompt from model) until maximum count is reached 
	elif focus["intent"] == "actions.intent.NO_INPUT":
		#increment reprompt count
		manwal_kawnt = manwal_kawnt + 1
		#app termination when maximum reprompt count is reached
		if manwal_kawnt == MAKSIMUM_KAWNT:
			data = {"expectUserResponse": False, "finalResponse": {"speechResponse": {"textToSpeech": "Okay. Goodbye"}}}
            
			#FOR FILES - CLOSE
			convo_fileWriter.write("ORSEN: Okay. Goodbye" + "\n")
			convo_fileWriter.close()
			ie_fileWriter.write("~~~ Story Ends Because of No Input ~~~" + "\n")
			ie_fileWriter.close()


			world = server.get_world(storyId)
			dm_fileWriter.write("\n\n")
			dm_fileWriter.write("---DIALOGUE MOVE COUNTS--- \n")
			dm_fileWriter.write("FEEdBACK COUNTS: "+ str(world.feedback_count) + "\n")
			dm_fileWriter.write("GENERAL COUNTS: "+ str(world.general_pump_count) + "\n")
			dm_fileWriter.write("SPECIFIC COUNTS: " + str(world.specific_pump_count) + "\n")
			dm_fileWriter.write("PROMPT COUNTS: " + str(world.prompt_count) + "\n")
			dm_fileWriter.write("HINT COUNTS: " + str(world.hint_count) + "\n")
			dm_fileWriter.write("SUGGEST COUNTS: " + str(world.suggest_count) + "\n")
			dm_fileWriter.write("FOLLOWUP1 COUNTS: " + str(world.followup1_count) + "\n")
			dm_fileWriter.write("FOLLOWUP2 COUNTS: " + str(world.followup2_count) + "\n")

			dm_fileWriter.write("---COMBINATION DIALOGUE MOVE COUNTS--- \n")
			dm_fileWriter.write("F + General: "+ str(world.feedback_general_count) + "\n")
			dm_fileWriter.write("F + Specific: "+ str(world.feedback_specific_count) + "\n")
			dm_fileWriter.write("F + Hinting: "+ str(world.feedback_hint_count) + "\n")
			dm_fileWriter.write("F + Suggesting: "+ str(world.feedback_suggest_count) + "\n")

			dm_fileWriter.write("---SUGGESTION YES/NO--- \n")
			dm_fileWriter.write("Yes: "+ str(world.yes) + "\n")
			dm_fileWriter.write("No: "+ str(world.no) + "\n")

			dm_fileWriter.write("---Follow Up1 Don'tLike/Wrong--- \n")
			dm_fileWriter.write("Don't Like: "+ str(world.dontLike) + "\n")
			dm_fileWriter.write("Wrong: "+ str(world.wrong) + "\n")

			dm_fileWriter.write("---Follow Up2 in/not--- \n")
			dm_fileWriter.write("In Choices: "+ str(world.inChoices) + "\n")
			dm_fileWriter.write("None of the Above: "+ str(world.notInChoices) + "\n")

			dm_fileWriter.write("---GLOBAL + LOCAL CONCEPTS --- \n")
			dm_fileWriter.write("GLOBAL CONCEPT LIST: " + str(world.global_concept_list) + "\n")
			dm_fileWriter.write("LENGTH GLOBAL CONCEPT LIST: " + str(len(world.global_concept_list)) + "\n")
			dm_fileWriter.write("LOCAL CONCEPT LIST: " + str(world.local_concept_list) + "\n")
			dm_fileWriter.write("LENGTH LOCAL CONCEPT LIST: " + str(len(world.local_concept_list)) + "\n")
			dm_fileWriter.write("END OF SESSION")

			dm_fileWriter.close()
		#reprompt user
		else:
			#get the reprompt
			retrieved = retrieve_output("", storyId, userid, dm_fileWriter)
			
			if retrieved.type_num == MOVE_HINT:
				extract_info(userid, retrieved.get_string_response())
	
			output_reply = retrieved.get_string_response()
			#reprompt user
			data = {"conversationToken":"{\"state\":null,\"data\":{}}","expectUserResponse":True,"expectedInputs":[{"inputPrompt":{"initialPrompts":[{"textToSpeech":""+output_reply+""}],"noInputPrompts":[{"textToSpeech":tts,"displayText":dt}]},"possibleIntents":[{"intent":"actions.intent.TEXT"}]}]}
	
	elif turn_count == 1:
		rawTextQuery = requestJson["inputs"][0]["rawInputs"][0]["query"]
		turn_count = turn_count + 1
		username = str(rawTextQuery).split()
		username = username[len(username)-1].lower()
		convo_fileWriter.write("CHILD: My name is " + username + "\n")
		ie_fileWriter.write("Child name is " + username + "\n")
		data = {"conversationToken":"{\"state\":null,\"data\":{}}","expectUserResponse":True,"expectedInputs":[{"inputPrompt":{"initialPrompts":[{"textToSpeech":"Do we have a secret code?"}],"noInputPrompts":[{"textToSpeech":tts,"displayText":dt}]},"possibleIntents":[{"intent":"actions.intent.TEXT"}]}]}
		
	elif turn_count == 2:
		rawTextQuery = requestJson["inputs"][0]["rawInputs"][0]["query"]
		if "yes" in str(rawTextQuery).lower():
			turn_count = turn_count + 2
			data = {"conversationToken":"{\"state\":null,\"data\":{}}","expectUserResponse":True,"expectedInputs":[{"inputPrompt":{"initialPrompts":[{"textToSpeech":"I see, can you tell me what it is?"}],"noInputPrompts":[{"textToSpeech":tts,"displayText":dt}]},"possibleIntents":[{"intent":"actions.intent.TEXT"}]}]}
		else:
			turn_count = turn_count + 1
			data = {"conversationToken":"{\"state\":null,\"data\":{}}","expectUserResponse":True,"expectedInputs":[{"inputPrompt":{"initialPrompts":[{"textToSpeech":"I see, let's make one then. So what will it be?"}],"noInputPrompts":[{"textToSpeech":tts,"displayText":dt}]},"possibleIntents":[{"intent":"actions.intent.TEXT"}]}]}
		
	elif turn_count == 3:
		rawTextQuery = requestJson["inputs"][0]["rawInputs"][0]["query"]
		if str(rawTextQuery) != "":
			secret_code = str(rawTextQuery).split()
			secret_code = secret_code[len(secret_code)-1].lower()
			turn_count = turn_count + 2
			# add to DB
			user = User.User(-1, username, secret_code)
			if DBO_User.get_user_id(username, secret_code) == -1:
				DBO_User.add_user(user)
			# get user id
			userid = DBO_User.get_user_id(username, secret_code)
			data = {"conversationToken":"{\"state\":null,\"data\":{}}","expectUserResponse":True,"expectedInputs":[{"inputPrompt":{"initialPrompts":[{"textToSpeech":"Yey, a new friend! Let's make a story. You go first " + username + "."}],"noInputPrompts":[{"textToSpeech":tts,"displayText":dt}]},"possibleIntents":[{"intent":"actions.intent.TEXT"}]}]}

	elif turn_count == 4:
		rawTextQuery = requestJson["inputs"][0]["rawInputs"][0]["query"]
		secret_code = str(rawTextQuery).split()
		secret_code = secret_code[len(secret_code)-1].lower()
		# check if username and secret code match in db

		userid = DBO_User.get_user_id(username, secret_code)
		
		if userid != -1:
			turn_count = turn_count + 1
			data = {"conversationToken":"{\"state\":null,\"data\":{}}","expectUserResponse":True,"expectedInputs":[{"inputPrompt":{"initialPrompts":[{"textToSpeech":"Oh, you remembered " + username + "! Okay, let's make a story then. You start!"}],"noInputPrompts":[{"textToSpeech":tts,"displayText":dt}]},"possibleIntents":[{"intent":"actions.intent.TEXT"}]}]}
		else:
			print("try again")
			data = {"conversationToken":"{\"state\":null,\"data\":{}}","expectUserResponse":True,"expectedInputs":[{"inputPrompt":{"initialPrompts":[{"textToSpeech":"Hmm, I don't think that was our secret code. Why don't you give it another try " + username + "?"}],"noInputPrompts":[{"textToSpeech":tts,"displayText":dt}]},"possibleIntents":[{"intent":"actions.intent.TEXT"}]}]}

	#When there is input, simply pass to model and get reply
	else:
		rawTextQuery = requestJson["inputs"][0]["rawInputs"][0]["query"]
	
		manwal_kawnt =0
		# userId = requestJson["user"]["userId"] # some really long id
		data = {}
		genstory = ""
	
		#print(rawTextQuery + " ["+userId+"]")

		if endstory:
			rawTextQuery = requestJson["inputs"][0]["rawInputs"][0]["query"]
			#If user wants to create another story, create new story and reset reprompt counts
			# if user wants to hear the whole story
			if (not endstorygen) and (rawTextQuery == "yes" or rawTextQuery == "yes." or rawTextQuery == "sure" or rawTextQuery == "sure." or rawTextQuery == "yeah" or rawTextQuery == "yeah."):
				#(edit-addhearstory-p2)swapped the contents of first and this condition
				output_reply = generate_collated_story(server.get_world(storyId))
				print("-----======= GENERATED STORY =======------")
				print(output_reply)
				data = {"conversationToken":"{\"state\":null,\"data\":{}}","expectUserResponse":True,"expectedInputs":[{"inputPrompt":{"initialPrompts":[{"textToSpeech":""+output_reply+""+". Do you want to create another story?"}],"noInputPrompts":[{"textToSpeech":tts,"displayText":dt}]},"possibleIntents":[{"intent":"actions.intent.TEXT"}]}]}
				endstorygen = True
                
				#FOR FILES
				convo_fileWriter.write("CHILD: "+ rawTextQuery + "\n")
				convo_fileWriter.write("ORSEN: "+ output_reply + "Do you want to create another story?" + "\n")
			
			# user does not want to hear the full story
			elif not endstorygen:
				#(edit-addhearstory-p1) changed prompt from 'hear story' to 'create story'
				data = {"conversationToken":"{\"state\":null,\"data\":{}}","expectUserResponse":True,"expectedInputs":[{"inputPrompt":{"initialPrompts":[{"textToSpeech":"Okay. Do you want to create another story?"}],"noInputPrompts":[{"textToSpeech":tts,"displayText":dt}]},"possibleIntents":[{"intent":"actions.intent.TEXT"}]}]}
				endstorygen = True
                
				#FOR FILES
				convo_fileWriter.write("CHILD: "+ rawTextQuery + "\n")
				convo_fileWriter.write("ORSEN: Okay. Do you want to create another story?" + "\n")
				
			# user wants to create a new story
			elif endstorygen and (rawTextQuery == "yes" or rawTextQuery == "yes." or rawTextQuery == "sure" or rawTextQuery == "sure." or rawTextQuery == "yeah" or rawTextQuery == "yeah."):
				#(edit-addhearstory-p2) swapped the contents of first and this condition
				data = {"conversationToken":"{\"state\":null,\"data\":{}}","expectUserResponse":True,"expectedInputs":[{"inputPrompt":{"initialPrompts":[{"textToSpeech":"Okay then, Let's create a story. You start"}],"noInputPrompts":[{"textToSpeech":tts,"displayText":dt}]},"possibleIntents":[{"intent":"actions.intent.TEXT"}]}]}
				manwal_kawnt = 0
				storyId = storyId + 1
				print("STORY ID ",storyId)
				new_world(storyId)
				endstorygen = False
				endstory = False
				story_list = []
				turn_count = 0
                
				#FOR FILES
				convo_fileWriter.write("CHILD: "+ rawTextQuery + "\n")
				convo_fileWriter.write("ORSEN: Okay then, Let's create a story. You start" + "\n")
				
			#If the user does not want to create a new story 
			else:
				#inserted, generatestory
				data = {"expectUserResponse": False, "finalResponse": {"speechResponse": {"textToSpeech": "Thank you. Goodbye"}}}
				endstorygen = False
				endstory = False
				story_list = []
				turn_count = 0
                
				#FOR FILES - CLOSE
				convo_fileWriter.write("CHILD: "+ rawTextQuery + "\n")
				convo_fileWriter.write("ORSEN: Thank you. Goodbye" + "\n")
				end = datetime.datetime.now().strftime("%Y-%m-%d %H-%M-%S")
				convo_fileWriter.write(end)
				convo_fileWriter.close()

				ie_fileWriter.write("~~~ End Session ~~~")
				ie_fileWriter.write(end)
				ie_fileWriter.close()
				
		#when the user says they want to stop telling the story
		elif rawTextQuery.lower() == "bye" or rawTextQuery.lower() == "the end" or rawTextQuery.lower() == "the end.":
			#(edit-addhearstory-p1) changed the prompt from 'create another story' to 'hear full story'
			data = {"conversationToken":"{\"state\":null,\"data\":{}}","expectUserResponse":True,"expectedInputs":[{"inputPrompt":{"initialPrompts":[{"textToSpeech":"Wow. Thanks for the story. Do you want to hear the full story?"}],"noInputPrompts":[{"textToSpeech":tts,"displayText":dt}]},"possibleIntents":[{"intent":"actions.intent.TEXT"}]}]}
			endstory = True
            
			#FOR FILES
			convo_fileWriter.write("CHILD: "+ rawTextQuery + "\n")
			convo_fileWriter.write("ORSEN: Wow. Thanks for the story. Do you want to hear the full story?" + "\n")
            
		else:
			result = None
			story_list.append(rawTextQuery)
			# if the reply is a story, then extract info and add in story. If not, then don't add
			if getCategory(rawTextQuery) == CAT_STORY:
				# you can pass user id here
				story_list[len(story_list)-1] = extract_info(userid, story_list, ie_fileWriter)
				result = get_unkown_word()
			
			if result != None:
				output_reply = "I need help! Please use " + result + " in a sentence."

			else:
				#dialogue
				#get the dialogue regardless of type
				retrieved = retrieve_output(rawTextQuery, storyId, userid, dm_fileWriter)

				if retrieved.type_num == MOVE_HINT:
					extract_info(userid, retrieved.get_string_response(), ie_fileWriter)

				output_reply = retrieved.get_string_response()
				
			data = {"conversationToken":"{\"state\":null,\"data\":{}}","expectUserResponse":True,"expectedInputs":[{"inputPrompt":{"initialPrompts":[{"textToSpeech":""+output_reply+""}],"noInputPrompts":[{"textToSpeech":tts,"displayText":dt}]},"possibleIntents":[{"intent":"actions.intent.TEXT"}]}]}
	
			print("I: ", rawTextQuery)
			print("O: ", output_reply)

			convo_fileWriter.write("Child: " + rawTextQuery + "\n")
			convo_fileWriter.write("ORSEN: " + output_reply + "\n")
	
	
	#if expectedUserResponse is false, change storyId
	
	return jsonify(data)