Spaces:
Paused

miracle / core /sync.py
dushyantsingh0
backend stabilisation
e190dbe
Raw History Blame Contribute Delete
8.02 kB
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
)
INTERNAL_ATTACHMENT_PATTERN = re.compile(r'/attachments/([0-9a-fA-F-]{36})/')
async def parse_mentions(content: str, workspace_id: UUID, db: AsyncSession) -> list[dict[str, any]]:
"""
Parses mentions from content. Supports:
1. Structured @[Name](UUID) - modern RichEditor format
2. Structured @[Name](email) - historical/manual format
3. Simple @email - legacy format
"""
if not content:
return []
# 1. Match structured @[Name](email or UUID)
structured_raw = re.findall(r"@\[.*?\]\(([a-fA-F0-9-]{36}|[\w\.-]+@[\w\.-]+\.\w+)\)", content)
# 2. Match simple @email
simple_emails = re.findall(r"(?<!\()@([\w\.-]+@[\w\.-]+\.\w+)", content)
emails = []
uuids = []
from sqlalchemy import func, or_
from models.user import User
from models.user_workspace import UserWorkspace
for match in list(set(structured_raw + simple_emails)):
if "@" in match:
emails.append(match.lower())
else:
try:
uuids.append(UUID(match))
except ValueError:
pass
if not emails and not uuids:
return []
filters = []
if emails:
filters.append(func.lower(User.email).in_(emails))
if uuids:
filters.append(User.id.in_(uuids))
stmt = (
select(User)
.join(UserWorkspace, User.id == UserWorkspace.user_id)
.where(
UserWorkspace.workspace_id == workspace_id,
or_(*filters),
User.deleted_at.is_(None)
)
.distinct()
)
result = await db.execute(stmt)
users = result.scalars().all()
return [{"user_id": str(u.id), "name": u.full_name} for u in users]
async def link_internal_attachments(db: AsyncSession, entity_id: UUID, content: str, entity_type: str = "ticket"):
"""
Scans content for our own attachment IDs and links them to the entity if they are currently unlinked.
This ensures that images pasted into the RichEditor appear in the 'Files' tab.
"""
if not content:
return
matches = INTERNAL_ATTACHMENT_PATTERN.findall(content)
if not matches:
return
attachment_ids = [UUID(m) for m in matches]
from sqlalchemy import update
stmt = (
update(Attachment)
.where(Attachment.id.in_(attachment_ids))
.where(Attachment.ticket_id.is_(None))
.where(Attachment.article_id.is_(None))
)
if entity_type == "ticket":
stmt = stmt.values(ticket_id=entity_id)
else:
stmt = stmt.values(article_id=entity_id)
await db.execute(stmt)
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