예제 #1
0
    def has_completed_exit_survey(self, user, team_id):
        [response] = Response.get(
            user_id=user.uid,
            team_id=team_id,
            module_label='EPExitSurvey',
            progress=100,
        ) or [None]

        if response:
            return True

        return False
예제 #2
0
    def test_body_too_large(self):
        other, teammate, team, cycles, responses = self.create()

        response_params = {
            'user_id': teammate.uid,
            'team_id': team.uid,
            'parent_id': cycles[1].uid,
            'module_label': 'ModuleBar',
        }

        # A property is too long.
        self.testapp.post_json(
            '/api/responses',
            dict(response_params, body={'foo': {
                'value': 'x' * 10**5
            }}),
            headers=jwt_headers(teammate),
            status=413,
        )

        # Too many properties.
        self.testapp.post_json(
            '/api/responses',
            dict(
                response_params,
                body={'foo{}'.format(x): {
                    'value': x
                }
                      for x in range(10**3)},
            ),
            headers=jwt_headers(teammate),
            status=413,
        )

        # Both posts should have prevented new responses from being stored.
        self.assertEqual(len(Response.get()), len(responses))

        # Successful POST
        resp = self.testapp.post_json(
            '/api/responses',
            dict(response_params, body={'safe': {
                'value': 'data'
            }}),
            headers=jwt_headers(teammate),
        )
        resp_dict = json.loads(resp.body)
        put_url = '/api/responses/{}'.format(resp_dict['uid'])

        # Same errors but for PUT
        # A property is too long.
        self.testapp.put_json(
            put_url,
            {'body': {
                'foo': {
                    'value': 'x' * 10**5
                }
            }},
            headers=jwt_headers(teammate),
            status=413,
        )
        # Too many properties.
        self.testapp.put_json(
            put_url,
            {'body': {'foo{}'.format(x): {
                'value': x
            }
                      for x in range(10**3)}},
            headers=jwt_headers(teammate),
            status=413,
        )

        # Puts should have left body unchanged.
        fetched_body = Response.get_by_id(resp_dict['uid']).body
        self.assertEqual(fetched_body.keys(), ['safe'])
        self.assertEqual(fetched_body['safe']['value'], 'data')
예제 #3
0
def ask(question, lang, sid, query=False, request_id=None, **kwargs):
    response = Response()
    response.Datetime = str(dt.datetime.utcnow())
    response.Rate = ''
    response.Lang = lang
    response.Location = LOCATION
    response.ServerIP = IP
    response.RequestId = request_id
    response.Revision = REVISION

    #response = {'text': '', 'emotion': '', 'botid': '', 'botname': ''}

    session = session_manager.get_session(sid)
    if session is None:
        response.ret = codes.INVALID_SESSION
        return response

    if not question or not question.strip():
        response.ret = codes.INVALID_QUESTION
        return response

    botname = session.session_context.botname
    if not botname:
        logger.error("No botname is specified")
    user = session.session_context.user
    client_id = session.session_context.client_id
    response.BotName = botname
    response.User = user
    response.ClientId = client_id
    response.OriginalQuestion = question

    input_translated = False
    output_translated = False
    fallback_mode = False
    responding_characters = get_responding_characters(lang, sid)
    if not responding_characters and lang != FALLBACK_LANG:
        fallback_mode = True
        logger.warn("Use %s medium language, in fallback mode", FALLBACK_LANG)
        responding_characters = get_responding_characters(FALLBACK_LANG, sid)
        try:
            input_translated, question = do_translate(question, FALLBACK_LANG)
        except Exception as ex:
            logger.error(ex)
            logger.error(traceback.format_exc())
            response.ret = codes.TRANSLATE_ERROR
            return response

    if not responding_characters:
        logger.error("Wrong characer name")
        response.ret = codes.WRONG_CHARACTER_NAME
        return response

    # Handle commands
    if question == ':reset':
        session_manager.dump(sid)
        session_manager.reset_session(sid)
        logger.warn("Session {} is reset by :reset".format(sid))
    for c in responding_characters:
        if c.is_command(question):
            response.update(c.respond(question, lang, session, query, request_id))
            return response

    response['yousaid'] = question

    session.set_characters(responding_characters)
    logger.info("Responding characters %s", responding_characters)
    
    request = Request()
    request.id = request_id
    request.lang = lang
    request.sid = sid
    request.question = question
    request.query = query

    _question = preprocessing(request.question, request.lang)
    request.question = _question
    response['ModQuestion'] = _question
    response.Question = response.get('OriginalQuestion')
    response.Marker = kwargs.get('marker')
    response.RunId = kwargs.get('run_id')

    if fallback_mode:
        request.lang = FALLBACK_LANG
        _ask_characters(
            responding_characters, request, response)
    else:
        _ask_characters(
            responding_characters, request, response)

    #if not query:
        # Sync session data
        #if session.last_used_character is not None:
        #    context = session.last_used_character.get_context(session)
        #    for c in responding_characters:
        #        if c.id == session.last_used_character.id:
        #            continue
        #        try:
        #            c.set_context(session, context)
        #        except NotImplementedError:
        #            pass

        #    for c in responding_characters:
        #        if c.type != TYPE_AIML:
        #            continue
        #        try:
        #            c.check_reset_topic(sid)
        #        except Exception:
        #            continue

    record = OrderedDict()
    record['Datetime'] = dt.datetime.utcnow()
    record['Question'] = response.Question
    record['Rate'] = ''
    record['Lang'] = lang
    record['Location'] = LOCATION
    record['ServerIP'] = IP
    record['RequestId'] = request_id
    record['Revision'] = REVISION
    record['ClientId'] = client_id
    record['User'] = user
    record['Marker'] = response.Marker
    record['BotName'] = botname
    record['RunId'] = response.RunId

    if response.answered:
        answer = response.default_response.get('text')
        response['OriginalAnswer'] = answer
        response['AnsweredBy'] = response.default_response.get('botid')
        if fallback_mode:
            try:
                output_translated, answer = do_translate(answer, lang)
                response.default_response['text'] = answer
            except Exception as ex:
                logger.error(ex)
                logger.error(traceback.format_exc())
                response.ret = codes.TRANSLATE_ERROR
                return response

        record['Answer'] = response.default_response.get('text')
        record['LineNO'] = response.default_response.get('lineno')
        record['OriginalAnswer'] = response.get('OriginalAnswer')
        record['TranslatedQuestion'] = question
        record['Topic'] = response.default_response.get('topic')
        record['ModQuestion'] = response.get('ModQuestion')
        record['Trace'] = response.get('trace')
        record['AnsweredBy'] = response.get('AnsweredBy')
        record['TranslateOutput'] = output_translated
        record['TranslateInput'] = input_translated
        record['NormQuestion'] = norm2(response.get('OriginalQuestion'))
        record['NormAnswer'] = norm2(response.default_response.get('text'))
        session.add(record)
        #logger.info("Ask {}, response {}".format(response['OriginalQuestion'], response))
        #response.update(record)
        #response['Datetime'] = str(response['Datetime'])
        return response
    else:
        logger.error("No pattern match")
        response.ret = codes.NO_PATTERN_MATCH
        return response