core/orm/shout.py

168 lines
5.4 KiB
Python
Raw Normal View History

from typing import List
2021-09-29 12:59:48 +00:00
from datetime import datetime, timedelta
2021-08-20 08:08:32 +00:00
from sqlalchemy import Table, Column, Integer, String, ForeignKey, DateTime, Boolean
from sqlalchemy.orm import relationship
2021-09-27 14:59:44 +00:00
from sqlalchemy.orm.attributes import flag_modified
2021-09-05 08:56:15 +00:00
from orm import Permission, User, Topic
from orm.comment import Comment
2021-09-29 12:59:48 +00:00
from orm.base import Base, local_session
2021-09-24 14:39:37 +00:00
from functools import reduce
2021-09-29 12:59:48 +00:00
import asyncio
2021-08-28 10:13:50 +00:00
class ShoutAuthor(Base):
__tablename__ = "shout_author"
id = None
shout = Column(ForeignKey('shout.id'), primary_key = True)
user = Column(ForeignKey('user.id'), primary_key = True)
2021-09-05 08:56:15 +00:00
2021-09-05 07:16:28 +00:00
class ShoutViewer(Base):
2021-09-05 08:56:15 +00:00
__tablename__ = "shout_viewer"
id = None
shout = Column(ForeignKey('shout.id'), primary_key = True)
user = Column(ForeignKey('user.id'), primary_key = True)
2021-08-20 08:08:32 +00:00
2021-08-28 15:12:13 +00:00
class ShoutTopic(Base):
__tablename__ = 'shout_topic'
id = None
shout = Column(ForeignKey('shout.id'), primary_key = True)
topic = Column(ForeignKey('topic.id'), primary_key = True)
2021-08-30 07:41:59 +00:00
class ShoutRating(Base):
2021-08-31 15:15:27 +00:00
__tablename__ = "shout_rating"
2021-08-25 21:20:53 +00:00
id = None
rater_id = Column(ForeignKey('user.id'), primary_key = True)
shout_id = Column(ForeignKey('shout.id'), primary_key = True)
2021-09-25 11:40:37 +00:00
ts = Column(DateTime, nullable=False, default = datetime.now, comment="Timestamp")
2021-08-31 15:15:27 +00:00
value = Column(Integer)
2021-09-24 14:39:37 +00:00
class ShoutRatingStorage:
2021-09-29 13:37:08 +00:00
ratings = []
2021-09-24 14:39:37 +00:00
2021-09-29 13:37:08 +00:00
lock = asyncio.Lock()
@staticmethod
def init(session):
ShoutRatingStorage.ratings = session.query(ShoutRating).all()
@staticmethod
async def get_rating(shout_id):
async with ShoutRatingStorage.lock:
shout_ratings = list(filter(lambda x: x.shout_id == shout_id, ShoutRatingStorage.ratings))
2021-09-24 14:39:37 +00:00
return reduce((lambda x, y: x + y.value), shout_ratings, 0)
2021-09-29 13:37:08 +00:00
@staticmethod
async def update_rating(new_rating):
async with ShoutRatingStorage.lock:
rating = next((x for x in ShoutRatingStorage.ratings \
if x.rater_id == new_rating.rater_id and x.shout_id == new_rating.shout_id), None)
if rating:
rating.value = new_rating.value
rating.ts = new_rating.ts
else:
ShoutRatingStorage.ratings.append(new_rating)
2021-09-24 14:39:37 +00:00
2021-08-31 15:15:27 +00:00
class ShoutViewByDay(Base):
__tablename__ = "shout_view_by_day"
id = None
shout_id = Column(ForeignKey('shout.id'), primary_key = True)
2021-09-27 14:59:44 +00:00
day = Column(DateTime, primary_key = True, default = datetime.now)
2021-08-25 21:20:53 +00:00
value = Column(Integer)
2021-09-24 14:39:37 +00:00
class ShoutViewStorage:
2021-09-29 12:59:48 +00:00
views = []
this_day_views = {}
period = 30*60 #sec
lock = asyncio.Lock()
@staticmethod
def init(session):
self = ShoutViewStorage
2021-09-24 14:39:37 +00:00
self.views = session.query(ShoutViewByDay).all()
2021-09-27 14:59:44 +00:00
for view in self.views:
shout_id = view.shout_id
if not shout_id in self.this_day_views:
self.this_day_views[shout_id] = view
this_day_view = self.this_day_views[shout_id]
if this_day_view.day < view.day:
self.this_day_views[shout_id] = view
2021-09-24 14:39:37 +00:00
2021-09-29 12:59:48 +00:00
@staticmethod
async def get_view(shout_id):
async with ShoutViewStorage.lock:
shout_views = list(filter(lambda x: x.shout_id == shout_id, ShoutViewStorage.views))
2021-09-24 14:39:37 +00:00
return reduce((lambda x, y: x + y.value), shout_views, 0)
2021-09-29 12:59:48 +00:00
@staticmethod
async def inc_view(shout_id):
self = ShoutViewStorage
async with ShoutViewStorage.lock:
this_day_view = self.this_day_views.get(shout_id)
day_start = datetime.now().replace(hour = 0, minute = 0, second = 0)
if not this_day_view or this_day_view.day < day_start:
this_day_view = ShoutViewByDay.create(shout_id = shout_id, value = 1)
self.this_day_views[shout_id] = this_day_view
self.views.append(this_day_view)
else:
this_day_view.value = this_day_view.value + 1
this_day_view.modified = True
@staticmethod
async def flush_changes(session):
async with ShoutViewStorage.lock:
for view in ShoutViewStorage.this_day_views.values():
if getattr(view, "modified", False):
session.add(view)
flag_modified(view, "value")
view.modified = False
2021-09-27 14:59:44 +00:00
session.commit()
2021-09-29 12:59:48 +00:00
@staticmethod
async def worker():
print("ShoutViewStorage worker start")
while True:
try:
print("ShoutViewStorage worker: flush changes")
with local_session() as session:
await ShoutViewStorage.flush_changes(session)
except Exception as err:
print("ShoutViewStorage worker: error = %s" % (err))
await asyncio.sleep(ShoutViewStorage.period)
2021-09-24 14:39:37 +00:00
class Shout(Base):
2021-08-07 16:14:20 +00:00
__tablename__ = 'shout'
2021-08-25 21:20:53 +00:00
# NOTE: automatic ID here
slug: str = Column(String, nullable=False, unique=True)
2021-08-26 21:14:20 +00:00
community: int = Column(Integer, ForeignKey("community.id"), nullable=True, comment="Community")
2021-08-07 16:14:20 +00:00
body: str = Column(String, nullable=False, comment="Body")
createdAt: str = Column(DateTime, nullable=False, default = datetime.now, comment="Created at")
updatedAt: str = Column(DateTime, nullable=True, comment="Updated at")
2021-08-25 21:20:53 +00:00
replyTo: int = Column(ForeignKey("shout.id"), nullable=True)
versionOf: int = Column(ForeignKey("shout.id"), nullable=True)
2021-08-08 12:23:12 +00:00
tags: str = Column(String, nullable=True)
2021-09-05 07:16:28 +00:00
publishedBy: bool = Column(ForeignKey("user.id"), nullable=True)
2021-08-20 08:08:32 +00:00
publishedAt: str = Column(DateTime, nullable=True)
cover: str = Column(String, nullable = True)
2021-08-25 21:20:53 +00:00
title: str = Column(String, nullable = True)
subtitle: str = Column(String, nullable = True)
2021-09-05 07:16:28 +00:00
comments = relationship(Comment)
2021-08-20 08:08:32 +00:00
layout: str = Column(String, nullable = True)
2021-08-28 10:13:50 +00:00
authors = relationship(lambda: User, secondary=ShoutAuthor.__tablename__) # NOTE: multiple authors
2021-08-28 15:12:13 +00:00
topics = relationship(lambda: Topic, secondary=ShoutTopic.__tablename__)
2021-09-05 07:16:28 +00:00
visibleFor = relationship(lambda: User, secondary=ShoutViewer.__tablename__)
2021-08-25 21:20:53 +00:00
old_id: str = Column(String, nullable = True)