Merge remote-tracking branch 'origin/main' into storages-to-qeuries

This commit is contained in:
Igor Lobanov
2022-11-28 13:54:22 +01:00
30 changed files with 605 additions and 430 deletions

View File

@@ -44,8 +44,11 @@ def apply_filters(q, filters, user=None):
filters = {} if filters is None else filters
if filters.get("reacted") and user:
q.join(Reaction, Reaction.createdBy == user.slug)
if filters.get("visibility"):
v = filters.get("visibility")
if v == "public":
q = q.filter(Shout.visibility == filters.get("visibility"))
if v == "community":
q = q.filter(Shout.visibility.in_(["public", "community"]))
if filters.get("layout"):
q = q.filter(Shout.layout == filters.get("layout"))
if filters.get("author"):
@@ -74,7 +77,6 @@ def add_stat_columns(q):
async def load_shout(_, info, slug):
with local_session() as session:
q = select(Shout).options(
# TODO add cation
joinedload(Shout.authors),
joinedload(Shout.topics),
)

View File

@@ -13,21 +13,18 @@ from orm.user import AuthorFollower, Role, User, UserRating, UserRole
# from .community import followed_communities
from resolvers.inbox.unread import get_total_unread_counter
from .topics import get_topic_stat
async def user_subscriptions(slug: str):
return {
"unread": await get_total_unread_counter(slug), # unread inbox messages counter
"topics": [t.slug for t in await followed_topics(slug)], # followed topics slugs
"authors": [a.slug for a in await followed_authors(slug)], # followed authors slugs
"reactions": await ReactedStorage.get_shouts_by_author(slug),
"reactions": await followed_reactions(slug)
# "communities": [c.slug for c in followed_communities(slug)], # communities
}
async def get_author_stat(slug):
# TODO: implement author stat
with local_session() as session:
return {
"shouts": session.query(ShoutAuthor).where(ShoutAuthor.user == slug).count(),
@@ -39,11 +36,29 @@ async def get_author_stat(slug):
).where(
Reaction.createdBy == slug
).filter(
func.length(Reaction.body) > 0
Reaction.body.is_not(None)
).count()
}
# @query.field("userFollowedDiscussions")
@login_required
async def followed_discussions(_, info, slug) -> List[Topic]:
return await followed_reactions(slug)
async def followed_reactions(slug):
with local_session() as session:
user = session.query(User).where(User.slug == slug).first()
return session.query(
Reaction.shout
).where(
Reaction.createdBy == slug
).filter(
Reaction.createdAt > user.lastSeen
).all()
@query.field("userFollowedTopics")
@login_required
async def get_followed_topics(_, info, slug) -> List[Topic]:

View File

@@ -146,7 +146,11 @@ async def create_reaction(_, info, inp):
except Exception as e:
print(f"[resolvers.reactions] error on reactions autofollowing: {e}")
reaction.stat = await get_reaction_stat(reaction.id)
reaction.stat = {
"commented": 0,
"reacted": 0,
"rating": 0
}
return {"reaction": reaction}
@@ -158,11 +162,16 @@ async def update_reaction(_, info, inp):
with local_session() as session:
user = session.query(User).where(User.id == user_id).first()
reaction = session.query(Reaction).filter(Reaction.id == inp.id).first()
q = select(Reaction).filter(Reaction.id == inp.id)
q = calc_reactions(q)
[reaction, rating, commented, reacted] = session.execute(q).unique().one()
if not reaction:
return {"error": "invalid reaction id"}
if reaction.createdBy != user.slug:
return {"error": "access denied"}
reaction.body = inp["body"]
reaction.updatedAt = datetime.now(tz=timezone.utc)
if reaction.kind != inp["kind"]:
@@ -171,8 +180,11 @@ async def update_reaction(_, info, inp):
if inp.get("range"):
reaction.range = inp.get("range")
session.commit()
reaction.stat = await get_reaction_stat(reaction.id)
reaction.stat = {
"commented": commented,
"reacted": reacted,
"rating": rating
}
return {"reaction": reaction}
@@ -195,9 +207,11 @@ async def delete_reaction(_, info, rid):
def map_result_item(result_item):
reaction = result_item[0]
user = result_item[1]
[user, shout, reaction] = result_item
print(reaction)
reaction.createdBy = user
reaction.shout = shout
reaction.replyTo = reaction
return reaction
@@ -220,10 +234,17 @@ async def load_reactions_by(_, _info, by, limit=50, offset=0):
"""
CreatedByUser = aliased(User)
ReactedShout = aliased(Shout)
RepliedReaction = aliased(Reaction)
q = select(
Reaction, CreatedByUser
).join(CreatedByUser, Reaction.createdBy == CreatedByUser.slug)
Reaction, CreatedByUser, ReactedShout, RepliedReaction
).join(
CreatedByUser, Reaction.createdBy == CreatedByUser.slug
).join(
ReactedShout, Reaction.shout == ReactedShout.slug
).join(
RepliedReaction, Reaction.replyTo == RepliedReaction.id
)
if by.get("shout"):
q = q.filter(Reaction.shout == by["shout"])
@@ -243,20 +264,28 @@ async def load_reactions_by(_, _info, by, limit=50, offset=0):
order_way = asc if by.get("sort", "").startswith("-") else desc
order_field = by.get("sort") or Reaction.createdAt
q = q.group_by(
Reaction.id, CreatedByUser.id
Reaction.id, CreatedByUser.id, ReactedShout.id
).order_by(
order_way(order_field)
)
q = calc_reactions(q)
q = q.where(Reaction.deletedAt.is_(None))
q = q.limit(limit).offset(offset)
reactions = []
with local_session() as session:
reactions = list(map(map_result_item, session.execute(q)))
for reaction in reactions:
reaction.stat = await get_reaction_stat(reaction.id)
for [
[reaction, rating, commented, reacted], shout, reply
] in list(map(map_result_item, session.execute(q))):
reaction.shout = shout
reaction.replyTo = reply
reaction.stat = {
"rating": rating,
"commented": commented,
"reacted": reacted
}
reactions.append(reaction)
if by.get("stat"):
reactions.sort(lambda r: r.stat.get(by["stat"]) or r.createdAt)
if by.get("stat"):
reactions.sort(lambda r: r.stat.get(by["stat"]) or r.createdAt)
return reactions

View File

@@ -3,23 +3,14 @@ from sqlalchemy import and_, select
from auth.authenticate import login_required
from base.orm import local_session
from base.resolvers import mutation, query
from orm import Shout
from orm.topic import Topic, TopicFollower
# from services.stat.reacted import ReactedStorage
# from services.stat.viewed import ViewedStorage
from orm import Shout
async def get_topic_stat(slug):
return {
"shouts": len(TopicStat.shouts_by_topic.get(slug, {}).keys()),
"authors": len(TopicStat.authors_by_topic.get(slug, {}).keys()),
"followers": len(TopicStat.followers_by_topic.get(slug, {}).keys()),
# "viewed": await ViewedStorage.get_topic(slug),
# "reacted": len(await ReactedStorage.get_topic(slug)),
# "commented": len(await ReactedStorage.get_topic_comments(slug)),
# "rating": await ReactedStorage.get_topic_rating(slug)
"followers": len(TopicStat.followers_by_topic.get(slug, {}).keys())
}
@@ -96,11 +87,12 @@ async def topic_follow(user, slug):
async def topic_unfollow(user, slug):
with local_session() as session:
sub = (
session.query(TopicFollower)
.filter(
and_(TopicFollower.follower == user.slug, TopicFollower.topic == slug)
)
.first()
session.query(TopicFollower).filter(
and_(
TopicFollower.follower == user.slug,
TopicFollower.topic == slug
)
).first()
)
if not sub:
raise Exception("[resolvers.topics] follower not exist")