import vk_api from datetime import datetime import sys import os import time import threading from dotenv import load_dotenv load_dotenv() def _env_str(key: str, default: str = "") -> str: value = os.getenv(key) return value.strip() if value is not None else default def _env_int(key: str, default: int) -> int: raw = os.getenv(key) if raw is None or raw.strip() == "": return default try: return int(raw.strip()) except ValueError: print(f"[config] invalid int for {key}={raw!r}, using default {default}") return default def _env_bool(key: str, default: bool) -> bool: raw = os.getenv(key) if raw is None: return default return raw.strip().lower() in ("1", "true", "yes", "on", "y", "t") def _env_list(key: str, default: list | None = None) -> list: raw = os.getenv(key) if raw is None or raw.strip() == "": return list(default or []) return [item.strip() for item in raw.split(",") if item.strip()] VK_TOKEN = _env_str("VK_TOKEN") BOT_TOKEN = _env_str("BOT_TOKEN") NOTIFY_PEER_ID = _env_int("NOTIFY_PEER_ID", 0) NOTIFY_ENABLED = _env_bool("NOTIFY_ENABLED", True) USER_IDS = _env_list("USER_IDS", []) LOG_FILE = _env_str("LOG_FILE", "online_log.txt") CHECK_INTERVAL = _env_int("CHECK_INTERVAL", 3) APP_DEVICES = { 0: "web-pc", 1: "mobile-official", 2: "mobile-web", 3: "tablet-ipad", 4: "android", 5: "wp", 6: "ios", 7: "win10", 8: "macos", 9: "samsung", 10: "messenger", 11: "mobile-lite", } online_status = {} session_start = {} intersection_active = False intersection_start = None user_names = {} user_ids = [] node_labels = {} _bot_api = None def get_app_name(app_id): return APP_DEVICES.get(app_id, f"unknown-{app_id}") def get_user_full_name(uid): if uid in user_names: return user_names[uid] return str(uid) def get_node_label(uid): return node_labels.get(uid, f"node-{uid}") def init_bot(): global _bot_api if not BOT_TOKEN: write_log("bot token empty, notifications disabled") _bot_api = None return try: vk_bot_session = vk_api.VkApi(token=BOT_TOKEN) _bot_api = vk_bot_session.get_api() write_log("bot init ok") except Exception as e: write_log(f"bot init fail: {e}") _bot_api = None def send_vk_message(text): if not NOTIFY_ENABLED or _bot_api is None: return try: _bot_api.messages.send( peer_id=NOTIFY_PEER_ID, message=text, random_id=int(time.time() * 1000) % (2**31) ) except Exception as e: write_log(f"send msg error: {e}") def notify_async(text): if not NOTIFY_ENABLED or _bot_api is None: return threading.Thread(target=send_vk_message, args=(text,), daemon=True).start() def write_log(message, notify=False): timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S') full_msg = f"[{timestamp}] {message}" print(full_msg) try: with open(LOG_FILE, 'a', encoding='utf-8') as f: f.write(full_msg + '\n') except Exception as e: print(f"log write error: {e}") if notify: notify_async(full_msg) def get_user_ids(vk_session, usernames): global user_names, user_ids try: users = vk_session.method('users.get', { 'user_ids': ','.join(usernames), 'fields': 'id' }) result_ids = [] for user in users: uid = user['id'] full_name = f"{user.get('first_name', '')} {user.get('last_name', '')}".strip() if not full_name: full_name = str(uid) user_names[uid] = full_name result_ids.append(uid) return result_ids except Exception as e: write_log(f"resolve error: {e}") return [] def check_intersection(): global intersection_active, intersection_start online_users = [uid for uid, status in online_status.items() if status] online_count = len(online_users) labels = [get_node_label(uid) for uid in online_users] if online_count >= 2: if not intersection_active: intersection_active = True intersection_start = datetime.now() labels_str = ", ".join(labels) write_log(f"sync overlap detected: {online_count} nodes [{labels_str}]", notify=True) write_log(f"window start: {intersection_start.strftime('%H:%M:%S')}", notify=True) else: if intersection_active: intersection_active = False duration = (datetime.now() - intersection_start).total_seconds() duration_min = duration / 60 write_log(f"sync overlap closed: {duration_min:.1f} min", notify=True) intersection_start = None def check_online_periodically(vk_session, user_ids): global online_status, session_start while True: try: time.sleep(CHECK_INTERVAL) users = vk_session.method('users.get', { 'user_ids': ','.join(map(str, user_ids)), 'fields': 'online, online_app' }) status_changed = False for user in users: uid = user['id'] is_online = bool(user.get('online', 0)) online_app = user.get('online_app', 0) app_name = get_app_name(online_app) if uid not in online_status: online_status[uid] = None if online_status[uid] != is_online: status_changed = True status_text = "up" if is_online else "down" label = get_node_label(uid) if is_online: session_start[uid] = datetime.now() write_log(f"heartbeat {label} {status_text} [{app_name}]", notify=True) else: if uid in session_start: duration = (datetime.now() - session_start[uid]).total_seconds() duration_min = duration / 60 write_log(f"heartbeat {label} {status_text} (uptime {duration_min:.1f} min, {app_name})", notify=True) del session_start[uid] else: write_log(f"heartbeat {label} {status_text} [{app_name}]", notify=True) online_status[uid] = is_online if status_changed: check_intersection() except Exception as e: write_log(f"poll error: {e}") time.sleep(5) def main(): global online_status, session_start, user_names, user_ids, node_labels if not VK_TOKEN: print("VK_TOKEN is not set in .env") sys.exit(1) if not USER_IDS: print("USER_IDS is empty in .env") sys.exit(1) if NOTIFY_ENABLED and NOTIFY_PEER_ID == 0: print("NOTIFY_PEER_ID is 0, notifications will not work") write_log("service start") write_log(f"targets: {len(USER_IDS)}") write_log(f"interval: {CHECK_INTERVAL}s") init_bot() try: vk_session = vk_api.VkApi(token=VK_TOKEN) write_log("auth ok") except Exception as e: write_log(f"auth fail: {e}") sys.exit(1) user_ids = get_user_ids(vk_session, USER_IDS) if not user_ids: write_log("resolve fail") sys.exit(1) node_labels = {uid: f"node-{i+1}" for i, uid in enumerate(user_ids)} labels_list = [get_node_label(uid) for uid in user_ids] write_log(f"watching: {', '.join(labels_list)}") online_status = {uid: None for uid in user_ids} session_start = {} try: users = vk_session.method('users.get', { 'user_ids': ','.join(map(str, user_ids)), 'fields': 'online, online_app' }) for user in users: uid = user['id'] is_online = bool(user.get('online', 0)) online_app = user.get('online_app', 0) app_name = get_app_name(online_app) online_status[uid] = is_online label = get_node_label(uid) status_text = "active" if is_online else "idle" write_log(f"state {label} -> {status_text} [{app_name}]") if is_online: session_start[uid] = datetime.now() except Exception as e: write_log(f"state read error: {e}") check_intersection() check_thread = threading.Thread( target=check_online_periodically, args=(vk_session, user_ids), daemon=True ) check_thread.start() write_log(f"poller started ({CHECK_INTERVAL}s)") try: while True: time.sleep(1) except KeyboardInterrupt: write_log("service stop") sys.exit(0) if __name__ == '__main__': main()