""" ALLI Community Forums Domain - Business Logic Service Layer """ import html import re import uuid from typing import Dict, Any, List, Optional, Tuple from fastapi import HTTPException, status from .schemas import ( TopicCreateRequest, TopicUpdateRequest, TopicResponse, ReplyCreateRequest, ReplyUpdateRequest, ReplyResponse, TopicDetailResponse, TopicListResponse, ) from .repository import ForumRepository, MongoForumRepository def sanitize_input_text(text: Optional[str]) -> Optional[str]: """Sanitize text against script injection while preserving markdown structure.""" if not text: return text # Strip script and dangerous iframe tags clean = re.sub(r"<\s*script[^>]*>.*?<\s*/\s*script\s*>", "", text, flags=re.DOTALL | re.IGNORECASE) clean = re.sub(r"<\s*iframe[^>]*>.*?<\s*/\s*iframe\s*>", "", clean, flags=re.DOTALL | re.IGNORECASE) clean = re.sub(r"javascript:\s*", "", clean, flags=re.IGNORECASE) return clean.strip() DEFAULT_SEED_TOPICS: List[Dict[str, Any]] = [] class ForumService: """Core domain service for community forum workflows.""" def __init__(self, repository: Optional[ForumRepository] = None): self.repo = repository or MongoForumRepository() self._seeded = False def _ensure_seeded(self): """No mock topics seeded. Keeps forum data real and simple.""" pass # ─── TOPICS ─────────────────────────────────────────────────────────────── def create_topic( self, request: TopicCreateRequest, author_id: str, author_name: str = "Anonymous", author_avatar: Optional[str] = None, ) -> TopicResponse: clean_title = sanitize_input_text(request.title) clean_content = sanitize_input_text(request.content) clean_category = request.category.lower().strip() clean_tags = [re.sub(r"[^a-zA-Z0-9_-]", "", t.lower().strip()) for t in request.tags if t.strip()] doc = { "title": clean_title, "content": clean_content, "author_id": author_id, "author_name": author_name, "author_avatar": author_avatar, "category": clean_category, "tags": clean_tags, } created = self.repo.create_topic(doc) return TopicResponse(**created) def list_topics( self, category: Optional[str] = None, search: Optional[str] = None, tag: Optional[str] = None, page: int = 1, limit: int = 20, sort_by: str = "latest", ) -> TopicListResponse: self._ensure_seeded() docs, total = self.repo.list_topics( category=category, search=search, tag=tag, page=page, limit=limit, sort_by=sort_by, ) total_pages = max(1, (total + limit - 1) // limit) if total > 0 else 1 return TopicListResponse( topics=[TopicResponse(**d) for d in docs], total=total, page=page, limit=limit, total_pages=total_pages, ) def get_topic_detail(self, topic_id: str) -> TopicDetailResponse: topic_doc = self.repo.get_topic(topic_id) if not topic_doc: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"Topic '{topic_id}' was not found.", ) # Increment view count self.repo.increment_views(topic_id) topic_doc["views_count"] = topic_doc.get("views_count", 0) + 1 replies_docs = self.repo.list_replies(topic_id) return TopicDetailResponse( topic=TopicResponse(**topic_doc), replies=[ReplyResponse(**r) for r in replies_docs], ) def update_topic( self, topic_id: str, updates: TopicUpdateRequest, user_id: str, is_admin: bool = False, ) -> TopicResponse: existing = self.repo.get_topic(topic_id) if not existing: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"Topic '{topic_id}' was not found.", ) # Check authorization: author or admin if existing.get("author_id") != user_id and not is_admin: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Not authorized to modify topics created by another user.", ) patch_dict: Dict[str, Any] = {} if updates.title is not None: patch_dict["title"] = sanitize_input_text(updates.title) if updates.content is not None: patch_dict["content"] = sanitize_input_text(updates.content) if updates.category is not None: patch_dict["category"] = updates.category.lower().strip() if updates.tags is not None: patch_dict["tags"] = [re.sub(r"[^a-zA-Z0-9_-]", "", t.lower().strip()) for t in updates.tags if t.strip()] # Moderation fields (admin only) if updates.is_pinned is not None: if not is_admin: raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Admin role required to pin topics.") patch_dict["is_pinned"] = updates.is_pinned if updates.is_locked is not None: if not is_admin: raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Admin role required to lock topics.") patch_dict["is_locked"] = updates.is_locked if updates.status is not None: if not is_admin: raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Admin role required to alter topic status.") patch_dict["status"] = updates.status updated = self.repo.update_topic(topic_id, patch_dict) if not updated: raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Failed to update topic.") return TopicResponse(**updated) def delete_topic(self, topic_id: str, user_id: str, is_admin: bool = False) -> bool: existing = self.repo.get_topic(topic_id) if not existing: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"Topic '{topic_id}' was not found.", ) if existing.get("author_id") != user_id and not is_admin: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Not authorized to delete topics created by another user.", ) return self.repo.delete_topic(topic_id) # ─── REPLIES ────────────────────────────────────────────────────────────── def create_reply( self, topic_id: str, request: ReplyCreateRequest, author_id: str, author_name: str = "Anonymous", author_avatar: Optional[str] = None, ) -> ReplyResponse: topic = self.repo.get_topic(topic_id) if not topic: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"Topic '{topic_id}' does not exist.", ) if topic.get("is_locked", False): raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="This topic has been locked by a moderator. No further replies are allowed.", ) clean_content = sanitize_input_text(request.content) doc = { "topic_id": topic_id, "author_id": author_id, "author_name": author_name, "author_avatar": author_avatar, "content": clean_content, "reply_to_id": request.reply_to_id, } created = self.repo.create_reply(doc) return ReplyResponse(**created) def update_reply( self, reply_id: str, request: ReplyUpdateRequest, user_id: str, is_admin: bool = False, ) -> ReplyResponse: reply = self.repo.get_reply(reply_id) if not reply: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"Reply '{reply_id}' was not found.", ) if reply.get("author_id") != user_id and not is_admin: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Not authorized to edit replies created by another user.", ) clean_content = sanitize_input_text(request.content) updated = self.repo.update_reply(reply_id, {"content": clean_content}) if not updated: raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Failed to update reply.") return ReplyResponse(**updated) def delete_reply(self, reply_id: str, user_id: str, is_admin: bool = False) -> bool: reply = self.repo.get_reply(reply_id) if not reply: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"Reply '{reply_id}' was not found.", ) if reply.get("author_id") != user_id and not is_admin: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Not authorized to delete replies created by another user.", ) return self.repo.delete_reply(reply_id)