mirror of
https://github.com/Xevion/runnerspace.git
synced 2025-12-08 06:08:19 -06:00
Add like querying/checking/rendering to Feed posts
- Change runnerspace.live to Runnerspace - Change post viewing URL to say /post/🆔 instead of /feed/🆔
This commit is contained in:
28
models.py
28
models.py
@@ -3,6 +3,7 @@ import json
|
||||
from typing import List
|
||||
|
||||
import humanize
|
||||
from flask import url_for
|
||||
from flask_login import UserMixin
|
||||
from sqlalchemy import func
|
||||
|
||||
@@ -27,6 +28,9 @@ class User(UserMixin, db.Model):
|
||||
posts_liked = db.relationship("PostLike", backref=db.backref('user', lazy='joined'), lazy='dynamic', cascade='all, delete-orphan')
|
||||
comments_liked = db.relationship("CommentLike", backref=db.backref('user', lazy='joined'), lazy='dynamic', cascade='all, delete-orphan')
|
||||
|
||||
def get_url(self) -> str:
|
||||
return url_for('main.view_user', username=self.username)
|
||||
|
||||
def get_last_seen_text(self) -> str:
|
||||
delta: datetime.timedelta = datetime.datetime.utcnow() - self.last_seen
|
||||
if delta > MAXIMUM_ONLINE_DELTA:
|
||||
@@ -70,6 +74,14 @@ class User(UserMixin, db.Model):
|
||||
def display_about(self) -> str:
|
||||
return self.about_me or "This user hasn't written a bio yet."
|
||||
|
||||
def has_liked_post(self, post_id: int) -> bool:
|
||||
"""Check whether a user has liked a given post."""
|
||||
return db.session.query(PostLike.id).filter_by(post_id=post_id, user_id=self.id).first() is not None
|
||||
|
||||
def has_liked_comment(self, comment_id: int) -> bool:
|
||||
"""Check whether a user has liked a given post."""
|
||||
return db.session.query(CommentLike.id).filter_by(comment_id=comment_id, user_id=user_id).first() is not None
|
||||
|
||||
|
||||
class Post(db.Model):
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
@@ -84,6 +96,22 @@ class Post(db.Model):
|
||||
delta: datetime.timedelta = datetime.datetime.utcnow() - self.date_posted
|
||||
return humanize.naturaldelta(delta)
|
||||
|
||||
def get_like_count(self) -> bool:
|
||||
return PostLike.query.filter_by(post_id=self.id).count()
|
||||
|
||||
def get_like_text(self) -> str:
|
||||
like_count = self.get_like_count()
|
||||
top_likes = PostLike.query.filter_by(post_id=self.id).order_by(PostLike.timestamp.asc()).limit(3)
|
||||
users = [like.user for like in top_likes]
|
||||
names = [f'<a href="{user.get_url()}">{user.name}</a>' for user in users]
|
||||
|
||||
if like_count >= 3: format_string = '{0}, {1} and {2} has liked this post.'
|
||||
elif like_count == 2: format_string = '{0} and {1} has liked this post.'
|
||||
elif like_count == 1: format_string = '{0} has liked this post.'
|
||||
else: format_string = '0 likes'
|
||||
|
||||
return format_string.format(*names)
|
||||
|
||||
|
||||
class PostLike(db.Model):
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
|
||||
Reference in New Issue
Block a user