Exemplo n.º 1
0
def get_list_of_all_feeds(ui_locale: str) -> list:
    """
    Returns list of all feeds

    :param ui_locale: Language.ui_locale
    :return: list
    """
    logger('RSS-Handler', 'def with ' + str(ui_locale))

    feeds = []
    feed = {
        'title': 'News',
        'description':
        'Latest news about D-BAS, the Dialog-Based Argumentation System',
        'link': '{}/news.xml'.format(rss_path)
    }
    feeds.append(feed)

    _tn = Translator(ui_locale)
    db_issues = get_enabled_issues_as_query().all()
    for issue in db_issues:
        feed = {
            'title':
            issue.title,
            'description':
            '{}: <em> {} - {} </em>'.format(
                _tn.get(_.latestNewsFromDiscussion), issue.title, issue.info),
            'link':
            '{}/{}.xml'.format(rss_path, issue.slug)
        }
        feeds.append(feed)

    return feeds
Exemplo n.º 2
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
    :return: Dictionary with info and/or error
    """
    user_handler.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
Exemplo n.º 3
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:
    """
    logger('ViewHelper', '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)
    add_rep, broke_limit = add_reputation_for(nickname,
                                              rep_reason_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
Exemplo n.º 4
0
def valid_premisegroups(request):
    """
    Validates the correct build of premisegroups

    :param request:
    :return:
    """
    premisegroups = request.json_body.get('premisegroups')
    if not premisegroups \
            or not isinstance(premisegroups, list) \
            or not all([isinstance(l, list) for l in premisegroups]):
        _tn = Translator(get_language_from_cookie(request))
        add_error(request, 'Invalid conclusion id', _tn.get(_.requestFailed))
        return False

    min_length = int(environ.get('MIN_LENGTH_OF_STATEMENT', 10))
    for premisegroup in premisegroups:
        for premise in premisegroup:
            if isinstance(premise, str):
                if len(premise) < min_length:
                    __set_min_length_error(request, min_length)
                    return False
            else:
                add_error(request, 'At least one premise isn\'t a string!')
                return False

    request.validated['premisegroups'] = premisegroups
    return True
Exemplo n.º 5
0
    def test_get_text_for_add_premise_container(self):
        _t = Translator('en')

        for is_supportive in [True, False]:
            confrontation = start_with_capital(self.confrontation)
            undermine = _t.get(_.itIsFalseThat) + ' ' + self.premise
            support = _t.get(_.itIsTrueThat) if is_supportive else _t.get(
                _.itIsFalseThat)
            support += ' ' + self.conclusion + ' '
            support += _t.get(_.hold) if is_supportive else _t.get(
                _.doesNotHold)
            undercut = confrontation + ', ' + _t.get(
                _.butIDoNotBelieveCounterFor).format(self.conclusion)
            rebut = confrontation + ' '
            rebut += _t.get(_.iAcceptCounterThat) if is_supportive else _t.get(
                _.iAcceptArgumentThat)
            rebut += ' ' + self.conclusion

            results = {
                Relations.UNDERMINE: undermine + ' ...',
                Relations.SUPPORT: support + ' ...',
                Relations.UNDERCUT: undercut + ' ...',
                Relations.REBUT: rebut + ' ...',
                '': '',
            }

            for r in results:
                self.assertEqual(
                    results[r],
                    tg.get_text_for_add_premise_container(
                        'en', self.confrontation, self.premise, r,
                        self.conclusion, is_supportive))
Exemplo n.º 6
0
def flag_statement_for_merge_or_split(key: str, pgroup: PremiseGroup, text_values: list, db_user: User,
                                      tn: Translator) -> dict:
    """
    Flags a statement for a merge or split event. On split, the statement of the pgroup will be splitted into the
    given text_values. On merge the statements of the pgroup will be connected by an and.

    :param key: either 'split' or 'merge'
    :param pgroup: ID of the selected PremiseGroup
    :param text_values: text values
    :param db_user: current user
    :param tn: The translator used
    :return: success, info
    """
    LOG.debug("Flag statements in pgroup %s for a %s with values %s", pgroup.uid, key, text_values)
    # was this already flagged?
    flag_status = QueueAdapter(db_user=db_user).element_in_queue(argument_uid=None,
                                                                 statement_uid=None,
                                                                 premisegroup_uid=pgroup.uid)
    if flag_status:
        LOG.debug("Already flagged")
        if flag_status == FlaggedBy.user:
            info = tn.get(_.alreadyFlaggedByYou)
        else:
            info = tn.get(_.alreadyFlaggedByOthers)
        return {'success': '', 'info': info}

    if key is key_merge:
        __add_merge_review(pgroup.uid, db_user.uid, text_values)
    elif key is key_split:
        __add_split_review(pgroup.uid, db_user.uid, text_values)

    success = tn.get(_.thxForFlagText)
    return {'success': success, 'info': ''}
Exemplo n.º 7
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
        }
Exemplo n.º 8
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
Exemplo n.º 9
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
    }
Exemplo n.º 10
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
Exemplo n.º 11
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
Exemplo n.º 12
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
Exemplo n.º 13
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']}
Exemplo n.º 14
0
def create_news_rss(main_page: str, ui_locale: str) -> bool:
    """
    Creates a new news rss

    :param main_page: Host URL
    :param ui_locale: Language.ui_locale
    :return: Boolean
    """
    logger('RSS-Handler', 'def')
    db_news = Session.query(News).order_by(News.date.desc()).all()
    items = [
        __get_rss_item(n.title, n.news, n.date.datetime, n.author,
                       '{}/news'.format(get_global_url())) for n in db_news
    ]

    _tn = Translator(ui_locale)
    rss = PyRSS2Gen.RSS2(title='D-BAS Feed',
                         link=main_page + '{}/rss.xml'.format(rss_path),
                         description=_tn.get(_.latestNewsFromDBAS),
                         lastBuildDate=datetime.now(),
                         items=items)

    if not os.path.exists('dbas{}'.format(rss_path)):
        os.makedirs('dbas{}'.format(rss_path))

    rss.write_xml(open('dbas{}/news.xml'.format(rss_path), 'w'),
                  encoding='utf-8')

    return True
Exemplo n.º 15
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)
Exemplo n.º 16
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
Exemplo n.º 17
0
def __add_flag(reason: Union[key_duplicate, key_optimization, ReviewDeleteReasons], argument_uid: Union[int, None],
               statement_uid: Optional[int], extra_uid: Optional[int], db_user: User, tn: Translator) -> dict:
    """

    :param reason:
    :param argument_uid:
    :param statement_uid:
    :param extra_uid:
    :param db_user:
    :param tn:
    :return:
    """
    reason_val = reason.value if isinstance(reason, ReviewDeleteReasons) else reason
    db_del_reason = DBDiscussionSession.query(ReviewDeleteReason).filter_by(reason=reason_val).first()
    if db_del_reason:
        __add_delete_review(argument_uid, statement_uid, db_user.uid, db_del_reason.uid)

    elif reason_val == key_optimization:
        __add_optimization_review(argument_uid, statement_uid, db_user.uid)

    elif reason_val == key_duplicate:
        if statement_uid == extra_uid:
            LOG.debug("uid Error")
            return {'success': '', 'info': tn.get(_.internalKeyError)}
        __add_duplication_review(statement_uid, extra_uid, db_user.uid)

    return {'success': tn.get(_.thxForFlagText), 'info': ''}
Exemplo n.º 18
0
def flag_statement_for_merge_or_split(key: str, pgroup: PremiseGroup,
                                      text_values: list(), db_user: User,
                                      tn: Translator) -> dict():
    """
    Flags a statement for a merge or split event

    :param key: either 'split' or 'merge'
    :param pgroup_uid: ID of the selected PremiseGroup
    :param text_values: text values
    :param nickname: Users nickname
    :return: success, info, error
    """
    logger(
        'FlagingHelper',
        'Flag statements in pgroup {} for a {} with values {}'.format(
            pgroup.uid, key, text_values))
    # was this already flagged?
    flag_status = __get_flag_status(None, None, pgroup.uid, db_user.uid)
    if flag_status:
        logger('FlagingHelper', 'already flagged')
        return {
            'success':
            '',
            'info':
            tn.get(_.alreadyFlaggedByYou if flag_status ==
                   'user' else _.alreadyFlaggedByOthers)
        }

    if key is 'merge':
        __add_merge_review(pgroup.uid, db_user.uid, text_values)
    elif key is 'split':
        __add_split_review(pgroup.uid, db_user.uid, text_values)

    return {'success': tn.get(_.thxForFlagText), 'info': ''}
Exemplo n.º 19
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
        }
Exemplo n.º 20
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:]}
Exemplo n.º 21
0
def valid_conclusion(request):
    """
    Given a conclusion id, query the object from the database and return it in the request.

    :param request:
    :return:
    """
    conclusion_id = request.json_body.get('conclusion_id')
    issue = request.validated.get('issue')
    _tn = Translator(get_language_from_cookie(request))

    if not issue:
        find_issue_in_request = issue_handler.get_issue_id(request)
        if find_issue_in_request:
            issue = DBDiscussionSession.query(Issue).get(
                issue_handler.get_issue_id(request))
        else:
            add_error(request, 'Issue is missing', _tn.get(_.issueNotFound))
            return False

    if conclusion_id and isinstance(conclusion_id, int):
        db_statement2issue = DBDiscussionSession.query(
            StatementToIssue).filter(
                StatementToIssue.issue_uid == issue.uid,
                StatementToIssue.statement_uid == conclusion_id).first()
        if db_statement2issue:
            db_conclusion = DBDiscussionSession.query(Statement).filter_by(
                uid=conclusion_id, is_disabled=False).first()
            if db_conclusion:
                request.validated['conclusion'] = db_conclusion
                return True

    add_error(request, 'Conclusion id is missing',
              _tn.get(_.conclusionIsMissing))
    return False
Exemplo n.º 22
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:]}
Exemplo n.º 23
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)
Exemplo n.º 24
0
def valid_notification_recipient(request):
    """
    Recipients must exist, author and recipient must be different users.

    :param request:
    :return:
    """
    _tn = Translator(get_language_from_cookie(request))
    if not valid_user(request):
        add_error(request, 'Not logged in', _tn.get(_.notLoggedIn))
        return False

    db_author = request.validated["user"]
    recipient_nickname = str(request.json_body.get('recipient')).replace(
        '%20', ' ')
    db_recipient = get_user_by_private_or_public_nickname(recipient_nickname)

    if not db_recipient or recipient_nickname == 'admin' or recipient_nickname == nick_of_anonymous_user:
        add_error(request, 'Recipient not found', _tn.get(_.recipientNotFound))
        return False
    elif db_author and db_author.uid == db_recipient.uid:
        add_error(request, 'Author and Recipient are the same user',
                  _tn.get(_.senderReceiverSame))
        return False
    else:
        request.validated["recipient"] = db_recipient
        return True
Exemplo n.º 25
0
def get_history_of(db_user: User, translator: Translator):
    """
    Returns the reputation history of an user

    :param db_user: User
    :param translator: Translator
    :return: dict()
    """

    db_reputation = DBDiscussionSession.query(ReputationHistory) \
        .filter_by(reputator_uid=db_user.uid) \
        .join(ReputationReason, ReputationReason.uid == ReputationHistory.reputation_uid) \
        .order_by(ReputationHistory.uid.asc()) \
        .all()

    rep_list = []
    for rep in db_reputation:
        date = sql_timestamp_pretty_print(rep.timestamp,
                                          translator.get_lang(),
                                          humanize=False)
        points_data = ('+' if rep.reputations.points > 0 else '') + str(
            rep.reputations.points)
        rep_list.append({
            'date': date,
            'points_data': points_data,
            'action': translator.get(rep.reputations.reason),
            'points': rep.reputations.points
        })

    count, all_rights = get_reputation_of(db_user)
    return {
        'count': count,
        'all_rights': all_rights,
        'history': list(reversed(rep_list))
    }
Exemplo n.º 26
0
def set_oauth_user(user_data, service, ui_locales) -> Dict[str, Any]:
    """

    :param user_data:
    :param service:
    :param ui_locales:
    :return: A Dictionary with a status an error and an user object
    """
    _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')
    }
Exemplo n.º 27
0
def send_mail_due_to_edit_text(statement_uid: int, previous_author: User,
                               current_author: User, url: str, mailer: Mailer):
    """
    Will send an email to the author of the statement.

    :param statement_uid: Statement.uid
    :param previous_author: User
    :param current_author: User
    :param url: current url
    :param mailer: current mailer
    :return: duple with boolean for sent message, message-string
    """
    db_statement = DBDiscussionSession.query(Statement).get(statement_uid)
    db_textversion_old = DBDiscussionSession.query(TextVersion).filter_by(
        statement_uid=statement_uid)  # TODO #432
    db_textversion_new = DBDiscussionSession.query(TextVersion).get(
        db_statement.uid)

    db_previous_author = DBDiscussionSession.query(User).get(previous_author)
    db_current_author = DBDiscussionSession.query(User).get(current_author)

    db_language = DBDiscussionSession.query(Language).get(
        db_previous_author.setting.lang_uid)
    _t = Translator(db_language.ui_locales)
    subject = _t.get(_.textversionChangedTopic)
    body = get_text_for_edit_text_message(db_language.ui_locales,
                                          db_current_author.public_nickname,
                                          db_textversion_old.content,
                                          db_textversion_new.content, url,
                                          False)
    recipient = db_previous_author.email

    return send_mail(mailer, subject, body, recipient, db_language.ui_locales)
Exemplo n.º 28
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
Exemplo n.º 29
0
def get_d3_partial_dump(request):
    LOG.debug("Create partial d3 dump. %s", 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
Exemplo n.º 30
0
def insert_as_statement(text: str, db_user: User, db_issue: Issue, is_start=False) -> Statement:
    """
    Inserts the given text as statement and returns the uid

    :param text: String
    :param db_user: User
    :param db_issue: Issue
    :param is_start: Boolean
    :return: Statement
    """
    new_statement, is_duplicate = set_statement(text, db_user, is_start, db_issue)

    # add marked statement
    DBDiscussionSession.add(MarkedStatement(statement=new_statement.uid, user=db_user.uid))
    DBDiscussionSession.add(SeenStatement(statement_uid=new_statement.uid, user_uid=db_user.uid))
    DBDiscussionSession.flush()

    _tn = Translator(db_issue.lang)
    _um = UrlManager(db_issue.slug)
    append_action_to_issue_rss(db_issue=db_issue, db_author=db_user,
                               title=_tn.get(_.positionAdded if is_start else _.statementAdded),
                               description='...' + get_text_for_statement_uid(new_statement.uid) + '...',
                               url=_um.get_url_for_statement_attitude(new_statement.uid))

    return new_statement