fmt
This commit is contained in:
@@ -1,75 +1,103 @@
|
||||
from resolvers.author import (get_author, get_author_followers,
|
||||
get_author_follows, get_author_follows_authors,
|
||||
get_author_follows_topics, get_author_id,
|
||||
get_authors_all, load_authors_by, search_authors,
|
||||
update_author)
|
||||
from resolvers.author import (
|
||||
get_author,
|
||||
get_author_followers,
|
||||
get_author_follows,
|
||||
get_author_follows_authors,
|
||||
get_author_follows_topics,
|
||||
get_author_id,
|
||||
get_authors_all,
|
||||
load_authors_by,
|
||||
search_authors,
|
||||
update_author,
|
||||
)
|
||||
from resolvers.community import get_communities_all, get_community
|
||||
from resolvers.editor import create_shout, delete_shout, update_shout
|
||||
from resolvers.follower import (follow, get_shout_followers,
|
||||
get_topic_followers, unfollow)
|
||||
from resolvers.notifier import (load_notifications, notification_mark_seen,
|
||||
notifications_seen_after,
|
||||
notifications_seen_thread)
|
||||
from resolvers.follower import (
|
||||
follow,
|
||||
get_shout_followers,
|
||||
get_topic_followers,
|
||||
unfollow,
|
||||
)
|
||||
from resolvers.notifier import (
|
||||
load_notifications,
|
||||
notification_mark_seen,
|
||||
notifications_seen_after,
|
||||
notifications_seen_thread,
|
||||
)
|
||||
from resolvers.rating import rate_author
|
||||
from resolvers.reaction import (create_reaction, delete_reaction,
|
||||
load_reactions_by, load_shouts_followed,
|
||||
update_reaction)
|
||||
from resolvers.reader import (get_shout, load_shouts_by, load_shouts_feed,
|
||||
load_shouts_random_top, load_shouts_random_topic,
|
||||
load_shouts_search, load_shouts_unrated)
|
||||
from resolvers.topic import (get_topic, get_topics_all, get_topics_by_author,
|
||||
get_topics_by_community)
|
||||
from resolvers.reaction import (
|
||||
create_reaction,
|
||||
delete_reaction,
|
||||
load_reactions_by,
|
||||
load_shouts_followed,
|
||||
update_reaction,
|
||||
)
|
||||
from resolvers.reader import (
|
||||
get_shout,
|
||||
load_shouts_by,
|
||||
load_shouts_feed,
|
||||
load_shouts_random_top,
|
||||
load_shouts_random_topic,
|
||||
load_shouts_search,
|
||||
load_shouts_unrated,
|
||||
)
|
||||
from resolvers.topic import (
|
||||
get_topic,
|
||||
get_topics_all,
|
||||
get_topics_by_author,
|
||||
get_topics_by_community,
|
||||
)
|
||||
from services.triggers import events_register
|
||||
|
||||
events_register()
|
||||
|
||||
__all__ = [
|
||||
# author
|
||||
'get_author',
|
||||
'get_author_id',
|
||||
'get_author_follows',
|
||||
'get_author_follows_topics',
|
||||
'get_author_follows_authors',
|
||||
'get_authors_all',
|
||||
'load_authors_by',
|
||||
'rate_author',
|
||||
'update_author',
|
||||
'search_authors',
|
||||
"get_author",
|
||||
"get_author_id",
|
||||
"get_author_follows",
|
||||
"get_author_follows_topics",
|
||||
"get_author_follows_authors",
|
||||
"get_authors_all",
|
||||
"load_authors_by",
|
||||
"rate_author",
|
||||
"update_author",
|
||||
"search_authors",
|
||||
# community
|
||||
'get_community',
|
||||
'get_communities_all',
|
||||
"get_community",
|
||||
"get_communities_all",
|
||||
# topic
|
||||
'get_topic',
|
||||
'get_topics_all',
|
||||
'get_topics_by_community',
|
||||
'get_topics_by_author',
|
||||
"get_topic",
|
||||
"get_topics_all",
|
||||
"get_topics_by_community",
|
||||
"get_topics_by_author",
|
||||
# reader
|
||||
'get_shout',
|
||||
'load_shouts_by',
|
||||
'load_shouts_feed',
|
||||
'load_shouts_search',
|
||||
'load_shouts_followed',
|
||||
'load_shouts_unrated',
|
||||
'load_shouts_random_top',
|
||||
'load_shouts_random_topic',
|
||||
"get_shout",
|
||||
"load_shouts_by",
|
||||
"load_shouts_feed",
|
||||
"load_shouts_search",
|
||||
"load_shouts_followed",
|
||||
"load_shouts_unrated",
|
||||
"load_shouts_random_top",
|
||||
"load_shouts_random_topic",
|
||||
# follower
|
||||
'follow',
|
||||
'unfollow',
|
||||
'get_topic_followers',
|
||||
'get_shout_followers',
|
||||
'get_author_followers',
|
||||
"follow",
|
||||
"unfollow",
|
||||
"get_topic_followers",
|
||||
"get_shout_followers",
|
||||
"get_author_followers",
|
||||
# editor
|
||||
'create_shout',
|
||||
'update_shout',
|
||||
'delete_shout',
|
||||
"create_shout",
|
||||
"update_shout",
|
||||
"delete_shout",
|
||||
# reaction
|
||||
'create_reaction',
|
||||
'update_reaction',
|
||||
'delete_reaction',
|
||||
'load_reactions_by',
|
||||
"create_reaction",
|
||||
"update_reaction",
|
||||
"delete_reaction",
|
||||
"load_reactions_by",
|
||||
# notifier
|
||||
'load_notifications',
|
||||
'notifications_seen_thread',
|
||||
'notifications_seen_after',
|
||||
'notification_mark_seen',
|
||||
"load_notifications",
|
||||
"notifications_seen_thread",
|
||||
"notifications_seen_after",
|
||||
"notification_mark_seen",
|
||||
]
|
||||
|
@@ -19,12 +19,12 @@ from services.rediscache import redis
|
||||
from services.schema import mutation, query
|
||||
|
||||
|
||||
@mutation.field('update_author')
|
||||
@mutation.field("update_author")
|
||||
@login_required
|
||||
async def update_author(_, info, profile):
|
||||
user_id = info.context.get('user_id')
|
||||
user_id = info.context.get("user_id")
|
||||
if not user_id:
|
||||
return {'error': 'unauthorized', 'author': None}
|
||||
return {"error": "unauthorized", "author": None}
|
||||
try:
|
||||
with local_session() as session:
|
||||
author = session.query(Author).where(Author.user == user_id).first()
|
||||
@@ -32,69 +32,72 @@ async def update_author(_, info, profile):
|
||||
Author.update(author, profile)
|
||||
session.add(author)
|
||||
session.commit()
|
||||
return {'error': None, 'author': author}
|
||||
return {"error": None, "author": author}
|
||||
except Exception as exc:
|
||||
import traceback
|
||||
|
||||
logger.error(traceback.format_exc())
|
||||
return {'error': exc, 'author': None}
|
||||
return {"error": exc, "author": None}
|
||||
|
||||
|
||||
@query.field('get_authors_all')
|
||||
@query.field("get_authors_all")
|
||||
def get_authors_all(_, _info):
|
||||
with local_session() as session:
|
||||
authors = session.query(Author).all()
|
||||
return authors
|
||||
|
||||
|
||||
@query.field('get_author')
|
||||
async def get_author(_, _info, slug='', author_id=0):
|
||||
author_query = ''
|
||||
@query.field("get_author")
|
||||
async def get_author(_, _info, slug="", author_id=0):
|
||||
author_query = ""
|
||||
author = None
|
||||
author_dict = None
|
||||
try:
|
||||
# lookup for cached author
|
||||
author_query = select(Author).filter(or_(Author.slug == slug, Author.id == author_id))
|
||||
author_query = select(Author).filter(
|
||||
or_(Author.slug == slug, Author.id == author_id)
|
||||
)
|
||||
[found_author] = local_session().execute(author_query).first()
|
||||
logger.debug(found_author)
|
||||
if found_author:
|
||||
logger.debug(f'found author id: {found_author.id}')
|
||||
logger.debug(f"found author id: {found_author.id}")
|
||||
author_id = found_author.id if found_author.id else author_id
|
||||
if author_id:
|
||||
cached_result = await redis.execute('GET', f'author:{author_id}')
|
||||
cached_result = await redis.execute("GET", f"author:{author_id}")
|
||||
author_dict = json.loads(cached_result) if cached_result else None
|
||||
|
||||
# update stat from db
|
||||
if not author_dict or not author_dict.get('stat'):
|
||||
if not author_dict or not author_dict.get("stat"):
|
||||
result = get_with_stat(author_query)
|
||||
if not result:
|
||||
raise ValueError('Author not found')
|
||||
raise ValueError("Author not found")
|
||||
[author] = result
|
||||
# use found author
|
||||
if isinstance(author, Author):
|
||||
logger.debug(f'update @{author.slug} with id {author.id}')
|
||||
logger.debug(f"update @{author.slug} with id {author.id}")
|
||||
author_dict = author.dict()
|
||||
await cache_author(author_dict)
|
||||
except ValueError:
|
||||
pass
|
||||
except Exception as exc:
|
||||
import traceback
|
||||
logger.error(f'{exc}:\n{traceback.format_exc()}')
|
||||
|
||||
logger.error(f"{exc}:\n{traceback.format_exc()}")
|
||||
return author_dict
|
||||
|
||||
|
||||
async def get_author_by_user_id(user_id: str):
|
||||
logger.info(f'getting author id for {user_id}')
|
||||
redis_key = f'user:{user_id}'
|
||||
logger.info(f"getting author id for {user_id}")
|
||||
redis_key = f"user:{user_id}"
|
||||
author = None
|
||||
try:
|
||||
res = await redis.execute('GET', redis_key)
|
||||
res = await redis.execute("GET", redis_key)
|
||||
if isinstance(res, str):
|
||||
author = json.loads(res)
|
||||
author_id = author.get('id')
|
||||
author_slug = author.get('slug')
|
||||
author_id = author.get("id")
|
||||
author_slug = author.get("slug")
|
||||
if author_id:
|
||||
logger.debug(f'got author @{author_slug} #{author_id} cached')
|
||||
logger.debug(f"got author @{author_slug} #{author_id} cached")
|
||||
return author
|
||||
|
||||
author_query = select(Author).filter(Author.user == user_id)
|
||||
@@ -110,41 +113,41 @@ async def get_author_by_user_id(user_id: str):
|
||||
return author
|
||||
|
||||
|
||||
@query.field('get_author_id')
|
||||
@query.field("get_author_id")
|
||||
async def get_author_id(_, _info, user: str):
|
||||
return await get_author_by_user_id(user)
|
||||
|
||||
|
||||
@query.field('load_authors_by')
|
||||
@query.field("load_authors_by")
|
||||
def load_authors_by(_, _info, by, limit, offset):
|
||||
cache_key = f'{json.dumps(by)}_{limit}_{offset}'
|
||||
cache_key = f"{json.dumps(by)}_{limit}_{offset}"
|
||||
|
||||
@cache_region.cache_on_arguments(cache_key)
|
||||
def _load_authors_by():
|
||||
logger.debug(f'loading authors by {by}')
|
||||
logger.debug(f"loading authors by {by}")
|
||||
q = select(Author)
|
||||
if by.get('slug'):
|
||||
if by.get("slug"):
|
||||
q = q.filter(Author.slug.ilike(f"%{by['slug']}%"))
|
||||
elif by.get('name'):
|
||||
elif by.get("name"):
|
||||
q = q.filter(Author.name.ilike(f"%{by['name']}%"))
|
||||
elif by.get('topic'):
|
||||
elif by.get("topic"):
|
||||
q = (
|
||||
q.join(ShoutAuthor)
|
||||
.join(ShoutTopic)
|
||||
.join(Topic)
|
||||
.where(Topic.slug == str(by['topic']))
|
||||
.where(Topic.slug == str(by["topic"]))
|
||||
)
|
||||
|
||||
if by.get('last_seen'): # in unix time
|
||||
before = int(time.time()) - by['last_seen']
|
||||
if by.get("last_seen"): # in unix time
|
||||
before = int(time.time()) - by["last_seen"]
|
||||
q = q.filter(Author.last_seen > before)
|
||||
elif by.get('created_at'): # in unix time
|
||||
before = int(time.time()) - by['created_at']
|
||||
elif by.get("created_at"): # in unix time
|
||||
before = int(time.time()) - by["created_at"]
|
||||
q = q.filter(Author.created_at > before)
|
||||
|
||||
order = by.get('order')
|
||||
if order in ['likes', 'shouts', 'followers']:
|
||||
q = q.order_by(desc(text(f'{order}_stat')))
|
||||
order = by.get("order")
|
||||
if order in ["likes", "shouts", "followers"]:
|
||||
q = q.order_by(desc(text(f"{order}_stat")))
|
||||
|
||||
# q = q.distinct()
|
||||
q = q.limit(limit).offset(offset)
|
||||
@@ -156,8 +159,8 @@ def load_authors_by(_, _info, by, limit, offset):
|
||||
return _load_authors_by()
|
||||
|
||||
|
||||
@query.field('get_author_follows')
|
||||
async def get_author_follows(_, _info, slug='', user=None, author_id=0):
|
||||
@query.field("get_author_follows")
|
||||
async def get_author_follows(_, _info, slug="", user=None, author_id=0):
|
||||
try:
|
||||
author_query = select(Author)
|
||||
if user:
|
||||
@@ -167,7 +170,7 @@ async def get_author_follows(_, _info, slug='', user=None, author_id=0):
|
||||
elif author_id:
|
||||
author_query = author_query.filter(Author.id == author_id)
|
||||
else:
|
||||
raise ValueError('One of slug, user, or author_id must be provided')
|
||||
raise ValueError("One of slug, user, or author_id must be provided")
|
||||
[result] = local_session().execute(author_query)
|
||||
if len(result) > 0:
|
||||
# logger.debug(result)
|
||||
@@ -176,19 +179,21 @@ async def get_author_follows(_, _info, slug='', user=None, author_id=0):
|
||||
if author and isinstance(author, Author):
|
||||
# logger.debug(author.dict())
|
||||
author_id = author.id
|
||||
rkey = f'author:{author_id}:follows-authors'
|
||||
logger.debug(f'getting {author_id} follows authors')
|
||||
cached = await redis.execute('GET', rkey)
|
||||
rkey = f"author:{author_id}:follows-authors"
|
||||
logger.debug(f"getting {author_id} follows authors")
|
||||
cached = await redis.execute("GET", rkey)
|
||||
authors = []
|
||||
if not cached:
|
||||
authors = author_follows_authors(author_id)
|
||||
prepared = [author.dict() for author in authors]
|
||||
await redis.execute('SET', rkey, json.dumps(prepared, cls=CustomJSONEncoder))
|
||||
await redis.execute(
|
||||
"SET", rkey, json.dumps(prepared, cls=CustomJSONEncoder)
|
||||
)
|
||||
elif isinstance(cached, str):
|
||||
authors = json.loads(cached)
|
||||
|
||||
rkey = f'author:{author_id}:follows-topics'
|
||||
cached = await redis.execute('GET', rkey)
|
||||
rkey = f"author:{author_id}:follows-topics"
|
||||
cached = await redis.execute("GET", rkey)
|
||||
topics = []
|
||||
if cached and isinstance(cached, str):
|
||||
topics = json.loads(cached)
|
||||
@@ -196,24 +201,24 @@ async def get_author_follows(_, _info, slug='', user=None, author_id=0):
|
||||
topics = author_follows_topics(author_id)
|
||||
prepared = [topic.dict() for topic in topics]
|
||||
await redis.execute(
|
||||
'SET', rkey, json.dumps(prepared, cls=CustomJSONEncoder)
|
||||
"SET", rkey, json.dumps(prepared, cls=CustomJSONEncoder)
|
||||
)
|
||||
return {
|
||||
'topics': topics,
|
||||
'authors': authors,
|
||||
'communities': [
|
||||
{'id': 1, 'name': 'Дискурс', 'slug': 'discours', 'pic': ''}
|
||||
"topics": topics,
|
||||
"authors": authors,
|
||||
"communities": [
|
||||
{"id": 1, "name": "Дискурс", "slug": "discours", "pic": ""}
|
||||
],
|
||||
}
|
||||
except Exception:
|
||||
import traceback
|
||||
|
||||
traceback.print_exc()
|
||||
return {'error': 'Author not found'}
|
||||
return {"error": "Author not found"}
|
||||
|
||||
|
||||
@query.field('get_author_follows_topics')
|
||||
async def get_author_follows_topics(_, _info, slug='', user=None, author_id=None):
|
||||
@query.field("get_author_follows_topics")
|
||||
async def get_author_follows_topics(_, _info, slug="", user=None, author_id=None):
|
||||
with local_session() as session:
|
||||
if user or slug:
|
||||
author_id_result = (
|
||||
@@ -223,10 +228,10 @@ async def get_author_follows_topics(_, _info, slug='', user=None, author_id=None
|
||||
)
|
||||
author_id = author_id_result[0] if author_id_result else None
|
||||
if not author_id:
|
||||
raise ValueError('Author not found')
|
||||
logger.debug(f'getting {author_id} follows topics')
|
||||
rkey = f'author:{author_id}:follows-topics'
|
||||
cached = await redis.execute('GET', rkey)
|
||||
raise ValueError("Author not found")
|
||||
logger.debug(f"getting {author_id} follows topics")
|
||||
rkey = f"author:{author_id}:follows-topics"
|
||||
cached = await redis.execute("GET", rkey)
|
||||
topics = []
|
||||
if isinstance(cached, str):
|
||||
topics = json.loads(cached)
|
||||
@@ -234,13 +239,13 @@ async def get_author_follows_topics(_, _info, slug='', user=None, author_id=None
|
||||
topics = author_follows_topics(author_id)
|
||||
prepared = [topic.dict() for topic in topics]
|
||||
await redis.execute(
|
||||
'SET', rkey, json.dumps(prepared, cls=CustomJSONEncoder)
|
||||
"SET", rkey, json.dumps(prepared, cls=CustomJSONEncoder)
|
||||
)
|
||||
return topics
|
||||
|
||||
|
||||
@query.field('get_author_follows_authors')
|
||||
async def get_author_follows_authors(_, _info, slug='', user=None, author_id=None):
|
||||
@query.field("get_author_follows_authors")
|
||||
async def get_author_follows_authors(_, _info, slug="", user=None, author_id=None):
|
||||
with local_session() as session:
|
||||
if user or slug:
|
||||
author_id_result = (
|
||||
@@ -250,9 +255,9 @@ async def get_author_follows_authors(_, _info, slug='', user=None, author_id=Non
|
||||
)
|
||||
author_id = author_id_result[0] if author_id_result else None
|
||||
if author_id:
|
||||
logger.debug(f'getting {author_id} follows authors')
|
||||
rkey = f'author:{author_id}:follows-authors'
|
||||
cached = await redis.execute('GET', rkey)
|
||||
logger.debug(f"getting {author_id} follows authors")
|
||||
rkey = f"author:{author_id}:follows-authors"
|
||||
cached = await redis.execute("GET", rkey)
|
||||
authors = []
|
||||
if isinstance(cached, str):
|
||||
authors = json.loads(cached)
|
||||
@@ -260,14 +265,14 @@ async def get_author_follows_authors(_, _info, slug='', user=None, author_id=Non
|
||||
authors = author_follows_authors(author_id)
|
||||
prepared = [author.dict() for author in authors]
|
||||
await redis.execute(
|
||||
'SET', rkey, json.dumps(prepared, cls=CustomJSONEncoder)
|
||||
"SET", rkey, json.dumps(prepared, cls=CustomJSONEncoder)
|
||||
)
|
||||
return authors
|
||||
else:
|
||||
raise ValueError('Author not found')
|
||||
raise ValueError("Author not found")
|
||||
|
||||
|
||||
def create_author(user_id: str, slug: str, name: str = ''):
|
||||
def create_author(user_id: str, slug: str, name: str = ""):
|
||||
with local_session() as session:
|
||||
try:
|
||||
author = None
|
||||
@@ -279,14 +284,14 @@ def create_author(user_id: str, slug: str, name: str = ''):
|
||||
new_author = Author(user=user_id, slug=slug, name=name)
|
||||
session.add(new_author)
|
||||
session.commit()
|
||||
logger.info(f'author created by webhook {new_author.dict()}')
|
||||
logger.info(f"author created by webhook {new_author.dict()}")
|
||||
except Exception as exc:
|
||||
logger.debug(exc)
|
||||
|
||||
|
||||
@query.field('get_author_followers')
|
||||
@query.field("get_author_followers")
|
||||
async def get_author_followers(_, _info, slug: str):
|
||||
logger.debug(f'getting followers for @{slug}')
|
||||
logger.debug(f"getting followers for @{slug}")
|
||||
try:
|
||||
author_alias = aliased(Author)
|
||||
author_query = select(author_alias).filter(author_alias.slug == slug)
|
||||
@@ -294,9 +299,9 @@ async def get_author_followers(_, _info, slug: str):
|
||||
if result:
|
||||
[author] = result
|
||||
author_id = author.id
|
||||
cached = await redis.execute('GET', f'author:{author_id}:followers')
|
||||
cached = await redis.execute("GET", f"author:{author_id}:followers")
|
||||
if not cached:
|
||||
author_follower_alias = aliased(AuthorFollower, name='af')
|
||||
author_follower_alias = aliased(AuthorFollower, name="af")
|
||||
q = select(Author).join(
|
||||
author_follower_alias,
|
||||
and_(
|
||||
@@ -308,10 +313,10 @@ async def get_author_followers(_, _info, slug: str):
|
||||
if isinstance(results, list):
|
||||
for follower in results:
|
||||
await cache_follower(follower, author)
|
||||
logger.debug(f'@{slug} cache updated with {len(results)} followers')
|
||||
logger.debug(f"@{slug} cache updated with {len(results)} followers")
|
||||
return results
|
||||
else:
|
||||
logger.debug(f'@{slug} got followers cached')
|
||||
logger.debug(f"@{slug} got followers cached")
|
||||
if isinstance(cached, str):
|
||||
return json.loads(cached)
|
||||
except Exception as exc:
|
||||
@@ -322,7 +327,7 @@ async def get_author_followers(_, _info, slug: str):
|
||||
return []
|
||||
|
||||
|
||||
@query.field('search_authors')
|
||||
@query.field("search_authors")
|
||||
async def search_authors(_, _info, what: str):
|
||||
q = search(select(Author), what)
|
||||
return get_with_stat(q)
|
||||
|
@@ -6,10 +6,10 @@ from services.db import local_session
|
||||
from services.schema import mutation
|
||||
|
||||
|
||||
@mutation.field('accept_invite')
|
||||
@mutation.field("accept_invite")
|
||||
@login_required
|
||||
async def accept_invite(_, info, invite_id: int):
|
||||
user_id = info.context['user_id']
|
||||
user_id = info.context["user_id"]
|
||||
|
||||
# Check if the user exists
|
||||
with local_session() as session:
|
||||
@@ -30,19 +30,19 @@ async def accept_invite(_, info, invite_id: int):
|
||||
session.delete(invite)
|
||||
session.add(shout)
|
||||
session.commit()
|
||||
return {'success': True, 'message': 'Invite accepted'}
|
||||
return {"success": True, "message": "Invite accepted"}
|
||||
else:
|
||||
return {'error': 'Shout not found'}
|
||||
return {"error": "Shout not found"}
|
||||
else:
|
||||
return {'error': 'Invalid invite or already accepted/rejected'}
|
||||
return {"error": "Invalid invite or already accepted/rejected"}
|
||||
else:
|
||||
return {'error': 'User not found'}
|
||||
return {"error": "User not found"}
|
||||
|
||||
|
||||
@mutation.field('reject_invite')
|
||||
@mutation.field("reject_invite")
|
||||
@login_required
|
||||
async def reject_invite(_, info, invite_id: int):
|
||||
user_id = info.context['user_id']
|
||||
user_id = info.context["user_id"]
|
||||
|
||||
# Check if the user exists
|
||||
with local_session() as session:
|
||||
@@ -58,17 +58,17 @@ async def reject_invite(_, info, invite_id: int):
|
||||
# Delete the invite
|
||||
session.delete(invite)
|
||||
session.commit()
|
||||
return {'success': True, 'message': 'Invite rejected'}
|
||||
return {"success": True, "message": "Invite rejected"}
|
||||
else:
|
||||
return {'error': 'Invalid invite or already accepted/rejected'}
|
||||
return {"error": "Invalid invite or already accepted/rejected"}
|
||||
else:
|
||||
return {'error': 'User not found'}
|
||||
return {"error": "User not found"}
|
||||
|
||||
|
||||
@mutation.field('create_invite')
|
||||
@mutation.field("create_invite")
|
||||
@login_required
|
||||
async def create_invite(_, info, slug: str = '', author_id: int = 0):
|
||||
user_id = info.context['user_id']
|
||||
async def create_invite(_, info, slug: str = "", author_id: int = 0):
|
||||
user_id = info.context["user_id"]
|
||||
|
||||
# Check if the inviter is the owner of the shout
|
||||
with local_session() as session:
|
||||
@@ -90,7 +90,7 @@ async def create_invite(_, info, slug: str = '', author_id: int = 0):
|
||||
.first()
|
||||
)
|
||||
if existing_invite:
|
||||
return {'error': 'Invite already sent'}
|
||||
return {"error": "Invite already sent"}
|
||||
|
||||
# Create a new invite
|
||||
new_invite = Invite(
|
||||
@@ -102,17 +102,17 @@ async def create_invite(_, info, slug: str = '', author_id: int = 0):
|
||||
session.add(new_invite)
|
||||
session.commit()
|
||||
|
||||
return {'error': None, 'invite': new_invite}
|
||||
return {"error": None, "invite": new_invite}
|
||||
else:
|
||||
return {'error': 'Invalid author'}
|
||||
return {"error": "Invalid author"}
|
||||
else:
|
||||
return {'error': 'Access denied'}
|
||||
return {"error": "Access denied"}
|
||||
|
||||
|
||||
@mutation.field('remove_author')
|
||||
@mutation.field("remove_author")
|
||||
@login_required
|
||||
async def remove_author(_, info, slug: str = '', author_id: int = 0):
|
||||
user_id = info.context['user_id']
|
||||
async def remove_author(_, info, slug: str = "", author_id: int = 0):
|
||||
user_id = info.context["user_id"]
|
||||
with local_session() as session:
|
||||
author = session.query(Author).filter(Author.user == user_id).first()
|
||||
if author:
|
||||
@@ -124,13 +124,13 @@ async def remove_author(_, info, slug: str = '', author_id: int = 0):
|
||||
]
|
||||
session.commit()
|
||||
return {}
|
||||
return {'error': 'Access denied'}
|
||||
return {"error": "Access denied"}
|
||||
|
||||
|
||||
@mutation.field('remove_invite')
|
||||
@mutation.field("remove_invite")
|
||||
@login_required
|
||||
async def remove_invite(_, info, invite_id: int):
|
||||
user_id = info.context['user_id']
|
||||
user_id = info.context["user_id"]
|
||||
|
||||
# Check if the user exists
|
||||
with local_session() as session:
|
||||
@@ -148,6 +148,6 @@ async def remove_invite(_, info, invite_id: int):
|
||||
session.commit()
|
||||
return {}
|
||||
else:
|
||||
return {'error': 'Invalid invite or already accepted/rejected'}
|
||||
return {"error": "Invalid invite or already accepted/rejected"}
|
||||
else:
|
||||
return {'error': 'Author not found'}
|
||||
return {"error": "Author not found"}
|
||||
|
@@ -14,12 +14,12 @@ def add_community_stat_columns(q):
|
||||
shout_community_aliased = aliased(ShoutCommunity)
|
||||
|
||||
q = q.outerjoin(shout_community_aliased).add_columns(
|
||||
func.count(distinct(shout_community_aliased.shout)).label('shouts_stat')
|
||||
func.count(distinct(shout_community_aliased.shout)).label("shouts_stat")
|
||||
)
|
||||
q = q.outerjoin(
|
||||
community_followers, community_followers.author == Author.id
|
||||
).add_columns(
|
||||
func.count(distinct(community_followers.follower)).label('followers_stat')
|
||||
func.count(distinct(community_followers.follower)).label("followers_stat")
|
||||
)
|
||||
|
||||
q = q.group_by(Author.id)
|
||||
@@ -32,8 +32,8 @@ def get_communities_from_query(q):
|
||||
with local_session() as session:
|
||||
for [c, shouts_stat, followers_stat] in session.execute(q):
|
||||
c.stat = {
|
||||
'shouts': shouts_stat,
|
||||
'followers': followers_stat,
|
||||
"shouts": shouts_stat,
|
||||
"followers": followers_stat,
|
||||
# "commented": commented_stat,
|
||||
}
|
||||
ccc.append(c)
|
||||
@@ -72,7 +72,7 @@ def community_unfollow(follower_id, slug):
|
||||
return False
|
||||
|
||||
|
||||
@query.field('get_communities_all')
|
||||
@query.field("get_communities_all")
|
||||
async def get_communities_all(_, _info):
|
||||
q = select(Author)
|
||||
q = add_community_stat_columns(q)
|
||||
@@ -80,7 +80,7 @@ async def get_communities_all(_, _info):
|
||||
return get_communities_from_query(q)
|
||||
|
||||
|
||||
@query.field('get_community')
|
||||
@query.field("get_community")
|
||||
async def get_community(_, _info, slug: str):
|
||||
q = select(Community).where(Community.slug == slug)
|
||||
q = add_community_stat_columns(q)
|
||||
|
@@ -19,13 +19,13 @@ from services.schema import mutation, query
|
||||
from services.search import search_service
|
||||
|
||||
|
||||
@query.field('get_my_shout')
|
||||
@query.field("get_my_shout")
|
||||
@login_required
|
||||
async def get_my_shout(_, info, shout_id: int):
|
||||
with local_session() as session:
|
||||
user_id = info.context.get('user_id', '')
|
||||
user_id = info.context.get("user_id", "")
|
||||
if not user_id:
|
||||
return {'error': 'unauthorized', 'shout': None}
|
||||
return {"error": "unauthorized", "shout": None}
|
||||
shout = (
|
||||
session.query(Shout)
|
||||
.filter(Shout.id == shout_id)
|
||||
@@ -34,23 +34,23 @@ async def get_my_shout(_, info, shout_id: int):
|
||||
.first()
|
||||
)
|
||||
if not shout:
|
||||
return {'error': 'no shout found', 'shout': None}
|
||||
return {"error": "no shout found", "shout": None}
|
||||
if not bool(shout.published_at):
|
||||
author = session.query(Author).filter(Author.user == user_id).first()
|
||||
if not author:
|
||||
return {'error': 'no author found', 'shout': None}
|
||||
roles = info.context.get('roles', [])
|
||||
if 'editor' not in roles and not filter(
|
||||
return {"error": "no author found", "shout": None}
|
||||
roles = info.context.get("roles", [])
|
||||
if "editor" not in roles and not filter(
|
||||
lambda x: x.id == author.id, [x for x in shout.authors]
|
||||
):
|
||||
return {'error': 'forbidden', 'shout': None}
|
||||
return {'error': None, 'shout': shout}
|
||||
return {"error": "forbidden", "shout": None}
|
||||
return {"error": None, "shout": shout}
|
||||
|
||||
|
||||
@query.field('get_shouts_drafts')
|
||||
@query.field("get_shouts_drafts")
|
||||
@login_required
|
||||
async def get_shouts_drafts(_, info):
|
||||
user_id = info.context.get('user_id')
|
||||
user_id = info.context.get("user_id")
|
||||
shouts = []
|
||||
with local_session() as session:
|
||||
author = session.query(Author).filter(Author.user == user_id).first()
|
||||
@@ -67,44 +67,44 @@ async def get_shouts_drafts(_, info):
|
||||
return shouts
|
||||
|
||||
|
||||
@mutation.field('create_shout')
|
||||
@mutation.field("create_shout")
|
||||
@login_required
|
||||
async def create_shout(_, info, inp):
|
||||
user_id = info.context.get('user_id')
|
||||
user_id = info.context.get("user_id")
|
||||
if user_id:
|
||||
with local_session() as session:
|
||||
author = session.query(Author).filter(Author.user == user_id).first()
|
||||
if isinstance(author, Author):
|
||||
current_time = int(time.time())
|
||||
slug = inp.get('slug') or f'draft-{current_time}'
|
||||
slug = inp.get("slug") or f"draft-{current_time}"
|
||||
shout_dict = {
|
||||
'title': inp.get('title', ''),
|
||||
'subtitle': inp.get('subtitle', ''),
|
||||
'lead': inp.get('lead', ''),
|
||||
'description': inp.get('description', ''),
|
||||
'body': inp.get('body', ''),
|
||||
'layout': inp.get('layout', 'article'),
|
||||
'created_by': author.id,
|
||||
'authors': [],
|
||||
'slug': slug,
|
||||
'topics': inp.get('topics', []),
|
||||
'published_at': None,
|
||||
'created_at': current_time, # Set created_at as Unix timestamp
|
||||
"title": inp.get("title", ""),
|
||||
"subtitle": inp.get("subtitle", ""),
|
||||
"lead": inp.get("lead", ""),
|
||||
"description": inp.get("description", ""),
|
||||
"body": inp.get("body", ""),
|
||||
"layout": inp.get("layout", "article"),
|
||||
"created_by": author.id,
|
||||
"authors": [],
|
||||
"slug": slug,
|
||||
"topics": inp.get("topics", []),
|
||||
"published_at": None,
|
||||
"created_at": current_time, # Set created_at as Unix timestamp
|
||||
}
|
||||
same_slug_shout = (
|
||||
session.query(Shout)
|
||||
.filter(Shout.slug == shout_dict.get('slug'))
|
||||
.filter(Shout.slug == shout_dict.get("slug"))
|
||||
.first()
|
||||
)
|
||||
c = 1
|
||||
while same_slug_shout is not None:
|
||||
same_slug_shout = (
|
||||
session.query(Shout)
|
||||
.filter(Shout.slug == shout_dict.get('slug'))
|
||||
.filter(Shout.slug == shout_dict.get("slug"))
|
||||
.first()
|
||||
)
|
||||
c += 1
|
||||
shout_dict['slug'] += f'-{c}'
|
||||
shout_dict["slug"] += f"-{c}"
|
||||
new_shout = Shout(**shout_dict)
|
||||
session.add(new_shout)
|
||||
session.commit()
|
||||
@@ -117,7 +117,7 @@ async def create_shout(_, info, inp):
|
||||
|
||||
topics = (
|
||||
session.query(Topic)
|
||||
.filter(Topic.slug.in_(inp.get('topics', [])))
|
||||
.filter(Topic.slug.in_(inp.get("topics", [])))
|
||||
.all()
|
||||
)
|
||||
for topic in topics:
|
||||
@@ -131,9 +131,9 @@ async def create_shout(_, info, inp):
|
||||
# notifier
|
||||
# await notify_shout(shout_dict, 'create')
|
||||
|
||||
return {'shout': shout}
|
||||
return {"shout": shout}
|
||||
|
||||
return {'error': 'cant create shout' if user_id else 'unauthorized'}
|
||||
return {"error": "cant create shout" if user_id else "unauthorized"}
|
||||
|
||||
|
||||
def patch_main_topic(session, main_topic, shout):
|
||||
@@ -170,16 +170,16 @@ def patch_main_topic(session, main_topic, shout):
|
||||
and new_main_topic
|
||||
and old_main_topic is not new_main_topic
|
||||
):
|
||||
ShoutTopic.update(old_main_topic, {'main': False})
|
||||
ShoutTopic.update(old_main_topic, {"main": False})
|
||||
session.add(old_main_topic)
|
||||
|
||||
ShoutTopic.update(new_main_topic, {'main': True})
|
||||
ShoutTopic.update(new_main_topic, {"main": True})
|
||||
session.add(new_main_topic)
|
||||
|
||||
|
||||
def patch_topics(session, shout, topics_input):
|
||||
new_topics_to_link = [
|
||||
Topic(**new_topic) for new_topic in topics_input if new_topic['id'] < 0
|
||||
Topic(**new_topic) for new_topic in topics_input if new_topic["id"] < 0
|
||||
]
|
||||
if new_topics_to_link:
|
||||
session.add_all(new_topics_to_link)
|
||||
@@ -190,12 +190,12 @@ def patch_topics(session, shout, topics_input):
|
||||
session.add(created_unlinked_topic)
|
||||
|
||||
existing_topics_input = [
|
||||
topic_input for topic_input in topics_input if topic_input.get('id', 0) > 0
|
||||
topic_input for topic_input in topics_input if topic_input.get("id", 0) > 0
|
||||
]
|
||||
existing_topic_to_link_ids = [
|
||||
existing_topic_input['id']
|
||||
existing_topic_input["id"]
|
||||
for existing_topic_input in existing_topics_input
|
||||
if existing_topic_input['id'] not in [topic.id for topic in shout.topics]
|
||||
if existing_topic_input["id"] not in [topic.id for topic in shout.topics]
|
||||
]
|
||||
|
||||
for existing_topic_to_link_id in existing_topic_to_link_ids:
|
||||
@@ -207,7 +207,7 @@ def patch_topics(session, shout, topics_input):
|
||||
topic_to_unlink_ids = [
|
||||
topic.id
|
||||
for topic in shout.topics
|
||||
if topic.id not in [topic_input['id'] for topic_input in existing_topics_input]
|
||||
if topic.id not in [topic_input["id"] for topic_input in existing_topics_input]
|
||||
]
|
||||
|
||||
session.query(ShoutTopic).filter(
|
||||
@@ -215,25 +215,25 @@ def patch_topics(session, shout, topics_input):
|
||||
).delete(synchronize_session=False)
|
||||
|
||||
|
||||
@mutation.field('update_shout')
|
||||
@mutation.field("update_shout")
|
||||
@login_required
|
||||
async def update_shout(_, info, shout_id: int, shout_input=None, publish=False):
|
||||
user_id = info.context.get('user_id')
|
||||
roles = info.context.get('roles', [])
|
||||
user_id = info.context.get("user_id")
|
||||
roles = info.context.get("roles", [])
|
||||
shout_input = shout_input or {}
|
||||
current_time = int(time.time())
|
||||
shout_id = shout_id or shout_input.get('id', shout_id)
|
||||
slug = shout_input.get('slug')
|
||||
shout_id = shout_id or shout_input.get("id", shout_id)
|
||||
slug = shout_input.get("slug")
|
||||
if not user_id:
|
||||
return {'error': 'unauthorized'}
|
||||
return {"error": "unauthorized"}
|
||||
try:
|
||||
with local_session() as session:
|
||||
author = session.query(Author).filter(Author.user == user_id).first()
|
||||
if author:
|
||||
logger.info(f'author for shout#{shout_id} detected {author.dict()}')
|
||||
logger.info(f"author for shout#{shout_id} detected {author.dict()}")
|
||||
shout_by_id = session.query(Shout).filter(Shout.id == shout_id).first()
|
||||
if not shout_by_id:
|
||||
return {'error': 'shout not found'}
|
||||
return {"error": "shout not found"}
|
||||
if slug != shout_by_id.slug:
|
||||
same_slug_shout = (
|
||||
session.query(Shout).filter(Shout.slug == slug).first()
|
||||
@@ -241,31 +241,31 @@ async def update_shout(_, info, shout_id: int, shout_input=None, publish=False):
|
||||
c = 1
|
||||
while same_slug_shout is not None:
|
||||
c += 1
|
||||
slug = f'{slug}-{c}'
|
||||
slug = f"{slug}-{c}"
|
||||
same_slug_shout = (
|
||||
session.query(Shout).filter(Shout.slug == slug).first()
|
||||
)
|
||||
shout_input['slug'] = slug
|
||||
shout_input["slug"] = slug
|
||||
|
||||
if (
|
||||
filter(
|
||||
lambda x: x.id == author.id, [x for x in shout_by_id.authors]
|
||||
)
|
||||
or 'editor' in roles
|
||||
or "editor" in roles
|
||||
):
|
||||
# topics patch
|
||||
topics_input = shout_input.get('topics')
|
||||
topics_input = shout_input.get("topics")
|
||||
if topics_input:
|
||||
patch_topics(session, shout_by_id, topics_input)
|
||||
del shout_input['topics']
|
||||
del shout_input["topics"]
|
||||
|
||||
# main topic
|
||||
main_topic = shout_input.get('main_topic')
|
||||
main_topic = shout_input.get("main_topic")
|
||||
if main_topic:
|
||||
patch_main_topic(session, main_topic, shout_by_id)
|
||||
|
||||
shout_input['updated_at'] = current_time
|
||||
shout_input['published_at'] = current_time if publish else None
|
||||
shout_input["updated_at"] = current_time
|
||||
shout_input["published_at"] = current_time if publish else None
|
||||
Shout.update(shout_by_id, shout_input)
|
||||
session.add(shout_by_id)
|
||||
session.commit()
|
||||
@@ -273,52 +273,52 @@ async def update_shout(_, info, shout_id: int, shout_input=None, publish=False):
|
||||
shout_dict = shout_by_id.dict()
|
||||
|
||||
if not publish:
|
||||
await notify_shout(shout_dict, 'update')
|
||||
await notify_shout(shout_dict, "update")
|
||||
else:
|
||||
await notify_shout(shout_dict, 'published')
|
||||
await notify_shout(shout_dict, "published")
|
||||
# search service indexing
|
||||
search_service.index(shout_by_id)
|
||||
|
||||
return {'shout': shout_dict, 'error': None}
|
||||
return {"shout": shout_dict, "error": None}
|
||||
else:
|
||||
return {'error': 'access denied', 'shout': None}
|
||||
return {"error": "access denied", "shout": None}
|
||||
|
||||
except Exception as exc:
|
||||
import traceback
|
||||
|
||||
traceback.print_exc()
|
||||
logger.error(exc)
|
||||
logger.error(f' cannot update with data: {shout_input}')
|
||||
logger.error(f" cannot update with data: {shout_input}")
|
||||
|
||||
return {'error': 'cant update shout'}
|
||||
return {"error": "cant update shout"}
|
||||
|
||||
|
||||
@mutation.field('delete_shout')
|
||||
@mutation.field("delete_shout")
|
||||
@login_required
|
||||
async def delete_shout(_, info, shout_id: int):
|
||||
user_id = info.context.get('user_id')
|
||||
roles = info.context.get('roles')
|
||||
user_id = info.context.get("user_id")
|
||||
roles = info.context.get("roles")
|
||||
if user_id:
|
||||
with local_session() as session:
|
||||
author = session.query(Author).filter(Author.user == user_id).first()
|
||||
shout = session.query(Shout).filter(Shout.id == shout_id).first()
|
||||
if not shout:
|
||||
return {'error': 'invalid shout id'}
|
||||
return {"error": "invalid shout id"}
|
||||
if author and shout:
|
||||
# NOTE: only owner and editor can mark the shout as deleted
|
||||
if shout.created_by == author.id or 'editor' in roles:
|
||||
if shout.created_by == author.id or "editor" in roles:
|
||||
for author_id in shout.authors:
|
||||
reactions_unfollow(author_id, shout_id)
|
||||
|
||||
shout_dict = shout.dict()
|
||||
shout_dict['deleted_at'] = int(time.time())
|
||||
shout_dict["deleted_at"] = int(time.time())
|
||||
Shout.update(shout, shout_dict)
|
||||
session.add(shout)
|
||||
session.commit()
|
||||
await notify_shout(shout_dict, 'delete')
|
||||
return {'error': None}
|
||||
await notify_shout(shout_dict, "delete")
|
||||
return {"error": None}
|
||||
else:
|
||||
return {'error': 'access denied'}
|
||||
return {"error": "access denied"}
|
||||
|
||||
|
||||
def handle_proposing(session, r, shout):
|
||||
@@ -350,7 +350,7 @@ def handle_proposing(session, r, shout):
|
||||
if proposal.quote:
|
||||
proposal_diff = get_diff(shout.body, proposal.quote)
|
||||
proposal_dict = proposal.dict()
|
||||
proposal_dict['quote'] = apply_diff(
|
||||
proposal_dict["quote"] = apply_diff(
|
||||
replied_reaction.quote, proposal_diff
|
||||
)
|
||||
Reaction.update(proposal, proposal_dict)
|
||||
@@ -358,7 +358,7 @@ def handle_proposing(session, r, shout):
|
||||
|
||||
# patch shout's body
|
||||
shout_dict = shout.dict()
|
||||
shout_dict['body'] = replied_reaction.quote
|
||||
shout_dict["body"] = replied_reaction.quote
|
||||
Shout.update(shout, shout_dict)
|
||||
session.add(shout)
|
||||
session.commit()
|
||||
|
@@ -21,111 +21,111 @@ from services.rediscache import redis
|
||||
from services.schema import mutation, query
|
||||
|
||||
|
||||
@mutation.field('follow')
|
||||
@mutation.field("follow")
|
||||
@login_required
|
||||
async def follow(_, info, what, slug):
|
||||
follows = []
|
||||
error = None
|
||||
user_id = info.context.get('user_id')
|
||||
user_id = info.context.get("user_id")
|
||||
if not user_id:
|
||||
return {'error': 'unauthorized'}
|
||||
return {"error": "unauthorized"}
|
||||
|
||||
follower = local_session().query(Author).filter(Author.user == user_id).first()
|
||||
if not follower:
|
||||
return {'error': 'cant find follower'}
|
||||
if what == 'AUTHOR':
|
||||
return {"error": "cant find follower"}
|
||||
if what == "AUTHOR":
|
||||
error = author_follow(follower.id, slug)
|
||||
if not error:
|
||||
author = local_session().query(Author).where(Author.slug == slug).first()
|
||||
if author:
|
||||
await notify_follower(follower.dict(), author.id, 'follow')
|
||||
await notify_follower(follower.dict(), author.id, "follow")
|
||||
|
||||
elif what == 'TOPIC':
|
||||
elif what == "TOPIC":
|
||||
error = topic_follow(follower.id, slug)
|
||||
|
||||
elif what == 'COMMUNITY':
|
||||
elif what == "COMMUNITY":
|
||||
# FIXME: when more communities
|
||||
follows = local_session().execute(select(Community))
|
||||
|
||||
elif what == 'SHOUT':
|
||||
elif what == "SHOUT":
|
||||
error = reactions_follow(follower.id, slug)
|
||||
|
||||
if error:
|
||||
return {'error': error}
|
||||
return {"error": error}
|
||||
|
||||
entity = what.lower()
|
||||
follows_str = await redis.execute('GET', f'author:{follower.id}:follows-{entity}s')
|
||||
follows_str = await redis.execute("GET", f"author:{follower.id}:follows-{entity}s")
|
||||
if follows_str:
|
||||
follows = json.loads(follows_str)
|
||||
return { f'{entity}s': follows }
|
||||
return {f"{entity}s": follows}
|
||||
|
||||
|
||||
@mutation.field('unfollow')
|
||||
@mutation.field("unfollow")
|
||||
@login_required
|
||||
async def unfollow(_, info, what, slug):
|
||||
follows = []
|
||||
error = None
|
||||
user_id = info.context.get('user_id')
|
||||
user_id = info.context.get("user_id")
|
||||
if not user_id:
|
||||
return {'error': 'unauthorized'}
|
||||
return {"error": "unauthorized"}
|
||||
follower = local_session().query(Author).filter(Author.user == user_id).first()
|
||||
if not follower:
|
||||
return {'error': 'follower profile is not found'}
|
||||
if what == 'AUTHOR':
|
||||
return {"error": "follower profile is not found"}
|
||||
if what == "AUTHOR":
|
||||
error = author_unfollow(follower.id, slug)
|
||||
# NOTE: after triggers should update cached stats
|
||||
if not error:
|
||||
logger.info(f'@{follower.slug} unfollowed @{slug}')
|
||||
logger.info(f"@{follower.slug} unfollowed @{slug}")
|
||||
author = local_session().query(Author).where(Author.slug == slug).first()
|
||||
if author:
|
||||
await notify_follower(follower.dict(), author.id, 'unfollow')
|
||||
await notify_follower(follower.dict(), author.id, "unfollow")
|
||||
|
||||
elif what == 'TOPIC':
|
||||
elif what == "TOPIC":
|
||||
error = topic_unfollow(follower.id, slug)
|
||||
|
||||
elif what == 'COMMUNITY':
|
||||
elif what == "COMMUNITY":
|
||||
follows = local_session().execute(select(Community))
|
||||
|
||||
elif what == 'SHOUT':
|
||||
elif what == "SHOUT":
|
||||
error = reactions_unfollow(follower.id, slug)
|
||||
|
||||
entity = what.lower()
|
||||
follows_str = await redis.execute('GET', f'author:{follower.id}:follows-{entity}s')
|
||||
follows_str = await redis.execute("GET", f"author:{follower.id}:follows-{entity}s")
|
||||
if follows_str:
|
||||
follows = json.loads(follows_str)
|
||||
return {'error': error, f'{entity}s': follows}
|
||||
return {"error": error, f"{entity}s": follows}
|
||||
|
||||
|
||||
async def get_follows_by_user_id(user_id: str):
|
||||
if not user_id:
|
||||
return {'error': 'unauthorized'}
|
||||
author = await redis.execute('GET', f'user:{user_id}')
|
||||
return {"error": "unauthorized"}
|
||||
author = await redis.execute("GET", f"user:{user_id}")
|
||||
if isinstance(author, str):
|
||||
author = json.loads(author)
|
||||
if not author:
|
||||
with local_session() as session:
|
||||
author = session.query(Author).filter(Author.user == user_id).first()
|
||||
if not author:
|
||||
return {'error': 'cant find author'}
|
||||
return {"error": "cant find author"}
|
||||
author = author.dict()
|
||||
last_seen = author.get('last_seen', 0) if isinstance(author, dict) else 0
|
||||
last_seen = author.get("last_seen", 0) if isinstance(author, dict) else 0
|
||||
follows = DEFAULT_FOLLOWS
|
||||
day_old = int(time.time()) - last_seen > 24 * 60 * 60
|
||||
if day_old:
|
||||
author_id = json.loads(str(author)).get('id')
|
||||
author_id = json.loads(str(author)).get("id")
|
||||
if author_id:
|
||||
topics = author_follows_topics(author_id)
|
||||
authors = author_follows_authors(author_id)
|
||||
follows = {
|
||||
'topics': topics,
|
||||
'authors': authors,
|
||||
'communities': [
|
||||
{'id': 1, 'name': 'Дискурс', 'slug': 'discours', 'pic': ''}
|
||||
"topics": topics,
|
||||
"authors": authors,
|
||||
"communities": [
|
||||
{"id": 1, "name": "Дискурс", "slug": "discours", "pic": ""}
|
||||
],
|
||||
}
|
||||
else:
|
||||
logger.debug(f'getting follows for {user_id} from redis')
|
||||
res = await redis.execute('GET', f'user:{user_id}:follows')
|
||||
logger.debug(f"getting follows for {user_id} from redis")
|
||||
res = await redis.execute("GET", f"user:{user_id}:follows")
|
||||
if isinstance(res, str):
|
||||
follows = json.loads(res)
|
||||
return follows
|
||||
@@ -139,7 +139,7 @@ def topic_follow(follower_id, slug):
|
||||
return None
|
||||
except UniqueViolation as error:
|
||||
logger.warn(error)
|
||||
return 'already followed'
|
||||
return "already followed"
|
||||
except Exception as exc:
|
||||
logger.error(exc)
|
||||
return exc
|
||||
@@ -160,7 +160,7 @@ def topic_unfollow(follower_id, slug):
|
||||
return None
|
||||
except UniqueViolation as error:
|
||||
logger.warn(error)
|
||||
return 'already unfollowed'
|
||||
return "already unfollowed"
|
||||
except Exception as ex:
|
||||
logger.debug(ex)
|
||||
return ex
|
||||
@@ -191,7 +191,7 @@ def reactions_follow(author_id, shout_id, auto=False):
|
||||
return None
|
||||
except UniqueViolation as error:
|
||||
logger.warn(error)
|
||||
return 'already followed'
|
||||
return "already followed"
|
||||
except Exception as exc:
|
||||
return exc
|
||||
|
||||
@@ -218,7 +218,7 @@ def reactions_unfollow(author_id, shout_id: int):
|
||||
return None
|
||||
except UniqueViolation as error:
|
||||
logger.warn(error)
|
||||
return 'already unfollowed'
|
||||
return "already unfollowed"
|
||||
except Exception as ex:
|
||||
import traceback
|
||||
|
||||
@@ -237,7 +237,7 @@ def author_follow(follower_id, slug):
|
||||
return None
|
||||
except UniqueViolation as error:
|
||||
logger.warn(error)
|
||||
return 'already followed'
|
||||
return "already followed"
|
||||
except Exception as exc:
|
||||
import traceback
|
||||
|
||||
@@ -263,12 +263,12 @@ def author_unfollow(follower_id, slug):
|
||||
return None
|
||||
except UniqueViolation as error:
|
||||
logger.warn(error)
|
||||
return 'already unfollowed'
|
||||
return "already unfollowed"
|
||||
except Exception as exc:
|
||||
return exc
|
||||
|
||||
|
||||
@query.field('get_topic_followers')
|
||||
@query.field("get_topic_followers")
|
||||
async def get_topic_followers(_, _info, slug: str, topic_id: int) -> List[Author]:
|
||||
q = select(Author)
|
||||
q = (
|
||||
@@ -279,9 +279,9 @@ async def get_topic_followers(_, _info, slug: str, topic_id: int) -> List[Author
|
||||
return get_with_stat(q)
|
||||
|
||||
|
||||
@query.field('get_shout_followers')
|
||||
@query.field("get_shout_followers")
|
||||
def get_shout_followers(
|
||||
_, _info, slug: str = '', shout_id: int | None = None
|
||||
_, _info, slug: str = "", shout_id: int | None = None
|
||||
) -> List[Author]:
|
||||
followers = []
|
||||
with local_session() as session:
|
||||
|
@@ -8,8 +8,12 @@ from sqlalchemy.orm import aliased
|
||||
from sqlalchemy.sql import not_
|
||||
|
||||
from orm.author import Author
|
||||
from orm.notification import (Notification, NotificationAction,
|
||||
NotificationEntity, NotificationSeen)
|
||||
from orm.notification import (
|
||||
Notification,
|
||||
NotificationAction,
|
||||
NotificationEntity,
|
||||
NotificationSeen,
|
||||
)
|
||||
from orm.shout import Shout
|
||||
from services.auth import login_required
|
||||
from services.db import local_session
|
||||
@@ -21,7 +25,7 @@ def query_notifications(
|
||||
author_id: int, after: int = 0
|
||||
) -> Tuple[int, int, List[Tuple[Notification, bool]]]:
|
||||
notification_seen_alias = aliased(NotificationSeen)
|
||||
q = select(Notification, notification_seen_alias.viewer.label('seen')).outerjoin(
|
||||
q = select(Notification, notification_seen_alias.viewer.label("seen")).outerjoin(
|
||||
NotificationSeen,
|
||||
and_(
|
||||
NotificationSeen.viewer == author_id,
|
||||
@@ -65,18 +69,18 @@ def query_notifications(
|
||||
|
||||
|
||||
def group_notification(
|
||||
thread, authors=None, shout=None, reactions=None, entity='follower', action='follow'
|
||||
thread, authors=None, shout=None, reactions=None, entity="follower", action="follow"
|
||||
):
|
||||
reactions = reactions or []
|
||||
authors = authors or []
|
||||
return {
|
||||
'thread': thread,
|
||||
'authors': authors,
|
||||
'updated_at': int(time.time()),
|
||||
'shout': shout,
|
||||
'reactions': reactions,
|
||||
'entity': entity,
|
||||
'action': action,
|
||||
"thread": thread,
|
||||
"authors": authors,
|
||||
"updated_at": int(time.time()),
|
||||
"shout": shout,
|
||||
"reactions": reactions,
|
||||
"entity": entity,
|
||||
"action": action,
|
||||
}
|
||||
|
||||
|
||||
@@ -121,9 +125,9 @@ def get_notifications_grouped(
|
||||
|
||||
if str(notification.entity) == NotificationEntity.SHOUT.value:
|
||||
shout = payload
|
||||
shout_id = shout.get('id')
|
||||
author_id = shout.get('created_by')
|
||||
thread_id = f'shout-{shout_id}'
|
||||
shout_id = shout.get("id")
|
||||
author_id = shout.get("created_by")
|
||||
thread_id = f"shout-{shout_id}"
|
||||
with local_session() as session:
|
||||
author = session.query(Author).filter(Author.id == author_id).first()
|
||||
shout = session.query(Shout).filter(Shout.id == shout_id).first()
|
||||
@@ -143,9 +147,9 @@ def get_notifications_grouped(
|
||||
elif str(notification.entity) == NotificationEntity.REACTION.value:
|
||||
reaction = payload
|
||||
if not isinstance(shout, dict):
|
||||
raise ValueError('reaction data is not consistent')
|
||||
shout_id = shout.get('shout')
|
||||
author_id = shout.get('created_by', 0)
|
||||
raise ValueError("reaction data is not consistent")
|
||||
shout_id = shout.get("shout")
|
||||
author_id = shout.get("created_by", 0)
|
||||
if shout_id and author_id:
|
||||
with local_session() as session:
|
||||
author = (
|
||||
@@ -155,18 +159,18 @@ def get_notifications_grouped(
|
||||
if shout and author:
|
||||
author = author.dict()
|
||||
shout = shout.dict()
|
||||
reply_id = reaction.get('reply_to')
|
||||
thread_id = f'shout-{shout_id}'
|
||||
if reply_id and reaction.get('kind', '').lower() == 'comment':
|
||||
thread_id += f'{reply_id}'
|
||||
reply_id = reaction.get("reply_to")
|
||||
thread_id = f"shout-{shout_id}"
|
||||
if reply_id and reaction.get("kind", "").lower() == "comment":
|
||||
thread_id += f"{reply_id}"
|
||||
existing_group = groups_by_thread.get(thread_id)
|
||||
if existing_group:
|
||||
existing_group['seen'] = False
|
||||
existing_group['authors'].append(author_id)
|
||||
existing_group['reactions'] = (
|
||||
existing_group['reactions'] or []
|
||||
existing_group["seen"] = False
|
||||
existing_group["authors"].append(author_id)
|
||||
existing_group["reactions"] = (
|
||||
existing_group["reactions"] or []
|
||||
)
|
||||
existing_group['reactions'].append(reaction)
|
||||
existing_group["reactions"].append(reaction)
|
||||
groups_by_thread[thread_id] = existing_group
|
||||
else:
|
||||
group = group_notification(
|
||||
@@ -181,18 +185,18 @@ def get_notifications_grouped(
|
||||
groups_by_thread[thread_id] = group
|
||||
groups_amount += 1
|
||||
|
||||
elif str(notification.entity) == 'follower':
|
||||
thread_id = 'followers'
|
||||
elif str(notification.entity) == "follower":
|
||||
thread_id = "followers"
|
||||
follower = json.loads(payload)
|
||||
group = groups_by_thread.get(thread_id)
|
||||
if group:
|
||||
if str(notification.action) == 'follow':
|
||||
group['authors'].append(follower)
|
||||
elif str(notification.action) == 'unfollow':
|
||||
follower_id = follower.get('id')
|
||||
for author in group['authors']:
|
||||
if author.get('id') == follower_id:
|
||||
group['authors'].remove(author)
|
||||
if str(notification.action) == "follow":
|
||||
group["authors"].append(follower)
|
||||
elif str(notification.action) == "unfollow":
|
||||
follower_id = follower.get("id")
|
||||
for author in group["authors"]:
|
||||
if author.get("id") == follower_id:
|
||||
group["authors"].remove(author)
|
||||
break
|
||||
else:
|
||||
group = group_notification(
|
||||
@@ -206,10 +210,10 @@ def get_notifications_grouped(
|
||||
return groups_by_thread, unread, total
|
||||
|
||||
|
||||
@query.field('load_notifications')
|
||||
@query.field("load_notifications")
|
||||
@login_required
|
||||
async def load_notifications(_, info, after: int, limit: int = 50, offset=0):
|
||||
author_id = info.context.get('author_id')
|
||||
author_id = info.context.get("author_id")
|
||||
error = None
|
||||
total = 0
|
||||
unread = 0
|
||||
@@ -224,17 +228,17 @@ async def load_notifications(_, info, after: int, limit: int = 50, offset=0):
|
||||
error = e
|
||||
logger.error(e)
|
||||
return {
|
||||
'notifications': notifications,
|
||||
'total': total,
|
||||
'unread': unread,
|
||||
'error': error,
|
||||
"notifications": notifications,
|
||||
"total": total,
|
||||
"unread": unread,
|
||||
"error": error,
|
||||
}
|
||||
|
||||
|
||||
@mutation.field('notification_mark_seen')
|
||||
@mutation.field("notification_mark_seen")
|
||||
@login_required
|
||||
async def notification_mark_seen(_, info, notification_id: int):
|
||||
author_id = info.context.get('author_id')
|
||||
author_id = info.context.get("author_id")
|
||||
if author_id:
|
||||
with local_session() as session:
|
||||
try:
|
||||
@@ -243,18 +247,18 @@ async def notification_mark_seen(_, info, notification_id: int):
|
||||
session.commit()
|
||||
except SQLAlchemyError as e:
|
||||
session.rollback()
|
||||
logger.error(f'seen mutation failed: {e}')
|
||||
return {'error': 'cant mark as read'}
|
||||
return {'error': None}
|
||||
logger.error(f"seen mutation failed: {e}")
|
||||
return {"error": "cant mark as read"}
|
||||
return {"error": None}
|
||||
|
||||
|
||||
@mutation.field('notifications_seen_after')
|
||||
@mutation.field("notifications_seen_after")
|
||||
@login_required
|
||||
async def notifications_seen_after(_, info, after: int):
|
||||
# TODO: use latest loaded notification_id as input offset parameter
|
||||
error = None
|
||||
try:
|
||||
author_id = info.context.get('author_id')
|
||||
author_id = info.context.get("author_id")
|
||||
if author_id:
|
||||
with local_session() as session:
|
||||
nnn = (
|
||||
@@ -271,24 +275,24 @@ async def notifications_seen_after(_, info, after: int):
|
||||
session.rollback()
|
||||
except Exception as e:
|
||||
print(e)
|
||||
error = 'cant mark as read'
|
||||
return {'error': error}
|
||||
error = "cant mark as read"
|
||||
return {"error": error}
|
||||
|
||||
|
||||
@mutation.field('notifications_seen_thread')
|
||||
@mutation.field("notifications_seen_thread")
|
||||
@login_required
|
||||
async def notifications_seen_thread(_, info, thread: str, after: int):
|
||||
error = None
|
||||
author_id = info.context.get('author_id')
|
||||
author_id = info.context.get("author_id")
|
||||
if author_id:
|
||||
[shout_id, reply_to_id] = thread.split(':')
|
||||
[shout_id, reply_to_id] = thread.split(":")
|
||||
with local_session() as session:
|
||||
# TODO: handle new follower and new shout notifications
|
||||
new_reaction_notifications = (
|
||||
session.query(Notification)
|
||||
.filter(
|
||||
Notification.action == 'create',
|
||||
Notification.entity == 'reaction',
|
||||
Notification.action == "create",
|
||||
Notification.entity == "reaction",
|
||||
Notification.created_at > after,
|
||||
)
|
||||
.all()
|
||||
@@ -296,8 +300,8 @@ async def notifications_seen_thread(_, info, thread: str, after: int):
|
||||
removed_reaction_notifications = (
|
||||
session.query(Notification)
|
||||
.filter(
|
||||
Notification.action == 'delete',
|
||||
Notification.entity == 'reaction',
|
||||
Notification.action == "delete",
|
||||
Notification.entity == "reaction",
|
||||
Notification.created_at > after,
|
||||
)
|
||||
.all()
|
||||
@@ -305,15 +309,15 @@ async def notifications_seen_thread(_, info, thread: str, after: int):
|
||||
exclude = set()
|
||||
for nr in removed_reaction_notifications:
|
||||
reaction = json.loads(str(nr.payload))
|
||||
reaction_id = reaction.get('id')
|
||||
reaction_id = reaction.get("id")
|
||||
exclude.add(reaction_id)
|
||||
for n in new_reaction_notifications:
|
||||
reaction = json.loads(str(n.payload))
|
||||
reaction_id = reaction.get('id')
|
||||
reaction_id = reaction.get("id")
|
||||
if (
|
||||
reaction_id not in exclude
|
||||
and reaction.get('shout') == shout_id
|
||||
and reaction.get('reply_to') == reply_to_id
|
||||
and reaction.get("shout") == shout_id
|
||||
and reaction.get("reply_to") == reply_to_id
|
||||
):
|
||||
try:
|
||||
ns = NotificationSeen(notification=n.id, viewer=author_id)
|
||||
@@ -323,5 +327,5 @@ async def notifications_seen_thread(_, info, thread: str, after: int):
|
||||
logger.warn(e)
|
||||
session.rollback()
|
||||
else:
|
||||
error = 'You are not logged in'
|
||||
return {'error': error}
|
||||
error = "You are not logged in"
|
||||
return {"error": error}
|
||||
|
@@ -9,10 +9,10 @@ from services.db import local_session
|
||||
from services.schema import mutation
|
||||
|
||||
|
||||
@mutation.field('rate_author')
|
||||
@mutation.field("rate_author")
|
||||
@login_required
|
||||
async def rate_author(_, info, rated_slug, value):
|
||||
user_id = info.context['user_id']
|
||||
user_id = info.context["user_id"]
|
||||
|
||||
with local_session() as session:
|
||||
rated_author = session.query(Author).filter(Author.slug == rated_slug).first()
|
||||
@@ -41,7 +41,7 @@ async def rate_author(_, info, rated_slug, value):
|
||||
session.add(rating)
|
||||
session.commit()
|
||||
except Exception as err:
|
||||
return {'error': err}
|
||||
return {"error": err}
|
||||
return {}
|
||||
|
||||
|
||||
@@ -129,7 +129,7 @@ def get_author_rating_shouts(session, author: Author) -> int:
|
||||
)
|
||||
),
|
||||
0,
|
||||
).label('shouts_rating')
|
||||
).label("shouts_rating")
|
||||
)
|
||||
.select_from(Reaction)
|
||||
.outerjoin(Shout, Shout.authors.any(id=author.id))
|
||||
@@ -159,7 +159,7 @@ def get_author_rating_comments(session, author: Author) -> int:
|
||||
)
|
||||
),
|
||||
0,
|
||||
).label('shouts_rating')
|
||||
).label("shouts_rating")
|
||||
)
|
||||
.select_from(Reaction)
|
||||
.outerjoin(
|
||||
@@ -185,7 +185,7 @@ def add_author_rating_columns(q, group_list):
|
||||
# old karma
|
||||
q = q.outerjoin(AuthorRating, AuthorRating.author == Author.id)
|
||||
q = q.add_columns(
|
||||
func.sum(case((AuthorRating.plus == true(), 1), else_=-1)).label('rating')
|
||||
func.sum(case((AuthorRating.plus == true(), 1), else_=-1)).label("rating")
|
||||
)
|
||||
|
||||
# by shouts rating
|
||||
@@ -201,7 +201,7 @@ def add_author_rating_columns(q, group_list):
|
||||
else_=0,
|
||||
)
|
||||
)
|
||||
).label('shouts_rating'),
|
||||
).label("shouts_rating"),
|
||||
)
|
||||
.select_from(shout_reaction)
|
||||
.outerjoin(Shout, Shout.authors.any(id=Author.id))
|
||||
@@ -235,7 +235,7 @@ def add_author_rating_columns(q, group_list):
|
||||
else_=0,
|
||||
)
|
||||
)
|
||||
).label('comments_rating'),
|
||||
).label("comments_rating"),
|
||||
)
|
||||
.select_from(reaction_2)
|
||||
.outerjoin(
|
||||
|
@@ -22,22 +22,22 @@ from services.viewed import ViewedStorage
|
||||
|
||||
def add_reaction_stat_columns(q, aliased_reaction):
|
||||
q = q.outerjoin(aliased_reaction).add_columns(
|
||||
func.sum(aliased_reaction.id).label('reacted_stat'),
|
||||
func.sum(aliased_reaction.id).label("reacted_stat"),
|
||||
func.sum(
|
||||
case((aliased_reaction.kind == str(ReactionKind.COMMENT.value), 1), else_=0)
|
||||
).label('comments_stat'),
|
||||
).label("comments_stat"),
|
||||
func.sum(
|
||||
case((aliased_reaction.kind == str(ReactionKind.LIKE.value), 1), else_=0)
|
||||
).label('likes_stat'),
|
||||
).label("likes_stat"),
|
||||
func.sum(
|
||||
case((aliased_reaction.kind == str(ReactionKind.DISLIKE.value), 1), else_=0)
|
||||
).label('dislikes_stat'),
|
||||
).label("dislikes_stat"),
|
||||
func.max(
|
||||
case(
|
||||
(aliased_reaction.kind != str(ReactionKind.COMMENT.value), None),
|
||||
else_=aliased_reaction.created_at,
|
||||
)
|
||||
).label('last_comment_stat'),
|
||||
).label("last_comment_stat"),
|
||||
)
|
||||
|
||||
return q
|
||||
@@ -101,7 +101,7 @@ def check_to_unfeature(session, rejecter_id, reaction):
|
||||
async def set_featured(session, shout_id):
|
||||
s = session.query(Shout).where(Shout.id == shout_id).first()
|
||||
s.featured_at = int(time.time())
|
||||
Shout.update(s, {'featured_at': int(time.time())})
|
||||
Shout.update(s, {"featured_at": int(time.time())})
|
||||
author = session.query(Author).filter(Author.id == s.created_by).first()
|
||||
if author:
|
||||
await add_user_role(str(author.user))
|
||||
@@ -111,7 +111,7 @@ async def set_featured(session, shout_id):
|
||||
|
||||
def set_unfeatured(session, shout_id):
|
||||
s = session.query(Shout).where(Shout.id == shout_id).first()
|
||||
Shout.update(s, {'featured_at': None})
|
||||
Shout.update(s, {"featured_at": None})
|
||||
session.add(s)
|
||||
session.commit()
|
||||
|
||||
@@ -128,7 +128,7 @@ async def _create_reaction(session, shout, author, reaction):
|
||||
|
||||
# collaborative editing
|
||||
if (
|
||||
rdict.get('reply_to')
|
||||
rdict.get("reply_to")
|
||||
and r.kind in PROPOSAL_REACTIONS
|
||||
and author.id in shout.authors
|
||||
):
|
||||
@@ -146,7 +146,7 @@ async def _create_reaction(session, shout, author, reaction):
|
||||
if r.kind == ReactionKind.LIKE.value:
|
||||
try:
|
||||
# reactions auto-following
|
||||
reactions_follow(author.id, reaction['shout'], True)
|
||||
reactions_follow(author.id, reaction["shout"], True)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -154,18 +154,18 @@ async def _create_reaction(session, shout, author, reaction):
|
||||
if r.kind == ReactionKind.COMMENT.value:
|
||||
await update_author_stat(author)
|
||||
|
||||
rdict['shout'] = shout.dict()
|
||||
rdict['created_by'] = author.id
|
||||
rdict['stat'] = {'commented': 0, 'reacted': 0, 'rating': 0}
|
||||
rdict["shout"] = shout.dict()
|
||||
rdict["created_by"] = author.id
|
||||
rdict["stat"] = {"commented": 0, "reacted": 0, "rating": 0}
|
||||
|
||||
# notifications call
|
||||
await notify_reaction(rdict, 'create')
|
||||
await notify_reaction(rdict, "create")
|
||||
|
||||
return rdict
|
||||
|
||||
|
||||
def prepare_new_rating(reaction: dict, shout_id: int, session, author: Author):
|
||||
kind = reaction.get('kind')
|
||||
kind = reaction.get("kind")
|
||||
opposite_kind = (
|
||||
ReactionKind.DISLIKE.value if is_positive(kind) else ReactionKind.LIKE.value
|
||||
)
|
||||
@@ -177,7 +177,7 @@ def prepare_new_rating(reaction: dict, shout_id: int, session, author: Author):
|
||||
Reaction.kind.in_(RATING_REACTIONS),
|
||||
)
|
||||
)
|
||||
reply_to = reaction.get('reply_to')
|
||||
reply_to = reaction.get("reply_to")
|
||||
if reply_to and isinstance(reply_to, int):
|
||||
q = q.filter(Reaction.reply_to == reply_to)
|
||||
rating_reactions = session.execute(q).all()
|
||||
@@ -190,41 +190,43 @@ def prepare_new_rating(reaction: dict, shout_id: int, session, author: Author):
|
||||
rating_reactions,
|
||||
)
|
||||
if same_rating:
|
||||
return {'error': "You can't rate the same thing twice"}
|
||||
return {"error": "You can't rate the same thing twice"}
|
||||
elif opposite_rating:
|
||||
return {'error': 'Remove opposite vote first'}
|
||||
return {"error": "Remove opposite vote first"}
|
||||
elif filter(lambda r: r.created_by == author.id, rating_reactions):
|
||||
return {'error': "You can't rate your own thing"}
|
||||
return {"error": "You can't rate your own thing"}
|
||||
return
|
||||
|
||||
|
||||
@mutation.field('create_reaction')
|
||||
@mutation.field("create_reaction")
|
||||
@login_required
|
||||
async def create_reaction(_, info, reaction):
|
||||
logger.debug(f'{info.context} for {reaction}')
|
||||
user_id = info.context.get('user_id')
|
||||
shout_id = reaction.get('shout')
|
||||
logger.debug(f"{info.context} for {reaction}")
|
||||
user_id = info.context.get("user_id")
|
||||
shout_id = reaction.get("shout")
|
||||
|
||||
if not shout_id:
|
||||
return {'error': 'Shout ID is required to create a reaction.'}
|
||||
return {"error": "Shout ID is required to create a reaction."}
|
||||
|
||||
try:
|
||||
with local_session() as session:
|
||||
shout = session.query(Shout).filter(Shout.id == shout_id).first()
|
||||
author = session.query(Author).filter(Author.user == user_id).first()
|
||||
if shout and author:
|
||||
reaction['created_by'] = author.id
|
||||
kind = reaction.get('kind')
|
||||
reaction["created_by"] = author.id
|
||||
kind = reaction.get("kind")
|
||||
shout_id = shout.id
|
||||
|
||||
if not kind and isinstance(reaction.get('body'), str):
|
||||
if not kind and isinstance(reaction.get("body"), str):
|
||||
kind = ReactionKind.COMMENT.value
|
||||
|
||||
if not kind:
|
||||
return {'error': 'cannot create reaction without a kind'}
|
||||
return {"error": "cannot create reaction without a kind"}
|
||||
|
||||
if kind in RATING_REACTIONS:
|
||||
error_result = prepare_new_rating(reaction, shout_id, session, author)
|
||||
error_result = prepare_new_rating(
|
||||
reaction, shout_id, session, author
|
||||
)
|
||||
if error_result:
|
||||
return error_result
|
||||
|
||||
@@ -232,25 +234,25 @@ async def create_reaction(_, info, reaction):
|
||||
|
||||
# TODO: call recount ratings periodically
|
||||
|
||||
return {'reaction': rdict}
|
||||
return {"reaction": rdict}
|
||||
except Exception as e:
|
||||
import traceback
|
||||
|
||||
traceback.print_exc()
|
||||
logger.error(f'{type(e).__name__}: {e}')
|
||||
logger.error(f"{type(e).__name__}: {e}")
|
||||
|
||||
return {'error': 'Cannot create reaction.'}
|
||||
return {"error": "Cannot create reaction."}
|
||||
|
||||
|
||||
@mutation.field('update_reaction')
|
||||
@mutation.field("update_reaction")
|
||||
@login_required
|
||||
async def update_reaction(_, info, reaction):
|
||||
logger.debug(f'{info.context} for {reaction}')
|
||||
user_id = info.context.get('user_id')
|
||||
roles = info.context.get('roles')
|
||||
rid = reaction.get('id')
|
||||
logger.debug(f"{info.context} for {reaction}")
|
||||
user_id = info.context.get("user_id")
|
||||
roles = info.context.get("roles")
|
||||
rid = reaction.get("id")
|
||||
if rid and isinstance(rid, int) and user_id and roles:
|
||||
del reaction['id']
|
||||
del reaction["id"]
|
||||
with local_session() as session:
|
||||
reaction_query = select(Reaction).filter(Reaction.id == rid)
|
||||
aliased_reaction = aliased(Reaction)
|
||||
@@ -263,19 +265,19 @@ async def update_reaction(_, info, reaction):
|
||||
)
|
||||
|
||||
if not r:
|
||||
return {'error': 'invalid reaction id'}
|
||||
return {"error": "invalid reaction id"}
|
||||
|
||||
author = session.query(Author).filter(Author.user == user_id).first()
|
||||
if author:
|
||||
if r.created_by != author.id and 'editor' not in roles:
|
||||
return {'error': 'access denied'}
|
||||
if r.created_by != author.id and "editor" not in roles:
|
||||
return {"error": "access denied"}
|
||||
|
||||
body = reaction.get('body')
|
||||
body = reaction.get("body")
|
||||
if body:
|
||||
r.body = body
|
||||
r.updated_at = int(time.time())
|
||||
|
||||
if r.kind != reaction['kind']:
|
||||
if r.kind != reaction["kind"]:
|
||||
# Определение изменения мнения может быть реализовано здесь
|
||||
pass
|
||||
|
||||
@@ -284,38 +286,38 @@ async def update_reaction(_, info, reaction):
|
||||
session.commit()
|
||||
|
||||
r.stat = {
|
||||
'reacted': reacted_stat,
|
||||
'commented': commented_stat,
|
||||
'rating': int(likes_stat or 0) - int(dislikes_stat or 0),
|
||||
"reacted": reacted_stat,
|
||||
"commented": commented_stat,
|
||||
"rating": int(likes_stat or 0) - int(dislikes_stat or 0),
|
||||
}
|
||||
|
||||
await notify_reaction(r.dict(), 'update')
|
||||
await notify_reaction(r.dict(), "update")
|
||||
|
||||
return {'reaction': r}
|
||||
return {"reaction": r}
|
||||
else:
|
||||
return {'error': 'not authorized'}
|
||||
return {"error": "not authorized"}
|
||||
except Exception:
|
||||
import traceback
|
||||
|
||||
traceback.print_exc()
|
||||
return {'error': 'cannot create reaction'}
|
||||
return {"error": "cannot create reaction"}
|
||||
|
||||
|
||||
@mutation.field('delete_reaction')
|
||||
@mutation.field("delete_reaction")
|
||||
@login_required
|
||||
async def delete_reaction(_, info, reaction_id: int):
|
||||
logger.debug(f'{info.context} for {reaction_id}')
|
||||
user_id = info.context.get('user_id')
|
||||
roles = info.context.get('roles', [])
|
||||
logger.debug(f"{info.context} for {reaction_id}")
|
||||
user_id = info.context.get("user_id")
|
||||
roles = info.context.get("roles", [])
|
||||
if user_id:
|
||||
with local_session() as session:
|
||||
try:
|
||||
author = session.query(Author).filter(Author.user == user_id).one()
|
||||
r = session.query(Reaction).filter(Reaction.id == reaction_id).one()
|
||||
if r.created_by != author.id and 'editor' not in roles:
|
||||
return {'error': 'access denied'}
|
||||
if r.created_by != author.id and "editor" not in roles:
|
||||
return {"error": "access denied"}
|
||||
|
||||
logger.debug(f'{user_id} user removing his #{reaction_id} reaction')
|
||||
logger.debug(f"{user_id} user removing his #{reaction_id} reaction")
|
||||
reaction_dict = r.dict()
|
||||
session.delete(r)
|
||||
session.commit()
|
||||
@@ -323,47 +325,47 @@ async def delete_reaction(_, info, reaction_id: int):
|
||||
# обновление счетчика комментариев в кеше
|
||||
if r.kind == ReactionKind.COMMENT.value:
|
||||
await update_author_stat(author)
|
||||
await notify_reaction(reaction_dict, 'delete')
|
||||
await notify_reaction(reaction_dict, "delete")
|
||||
|
||||
return {'error': None, 'reaction': reaction_dict}
|
||||
return {"error": None, "reaction": reaction_dict}
|
||||
except Exception as exc:
|
||||
return {'error': f'cannot delete reaction: {exc}'}
|
||||
return {'error': 'cannot delete reaction'}
|
||||
return {"error": f"cannot delete reaction: {exc}"}
|
||||
return {"error": "cannot delete reaction"}
|
||||
|
||||
|
||||
def apply_reaction_filters(by, q):
|
||||
shout_slug = by.get('shout', None)
|
||||
shout_slug = by.get("shout", None)
|
||||
if shout_slug:
|
||||
q = q.filter(Shout.slug == shout_slug)
|
||||
|
||||
elif by.get('shouts'):
|
||||
q = q.filter(Shout.slug.in_(by.get('shouts', [])))
|
||||
elif by.get("shouts"):
|
||||
q = q.filter(Shout.slug.in_(by.get("shouts", [])))
|
||||
|
||||
created_by = by.get('created_by', None)
|
||||
created_by = by.get("created_by", None)
|
||||
if created_by:
|
||||
q = q.filter(Author.id == created_by)
|
||||
|
||||
topic = by.get('topic', None)
|
||||
topic = by.get("topic", None)
|
||||
if isinstance(topic, int):
|
||||
q = q.filter(Shout.topics.any(id=topic))
|
||||
|
||||
if by.get('comment', False):
|
||||
if by.get("comment", False):
|
||||
q = q.filter(Reaction.kind == ReactionKind.COMMENT.value)
|
||||
if by.get('rating', False):
|
||||
if by.get("rating", False):
|
||||
q = q.filter(Reaction.kind.in_(RATING_REACTIONS))
|
||||
|
||||
by_search = by.get('search', '')
|
||||
by_search = by.get("search", "")
|
||||
if len(by_search) > 2:
|
||||
q = q.filter(Reaction.body.ilike(f'%{by_search}%'))
|
||||
q = q.filter(Reaction.body.ilike(f"%{by_search}%"))
|
||||
|
||||
after = by.get('after', None)
|
||||
after = by.get("after", None)
|
||||
if isinstance(after, int):
|
||||
q = q.filter(Reaction.created_at > after)
|
||||
|
||||
return q
|
||||
|
||||
|
||||
@query.field('load_reactions_by')
|
||||
@query.field("load_reactions_by")
|
||||
async def load_reactions_by(_, info, by, limit=50, offset=0):
|
||||
"""
|
||||
:param info: graphql meta
|
||||
@@ -401,12 +403,12 @@ async def load_reactions_by(_, info, by, limit=50, offset=0):
|
||||
q = q.group_by(Reaction.id, Author.id, Shout.id, aliased_reaction.id)
|
||||
|
||||
# order by
|
||||
order_stat = by.get('sort', '').lower() # 'like' | 'dislike' | 'newest' | 'oldest'
|
||||
order_stat = by.get("sort", "").lower() # 'like' | 'dislike' | 'newest' | 'oldest'
|
||||
order_by_stmt = desc(Reaction.created_at)
|
||||
if order_stat == 'oldest':
|
||||
if order_stat == "oldest":
|
||||
order_by_stmt = asc(Reaction.created_at)
|
||||
elif order_stat.endswith('like'):
|
||||
order_by_stmt = desc(f'{order_stat}s_stat')
|
||||
elif order_stat.endswith("like"):
|
||||
order_by_stmt = desc(f"{order_stat}s_stat")
|
||||
q = q.order_by(order_by_stmt)
|
||||
|
||||
# pagination
|
||||
@@ -428,9 +430,9 @@ async def load_reactions_by(_, info, by, limit=50, offset=0):
|
||||
reaction.created_by = author
|
||||
reaction.shout = shout
|
||||
reaction.stat = {
|
||||
'rating': int(likes_stat or 0) - int(dislikes_stat or 0),
|
||||
'reacted': reacted_stat,
|
||||
'commented': commented_stat,
|
||||
"rating": int(likes_stat or 0) - int(dislikes_stat or 0),
|
||||
"reacted": reacted_stat,
|
||||
"commented": commented_stat,
|
||||
}
|
||||
reactions.add(reaction) # Используем список для хранения реакций
|
||||
|
||||
@@ -470,7 +472,7 @@ async def reacted_shouts_updates(follower_id: int, limit=50, offset=0) -> List[S
|
||||
# Sort shouts by the `last_comment` field
|
||||
combined_query = (
|
||||
union(q1, q2)
|
||||
.order_by(desc(text('last_comment_stat')))
|
||||
.order_by(desc(text("last_comment_stat")))
|
||||
.limit(limit)
|
||||
.offset(offset)
|
||||
)
|
||||
@@ -485,26 +487,26 @@ async def reacted_shouts_updates(follower_id: int, limit=50, offset=0) -> List[S
|
||||
last_comment,
|
||||
] in results:
|
||||
shout.stat = {
|
||||
'viewed': await ViewedStorage.get_shout(shout.slug),
|
||||
'rating': int(likes_stat or 0) - int(dislikes_stat or 0),
|
||||
'reacted': reacted_stat,
|
||||
'commented': commented_stat,
|
||||
'last_comment': last_comment,
|
||||
"viewed": await ViewedStorage.get_shout(shout.slug),
|
||||
"rating": int(likes_stat or 0) - int(dislikes_stat or 0),
|
||||
"reacted": reacted_stat,
|
||||
"commented": commented_stat,
|
||||
"last_comment": last_comment,
|
||||
}
|
||||
shouts.append(shout)
|
||||
|
||||
return shouts
|
||||
|
||||
|
||||
@query.field('load_shouts_followed')
|
||||
@query.field("load_shouts_followed")
|
||||
@login_required
|
||||
async def load_shouts_followed(_, info, limit=50, offset=0) -> List[Shout]:
|
||||
user_id = info.context['user_id']
|
||||
user_id = info.context["user_id"]
|
||||
with local_session() as session:
|
||||
author = session.query(Author).filter(Author.user == user_id).first()
|
||||
if author:
|
||||
try:
|
||||
author_id: int = author.dict()['id']
|
||||
author_id: int = author.dict()["id"]
|
||||
shouts = await reacted_shouts_updates(author_id, limit, offset)
|
||||
return shouts
|
||||
except Exception as error:
|
||||
|
@@ -1,7 +1,6 @@
|
||||
from sqlalchemy import bindparam, distinct, or_, text
|
||||
from sqlalchemy.orm import aliased, joinedload
|
||||
from sqlalchemy.sql.expression import (and_, asc, case, desc, func, nulls_last,
|
||||
select)
|
||||
from sqlalchemy.sql.expression import and_, asc, case, desc, func, nulls_last, select
|
||||
|
||||
from orm.author import Author, AuthorFollower
|
||||
from orm.reaction import Reaction, ReactionKind
|
||||
@@ -29,7 +28,7 @@ def filter_my(info, session, q):
|
||||
reader_id = None
|
||||
user_id = None
|
||||
if isinstance(info.context, dict):
|
||||
user_id = info.context.get('user_id')
|
||||
user_id = info.context.get("user_id")
|
||||
if user_id:
|
||||
reader = session.query(Author).filter(Author.user == user_id).first()
|
||||
if reader:
|
||||
@@ -56,22 +55,22 @@ def filter_my(info, session, q):
|
||||
|
||||
def apply_filters(q, filters, author_id=None):
|
||||
if isinstance(filters, dict):
|
||||
if filters.get('reacted'):
|
||||
if filters.get("reacted"):
|
||||
q.join(Reaction, Reaction.created_by == author_id)
|
||||
|
||||
by_featured = filters.get('featured')
|
||||
by_featured = filters.get("featured")
|
||||
if by_featured:
|
||||
q = q.filter(Shout.featured_at.is_not(None))
|
||||
by_layouts = filters.get('layouts')
|
||||
by_layouts = filters.get("layouts")
|
||||
if by_layouts:
|
||||
q = q.filter(Shout.layout.in_(by_layouts))
|
||||
by_author = filters.get('author')
|
||||
by_author = filters.get("author")
|
||||
if by_author:
|
||||
q = q.filter(Shout.authors.any(slug=by_author))
|
||||
by_topic = filters.get('topic')
|
||||
by_topic = filters.get("topic")
|
||||
if by_topic:
|
||||
q = q.filter(Shout.topics.any(slug=by_topic))
|
||||
by_after = filters.get('after')
|
||||
by_after = filters.get("after")
|
||||
if by_after:
|
||||
ts = int(by_after)
|
||||
q = q.filter(Shout.created_at > ts)
|
||||
@@ -79,7 +78,7 @@ def apply_filters(q, filters, author_id=None):
|
||||
return q
|
||||
|
||||
|
||||
@query.field('get_shout')
|
||||
@query.field("get_shout")
|
||||
async def get_shout(_, info, slug: str):
|
||||
with local_session() as session:
|
||||
q = query_shouts()
|
||||
@@ -100,11 +99,11 @@ async def get_shout(_, info, slug: str):
|
||||
] = results
|
||||
|
||||
shout.stat = {
|
||||
'viewed': await ViewedStorage.get_shout(shout.slug),
|
||||
'reacted': reacted_stat,
|
||||
'commented': commented_stat,
|
||||
'rating': int(likes_stat or 0) - int(dislikes_stat or 0),
|
||||
'last_comment': last_comment,
|
||||
"viewed": await ViewedStorage.get_shout(shout.slug),
|
||||
"reacted": reacted_stat,
|
||||
"commented": commented_stat,
|
||||
"rating": int(likes_stat or 0) - int(dislikes_stat or 0),
|
||||
"last_comment": last_comment,
|
||||
}
|
||||
|
||||
for author_caption in (
|
||||
@@ -139,7 +138,7 @@ async def get_shout(_, info, slug: str):
|
||||
return shout
|
||||
|
||||
|
||||
@query.field('load_shouts_by')
|
||||
@query.field("load_shouts_by")
|
||||
async def load_shouts_by(_, _info, options):
|
||||
"""
|
||||
:param options: {
|
||||
@@ -168,25 +167,25 @@ async def load_shouts_by(_, _info, options):
|
||||
q = add_reaction_stat_columns(q, aliased_reaction)
|
||||
|
||||
# filters
|
||||
filters = options.get('filters', {})
|
||||
filters = options.get("filters", {})
|
||||
q = apply_filters(q, filters)
|
||||
|
||||
# group
|
||||
q = q.group_by(Shout.id)
|
||||
|
||||
# order
|
||||
order_by = Shout.featured_at if filters.get('featured') else Shout.published_at
|
||||
order_str = options.get('order_by')
|
||||
if order_str in ['likes', 'shouts', 'followers', 'comments', 'last_comment']:
|
||||
q = q.order_by(desc(text(f'{order_str}_stat')))
|
||||
order_by = Shout.featured_at if filters.get("featured") else Shout.published_at
|
||||
order_str = options.get("order_by")
|
||||
if order_str in ["likes", "shouts", "followers", "comments", "last_comment"]:
|
||||
q = q.order_by(desc(text(f"{order_str}_stat")))
|
||||
query_order_by = (
|
||||
desc(order_by) if options.get('order_by_desc', True) else asc(order_by)
|
||||
desc(order_by) if options.get("order_by_desc", True) else asc(order_by)
|
||||
)
|
||||
q = q.order_by(nulls_last(query_order_by))
|
||||
|
||||
# limit offset
|
||||
offset = options.get('offset', 0)
|
||||
limit = options.get('limit', 10)
|
||||
offset = options.get("offset", 0)
|
||||
limit = options.get("limit", 10)
|
||||
q = q.limit(limit).offset(offset)
|
||||
|
||||
shouts = []
|
||||
@@ -215,18 +214,18 @@ async def load_shouts_by(_, _info, options):
|
||||
if main_topic:
|
||||
shout.main_topic = main_topic[0]
|
||||
shout.stat = {
|
||||
'viewed': await ViewedStorage.get_shout(shout.slug),
|
||||
'reacted': reacted_stat,
|
||||
'commented': commented_stat,
|
||||
'rating': int(likes_stat) - int(dislikes_stat),
|
||||
'last_comment': last_comment,
|
||||
"viewed": await ViewedStorage.get_shout(shout.slug),
|
||||
"reacted": reacted_stat,
|
||||
"commented": commented_stat,
|
||||
"rating": int(likes_stat) - int(dislikes_stat),
|
||||
"last_comment": last_comment,
|
||||
}
|
||||
shouts.append(shout)
|
||||
|
||||
return shouts
|
||||
|
||||
|
||||
@query.field('load_shouts_feed')
|
||||
@query.field("load_shouts_feed")
|
||||
@login_required
|
||||
async def load_shouts_feed(_, info, options):
|
||||
shouts = []
|
||||
@@ -237,24 +236,24 @@ async def load_shouts_feed(_, info, options):
|
||||
q = add_reaction_stat_columns(q, aliased_reaction)
|
||||
|
||||
# filters
|
||||
filters = options.get('filters', {})
|
||||
filters = options.get("filters", {})
|
||||
if filters:
|
||||
q, reader_id = filter_my(info, session, q)
|
||||
q = apply_filters(q, filters, reader_id)
|
||||
|
||||
# sort order
|
||||
order_by = options.get(
|
||||
'order_by',
|
||||
Shout.featured_at if filters.get('featured') else Shout.published_at,
|
||||
"order_by",
|
||||
Shout.featured_at if filters.get("featured") else Shout.published_at,
|
||||
)
|
||||
|
||||
query_order_by = (
|
||||
desc(order_by) if options.get('order_by_desc', True) else asc(order_by)
|
||||
desc(order_by) if options.get("order_by_desc", True) else asc(order_by)
|
||||
)
|
||||
|
||||
# pagination
|
||||
offset = options.get('offset', 0)
|
||||
limit = options.get('limit', 10)
|
||||
offset = options.get("offset", 0)
|
||||
limit = options.get("limit", 10)
|
||||
|
||||
q = (
|
||||
q.group_by(Shout.id)
|
||||
@@ -289,18 +288,18 @@ async def load_shouts_feed(_, info, options):
|
||||
if main_topic:
|
||||
shout.main_topic = main_topic[0]
|
||||
shout.stat = {
|
||||
'viewed': await ViewedStorage.get_shout(shout.slug),
|
||||
'reacted': reacted_stat,
|
||||
'commented': commented_stat,
|
||||
'rating': likes_stat - dislikes_stat,
|
||||
'last_comment': last_comment,
|
||||
"viewed": await ViewedStorage.get_shout(shout.slug),
|
||||
"reacted": reacted_stat,
|
||||
"commented": commented_stat,
|
||||
"rating": likes_stat - dislikes_stat,
|
||||
"last_comment": last_comment,
|
||||
}
|
||||
shouts.append(shout)
|
||||
|
||||
return shouts
|
||||
|
||||
|
||||
@query.field('load_shouts_search')
|
||||
@query.field("load_shouts_search")
|
||||
async def load_shouts_search(_, _info, text, limit=50, offset=0):
|
||||
if isinstance(text, str) and len(text) > 2:
|
||||
results = await search_text(text, limit, offset)
|
||||
@@ -309,7 +308,7 @@ async def load_shouts_search(_, _info, text, limit=50, offset=0):
|
||||
return []
|
||||
|
||||
|
||||
@query.field('load_shouts_unrated')
|
||||
@query.field("load_shouts_unrated")
|
||||
@login_required
|
||||
async def load_shouts_unrated(_, info, limit: int = 50, offset: int = 0):
|
||||
q = query_shouts()
|
||||
@@ -324,7 +323,7 @@ async def load_shouts_unrated(_, info, limit: int = 50, offset: int = 0):
|
||||
),
|
||||
),
|
||||
)
|
||||
.outerjoin(Author, Author.user == bindparam('user_id'))
|
||||
.outerjoin(Author, Author.user == bindparam("user_id"))
|
||||
.where(
|
||||
and_(
|
||||
Shout.deleted_at.is_(None),
|
||||
@@ -341,7 +340,7 @@ async def load_shouts_unrated(_, info, limit: int = 50, offset: int = 0):
|
||||
q = add_reaction_stat_columns(q, aliased_reaction)
|
||||
|
||||
q = q.group_by(Shout.id).order_by(func.random()).limit(limit).offset(offset)
|
||||
user_id = info.context.get('user_id') if isinstance(info.context, dict) else None
|
||||
user_id = info.context.get("user_id") if isinstance(info.context, dict) else None
|
||||
if user_id:
|
||||
with local_session() as session:
|
||||
author = session.query(Author).filter(Author.user == user_id).first()
|
||||
@@ -361,20 +360,20 @@ async def get_shouts_from_query(q, author_id=None):
|
||||
likes_stat,
|
||||
dislikes_stat,
|
||||
last_comment,
|
||||
] in session.execute(q, {'author_id': author_id}).unique():
|
||||
] in session.execute(q, {"author_id": author_id}).unique():
|
||||
shouts.append(shout)
|
||||
shout.stat = {
|
||||
'viewed': await ViewedStorage.get_shout(shout_slug=shout.slug),
|
||||
'reacted': reacted_stat,
|
||||
'commented': commented_stat,
|
||||
'rating': int(likes_stat or 0) - int(dislikes_stat or 0),
|
||||
'last_comment': last_comment,
|
||||
"viewed": await ViewedStorage.get_shout(shout_slug=shout.slug),
|
||||
"reacted": reacted_stat,
|
||||
"commented": commented_stat,
|
||||
"rating": int(likes_stat or 0) - int(dislikes_stat or 0),
|
||||
"last_comment": last_comment,
|
||||
}
|
||||
|
||||
return shouts
|
||||
|
||||
|
||||
@query.field('load_shouts_random_top')
|
||||
@query.field("load_shouts_random_top")
|
||||
async def load_shouts_random_top(_, _info, options):
|
||||
"""
|
||||
:param _
|
||||
@@ -399,7 +398,7 @@ async def load_shouts_random_top(_, _info, options):
|
||||
.where(and_(Shout.deleted_at.is_(None), Shout.layout.is_not(None)))
|
||||
)
|
||||
|
||||
subquery = apply_filters(subquery, options.get('filters', {}))
|
||||
subquery = apply_filters(subquery, options.get("filters", {}))
|
||||
|
||||
subquery = subquery.group_by(Shout.id).order_by(
|
||||
desc(
|
||||
@@ -415,7 +414,7 @@ async def load_shouts_random_top(_, _info, options):
|
||||
)
|
||||
)
|
||||
|
||||
random_limit = options.get('random_limit', 100)
|
||||
random_limit = options.get("random_limit", 100)
|
||||
if random_limit:
|
||||
subquery = subquery.limit(random_limit)
|
||||
|
||||
@@ -427,7 +426,7 @@ async def load_shouts_random_top(_, _info, options):
|
||||
|
||||
q = add_reaction_stat_columns(q, aliased_reaction)
|
||||
|
||||
limit = options.get('limit', 10)
|
||||
limit = options.get("limit", 10)
|
||||
q = q.group_by(Shout.id).order_by(func.random()).limit(limit)
|
||||
|
||||
shouts = await get_shouts_from_query(q)
|
||||
@@ -435,17 +434,17 @@ async def load_shouts_random_top(_, _info, options):
|
||||
return shouts
|
||||
|
||||
|
||||
@query.field('load_shouts_random_topic')
|
||||
@query.field("load_shouts_random_topic")
|
||||
async def load_shouts_random_topic(_, info, limit: int = 10):
|
||||
[topic] = get_topics_random(None, None, 1)
|
||||
if topic:
|
||||
shouts = fetch_shouts_by_topic(topic, limit)
|
||||
if shouts:
|
||||
return {'topic': topic, 'shouts': shouts}
|
||||
return {"topic": topic, "shouts": shouts}
|
||||
return {
|
||||
'error': 'failed to get random topic after few retries',
|
||||
'shouts': [],
|
||||
'topic': {},
|
||||
"error": "failed to get random topic after few retries",
|
||||
"shouts": [],
|
||||
"topic": {},
|
||||
}
|
||||
|
||||
|
||||
|
@@ -18,28 +18,35 @@ def add_topic_stat_columns(q):
|
||||
|
||||
# shouts
|
||||
q = q.outerjoin(aliased_shout_topic, aliased_shout_topic.topic == Topic.id)
|
||||
q = q.add_columns(func.count(distinct(aliased_shout_topic.shout)).label('shouts_stat'))
|
||||
q = q.add_columns(
|
||||
func.count(distinct(aliased_shout_topic.shout)).label("shouts_stat")
|
||||
)
|
||||
|
||||
# authors
|
||||
q = q.outerjoin(aliased_shout, and_(
|
||||
aliased_shout.id == aliased_shout_topic.shout,
|
||||
aliased_shout.published_at.is_not(None),
|
||||
aliased_shout.deleted_at.is_(None)
|
||||
))
|
||||
q = q.outerjoin(
|
||||
aliased_shout,
|
||||
and_(
|
||||
aliased_shout.id == aliased_shout_topic.shout,
|
||||
aliased_shout.published_at.is_not(None),
|
||||
aliased_shout.deleted_at.is_(None),
|
||||
),
|
||||
)
|
||||
q = q.outerjoin(aliased_authors, aliased_shout.authors.any(id=aliased_authors.id))
|
||||
q = q.add_columns(func.count(distinct(aliased_authors.author)).label('authors_stat'))
|
||||
q = q.add_columns(
|
||||
func.count(distinct(aliased_authors.author)).label("authors_stat")
|
||||
)
|
||||
|
||||
# followers
|
||||
q = q.outerjoin(aliased_followers, aliased_followers.topic == Topic.id)
|
||||
q = q.add_columns(
|
||||
func.count(distinct(aliased_followers.follower)).label('followers_stat')
|
||||
func.count(distinct(aliased_followers.follower)).label("followers_stat")
|
||||
)
|
||||
|
||||
# comments
|
||||
sub_comments = (
|
||||
select(
|
||||
Shout.id.label('shout_id'),
|
||||
func.coalesce(func.count(Reaction.id)).label('comments_count')
|
||||
Shout.id.label("shout_id"),
|
||||
func.coalesce(func.count(Reaction.id)).label("comments_count"),
|
||||
)
|
||||
.join(ShoutTopic, ShoutTopic.shout == Shout.id)
|
||||
.join(Topic, ShoutTopic.topic == Topic.id)
|
||||
@@ -55,7 +62,9 @@ def add_topic_stat_columns(q):
|
||||
.subquery()
|
||||
)
|
||||
q = q.outerjoin(sub_comments, aliased_shout_topic.shout == sub_comments.c.shout_id)
|
||||
q = q.add_columns(func.coalesce(sub_comments.c.comments_count, 0).label('comments_stat'))
|
||||
q = q.add_columns(
|
||||
func.coalesce(sub_comments.c.comments_count, 0).label("comments_stat")
|
||||
)
|
||||
|
||||
group_list = [Topic.id, sub_comments.c.comments_count]
|
||||
|
||||
@@ -71,23 +80,23 @@ def add_author_stat_columns(q):
|
||||
|
||||
q = q.outerjoin(aliased_shout_author, aliased_shout_author.author == Author.id)
|
||||
q = q.add_columns(
|
||||
func.count(distinct(aliased_shout_author.shout)).label('shouts_stat')
|
||||
func.count(distinct(aliased_shout_author.shout)).label("shouts_stat")
|
||||
)
|
||||
|
||||
q = q.outerjoin(aliased_authors, aliased_authors.follower == Author.id)
|
||||
q = q.add_columns(
|
||||
func.count(distinct(aliased_authors.author)).label('authors_stat')
|
||||
func.count(distinct(aliased_authors.author)).label("authors_stat")
|
||||
)
|
||||
|
||||
q = q.outerjoin(aliased_followers, aliased_followers.author == Author.id)
|
||||
q = q.add_columns(
|
||||
func.count(distinct(aliased_followers.follower)).label('followers_stat')
|
||||
func.count(distinct(aliased_followers.follower)).label("followers_stat")
|
||||
)
|
||||
|
||||
# Create a subquery for comments count
|
||||
sub_comments = (
|
||||
select(
|
||||
Author.id, func.coalesce(func.count(Reaction.id)).label('comments_count')
|
||||
Author.id, func.coalesce(func.count(Reaction.id)).label("comments_count")
|
||||
)
|
||||
.outerjoin(
|
||||
Reaction,
|
||||
@@ -113,8 +122,8 @@ def add_author_stat_columns(q):
|
||||
def get_with_stat(q):
|
||||
records = []
|
||||
try:
|
||||
is_author = f'{q}'.lower().startswith('select author')
|
||||
is_topic = f'{q}'.lower().startswith('select topic')
|
||||
is_author = f"{q}".lower().startswith("select author")
|
||||
is_topic = f"{q}".lower().startswith("select topic")
|
||||
if is_author:
|
||||
q = add_author_stat_columns(q)
|
||||
elif is_topic:
|
||||
@@ -124,22 +133,23 @@ def get_with_stat(q):
|
||||
for cols in result:
|
||||
entity = cols[0]
|
||||
stat = dict()
|
||||
stat['shouts'] = cols[1]
|
||||
stat['authors'] = cols[2]
|
||||
stat['followers'] = cols[3]
|
||||
stat["shouts"] = cols[1]
|
||||
stat["authors"] = cols[2]
|
||||
stat["followers"] = cols[3]
|
||||
if is_author:
|
||||
stat['comments'] = cols[4]
|
||||
stat["comments"] = cols[4]
|
||||
entity.stat = stat
|
||||
records.append(entity)
|
||||
except Exception as exc:
|
||||
import traceback
|
||||
|
||||
logger.error(exc, traceback.format_exc())
|
||||
raise Exception(exc)
|
||||
return records
|
||||
|
||||
|
||||
def author_follows_authors(author_id: int):
|
||||
af = aliased(AuthorFollower, name='af')
|
||||
af = aliased(AuthorFollower, name="af")
|
||||
q = (
|
||||
select(Author)
|
||||
.select_from(join(Author, af, Author.id == af.author))
|
||||
@@ -158,7 +168,7 @@ def author_follows_topics(author_id: int):
|
||||
|
||||
|
||||
async def update_author_stat(author: Author):
|
||||
author_with_stat = get_with_stat(select(Author).where(Author.id==author.id))
|
||||
author_with_stat = get_with_stat(select(Author).where(Author.id == author.id))
|
||||
if isinstance(author_with_stat, Author):
|
||||
author_dict = author_with_stat.dict()
|
||||
await cache_author(author_dict)
|
||||
|
@@ -10,9 +10,9 @@ from services.memorycache import cache_region
|
||||
from services.schema import mutation, query
|
||||
|
||||
|
||||
@query.field('get_topics_all')
|
||||
@query.field("get_topics_all")
|
||||
def get_topics_all(_, _info):
|
||||
cache_key = 'get_topics_all'
|
||||
cache_key = "get_topics_all"
|
||||
|
||||
@cache_region.cache_on_arguments(cache_key)
|
||||
def _get_topics_all():
|
||||
@@ -21,9 +21,9 @@ def get_topics_all(_, _info):
|
||||
return _get_topics_all()
|
||||
|
||||
|
||||
@query.field('get_topics_by_community')
|
||||
@query.field("get_topics_by_community")
|
||||
def get_topics_by_community(_, _info, community_id: int):
|
||||
cache_key = f'get_topics_by_community_{community_id}'
|
||||
cache_key = f"get_topics_by_community_{community_id}"
|
||||
|
||||
@cache_region.cache_on_arguments(cache_key)
|
||||
def _get_topics_by_community():
|
||||
@@ -33,8 +33,8 @@ def get_topics_by_community(_, _info, community_id: int):
|
||||
return _get_topics_by_community()
|
||||
|
||||
|
||||
@query.field('get_topics_by_author')
|
||||
async def get_topics_by_author(_, _info, author_id=0, slug='', user=''):
|
||||
@query.field("get_topics_by_author")
|
||||
async def get_topics_by_author(_, _info, author_id=0, slug="", user=""):
|
||||
q = select(Topic)
|
||||
if author_id:
|
||||
q = q.join(Author).where(Author.id == author_id)
|
||||
@@ -46,7 +46,7 @@ async def get_topics_by_author(_, _info, author_id=0, slug='', user=''):
|
||||
return get_with_stat(q)
|
||||
|
||||
|
||||
@query.field('get_topic')
|
||||
@query.field("get_topic")
|
||||
def get_topic(_, _info, slug: str):
|
||||
q = select(Topic).filter(Topic.slug == slug)
|
||||
result = get_with_stat(q)
|
||||
@@ -54,7 +54,7 @@ def get_topic(_, _info, slug: str):
|
||||
return topic
|
||||
|
||||
|
||||
@mutation.field('create_topic')
|
||||
@mutation.field("create_topic")
|
||||
@login_required
|
||||
async def create_topic(_, _info, inp):
|
||||
with local_session() as session:
|
||||
@@ -64,46 +64,46 @@ async def create_topic(_, _info, inp):
|
||||
session.add(new_topic)
|
||||
session.commit()
|
||||
|
||||
return {'topic': new_topic}
|
||||
return {"topic": new_topic}
|
||||
|
||||
|
||||
@mutation.field('update_topic')
|
||||
@mutation.field("update_topic")
|
||||
@login_required
|
||||
async def update_topic(_, _info, inp):
|
||||
slug = inp['slug']
|
||||
slug = inp["slug"]
|
||||
with local_session() as session:
|
||||
topic = session.query(Topic).filter(Topic.slug == slug).first()
|
||||
if not topic:
|
||||
return {'error': 'topic not found'}
|
||||
return {"error": "topic not found"}
|
||||
else:
|
||||
Topic.update(topic, inp)
|
||||
session.add(topic)
|
||||
session.commit()
|
||||
|
||||
return {'topic': topic}
|
||||
return {"topic": topic}
|
||||
|
||||
|
||||
@mutation.field('delete_topic')
|
||||
@mutation.field("delete_topic")
|
||||
@login_required
|
||||
async def delete_topic(_, info, slug: str):
|
||||
user_id = info.context['user_id']
|
||||
user_id = info.context["user_id"]
|
||||
with local_session() as session:
|
||||
t: Topic = session.query(Topic).filter(Topic.slug == slug).first()
|
||||
if not t:
|
||||
return {'error': 'invalid topic slug'}
|
||||
return {"error": "invalid topic slug"}
|
||||
author = session.query(Author).filter(Author.user == user_id).first()
|
||||
if author:
|
||||
if t.created_by != author.id:
|
||||
return {'error': 'access denied'}
|
||||
return {"error": "access denied"}
|
||||
|
||||
session.delete(t)
|
||||
session.commit()
|
||||
|
||||
return {}
|
||||
return {'error': 'access denied'}
|
||||
return {"error": "access denied"}
|
||||
|
||||
|
||||
@query.field('get_topics_random')
|
||||
@query.field("get_topics_random")
|
||||
def get_topics_random(_, _info, amount=12):
|
||||
q = select(Topic)
|
||||
q = q.join(ShoutTopic)
|
||||
|
Reference in New Issue
Block a user