Пример #1
0
class Vote(db.Model, DeleteMixin):
    __tablename__ = 'vote'

    user_id = db.Column(UUID,
                        db.ForeignKey('user.id', ondelete='CASCADE'),
                        primary_key=True)
    revision_id = db.Column(db.Integer,
                            db.ForeignKey('revision.id', ondelete='CASCADE'),
                            primary_key=True)
    vote = db.Column(db.Boolean, nullable=False)
    rated_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)

    @classmethod
    def create(cls, user, review, vote):
        """Create new vote for the latest revision of a specified review."""
        # Deleting the vote from the last revision if it exists
        user.display_name, cls.query.filter_by(
            user=user, revision=review.last_revision).delete()
        # Creating a new vote for the last revision
        vote_obj = cls(user=user, revision=review.last_revision, vote=vote)
        db.session.add(vote_obj)
        db.session.commit()
        return vote_obj

    def to_dict(self):
        response = dict(vote=self.vote, voted_at=self.rated_at)
        return response
Пример #2
0
class Revision(db.Model, DeleteMixin):
    __tablename__ = 'revision'

    id = db.Column(db.Integer, primary_key=True)
    review_id = db.Column(UUID,
                          db.ForeignKey('review.id', ondelete='CASCADE'),
                          index=True)
    timestamp = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    text = db.Column(db.Unicode, nullable=False)

    _votes = db.relationship('Vote',
                             cascade='delete',
                             lazy='dynamic',
                             backref='revision')
    _spam_reports = db.relationship('SpamReport',
                                    cascade='delete',
                                    lazy='dynamic',
                                    backref='revision')

    @property
    def votes_positive_count(self):
        if hasattr(self, '_votes_positive_count') is False:
            self._votes_positive_count = self._votes.filter_by(
                vote=True).count()
        return self._votes_positive_count

    @property
    def votes_negative_count(self):
        if hasattr(self, '_votes_negative_count') is False:
            self._votes_negative_count = self._votes.filter_by(
                vote=False).count()
        return self._votes_negative_count

    def to_dict(self):
        response = dict(id=self.id,
                        review_id=self.review_id,
                        timestamp=self.timestamp,
                        votes_positive=self.votes_positive_count,
                        votes_negative=self.votes_negative_count,
                        text=self.text)
        return response

    @classmethod
    def create(cls, review_id, text):
        revision = cls(review_id=review_id, text=text)
        db.session.add(revision)
        db.session.commit()
        return revision
Пример #3
0
class License(db.Model, DeleteMixin):
    __tablename__ = 'license'

    id = db.Column(db.Unicode, primary_key=True)
    full_name = db.Column(db.Unicode, nullable=False)
    info_url = db.Column(db.Unicode)

    _reviews = db.relationship('Review',
                               cascade='delete',
                               lazy='dynamic',
                               backref='license')

    @classmethod
    def create(cls, id, full_name, info_url=None):
        new = cls(id=id, full_name=full_name, info_url=info_url)
        db.session.add(new)
        db.session.commit()
        return new

    def to_dict(self):
        response = dict(id=self.id,
                        full_name=self.full_name,
                        info_url=self.info_url)
        return response
Пример #4
0
class OAuthGrant(db.Model, DeleteMixin):
    __tablename__ = 'oauth_grant'

    id = db.Column(db.Integer, primary_key=True)
    client_id = db.Column(db.Unicode, db.ForeignKey('oauth_client.client_id', onupdate='CASCADE', ondelete='CASCADE'), nullable=False)
    code = db.Column(db.Unicode, index=True, nullable=False)
    expires = db.Column(db.DateTime, nullable=False)
    redirect_uri = db.Column(db.UnicodeText, nullable=False)
    scopes = db.Column(db.UnicodeText)

    # Resource owner
    user_id = db.Column(UUID, db.ForeignKey('user.id', ondelete='CASCADE'), nullable=False)

    def get_scopes(self):
        if hasattr(self, '_scopes') is False:
            self._scopes = self.scopes.split()
        return self._scopes
Пример #5
0
class SpamReport(db.Model, DeleteMixin):
    __tablename__ = 'spam_report'

    user_id = db.Column(UUID,
                        db.ForeignKey('user.id', ondelete='CASCADE'),
                        primary_key=True)
    reason = db.Column(db.Unicode)
    revision_id = db.Column(db.Integer,
                            db.ForeignKey('revision.id', ondelete='CASCADE'),
                            primary_key=True)
    reported_at = db.Column(db.DateTime,
                            default=datetime.utcnow,
                            nullable=False)
    is_archived = db.Column(db.Boolean, nullable=False, default=False)

    @classmethod
    def get(cls, **kwargs):
        return cls.query.filter_by(**kwargs).first()

    @property
    def review(self):
        return Review.get(id=self.revision.review_id)

    @classmethod
    def create(cls, revision_id, user, reason):
        report = cls(user=user, revision_id=revision_id, reason=reason)
        db.session.add(report)
        db.session.commit()
        return report

    def archive(self):
        self.is_archived = True
        db.session.commit()

    @classmethod
    def list(cls, **kwargs):
        """Get a list of reports.

        Args:
            review_id: UUID of the review that is associated with the report.
            user_id: UUID of the user who created the report.
            limit: Maximum number of reviews returned by this method.
            offset: Offset that can be used in conjunction with the limit.

        Returns:
            Pair of values: list of report that match applied filters and
            total number of reports.
        """

        query = SpamReport.query
        inc_archived = kwargs.pop('inc_archived', None)
        if not inc_archived:
            query = query.filter(SpamReport.is_archived == False)

        review_id = kwargs.pop('review_id', None)
        if review_id is not None:
            revision_ids = db.session.query(
                Revision.id).filter_by(review_id=review_id)
            query = SpamReport.query.filter(
                SpamReport.revision_id.in_(revision_ids))

        user_id = kwargs.pop('user_id', None)
        if user_id is not None:
            query = query.filter(SpamReport.user_id == user_id)

        count = query.count()

        query = query.order_by(desc(SpamReport.reported_at))

        limit = kwargs.pop('limit', None)
        if limit is not None:
            query = query.limit(limit)

        offset = kwargs.pop('offset', None)
        if offset is not None:
            query = query.offset(offset)

        if kwargs:
            raise TypeError('Unexpected **kwargs: %r' % kwargs)

        return query.all(), count
Пример #6
0
class Review(db.Model, DeleteMixin):
    __tablename__ = 'review'
    CACHE_NAMESPACE = 'Review'

    id = db.Column(UUID,
                   primary_key=True,
                   server_default=db.text('uuid_generate_v4()'))
    entity_id = db.Column(UUID, index=True, nullable=False)
    entity_type = db.Column(db.Enum(*ENTITY_TYPES, name='entity_types'),
                            nullable=False)
    user_id = db.Column(UUID,
                        db.ForeignKey('user.id', ondelete='CASCADE'),
                        nullable=False)
    edits = db.Column(db.Integer, nullable=False, default=0)
    is_draft = db.Column(db.Boolean, nullable=False, default=False)
    is_hidden = db.Column(db.Boolean, nullable=False, default=False)
    license_id = db.Column(db.Unicode,
                           db.ForeignKey('license.id', ondelete='CASCADE'),
                           nullable=False)
    language = db.Column(db.String(3), default='en', nullable=False)
    source = db.Column(db.Unicode)
    source_url = db.Column(db.Unicode)

    revisions = db.relationship('Revision',
                                order_by='Revision.timestamp',
                                backref='review',
                                cascade='delete')

    __table_args__ = (db.UniqueConstraint('entity_id', 'user_id'), )

    def to_dict(self, confidential=False):
        return dict(
            id=self.id,
            entity_id=self.entity_id,
            entity_type=self.entity_type,
            user=self.user.to_dict(confidential=confidential),
            text=self.text,
            created=self.revisions[0].timestamp,
            last_updated=self.revisions[-1].timestamp,
            edits=self.edits,
            votes_positive=self.votes_positive_count,
            votes_negative=self.votes_negative_count,
            rating=self.rating,
            license=self.license.to_dict(),
            language=self.language,
            source=self.source,
            source_url=self.source_url,
        )

    @classmethod
    def get(cls, **kwargs):
        return cls.query.filter_by(**kwargs).first()

    @property
    def last_revision(self):
        """Returns latest revision of this review."""
        return self.revisions[-1]

    @property
    def text(self):
        """Returns text of the latest revision."""
        return self.last_revision.text  # latest revision

    @hybrid_property
    def created(self):
        """Returns creation time of this review (first revision)."""
        if self.revisions:
            return self.revisions[0].timestamp
        else:
            return None

    @created.expression
    def created(cls):
        return Revision.timestamp

    @property
    def votes_positive_count(self):
        return self.last_revision.votes_positive_count

    @property
    def votes_negative_count(self):
        return self.last_revision.votes_negative_count

    @property
    def rating(self):
        if hasattr(self, '_rating') is False:
            self._rating = self.votes_positive_count - self.votes_negative_count
        return self._rating

    def hide(self):
        self.is_hidden = True
        db.session.commit()

    def unhide(self):
        self.is_hidden = False
        db.session.commit()

    @classmethod
    def list(cls, **kwargs):
        """Get a list of reviews.

        This method provides several filters that can be used to select
        specific reviews. See argument description below for more info.

        Args:
            entity_id: MBID of the entity that is associated with a
                review.
            entity_type: One of the supported reviewable entities. 'release_group'
                or 'event' etc.
            user_id: UUID of the author.
            sort: Order of returned reviews. Can be either "rating" (order by
                rating), or "created" (order by creation time), or "random" (order randomly)
            limit: Maximum number of reviews returned by this method.
            offset: Offset that can be used in conjunction with the limit.
            language: Language (code) of returned reviews.
            licence_id: License of returned reviews.
            inc_drafts: True if reviews marked as drafts should be included,
                False if not.
            inc_hidden: True if reviews marked as hidden should be included,
                False if not.
            exclude: List of id of reviews to exclude.

        Returns:
            Pair of values: list of reviews that match applied filters and
            total number of reviews.
        """
        query = Review.query
        inc_drafts = kwargs.pop('inc_drafts', None)
        if not inc_drafts:
            query = query.filter(Review.is_draft == False)

        inc_hidden = kwargs.pop('inc_hidden', None)
        if not inc_hidden:
            query = query.filter(Review.is_hidden == False)

        # FILTERING:

        entity_id = kwargs.pop('entity_id', None)
        if entity_id is not None:
            query = query.filter(Review.entity_id == entity_id)

        entity_type = kwargs.pop('entity_type', None)
        if entity_type is not None:
            query = query.filter(Review.entity_type == entity_type)

        language = kwargs.pop('language', None)
        if language is not None:
            query = query.filter(Review.language == language)

        license_id = kwargs.pop('license_id', None)
        if license_id is not None:
            query = query.filter(Review.license_id == license_id)

        user_id = kwargs.pop('user_id', None)
        if user_id is not None:
            query = query.filter(Review.user_id == user_id)

        exclude = kwargs.pop('exclude', None)
        if exclude is not None:
            query = query.filter(Review.id.notin_(exclude))

        count = query.count(
        )  # Total count should be calculated before limits and sorting

        # SORTING:
        sort = kwargs.pop('sort', None)

        if sort == 'rating':  # order by rating (positive votes - negative votes)

            # TODO(roman): Simplify this part. It can probably be rewritten using
            # hybrid attributes (by making rating property a hybrid_property),
            # but I'm not sure how to do that.

            # Preparing base query for getting votes
            vote_query_base = db.session.query(
                Vote.revision_id,  # revision associated with a vote
                Vote.vote,  # vote itself (True if positive, False if negative)
                func.count().label('c')  # number of votes
            ).group_by(Vote.revision_id, Vote.vote)

            # Getting positive votes
            votes_pos = vote_query_base.subquery('votes_pos')
            query = query.outerjoin(Revision).outerjoin(
                votes_pos,
                and_(votes_pos.c.revision_id == Revision.id,
                     votes_pos.c.vote == True))

            # Getting negative votes
            votes_neg = vote_query_base.subquery('votes_neg')
            query = query.outerjoin(Revision).outerjoin(
                votes_neg,
                and_(votes_neg.c.revision_id == Revision.id,
                     votes_neg.c.vote == False))

            query = query.order_by(
                desc(
                    func.coalesce(votes_pos.c.c, 0) -
                    func.coalesce(votes_neg.c.c, 0)))

        elif sort == 'created':  # order by creation time
            # Getting publication times for all reviews
            pub_times = db.session.query(
                func.min(Revision.timestamp).label('published_on'),
                Revision.review_id,
            ).group_by(Revision.review_id).subquery('pub_times')

            # Joining and sorting by publication time
            query = query.outerjoin(pub_times).order_by(
                desc('pub_times.published_on'))

        elif sort == 'random':  # order randomly
            query = query.order_by(func.random())

        limit = kwargs.pop('limit', None)
        if limit is not None:
            query = query.limit(limit)

        offset = kwargs.pop('offset', None)
        if offset is not None:
            query = query.offset(offset)

        if kwargs:
            raise TypeError('Unexpected **kwargs: %r' % kwargs)

        return query.all(), count

    @classmethod
    def get_count(cls, **kwargs):
        review_count = 0
        if ('is_draft' in kwargs):
            is_drafted = kwargs.pop('is_draft', False)
            review_count += cls.query.filter(
                cls.is_draft == is_drafted).count()
        if ('is_hidden' in kwargs):
            is_hidden = kwargs.pop('is_hidden', False)
            review_count += cls.query.filter(
                cls.is_hidden == is_hidden).count()
        if (kwargs):
            raise TypeError('Unexpected **kwargs: %r' % kwargs)
        return review_count

    @classmethod
    def create(cls, **kwargs):
        if 'release_group' in kwargs:
            entity_id = kwargs.pop('release_group')
            entity_type = 'release_group'
        else:
            entity_id = kwargs.pop('entity_id')
            entity_type = kwargs.pop('entity_type')

        review = Review(entity_id=entity_id,
                        entity_type=entity_type,
                        user_id=kwargs.pop('user_id'),
                        language=kwargs.pop('language', None),
                        is_draft=kwargs.pop('is_draft', False),
                        license_id=kwargs.pop('license_id',
                                              DEFAULT_LICENSE_ID),
                        source=kwargs.pop('source', None),
                        source_url=kwargs.pop('source_url', None))
        db.session.add(review)
        db.session.flush()
        db.session.add(Revision(review_id=review.id, text=kwargs.pop('text')))

        if kwargs:
            db.session.rollback()
            raise TypeError('Unexpected **kwargs: %r' % kwargs)

        db.session.commit()
        cache.invalidate_namespace(Review.CACHE_NAMESPACE)

        return review

    def update(self, **kwargs):
        """Update contents of this review.

        Returns:
            New revision of this review.
        """
        license_id = kwargs.pop('license_id', None)
        if license_id is not None:
            if not self.is_draft:  # If trying to convert published review into draft.
                raise BadRequest(
                    lazy_gettext(
                        "Changing license of a published review is not allowed."
                    ))
            self.license_id = license_id

        language = kwargs.pop('language', None)
        if language is not None:
            self.language = language

        is_draft = kwargs.pop('is_draft', None)
        if is_draft is not None:  # This should be done after all changes that depend on review being a draft.
            if not self.is_draft and is_draft:  # If trying to convert published review into draft.
                raise BadRequest(
                    lazy_gettext(
                        "Converting published reviews back to drafts is not allowed."
                    ))
            self.is_draft = is_draft

        new_revision = Revision.create(self.id, kwargs.pop('text'))
        cache.invalidate_namespace(Review.CACHE_NAMESPACE)

        if kwargs:
            # FIXME: Revision creation and other changes need to be rolled back
            # there, but there's a `commit` in Revision.create.
            raise TypeError('Unexpected **kwargs: %r' % kwargs)

        return new_revision

    @classmethod
    def get_popular(cls, limit=None):
        """Get list of popular reviews.

        Popularity is determined by rating of a particular review. Rating is a
        difference between positive votes and negative. In this case only votes
        from the last month are used to calculate rating.

        Results are cached for 12 hours.

        Args:
            limit: Maximum number of reviews to return.

        Returns:
            Randomized list of popular reviews which are converted into
            dictionaries using to_dict method.
        """
        cache_key = cache.gen_key('popular_reviews', limit)
        reviews = cache.get(cache_key, Review.CACHE_NAMESPACE)

        if not reviews:
            # Selecting reviews for distinct release groups
            # TODO(roman): The is a problem with selecting popular reviews like
            # this: if there are multiple reviews for a release group we don't
            # choose the most popular.
            distinct_subquery = db.session.query(Review) \
                .filter(Review.is_draft == False) \
                .distinct(Review.entity_id).subquery()

            # Randomizing results to get some variety
            rand_subquery = db.session.query(aliased(Review, distinct_subquery)) \
                .order_by(func.random()).subquery()

            # Sorting reviews by rating
            query = db.session.query(aliased(Review, rand_subquery))

            # Preparing base query for getting votes
            vote_query_base = db.session.query(
                Vote.revision_id, Vote.vote, func.count().label('c')) \
                .group_by(Vote.revision_id, Vote.vote) \
                .filter(Vote.rated_at > datetime.now() - timedelta(weeks=4))

            # Getting positive votes
            votes_pos = vote_query_base.subquery('votes_pos')
            query = query.outerjoin(Revision).outerjoin(
                votes_pos,
                and_(votes_pos.c.revision_id == Revision.id,
                     votes_pos.c.vote == True))

            # Getting negative votes
            votes_neg = vote_query_base.subquery('votes_neg')
            query = query.outerjoin(Revision).outerjoin(
                votes_neg,
                and_(votes_neg.c.revision_id == Revision.id,
                     votes_neg.c.vote == False))

            query = query.order_by(
                desc(
                    func.coalesce(votes_pos.c.c, 0) -
                    func.coalesce(votes_neg.c.c, 0)))

            if limit is not None:
                # Selecting more reviews there so we'll have something
                # different to show (shuffling is done below).
                query = query.limit(limit * 4)

            reviews = query.all()
            reviews = [review.to_dict(confidential=True) for review in reviews]
            cache.set(cache_key, reviews, 1 * 60 * 60,
                      Review.CACHE_NAMESPACE)  # 1 hour

        shuffle(reviews)  # a bit more variety
        return reviews[:limit]
Пример #7
0
class ModerationLog(db.Model, DeleteMixin):
    __tablename__ = 'moderation_log'

    id = db.Column(db.Integer, primary_key=True)
    admin_id = db.Column(UUID,
                         db.ForeignKey('user.id', ondelete='CASCADE'),
                         nullable=False)
    user_id = db.Column(UUID, db.ForeignKey('user.id', ondelete='CASCADE'))
    review_id = db.Column(UUID, db.ForeignKey('review.id', ondelete='CASCADE'))
    action = db.Column(db.Enum(ACTION_HIDE_REVIEW,
                               ACTION_BLOCK_USER,
                               name='action_types'),
                       nullable=False)
    timestamp = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)
    reason = db.Column(db.Unicode, nullable=False)

    @property
    def user(self):
        return User.get(id=self.user_id)

    @property
    def admin(self):
        return User.get(id=self.admin_id)

    @property
    def review(self):
        return Review.get(id=self.review_id)

    @classmethod
    def get(cls, **kwargs):
        return cls.query.filter_by(**kwargs).first()

    @classmethod
    def create(cls, admin_id, action, reason, user_id=None, review_id=None):
        if user_id:
            log = cls(admin_id=str(admin_id),
                      action=action,
                      reason=reason,
                      user_id=str(user_id))
        elif review_id:
            log = cls(admin_id=str(admin_id),
                      action=action,
                      reason=reason,
                      review_id=str(review_id))
        db.session.add(log)
        db.session.commit()
        return log

    @classmethod
    def list(cls, **kwargs):
        """Get a list of log entries.

        Args:
            admin_id: UUID of the admin whose actions generated the log.
            limit: Maximum number of reviews returned by this method.
            offset: Offset that can be used in conjunction with the limit.

        Returns:
            Pair of values: list of log entries that match applied filters and
            total number of log entries.
        """

        query = ModerationLog.query

        admin_id = kwargs.pop('admin_id', None)
        if admin_id is not None:
            query = query.filter(ModerationLog.admin_id == admin_id)

        count = query.count()

        query = query.order_by(desc(ModerationLog.timestamp))

        limit = kwargs.pop('limit', None)
        if limit is not None:
            query = query.limit(limit)

        offset = kwargs.pop('offset', None)
        if offset is not None:
            query = query.offset(offset)

        if kwargs:
            raise TypeError('Unexpected **kwargs: %r' % kwargs)

        return query.all(), count
Пример #8
0
class User(db.Model, AdminMixin, DeleteMixin):
    __tablename__ = 'user'

    id = db.Column(UUID,
                   primary_key=True,
                   server_default=db.text('uuid_generate_v4()'))
    display_name = db.Column(db.Unicode, nullable=False)
    email = db.Column(db.Unicode)
    created = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
    musicbrainz_id = db.Column(db.Unicode, unique=True)
    show_gravatar = db.Column(db.Boolean,
                              nullable=False,
                              server_default="False")
    is_blocked = db.Column(db.Boolean, nullable=False, server_default="False")

    spam_reports = db.relationship('SpamReport',
                                   cascade='delete',
                                   backref='user')
    clients = db.relationship('OAuthClient', cascade='delete', backref='user')
    grants = db.relationship('OAuthGrant', cascade='delete', backref='user')
    tokens = db.relationship('OAuthToken', cascade='delete', backref='user')

    _reviews = db.relationship('Review',
                               cascade='delete',
                               lazy='dynamic',
                               backref=backref('user', lazy='joined'))
    _votes = db.relationship('Vote',
                             cascade='delete',
                             lazy='dynamic',
                             backref='user')

    # a list of allowed values of `inc` parameter in API calls
    allowed_includes = ('user_type', 'stats')

    @classmethod
    def get(cls, **kwargs):
        return cls.query.filter_by(**kwargs).first()

    @classmethod
    def get_or_create(cls, display_name, musicbrainz_id, **kwargs):
        user = cls.query.filter_by(musicbrainz_id=musicbrainz_id,
                                   **kwargs).first()
        if user is None:
            user = cls(display_name=display_name,
                       musicbrainz_id=musicbrainz_id,
                       **kwargs)
            db.session.add(user)
            db.session.commit()
        return user

    @classmethod
    def list(cls, limit=None, offset=None):
        query = User.query
        count = query.count()
        if limit is not None:
            query = query.limit(limit)
        if offset is not None:
            query = query.offset(offset)
        users = query.all()
        return users, count

    @classmethod
    def get_count(cls):
        return cls.query.count()

    def has_voted(self, review):
        if self._votes.filter_by(revision=review.last_revision).count() > 0:
            return True
        else:
            return False

    @property
    def is_review_limit_exceeded(self):
        if self.reviews_today_count() >= self.user_type.reviews_per_day:
            return True
        else:
            return False

    @property
    def is_vote_limit_exceeded(self):
        if self.votes_today_count() >= self.user_type.votes_per_day:
            return True
        else:
            return False

    @property
    def karma(self):
        """User's karma. Based on ratings of revisions."""
        if hasattr(self, '_karma') is False:
            # TODO: Improve this
            q = db.session.query(Vote).outerjoin(Revision).outerjoin(
                Review).outerjoin(User).filter(User.id == self.id)
            query_pos = q.filter(Vote.vote == True)
            query_neg = q.filter(Vote.vote == False)
            self._karma = query_pos.count() - query_neg.count()
        return self._karma

    @property
    def reviews(self):
        return self._reviews.all()

    @property
    def avatar(self):
        """Link to user's avatar image."""
        if self.show_gravatar and self.email:
            return "https://gravatar.com/avatar/" + hashlib.md5(
                self.email.encode("utf-8")).hexdigest() + "?d=identicon&r=pg"
        else:
            return "https://gravatar.com/avatar/" + hashlib.md5(
                self.id.encode("utf-8")).hexdigest() + "?d=identicon"

    @property
    def stats(self):
        today = date.today()
        return dict(
            reviews_today=self.reviews_today_count(),
            reviews_last_7_days=self.reviews_since_count(today -
                                                         timedelta(days=7)),
            reviews_this_month=self.reviews_since_count(
                date(today.year, today.month, 1)),
            votes_today=self.votes_today_count(),
            votes_last_7_days=self.votes_since_count(today -
                                                     timedelta(days=7)),
            votes_this_month=self.votes_since_count(
                date(today.year, today.month, 1)))

    def _reviews_since(self, date):
        rev_q = db.session.query(Revision.review_id, db.func.min(Revision.timestamp).label('creation_time'))\
            .group_by(Revision.review_id).subquery('time')
        return self._reviews.outerjoin(rev_q,
                                       Review.id == rev_q.c.review_id).filter(
                                           rev_q.c.creation_time >= date)

    def reviews_since(self, date):
        return self._reviews_since(date).all()

    def reviews_since_count(self, date):
        return self._reviews_since(date).count()

    def reviews_today(self):
        return self.reviews_since(date.today())

    def reviews_today_count(self):
        return self.reviews_since_count(date.today())

    @property
    def votes(self):
        return self._votes.all()

    def _votes_since(self, date):
        return self._votes.filter(Vote.rated_at >= date)

    def votes_since(self, date):
        return self._votes_since(date).all()

    def votes_since_count(self, date):
        return self._votes_since(date).count()

    def votes_today(self):
        return self.votes_since(date.today())

    def votes_today_count(self):
        return self.votes_since_count(date.today())

    def to_dict(self, includes=None, confidential=False):
        if includes is None:
            includes = []
        response = dict(id=self.id,
                        display_name=self.display_name,
                        created=self.created,
                        karma=self.karma,
                        user_type=self.user_type.label)

        if confidential is True:
            response.update(
                dict(email=self.email,
                     avatar=self.avatar,
                     show_gravatar=self.show_gravatar,
                     musicbrainz_id=self.musicbrainz_id))

        if 'user_type' in includes:
            response['user_type'] = dict(
                label=self.user_type.label,
                reviews_per_day=self.user_type.reviews_per_day,
                votes_per_day=self.user_type.votes_per_day)

        if 'stats' in includes:
            today = date.today()
            response['stats'] = dict(
                reviews_today=self.reviews_today_count(),
                reviews_last_7_days=self.reviews_since_count(today - timedelta(
                    days=7)),
                reviews_this_month=self.reviews_since_count(
                    date(today.year, today.month, 1)),
                votes_today=self.votes_today_count(),
                votes_last_7_days=self.votes_since_count(today -
                                                         timedelta(days=7)),
                votes_this_month=self.votes_since_count(
                    date(today.year, today.month, 1)))

        return response

    @property
    def user_type(self):
        def get_user_type(user):
            for user_type in user_types:
                if user_type.is_instance(user):
                    return user_type

        if hasattr(self, '_user_type') is False:
            self._user_type = get_user_type(self)
        return self._user_type

    def update(self, display_name=None, email=None, show_gravatar=None):
        if display_name is not None:
            self.display_name = display_name
        if show_gravatar is not None:
            self.show_gravatar = show_gravatar
        self.email = email
        db.session.commit()

    def block(self):
        self.is_blocked = True
        db.session.commit()

    def unblock(self):
        self.is_blocked = False
        db.session.commit()
Пример #9
0
class OAuthClient(db.Model, DeleteMixin):
    __tablename__ = 'oauth_client'

    client_id = db.Column(db.Unicode, primary_key=True)
    client_secret = db.Column(db.Unicode, nullable=False)
    redirect_uri = db.Column(db.UnicodeText, nullable=False)

    user_id = db.Column(UUID, db.ForeignKey('user.id', ondelete='CASCADE'))
    name = db.Column(db.Unicode, nullable=False)
    desc = db.Column(db.Unicode, nullable=False)
    website = db.Column(db.Unicode, nullable=False)

    grants = db.relationship('OAuthGrant', cascade='all', backref='client')
    tokens = db.relationship('OAuthToken', cascade='all', backref='client')

    allowed_includes = []

    @classmethod
    def create(cls, user, name, desc, website, redirect_uri):
        """Creates new OAuth client and generates a secret key for it.

        Args:
            user: User who manages the client.
            name: Name of the client.
            desc: Client description.
            website: Client web site.
            redirect_uri: URI where responses will be sent.

        Returns:
            New OAuth client.
        """
        client_id = generate_string(20)
        client_secret = generate_string(40)
        client = cls(client_id=client_id, client_secret=client_secret,
                     user=user, name=name, desc=desc, website=website,
                     redirect_uri=redirect_uri)
        db.session.add(client)
        db.session.commit()
        return client

    def to_dict(self):
        return dict(
            client_id=self.client_id,
            client_secret=self.client_secret,
            user_id=self.user_id,
            name=self.name,
            desc=self.desc,
            website=self.website,
            redirect_uri=self.redirect_uri
        )

    def update(self, name=None, desc=None, website=None, redirect_uri=None):
        if name is not None:
            self.name = name
        if desc is not None:
            self.desc = desc
        if website is not None:
            self.website = website
        if redirect_uri is not None:
            self.redirect_uri = redirect_uri
        db.session.commit()