Exemple #1
0
def get_d3_partial_dump(request):
    logger('Graph', 'main: ' + str(request.json_body))
    path = request.validated['path']
    uid = request.validated['uid']
    is_argument = request.validated['is_argument']
    db_issue = request.validated['issue']
    return_dict = {
        'type': 'partial'
    }

    if is_argument:
        graph, error = get_partial_graph_for_argument(uid, db_issue)
    else:
        graph, error = get_partial_graph_for_statement(uid, db_issue, path)

    if not error:
        return_dict.update(graph)
        return_dict.update({'node_opinion_factors': get_opinion_data(db_issue)})
        return_dict.update({'path': get_path_of_user(request.application_url, path, db_issue)})
        return_dict.update({'error': ''})
    else:  # gets called if the data itself is malicious
        ui_locales = get_language_from_cookie(request)
        _t = Translator(ui_locales)
        error = _t.get(_.internalKeyError)
        return_dict = {
            'error': error
        }

    return return_dict
Exemple #2
0
def login_local_user(nickname: str,
                     password: str,
                     mailer: Mailer,
                     lang='en') -> dict:
    """
    Try to login the user whereby she is maybe a HHU-LDAP user or known locally

    :param nickname: User.nickname
    :param password: String
    :param mailer: request.mailer
    :param lang: current language
    :return: dict() or HTTPFound if the user is logged in and it is not the api
    """
    LOG.debug("Trying to login user: %s", nickname)
    _tn = Translator(lang)

    # now we have several options:
    # 1. the user is unknown in our DB, maybe has HHU-LDAP account
    # 2. oauth nickname
    # 3. the user is known, but
    #  a) keep local
    #  b) keep in ldap
    db_user = get_user_by_case_insensitive_nickname(nickname)
    if not db_user:  # this is 1.
        return __register_user_with_ldap_data(mailer, nickname, password, _tn)

    # this is 2.
    if len(str(db_user.oauth_provider)) > 4 and len(
            str(db_user.oauth_provider_id)) > 4:  # >4 because len('None') is 4
        return {'info': _tn.get(_.userIsOAuth)}

    # this is 3.
    return __check_in_local_known_user(db_user, password, _tn)
Exemple #3
0
def update_row(table_name, uids, keys, values):
    """
    Updates the data in a specific row of an table

    :param table_name: Name of the table
    :param uids: Array with uids
    :param keys: Array with keys
    :param values: Array with values
    :return: Empty string or error message
    """
    table = table_mapper[table_name.lower()]['table']
    _tn = Translator('en')
    try:
        update_dict = __update_row_dict(table, values, keys, _tn)
    except ProgrammingError as e:
        LOG.error("%s", e)
        return exception_response(400, error='SQLAlchemy ProgrammingError: ' + str(e))

    try:
        __update_row(table, table_name, uids, update_dict)
    except IntegrityError as e:
        LOG.error("%s", e)
        return exception_response(400, error='SQLAlchemy IntegrityError: ' + str(e))
    except ProgrammingError as e:
        LOG.error("%s", e)
        return exception_response(400, error='SQLAlchemy ProgrammingError: ' + str(e))

    DBDiscussionSession.flush()
    transaction.commit()
    return True
Exemple #4
0
def __build_argument_for_jump(arg_array: List[Argument],
                              with_html_tag: bool) -> str:
    """
    Build text for an argument, if we jump to this argument

    :param arg_array: [Argument]
    :param with_html_tag: This parameter is ignored in the next steps, which is why we should rewrite this function.
    "intro" in the next steps will always add html attributes.
    :return: String
    """
    tag_premise = ('<{} data-argumentation-type="attack">'.format(tag_type))
    tag_conclusion = (
        '<{} data-argumentation-type="argument">'.format(tag_type))
    tag_end = ('</{}>'.format(tag_type))
    _t = Translator(arg_array[0].lang)

    if len(arg_array) == 1:
        ret_value = __build_val_for_jump(arg_array[0], tag_premise,
                                         tag_conclusion, tag_end, _t)
    elif len(arg_array) == 2:
        ret_value = __build_val_for_undercut(arg_array, tag_premise,
                                             tag_conclusion, tag_end, _t)
    else:
        ret_value = __build_val_for_undercutted_undercut(
            arg_array, tag_premise, tag_conclusion, tag_end, _t)

    ret_value = unhtmlify(ret_value) if not with_html_tag else ret_value

    return ret_value.replace('  ', ' ')
Exemple #5
0
def get_user_with_same_opinion_for_statements(statement_uids, is_supportive,
                                              db_user, lang, main_page):
    """
    Returns nested dictionary with all kinds of information about the votes of the statements.

    :param statement_uid: Statement.uid
    :param is_supportive: Boolean
    :param db_user: User
    :param lang: language
    :param main_page: url
    :return: {'users':[{nickname1.avatar_url, nickname1.vote_timestamp}*]}
    """
    logger('OpinionHandler',
           'Statement {} ({})'.format(statement_uids, is_supportive))

    opinions = []
    _t = Translator(lang)
    title = _t.get(_.relativePopularityOfStatements)

    for statement_uid in statement_uids:
        statement_dict = __get_opinions_for_uid(statement_uid, is_supportive,
                                                db_user, lang, _t, main_page)
        opinions.append(statement_dict)

    return {'opinions': opinions, 'title': title[0:1].upper() + title[1:]}
Exemple #6
0
def __get_text_for_click_and_mark_count(db_user: User, is_user: bool, argument_uid: int, statement_uid: int,
                                        speech: dict, lang: str):
    """
    Build text for a bubble, how many other participants have the same interest?

    :param nickname: User.nickname
    :param is_user: boolean
    :param argument_uid: Argument.uid
    :param statement_uid: Statement.uid
    :param speech: dict()
    :param lang: ui_locales
    :return: [String]
    """
    if not db_user:
        db_user = DBDiscussionSession.query(User).filter_by(nickname=nick_of_anonymous_user).first()
    db_clicks, db_marks = __get_clicks_and_marks(argument_uid, statement_uid, db_user)

    _t = Translator(lang)
    speech['votecounts'] = len(db_clicks) if db_clicks else 0
    if db_marks:
        speech['votecounts'] += len(db_marks)

    votecount_keys = defaultdict(lambda: "{} {}.".format(speech['votecounts'], _t.get(_.voteCountTextMore)))

    if is_user and db_user.gender == 'm':
        gender_key = _.voteCountTextFirstM
    elif is_user and db_user.gender == 'f':
        gender_key = _.voteCountTextFirstF
    else:
        gender_key = _.voteCountTextFirst

    votecount_keys[0] = '{}.'.format(_t.get(gender_key))
    votecount_keys[1] = _t.get(_.voteCountTextOneOther) + '.'

    return votecount_keys
Exemple #7
0
def flag_element(uid: int, reason: Union[key_duplicate, key_optimization, ReviewDeleteReasons], db_user: User,
                 is_argument: bool, ui_locales: str, extra_uid=None) -> dict:
    """
    Flags an given argument based on the reason which was sent by the author. This argument will be enqueued
    for a review process.

    :param uid: Uid of the argument/statement, which should be flagged
    :param reason: String which describes the reason
    :param db_user: User
    :param is_argument: Boolean
    :param ui_locales: ui_locales
    :param extra_uid: Uid of the argument/statement, which should be flagged
    :return: success, info, error
    """
    tn = Translator(ui_locales)

    argument_uid = uid if is_argument else None
    statement_uid = uid if not is_argument else None

    # was this already flagged?
    flag_status = QueueAdapter(db_user=db_user).element_in_queue(argument_uid=argument_uid,
                                                                 statement_uid=statement_uid,
                                                                 premisegroup_uid=None)
    if flag_status:
        LOG.debug("Already flagged by %s", flag_status)
        if flag_status == FlaggedBy.user:
            info = tn.get(_.alreadyFlaggedByYou)
        else:
            info = tn.get(_.alreadyFlaggedByOthers)
        return {'success': '', 'info': info}

    return __add_flag(reason, argument_uid, statement_uid, extra_uid, db_user, tn)
Exemple #8
0
def delete_notifications(uids_list, db_user, ui_locales,
                         application_url) -> dict:
    """
    Simply deletes a specific notification

    :param uids_list: List of message ids which should be deleted
    :param db_user: User
    :param ui_locales: Language of current users session
    :param application_url Url of the App
    :rtype: dict
    :return: Dictionary with info and/or error
    """

    user.update_last_action(db_user)
    _tn = Translator(ui_locales)

    for uid in uids_list:
        # inbox
        DBDiscussionSession.query(Message).filter(
            Message.uid == uid, Message.to_author_uid == db_user.uid,
            Message.is_inbox == True).delete()
        # send
        DBDiscussionSession.query(Message).filter(
            Message.uid == uid, Message.from_author_uid == db_user.uid,
            Message.is_inbox == False).delete()
    transaction.commit()
    prepared_dict = dict()
    prepared_dict['unread_messages'] = count_of_new_notifications(db_user)
    prepared_dict['total_in_messages'] = str(
        len(get_box_for(db_user, ui_locales, application_url, True)))
    prepared_dict['total_out_messages'] = str(
        len(get_box_for(db_user, ui_locales, application_url, False)))
    prepared_dict['success'] = _tn.get(_.messageDeleted)

    return prepared_dict
Exemple #9
0
def get_short_url(url) -> dict:
    """
    Shortens the url via external service.

    :param url: Url as string, which should be shortened
    :rtype: dict
    :return: dictionary with the url, services name and the url of the service or an error
    """
    service = Shorteners.TINYURL
    service_text = service
    service_url = 'http://tinyurl.com/'
    short_url = ''
    try:
        short_url = format(Shortener(service).short(url))
    except (ReadTimeout, ConnectionError, NewConnectionError,
            ShorteningErrorException) as e:
        logger('getter', repr(e), error=True)
        service_text = Translator('en').get(_.serviceNotAvailable)

    return {
        'url': short_url,
        'service': service,
        'service_url': service_url,
        'service_text': service_text,
    }
Exemple #10
0
def main_review(request):
    """
    View configuration for the review index.

    :param request: current request of the server
    :return: dictionary with title and project name as well as a value, weather the user is logged in
    """
    logger('main_review', 'def {}'.format(request.matchdict))
    nickname = request.authenticated_userid

    _tn = Translator(get_language_from_cookie(request))
    review_dict = review_queue_helper.get_review_queues_as_lists(
        request.application_url, _tn, nickname)
    count, all_rights = review_reputation_helper.get_reputation_of(nickname)

    prep_dict = __main_dict(request, _tn.get(_.review))
    prep_dict.update({
        'review':
        review_dict,
        'privilege_list':
        review_reputation_helper.get_privilege_list(_tn),
        'reputation_list':
        review_reputation_helper.get_reputation_list(_tn),
        'reputation': {
            'count': count,
            'has_all_rights': all_rights
        }
    })
    return prep_dict
Exemple #11
0
def review_content(request):
    """
    View configuration for the review content.

    :param request: current request of the server
    :return: dictionary with title and project name as well as a value, weather the user is logged in
    """
    logger('review_content', 'def {}'.format(request.matchdict))
    ui_locales = get_language_from_cookie(request)
    _tn = Translator(ui_locales)

    subpage_name = request.matchdict['queue']
    nickname = request.authenticated_userid
    session = request.session
    application_url = request.application_url
    subpage_dict = review_page_helper.get_subpage_elements_for(
        nickname, session, application_url, subpage_name, _tn)
    request.session.update(subpage_dict['session'])
    if not subpage_dict['elements'] and not subpage_dict[
            'has_access'] and not subpage_dict['no_arguments_to_review']:
        logger('review_content', 'subpage error', error=True)
        raise HTTPNotFound()

    title = _tn.get(_.review)
    if subpage_name in review_queue_helper.title_mapping:
        title = _tn.get(review_queue_helper.title_mapping[subpage_name])

    prep_dict = __main_dict(request, title)
    prep_dict.update({
        'extras': request.decorated['extras'],
        'subpage': subpage_dict,
        'lock_time': review_queue_helper.max_lock_time_in_sec
    })
    return prep_dict
Exemple #12
0
def set_statement(text: str, db_user: User, is_position: bool, db_issue: Issue) -> Tuple[Statement, bool]:
    """
    Saves statement for user

    :param text: given statement
    :param db_user: User of given user
    :param is_position: if it is a start statement
    :param db_issue: Issue
    :return: Statement, is_duplicate or -1, False on error
    """

    LOG.debug("User_id: %s, text: %s, issue: %s", db_user.uid, text, db_issue.uid)

    # escaping and cleaning
    text = escape_string(' '.join(text.strip().split()))
    _tn = Translator(db_issue.lang)
    if text.startswith(_tn.get(_.because).lower() + ' '):
        text = text[len(_tn.get(_.because) + ' '):]
    while text.endswith(('.', '?', '!', ',')):
        text = text[:-1]

    # check, if the text already exists
    db_dupl = __check_duplicate(db_issue, text)
    if db_dupl:
        return db_dupl, True

    db_statement = __add_statement(is_position)
    __add_textversion(text, db_user.uid, db_statement.uid)
    __add_statement2issue(db_statement.uid, db_issue.uid)

    return db_statement, False
Exemple #13
0
def queue_details(request):
    """
    View configuration for the review content.

    :param request: current request of the server
    :return: dictionary with title and project name as well as a value, weather the user is logged in
    """
    LOG.debug("Queue Details %s / %s", request.matchdict, request.params)
    ui_locales = get_language_from_cookie(request)
    _tn = Translator(ui_locales)

    queue_name = request.validated['queue']
    db_user = request.validated['user']
    application_url = request.application_url

    queue = subclass_by_name(queue_name)
    adapter = QueueAdapter(queue=queue(),
                           db_user=db_user,
                           application_url=application_url,
                           translator=_tn)
    subpage_dict = adapter.get_subpage_of_queue(request.session, queue_name)
    request.session.update(subpage_dict['session'])

    prep_dict = main_dict(request, _tn.get(get_title_by_key(queue_name)))
    prep_dict.update({
        'extras': request.decorated['extras'],
        'subpage': subpage_dict,
        'lock_time': dbas.review.queue.max_lock_time_in_sec
    })
    return prep_dict
Exemple #14
0
def index(request):
    """
    View configuration for the review index.

    :param request: current request of the server
    :return: dictionary with title and project name as well as a value, weather the user is logged in
    """
    LOG.debug("Review Index: %s / %s", request.matchdict, request.params)
    db_user = request.validated['user']

    _tn = Translator(get_language_from_cookie(request))
    adapter = QueueAdapter(db_user=db_user,
                           main_page=request.application_url,
                           translator=_tn)
    review_dict = adapter.get_review_queues_as_lists()
    count, all_rights = get_reputation_of(db_user)

    prep_dict = main_dict(request, _tn.get(_.review))
    prep_dict.update({
        'review': review_dict,
        'privilege_list': get_privilege_list(_tn),
        'reputation_list': get_reputation_reasons_list(_tn),
        'reputation': {
            'count': count,
            'has_all_rights': all_rights
        }
    })
    return prep_dict
Exemple #15
0
def __get_bubble_from_support_step(arg_uid_user: int, uid_system: int, db_user: User, lang: str) \
        -> Optional[List[list]]:
    """
    Creates bubbles for the support-keyword for an statement.

    :param arg_uid_user: User.uid
    :param uid_system: Argument.uid
    :param db_user: User
    :param lang: Language.ui_locales
    :return: [dict()]
    """
    db_arg_user = DBDiscussionSession.query(Argument).get(arg_uid_user)
    db_arg_system = DBDiscussionSession.query(Argument).get(uid_system)

    if not db_arg_user or not db_arg_system:
        return None

    user_text = get_text_for_argument_uid(arg_uid_user)
    bubble_user = create_speechbubble_dict(BubbleTypes.USER, content=user_text, omit_bubble_url=True,
                                           argument_uid=arg_uid_user, is_supportive=db_arg_user.is_supportive,
                                           db_user=db_user, lang=lang)

    argument_text = get_text_for_argument_uid(uid_system, colored_position=True, with_html_tag=True, attack_type='jump')
    offset = len('</' + tag_type + '>') if argument_text.endswith('</' + tag_type + '>') else 1

    while argument_text[:-offset].endswith(('.', '?', '!')):
        argument_text = argument_text[:-offset - 1] + argument_text[-offset:]

    text = get_text_for_support(db_arg_system, argument_text, db_user.nickname, Translator(lang))
    db_other_author = DBDiscussionSession.query(User).get(db_arg_system.author_uid)
    bubble_system = create_speechbubble_dict(BubbleTypes.SYSTEM, content=text, omit_bubble_url=True, lang=lang,
                                             other_author=db_other_author)

    return [bubble_user, bubble_system]
Exemple #16
0
def set_user_language(db_user: User, ui_locales) -> dict:
    """
    Changes the users language of the web frontend

    :param db_user: User
    :param ui_locales: current ui_locales
    :rtype: dict
    :return: prepared collection with status information
    """
    _tn = Translator(ui_locales)

    db_settings = db_user.settings
    db_language = DBDiscussionSession.query(Language).filter_by(
        ui_locales=ui_locales).first()

    if not db_language:
        return {
            'error': _tn.get(_.internalError),
            'ui_locales': ui_locales,
            'current_lang': ''
        }

    current_lang = db_language.name
    db_settings.set_lang_uid(db_language.uid)
    transaction.commit()

    return {
        'error': '',
        'ui_locales': ui_locales,
        'current_lang': current_lang
    }
Exemple #17
0
def __get_bubble_from_dont_know_step(step: str, db_user: User, lang: str) -> List[dict]:
    """
    Creates bubbles for the don't-know-reaction for a statement.

    :param step: String
    :param db_user: User
    :param lang: ui_locales
    :return: [dict()]
    """
    steps = step.split('/')
    uid = int(steps[1])

    text = get_text_for_argument_uid(uid, rearrange_intro=True, attack_type='dont_know', with_html_tag=False,
                                     start_with_intro=True)
    db_argument = DBDiscussionSession.query(Argument).get(uid)
    if not db_argument:
        text = ''

    from dbas.strings.text_generator import get_name_link_of_arguments_author
    _tn = Translator(lang)

    data = get_name_link_of_arguments_author(db_argument, db_user.nickname, False)
    if data['is_valid']:
        intro = data['link'] + ' ' + _tn.get(_.thinksThat)
    else:
        intro = _tn.get(_.otherParticipantsThinkThat)
    sys_text = intro + ' ' + start_with_small(text) + '. '
    sys_text += '<br><br>' + _tn.get(_.whatDoYouThinkAboutThat) + '?'
    sys_bubble = create_speechbubble_dict(BubbleTypes.SYSTEM, content=sys_text, db_user=db_user,
                                          other_author=data['user'])

    text = _tn.get(_.showMeAnArgumentFor) + (' ' if lang == 'de' else ': ') + get_text_for_conclusion(db_argument)
    user_bubble = create_speechbubble_dict(BubbleTypes.USER, content=text, db_user=db_user)

    return [user_bubble, sys_bubble]
Exemple #18
0
def set_oauth_user(user_data, service, ui_locales):
    """

    :param user_data:
    :param service:
    :param ui_locales:
    :return:
    """
    _tn = Translator(ui_locales)

    db_group = DBDiscussionSession.query(Group).filter_by(name='users').first()
    if not db_group:
        LOG.debug(
            "Error occured: No db_group for users during `set_oauth_user`")
        return {'error': _tn.get(_.errorTryLateOrContant)}

    ret_dict = user.set_new_oauth_user(user_data, user_data['id'], service,
                                       _tn)

    return {
        'status':
        ret_dict['success'] if ret_dict['success'] else ret_dict['error'],
        'error': ret_dict.get('error', ''),
        'user': ret_dict.get('user')
    }
    def test_set_discussions_properties(self):
        db_walter = DBDiscussionSession.query(User).filter_by(nickname='Walter').one_or_none()
        issue_slug = 'cat-or-dog'
        db_issue = DBDiscussionSession.query(Issue).filter_by(slug=issue_slug).one()
        translator = Translator('en')

        enable = True
        response = ih.set_discussions_properties(db_walter, db_issue, enable, 'somekeywhichdoesnotexist', translator)
        self.assertTrue(len(response['error']) > 0)

        db_christian = DBDiscussionSession.query(User).filter_by(nickname='Christian').one_or_none()
        response = ih.set_discussions_properties(db_christian, db_issue, enable, 'somekeywhichdoesnotexist', translator)
        self.assertTrue(len(response['error']) > 0)

        response = ih.set_discussions_properties(db_christian, db_issue, enable, 'somekeywhichdoesnotexist', translator)
        self.assertTrue(len(response['error']) > 0)

        db_tobias = DBDiscussionSession.query(User).filter_by(nickname='Tobias').one_or_none()
        response = ih.set_discussions_properties(db_tobias, db_issue, enable, 'enable', translator)
        self.assertTrue(len(response['error']) == 0)
        self.assertTrue(DBDiscussionSession.query(Issue).filter_by(slug=issue_slug).one().is_disabled is False)

        enable = False
        response = ih.set_discussions_properties(db_tobias, db_issue, enable, 'enable', translator)
        self.assertTrue(len(response['error']) == 0)
        self.assertTrue(DBDiscussionSession.query(Issue).filter_by(slug=issue_slug).one().is_disabled is True)

        enable = True
        response = ih.set_discussions_properties(db_tobias, db_issue, enable, 'enable', translator)
        self.assertTrue(len(response['error']) == 0)
        self.assertTrue(DBDiscussionSession.query(Issue).filter_by(slug=issue_slug).one().is_disabled is False)
Exemple #20
0
def review_optimization_argument(request):
    """
    Values for the review for an argument, which should be optimized

    :param request: current request of the server
    :return: json-dict()
    """
    LOG.debug("Request to review an optimization. %s - %s", request.json_body,
              request.authenticated_userid)
    ui_locales = get_discussion_language(request.matchdict, request.params,
                                         request.session)
    db_review = request.validated['db_review']
    db_user = request.validated['user']
    should_optimized = request.validated['should_optimized']
    new_data = request.validated['new_data']
    main_page = request.application_url
    _t = Translator(ui_locales)

    QueueAdapter(OptimizationQueue(),
                 db_user,
                 main_page,
                 _t,
                 new_data=new_data).add_vote(db_review, should_optimized)
    send_request_for_recent_reviewer_socketio(db_user.nickname, main_page,
                                              key_optimization)
    return True
Exemple #21
0
def __get_bubble_from_justify_statement_step(step: str, db_user: User,
                                             lang: str,
                                             url: str) -> List[dict]:
    """
    Creates bubbles for the justify-keyword for an statement.

    :param step: String
    :param db_user: User
    :param lang: ui_locales
    :param url: String
    :return: [dict()]
    """
    steps = step.split('/')
    uid = int(steps[1])
    is_supportive = steps[2] == Attitudes.AGREE.value or steps[
        2] == Attitudes.DONT_KNOW.value

    _tn = Translator(lang)
    msg, tmp = get_user_bubble_text_for_justify_statement(
        uid, db_user, is_supportive, _tn)

    bubble_user = create_speechbubble_dict(BubbleTypes.USER,
                                           bubble_url=url,
                                           content=msg,
                                           omit_bubble_url=False,
                                           statement_uid=uid,
                                           is_supportive=is_supportive,
                                           db_user=db_user,
                                           lang=lang)
    return [bubble_user]
Exemple #22
0
    def test_login_user(self):
        nickname = 'Bob'
        password = '******'
        keep_login = True

        request = construct_dummy_request(
            json_body={
                'user': nickname,
                'password': password,
                'keep_login': keep_login,
                'redirect_url': 'http://some.url'
            })

        _tn = Translator('en')
        response = user_login(request)
        self.assertTrue(type(response) is HTTPFound)

        response = login_local_user(nickname, password, DummyMailer, lang=_tn)
        self.assertTrue(isinstance(response, dict))
        self.assertNotIn('error', response)
        self.assertIn('user', response)

        response = login_local_user('definitelynotauser',
                                    r'¯\_(ツ)_/¯',
                                    DummyMailer,
                                    lang=_tn)
        self.assertTrue(isinstance(response, dict))
        self.assertIn('error', response)
        self.assertNotIn('user', response)
Exemple #23
0
def settings(request):
    """
    View configuration for the personal settings view. Only logged in user can reach this page.

    :param request: current request of the server
    :return: dictionary with title and project name as well as a value, weather the user is logged in
    """
    LOG.debug("Show settings %s", request.params)

    ui_locales = get_language_from_cookie(request)
    old_pw, new_pw, confirm_pw, message = '', '', '', ''
    success, error = False, False
    db_user: User = request.validated['user']

    if 'form.passwordchange.submitted' in request.params:
        old_pw = escape_string(request.params['passwordold'])
        new_pw = escape_string(request.params['password'])
        confirm_pw = escape_string(request.params['passwordconfirm'])

        message, success = change_password(db_user, old_pw, new_pw, confirm_pw, ui_locales)
        error = not success

    settings_dict = DictionaryHelper(ui_locales).prepare_settings_dict(success, old_pw, new_pw, confirm_pw, error,
                                                                       message, db_user, request.application_url,
                                                                       request.decorated['extras']['use_with_ldap'])

    prep_dict = main_dict(request, Translator(ui_locales).get(_.settings))
    prep_dict.update({
        'settings': settings_dict
    })
    return prep_dict
Exemple #24
0
    def get_dict_for_dont_know_reaction(self, uid, nickname) -> dict:
        """
        Prepares the discussion dict with all bubbles for the third step,
        where an supportive argument will be presented.

        :param uid: Argument.uid
        :param nickname:
        :return: dict()
        """
        LOG.debug("Entering get_dict_for_dont_know_reaction")
        _tn = Translator(self.lang)
        bubbles_array = history_handler.create_bubbles(self.history,
                                                       self.nickname,
                                                       self.lang, self.slug)
        add_premise_text = ''
        save_statement_url = 'set_new_start_statement'
        gender = ''
        b = '<' + tag_type + '>'
        e = '</' + tag_type + '>'
        statement_list = list()

        if int(uid) != 0:
            text = get_text_for_argument_uid(uid,
                                             rearrange_intro=True,
                                             attack_type='dont_know',
                                             with_html_tag=True,
                                             start_with_intro=True)
            db_argument = DBDiscussionSession.query(Argument).get(uid)
            if not db_argument:
                text = ''
            data = get_name_link_of_arguments_author(db_argument, nickname)
            gender = data['gender']
            if data['is_valid']:
                intro = data['link'] + ' ' + b + _tn.get(_.thinksThat) + e
            else:
                intro = b + _tn.get(_.otherParticipantsThinkThat) + e
            sys_text = intro + ' ' + start_with_small(text) + '. '
            sys_text += '<br><br> ' + b + _tn.get(
                _.whatDoYouThinkAboutThat) + '?' + e
            bubble_sys = create_speechbubble_dict(BubbleTypes.SYSTEM,
                                                  is_markable=True,
                                                  uid=uid,
                                                  content=sys_text,
                                                  other_author=data['user'])
            if not bubbles_already_last_in_list(bubbles_array, bubble_sys):
                bubbles_array.append(bubble_sys)

            # add statements of discussion to report them
            statement_list = self.__get_all_statement_texts_by_argument(
                db_argument)

        return {
            'bubbles': bubbles_array,
            'add_premise_text': add_premise_text,
            'save_statement_url': save_statement_url,
            'mode': '',
            'extras': statement_list,
            'gender': gender,
            'broke_limit': self.broke_limit
        }
Exemple #25
0
def get_user_with_same_opinion_for_premisegroups_of_args(
        argument_uids, db_user, lang, main_page):
    """
    Returns nested dictionary with all kinds of information about the votes of the premisegroups.

    :param argument_uids: [Argument.uid]
    :param db_user: User
    :param lang: language
    :param main_page: url
    :return: {'users':[{nickname1.avatar_url, nickname1.vote_timestamp}*]}
    """
    logger('OpinionHandler', 'Arguments ' + str(argument_uids))

    opinions = []
    _t = Translator(lang)
    title = _t.get(_.relativePopularityOfStatements)
    for arg_uid in argument_uids:
        db_argument = DBDiscussionSession.query(Argument).get(arg_uid)
        db_premises = DBDiscussionSession.query(Premise).filter_by(
            premisegroup_uid=db_argument.premisegroup_uid).all()
        if db_premises:
            opinions.append(
                get_user_with_same_opinion_for_premisegroups_of_arg(
                    db_argument, db_premises, db_user, lang, main_page))

    return {'opinions': opinions, 'title': title[0:1].upper() + title[1:]}
Exemple #26
0
    def get_dict_for_start(self, position_count):
        """
        Prepares the discussion dict with all bubbles for the first step in discussion,
        where the user chooses a position.

        :position_count: int
        :return: dict()
        """
        LOG.debug("At_start with positions: %s", position_count)
        _tn = Translator(self.lang)
        add_premise_text = _tn.get(_.whatIsYourIdea)
        intro = _tn.get(_.initialPositionInterest)
        save_statement_url = 'set_new_start_premise'

        start_bubble = create_speechbubble_dict(BubbleTypes.USER,
                                                uid='start',
                                                content=intro,
                                                omit_bubble_url=True,
                                                lang=self.lang)
        bubbles_array = [] if position_count == 1 else [start_bubble]

        return {
            'bubbles': bubbles_array,
            'add_premise_text': add_premise_text,
            'save_statement_url': save_statement_url,
            'mode': '',
            'broke_limit': self.broke_limit
        }
Exemple #27
0
def handle_justification_argument(db_issue: Issue, db_user: User,
                                  db_argument: Argument, attitude: str,
                                  relation: str, history,
                                  path) -> Tuple[dict, dict]:
    """

    :param db_issue:
    :param db_user:
    :param db_argument:
    :param attitude:
    :param relation:
    :param history:
    :param path:
    :return:
    """
    LOG.debug("Justify argument")
    ui_locales = db_issue.lang
    nickname = db_user.nickname
    supportive = attitude in [Attitudes.AGREE, Attitudes.DONT_KNOW]

    item_dict, discussion_dict = preparation_for_justify_argument(
        db_issue, db_user, db_argument, relation, supportive, history, path)

    broke_limit = add_reputation_and_check_review_access(
        db_user, ReputationReasons.first_confrontation)

    if broke_limit:
        _t = Translator(ui_locales)
        send_request_for_info_popup_to_socketio(
            nickname, _t.get(_.youAreAbleToReviewNow), '/review')
    return item_dict, discussion_dict
Exemple #28
0
    def __get_dict_for_argumentation_end(self, argument_uid: int,
                                         user_changed_opinion: bool,
                                         db_user: User) -> dict:
        """
        Returns a special dict() when the discussion ends during an argumentation

        :param argument_uid: Argument.uid
        :param user_changed_opinion:  Boolean
        :param db_user: User
        :return: String, String, String
        """
        nickname = db_user.nickname if db_user and db_user.nickname != nick_of_anonymous_user else None
        _tn = Translator(self.lang)
        text = get_text_for_argument_uid(
            argument_uid,
            user_changed_opinion=user_changed_opinion,
            minimize_on_undercut=True,
            nickname=nickname)
        user_text = start_with_capital(text)
        sys_text = _tn.get(_.otherParticipantsDontHaveCounterForThat) + '.'
        trophy = '<i class="fa fa-trophy" aria-hidden="true"></i>'
        mid_text = '{} {} {} <br>{}'.format(
            trophy, _tn.get(_.congratulation), trophy,
            _tn.get(_.discussionCongratulationEnd))

        if nickname is not None:
            mid_text += _tn.get(_.discussionEndLinkTextWithQueueLoggedIn)
        else:
            mid_text += _tn.get(_.discussionEndLinkTextWithQueueNotLoggedIn)

        return {'user': user_text, 'mid': mid_text, 'sys': sys_text}
Exemple #29
0
def __check_for_duplicated_field(title: str, info: str, long_info: str,
                                 request: dict) -> dict:
    """
    This method checks if there is a duplication in any field of the new issue.
    It also creates a error-message with the fields which are containing the duplication.

    :param title: The title of the new issue
    :param info: The info of the new issue
    :param long_info: The long info of the new issue
    :param request: The request with the data of the new issue
    :return: a dict with a boolean which tells if there is any duplicated field and a equivalent error-message.
    """
    _tn = Translator(get_language_from_cookie(request))
    error = _tn.get(_.duplicate) + ': '

    title_is_duplicate = DBDiscussionSession.query(Issue).filter_by(
        title=title).all()
    info_is_duplicate = DBDiscussionSession.query(Issue).filter_by(
        info=info).all()
    long_info_is_duplicate = DBDiscussionSession.query(Issue).filter_by(
        long_info=long_info).all()

    if title_is_duplicate:
        error = error + _tn.get(_.newIssueTitle) + ', '
    if info_is_duplicate:
        error = error + _tn.get(_.newIssueInfo) + ', '
    if long_info_is_duplicate:
        error = error + _tn.get(_.newIssueLongInfo) + ', '

    return {
        "contains_duplicated_field": title_is_duplicate or info_is_duplicate
        or long_info_is_duplicate,
        "error": error[:-2]
    }
Exemple #30
0
def __set_oauth_user(request, user_data, service, ui_locales):
    """

    :param request:
    :param user_data:
    :param service:
    :param ui_locales:
    :return:
    """
    _tn = Translator(ui_locales)

    db_group = DBDiscussionSession.query(Group).filter_by(name='users').first()
    if not db_group:
        logger('Auth.Login', 'Error occured')
        return {'error': _tn.get(_.errorTryLateOrContant)}

    ret_dict = user.set_new_oauth_user(user_data['firstname'],
                                       user_data['lastname'],
                                       user_data['nickname'],
                                       user_data['email'], user_data['gender'],
                                       user_data['id'], service, _tn)

    if ret_dict['success']:
        url = request.session['oauth_redirect_url']
        return __return_success_login(request, False, ret_dict['user'], False,
                                      url)
    else:
        return {'error': ret_dict['error'], 'success': ret_dict['success']}