core/services/viewed.py

210 lines
9.2 KiB
Python
Raw Normal View History

2024-08-07 10:25:48 +00:00
import asyncio
2024-01-25 19:41:27 +00:00
import json
import os
import time
2023-12-17 20:30:20 +00:00
from datetime import datetime, timedelta, timezone
2024-01-25 19:41:27 +00:00
from typing import Dict
2024-01-23 13:04:38 +00:00
2024-08-07 10:37:08 +00:00
# ga
2024-01-28 13:26:40 +00:00
from google.analytics.data_v1beta import BetaAnalyticsDataClient
2024-08-09 06:37:06 +00:00
from google.analytics.data_v1beta.types import (
DateRange,
Dimension,
Metric,
RunReportRequest,
)
2022-11-21 22:23:16 +00:00
2024-01-23 13:04:38 +00:00
from orm.author import Author
from orm.shout import Shout, ShoutAuthor, ShoutTopic
from orm.topic import Topic
from services.db import local_session
2024-08-07 10:37:50 +00:00
from utils.logger import root_logger as logger
2024-01-23 13:04:38 +00:00
2024-08-07 10:37:08 +00:00
GOOGLE_KEYFILE_PATH = os.environ.get("GOOGLE_KEYFILE_PATH", "/dump/google-service.json")
GOOGLE_PROPERTY_ID = os.environ.get("GOOGLE_PROPERTY_ID", "")
2024-04-17 15:32:23 +00:00
VIEWS_FILEPATH = "/dump/views.json"
2024-01-28 12:54:38 +00:00
2024-01-13 12:44:56 +00:00
2022-11-18 17:54:37 +00:00
class ViewedStorage:
2024-08-07 10:37:08 +00:00
lock = asyncio.Lock()
2024-01-22 18:20:17 +00:00
views_by_shout = {}
shouts_by_topic = {}
shouts_by_author = {}
2024-08-07 10:37:08 +00:00
views = None
2024-01-23 13:04:38 +00:00
period = 60 * 60 # каждый час
2024-01-28 13:26:40 +00:00
analytics_client: BetaAnalyticsDataClient | None = None
2024-08-07 10:37:08 +00:00
auth_result = None
2022-11-22 07:29:54 +00:00
disabled = False
2024-04-26 22:51:45 +00:00
start_date = datetime.now().strftime("%Y-%m-%d")
2022-11-18 17:54:37 +00:00
2022-11-20 07:48:40 +00:00
@staticmethod
2024-08-07 10:25:48 +00:00
async def init():
2024-08-07 10:37:08 +00:00
"""Подключение к клиенту Google Analytics с использованием аутентификации"""
2022-11-22 07:29:54 +00:00
self = ViewedStorage
2024-08-07 10:37:08 +00:00
async with self.lock:
# Загрузка предварительно подсчитанных просмотров из файла JSON
self.load_precounted_views()
os.environ.setdefault("GOOGLE_APPLICATION_CREDENTIALS", GOOGLE_KEYFILE_PATH)
if GOOGLE_KEYFILE_PATH and os.path.isfile(GOOGLE_KEYFILE_PATH):
# Using a default constructor instructs the client to use the credentials
# specified in GOOGLE_APPLICATION_CREDENTIALS environment variable.
self.analytics_client = BetaAnalyticsDataClient()
logger.info(" * Клиент Google Analytics успешно авторизован")
# Запуск фоновой задачи
_task = asyncio.create_task(self.worker())
else:
2024-10-15 08:12:09 +00:00
logger.warning(" * please, add Google Analytics credentials file")
2024-08-07 10:37:08 +00:00
self.disabled = True
2022-11-20 07:48:40 +00:00
2024-01-22 16:17:39 +00:00
@staticmethod
def load_precounted_views():
2024-08-07 10:37:08 +00:00
"""Загрузка предварительно подсчитанных просмотров из файла JSON"""
2024-01-22 16:17:39 +00:00
self = ViewedStorage
2024-10-15 08:12:09 +00:00
viewfile_path = VIEWS_FILEPATH
if not os.path.exists(viewfile_path):
viewfile_path = os.path.join(os.path.curdir, "views.json")
if not os.path.exists(viewfile_path):
logger.warning(" * views.json not found")
return
logger.info(f" * loading views from {viewfile_path}")
2024-01-22 16:17:39 +00:00
try:
2024-10-15 08:12:09 +00:00
start_date_int = os.path.getmtime(viewfile_path)
start_date_str = datetime.fromtimestamp(start_date_int).strftime("%Y-%m-%d")
self.start_date = start_date_str
now_date = datetime.now().strftime("%Y-%m-%d")
if now_date == self.start_date:
logger.info(" * views data is up to date!")
2024-03-12 12:57:46 +00:00
else:
2024-10-15 08:12:09 +00:00
logger.warn(f" * {viewfile_path} is too old: {self.start_date}")
with open(viewfile_path, "r") as file:
precounted_views = json.load(file)
self.views_by_shout.update(precounted_views)
logger.info(f" * {len(precounted_views)} shouts with views was loaded.")
2024-01-22 16:17:39 +00:00
except Exception as e:
2024-10-15 08:12:09 +00:00
logger.error(f"precounted views loading error: {e}")
2024-01-22 16:17:39 +00:00
2024-08-07 10:37:08 +00:00
# noinspection PyTypeChecker
2022-11-21 22:23:16 +00:00
@staticmethod
2024-08-07 10:25:48 +00:00
async def update_pages():
2024-08-07 10:37:08 +00:00
"""Запрос всех страниц от Google Analytics, отсортированных по количеству просмотров"""
2022-11-21 22:23:16 +00:00
self = ViewedStorage
2024-10-15 08:12:09 +00:00
logger.info(" ⎧ views update from Google Analytics ---")
2024-01-28 09:03:41 +00:00
if not self.disabled:
2024-01-23 13:04:38 +00:00
try:
start = time.time()
2024-08-07 10:37:08 +00:00
async with self.lock:
if self.analytics_client:
request = RunReportRequest(
property=f"properties/{GOOGLE_PROPERTY_ID}",
dimensions=[Dimension(name="pagePath")],
metrics=[Metric(name="screenPageViews")],
date_ranges=[DateRange(start_date=self.start_date, end_date="today")],
)
response = self.analytics_client.run_report(request)
if response and isinstance(response.rows, list):
slugs = set()
for row in response.rows:
print(
row.dimension_values[0].value,
row.metric_values[0].value,
)
# Извлечение путей страниц из ответа Google Analytics
if isinstance(row.dimension_values, list):
page_path = row.dimension_values[0].value
slug = page_path.split("discours.io/")[-1]
views_count = int(row.metric_values[0].value)
# Обновление данных в хранилище
self.views_by_shout[slug] = self.views_by_shout.get(slug, 0)
self.views_by_shout[slug] += views_count
self.update_topics(slug)
# Запись путей страниц для логирования
slugs.add(slug)
2024-10-15 08:12:09 +00:00
logger.info(f" ⎪ collected pages: {len(slugs)} ")
2024-08-07 10:37:08 +00:00
end = time.time()
2024-10-15 08:12:09 +00:00
logger.info(" ⎪ views update time: %fs " % (end - start))
2024-01-28 09:03:41 +00:00
except Exception as error:
logger.error(error)
2024-06-04 09:55:12 +00:00
self.disabled = True
2022-11-18 17:54:37 +00:00
2022-11-19 11:35:34 +00:00
@staticmethod
2024-08-07 10:15:58 +00:00
def get_shout(shout_slug) -> int:
2024-08-07 10:30:41 +00:00
"""Получение метрики просмотров shout по slug."""
2022-11-19 11:35:34 +00:00
self = ViewedStorage
2024-08-07 10:30:41 +00:00
return self.views_by_shout.get(shout_slug, 0)
2023-11-03 10:10:22 +00:00
@staticmethod
2024-08-07 10:15:58 +00:00
def get_shout_media(shout_slug) -> Dict[str, int]:
2024-08-07 10:30:41 +00:00
"""Получение метрики воспроизведения shout по slug."""
2023-11-03 10:10:22 +00:00
self = ViewedStorage
2024-08-07 10:30:41 +00:00
return self.views_by_shout.get(shout_slug, 0)
2022-11-19 11:35:34 +00:00
2022-11-21 05:18:50 +00:00
@staticmethod
2024-08-07 10:15:58 +00:00
def get_topic(topic_slug) -> int:
2024-08-07 10:30:41 +00:00
"""Получение суммарного значения просмотров темы."""
2022-11-21 05:18:50 +00:00
self = ViewedStorage
2024-08-07 10:30:41 +00:00
return sum(self.views_by_shout.get(shout_slug, 0) for shout_slug in self.shouts_by_topic.get(topic_slug, []))
2022-11-21 05:18:50 +00:00
2024-01-22 15:42:45 +00:00
@staticmethod
2024-08-07 10:15:58 +00:00
def get_author(author_slug) -> int:
2024-08-07 10:30:41 +00:00
"""Получение суммарного значения просмотров автора."""
2024-01-22 15:42:45 +00:00
self = ViewedStorage
2024-08-07 10:30:41 +00:00
return sum(self.views_by_shout.get(shout_slug, 0) for shout_slug in self.shouts_by_author.get(author_slug, []))
2024-01-22 15:42:45 +00:00
2022-11-22 13:58:55 +00:00
@staticmethod
2023-11-22 18:23:15 +00:00
def update_topics(shout_slug):
2024-08-07 10:37:08 +00:00
"""Обновление счетчиков темы по slug shout"""
2022-11-22 13:58:55 +00:00
self = ViewedStorage
2023-11-22 18:23:15 +00:00
with local_session() as session:
2024-01-23 13:04:38 +00:00
# Определение вспомогательной функции для избежания повторения кода
2024-01-22 18:20:17 +00:00
def update_groups(dictionary, key, value):
dictionary[key] = list(set(dictionary.get(key, []) + [value]))
2024-01-23 13:04:38 +00:00
# Обновление тем и авторов с использованием вспомогательной функции
2024-01-25 19:41:27 +00:00
for [_shout_topic, topic] in (
2024-05-30 04:12:00 +00:00
session.query(ShoutTopic, Topic).join(Topic).join(Shout).where(Shout.slug == shout_slug).all()
2024-01-25 19:41:27 +00:00
):
2024-01-22 18:20:17 +00:00
update_groups(self.shouts_by_topic, topic.slug, shout_slug)
2024-01-25 19:41:27 +00:00
for [_shout_topic, author] in (
2024-05-30 04:12:00 +00:00
session.query(ShoutAuthor, Author).join(Author).join(Shout).where(Shout.slug == shout_slug).all()
2024-01-25 19:41:27 +00:00
):
2024-01-22 18:20:17 +00:00
update_groups(self.shouts_by_author, author.slug, shout_slug)
2024-01-22 15:42:45 +00:00
2023-11-03 10:10:22 +00:00
@staticmethod
2024-08-07 10:25:48 +00:00
async def worker():
2024-08-07 10:37:08 +00:00
"""Асинхронная задача обновления"""
2022-11-21 22:23:16 +00:00
failed = 0
2022-11-22 07:29:54 +00:00
self = ViewedStorage
if self.disabled:
return
2023-10-05 22:45:32 +00:00
2023-01-18 12:43:56 +00:00
while True:
try:
2024-08-07 10:25:48 +00:00
await self.update_pages()
2023-01-18 12:43:56 +00:00
failed = 0
2024-02-29 10:04:25 +00:00
except Exception as exc:
2023-01-18 12:43:56 +00:00
failed += 1
2024-02-29 10:04:25 +00:00
logger.debug(exc)
2024-10-15 08:12:09 +00:00
logger.info(" - update failed #%d, wait 10 secs" % failed)
2023-01-18 12:43:56 +00:00
if failed > 3:
2024-10-15 08:12:09 +00:00
logger.info(" - views update failed, not trying anymore")
2023-01-18 12:43:56 +00:00
break
if failed == 0:
when = datetime.now(timezone.utc) + timedelta(seconds=self.period)
t = format(when.astimezone().isoformat())
2024-10-15 08:12:09 +00:00
logger.info(" ⎩ next update: %s" % (t.split("T")[0] + " " + t.split("T")[1].split(".")[0]))
2024-08-07 10:25:48 +00:00
await asyncio.sleep(self.period)
2023-01-18 12:43:56 +00:00
else:
2024-08-07 10:25:48 +00:00
await asyncio.sleep(10)
2024-10-15 08:12:09 +00:00
logger.info(" - try to update views again")