https://dev.kronoz.win/r/marzneshin.git
1import asyncio
2from datetime import datetime, timedelta
3
4from app.config import NOTIFY_DAYS_LEFT
5from app.db import GetDB
6from app.db.models import User
7from app.models.notification import UserNotification
8from app.models.user import UserResponse
9from app.notification.notifiers import notify
10
11
12async def expire_days_reached():
13 """
14 Identifies users whose expiration days have reached a predefined notification period and sends notifications.
15
16 This function checks each active user with an expiration date set and determines if they are within a
17 specific notification window (`NOTIFY_DAYS_LEFT` days before expiration). If the condition is met,
18 it sends a notification.
19
20 How it works:
21 - The current UTC time is obtained.
22 - For each user in the database who is activated and currently active, check if their expiration date is set.
23 - If the user's expiration date is within the `NOTIFY_DAYS_LEFT` threshold (plus a 30-second margin),
24 log the event and trigger a notification.
25 """
26
27 now = datetime.utcnow()
28 cleft = timedelta(days=NOTIFY_DAYS_LEFT) + now
29 cright = timedelta(days=NOTIFY_DAYS_LEFT, seconds=30) + now
30 with GetDB() as db:
31 users = db.query(User).filter(
32 User.is_active == True,
33 User.activated == True,
34 User.expire_date.isnot(None),
35 User.expire_date.between(cleft, cright),
36 )
37 for user in users:
38 asyncio.ensure_future(
39 notify(
40 action=UserNotification.Action.reached_days_left,
41 user=UserResponse.model_validate(user),
42 )
43 )