Spaces:
Sleeping
Sleeping
Download db.py from xkailashhh/postingbot: direct link, hf CLI and curl.
- Browser
- Download file 13.9 kB
-
https://huggingface.co/spaces/xkailashhh/postingbot/resolve/main/db.py
- Command line
-
hf download hf://spaces/xkailashhh/postingbot/db.py
-
curl -L -o db.py https://huggingface.co/spaces/xkailashhh/postingbot/resolve/main/db.py
13.9 kB
| """ | |
| db.py – MongoDB async client (Motor). All DB operations live here. | |
| """ | |
| from __future__ import annotations | |
| import re | |
| from datetime import datetime | |
| from typing import Any, Optional, List, Dict | |
| from bson import ObjectId | |
| from motor.motor_asyncio import AsyncIOMotorClient, AsyncIOMotorDatabase | |
| from pymongo import ASCENDING, DESCENDING, IndexModel | |
| from pymongo.errors import DuplicateKeyError | |
| import config | |
| _client: Optional[AsyncIOMotorClient] = None | |
| # ---------- Client ---------- | |
| def get_client() -> AsyncIOMotorClient: | |
| global _client | |
| if _client is None: | |
| _client = AsyncIOMotorClient(config.MONGO_URI) | |
| return _client | |
| def get_db() -> AsyncIOMotorDatabase: | |
| return get_client()[config.MONGO_DB_NAME] | |
| async def close_client(): | |
| global _client | |
| if _client: | |
| _client.close() | |
| _client = None | |
| # ---------- Collection accessors ---------- | |
| def posts_col(): return get_db()["posts"] | |
| def unlocks_col(): return get_db()["unlocks"] | |
| def views_col(): return get_db()["views"] | |
| def settings_col(): return get_db()["admin_settings"] | |
| def sessions_col(): return get_db()["owner_sessions"] | |
| def users_col(): return get_db()["users"] | |
| def channels_col(): return get_db()["channels"] # unified channels | |
| # ---------- Index creation ---------- | |
| async def ensure_indexes(): | |
| """Create all necessary indexes for the database""" | |
| # Posts | |
| existing = await posts_col().index_information() | |
| if 'caption_text' in existing: | |
| await posts_col().drop_index('caption_text') | |
| await posts_col().create_indexes([ | |
| IndexModel([("magical_hash", ASCENDING)], unique=True), | |
| IndexModel([("is_active", ASCENDING)]), | |
| IndexModel([("created_at", DESCENDING)]), | |
| IndexModel([("category", ASCENDING)]), | |
| IndexModel([("caption", "text"), ("category", "text")]), | |
| ]) | |
| # Unlocks | |
| await unlocks_col().create_indexes([ | |
| IndexModel([("post_id", ASCENDING), ("telegram_id", ASCENDING)], unique=True), | |
| ]) | |
| # Views | |
| await views_col().create_indexes([ | |
| IndexModel([("post_id", ASCENDING)]), | |
| IndexModel([("viewed_at", DESCENDING)]), | |
| ]) | |
| # Settings | |
| await settings_col().create_indexes([ | |
| IndexModel([("key", ASCENDING)], unique=True), | |
| ]) | |
| # Sessions | |
| await sessions_col().create_indexes([ | |
| IndexModel([("session_token", ASCENDING)], unique=True), | |
| IndexModel([("created_at", ASCENDING)]), | |
| ]) | |
| # Users | |
| await users_col().create_indexes([ | |
| IndexModel([("telegram_id", ASCENDING)], unique=True), | |
| ]) | |
| # Channels (unified) | |
| await channels_col().create_indexes([ | |
| IndexModel([("channel_id", ASCENDING), ("type", ASCENDING)], unique=True), | |
| IndexModel([("type", ASCENDING)]), | |
| IndexModel([("is_active", ASCENDING)]), | |
| ]) | |
| # Seed default settings | |
| defaults = [ | |
| ("default_ads", str(config.DEFAULT_ADS)), | |
| ("admin_password_hash", ""), | |
| ("premium_link", ""), | |
| ("popunder_urls", "[]"), | |
| ("extra_owners", "[]"), | |
| ("fsub_timeout", str(config.DEFAULT_FSUB_TIMEOUT)), | |
| ] | |
| for key, val in defaults: | |
| await settings_col().update_one( | |
| {"key": key}, | |
| {"$setOnInsert": {"key": key, "value": val}}, | |
| upsert=True, | |
| ) | |
| print("[DB] Indexes ensured.") | |
| # ---------- POSTS ---------- | |
| async def create_post(magical_hash, image_url, caption, redirect_link, required_ads, category=""): | |
| doc = { | |
| "magical_hash": magical_hash, | |
| "image_url": image_url, | |
| "caption": caption, | |
| "redirect_link": redirect_link, | |
| "required_ads": required_ads, | |
| "category": category, | |
| "created_at": datetime.utcnow(), | |
| "is_active": True, | |
| } | |
| result = await posts_col().insert_one(doc) | |
| doc["_id"] = result.inserted_id | |
| return doc | |
| async def get_post_by_hash(magical_hash: str) -> Optional[dict]: | |
| return await posts_col().find_one({"magical_hash": magical_hash, "is_active": True}) | |
| async def get_post_by_hash_any(magical_hash: str) -> Optional[dict]: | |
| """Return post even if soft‑deleted (needed for deletion commands).""" | |
| return await posts_col().find_one({"magical_hash": magical_hash}) | |
| async def get_post_by_id(post_id: Any) -> Optional[dict]: | |
| return await posts_col().find_one({"_id": ObjectId(str(post_id))}) | |
| async def update_post(post_id: Any, updates: dict) -> bool: | |
| r = await posts_col().update_one({"_id": ObjectId(str(post_id))}, {"$set": updates}) | |
| return r.modified_count > 0 | |
| async def soft_delete_post(post_id: Any) -> bool: | |
| return await update_post(post_id, {"is_active": False}) | |
| async def search_posts(query: str = "", limit: int = 100) -> list[dict]: | |
| projection = {"redirect_link": 0} | |
| if not query.strip(): | |
| cursor = posts_col().find({"is_active": True}, projection).sort("created_at", DESCENDING).limit(limit) | |
| return await cursor.to_list(length=limit) | |
| # Try text search first | |
| try: | |
| cursor = posts_col().find( | |
| {"$text": {"$search": query}, "is_active": True}, | |
| {**projection, "score": {"$meta": "textScore"}}, | |
| ).sort([("score", {"$meta": "textScore"})]).limit(limit) | |
| results = await cursor.to_list(length=limit) | |
| if results: | |
| return results | |
| except Exception: | |
| pass | |
| # Fallback regex | |
| pattern = re.compile(re.escape(query), re.IGNORECASE) | |
| cursor = posts_col().find( | |
| {"is_active": True, "$or": [{"caption": pattern}, {"category": pattern}]}, | |
| projection, | |
| ).sort("created_at", DESCENDING).limit(limit) | |
| return await cursor.to_list(length=limit) | |
| async def count_active_posts() -> int: | |
| return await posts_col().count_documents({"is_active": True}) | |
| async def list_all_posts_admin(limit: int = 500) -> list[dict]: | |
| """Only active posts (soft‑deleted excluded).""" | |
| return await posts_col().find({"is_active": True}).sort("created_at", DESCENDING).limit(limit).to_list(length=limit) | |
| async def get_categories() -> list[dict]: | |
| pipeline = [ | |
| {"$match": {"is_active": True, "category": {"$nin": [None, ""]}}}, | |
| {"$group": {"_id": "$category", "count": {"$sum": 1}}}, | |
| {"$sort": {"count": DESCENDING}}, | |
| ] | |
| results = await posts_col().aggregate(pipeline).to_list(length=50) | |
| return [{"id": r["_id"], "name": r["_id"], "count": r["count"]} for r in results] | |
| # ---------- UNLOCKS ---------- | |
| async def has_unlocked(post_id: Any, telegram_id: int) -> bool: | |
| return bool(await unlocks_col().find_one({"post_id": str(post_id), "telegram_id": telegram_id})) | |
| async def record_unlock(post_id: Any, telegram_id: int, ip_address: str) -> bool: | |
| try: | |
| await unlocks_col().insert_one({ | |
| "post_id": str(post_id), | |
| "telegram_id": telegram_id, | |
| "ip_address": ip_address, | |
| "unlocked_at": datetime.utcnow(), | |
| }) | |
| return True | |
| except DuplicateKeyError: | |
| return False | |
| async def unlock_count(post_id: Any) -> int: | |
| return await unlocks_col().count_documents({"post_id": str(post_id)}) | |
| async def total_unlocks() -> int: | |
| return await unlocks_col().count_documents({}) | |
| async def unique_users() -> int: | |
| return len(await unlocks_col().distinct("telegram_id")) | |
| # ---------- VIEWS ---------- | |
| async def record_view(post_id: Any, telegram_id: Optional[int], ip_address: str): | |
| await views_col().insert_one({ | |
| "post_id": str(post_id), | |
| "telegram_id": telegram_id, | |
| "ip_address": ip_address, | |
| "viewed_at": datetime.utcnow(), | |
| }) | |
| async def view_count(post_id: Any) -> int: | |
| return await views_col().count_documents({"post_id": str(post_id)}) | |
| async def total_views() -> int: | |
| return await views_col().count_documents({}) | |
| # ---------- CHANNELS (unified) ---------- | |
| async def add_channel( | |
| channel_id: str, | |
| channel_name: str, | |
| added_by: int, | |
| channel_type: str, # "request" or "posting" | |
| invite_link: str = "", | |
| is_active: bool = True | |
| ) -> bool: | |
| """Add a channel. Returns True if added, False if duplicate.""" | |
| try: | |
| await channels_col().insert_one({ | |
| "channel_id": channel_id, | |
| "channel_name": channel_name, | |
| "added_by": added_by, | |
| "type": channel_type, | |
| "invite_link": invite_link, | |
| "last_updated": datetime.utcnow(), | |
| "is_active": is_active, | |
| }) | |
| return True | |
| except DuplicateKeyError: | |
| return False | |
| async def remove_channel(channel_id: str, channel_type: str) -> bool: | |
| """Permanently delete a channel (by ID and type).""" | |
| result = await channels_col().delete_one({"channel_id": channel_id, "type": channel_type}) | |
| return result.deleted_count > 0 | |
| async def remove_all_channels(channel_type: Optional[str] = None) -> int: | |
| """ | |
| Delete channels from the unified channels collection. | |
| - If channel_type is provided (e.g., "request" or "posting"), deletes only those. | |
| - If channel_type is None, deletes ALL channels. | |
| Returns the number of deleted documents. | |
| """ | |
| query = {} | |
| if channel_type: | |
| query["type"] = channel_type | |
| result = await channels_col().delete_many(query) | |
| return result.deleted_count | |
| async def update_channel_invite_link(channel_id: str, channel_type: str, new_link: str): | |
| """Update invite link and refresh last_updated.""" | |
| await channels_col().update_one( | |
| {"channel_id": channel_id, "type": channel_type}, | |
| {"$set": {"invite_link": new_link, "last_updated": datetime.utcnow()}} | |
| ) | |
| async def update_channel_last_updated(channel_id: str, channel_type: str): | |
| """Refresh the last_updated timestamp without changing link.""" | |
| await channels_col().update_one( | |
| {"channel_id": channel_id, "type": channel_type}, | |
| {"$set": {"last_updated": datetime.utcnow()}} | |
| ) | |
| async def get_channel(channel_id: str, channel_type: str) -> Optional[dict]: | |
| """Get a single channel by ID and type.""" | |
| return await channels_col().find_one({"channel_id": channel_id, "type": channel_type}) | |
| async def get_channels(channel_type: Optional[str] = None, include_inactive: bool = False) -> list[dict]: | |
| """ | |
| Get all channels (optionally filtered by type). | |
| - If include_inactive=True, returns all; otherwise only active ones. | |
| """ | |
| query = {} | |
| if channel_type: | |
| query["type"] = channel_type | |
| if not include_inactive: | |
| query["is_active"] = True | |
| cursor = channels_col().find(query).sort("last_updated", DESCENDING) | |
| return await cursor.to_list(length=None) | |
| async def count_channels(channel_type: Optional[str] = None) -> int: | |
| """Count active channels (optionally by type).""" | |
| query = {"is_active": True} | |
| if channel_type: | |
| query["type"] = channel_type | |
| return await channels_col().count_documents(query) | |
| async def set_channel_active(channel_id: str, channel_type: str, active: bool) -> bool: | |
| """Set channel active/inactive without deleting.""" | |
| result = await channels_col().update_one( | |
| {"channel_id": channel_id, "type": channel_type}, | |
| {"$set": {"is_active": active, "last_updated": datetime.utcnow()}} | |
| ) | |
| return result.modified_count > 0 | |
| # ---------- Legacy force‑sub compatibility (using new channels) ---------- | |
| async def get_force_sub_channels() -> list[dict]: | |
| """Legacy: returns all active 'request' channels.""" | |
| return await get_channels(channel_type="request", include_inactive=False) | |
| async def add_force_sub_channel(channel_id: str, invite_link: str = "") -> bool: | |
| return await add_channel(channel_id, channel_id, 0, "request", invite_link) | |
| async def remove_force_sub_channel(channel_id: str) -> bool: | |
| """Legacy: removes 'request' channel.""" | |
| return await remove_channel(channel_id, "request") | |
| async def add_posting_channel(channel_id: str, channel_name: str, invite_link: str = "") -> bool: | |
| """Convenience wrapper: add a posting channel.""" | |
| return await add_channel(channel_id, channel_name, 0, "posting", invite_link) | |
| # ---------- SETTINGS ---------- | |
| async def get_setting(key: str, default: str = "") -> str: | |
| doc = await settings_col().find_one({"key": key}) | |
| return doc["value"] if doc else default | |
| async def set_setting(key: str, value: str): | |
| await settings_col().update_one({"key": key}, {"$set": {"key": key, "value": value}}, upsert=True) | |
| # ---------- SESSIONS ---------- | |
| async def create_session(token: str): | |
| await sessions_col().insert_one({"session_token": token, "created_at": datetime.utcnow()}) | |
| async def get_session(token: str) -> Optional[dict]: | |
| return await sessions_col().find_one({"session_token": token}) | |
| async def delete_session(token: str): | |
| await sessions_col().delete_one({"session_token": token}) | |
| # ---------- USERS ---------- | |
| async def record_user(telegram_id: int, first_name: str, username: str = ""): | |
| await users_col().update_one( | |
| {"telegram_id": telegram_id}, | |
| {"$set": {"first_name": first_name, "username": username, "last_seen": datetime.utcnow()}}, | |
| upsert=True, | |
| ) | |
| async def remove_user(telegram_id: int) -> bool: | |
| result = await users_col().delete_one({"telegram_id": telegram_id}) | |
| return result.deleted_count > 0 | |
| async def get_all_users() -> List[Dict]: | |
| return await users_col().find().to_list(length=None) | |
| # ---------- HELPERS ---------- | |
| def get_collection(name: str): | |
| return get_db()[name] | |
| def serialize(doc: dict) -> dict: | |
| if not doc: | |
| return {} | |
| result = {} | |
| for k, v in doc.items(): | |
| if k == "_id": | |
| result["id"] = str(v) | |
| elif k == "score": | |
| continue | |
| elif hasattr(v, "isoformat"): | |
| result[k] = v.isoformat() | |
| else: | |
| result[k] = v | |
| return result |