import httpx import re import mimetypes from uuid import UUID, uuid4 from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy import select from models.attachment import Attachment from core.storage import get_storage_provider from core.logging import get_logger logger = get_logger(__name__) # Comprehensive pattern for images: Markdown ![alt](url) OR raw URLs ending in extensions # Matches: # 1. ![alt text](https://url) # 2. https://url.jpg, .png, .jpeg, .webp, .gif (even without markdown) IMAGE_PATTERN = re.compile( r'(?:!\[.*?\]\((https?://[^\s\)]+)\))|' r'(https?://[^\s\)]+(?:\.jpg|\.jpeg|\.png|\.webp|\.gif)(?:\?[^\s\)]*)?)', re.IGNORECASE ) async def sync_markdown_images(db: AsyncSession, entity_id: UUID, workspace_id: UUID, content: str, entity_type: str = "ticket", uploader_id: UUID = None): """ Parses content for external images (Markdown or raw URLs), downloads them, and saves them as formal Attachment records. """ if not content: return [] # findall returns a list of tuples for multiple capturing groups matches = IMAGE_PATTERN.findall(content) # Flatten matches and filter out empty strings urls = [url for group in matches for url in group if url] if not urls: return [] new_attachments = [] storage = get_storage_provider() # Use a real browser user agent to avoid being blocked by Pexels/Unsplash/etc. headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36" } async with httpx.AsyncClient(timeout=30.0, follow_redirects=True, headers=headers) as client: for url in set(urls): # Use set to avoid double-processing same URL in one content block try: # 1. Check if already synced for this entity stmt = select(Attachment).where( Attachment.workspace_id == workspace_id, Attachment.source_url == url, Attachment.deleted_at.is_(None) ) # Link to the specific entity type if entity_type == "ticket": stmt = stmt.where(Attachment.ticket_id == entity_id) else: stmt = stmt.where(Attachment.article_id == entity_id) res = await db.execute(stmt) existing = res.scalar_one_or_none() # --- Metadata Recovery Update --- if existing: # If the attachment exists but is missing its source_url (from a previous failed run), # we update it now to ensure full traceability. if not existing.source_url: existing.source_url = url db.add(existing) logger.info(f"Image Sync: Recovered source_url for existing attachment {existing.id}") continue # 2. Download Image logger.info(f"Image Sync: Downloading external image for {entity_type} {entity_id}: {url}") resp = await client.get(url) if resp.status_code != 200: logger.warning(f"Image Sync: Failed to download {url}, status {resp.status_code}") continue # 3. Determine properties content_type = resp.headers.get("Content-Type", "image/png") ext = mimetypes.guess_extension(content_type) or ".png" filename = f"extracted_{uuid4().hex[:8]}{ext}" # 4. Save to Storage (Corrected Signature: bytes, filename, workspace_id) # Note: storage_path is determined internally by the provider storage_res = await storage.upload(resp.content, filename, workspace_id) storage_path = storage_res.path # 5. Create Attachment Record new_att = Attachment( workspace_id=workspace_id, filename=filename, storage_path=storage_path, storage_backend=storage.__class__.__name__.lower().replace("storage", ""), # "local" or "s3" content_type=content_type, file_size=len(resp.content), source_url=url, uploader_id=uploader_id, is_processed=False # Will be picked up by multimodal indexing ) if entity_type == "ticket": new_att.ticket_id = entity_id else: new_att.article_id = entity_id db.add(new_att) new_attachments.append(new_att) logger.info(f"Image Sync: Successfully synced {url} -> {storage_path}") except Exception as e: logger.error(f"Image Sync: Error processing {url}: {e}") if new_attachments: # We flush so IDs are available for multimodal processing in the same task await db.flush() logger.info(f"Image Sync: Successfully created {len(new_attachments)} attachments for {entity_type} {entity_id}") return new_attachments