Exemple #1
0
def set_new_user(mailer: Mailer, user_data: Dict[str, Any], password: str,
                 _tn: Translator) -> Dict[str, Any]:
    """
    Public interface for creating a new user.

    :param mailer: The mailer used to send Emails to the new user.
    :param user_data: Dictionary containing user information.
    :param password: The desired password to be set. (un-hashed)
    :param _tn: The translator object to be used for messaging.
    :return: A dictionary containing whether the operation was a success, an optional error message and the newly
        created user if the transaction was successful.
    """
    # copy the dict to not change the mutable structure
    temporary_user = dict(user_data)
    db_group = DBDiscussionSession.query(Group).filter_by(name='users').first()

    # does the group exists?
    if not db_group:
        LOG.debug("Internal error occurred")
        return {
            'success': False,
            'error': _tn.get(Keywords.errorTryLateOrContant),
            'user': None
        }

    if DBDiscussionSession.query(User).filter(
            User.nickname == temporary_user['nickname']).first():
        LOG.debug("User already exists")
        return {
            'success': False,
            'error': _tn.get(Keywords.nickIsTaken),
            'user': None
        }

    temporary_user['password'] = password
    temporary_user['db_group_uid'] = db_group.uid

    success, info, db_new_user = __create_new_user(temporary_user,
                                                   _tn.get_lang())

    if db_new_user:
        # sending an email and message
        subject = _tn.get(Keywords.accountRegistration)
        body = _tn.get(Keywords.accountWasRegistered).format(
            temporary_user['firstname'], temporary_user['lastname'],
            temporary_user['email'])
        send_mail(mailer, subject, body, temporary_user['email'],
                  _tn.get_lang())
        send_welcome_notification(db_new_user.uid, _tn)

        LOG.debug("Set new user in db")
        return {'success': success, 'error': '', 'user': db_new_user}

    LOG.debug("New user not found in db")
    return {
        'success': False,
        'error': _tn.get(Keywords.errorTryLateOrContant),
        'user': None
    }
Exemple #2
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))
    }
Exemple #3
0
    def get_queue_information(self, db_user: User, session: Session, application_url: str, translator: Translator):
        """
        Setup the subpage for the delete queue

        :param db_user: User
        :param session: session of current webserver request
        :param application_url: current url of the app
        :param translator: Translator
        :return: dict()
        """
        LOG.debug("Entering setup for subpage of deletion queue")
        all_rev_dict = get_all_allowed_reviews_for_user(session, f'already_seen_{self.key}', db_user, ReviewDelete,
                                                        LastReviewerDelete)

        rev_dict = get_base_subpage_dict(ReviewDelete, all_rev_dict['reviews'], all_rev_dict['already_seen_reviews'],
                                         all_rev_dict['first_time'], db_user, all_rev_dict['already_voted_reviews'])
        if not rev_dict['rnd_review']:
            return {
                'stats': None,
                'text': None,
                'reason': None,
                'issue_titles': None,
                'extra_info': None,
                'session': session
            }

        db_reason = DBDiscussionSession.query(ReviewDeleteReason).get(rev_dict['rnd_review'].reason_uid)
        stats = get_reporter_stats_for_review(rev_dict['rnd_review'], translator.get_lang(), application_url)

        reason = ''
        if db_reason.reason == 'offtopic':
            reason = translator.get(_.argumentFlaggedBecauseOfftopic)
        if db_reason.reason == 'spam':
            reason = translator.get(_.argumentFlaggedBecauseSpam)
        if db_reason.reason == 'harmful':
            reason = translator.get(_.argumentFlaggedBecauseHarmful)

        rev_dict['already_seen_reviews'].append(rev_dict['rnd_review'].uid)
        session[f'already_seen_{self.key}'] = rev_dict['already_seen_reviews']

        return {
            'stats': stats,
            'text': rev_dict['text'],
            'reason': reason,
            'issue_titles': rev_dict['issue_titles'],
            'extra_info': rev_dict['extra_info'],
            'session': session
        }
Exemple #4
0
    def get_queue_information(self, db_user: User, session: Session,
                              application_url: str, translator: Translator):
        """
        Setup the subpage for the edit queue

        :param db_user: User
        :param session: session of current webserver request
        :param application_url: current url of the app
        :param translator: Translator
        :return: dict()
        """
        LOG.debug("Setting up the page for the edit queue")
        all_rev_dict = get_all_allowed_reviews_for_user(
            session, f'already_seen_{self.key}', db_user, ReviewEdit,
            LastReviewerEdit)

        rev_dict = get_base_subpage_dict(ReviewEdit, all_rev_dict['reviews'],
                                         all_rev_dict['already_seen_reviews'],
                                         all_rev_dict['first_time'], db_user,
                                         all_rev_dict['already_voted_reviews'])
        if not rev_dict['rnd_review']:
            return {
                'stats': None,
                'text': None,
                'reason': None,
                'issue': None,
                'extra_info': None,
                'session': session
            }

        reason = translator.get(_.argumentFlaggedBecauseEdit)

        # build correction
        db_edit_value = DBDiscussionSession.query(ReviewEditValue).filter_by(
            review_edit_uid=rev_dict['rnd_review'].uid).first()
        stats = get_reporter_stats_for_review(rev_dict['rnd_review'],
                                              translator.get_lang(),
                                              application_url)

        if not db_edit_value:
            return {
                'stats': None,
                'text': None,
                'reason': None,
                'issue_titles': None,
                'extra_info': None,
                'session': session
            }

        correction_list = [char for char in rev_dict['text']]
        self.__difference_between_string(rev_dict['text'],
                                         db_edit_value.content,
                                         correction_list)
        correction = ''.join(correction_list)

        rev_dict['already_seen_reviews'].append(rev_dict['rnd_review'].uid)
        session[f'already_seen_{self.key}'] = rev_dict['already_seen_reviews']

        return {
            'stats': stats,
            'text': rev_dict['text'],
            'corrected_version': db_edit_value.content,
            'corrections': correction,
            'reason': reason,
            'issue_titles': rev_dict['issue_titles'],
            'extra_info': rev_dict['extra_info'],  # TODO KILL
            'session': session
        }
Exemple #5
0
    def get_queue_information(self, db_user: User, session: Session,
                              application_url: str, translator: Translator):
        """
        Setup the subpage for the merge queue

        :param db_user: User
        :param session: session of current webserver request
        :param application_url: current url of the app
        :param translator: Translator
        :return: dict()
        """
        LOG.debug("Setting up the subpage for merge queue")
        all_rev_dict = get_all_allowed_reviews_for_user(
            session, f'already_seen_{self.key}', db_user, ReviewMerge,
            LastReviewerMerge)

        extra_info = ''
        # if we have no reviews, try again with fewer restrictions
        if not all_rev_dict['reviews']:
            LOG.debug("No unseen reviews")
            all_rev_dict['already_seen_reviews'] = list()
            extra_info = 'already_seen' if not all_rev_dict[
                'first_time'] else ''
            db_reviews = DBDiscussionSession.query(ReviewMerge).filter(
                ReviewMerge.is_executed == False,
                ReviewMerge.detector_uid != db_user.uid)
            if len(all_rev_dict['already_voted_reviews']) > 0:
                LOG.debug("Every review-case was seen")
                db_reviews = db_reviews.filter(~ReviewMerge.uid.in_(
                    all_rev_dict['already_voted_reviews']))
            all_rev_dict['reviews'] = db_reviews.all()

        if not all_rev_dict['reviews']:
            LOG.debug("No reviews present")
            return {
                'stats': None,
                'text': None,
                'reason': None,
                'issue_titles': [],
                'extra_info': None,
                'session': session
            }

        rnd_review = random.choice(all_rev_dict['reviews'])
        premises = DBDiscussionSession.query(Premise).filter_by(
            premisegroup_uid=rnd_review.premisegroup_uid).all()
        text = [premise.get_text() for premise in premises]
        db_review_values = DBDiscussionSession.query(
            ReviewMergeValues).filter_by(review_uid=rnd_review.uid).all()

        discussion_lang = DBDiscussionSession.query(Statement).get(
            premises[0].uid).lang
        translator_discussion = Translator(discussion_lang)

        if db_review_values:
            aand = translator_discussion.get(_.aand)
            merged_text = ' {} '.format(aand).join(
                [rsv.content for rsv in db_review_values])
            pgroup_only = False
        else:
            merged_text = DBDiscussionSession.query(PremiseGroup).get(
                rnd_review.premisegroup_uid).get_text()
            pgroup_only = True

        statement_uids = [p.statement_uid for p in premises]
        issue_titles = [
            issue.title
            for issue in get_issues_for_statement_uids(statement_uids)
        ]
        reason = translator.get(_.argumentFlaggedBecauseMerge)

        stats = get_reporter_stats_for_review(rnd_review,
                                              translator.get_lang(),
                                              application_url)

        all_rev_dict['already_seen_reviews'].append(rnd_review.uid)
        session[f'already_seen_{self.key}'] = all_rev_dict[
            'already_seen_reviews']

        return {
            'stats': stats,
            'text': text,
            'merged_text': merged_text,
            'reason': reason,
            'issue_titles': issue_titles,
            'extra_info': extra_info,
            'pgroup_only': pgroup_only,
            'session': session
        }
Exemple #6
0
    def get_queue_information(self, db_user: User, session: Session, application_url: str, translator: Translator):
        """
        Setup the subpage for the duplicate queue

        :param db_user: User
        :param session: session of current webserver request
        :param application_url: current url of the app
        :param translator: Translator
        :return: dict()
        """
        LOG.debug("Setting up subpage for the duplication queue")
        all_rev_dict = get_all_allowed_reviews_for_user(session, f'already_seen_{self.key}', db_user,
                                                        ReviewDuplicate,
                                                        LastReviewerDuplicate)

        extra_info = ''
        # if we have no reviews, try again with fewer restrictions
        if not all_rev_dict['reviews']:
            LOG.debug("No unseen reviews found")
            all_rev_dict['already_seen_reviews'] = list()
            extra_info = 'already_seen' if not all_rev_dict['first_time'] else ''
            all_rev_dict['reviews'] = DBDiscussionSession.query(ReviewDuplicate).filter(
                ReviewDuplicate.is_executed == False,
                ReviewDuplicate.detector_uid != db_user.uid)
            if len(all_rev_dict['already_voted_reviews']) > 0:
                LOG.debug("Everything was seen in the duplication queue")
                all_rev_dict['reviews'] = all_rev_dict['reviews'].filter(
                    ~ReviewDuplicate.uid.in_(all_rev_dict['already_voted_reviews'])).all()

        if not all_rev_dict['reviews']:
            LOG.debug("No reviews available")
            return {
                'stats': None,
                'text': None,
                'reason': None,
                'issue_titles': None,
                'extra_info': None,
                'session': session
            }

        rnd_review = random.choice(all_rev_dict['reviews'])
        db_statement = DBDiscussionSession.query(Statement).get(rnd_review.duplicate_statement_uid)
        text = db_statement.get_text()

        issue_titles = [issue.title for issue in get_issues_for_statement_uids([rnd_review.duplicate_statement_uid])]
        reason = translator.get(_.argumentFlaggedBecauseDuplicate)
        rnd_review_original_statement = DBDiscussionSession.query(Statement).get(rnd_review.original_statement_uid)
        duplicate_of_text = rnd_review_original_statement.get_text()
        stats = get_reporter_stats_for_review(rnd_review, translator.get_lang(), application_url)

        all_rev_dict['already_seen_reviews'].append(rnd_review.uid)
        session['already_seen_duplicate'] = all_rev_dict['already_seen_reviews']

        return {
            'stats': stats,
            'text': text,
            'duplicate_of': duplicate_of_text,
            'reason': reason,
            'issue_titles': issue_titles,
            'extra_info': extra_info,
            'session': session
        }
Exemple #7
0
def set_new_oauth_user(user_data: Dict[str, Any], oauth_id: str, provider: str,
                       _tn: Translator) -> Dict[str, Any]:
    """
    Create a new user for an oauth provider.

    :param user_data: Dictionary containing user information.
    :param oauth_id: The user id at his oauth-provider.
    :param provider: The oauth provider.
    :param _tn: A Translator object.
    :return: A dictionary containing whether the operation was a success, an optional error message and the newly
        created user if the transaction was successful.
    """
    temporary_user = dict(user_data)
    db_group = DBDiscussionSession.query(Group).filter_by(name='users').first()

    # does the group exists?
    if not db_group:
        LOG.debug("Internal error occurred")
        return {
            'success': False,
            'error': _tn.get(Keywords.errorTryLateOrContant),
            'user': None
        }

    # sanity check
    db_user = DBDiscussionSession.query(User).filter(
        User.oauth_provider == str(provider),
        User.oauth_provider_id == str(oauth_id)).first()
    # login of oauth user
    if db_user:
        LOG.debug("User already exists. They will login")
        return {'success': True, 'error': '', 'user': db_user}

    # sanity check
    db_user = DBDiscussionSession.query(User).filter_by(
        nickname=temporary_user['nickname']).first()
    if db_user:
        LOG.debug("User already exists")
        return {
            'success': False,
            'error': _tn.get(Keywords.nickIsTaken),
            'user': None
        }

    temporary_user['password'] = str(uuid.uuid4().hex)
    temporary_user['db_group_uid'] = db_group.uid

    success, info, db_new_user = __create_new_user(temporary_user,
                                                   _tn.get_lang(),
                                                   oauth_provider=provider,
                                                   oauth_provider_id=oauth_id)

    if db_new_user:
        LOG.debug("Set new user in db")
        return {'success': success, 'error': '', 'user': db_new_user}

    LOG.debug("New user not found in db")

    return {
        'success': False,
        'error': _tn.get(Keywords.errorTryLateOrContant),
        'user': None
    }
Exemple #8
0
    def get_queue_information(self, db_user: User, session: Session,
                              application_url: str, translator: Translator):
        """
        Setup the subpage for the optimization queue

        :param db_user: User
        :param session: session of current webserver request
        :param application_url: current url of the app
        :param translator: Translator
        :return: dict()
        """
        LOG.debug("Setting up the sub-page for the optimization-queue")
        all_rev_dict = get_all_allowed_reviews_for_user(
            session, f'already_seen_{self.key}', db_user, ReviewOptimization,
            LastReviewerOptimization)

        extra_info = ''
        # if we have no reviews, try again with fewer restrictions
        if not all_rev_dict['reviews']:
            all_rev_dict['already_seen_reviews'] = list()
            extra_info = 'already_seen' if not all_rev_dict[
                'first_time'] else ''
            db_reviews = DBDiscussionSession.query(ReviewOptimization).filter(
                ReviewOptimization.is_executed == False,
                ReviewOptimization.detector_uid != db_user.uid)
            if len(all_rev_dict['already_voted_reviews']) > 0:
                db_reviews = db_reviews.filter(~ReviewOptimization.uid.in_(
                    all_rev_dict['already_voted_reviews']))
            all_rev_dict['reviews'] = db_reviews.all()

        if not all_rev_dict['reviews']:
            return {
                'stats': None,
                'text': None,
                'reason': None,
                'issue_titles': None,
                'context': [],
                'extra_info': None,
                'session': session
            }

        rnd_review = random.choice(all_rev_dict['reviews'])
        if rnd_review.statement_uid is None:
            db_argument = DBDiscussionSession.query(Argument).get(
                rnd_review.argument_uid)
            text = get_text_for_argument_uid(db_argument.uid)
            issue_titles = [
                DBDiscussionSession.query(Issue).get(
                    db_argument.issue_uid).title
            ]
            parts = self.__get_text_parts_of_argument(db_argument)
            context = [text]
        else:
            db_statement = DBDiscussionSession.query(Statement).get(
                rnd_review.statement_uid)
            text = db_statement.get_text()
            issue_titles = [
                issue.title for issue in get_issues_for_statement_uids(
                    [rnd_review.statement_uid])
            ]
            parts = [
                self.__get_part_dict('statement', text, 0,
                                     rnd_review.statement_uid)
            ]
            context = []
            args = get_all_arguments_by_statement(rnd_review.statement_uid)
            if args:
                html_wrap = '<span class="text-info"><strong>{}</strong></span>'
                context = [
                    get_text_for_argument_uid(arg.uid).replace(
                        text, html_wrap.format(text)) for arg in args
                ]

        reason = translator.get(_.argumentFlaggedBecauseOptimization)

        stats = get_reporter_stats_for_review(rnd_review,
                                              translator.get_lang(),
                                              application_url)

        all_rev_dict['already_seen_reviews'].append(rnd_review.uid)
        session[f'already_seen_{self.key}'] = all_rev_dict[
            'already_seen_reviews']

        return {
            'stats': stats,
            'text': text,
            'reason': reason,
            'issue_titles': issue_titles,
            'extra_info': extra_info,
            'context': context,
            'parts': parts,
            'session': session
        }