Spaces:
Paused

File size: 8,024 Bytes
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2bb9807
 
e190dbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2bb9807
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5eb4857
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
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