gitscope
https://dev.kronoz.win/r/marzneshin.git
app/tasks/reset_user_data_usage.py · v0.3.0-alpha7
Source
1 f7af2b3 Dawsh 2y ago import logging
2 a47eb4c Dawsh 2y ago from datetime import datetime
3 a47eb4c Dawsh 2y ago
4 f7af2b3 Dawsh 2y ago from app import marznode
5 a47eb4c Dawsh 2y ago from app.db import crud, GetDB, get_users
6 a47eb4c Dawsh 2y ago from app.models.user import UserDataLimitResetStrategy, UserStatus
7 a47eb4c Dawsh 2y ago
8 f7af2b3 Dawsh 2y ago logger = logging.getLogger(__name__)
9 f7af2b3 Dawsh 2y ago
10 a47eb4c Dawsh 2y ago reset_strategy_to_days = {
11 a47eb4c Dawsh 2y ago UserDataLimitResetStrategy.day.value: 1,
12 a47eb4c Dawsh 2y ago UserDataLimitResetStrategy.week.value: 7,
13 a47eb4c Dawsh 2y ago UserDataLimitResetStrategy.month.value: 30,
14 a47eb4c Dawsh 2y ago UserDataLimitResetStrategy.year.value: 365,
15 a47eb4c Dawsh 2y ago }
16 a47eb4c Dawsh 2y ago
17 a47eb4c Dawsh 2y ago
18 9a6b0fa Dawsh 2y ago async def reset_user_data_usage():
19 a47eb4c Dawsh 2y ago now = datetime.utcnow()
20 a47eb4c Dawsh 2y ago with GetDB() as db:
21 01cdf2e Dawsh 2y ago for user in get_users(
22 01cdf2e Dawsh 2y ago db,
23 01cdf2e Dawsh 2y ago reset_strategy=[
24 01cdf2e Dawsh 2y ago UserDataLimitResetStrategy.day.value,
25 01cdf2e Dawsh 2y ago UserDataLimitResetStrategy.week.value,
26 01cdf2e Dawsh 2y ago UserDataLimitResetStrategy.month.value,
27 01cdf2e Dawsh 2y ago UserDataLimitResetStrategy.year.value,
28 01cdf2e Dawsh 2y ago ],
29 01cdf2e Dawsh 2y ago ):
30 a47eb4c Dawsh 2y ago last_reset_time = user.last_traffic_reset_time
31 a47eb4c Dawsh 2y ago num_days_to_reset = reset_strategy_to_days[user.data_limit_reset_strategy]
32 a47eb4c Dawsh 2y ago
33 a47eb4c Dawsh 2y ago if not (now - last_reset_time).days >= num_days_to_reset:
34 a47eb4c Dawsh 2y ago continue
35 a47eb4c Dawsh 2y ago
36 9a6b0fa Dawsh 2y ago old_status = user.status
37 a47eb4c Dawsh 2y ago crud.reset_user_data_usage(db, user)
38 a47eb4c Dawsh 2y ago # make user active if limited on usage reset
39 9a6b0fa Dawsh 2y ago if user.status == UserStatus.active and old_status == UserStatus.limited:
40 d6e2aad Dawsh 2y ago await marznode.operations.update_user(user)
41 a47eb4c Dawsh 2y ago
42 01cdf2e Dawsh 2y ago logger.info(f'User data usage reset for User "{user.username}"')