Skip to content

OpenRAG is a comprehensive, single package Retrieval-Augmented Generation platform built on Langflow, Docling, and Opensearch.

Python

fix: make connectors folder ingestion throw errors and check for duplicates (#1706)

Lucas Oliveira1b25fd7689da
diff --git a/frontend/app/upload/[provider]/page.tsx b/frontend/app/upload/[provider]/page.tsx
index a4112d86c..c964fef9c 100644
--- a/frontend/app/upload/[provider]/page.tsx
+++ b/frontend/app/upload/[provider]/page.tsx
@@ -489,40 +489,55 @@ export default function UploadProviderPage() {
setIsCheckingDuplicates(true);
try {
- const results = await Promise.all(
- selectedFiles.map(async (file) => {
- if (file.isFolder) return { file, isDuplicate: false };
- try {
- const fakeFile = new File([], file.name);
- const { exists } = await duplicateCheck(fakeFile);
- return { file, isDuplicate: exists };
- } catch (err) {
- console.error(
- `[Connector Sync] Duplicate check failed for ${file.name}:`,
- err,
- );
- return { file, isDuplicate: false };
- }
- }),
+ const checkResponse = await fetch(
+ `/api/connectors/${connector.type}/check-duplicates`,
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ connection_id: connector.connectionId,
+ selected_files: selectedFiles.map((file) => ({
+ id: file.id,
+ name: file.name,
+ mimeType: file.mimeType,
+ downloadUrl: file.downloadUrl,
+ size: file.size,
+ isFolder: file.isFolder,
+ })),
+ }),
+ },
);
- const duplicates = results.filter((r) => r.isDuplicate);
- const nonDuplicates = results
- .filter((r) => !r.isDuplicate)
- .map((r) => r.file);
+ if (!checkResponse.ok) {
+ throw new Error(`Duplicate check failed: ${checkResponse.statusText}`);
+ }
- if (duplicates.length === 0) {
+ const checkData = await checkResponse.json();
+ const duplicateNames = checkData.duplicate_names || [];
+ const totalFiles = checkData.total_files || 0;
+
+ if (duplicateNames.length === 0) {
submitSync(connector, selectedFiles, false);
return;
}
+ // If all files are duplicates, we set nonDuplicateFiles to empty so it toasts "Nothing was synced" on skip
+ const isAllDuplicate = duplicateNames.length === totalFiles;
+ const nonDuplicateFiles = isAllDuplicate ? [] : selectedFiles;
+
setPendingSync({
connector,
allFiles: selectedFiles,
- nonDuplicateFiles: nonDuplicates,
- duplicateNames: duplicates.map((r) => r.file.name),
+ nonDuplicateFiles,
+ duplicateNames,
});
setDuplicateDialogOpen(true);
+ } catch (err) {
+ console.error("[Connector Sync] Duplicate check failed:", err);
+ // Fallback: proceed without overwrite
+ submitSync(connector, selectedFiles, false);
} finally {
setIsCheckingDuplicates(false);
}
diff --git a/frontend/components/cloud-picker/provider-handlers.ts b/frontend/components/cloud-picker/provider-handlers.ts
index 2966c4083..738d19b4a 100644
--- a/frontend/components/cloud-picker/provider-handlers.ts
+++ b/frontend/components/cloud-picker/provider-handlers.ts
@@ -201,6 +201,7 @@ export class OneDriveHandler {
clientId: this.clientId,
action: "query",
multiSelect: true,
+ viewType: "all",
advanced: {
endpointHint: endpointHint,
accessToken: this.accessToken,
diff --git a/frontend/components/cloud-picker/sharepoint-v8-handler.ts b/frontend/components/cloud-picker/sharepoint-v8-handler.ts
index d309b9a3b..19e2c125c 100644
--- a/frontend/components/cloud-picker/sharepoint-v8-handler.ts
+++ b/frontend/components/cloud-picker/sharepoint-v8-handler.ts
@@ -513,8 +513,12 @@ export class SharePointV8Handler {
mimeType = this.inferMimeType(item.name);
}
+ const driveId = item.parentReference?.driveId;
+ const itemId = item.id;
+ const finalId = driveId ? `${driveId}!${itemId}` : itemId;
+
return {
- id: item.id,
+ id: finalId,
name: item.name || "Unknown",
mimeType: mimeType || "application/octet-stream",
webUrl: item.webUrl || "",
diff --git a/src/api/connectors.py b/src/api/connectors.py
index df8acf690..ea4cab69e 100644
--- a/src/api/connectors.py
+++ b/src/api/connectors.py
@@ -345,6 +345,156 @@ class ConnectorSyncBody(BaseModel):
replace_duplicates: bool = False
+class ConnectorCheckDuplicatesBody(BaseModel):
+ connection_id: str | None = None
+ selected_files: list[Any] | None = None
+
+
+async def connector_check_duplicates(
+ connector_type: str,
+ body: ConnectorCheckDuplicatesBody,
+ connector_service=Depends(get_connector_service),
+ session_manager=Depends(get_session_manager),
+ user: User = Depends(require_permission("connectors:use")),
+):
+ """Check if any of the selected files or folders contain files that already exist in the index"""
+ selected_files_raw = body.selected_files
+ if not selected_files_raw:
+ return JSONResponse({"duplicate_names": []})
+
+ try:
+ jwt_token = user.jwt_token
+ # Get all active connections for this connector type and user
+ connections = await connector_service.connection_manager.list_connections(
+ user_id=user.user_id, connector_type=connector_type
+ )
+ active_connections = [conn for conn in connections if conn.is_active]
+
+ # If connection_id is provided, find it, otherwise find the first working connection
+ working_connection = None
+ if body.connection_id:
+ for conn in active_connections:
+ if conn.connection_id == body.connection_id:
+ working_connection = conn
+ break
+
+ if not working_connection:
+ for conn in active_connections:
+ try:
+ connector = await connector_service.get_connector(conn.connection_id)
+ if connector and await connector.authenticate():
+ working_connection = conn
+ break
+ except Exception:
+ continue
+
+ if not working_connection:
+ return JSONResponse(
+ {"error": f"No working {connector_type} connections found"},
+ status_code=404,
+ )
+
+ connector = await connector_service.get_connector(working_connection.connection_id)
+ if not connector:
+ return JSONResponse(
+ {"error": f"Connection '{working_connection.connection_id}' not found"},
+ status_code=404,
+ )
+
+ # Get list of file IDs to expand
+ file_ids = [f.get("id") for f in selected_files_raw if f.get("id")]
+
+ expanded_files_info = []
+
+ # Expand files (handling folders) if possible
+ if file_ids and hasattr(connector, "cfg"):
+ original_file_ids = getattr(connector.cfg, "file_ids", None)
+ original_folder_ids = getattr(connector.cfg, "folder_ids", None)
+ try:
+ connector.cfg.file_ids = file_ids
+ connector.cfg.folder_ids = None
+
+ result = await connector.list_files()
+ expanded_files = result.get("files", [])
+ for f in expanded_files:
+ expanded_files_info.append(
+ {
+ "name": f.get("name", ""),
+ "mimeType": f.get("mime_type") or f.get("mimeType") or "",
+ }
+ )
+ except Exception as e:
+ logger.error("Failed to expand files in duplicate check", error=str(e))
+ finally:
+ connector.cfg.file_ids = original_file_ids
+ connector.cfg.folder_ids = original_folder_ids
+
+ # If expansion returned nothing, fall back to non-folders in selected_files_raw
+ if not expanded_files_info:
+ for f in selected_files_raw:
+ if not f.get("isFolder"):
+ expanded_files_info.append(
+ {"name": f.get("name", ""), "mimeType": f.get("mimeType") or ""}
+ )
+
+ if not expanded_files_info:
+ return JSONResponse({"duplicate_names": []})
+
+ # Process and clean names using clean_connector_filename
+ from utils.file_utils import clean_connector_filename, get_filename_aliases
+
+ cleaned_names = []
+ for f in expanded_files_info:
+ cleaned_name = clean_connector_filename(f["name"], f["mimeType"])
+ cleaned_names.append(cleaned_name)
+
+ # Build candidate filenames (including aliases like .txt / .md mapping)
+ all_candidates = set()
+ for name in cleaned_names:
+ all_candidates.update(get_filename_aliases(name))
+
+ if not all_candidates:
+ return JSONResponse({"duplicate_names": []})
+
+ # Query OpenSearch in one batch
+ opensearch_client = session_manager.get_user_opensearch_client(user.user_id, jwt_token)
+
+ query_body = {
+ "size": 10000,
+ "query": {"terms": {"filename": list(all_candidates)}},
+ "_source": ["filename"],
+ }
+
+ existing_filenames = set()
+ try:
+ response = await opensearch_client.search(index=get_index_name(), body=query_body)
+ hits = response.get("hits", {}).get("hits", [])
+ for hit in hits:
+ fn = hit.get("_source", {}).get("filename")
+ if fn:
+ existing_filenames.add(fn)
+ except Exception as search_err:
+ if "index_not_found_exception" in str(search_err):
+ # Index doesn't exist yet, so no duplicates can exist
+ return JSONResponse({"duplicate_names": [], "total_files": len(cleaned_names)})
+ raise
+
+ # Check which of the cleaned names have duplicates (based on existing_filenames matching any alias)
+ duplicate_names = []
+ for name in cleaned_names:
+ aliases = get_filename_aliases(name)
+ if any(alias in existing_filenames for alias in aliases):
+ duplicate_names.append(name)
+
+ return JSONResponse(
+ {"duplicate_names": list(set(duplicate_names)), "total_files": len(cleaned_names)}
+ )
+
+ except Exception:
+ logger.exception("[CONNECTOR] Error checking duplicates")
+ return JSONResponse({"error": "An internal error has occurred."}, status_code=500)
+
+
async def list_connectors(
connector_service=Depends(get_connector_service),
user: User = Depends(get_current_user),
diff --git a/src/app/routes/internal.py b/src/app/routes/internal.py
index 299f05016..f55f77e83 100644
--- a/src/app/routes/internal.py
+++ b/src/app/routes/internal.py
@@ -265,6 +265,12 @@ def register_internal_routes(app: FastAPI):
methods=["POST"],
tags=["internal"],
)
+ app.add_api_route(
+ "/connectors/{connector_type}/check-duplicates",
+ connectors.connector_check_duplicates,
+ methods=["POST"],
+ tags=["internal"],
+ )
app.add_api_route(
"/connectors/{connector_type}/sync-preview",
connectors.connector_sync_preview,
diff --git a/src/connectors/onedrive/connector.py b/src/connectors/onedrive/connector.py
index 316369f6b..3f0b9cc38 100644
--- a/src/connectors/onedrive/connector.py
+++ b/src/connectors/onedrive/connector.py
@@ -636,7 +636,7 @@ class OneDriveConnector(BaseConnector):
# Check if ID contains '!' which indicates driveId!itemId format
if "!" in file_id:
- parts = file_id.split("!", 1)
+ parts = file_id.rsplit("!", 1)
if len(parts) == 2:
drive_id = parts[0]
item_id = parts[1]
@@ -735,7 +735,7 @@ class OneDriveConnector(BaseConnector):
# Build URL based on ID format
if "!" in file_id:
- parts = file_id.split("!", 1)
+ parts = file_id.rsplit("!", 1)
if len(parts) == 2:
drive_id = parts[0]
item_id = parts[1]
@@ -747,8 +747,11 @@ class OneDriveConnector(BaseConnector):
return content
# Try drives endpoint for driveId!itemId format
- url = f"{self._graph_base_url}/drives/{drive_id}/items/{file_id}/content"
- logger.info(f"Downloading via drives endpoint: {url}")
+ if not item_id.startswith("s"):
+ url = f"{self._graph_base_url}/drives/{drive_id}/items/{item_id}/content"
+ logger.info(f"Downloading via drives endpoint: {url}")
+ else:
+ url = f"{self._graph_base_url}/me/drive/items/{file_id}/content"
else:
url = f"{self._graph_base_url}/me/drive/items/{file_id}/content"
else:
@@ -883,7 +886,18 @@ class OneDriveConnector(BaseConnector):
files: list[dict[str, Any]] = []
try:
- url = f"{self._graph_base_url}/me/drive/items/{folder_id}/children"
+ drive_id = None
+ if "!" in folder_id:
+ parts = folder_id.rsplit("!", 1)
+ if len(parts) == 2:
+ potential_drive_id, item_id = parts
+ if not item_id.startswith("s"):
+ drive_id = potential_drive_id
+ url = f"{self._graph_base_url}/drives/{drive_id}/items/{item_id}/children"
+
+ if not drive_id:
+ url = f"{self._graph_base_url}/me/drive/items/{folder_id}/children"
+
params = dict(self._default_params)
response = await self._make_graph_request(url, params=params)
@@ -891,12 +905,32 @@ class OneDriveConnector(BaseConnector):
items = data.get("value", [])
for item in items:
+ parent_ref = item.get("parentReference", {})
+ item_drive_id = parent_ref.get("driveId") or drive_id
+ item_id = item.get("id")
+ if item_id and "!" in item_id:
+ final_item_id = item_id
+ else:
+ final_item_id = f"{item_drive_id}!{item_id}" if item_drive_id else item_id
+
if item.get("file"): # It's a file
- file_meta = await self._get_file_metadata_by_id(item.get("id"))
- if file_meta:
- files.append(file_meta)
+ file_meta = {
+ "id": final_item_id,
+ "name": item.get("name", ""),
+ "path": f"/drive/items/{item_id}",
+ "size": int(item.get("size") or 0),
+ "modified": item.get("lastModifiedDateTime"),
+ "created": item.get("createdDateTime"),
+ "mime_type": item.get("file", {}).get(
+ "mimeType", self._get_mime_type(item.get("name", ""))
+ ),
+ "url": item.get("webUrl", ""),
+ "download_url": item.get("@microsoft.graph.downloadUrl"),
+ "isFolder": False,
+ }
+ files.append(file_meta)
elif item.get("folder"): # It's a subfolder, recurse
- subfolder_files = await self._list_folder_contents(item.get("id"))
+ subfolder_files = await self._list_folder_contents(final_item_id)
files.extend(subfolder_files)
except Exception as e:
logger.error(f"Failed to list folder contents for {folder_id}: {e}")
diff --git a/src/connectors/sharepoint/connector.py b/src/connectors/sharepoint/connector.py
index 0a1b6cf61..825b83884 100644
--- a/src/connectors/sharepoint/connector.py
+++ b/src/connectors/sharepoint/connector.py
@@ -1,6 +1,6 @@
from datetime import datetime
from pathlib import Path
-from typing import Any, Dict, List, Optional
+from typing import Any
from urllib.parse import urlparse
import httpx
@@ -25,7 +25,7 @@ class SharePointConnector(BaseConnector):
CONNECTOR_DESCRIPTION = "Add knowledge from SharePoint"
CONNECTOR_ICON = "sharepoint"
- def __init__(self, config: Dict[str, Any]):
+ def __init__(self, config: dict[str, Any]):
super().__init__(config)
logger.debug(f"SharePoint connector __init__ called with config type: {type(config)}")
@@ -104,7 +104,7 @@ class SharePointConnector(BaseConnector):
self.oauth = None
# Track subscription ID for webhooks
- self._subscription_id: Optional[str] = None
+ self._subscription_id: str | None = None
# Add Graph API defaults similar to Google Drive flags
self._graph_api_version = "v1.0"
@@ -128,7 +128,7 @@ class SharePointConnector(BaseConnector):
# Cache for file metadata including download URLs
# This allows direct download without Graph API for sharing IDs
- self._file_infos: Dict[str, Dict[str, Any]] = {}
+ self._file_infos: dict[str, dict[str, Any]] = {}
@property
def _graph_base_url(self) -> str:
@@ -136,7 +136,7 @@ class SharePointConnector(BaseConnector):
return f"https://graph.microsoft.com/{self._graph_api_version}"
@property
- def base_url(self) -> Optional[str]:
+ def base_url(self) -> str | None:
"""Generic base URL property (returns sharepoint_url for SharePoint connector)"""
return self.sharepoint_url
@@ -145,7 +145,7 @@ class SharePointConnector(BaseConnector):
"""Set base URL (updates sharepoint_url internally)"""
self.sharepoint_url = value
- def set_file_infos(self, file_infos: List[Dict[str, Any]]) -> None:
+ def set_file_infos(self, file_infos: list[dict[str, Any]]) -> None:
"""
Cache file metadata including download URLs for later use.
This allows direct download without Graph API calls for sharing IDs.
@@ -161,7 +161,7 @@ class SharePointConnector(BaseConnector):
if info.get("downloadUrl"):
logger.debug(f"Cached download URL for file {file_id}: {info.get('name')}")
- def get_cached_file_info(self, file_id: str) -> Optional[Dict[str, Any]]:
+ def get_cached_file_info(self, file_id: str) -> dict[str, Any] | None:
"""Get cached file info by ID."""
return self._file_infos.get(file_id)
@@ -191,7 +191,7 @@ class SharePointConnector(BaseConnector):
self._authenticated = authenticated
return authenticated
- except Exception as e:
+ except Exception:
logger.exception("[CONNECTOR] SharePoint authentication failed")
self._authenticated = False
return False
@@ -202,7 +202,7 @@ class SharePointConnector(BaseConnector):
raise RuntimeError("SharePoint OAuth not initialized - missing credentials")
return self.oauth.create_authorization_url(self.redirect_uri)
- async def handle_oauth_callback(self, auth_code: str) -> Dict[str, Any]:
+ async def handle_oauth_callback(self, auth_code: str) -> dict[str, Any]:
"""Handle OAuth callback"""
if not self.oauth:
raise RuntimeError("SharePoint OAuth not initialized - missing credentials")
@@ -224,11 +224,11 @@ class SharePointConnector(BaseConnector):
logger.error(f"OAuth callback failed: {e}")
raise
- async def _detect_base_url(self) -> Optional[str]:
+ async def _detect_base_url(self) -> str | None:
"""Override base class method to detect SharePoint URL"""
return await self._detect_sharepoint_url()
- async def _detect_sharepoint_url(self) -> Optional[str]:
+ async def _detect_sharepoint_url(self) -> str | None:
"""Auto-detect SharePoint URL from Microsoft Graph API"""
logger.info("_detect_sharepoint_url: Starting SharePoint URL detection")
try:
@@ -277,7 +277,7 @@ class SharePointConnector(BaseConnector):
"[CONNECTOR] SharePoint detect URL failed", status_code=response.status_code
)
- except Exception as e:
+ except Exception:
logger.exception("[CONNECTOR] SharePoint URL detection failed")
return None
@@ -385,7 +385,7 @@ class SharePointConnector(BaseConnector):
expiry = datetime.utcnow() + timedelta(days=3) # 3 days max for Graph
return expiry.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
- def _parse_sharepoint_url(self) -> Optional[Dict[str, str]]:
+ def _parse_sharepoint_url(self) -> dict[str, str] | None:
"""Parse SharePoint URL to extract site information for Graph API"""
if not self.sharepoint_url:
return None
@@ -405,8 +405,8 @@ class SharePointConnector(BaseConnector):
return None
async def list_files(
- self, page_token: Optional[str] = None, max_files: Optional[int] = None, **kwargs
- ) -> Dict[str, Any]:
+ self, page_token: str | None = None, max_files: int | None = None, **kwargs
+ ) -> dict[str, Any]:
"""List all files using Microsoft Graph API - BaseConnector interface"""
try:
# Ensure authentication
@@ -473,7 +473,7 @@ class SharePointConnector(BaseConnector):
logger.error(f"Failed to list SharePoint files: {e}")
return {"files": [], "next_page_token": None} # Return empty result instead of raising
- async def _extract_sharepoint_acl(self, file_id: str, file_metadata: Dict) -> DocumentACL:
+ async def _extract_sharepoint_acl(self, file_id: str, file_metadata: dict) -> DocumentACL:
"""
Extract ACL from SharePoint item.
@@ -642,15 +642,23 @@ class SharePointConnector(BaseConnector):
logger.error(f"Failed to get SharePoint file content {file_id}: {e}")
raise
- async def _get_file_metadata_by_id(self, file_id: str) -> Optional[Dict[str, Any]]:
+ async def _get_file_metadata_by_id(self, file_id: str) -> dict[str, Any] | None:
"""Get file metadata by ID using Graph API"""
try:
- # Try site-specific path first, then fallback to user drive
- site_info = self._parse_sharepoint_url()
- if site_info:
- url = f"{self._graph_base_url}/sites/{site_info['host_name']}:/sites/{site_info['site_name']}:/drive/items/{file_id}"
+ # Check if ID contains '!' which indicates driveId!itemId format
+ if "!" in file_id:
+ parts = file_id.rsplit("!", 1)
+ if len(parts) == 2:
+ drive_id, item_id = parts
+ url = f"{self._graph_base_url}/drives/{drive_id}/items/{item_id}"
+ else:
+ url = f"{self._graph_base_url}/me/drive/items/{file_id}"
else:
- url = f"{self._graph_base_url}/me/drive/items/{file_id}"
+ site_info = self._parse_sharepoint_url()
+ if site_info:
+ url = f"{self._graph_base_url}/sites/{site_info['host_name']}:/sites/{site_info['site_name']}:/drive/items/{file_id}"
+ else:
+ url = f"{self._graph_base_url}/me/drive/items/{file_id}"
params = dict(self._default_params)
@@ -693,11 +701,23 @@ class SharePointConnector(BaseConnector):
async def _download_file_content(self, file_id: str) -> bytes:
"""Download file content by file ID using Graph API"""
try:
- site_info = self._parse_sharepoint_url()
- if site_info:
- url = f"{self._graph_base_url}/sites/{site_info['host_name']}:/sites/{site_info['site_name']}:/drive/items/{file_id}/content"
+ # Check if ID contains '!' which indicates driveId!itemId format
+ if "!" in file_id:
+ parts = file_id.rsplit("!", 1)
+ if len(parts) == 2:
+ drive_id, item_id = parts
+ if not item_id.startswith("s"):
+ url = f"{self._graph_base_url}/drives/{drive_id}/items/{item_id}/content"
+ else:
+ url = f"{self._graph_base_url}/me/drive/items/{file_id}/content"
+ else:
+ url = f"{self._graph_base_url}/me/drive/items/{file_id}/content"
else:
- url = f"{self._graph_base_url}/me/drive/items/{file_id}/content"
+ site_info = self._parse_sharepoint_url()
+ if site_info:
+ url = f"{self._graph_base_url}/sites/{site_info['host_name']}:/sites/{site_info['site_name']}:/drive/items/{file_id}/content"
+ else:
+ url = f"{self._graph_base_url}/me/drive/items/{file_id}/content"
token = self.oauth.get_access_token()
headers = {"Authorization": f"Bearer {token}"}
@@ -711,9 +731,9 @@ class SharePointConnector(BaseConnector):
logger.error(f"Failed to download file content for {file_id}: {e}")
raise
- async def _list_selected_files(self) -> Dict[str, Any]:
+ async def _list_selected_files(self) -> dict[str, Any]:
"""List only selected files/folders (selective sync)."""
- files: List[Dict[str, Any]] = []
+ files: list[dict[str, Any]] = []
# Process selected file IDs
if self.cfg.file_ids:
@@ -742,16 +762,26 @@ class SharePointConnector(BaseConnector):
return {"files": files, "next_page_token": None}
- async def _list_folder_contents(self, folder_id: str) -> List[Dict[str, Any]]:
+ async def _list_folder_contents(self, folder_id: str) -> list[dict[str, Any]]:
"""List all files in a folder recursively."""
- files: List[Dict[str, Any]] = []
+ files: list[dict[str, Any]] = []
try:
- site_info = self._parse_sharepoint_url()
- if site_info:
- url = f"{self._graph_base_url}/sites/{site_info['host_name']}:/sites/{site_info['site_name']}:/drive/items/{folder_id}/children"
- else:
- url = f"{self._graph_base_url}/me/drive/items/{folder_id}/children"
+ drive_id = None
+ if "!" in folder_id:
+ parts = folder_id.rsplit("!", 1)
+ if len(parts) == 2:
+ potential_drive_id, item_id = parts
+ if not item_id.startswith("s"):
+ drive_id = potential_drive_id
+ url = f"{self._graph_base_url}/drives/{drive_id}/items/{item_id}/children"
+
+ if not drive_id:
+ site_info = self._parse_sharepoint_url()
+ if site_info:
+ url = f"{self._graph_base_url}/sites/{site_info['host_name']}:/sites/{site_info['site_name']}:/drive/items/{folder_id}/children"
+ else:
+ url = f"{self._graph_base_url}/me/drive/items/{folder_id}/children"
params = dict(self._default_params)
@@ -760,15 +790,38 @@ class SharePointConnector(BaseConnector):
items = data.get("value", [])
for item in items:
+ parent_ref = item.get("parentReference", {})
+ item_drive_id = parent_ref.get("driveId") or drive_id
+ item_id = item.get("id")
+ if item_id and "!" in item_id:
+ final_item_id = item_id
+ else:
+ final_item_id = f"{item_drive_id}!{item_id}" if item_drive_id else item_id
+
if item.get("file"): # It's a file
- file_meta = await self._get_file_metadata_by_id(item.get("id"))
- if file_meta:
- files.append(file_meta)
+ file_meta = {
+ "id": final_item_id,
+ "name": item.get("name", ""),
+ "path": f"/drive/items/{item_id}",
+ "size": int(item.get("size") or 0),
+ "modified": item.get("lastModifiedDateTime"),
+ "created": item.get("createdDateTime"),
+ "mime_type": item.get("file", {}).get(
+ "mimeType", self._get_mime_type(item.get("name", ""))
+ ),
+ "url": item.get("webUrl", ""),
+ "download_url": item.get("@microsoft.graph.downloadUrl"),
+ }
+ files.append(file_meta)
elif item.get("folder"): # It's a subfolder, recurse
- subfolder_files = await self._list_folder_contents(item.get("id"))
+ subfolder_files = await self._list_folder_contents(final_item_id)
files.extend(subfolder_files)
except Exception as e:
- logger.error(f"Failed to list folder contents for {folder_id}: {e}")
+ import traceback
+
+ logger.error(
+ f"Failed to list folder contents for {folder_id}: {e}\n{traceback.format_exc()}"
+ )
return files
@@ -783,7 +836,7 @@ class SharePointConnector(BaseConnector):
logger.error(f"Failed to download from URL {download_url}: {e}")
raise
- def _parse_graph_date(self, date_str: Optional[str]) -> datetime:
+ def _parse_graph_date(self, date_str: str | None) -> datetime:
"""Parse Microsoft Graph date string to datetime"""
if not date_str:
return datetime.now()
@@ -800,8 +853,8 @@ class SharePointConnector(BaseConnector):
self,
url: str,
method: str = "GET",
- data: Optional[Dict] = None,
- params: Optional[Dict] = None,
+ data: dict | None = None,
+ params: dict | None = None,
) -> httpx.Response:
"""Make authenticated API request to Microsoft Graph"""
token = self.oauth.get_access_token()
@@ -829,23 +882,23 @@ class SharePointConnector(BaseConnector):
# Webhook methods - BaseConnector interface
def handle_webhook_validation(
- self, request_method: str, headers: Dict[str, str], query_params: Dict[str, str]
- ) -> Optional[str]:
+ self, request_method: str, headers: dict[str, str], query_params: dict[str, str]
+ ) -> str | None:
"""Handle webhook validation (Graph API specific)"""
if request_method == "POST" and "validationToken" in query_params:
return query_params["validationToken"]
return None
def extract_webhook_channel_id(
- self, payload: Dict[str, Any], headers: Dict[str, str]
- ) -> Optional[str]:
+ self, payload: dict[str, Any], headers: dict[str, str]
+ ) -> str | None:
"""Extract channel/subscription ID from webhook payload"""
notifications = payload.get("value", [])
if notifications:
return notifications[0].get("subscriptionId")
return None
- async def handle_webhook(self, payload: Dict[str, Any]) -> List[str]:
+ async def handle_webhook(self, payload: dict[str, Any]) -> list[str]:
"""Handle webhook notification and return affected file IDs"""
affected_files = []
diff --git a/src/models/processors.py b/src/models/processors.py
index c86fce45c..4174cca62 100644
--- a/src/models/processors.py
+++ b/src/models/processors.py
@@ -571,9 +571,6 @@ class DocumentFileProcessor(TaskProcessor):
file_task.updated_at = time.time()
upload_task.failed_files += 1
raise
- finally:
- upload_task.processed_files += 1
- upload_task.updated_at = time.time()
class ConnectorFileProcessor(TaskProcessor):
@@ -624,6 +621,46 @@ class ConnectorFileProcessor(TaskProcessor):
if not connector or not connection:
raise ValueError(f"Connection '{self.connection_id}' not found")
+ # Validate file extension early if filename is available
+ VALID_EXTENSIONS = {
+ "adoc",
+ "asciidoc",
+ "asc",
+ "bmp",
+ "csv",
+ "dotx",
+ "dotm",
+ "docm",
+ "docx",
+ "htm",
+ "html",
+ "jpeg",
+ "jpg",
+ "md",
+ "pdf",
+ "png",
+ "potx",
+ "ppsx",
+ "pptm",
+ "potm",
+ "ppsm",
+ "pptx",
+ "tiff",
+ "txt",
+ "xls",
+ "xlsx",
+ "xhtml",
+ "webp",
+ }
+ if file_task.filename:
+ ext = file_task.filename.split(".")[-1].lower() if "." in file_task.filename else ""
+ if ext not in VALID_EXTENSIONS:
+ file_task.status = TaskStatus.FAILED
+ file_task.error = f"The file '{file_task.filename}' has an incompatible type."
+ file_task.updated_at = time.time()
+ upload_task.failed_files += 1
+ return
+
# Get file content from connector
try:
document = await connector.get_file_content(file_id)
@@ -674,6 +711,16 @@ class ConnectorFileProcessor(TaskProcessor):
# Update filename in task once we have it from the connector
file_task.filename = clean_connector_filename(document.filename, document.mimetype)
+ # Re-check filename validation
+ name = file_task.filename or document.filename or ""
+ ext = name.split(".")[-1].lower() if "." in name else ""
+ if ext not in VALID_EXTENSIONS:
+ file_task.status = TaskStatus.FAILED
+ file_task.error = f"The file '{name}' has an incompatible type."
+ file_task.updated_at = time.time()
+ upload_task.failed_files += 1
+ return
+
if not self.user_id:
raise ValueError("user_id not provided to ConnectorFileProcessor")
diff --git a/src/services/docling_service.py b/src/services/docling_service.py
index 9831e89ab..e72fc2938 100644
--- a/src/services/docling_service.py
+++ b/src/services/docling_service.py
@@ -261,10 +261,20 @@ class DoclingService:
status = payload.get("task_status")
if status == "success":
return DoclingStatusSnapshot(state=DoclingTaskState.SUCCESS, raw=payload)
- if status == "failure":
+ if status == "failure" or payload.get("errors"):
+ errors = payload.get("errors", [])
+ err_msg_list = []
+ for err in errors:
+ if isinstance(err, dict) and "error_message" in err:
+ err_msg_list.append(err["error_message"])
+ elif isinstance(err, str):
+ err_msg_list.append(err)
+ err_details = (
+ "; ".join(err_msg_list) if err_msg_list else "Unknown Docling processing error"
+ )
return DoclingStatusSnapshot(
state=DoclingTaskState.FAILED,
- detail=str(payload),
+ detail=f"Docling processing failed: {err_details}",
raw=payload,
)
if status in ("started", "processing", "running"):
@@ -305,6 +315,19 @@ class DoclingService:
except ValueError as e:
raise DoclingServeError(f"Malformed docling result payload: {str(e)}") from e
+ if payload.get("status") == "failure" or payload.get("errors"):
+ errors = payload.get("errors", [])
+ err_msg_list = []
+ for err in errors:
+ if isinstance(err, dict) and "error_message" in err:
+ err_msg_list.append(err["error_message"])
+ elif isinstance(err, str):
+ err_msg_list.append(err)
+ err_details = (
+ "; ".join(err_msg_list) if err_msg_list else "Unknown Docling processing error"
+ )
+ raise DoclingServeError(f"Docling processing failed: {err_details}")
+
doc_content = payload.get("document", {}).get("json_content")
if doc_content is None:
raise DoclingServeError("docling-serve response missing document.json_content")
@@ -348,8 +371,18 @@ class DoclingService:
raise DoclingServeError("docling-serve response missing document.json_content")
return doc_content
- elif status == "failure":
- raise DoclingServeError(f"Docling conversion failed: {status_data}")
+ elif status == "failure" or status_data.get("errors"):
+ errors = status_data.get("errors", [])
+ err_msg_list = []
+ for err in errors:
+ if isinstance(err, dict) and "error_message" in err:
+ err_msg_list.append(err["error_message"])
+ elif isinstance(err, str):
+ err_msg_list.append(err)
+ err_details = (
+ "; ".join(err_msg_list) if err_msg_list else "Unknown Docling processing error"
+ )
+ raise DoclingServeError(f"Docling processing failed: {err_details}")
await asyncio.sleep(poll_interval)
elapsed += poll_interval
diff --git a/src/services/task_service.py b/src/services/task_service.py
index 4935a9220..bd147d594 100644
--- a/src/services/task_service.py
+++ b/src/services/task_service.py
@@ -939,6 +939,7 @@ class TaskService:
"actionable_by": "RETRYABLE",
}
+ # First, check if the error is non-retryable based on common markers
if _is_non_retryable_file_error(error):
if phase == IngestionPhase.LANGFLOW:
component = "langflow"
@@ -946,16 +947,48 @@ class TaskService:
else:
component = "docling"
failure_phase = "parsing"
+
+ # Extract detailed error message if possible, otherwise default to corrupted/invalid msg
+ msg = (
+ "The file appears corrupted or invalid and cannot be processed. "
+ "Upload a valid file."
+ )
+ if "Docling result unavailable after SUCCESS status: " in error:
+ msg = error.split("Docling result unavailable after SUCCESS status: ", 1)[1]
+ elif "Docling conversion did not complete" in error:
+ sub_msg = error.split("Docling conversion did not complete", 1)[1]
+ if sub_msg.startswith(" (failed): "):
+ msg = sub_msg[len(" (failed): ") :]
+ else:
+ msg = sub_msg.strip(" ():")
+
return {
"component": component,
"failure_phase": failure_phase,
- "user_facing_message": (
- "The file appears corrupted or invalid and cannot be processed. "
- "Upload a valid file."
- ),
+ "user_facing_message": msg,
"actionable_by": "USER_ACTIONABLE",
}
+ # Handle docling conversion completion issues (failed / timeout)
+ if phase == IngestionPhase.DOCLING and "Docling conversion did not complete" in error:
+ user_facing_message = "Document processing timed out. Please retry ingestion."
+ if "timeout" not in error.lower() and "expired" not in error.lower():
+ msg = error.split("Docling conversion did not complete", 1)[1]
+ if msg.startswith(" (failed): "):
+ user_facing_message = msg[len(" (failed): ") :]
+ elif msg.startswith(" (timeout): "):
+ user_facing_message = "Document processing timed out. Please retry ingestion."
+ else:
+ user_facing_message = msg.strip(" ():")
+ return {
+ "component": "docling",
+ "failure_phase": "parsing",
+ "user_facing_message": user_facing_message,
+ "actionable_by": "RETRYABLE"
+ if "timed out" in user_facing_message.lower()
+ else "USER_ACTIONABLE",
+ }
+
if phase == IngestionPhase.DOCLING and _is_docling_transient_error(error):
langflow_transport = _is_langflow_transport_failure(error)
return {
@@ -974,12 +1007,22 @@ class TaskService:
}
if docling_status == DoclingPhaseStatus.FAILED:
+ msg = "The file could not be processed into readable document content."
+ if error:
+ if "Docling result unavailable after SUCCESS status: " in error:
+ msg = error.split("Docling result unavailable after SUCCESS status: ", 1)[1]
+ elif "Docling conversion did not complete" in error:
+ sub_msg = error.split("Docling conversion did not complete", 1)[1]
+ if sub_msg.startswith(" (failed): "):
+ msg = sub_msg[len(" (failed): ") :]
+ else:
+ msg = sub_msg.strip(" ():")
+ else:
+ msg = error
return {
"component": "docling",
"failure_phase": "parsing",
- "user_facing_message": (
- "The file could not be processed into readable document content."
- ),
+ "user_facing_message": msg,
"actionable_by": "USER_ACTIONABLE",
}
diff --git a/tests/unit/connectors/test_connector_file_type_validation.py b/tests/unit/connectors/test_connector_file_type_validation.py
new file mode 100644
index 000000000..12e48a154
--- /dev/null
+++ b/tests/unit/connectors/test_connector_file_type_validation.py
@@ -0,0 +1,153 @@
+import sys
+from pathlib import Path
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+
+ROOT = Path(__file__).resolve().parent.parent.parent.parent
+SRC = ROOT / "src"
+if str(SRC) not in sys.path:
+ sys.path.insert(0, str(SRC))
+
+
+async def test_sync_specific_files_does_not_raise_on_incompatible_type():
+ from connectors.service import ConnectorService
+
+ # Instantiate the service
+ service = ConnectorService.__new__(ConnectorService)
+ service.task_service = MagicMock()
+ service.session_manager = MagicMock()
+ service.models_service = MagicMock()
+
+ # Mock the connector and config
+ connector = MagicMock()
+ connector.is_authenticated = True
+
+ # Mock list_files returning an incompatible file (e.g. an .exe)
+ connector.list_files = AsyncMock(
+ return_value={
+ "files": [
+ {"id": "file-1", "name": "document.pdf"},
+ {"id": "file-2", "name": "program.exe"},
+ ]
+ }
+ )
+ connector.cfg = MagicMock()
+
+ service.get_connector = AsyncMock(return_value=connector)
+
+ # When creating a custom task, we'll return a dummy task ID
+ service.task_service.create_custom_task = AsyncMock(return_value="dummy-task-id")
+
+ # Verify that calling sync_specific_files succeeds (no ValueError raised!)
+ task_id = await service.sync_specific_files(
+ connection_id="conn-id", user_id="user-id", file_ids=["folder-id"], jwt_token="jwt"
+ )
+
+ assert task_id == "dummy-task-id"
+
+
+async def test_connector_file_processor_fails_incompatible_file():
+ from models.processors import ConnectorFileProcessor
+ from models.tasks import FileTask, TaskStatus, UploadTask
+
+ connector_service = MagicMock()
+ connector = MagicMock()
+ connector_service.get_connector = AsyncMock(return_value=connector)
+ connection = MagicMock()
+ connection.connector_type = "onedrive"
+ connector_service.connection_manager.get_connection = AsyncMock(return_value=connection)
+
+ processor = ConnectorFileProcessor(
+ connector_service=connector_service,
+ connection_id="conn-id",
+ files_to_process=[],
+ user_id="user-id",
+ jwt_token="jwt",
+ document_service=MagicMock(),
+ models_service=MagicMock(),
+ )
+
+ upload_task = UploadTask(task_id="task-id", total_files=1)
+ file_task = FileTask(file_path="file-2", filename="program.exe")
+
+ await processor.process_item(upload_task, "file-2", file_task)
+
+ assert file_task.status == TaskStatus.FAILED
+ assert "has an incompatible type" in file_task.error
+ assert "program.exe" in file_task.error
+ assert upload_task.failed_files == 1
+
+
+async def test_connector_check_duplicates():
+ import json
+
+ from fastapi.responses import JSONResponse
+
+ from api.connectors import ConnectorCheckDuplicatesBody, connector_check_duplicates
+
+ # Mock parameters
+ connector_service = MagicMock()
+ connection_manager = MagicMock()
+ connector_service.connection_manager = connection_manager
+
+ connection = MagicMock()
+ connection.connection_id = "conn-id"
+ connection.is_active = True
+ connection_manager.list_connections = AsyncMock(return_value=[connection])
+
+ connector = MagicMock()
+ connector.is_authenticated = True
+ connector.authenticate = AsyncMock(return_value=True)
+
+ # Mock folder expansion
+ connector.list_files = AsyncMock(
+ return_value={
+ "files": [
+ {"id": "file-1", "name": "existing.pdf", "mimeType": "application/pdf"},
+ {
+ "id": "file-2",
+ "name": "new_file.docx",
+ "mimeType": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
+ },
+ ]
+ }
+ )
+ connector.cfg = MagicMock()
+ connector_service.get_connector = AsyncMock(return_value=connector)
+
+ # Mock session_manager and OpenSearch client
+ session_manager = MagicMock()
+ opensearch_client = AsyncMock()
+ session_manager.get_user_opensearch_client = MagicMock(return_value=opensearch_client)
+
+ # Mock search return value: existing.pdf exists, new_file.docx does not
+ opensearch_client.search = AsyncMock(
+ return_value={"hits": {"hits": [{"_source": {"filename": "existing.pdf"}}]}}
+ )
+
+ user = MagicMock()
+ user.user_id = "user-id"
+ user.jwt_token = "jwt-token"
+
+ body = ConnectorCheckDuplicatesBody(
+ connection_id="conn-id",
+ selected_files=[{"id": "folder-1", "name": "Folder 1", "isFolder": True}],
+ )
+
+ response = await connector_check_duplicates(
+ connector_type="onedrive",
+ body=body,
+ connector_service=connector_service,
+ session_manager=session_manager,
+ user=user,
+ )
+
+ assert isinstance(response, JSONResponse)
+ data = json.loads(response.body.decode())
+ assert "existing.pdf" in data["duplicate_names"]
+ assert "new_file.docx" not in data["duplicate_names"]
+ assert data["total_files"] == 2