260 lines
9.9 KiB
Python
260 lines
9.9 KiB
Python
import os
|
|
import uuid
|
|
import shutil
|
|
import base64
|
|
import logging
|
|
import httpx
|
|
from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Body
|
|
from typing import Dict, Any, List, Optional
|
|
from pydantic import BaseModel
|
|
|
|
from app.core.config.Config import settings
|
|
from app.core.integrations.meta_graph_service import meta_service, UPLOAD_DIR
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
router = APIRouter(
|
|
prefix="/api/v1/social/meta",
|
|
tags=["Social Media Management"]
|
|
)
|
|
|
|
class SocialPublishRequest(BaseModel):
|
|
platforms: Optional[List[str]] = None
|
|
target: Optional[str] = None # "all" | "both" | "instagram" | "facebook" | "whatsapp"
|
|
text: Optional[str] = None
|
|
caption: Optional[str] = None
|
|
media_url: Optional[str] = None
|
|
media_type: Optional[str] = "IMAGE" # "IMAGE" | "VIDEO"
|
|
mode: str = "POST" # "POST" | "REEL" | "STORY" | "STATUS"
|
|
filter: Optional[str] = None
|
|
schedule_at: Optional[str] = None
|
|
|
|
def dispatch_whatsapp_status(text: str, media_url: Optional[str] = None, media_type: Optional[str] = "IMAGE") -> Dict[str, Any]:
|
|
"""Posts a status update to WhatsApp via self-hosted OpenWA Gateway (:8088)."""
|
|
headers = {
|
|
"X-Api-Key": settings.OPENWA_MASTER_KEY,
|
|
"Content-Type": "application/json"
|
|
}
|
|
session_id = "default"
|
|
|
|
try:
|
|
with httpx.Client(timeout=10.0) as client:
|
|
# 1. Check sessions to get current session ID & state
|
|
sess_res = client.get(f"{settings.OPENWA_GATEWAY_URL}/api/sessions", headers=headers)
|
|
session_status = "UNKNOWN"
|
|
if sess_res.status_code == 200:
|
|
sessions = sess_res.json()
|
|
matching = next((s for s in sessions if s.get("name") == session_id or s.get("id") == session_id), None)
|
|
if matching:
|
|
session_status = matching.get("status", "READY").upper()
|
|
session_id = matching.get("id", session_id)
|
|
|
|
# 2. If media is provided, post image/video status
|
|
if media_url:
|
|
is_video = (media_type or "").upper() == "VIDEO" or any(media_url.lower().endswith(ext) for ext in [".mp4", ".mov", ".m4v"])
|
|
endpoint = f"{settings.OPENWA_GATEWAY_URL}/api/sessions/{session_id}/status/{'send-video' if is_video else 'send-image'}"
|
|
|
|
# Check if file exists locally in UPLOAD_DIR
|
|
filename = os.path.basename(media_url)
|
|
local_path = os.path.join(UPLOAD_DIR, filename)
|
|
|
|
if os.path.exists(local_path):
|
|
with open(local_path, "rb") as f:
|
|
b64_data = base64.b64encode(f.read()).decode("utf-8")
|
|
mime = "video/mp4" if is_video else "image/jpeg"
|
|
if filename.endswith(".png"):
|
|
mime = "image/png"
|
|
elif filename.endswith(".webp"):
|
|
mime = "image/webp"
|
|
payload = {
|
|
"video" if is_video else "image": {
|
|
"base64": b64_data,
|
|
"mimetype": mime
|
|
},
|
|
"caption": text
|
|
}
|
|
else:
|
|
payload = {
|
|
"video" if is_video else "image": {
|
|
"url": media_url
|
|
},
|
|
"caption": text
|
|
}
|
|
|
|
res = client.post(endpoint, json=payload, headers=headers)
|
|
if res.status_code in (200, 201):
|
|
return {
|
|
"success": True,
|
|
"channel": "whatsapp",
|
|
"type": "media_status",
|
|
"data": res.json()
|
|
}
|
|
else:
|
|
return {
|
|
"success": False,
|
|
"channel": "whatsapp",
|
|
"status_code": res.status_code,
|
|
"error": res.text,
|
|
"session_state": session_status
|
|
}
|
|
else:
|
|
# 3. Post text status
|
|
endpoint = f"{settings.OPENWA_GATEWAY_URL}/api/sessions/{session_id}/status/send-text"
|
|
res = client.post(endpoint, json={"text": text, "backgroundColor": "#128C7E"}, headers=headers)
|
|
if res.status_code in (200, 201):
|
|
return {
|
|
"success": True,
|
|
"channel": "whatsapp",
|
|
"type": "text_status",
|
|
"data": res.json()
|
|
}
|
|
else:
|
|
return {
|
|
"success": False,
|
|
"channel": "whatsapp",
|
|
"status_code": res.status_code,
|
|
"error": res.text,
|
|
"session_state": session_status
|
|
}
|
|
except Exception as e:
|
|
logger.error(f"WhatsApp status dispatch error: {e}")
|
|
return {
|
|
"success": False,
|
|
"channel": "whatsapp",
|
|
"error": str(e)
|
|
}
|
|
|
|
@router.get("/status")
|
|
def get_social_status():
|
|
"""Verify Meta configuration and OpenWA WhatsApp status."""
|
|
meta_health = meta_service.check_token_health()
|
|
|
|
# Query OpenWA Gateway status
|
|
wa_health: Dict[str, Any] = {
|
|
"connected": False,
|
|
"status": "OFFLINE",
|
|
"gateway_url": settings.OPENWA_GATEWAY_URL
|
|
}
|
|
try:
|
|
with httpx.Client(timeout=3.0) as client:
|
|
headers = {"X-Api-Key": settings.OPENWA_MASTER_KEY}
|
|
res = client.get(f"{settings.OPENWA_GATEWAY_URL}/api/sessions", headers=headers)
|
|
if res.status_code == 200:
|
|
sessions = res.json()
|
|
matching = next((s for s in sessions if s.get("name") == "default" or s.get("id") == "default"), None)
|
|
if matching:
|
|
st = matching.get("status", "READY").upper()
|
|
wa_health = {
|
|
"connected": st in ("CONNECTED", "READY", "AUTHENTICATED"),
|
|
"status": st,
|
|
"session_id": matching.get("id"),
|
|
"session_name": matching.get("name"),
|
|
"phone": matching.get("phone"),
|
|
"pushName": matching.get("pushName")
|
|
}
|
|
except Exception as e:
|
|
wa_health["error"] = str(e)
|
|
|
|
return {
|
|
"enabled": settings.META_ENABLED,
|
|
"api_version": "v22.0",
|
|
"app_id": settings.META_APP_ID,
|
|
"page_id": settings.FACEBOOK_PAGE_ID,
|
|
"instagram_id": settings.INSTAGRAM_BUSINESS_ACCOUNT_ID,
|
|
"token_health": meta_health,
|
|
"whatsapp": wa_health
|
|
}
|
|
|
|
@router.get("/instagram/posts")
|
|
def get_instagram_posts():
|
|
"""Fetch recent Instagram posts and engagement analytics."""
|
|
posts = meta_service.get_instagram_insights()
|
|
return {
|
|
"status": "success",
|
|
"count": len(posts),
|
|
"data": posts
|
|
}
|
|
|
|
@router.get("/facebook/posts")
|
|
def get_facebook_posts():
|
|
"""Fetch recent Facebook page posts and engagement metrics."""
|
|
posts = meta_service.get_facebook_posts()
|
|
return {
|
|
"status": "success",
|
|
"count": len(posts),
|
|
"data": posts
|
|
}
|
|
|
|
@router.post("/upload")
|
|
async def upload_social_media(file: UploadFile = File(...)):
|
|
"""Upload media locally for use in social posts."""
|
|
if not file.content_type.startswith(("image/", "video/")):
|
|
raise HTTPException(status_code=400, detail="Only image and video files are supported")
|
|
|
|
file_ext = os.path.splitext(file.filename)[1] or ".jpg"
|
|
safe_name = f"{uuid.uuid4().hex[:12]}{file_ext}"
|
|
file_path = os.path.join(UPLOAD_DIR, safe_name)
|
|
|
|
with open(file_path, "wb") as buffer:
|
|
shutil.copyfileobj(file.file, buffer)
|
|
|
|
local_url = f"/uploads/social/{safe_name}"
|
|
public_url = f"https://ifixkartbe.trionixsolution.com/uploads/social/{safe_name}"
|
|
return {
|
|
"status": "success",
|
|
"url": local_url,
|
|
"remote_url": public_url,
|
|
"filename": safe_name
|
|
}
|
|
|
|
@router.post("/publish")
|
|
def publish_to_social(req: SocialPublishRequest):
|
|
"""Publish a post simultaneously across Instagram, Facebook, and WhatsApp."""
|
|
resolved_text = (req.caption or req.text or "").strip()
|
|
if not resolved_text:
|
|
raise HTTPException(status_code=400, detail="Post text/caption cannot be empty")
|
|
|
|
# Resolve platforms from platforms list or target parameter
|
|
platforms: List[str] = []
|
|
if req.platforms:
|
|
platforms = [p.lower() for p in req.platforms]
|
|
elif req.target:
|
|
t = req.target.lower()
|
|
if t in ("all", "all_platforms"):
|
|
platforms = ["instagram", "facebook", "whatsapp"]
|
|
elif t in ("both", "meta"):
|
|
platforms = ["instagram", "facebook"]
|
|
elif t in ("instagram", "facebook", "whatsapp"):
|
|
platforms = [t]
|
|
|
|
if not platforms:
|
|
raise HTTPException(status_code=400, detail="At least one publishing platform (instagram, facebook, whatsapp) must be selected")
|
|
|
|
results: Dict[str, Any] = {}
|
|
|
|
# 1. Dispatch to Meta (Instagram & Facebook)
|
|
meta_platforms = [p for p in platforms if p in ("instagram", "facebook")]
|
|
if meta_platforms:
|
|
meta_results = meta_service.publish_post(
|
|
platforms=meta_platforms,
|
|
text=resolved_text,
|
|
media_url=req.media_url,
|
|
mode=req.mode
|
|
)
|
|
results.update(meta_results)
|
|
|
|
# 2. Dispatch to WhatsApp Status via OpenWA
|
|
if "whatsapp" in platforms:
|
|
wa_result = dispatch_whatsapp_status(
|
|
text=resolved_text,
|
|
media_url=req.media_url,
|
|
media_type=req.media_type
|
|
)
|
|
results["whatsapp"] = wa_result
|
|
|
|
return {
|
|
"status": "success",
|
|
"message": f"Published to {len(results)} channel(s)",
|
|
"results": results
|
|
}
|
|
|