Commit a6098676 authored by Aryan Noshirvani's avatar Aryan Noshirvani

Fix telegram_worker import path and include social router

parent d9ae9fba
......@@ -7,7 +7,7 @@ from fastapi.openapi.utils import get_openapi
from fastapi.security import APIKeyCookie
from fastapi.staticfiles import StaticFiles
from src.api.routers import auth, discovery, library, music
from src.api.routers import auth, discovery, library, music, social
os.makedirs("/root/antigrav-stax-audio/downloads", exist_ok=True)
os.makedirs("/root/antigrav-stax-audio/temp", exist_ok=True)
......@@ -27,6 +27,7 @@ app.include_router(auth.router)
app.include_router(discovery.router)
app.include_router(library.router)
app.include_router(music.router)
app.include_router(social.router)
@app.get("/", response_class=HTMLResponse, include_in_schema=False)
async def login_get(request: Request):
......
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel
from sqlalchemy.orm import Session
from src.core.database import get_db, User, Post, GeoDrop, LiveRoom
from datetime import datetime, timezone
import math
router = APIRouter(
prefix="/social",
tags=["social"],
)
# --- Schemas ---
class PostCreate(BaseModel):
user_id: int
song_id: int
parent_post_id: int = None
caption: str = ""
class GeoDropCreate(BaseModel):
user_id: int
song_id: int
latitude: float
longitude: float
class LiveRoomCreate(BaseModel):
dj_id: int
name: str
# --- Endpoints ---
@router.post("/posts", status_code=status.HTTP_201_CREATED)
def create_post(post: PostCreate, db: Session = Depends(get_db)):
db_post = Post(**post.dict())
db.add(db_post)
db.commit()
db.refresh(db_post)
return db_post
@router.get("/posts/{post_id}/tree")
def get_remix_tree(post_id: int, db: Session = Depends(get_db)):
post = db.query(Post).filter(Post.id == post_id).first()
if not post:
raise HTTPException(status_code=404, detail="Post not found")
children = db.query(Post).filter(Post.parent_post_id == post_id).all()
return {
"post": post,
"children": children
}
@router.post("/geo-drop", status_code=status.HTTP_201_CREATED)
def create_geo_drop(drop: GeoDropCreate, db: Session = Depends(get_db)):
db_drop = GeoDrop(**drop.dict())
db.add(db_drop)
db.commit()
db.refresh(db_drop)
return db_drop
@router.get("/geo-drop/nearby")
def get_nearby_drops(lat: float, lon: float, radius_km: float = 1.0, db: Session = Depends(get_db)):
all_drops = db.query(GeoDrop).all()
nearby = []
def haversine(lat1, lon1, lat2, lon2):
R = 6371.0 # Earth radius in kilometers
dlat = math.radians(lat2 - lat1)
dlon = math.radians(lon2 - lon1)
a = math.sin(dlat / 2)**2 + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(dlon / 2)**2
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
distance = R * c
return distance
for drop in all_drops:
if drop.latitude and drop.longitude:
dist = haversine(lat, lon, drop.latitude, drop.longitude)
if dist <= radius_km:
nearby.append({"drop": drop, "distance_km": dist})
return sorted(nearby, key=lambda x: x["distance_km"])
@router.post("/rooms", status_code=status.HTTP_201_CREATED)
def create_live_room(room: LiveRoomCreate, db: Session = Depends(get_db)):
db_room = LiveRoom(**room.dict())
db.add(db_room)
db.commit()
db.refresh(db_room)
return db_room
@router.get("/rooms")
def get_active_rooms(db: Session = Depends(get_db)):
rooms = db.query(LiveRoom).filter(LiveRoom.is_active == True).all()
return rooms
from database import *
import os
from sqlalchemy import create_engine, Column, Integer, String, DateTime, ForeignKey, Boolean, Float
from sqlalchemy.orm import declarative_base, sessionmaker
from datetime import datetime, timezone
DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./stax.db")
db_dir = os.path.dirname(DATABASE_URL.replace("sqlite:///", ""))
if db_dir and not os.path.exists(db_dir):
os.makedirs(db_dir, exist_ok=True)
engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False})
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
username = Column(String, unique=True, index=True)
class DiscoveredSong(Base):
__tablename__ = "discovered_songs"
id = Column(Integer, primary_key=True, index=True)
title = Column(String, index=True)
artist = Column(String, index=True)
genre = Column(String)
coverart = Column(String)
detected_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
liked = Column(Boolean, default=None, nullable=True)
class LibrarySong(Base):
__tablename__ = "library_songs"
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, ForeignKey("users.id"), index=True)
title = Column(String, index=True)
artist = Column(String, index=True)
album = Column(String)
genre = Column(String)
coverart = Column(String)
lyrics = Column(String)
file_path = Column(String)
added_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class Playlist(Base):
__tablename__ = "playlists"
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, ForeignKey("users.id"), index=True)
name = Column(String)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class PlaylistTrack(Base):
__tablename__ = "playlist_tracks"
id = Column(Integer, primary_key=True, index=True)
playlist_id = Column(Integer, ForeignKey("playlists.id"), index=True)
song_id = Column(Integer, ForeignKey("library_songs.id"))
order = Column(Integer)
class UserProfile(Base):
__tablename__ = "user_profiles"
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, ForeignKey("users.id"), unique=True, index=True)
bio = Column(String)
avatar_url = Column(String)
class Follow(Base):
__tablename__ = "follows"
id = Column(Integer, primary_key=True, index=True)
follower_id = Column(Integer, ForeignKey("users.id"), index=True)
following_id = Column(Integer, ForeignKey("users.id"), index=True)
class Post(Base):
__tablename__ = "posts"
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, ForeignKey("users.id"), index=True)
song_id = Column(Integer, ForeignKey("library_songs.id"))
parent_post_id = Column(Integer, ForeignKey("posts.id"), nullable=True)
caption = Column(String)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class GeoDrop(Base):
__tablename__ = "geo_drops"
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, ForeignKey("users.id"), index=True)
song_id = Column(Integer, ForeignKey("library_songs.id"))
latitude = Column(Float)
longitude = Column(Float)
dropped_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
class LiveRoom(Base):
__tablename__ = "live_rooms"
id = Column(Integer, primary_key=True, index=True)
dj_id = Column(Integer, ForeignKey("users.id"), index=True)
current_song_id = Column(Integer, ForeignKey("library_songs.id"), nullable=True)
name = Column(String)
is_active = Column(Boolean, default=True)
created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc))
Base.metadata.create_all(bind=engine)
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
# telegram_worker package initialization
from pyrogram import Client
from typing import Dict
import os
API_ID = int(os.getenv("TELEGRAM_API_ID", "2040")) # Fallback to official android app dummy
API_HASH = os.getenv("TELEGRAM_API_HASH", "b18441a1ff607e10a989891a5462e627")
# In-memory store for ongoing auth sessions
auth_clients: Dict[str, Client] = {}
async def request_code(phone_number: str):
client = Client(f"session_{phone_number.replace('+', '')}", api_id=API_ID, api_hash=API_HASH, in_memory=True)
await client.connect()
try:
sent_code = await client.send_code(phone_number)
auth_clients[phone_number] = client
return {"phone_code_hash": sent_code.phone_code_hash, "is_registered": True}
except Exception as e:
await client.disconnect()
raise e
async def login(phone_number: str, phone_code_hash: str, code: str):
if phone_number not in auth_clients:
raise Exception("Session expired or not found. Please request a new code.")
client = auth_clients[phone_number]
try:
signed_in = await client.sign_in(phone_number, phone_code_hash, code)
session_string = await client.export_session_string()
await client.disconnect()
del auth_clients[phone_number]
return {"session_string": session_string, "user_id": signed_in.id}
except Exception as e:
await client.disconnect()
del auth_clients[phone_number]
raise e
from pyrogram import Client
from pyrogram.enums import ChatType
import os
API_ID = int(os.getenv("TELEGRAM_API_ID", "2040"))
API_HASH = os.getenv("TELEGRAM_API_HASH", "b18441a1ff607e10a989891a5462e627")
async def get_chats(session_string: str):
client = Client("temp_session", session_string=session_string, api_id=API_ID, api_hash=API_HASH, in_memory=True)
await client.connect()
chats = []
try:
async for dialog in client.get_dialogs():
chats.append({
"id": dialog.chat.id,
"title": dialog.chat.title or dialog.chat.first_name,
"type": dialog.chat.type.value
})
finally:
await client.disconnect()
return chats
async def get_chat_music(session_string: str, chat_id: int, limit: int = 50):
client = Client("temp_session", session_string=session_string, api_id=API_ID, api_hash=API_HASH, in_memory=True)
await client.connect()
music = []
try:
async for message in client.search_messages(chat_id, filter="audio", limit=limit):
if message.audio:
music.append({
"message_id": message.id,
"title": message.audio.title or "Unknown Title",
"artist": message.audio.performer or "Unknown Artist",
"duration": message.audio.duration,
"file_name": message.audio.file_name
})
finally:
await client.disconnect()
return music
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment