feat(api): add folder browser API endpoints and UI for Dropbox and OneDrive
Added POST /api/dropbox/list-folders and POST /api/onedrive/list-folders endpoints that accept an OAuth access_token and return folder listings. After successful OAuth authorization in the callback pages, users now see an interactive folder browser to select the target folder for their integration. The selected folder is saved to the integration config. Co-authored-by: christianlouis <361235+christianlouis@users.noreply.github.com>
This commit is contained in:
@@ -207,6 +207,91 @@ async def test_dropbox_token(request: Request):
|
||||
return {"status": "error", "message": f"Connection error: {str(e)}"}
|
||||
|
||||
|
||||
@router.post("/dropbox/list-folders")
|
||||
@require_login
|
||||
async def list_dropbox_folders(
|
||||
request: Request,
|
||||
access_token: Annotated[str, Form(...)],
|
||||
path: Annotated[str, Form()] = "",
|
||||
):
|
||||
"""
|
||||
List folders in a Dropbox account for the directory selector.
|
||||
|
||||
Accepts an OAuth access token (short-lived) and a path to list.
|
||||
Returns a flat list of folder entries under the given path.
|
||||
"""
|
||||
try:
|
||||
# Normalize path: Dropbox API uses "" for root, otherwise "/path"
|
||||
folder_path = path.strip()
|
||||
if folder_path == "/":
|
||||
folder_path = ""
|
||||
elif folder_path and not folder_path.startswith("/"):
|
||||
folder_path = f"/{folder_path}"
|
||||
|
||||
headers = {
|
||||
"Authorization": f"Bearer {access_token}",
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
|
||||
payload = {
|
||||
"path": folder_path,
|
||||
"recursive": False,
|
||||
"include_deleted": False,
|
||||
"include_has_explicit_shared_members": False,
|
||||
"include_mounted_folders": True,
|
||||
}
|
||||
|
||||
response = requests.post(
|
||||
"https://api.dropboxapi.com/2/files/list_folder",
|
||||
headers=headers,
|
||||
json=payload,
|
||||
timeout=settings.http_request_timeout,
|
||||
)
|
||||
|
||||
if response.status_code == 401:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Access token is invalid or expired. Please re-authorize.",
|
||||
)
|
||||
|
||||
if response.status_code != 200:
|
||||
logger.error(f"Dropbox list_folder failed: {response.status_code} {response.text}")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail=f"Failed to list Dropbox folders: {response.text}",
|
||||
)
|
||||
|
||||
data = response.json()
|
||||
folders = []
|
||||
for entry in data.get("entries", []):
|
||||
if entry.get(".tag") == "folder":
|
||||
folders.append(
|
||||
{
|
||||
"name": entry["name"],
|
||||
"path": entry["path_display"],
|
||||
"id": entry.get("id", ""),
|
||||
}
|
||||
)
|
||||
|
||||
# Sort folders alphabetically
|
||||
folders.sort(key=lambda f: f["name"].lower())
|
||||
|
||||
return {
|
||||
"folders": folders,
|
||||
"path": folder_path or "/",
|
||||
"has_more": data.get("has_more", False),
|
||||
}
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.exception(f"Error listing Dropbox folders: {e}")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=f"Failed to list folders: {str(e)}",
|
||||
)
|
||||
|
||||
|
||||
@router.post("/dropbox/save-settings")
|
||||
@require_login
|
||||
async def save_dropbox_settings(
|
||||
|
||||
@@ -56,6 +56,7 @@ async def exchange_onedrive_token(
|
||||
# Return just what's needed by the frontend
|
||||
return {
|
||||
"refresh_token": token_data["refresh_token"],
|
||||
"access_token": token_data.get("access_token", ""),
|
||||
"expires_in": token_data.get("expires_in", 3600),
|
||||
}
|
||||
|
||||
@@ -206,6 +207,102 @@ async def test_onedrive_token(request: Request):
|
||||
return {"status": "error", "message": f"Connection error: {str(e)}"}
|
||||
|
||||
|
||||
@router.post("/onedrive/list-folders")
|
||||
@require_login
|
||||
async def list_onedrive_folders(
|
||||
request: Request,
|
||||
access_token: Annotated[str, Form(...)],
|
||||
path: Annotated[str, Form()] = "",
|
||||
):
|
||||
"""
|
||||
List folders in a OneDrive account for the directory selector.
|
||||
|
||||
Accepts an OAuth access token (short-lived) and a path to list.
|
||||
Returns a flat list of folder entries under the given path.
|
||||
"""
|
||||
try:
|
||||
folder_path = path.strip().strip("/")
|
||||
|
||||
headers = {
|
||||
"Authorization": f"Bearer {access_token}",
|
||||
}
|
||||
|
||||
# Build the Graph API URL for listing children
|
||||
if not folder_path or folder_path == "root":
|
||||
url = "https://graph.microsoft.com/v1.0/me/drive/root/children"
|
||||
else:
|
||||
url = f"https://graph.microsoft.com/v1.0/me/drive/root:/{folder_path}:/children"
|
||||
|
||||
# Only request folders and minimal fields
|
||||
params = {
|
||||
"$filter": "folder ne null",
|
||||
"$select": "name,id,parentReference,folder",
|
||||
"$top": "200",
|
||||
}
|
||||
|
||||
response = requests.get(
|
||||
url,
|
||||
headers=headers,
|
||||
params=params,
|
||||
timeout=settings.http_request_timeout,
|
||||
)
|
||||
|
||||
if response.status_code == 401:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Access token is invalid or expired. Please re-authorize.",
|
||||
)
|
||||
|
||||
if response.status_code != 200:
|
||||
logger.error(f"OneDrive list children failed: {response.status_code} {response.text}")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail=f"Failed to list OneDrive folders: {response.text}",
|
||||
)
|
||||
|
||||
data = response.json()
|
||||
folders = []
|
||||
for item in data.get("value", []):
|
||||
if "folder" in item:
|
||||
parent_path = ""
|
||||
if item.get("parentReference", {}).get("path"):
|
||||
# parentReference.path looks like /drive/root:/some/path
|
||||
raw_parent = item["parentReference"]["path"]
|
||||
prefix = "/drive/root:"
|
||||
if raw_parent.startswith(prefix):
|
||||
parent_path = raw_parent[len(prefix):]
|
||||
elif raw_parent == "/drive/root":
|
||||
parent_path = ""
|
||||
|
||||
item_path = f"{parent_path}/{item['name']}" if parent_path else f"/{item['name']}"
|
||||
|
||||
folders.append(
|
||||
{
|
||||
"name": item["name"],
|
||||
"path": item_path,
|
||||
"id": item.get("id", ""),
|
||||
"child_count": item.get("folder", {}).get("childCount", 0),
|
||||
}
|
||||
)
|
||||
|
||||
# Sort folders alphabetically
|
||||
folders.sort(key=lambda f: f["name"].lower())
|
||||
|
||||
return {
|
||||
"folders": folders,
|
||||
"path": f"/{folder_path}" if folder_path else "/",
|
||||
}
|
||||
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.exception(f"Error listing OneDrive folders: {e}")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=f"Failed to list folders: {str(e)}",
|
||||
)
|
||||
|
||||
|
||||
def format_time_remaining(time_delta):
|
||||
"""Format a timedelta into a human-readable string."""
|
||||
if time_delta.total_seconds() <= 0:
|
||||
|
||||
@@ -59,6 +59,40 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Folder selector (shown after authorization) -->
|
||||
<div id="folder-selector" class="hidden mt-6 p-4 bg-white border border-gray-200 rounded-lg">
|
||||
<h3 class="font-medium text-lg mb-3">
|
||||
<svg class="inline-block h-5 w-5 mr-1 text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
|
||||
<path fill-rule="evenodd" d="M2 6a2 2 0 012-2h4l2 2h4a2 2 0 012 2v1H8a3 3 0 00-3 3v1.5a1.5 1.5 0 01-3 0V6z" clip-rule="evenodd" />
|
||||
<path d="M6 12a2 2 0 012-2h8a2 2 0 012 2v2a2 2 0 01-2 2H2h2a2 2 0 002-2v-2z" />
|
||||
</svg>
|
||||
Select Folder
|
||||
</h3>
|
||||
<p class="text-sm text-gray-600 mb-3">Browse your Dropbox to select a folder for this integration.</p>
|
||||
|
||||
<div class="mb-3">
|
||||
<div id="folder-breadcrumb" class="flex items-center text-sm text-gray-500 mb-2">
|
||||
<button type="button" class="folder-nav-btn text-indigo-600 hover:text-indigo-800 font-medium" data-path="" aria-label="Navigate to root folder">/ Root</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="folder-list" class="border border-gray-200 rounded-md max-h-64 overflow-y-auto">
|
||||
<div class="p-4 text-center text-gray-500">
|
||||
<div class="animate-spin inline-block h-5 w-5 border-2 border-gray-300 border-t-indigo-600 rounded-full mb-2" role="status" aria-label="Loading folders"></div>
|
||||
<p class="text-sm">Loading folders…</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-3 flex items-center gap-3">
|
||||
<label for="selected-folder-path" class="text-sm font-medium text-gray-700 whitespace-nowrap">Selected folder:</label>
|
||||
<input id="selected-folder-path" type="text" class="flex-1 px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 text-sm" placeholder="/" />
|
||||
<button id="save-folder-btn" type="button" class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
|
||||
Save Folder
|
||||
</button>
|
||||
</div>
|
||||
<p id="folder-save-status" class="mt-2 text-sm hidden" aria-live="polite"></p>
|
||||
</div>
|
||||
|
||||
<div class="mt-6 p-4 bg-gray-100 rounded-md">
|
||||
<h3 class="font-medium text-lg mb-2">Configuration for Worker Nodes</h3>
|
||||
<p class="text-sm text-gray-600 mb-3">
|
||||
@@ -173,18 +207,21 @@ document.addEventListener('DOMContentLoaded', function() {
|
||||
}
|
||||
return response.json();
|
||||
}).then(() => {
|
||||
// Clean up
|
||||
// Clean up session storage
|
||||
sessionStorage.removeItem('dropbox_app_key');
|
||||
sessionStorage.removeItem('dropbox_app_secret');
|
||||
sessionStorage.removeItem('dropbox_folder_path');
|
||||
sessionStorage.removeItem('oauth_integration_id');
|
||||
sessionStorage.removeItem('dropbox_use_system_creds');
|
||||
|
||||
// Show brief success then redirect to integrations
|
||||
document.getElementById('processing-message').innerHTML =
|
||||
'<p class="text-green-600 font-semibold">✓ Dropbox authorized successfully!</p>' +
|
||||
'<p class="text-sm text-gray-500 mt-2">Redirecting to Integrations...</p>';
|
||||
// Hide processing spinner, show success
|
||||
document.querySelector('.animate-spin').parentNode.classList.add('hidden');
|
||||
setTimeout(() => { window.location.href = '/integrations'; }, 2000);
|
||||
document.getElementById('processing-message').innerHTML =
|
||||
'<p class="text-green-600 font-semibold">✓ Dropbox authorized successfully!</p>';
|
||||
document.getElementById('success-container').classList.remove('hidden');
|
||||
|
||||
// Show folder browser with the access token
|
||||
initFolderBrowser(data.access_token, integrationId);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -279,6 +316,122 @@ DROPBOX_FOLDER=${folderPath || '/Documents/Uploads'}`;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// ── Folder browser ────────────────────────────────────────────────
|
||||
function initFolderBrowser(accessToken, integrationId) {
|
||||
const folderSelector = document.getElementById('folder-selector');
|
||||
if (!folderSelector || !integrationId) return;
|
||||
|
||||
folderSelector.classList.remove('hidden');
|
||||
let currentPath = '';
|
||||
|
||||
const folderList = document.getElementById('folder-list');
|
||||
const breadcrumb = document.getElementById('folder-breadcrumb');
|
||||
const selectedInput = document.getElementById('selected-folder-path');
|
||||
const saveBtn = document.getElementById('save-folder-btn');
|
||||
const saveStatus = document.getElementById('folder-save-status');
|
||||
|
||||
function loadFolders(path) {
|
||||
currentPath = path;
|
||||
folderList.innerHTML = '<div class="p-4 text-center text-gray-500"><div class="animate-spin inline-block h-5 w-5 border-2 border-gray-300 border-t-indigo-600 rounded-full mb-2" role="status" aria-label="Loading folders"></div><p class="text-sm">Loading folders…</p></div>';
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('access_token', accessToken);
|
||||
formData.append('path', path);
|
||||
|
||||
fetch('/api/dropbox/list-folders', { method: 'POST', body: formData })
|
||||
.then(r => r.json())
|
||||
.then(data => {
|
||||
if (data.folders && data.folders.length > 0) {
|
||||
folderList.innerHTML = data.folders.map(f =>
|
||||
`<button type="button" class="folder-item w-full text-left px-4 py-3 hover:bg-indigo-50 border-b border-gray-100 flex items-center gap-3 text-sm focus:outline-none focus:bg-indigo-50" data-path="${f.path}" aria-label="Open folder ${f.name}">` +
|
||||
`<svg class="h-5 w-5 text-yellow-400 flex-shrink-0" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true"><path fill-rule="evenodd" d="M2 6a2 2 0 012-2h4l2 2h4a2 2 0 012 2v1H8a3 3 0 00-3 3v1.5a1.5 1.5 0 01-3 0V6z" clip-rule="evenodd" /><path d="M6 12a2 2 0 012-2h8a2 2 0 012 2v2a2 2 0 01-2 2H2h2a2 2 0 002-2v-2z" /></svg>` +
|
||||
`<span class="font-medium text-gray-700">${f.name}</span>` +
|
||||
`</button>`
|
||||
).join('');
|
||||
|
||||
folderList.querySelectorAll('.folder-item').forEach(btn => {
|
||||
btn.addEventListener('click', () => {
|
||||
const p = btn.getAttribute('data-path');
|
||||
selectedInput.value = p;
|
||||
loadFolders(p);
|
||||
});
|
||||
});
|
||||
} else {
|
||||
folderList.innerHTML = '<div class="p-4 text-center text-gray-400 text-sm">No subfolders found</div>';
|
||||
}
|
||||
updateBreadcrumb(path);
|
||||
})
|
||||
.catch(err => {
|
||||
folderList.innerHTML = `<div class="p-4 text-center text-red-500 text-sm">Failed to load folders: ${err.message}</div>`;
|
||||
});
|
||||
}
|
||||
|
||||
function updateBreadcrumb(path) {
|
||||
const parts = path.split('/').filter(Boolean);
|
||||
let html = '<button type="button" class="folder-nav-btn text-indigo-600 hover:text-indigo-800 font-medium" data-path="" aria-label="Navigate to root folder">/ Root</button>';
|
||||
let accumulated = '';
|
||||
for (const part of parts) {
|
||||
accumulated += '/' + part;
|
||||
html += `<span class="mx-1 text-gray-400">/</span>`;
|
||||
html += `<button type="button" class="folder-nav-btn text-indigo-600 hover:text-indigo-800 font-medium" data-path="${accumulated}" aria-label="Navigate to ${part}">${part}</button>`;
|
||||
}
|
||||
breadcrumb.innerHTML = html;
|
||||
breadcrumb.querySelectorAll('.folder-nav-btn').forEach(btn => {
|
||||
btn.addEventListener('click', () => {
|
||||
const p = btn.getAttribute('data-path');
|
||||
selectedInput.value = p || '/';
|
||||
loadFolders(p);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Save selected folder to integration config
|
||||
saveBtn.addEventListener('click', () => {
|
||||
const folderPath = selectedInput.value.trim() || '/';
|
||||
saveBtn.disabled = true;
|
||||
saveBtn.textContent = 'Saving…';
|
||||
|
||||
// Get the current integration config, update folder_path, then PUT back
|
||||
fetch(`/api/integrations/${integrationId}`)
|
||||
.then(r => r.json())
|
||||
.then(intg => {
|
||||
const cfg = intg.config || {};
|
||||
// Update the correct folder key based on integration type
|
||||
if (cfg.source_type) {
|
||||
cfg.folder_path = folderPath;
|
||||
} else {
|
||||
cfg.folder = folderPath;
|
||||
}
|
||||
return fetch(`/api/integrations/${integrationId}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ config: cfg }),
|
||||
});
|
||||
})
|
||||
.then(r => {
|
||||
if (!r.ok) throw new Error('Failed to save folder');
|
||||
return r.json();
|
||||
})
|
||||
.then(() => {
|
||||
saveStatus.textContent = '✓ Folder saved! Redirecting…';
|
||||
saveStatus.className = 'mt-2 text-sm text-green-600';
|
||||
saveStatus.classList.remove('hidden');
|
||||
saveBtn.textContent = 'Saved ✓';
|
||||
setTimeout(() => { window.location.href = '/integrations'; }, 1500);
|
||||
})
|
||||
.catch(err => {
|
||||
saveStatus.textContent = 'Error: ' + err.message;
|
||||
saveStatus.className = 'mt-2 text-sm text-red-600';
|
||||
saveStatus.classList.remove('hidden');
|
||||
saveBtn.disabled = false;
|
||||
saveBtn.textContent = 'Save Folder';
|
||||
});
|
||||
});
|
||||
|
||||
// Load root folders initially
|
||||
loadFolders('');
|
||||
}
|
||||
});
|
||||
</script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -59,6 +59,40 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Folder selector (shown after authorization) -->
|
||||
<div id="folder-selector" class="hidden mt-6 p-4 bg-white border border-gray-200 rounded-lg">
|
||||
<h3 class="font-medium text-lg mb-3">
|
||||
<svg class="inline-block h-5 w-5 mr-1 text-gray-500" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
|
||||
<path fill-rule="evenodd" d="M2 6a2 2 0 012-2h4l2 2h4a2 2 0 012 2v1H8a3 3 0 00-3 3v1.5a1.5 1.5 0 01-3 0V6z" clip-rule="evenodd" />
|
||||
<path d="M6 12a2 2 0 012-2h8a2 2 0 012 2v2a2 2 0 01-2 2H2h2a2 2 0 002-2v-2z" />
|
||||
</svg>
|
||||
Select Folder
|
||||
</h3>
|
||||
<p class="text-sm text-gray-600 mb-3">Browse your OneDrive to select a folder for this integration.</p>
|
||||
|
||||
<div class="mb-3">
|
||||
<div id="folder-breadcrumb" class="flex items-center text-sm text-gray-500 mb-2">
|
||||
<button type="button" class="folder-nav-btn text-indigo-600 hover:text-indigo-800 font-medium" data-path="" aria-label="Navigate to root folder">/ Root</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="folder-list" class="border border-gray-200 rounded-md max-h-64 overflow-y-auto">
|
||||
<div class="p-4 text-center text-gray-500">
|
||||
<div class="animate-spin inline-block h-5 w-5 border-2 border-gray-300 border-t-indigo-600 rounded-full mb-2" role="status" aria-label="Loading folders"></div>
|
||||
<p class="text-sm">Loading folders…</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-3 flex items-center gap-3">
|
||||
<label for="selected-folder-path" class="text-sm font-medium text-gray-700 whitespace-nowrap">Selected folder:</label>
|
||||
<input id="selected-folder-path" type="text" class="flex-1 px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:ring-indigo-500 focus:border-indigo-500 text-sm" placeholder="/" />
|
||||
<button id="save-folder-btn" type="button" class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
|
||||
Save Folder
|
||||
</button>
|
||||
</div>
|
||||
<p id="folder-save-status" class="mt-2 text-sm hidden" aria-live="polite"></p>
|
||||
</div>
|
||||
|
||||
<div class="mt-6 p-4 bg-gray-100 rounded-md">
|
||||
<h3 class="font-medium text-lg mb-2">Configuration for Worker Nodes</h3>
|
||||
<p class="text-sm text-gray-600 mb-3">
|
||||
@@ -177,19 +211,22 @@ document.addEventListener('DOMContentLoaded', function() {
|
||||
}
|
||||
return response.json();
|
||||
}).then(() => {
|
||||
// Clean up
|
||||
// Clean up session storage
|
||||
sessionStorage.removeItem('onedrive_client_id');
|
||||
sessionStorage.removeItem('onedrive_client_secret');
|
||||
sessionStorage.removeItem('onedrive_tenant_id');
|
||||
sessionStorage.removeItem('onedrive_folder_path');
|
||||
sessionStorage.removeItem('oauth_integration_id');
|
||||
sessionStorage.removeItem('onedrive_use_system_creds');
|
||||
|
||||
// Show brief success then redirect to integrations
|
||||
document.getElementById('processing-message').innerHTML =
|
||||
'<p class="text-green-600 font-semibold">✓ OneDrive authorized successfully!</p>' +
|
||||
'<p class="text-sm text-gray-500 mt-2">Redirecting to Integrations...</p>';
|
||||
// Hide processing spinner, show success
|
||||
document.querySelector('.animate-spin').parentNode.classList.add('hidden');
|
||||
setTimeout(() => { window.location.href = '/integrations'; }, 2000);
|
||||
document.getElementById('processing-message').innerHTML =
|
||||
'<p class="text-green-600 font-semibold">✓ OneDrive authorized successfully!</p>';
|
||||
document.getElementById('success-container').classList.remove('hidden');
|
||||
|
||||
// Show folder browser with the access token
|
||||
initFolderBrowser(data.access_token, integrationId);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -291,6 +328,114 @@ ONEDRIVE_FOLDER_PATH=${folderPath || 'Documents/Uploads'}`;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// ── Folder browser ────────────────────────────────────────────────
|
||||
function initFolderBrowser(accessToken, integrationId) {
|
||||
const folderSelector = document.getElementById('folder-selector');
|
||||
if (!folderSelector || !integrationId || !accessToken) return;
|
||||
|
||||
folderSelector.classList.remove('hidden');
|
||||
|
||||
const folderList = document.getElementById('folder-list');
|
||||
const breadcrumb = document.getElementById('folder-breadcrumb');
|
||||
const selectedInput = document.getElementById('selected-folder-path');
|
||||
const saveBtn = document.getElementById('save-folder-btn');
|
||||
const saveStatus = document.getElementById('folder-save-status');
|
||||
|
||||
function loadFolders(path) {
|
||||
folderList.innerHTML = '<div class="p-4 text-center text-gray-500"><div class="animate-spin inline-block h-5 w-5 border-2 border-gray-300 border-t-indigo-600 rounded-full mb-2" role="status" aria-label="Loading folders"></div><p class="text-sm">Loading folders…</p></div>';
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('access_token', accessToken);
|
||||
formData.append('path', path);
|
||||
|
||||
fetch('/api/onedrive/list-folders', { method: 'POST', body: formData })
|
||||
.then(r => r.json())
|
||||
.then(data => {
|
||||
if (data.folders && data.folders.length > 0) {
|
||||
folderList.innerHTML = data.folders.map(f =>
|
||||
`<button type="button" class="folder-item w-full text-left px-4 py-3 hover:bg-indigo-50 border-b border-gray-100 flex items-center gap-3 text-sm focus:outline-none focus:bg-indigo-50" data-path="${f.path}" aria-label="Open folder ${f.name}">` +
|
||||
`<svg class="h-5 w-5 text-blue-400 flex-shrink-0" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true"><path fill-rule="evenodd" d="M2 6a2 2 0 012-2h4l2 2h4a2 2 0 012 2v1H8a3 3 0 00-3 3v1.5a1.5 1.5 0 01-3 0V6z" clip-rule="evenodd" /><path d="M6 12a2 2 0 012-2h8a2 2 0 012 2v2a2 2 0 01-2 2H2h2a2 2 0 002-2v-2z" /></svg>` +
|
||||
`<span class="font-medium text-gray-700">${f.name}</span>` +
|
||||
`</button>`
|
||||
).join('');
|
||||
|
||||
folderList.querySelectorAll('.folder-item').forEach(btn => {
|
||||
btn.addEventListener('click', () => {
|
||||
const p = btn.getAttribute('data-path');
|
||||
selectedInput.value = p;
|
||||
loadFolders(p.replace(/^\//, ''));
|
||||
});
|
||||
});
|
||||
} else {
|
||||
folderList.innerHTML = '<div class="p-4 text-center text-gray-400 text-sm">No subfolders found</div>';
|
||||
}
|
||||
updateBreadcrumb(path);
|
||||
})
|
||||
.catch(err => {
|
||||
folderList.innerHTML = `<div class="p-4 text-center text-red-500 text-sm">Failed to load folders: ${err.message}</div>`;
|
||||
});
|
||||
}
|
||||
|
||||
function updateBreadcrumb(path) {
|
||||
const parts = path.split('/').filter(Boolean);
|
||||
let html = '<button type="button" class="folder-nav-btn text-indigo-600 hover:text-indigo-800 font-medium" data-path="" aria-label="Navigate to root folder">/ Root</button>';
|
||||
let accumulated = '';
|
||||
for (const part of parts) {
|
||||
accumulated += '/' + part;
|
||||
html += `<span class="mx-1 text-gray-400">/</span>`;
|
||||
html += `<button type="button" class="folder-nav-btn text-indigo-600 hover:text-indigo-800 font-medium" data-path="${accumulated.replace(/^\//, '')}" aria-label="Navigate to ${part}">${part}</button>`;
|
||||
}
|
||||
breadcrumb.innerHTML = html;
|
||||
breadcrumb.querySelectorAll('.folder-nav-btn').forEach(btn => {
|
||||
btn.addEventListener('click', () => {
|
||||
const p = btn.getAttribute('data-path');
|
||||
selectedInput.value = p ? '/' + p : '/';
|
||||
loadFolders(p);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Save selected folder to integration config
|
||||
saveBtn.addEventListener('click', () => {
|
||||
const folderPath = selectedInput.value.trim() || '/';
|
||||
saveBtn.disabled = true;
|
||||
saveBtn.textContent = 'Saving…';
|
||||
|
||||
fetch(`/api/integrations/${integrationId}`)
|
||||
.then(r => r.json())
|
||||
.then(intg => {
|
||||
const cfg = intg.config || {};
|
||||
cfg.folder_path = folderPath;
|
||||
return fetch(`/api/integrations/${integrationId}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ config: cfg }),
|
||||
});
|
||||
})
|
||||
.then(r => {
|
||||
if (!r.ok) throw new Error('Failed to save folder');
|
||||
return r.json();
|
||||
})
|
||||
.then(() => {
|
||||
saveStatus.textContent = '✓ Folder saved! Redirecting…';
|
||||
saveStatus.className = 'mt-2 text-sm text-green-600';
|
||||
saveStatus.classList.remove('hidden');
|
||||
saveBtn.textContent = 'Saved ✓';
|
||||
setTimeout(() => { window.location.href = '/integrations'; }, 1500);
|
||||
})
|
||||
.catch(err => {
|
||||
saveStatus.textContent = 'Error: ' + err.message;
|
||||
saveStatus.className = 'mt-2 text-sm text-red-600';
|
||||
saveStatus.classList.remove('hidden');
|
||||
saveBtn.disabled = false;
|
||||
saveBtn.textContent = 'Save Folder';
|
||||
});
|
||||
});
|
||||
|
||||
// Load root folders initially
|
||||
loadFolders('');
|
||||
}
|
||||
});
|
||||
</script>
|
||||
{% endblock %}
|
||||
|
||||
Reference in New Issue
Block a user