feat: fetch views manually and worker

This commit is contained in:
Artem Tsyrulnikov
2025-11-12 23:55:44 +03:00
parent 292bb0d49b
commit a48d5e67cb
28 changed files with 632 additions and 135 deletions

View File

@@ -0,0 +1,65 @@
import datetime
import logging
from typing import TYPE_CHECKING
from src import domain, dto
if TYPE_CHECKING:
from .. import Usecase
log = logging.getLogger(__name__)
async def fetch_views_manually(self: 'Usecase', input: dto.FetchViewsInputManually) -> dto.FetchViewsManuallyOutput:
async with self.database.transaction():
purchase = await self.database.get_purchase(input.user_id, input.purchase_id)
if not purchase:
raise domain.PurchaseNotFound(input.purchase_id)
if not purchase.ad_post_url:
return dto.FetchViewsManuallyOutput(
purchase_id=purchase.id,
views_count=None,
views_availability=domain.PostViewsAvailability.UNAVAILABLE,
fetched_at=datetime.datetime.now(datetime.UTC),
error_message='No ad_post_url specified',
)
views_count = await self.telegram_parser.get_post_views(purchase.ad_post_url)
fetched_at = datetime.datetime.now(datetime.UTC)
if views_count:
purchase.views_count = views_count
purchase.views_availability = domain.PostViewsAvailability.AVAILABLE
purchase.last_views_fetch_at = fetched_at
await self.database.update_purchase(purchase)
snapshot = domain.ViewsSnapshot(
purchase_id=purchase.id,
views_count=views_count,
fetched_at=fetched_at,
)
await self.database.create_views_snapshot(snapshot)
log.info('Views fetched for purchase %s: %d', purchase.id, views_count)
return dto.FetchViewsManuallyOutput(
purchase_id=purchase.id,
views_count=views_count,
views_availability=domain.PostViewsAvailability.AVAILABLE,
fetched_at=fetched_at,
)
purchase.views_availability = domain.PostViewsAvailability.UNAVAILABLE
purchase.last_views_fetch_at = fetched_at
await self.database.update_purchase(purchase)
log.warning('Failed to fetch views for purchase %s', purchase.id)
return dto.FetchViewsManuallyOutput(
purchase_id=purchase.id,
views_count=None,
views_availability=domain.PostViewsAvailability.UNAVAILABLE,
fetched_at=fetched_at,
error_message='Failed to fetch views from Telegram API',
)