openreplay/api/chalicelib/core/announcements.py
2024-02-06 14:18:50 +01:00

42 lines
1.5 KiB
Python

from chalicelib.utils import pg_client
from chalicelib.utils import helper
from decouple import config
from chalicelib.utils.TimeUTC import TimeUTC
async def get_all(user_id):
async with pg_client.cursor() as cur:
query = cur.mogrify("""
SELECT a.*, u.last >= (EXTRACT(EPOCH FROM a.created_at)*1000) AS viewed
FROM public.announcements AS a,
(SELECT COALESCE(CAST(data ->> 'lastAnnouncementView' AS bigint), 0)
FROM public.users
WHERE user_id = %(userId)s
LIMIT 1) AS u(last)
ORDER BY a.created_at DESC;""",
{"userId": user_id})
await cur.execute(
query
)
announcements = helper.list_to_camel_case(await cur.fetchall())
for a in announcements:
a["createdAt"] = TimeUTC.datetime_to_timestamp(a["createdAt"])
if a["imageUrl"] is not None and len(a["imageUrl"]) > 0:
a["imageUrl"] = config("announcement_url") + a["imageUrl"]
return announcements
async def view(user_id):
async with pg_client.cursor() as cur:
query = cur.mogrify("""
UPDATE public.users
SET data=data ||
('{"lastAnnouncementView":' ||
(EXTRACT(EPOCH FROM timezone('utc'::text, now())) * 1000)::bigint - 20 * 000 ||
'}')::jsonb
WHERE user_id = %(userId)s;""",
{"userId": user_id})
await cur.execute(
query
)
return True