gitscope
← marzneshin / v0.7.4 / app/tasks/review_users.py
https://dev.kronoz.win/r/marzneshin.git
app/tasks/review_users.py · Python
Blame Raw
 1import asyncio
 2import logging
 3from datetime import datetime, timedelta
 4from typing import TYPE_CHECKING
 5
 6from app import marznode
 7from app.db import (
 8    GetDB,
 9    get_users,
10)
11from app.models.notification import UserNotification
12from app.models.user import (
13    UserResponse,
14    UserExpireStrategy,
15)
16from app.notification import notify
17
18if TYPE_CHECKING:
19    pass
20
21
22logger = logging.getLogger(__name__)
23
24
25async def review_users():
26    now = datetime.utcnow()
27    with GetDB() as db:
28        for user in get_users(db, activated=True, is_active=False):
29            """looking for expired/to be limited users who are still active"""
30
31            marznode.operations.update_user(user, remove=True)
32            user.activated = False
33            db.commit()
34            db.refresh(user)
35
36            asyncio.ensure_future(
37                notify(
38                    action=UserNotification.Action.user_deactivated,
39                    user=UserResponse.model_validate(user),
40                )
41            )
42
43            logger.info(
44                "User `%s` activation state changed to `%s`",
45                user.username,
46                str(user.activated),
47            )
48
49        for user in get_users(
50            db,
51            expire_strategy=UserExpireStrategy.START_ON_FIRST_USE,
52            is_active=True,
53        ):
54            """looking for to be activated, on hold users"""
55            base_time = user.edit_at or user.created_at
56
57            # Check if the user is online After or at 'base_time' or...
58            # If the user didn't connect until activation_deadline; change status to "Active"
59            if not (
60                (user.online_at and base_time <= user.online_at)
61                or (
62                    user.activation_deadline
63                    and (user.activation_deadline <= now)
64                )
65            ):
66                continue
67
68            user.expire_date = datetime.utcnow() + timedelta(
69                seconds=user.usage_duration
70            )
71            user.expire_strategy = UserExpireStrategy.FIXED_DATE
72            db.commit()
73            db.refresh(user)
74            logger.info("on hold user `%s` has been activated", user.username)