feat: folder ownership scoping, batch operations integration, frontend audit fixes

Backend:
- Add owner_id to Folder entity + FolderDto (DB user_id column)
- Add list_folders_by_owner to FolderRepository trait + PG impl
- Add list_folders_for_owner to FolderUseCase + FolderService
- Rewrite FolderHandler: all endpoints now scope by AuthUser
- Remove dead handler methods (list_folders_inner, list_folders_for_user, is_user_home_folder, folder_belongs_to_user)
- Add ownership check in get_folder (returns 404 on mismatch)

Batch operations:
- Add trash_service + zip_service to BatchOperationService
- New methods: trash_files, trash_folders, move_folders, download_zip
- New handlers: trash_batch, move_folders_batch, download_batch
- New routes: POST /api/batch/trash, /api/batch/folders/move, /api/batch/download

Frontend:
- Replace findUserHomeFolder (~130 lines) with resolveHomeFolder (~35 lines)
- Remove client-side folder filtering in loadFiles (backend now scopes)
- Rewrite batchDelete: N requests -> 1 POST /api/batch/trash
- Rewrite batchMove: N requests -> 2 POST max (files + folders)
- Rewrite batchDownload: N requests -> 1 POST /api/batch/download (ZIP)
- Search moved to backend, share system uses backend API
- Dark mode fixes, frontend audit improvements
This commit is contained in:
Dionisio
2026-02-15 23:45:11 +01:00
parent 6e1b77f244
commit 7737ed90c7
33 changed files with 3078 additions and 1958 deletions
+70
View File
@@ -4,6 +4,8 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>OxiCloud — Admin Panel</title>
<!-- Apply saved theme immediately to prevent flash of light mode -->
<script>if(localStorage.getItem('oxicloud_theme')==='dark')document.documentElement.setAttribute('data-theme','dark');</script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
<style>
*{box-sizing:border-box;margin:0;padding:0;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Oxygen,Ubuntu,Cantarell,'Open Sans','Helvetica Neue',sans-serif}
@@ -194,6 +196,74 @@ details[open] summary{margin-bottom:14px;color:#ff5e3a}
/* ── Pagination ── */
.pagination{display:flex;align-items:center;justify-content:space-between;margin-top:14px;font-size:13px;color:#94a3b8;padding:0 4px}
.pagination button{padding:6px 14px}
/* ── Dark Mode ── */
[data-theme="dark"] body{background:#0f172a;color:#e2e8f0}
[data-theme="dark"] ::-webkit-scrollbar-thumb{background:rgba(255,255,255,.15)}
[data-theme="dark"] *{scrollbar-color:rgba(255,255,255,.15) transparent}
[data-theme="dark"] .admin-tabs{background:#1e293b;box-shadow:0 1px 4px rgba(0,0,0,.2)}
[data-theme="dark"] .admin-tab{color:#94a3b8}
[data-theme="dark"] .admin-tab:hover{color:#f1f5f9;background:#162032}
[data-theme="dark"] .admin-card{background:#1e293b;box-shadow:0 1px 4px rgba(0,0,0,.2),0 0 0 1px rgba(255,255,255,.03)}
[data-theme="dark"] .admin-card h2{color:#f1f5f9}
[data-theme="dark"] .stat-card{background:#162032;border-color:#334155}
[data-theme="dark"] .stat-card:hover{box-shadow:0 4px 12px rgba(0,0,0,.15)}
[data-theme="dark"] .stat-value{color:#f1f5f9}
[data-theme="dark"] .stat-label{color:#64748b}
[data-theme="dark"] .stat-card.warn{border-color:#92400e;background:#422006}
[data-theme="dark"] .stat-card.danger{border-color:#991b1b;background:#3b1111}
[data-theme="dark"] .progress-bar{background:#334155}
[data-theme="dark"] .table-wrap{border-color:#334155}
[data-theme="dark"] th{background:#162032;color:#64748b;border-bottom-color:#334155}
[data-theme="dark"] td{border-bottom-color:#334155;color:#e2e8f0}
[data-theme="dark"] tr:hover{background:#162032}
[data-theme="dark"] .user-name{color:#f1f5f9}
[data-theme="dark"] .user-email{color:#64748b}
[data-theme="dark"] .badge-admin{background:#1e3a5f;color:#60a5fa}
[data-theme="dark"] .badge-user{background:#334155;color:#94a3b8}
[data-theme="dark"] .badge-active{background:#052e16;color:#86efac}
[data-theme="dark"] .badge-inactive{background:#3b1111;color:#fca5a5}
[data-theme="dark"] .badge-oidc{background:#2e1065;color:#c4b5fd}
[data-theme="dark"] .btn-secondary{background:#1e293b;color:#e2e8f0;border-color:#334155}
[data-theme="dark"] .btn-secondary:hover{background:#334155;border-color:#475569}
[data-theme="dark"] .btn-danger{background:#3b1111;color:#fca5a5;border-color:#991b1b}
[data-theme="dark"] .btn-danger:hover{background:#4a1515}
[data-theme="dark"] .btn-success{background:#052e16;color:#86efac;border-color:#065f46}
[data-theme="dark"] .btn-success:hover{background:#064e27}
[data-theme="dark"] .form-group label{color:#94a3b8}
[data-theme="dark"] .form-group input[type="text"],
[data-theme="dark"] .form-group input[type="password"],
[data-theme="dark"] .form-group input[type="url"],
[data-theme="dark"] .form-group input[type="number"],
[data-theme="dark"] .form-group select{background:#0f172a;border-color:#334155;color:#e2e8f0}
[data-theme="dark"] .form-group input:focus,
[data-theme="dark"] .form-group select:focus{border-color:#ff5e3a;background:#0f172a;box-shadow:0 0 0 3px rgba(255,94,58,.15)}
[data-theme="dark"] .form-group small{color:#64748b}
[data-theme="dark"] .toggle-row label{color:#94a3b8}
[data-theme="dark"] .slider{background:#475569}
[data-theme="dark"] .readonly-field{background:#0f172a;border-color:#334155;color:#e2e8f0}
[data-theme="dark"] .readonly-field button{background:#1e293b;border-color:#334155;color:#94a3b8}
[data-theme="dark"] .readonly-field button:hover{background:#334155;color:#f1f5f9}
[data-theme="dark"] .warning{background:#422006;border-color:#92400e;color:#fbbf24}
[data-theme="dark"] .alert-success{background:#052e16;color:#86efac;border-color:#065f46}
[data-theme="dark"] .alert-error{background:#3b1111;color:#fca5a5;border-color:#991b1b}
[data-theme="dark"] .alert-info{background:#0c2d48;color:#93c5fd;border-color:#1d4ed8}
[data-theme="dark"] .discovery-result.ok{background:#052e16;border-color:#065f46;color:#86efac}
[data-theme="dark"] .discovery-result.fail{background:#3b1111;border-color:#991b1b;color:#fca5a5}
[data-theme="dark"] details{border-top-color:#334155}
[data-theme="dark"] details summary{color:#94a3b8}
[data-theme="dark"] details summary:hover{color:#ff5e3a}
[data-theme="dark"] details[open] summary{color:#ff5e3a}
[data-theme="dark"] .modal{background:#1e293b;box-shadow:0 20px 60px rgba(0,0,0,.4)}
[data-theme="dark"] .modal h3{color:#f1f5f9}
[data-theme="dark"] .modal-overlay{background:rgba(0,0,0,.6);backdrop-filter:blur(4px)}
[data-theme="dark"] .quota-text{color:#64748b}
[data-theme="dark"] .pagination{color:#64748b}
[data-theme="dark"] #access-denied h2{color:#fca5a5}
[data-theme="dark"] #access-denied p{color:#94a3b8}
[data-theme="dark"] #access-denied .access-icon{background:#3b1111}
[data-theme="dark"] #loading{color:#64748b}
[data-theme="dark"] .toggle-row{border-top-color:#334155}
</style>
</head>
<body>
+118
View File
@@ -465,3 +465,121 @@
max-height: 200px;
}
}
/* ============================================================
DARK MODE — Auth Pages
============================================================ */
[data-theme="dark"] .auth-container {
background-color: #0f172a;
}
[data-theme="dark"] .auth-panel {
background-color: #1e293b;
box-shadow: 0 5px 20px rgba(0, 0, 0, 0.3);
}
[data-theme="dark"] .auth-logo-text {
color: #f1f5f9;
}
[data-theme="dark"] .auth-title {
color: #f1f5f9;
}
[data-theme="dark"] .auth-label {
color: #94a3b8;
}
[data-theme="dark"] .auth-input {
background-color: #0f172a;
border-color: #334155;
color: #e2e8f0;
}
[data-theme="dark"] .auth-input:focus {
border-color: #ff5e3a;
background-color: #0f172a;
box-shadow: 0 0 0 3px rgba(255, 94, 58, 0.15);
}
[data-theme="dark"] .auth-input::placeholder {
color: #64748b;
}
[data-theme="dark"] .auth-error {
background-color: #3b1111;
color: #fca5a5;
}
[data-theme="dark"] .auth-success {
background-color: #052e16;
color: #86efac;
}
[data-theme="dark"] .auth-toggle {
color: #94a3b8;
}
[data-theme="dark"] .auth-divider {
color: #64748b;
}
[data-theme="dark"] .auth-divider::before,
[data-theme="dark"] .auth-divider::after {
background: #334155;
}
[data-theme="dark"] .language-subtitle {
color: #94a3b8;
}
[data-theme="dark"] .lang-picker-selected {
background-color: #0f172a;
border-color: #334155;
}
[data-theme="dark"] .lang-picker-selected:hover {
border-color: #ff5e3a;
background-color: #162032;
}
[data-theme="dark"] .lang-picker.open .lang-picker-selected {
border-color: #ff5e3a;
background-color: #162032;
}
[data-theme="dark"] .lang-picker-name {
color: #f1f5f9;
}
[data-theme="dark"] .lang-picker-arrow {
color: #64748b;
}
[data-theme="dark"] .lang-picker-dropdown {
background: #1e293b;
border-color: #ff5e3a;
border-top-color: #334155;
box-shadow: 0 12px 32px rgba(0, 0, 0, 0.3);
}
[data-theme="dark"] .lang-picker-search {
border-bottom-color: #334155;
}
[data-theme="dark"] .lang-picker-search input {
background-color: #0f172a;
border-color: #334155;
color: #e2e8f0;
}
[data-theme="dark"] .lang-picker-search input:focus {
border-color: #ff5e3a;
}
[data-theme="dark"] .lang-picker-search input::placeholder {
color: #64748b;
}
[data-theme="dark"] .lang-picker-list::-webkit-scrollbar-thumb {
background: #475569;
}
[data-theme="dark"] .lang-picker-item:hover {
background: #162032;
}
[data-theme="dark"] .lang-picker-item.selected {
background: #2a1a15;
}
[data-theme="dark"] .lang-picker-item-name {
color: #f1f5f9;
}
[data-theme="dark"] .lang-picker-item-english {
color: #64748b;
}
[data-theme="dark"] .lang-picker-empty {
color: #64748b;
}
/* Setup steps */
[data-theme="dark"] .step-number {
background-color: #334155;
color: #94a3b8;
}
[data-theme="dark"] .step-title {
color: #94a3b8;
}
+171
View File
@@ -371,6 +371,8 @@ select:focus {
margin-bottom: 15px;
border-bottom: 1px solid #eee;
width: 100%;
flex-wrap: wrap;
gap: 8px;
}
.search-results-header h3 {
@@ -379,6 +381,33 @@ select:focus {
color: #555;
}
.search-results-header .search-time {
font-size: 12px;
font-weight: normal;
color: #999;
}
.search-controls {
display: flex;
align-items: center;
gap: 8px;
}
.search-sort-select {
padding: 4px 8px;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 13px;
background: #fff;
color: #333;
cursor: pointer;
outline: none;
}
.search-sort-select:focus {
border-color: var(--primary-color, #4a90d9);
}
.empty-state {
display: flex;
flex-direction: column;
@@ -4567,4 +4596,146 @@ html[dir='rtl'] .fa-sign-out-alt {
/* Search results header */
[data-theme="dark"] .search-results-header h3 {
color: #f1f5f9;
}
/* ── Shared View Dark Mode ── */
[data-theme="dark"] .shared-filters {
background-color: transparent;
}
[data-theme="dark"] .filter-group label {
color: #94a3b8;
}
[data-theme="dark"] .filter-group select {
background-color: #1e293b;
border-color: #334155;
color: #e2e8f0;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%2394a3b8' d='M6 8L1 3h10z'/%3E%3C/svg%3E");
}
[data-theme="dark"] .filter-group select:focus {
border-color: #ff5e3a;
box-shadow: 0 0 0 3px rgba(255, 94, 58, 0.15);
}
[data-theme="dark"] .search-box input {
background-color: #1e293b;
border-color: #334155;
color: #e2e8f0;
}
[data-theme="dark"] .search-box input::placeholder {
color: #64748b;
}
[data-theme="dark"] .shared-list-container {
background-color: #1e293b;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
}
[data-theme="dark"] .shared-list thead th {
background-color: #162032;
color: #94a3b8;
border-bottom-color: #334155;
}
[data-theme="dark"] .shared-list tbody td {
border-bottom-color: #334155;
color: #e2e8f0;
}
[data-theme="dark"] .shared-list tbody tr:hover {
background-color: #162032;
}
[data-theme="dark"] .page-description {
color: #94a3b8;
}
[data-theme="dark"] .empty-state h3 {
color: #f1f5f9;
}
[data-theme="dark"] .empty-state p {
color: #94a3b8;
}
[data-theme="dark"] .empty-state .button.primary {
background: linear-gradient(135deg, #ff5e3a, #ff2d55);
color: #fff;
}
/* Shared view action buttons */
[data-theme="dark"] .shared-list .action-btn {
color: #94a3b8;
}
[data-theme="dark"] .shared-list .action-btn:hover {
color: #ff5e3a;
}
/* Share dialog dark mode (shared view specific) */
[data-theme="dark"] .dialog {
background-color: rgba(0, 0, 0, 0.6);
}
[data-theme="dark"] .dialog-content {
background-color: #1e293b;
color: #e2e8f0;
}
[data-theme="dark"] .dialog-header {
border-bottom-color: #334155;
}
[data-theme="dark"] .dialog-header h3 {
color: #f1f5f9;
}
[data-theme="dark"] .dialog-body label {
color: #94a3b8;
}
[data-theme="dark"] .dialog-body input,
[data-theme="dark"] .dialog-body textarea {
background-color: #0f172a;
border-color: #334155;
color: #e2e8f0;
}
[data-theme="dark"] .dialog-body input:focus,
[data-theme="dark"] .dialog-body textarea:focus {
border-color: #ff5e3a;
}
[data-theme="dark"] .close-dialog-btn {
color: #94a3b8;
}
[data-theme="dark"] .close-dialog-btn:hover {
color: #f1f5f9;
}
[data-theme="dark"] .notification-banner {
background-color: #1e293b;
color: #e2e8f0;
border-color: #334155;
}
[data-theme="dark"] .share-setting label {
color: #94a3b8;
}
[data-theme="dark"] .permissions-options label span {
color: #e2e8f0;
}
[data-theme="dark"] .share-item-info {
color: #e2e8f0;
}
/* Batch bar dark mode */
[data-theme="dark"] .batch-bar {
background-color: #1e293b;
border-color: #334155;
color: #e2e8f0;
}
/* Search results dark mode */
[data-theme="dark"] .search-results-header {
color: #f1f5f9;
border-bottom-color: #334155;
}
[data-theme="dark"] .search-results-header h3 {
color: #f1f5f9;
}
[data-theme="dark"] .search-results-header .search-time {
color: #64748b;
}
[data-theme="dark"] .search-results-header .btn-secondary {
background: #1e293b;
border-color: #334155;
color: #e2e8f0;
}
[data-theme="dark"] .search-results-header .btn-secondary:hover {
background: #334155;
}
[data-theme="dark"] .search-sort-select {
background: #1e293b;
border-color: #334155;
color: #e2e8f0;
}
[data-theme="dark"] .search-sort-select:focus {
border-color: #ff5e3a;
}
+97 -183
View File
@@ -396,9 +396,16 @@ function setupEventListeners() {
// Set up drag and drop
ui.setupDragAndDrop();
// Search input
// Debounce timer for live search
let searchDebounceTimer = null;
const SEARCH_DEBOUNCE_MS = 300;
const SEARCH_MIN_CHARS = 3;
// Search input — Enter key
elements.searchInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
// Cancel any pending debounce
if (searchDebounceTimer) clearTimeout(searchDebounceTimer);
const query = elements.searchInput.value.trim();
if (query) {
performSearch(query);
@@ -412,8 +419,29 @@ function setupEventListeners() {
}
});
// Search input — Live search (debounced, after 3+ chars)
elements.searchInput.addEventListener('input', () => {
if (searchDebounceTimer) clearTimeout(searchDebounceTimer);
const query = elements.searchInput.value.trim();
if (query.length >= SEARCH_MIN_CHARS) {
searchDebounceTimer = setTimeout(() => {
performSearch(query);
}, SEARCH_DEBOUNCE_MS);
} else if (query.length === 0 && app.isSearchMode) {
// User cleared the search input — return to normal view
searchDebounceTimer = setTimeout(() => {
app.isSearchMode = false;
app.currentPath = '';
ui.updateBreadcrumb('');
loadFiles();
}, SEARCH_DEBOUNCE_MS);
}
});
// Search button
document.getElementById('search-button').addEventListener('click', () => {
if (searchDebounceTimer) clearTimeout(searchDebounceTimer);
const query = elements.searchInput.value.trim();
if (query) {
performSearch(query);
@@ -686,14 +714,7 @@ async function loadFiles(options = {}) {
// Always ensure a userHomeFolderId is set
if (!app.userHomeFolderId) {
// If we don't have a home folder ID yet, try to get the user's username
const USER_DATA_KEY = 'oxicloud_user';
const userData = JSON.parse(localStorage.getItem(USER_DATA_KEY) || '{}');
if (userData.username) {
// Find user's home folder
console.log("Looking for user folder for", userData.username);
await findUserHomeFolder(userData.username);
}
await resolveHomeFolder();
}
// Add timestamp to avoid cache
@@ -791,28 +812,9 @@ async function loadFiles(options = {}) {
// Add folders (check if it's an array)
const folderList = Array.isArray(folders) ? folders : [];
// Get user info for filtering
const USER_DATA_KEY = 'oxicloud_user';
const userData = JSON.parse(localStorage.getItem(USER_DATA_KEY) || '{}');
const username = userData.username || '';
// Filter folders before adding them to the view
const visibleFolders = folderList.filter(folder => {
// Skip system folders (starting with dot) when at root
if (!app.currentPath && folder.name.startsWith('.')) {
return false;
}
// Skip other users' folders when at root
if (!app.currentPath && folder.name.startsWith('My Folder - ') && !folder.name.includes(username)) {
return false;
}
return true;
});
// Add filtered folders to the view
visibleFolders.forEach(folder => {
// Backend already scopes folders to the authenticated user,
// so no client-side filtering is needed.
folderList.forEach(folder => {
ui.addFolderToView(folder);
});
@@ -1064,55 +1066,51 @@ function addTrashItemToView(item) {
}
/**
* Perform search with the given query
* Perform search with the given query.
* All processing (filtering, scoring, sorting, categorization) is done
* server-side in Rust. This function only sends the request and renders.
*
* @param {string} query - Search query
* @param {string} [sortBy] - Sort order (relevance|name|name_desc|date|date_desc|size|size_desc)
*/
async function performSearch(query) {
console.log(`Performing search for: "${query}"`);
async function performSearch(query, sortBy) {
console.log(`Performing search for: "${query}" (sort: ${sortBy || 'relevance'})`);
try {
// Update UI to indicate search mode
app.isSearchMode = true;
// Set breadcrumb for search
ui.updateBreadcrumb(`Search: "${query}"`);
// Prepare search options
// Show loading spinner
const filesGrid = document.getElementById('files-grid');
if (filesGrid) {
filesGrid.innerHTML = `
<div class="search-results-header">
<h3><i class="fas fa-spinner fa-spin" style="margin-right:8px;"></i> Searching for "${query}"...</h3>
</div>
`;
}
// All options — backend handles all processing
const options = {
recursive: true, // Search in all subfolders
limit: 100 // Limit results for performance
recursive: true,
limit: 100,
sort_by: sortBy || 'relevance'
};
// Always restrict search to the user's current folder context
// This ensures users can't search outside their personal folder
// Restrict search to user's folder context
if (!app.isTrashView) {
// If we're in a subfolder, search from there, otherwise use the user's home folder
options.folder_id = app.currentPath;
// Always include folder_id even if it's the root of user's home folder
// so user cannot search outside their allowed scope
if (!options.folder_id || options.folder_id === '') {
// Fall back to user's home folder - we should never be here
// because findUserHomeFolder should have set app.currentPath
console.warn("Search without folder_id - this shouldn't happen with proper user context");
// Try to get folder from localStorage if available
const USER_DATA_KEY = 'oxicloud_user';
const userData = JSON.parse(localStorage.getItem(USER_DATA_KEY) || '{}');
if (userData.username) {
console.log("Retrieving home folder for user before search");
await findUserHomeFolder(userData.username);
options.folder_id = app.currentPath;
}
await resolveHomeFolder();
options.folder_id = app.currentPath;
}
}
console.log(`Searching with options:`, options);
// Perform the search
// Send search request — backend does all processing
const searchResults = await window.search.searchFiles(query, options);
// Display search results
// Render enriched results from the server
window.search.displaySearchResults(searchResults);
} catch (error) {
@@ -1121,6 +1119,14 @@ async function performSearch(query) {
}
}
// Listen for re-sort events from the search sort dropdown
document.addEventListener('search-resort', (e) => {
const searchInput = document.querySelector('.search-container input');
if (searchInput && searchInput.value.trim()) {
performSearch(searchInput.value.trim(), e.detail.sort_by);
}
});
// Expose needed functions to global scope
window.app = app;
window.loadFiles = loadFiles;
@@ -1713,7 +1719,7 @@ async function checkAuthentication() {
});
// Find and load the user's home folder
findUserHomeFolder(userData.username);
resolveHomeFolder().then(() => loadFiles());
} else {
// No user data but token exists — try to fetch from server
console.log('No user data, attempting to fetch from server');
@@ -1723,7 +1729,7 @@ async function checkAuthentication() {
const userInitials = freshData.username.substring(0, 2).toUpperCase();
document.querySelectorAll('.user-avatar, .user-menu-avatar').forEach(el => el.textContent = userInitials);
updateStorageUsageDisplay(freshData);
findUserHomeFolder(freshData.username);
resolveHomeFolder().then(() => loadFiles());
} else {
// Server didn't return valid user data — token is likely invalid
console.warn('Could not retrieve user data, redirecting to login');
@@ -1757,131 +1763,39 @@ async function checkAuthentication() {
* Find the user's home folder and load it
* @param {string} username - The current user's username
*/
async function findUserHomeFolder(username) {
/**
* Resolve the user's home folder from the backend.
* Since the backend now scopes GET /api/folders to the authenticated user,
* we simply pick the first root-level folder returned.
*/
async function resolveHomeFolder() {
if (app.userHomeFolderId) return; // Already resolved
try {
console.log("Finding home folder for user:", username);
// CRITICAL FIX: Always create a default folder if needed
// This prevents loops when the folder can't be found
const defaultFolder = {
id: 'default-folder',
name: `My Folder - ${username}`,
parent_id: null,
created_at: Date.now() / 1000,
updated_at: Date.now() / 1000
};
// First, load all folders at the root
console.log("Fetching folders from API");
// Set max retries and timeout to prevent potential infinite loops
let retries = 0;
const maxRetries = 1; // Reduced from 2 to 1
while (retries < maxRetries) {
try {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 3000); // Reduced timeout to 3 seconds
const folderToken = localStorage.getItem('oxicloud_token');
const folderHeaders = folderToken ? { 'Authorization': `Bearer ${folderToken}` } : {};
const response = await fetch('/api/folders', {
headers: folderHeaders,
signal: controller.signal
});
clearTimeout(timeoutId);
if (response.status === 401 || response.status === 403) {
console.warn(`Authentication error (${response.status}) when fetching folders`);
// Use default folder to break the loop
console.log('Using default folder to prevent redirection loop');
app.userHomeFolderId = defaultFolder.id;
app.userHomeFolderName = defaultFolder.name;
app.currentPath = defaultFolder.id;
ui.updateBreadcrumb(defaultFolder.name);
loadFiles();
return;
}
if (!response.ok) {
throw new Error(`Error loading folders: ${response.status}`);
}
const folders = await response.json();
const folderList = Array.isArray(folders) ? folders : [];
console.log(`Found ${folderList.length} folders at root`);
// Look for a folder with a name pattern that matches the user's home folder
const homeFolderPattern = `My Folder - ${username}`;
// Filter first to remove system folders and other users' folders
const visibleFolders = folderList.filter(folder => {
// Skip system folders (starting with dot)
if (folder.name.startsWith('.')) {
return false;
}
// Skip other users' home folders
if (folder.name.startsWith('My Folder - ') && !folder.name.includes(username)) {
return false;
}
return true;
});
// Find the user's home folder from filtered list
let homeFolder = visibleFolders.find(folder => folder.name === homeFolderPattern);
if (homeFolder) {
console.log(`Found user's home folder: ${homeFolder.name} (${homeFolder.id})`);
// Store the home folder ID and name in the app state
// This is used for breadcrumb navigation and restricting user access
app.userHomeFolderId = homeFolder.id;
app.userHomeFolderName = homeFolder.name;
// Set this as the current path and load its contents
app.currentPath = homeFolder.id;
ui.updateBreadcrumb(homeFolder.name);
loadFiles();
return; // Success! Exit function
} else {
console.warn("Could not find user's home folder");
// SECURITY: Never fall back to another user's folder.
// If user's own folder doesn't exist, show root (empty state).
console.log('User home folder not found, showing root');
app.currentPath = '';
ui.updateBreadcrumb('');
loadFiles();
return;
}
// If we get here, we've successfully processed the response
break;
} catch (fetchError) {
retries++;
console.error(`Fetch attempt ${retries} failed:`, fetchError);
if (retries >= maxRetries) {
throw fetchError; // Re-throw after max retries
}
// Wait before retrying
await new Promise(resolve => setTimeout(resolve, 1000));
}
const token = localStorage.getItem('oxicloud_token');
const headers = token ? { 'Authorization': `Bearer ${token}` } : {};
const response = await fetch('/api/folders', { headers });
if (!response.ok) {
console.warn(`Could not fetch home folder: ${response.status}`);
return;
}
const folders = await response.json();
const folderList = Array.isArray(folders) ? folders : [];
if (folderList.length > 0) {
const home = folderList[0];
app.userHomeFolderId = home.id;
app.userHomeFolderName = home.name;
app.currentPath = home.id;
ui.updateBreadcrumb(home.name);
console.log(`Home folder resolved: ${home.name} (${home.id})`);
} else {
console.warn('No root folders found for user');
app.currentPath = '';
ui.updateBreadcrumb('');
}
} catch (error) {
console.error('Error finding user home folder:', error);
// Fall back to loading root in case of error
// This is a critical fallback to prevent infinite loops
console.error('Error resolving home folder:', error);
app.currentPath = '';
ui.updateBreadcrumb('');
loadFiles();
}
}
File diff suppressed because it is too large Load Diff
+37 -35
View File
@@ -206,22 +206,39 @@ const contextMenus = {
if (window.app.moveDialogMode === 'batch' && window.multiSelect) {
const targetId = window.app.selectedTargetFolderId;
const items = window.app.batchMoveItems || [];
const fileIds = items.filter(i => i.type === 'file').map(i => i.id);
const folderIds = items.filter(i => i.type === 'folder' && i.id !== targetId).map(i => i.id);
let success = 0, errors = 0;
for (const item of items) {
try {
if (item.type === 'folder') {
if (item.id === targetId) continue;
const ok = await window.fileOps.moveFolder(item.id, targetId);
if (ok) success++; else errors++;
} else {
const ok = await window.fileOps.moveFile(item.id, targetId);
if (ok) success++; else errors++;
}
} catch (err) {
console.error('Error moving item:', item, err);
errors++;
try {
// Batch move files in a single request
if (fileIds.length > 0) {
const res = await fetch('/api/batch/files/move', {
method: 'POST',
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify({ file_ids: fileIds, target_folder_id: targetId })
});
const data = await res.json();
success += data.stats?.successful || 0;
errors += data.stats?.failed || 0;
}
// Batch move folders in a single request
if (folderIds.length > 0) {
const res = await fetch('/api/batch/folders/move', {
method: 'POST',
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify({ folder_ids: folderIds, target_folder_id: targetId })
});
const data = await res.json();
success += data.stats?.successful || 0;
errors += data.stats?.failed || 0;
}
} catch (err) {
console.error('Batch move error:', err);
errors++;
}
this.closeMoveDialog();
@@ -465,7 +482,7 @@ const contextMenus = {
* @param {Object} item - File or folder object
* @param {string} itemType - 'file' or 'folder'
*/
showShareDialog(item, itemType) {
async showShareDialog(item, itemType) {
try {
const shareDialog = document.getElementById('share-dialog');
if (!shareDialog) {
@@ -507,8 +524,8 @@ const contextMenus = {
window.app.shareDialogItem = item;
window.app.shareDialogItemType = itemType;
// Check if item already has shares
const existingShares = window.fileSharing.getSharedLinksForItem(item.id, itemType);
// Check if item already has shares (async API call)
const existingShares = await window.fileSharing.getSharedLinksForItem(item.id, itemType);
const existingSharesContainer = document.getElementById('existing-shares-container');
// Clear existing shares container
@@ -529,7 +546,7 @@ const contextMenus = {
shareEl.innerHTML = `
<div class="share-url">${share.url}</div>
<div class="share-info">
${share.password_protected ? '<span class="share-protected"><i class="fas fa-lock"></i> Password protected</span>' : ''}
${share.has_password ? '<span class="share-protected"><i class="fas fa-lock"></i> Password protected</span>' : ''}
<span class="share-expiration">${expiresText}</span>
</div>
<div class="share-actions">
@@ -563,9 +580,9 @@ const contextMenus = {
title: window.i18n ? window.i18n.t('dialogs.confirm_delete_share') : 'Delete link',
message: window.i18n ? window.i18n.t('dialogs.confirm_delete_share_msg') : 'Are you sure you want to delete this shared link?',
confirmText: window.i18n ? window.i18n.t('actions.delete') : 'Delete',
}).then(confirmed => {
}).then(async (confirmed) => {
if (confirmed) {
window.fileSharing.removeSharedLink(shareId);
await window.fileSharing.removeSharedLink(shareId);
btn.closest('.existing-share-item').remove();
if (existingSharesContainer.children.length === 0) {
document.getElementById('existing-shares-section').style.display = 'none';
@@ -613,6 +630,7 @@ const contextMenus = {
// Build DTO for backend API
const createDto = {
item_id: item.id,
item_name: item.name || null,
item_type: itemType,
password: password || null,
expires_at: expirationDate ? Math.floor(new Date(expirationDate).getTime() / 1000) : null,
@@ -640,22 +658,6 @@ const contextMenus = {
}
const shareInfo = await response.json();
// Also save to localStorage for offline / shared-view compatibility
window.fileSharing.saveSharedLink({
id: shareInfo.id,
type: shareInfo.item_type,
itemId: shareInfo.item_id,
url: shareInfo.url,
token: shareInfo.token,
password_protected: shareInfo.has_password,
expires_at: shareInfo.expires_at ? new Date(shareInfo.expires_at * 1000).toISOString() : null,
permissions: shareInfo.permissions,
created_at: new Date(shareInfo.created_at * 1000).toISOString(),
access_count: shareInfo.access_count || 0,
name: item.name,
dateShared: new Date().toISOString()
});
// Update UI with new share
const shareUrl = document.getElementById('generated-share-url');
+137 -313
View File
@@ -1,219 +1,146 @@
/**
* OxiCloud - File Sharing Module
* This file handles file sharing functionality (shared links, permissions, etc.)
* All operations go through the backend API at /api/shares.
* No localStorage is used for share data.
*/
// File Sharing Module
const fileSharing = {
/** Auth header helper */
_headers(json = true) {
const h = {};
const token = localStorage.getItem('oxicloud_token');
if (token) h['Authorization'] = `Bearer ${token}`;
if (json) h['Content-Type'] = 'application/json';
return h;
},
/**
* Generate a shared link for a file or folder
* Create a shared link via backend API
* @param {string} itemId - ID of the file or folder
* @param {string} itemType - Type ('file' or 'folder')
* @param {Object} options - Sharing options (password, expiration, etc.)
* @returns {Object} - Shared link information
* @param {string} itemType - 'file' or 'folder'
* @param {Object} options - { name, password, expirationDate, permissions }
* @returns {Promise<Object>} ShareDto from backend
*/
generateSharedLink(itemId, itemType, options = {}) {
try {
// In a real implementation, this would be a call to the backend
// But for now, we'll simulate it with a mock response
// Default options
const defaultOptions = {
password: null,
expirationDate: null,
permissions: {
read: true,
write: false,
reshare: false
}
};
// Merge options
const finalOptions = { ...defaultOptions, ...options };
// Generate a mock link (would normally come from server)
const linkId = Math.random().toString(36).substring(2, 15);
const shareToken = Math.random().toString(36).substring(2, 20);
const baseUrl = window.location.origin;
const sharedUrl = `${baseUrl}/s/${shareToken}`;
// Create expiration date if set
let expiresAt = null;
if (finalOptions.expirationDate) {
expiresAt = new Date(finalOptions.expirationDate);
}
// Create a mock response that matches what we'd expect from the server
const response = {
id: linkId,
type: itemType,
itemId: itemId,
url: sharedUrl,
token: shareToken,
password_protected: !!finalOptions.password,
expires_at: expiresAt ? expiresAt.toISOString() : null,
permissions: finalOptions.permissions,
created_at: new Date().toISOString(),
created_by: {
id: "current-user-id", // Would be the actual user ID
username: "current-user" // Would be the actual username
},
access_count: 0,
// Add some UI friendly properties for shared.js compatibility
name: options.name || "Shared Item",
dateShared: new Date().toISOString(),
expiration: expiresAt ? expiresAt.toISOString() : null,
password: finalOptions.password
};
// In a real implementation, we would store this link in localStorage for now
// until backend implementation is ready
this.saveSharedLink(response);
// Return the "response" as if it came from the server
return response;
} catch (error) {
console.error('Error generating shared link:', error);
throw error;
async createSharedLink(itemId, itemType, options = {}) {
const body = {
item_id: itemId,
item_name: options.name || null,
item_type: itemType,
password: options.password || null,
expires_at: options.expirationDate
? Math.floor(new Date(options.expirationDate).getTime() / 1000)
: null,
permissions: options.permissions || { read: true, write: false, reshare: false }
};
const res = await fetch('/api/shares', {
method: 'POST',
headers: this._headers(),
body: JSON.stringify(body)
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err.error || `Server error ${res.status}`);
}
return await res.json();
},
/**
* Save a shared link to localStorage (temporary storage until backend is ready)
* @param {Object} linkData - Shared link data
*/
saveSharedLink(linkData) {
try {
// Get existing shared links
const existingLinks = JSON.parse(localStorage.getItem('oxicloud_shared_links') || '[]');
// Add new link
existingLinks.push(linkData);
// Save back to localStorage
localStorage.setItem('oxicloud_shared_links', JSON.stringify(existingLinks));
} catch (error) {
console.error('Error saving shared link to local storage:', error);
}
},
/**
* Remove a shared link
* @param {string} linkId - ID of the shared link to remove
* @returns {Promise<boolean>} - Success status
*/
removeSharedLink(linkId) {
try {
// Get existing shared links
const existingLinks = JSON.parse(localStorage.getItem('oxicloud_shared_links') || '[]');
// Filter out the link to remove
const updatedLinks = existingLinks.filter(link => link.id !== linkId);
// Save back to localStorage
localStorage.setItem('oxicloud_shared_links', JSON.stringify(updatedLinks));
// Removed network delay simulation
return true;
} catch (error) {
console.error('Error removing shared link:', error);
return false;
}
},
/**
* Update a shared link's properties
* @param {string} linkId - ID of the shared link to update
* @param {Object} updateData - Properties to update
* @returns {Promise<Object>} - Updated shared link
*/
updateSharedLink(linkId, updateData) {
try {
// Get existing shared links
const existingLinks = JSON.parse(localStorage.getItem('oxicloud_shared_links') || '[]');
// Find the link to update
const linkIndex = existingLinks.findIndex(link => link.id === linkId);
if (linkIndex === -1) {
throw new Error('Shared link not found');
}
// Update link data
existingLinks[linkIndex] = {
...existingLinks[linkIndex],
...updateData,
updated_at: new Date().toISOString()
};
// Save back to localStorage
localStorage.setItem('oxicloud_shared_links', JSON.stringify(existingLinks));
// Removed network delay simulation
return existingLinks[linkIndex];
} catch (error) {
console.error('Error updating shared link:', error);
throw error;
}
},
/**
* Get all shared links for the current user
* @returns {Promise<Array>} - Array of shared links
* @returns {Promise<Array>} Array of ShareDto
*/
getSharedLinks() {
async getSharedLinks() {
try {
// Get shared links from localStorage
const links = JSON.parse(localStorage.getItem('oxicloud_shared_links') || '[]');
// Removed network delay simulation
return links;
const res = await fetch('/api/shares?page=1&per_page=1000', {
headers: this._headers(false)
});
if (!res.ok) return [];
const data = await res.json();
return data.items || [];
} catch (error) {
console.error('Error getting shared links:', error);
console.error('Error fetching shared links:', error);
return [];
}
},
/**
* Get shared links for a specific item
* @param {string} itemId - ID of the file or folder
* @param {string} itemType - Type ('file' or 'folder')
* @returns {Promise<Array>} - Array of shared links for the item
* @param {string} itemId
* @param {string} itemType - 'file' or 'folder'
* @returns {Promise<Array>} Filtered shares
*/
getSharedLinksForItem(itemId, itemType) {
async getSharedLinksForItem(itemId, itemType) {
try {
// Get all shared links
const allLinks = this.getSharedLinks();
// Filter by item ID and type
return allLinks.filter(link => link.itemId === itemId && link.type === itemType);
const all = await this.getSharedLinks();
return all.filter(s => s.item_id === itemId && s.item_type === itemType);
} catch (error) {
console.error('Error getting shared links for item:', error);
return [];
}
},
/**
* Check if an item has any shared links
* @param {string} itemId - ID of the file or folder
* @param {string} itemType - Type ('file' or 'folder')
* @returns {Promise<boolean>} - True if the item has shared links
* @returns {Promise<boolean>}
*/
hasSharedLinks(itemId, itemType) {
const links = this.getSharedLinksForItem(itemId, itemType);
async hasSharedLinks(itemId, itemType) {
const links = await this.getSharedLinksForItem(itemId, itemType);
return links.length > 0;
},
/**
* Update a shared link
* @param {string} shareId
* @param {Object} updateData - { permissions, password, expires_at }
* @returns {Promise<Object>} Updated ShareDto
*/
async updateSharedLink(shareId, updateData) {
const body = {};
if (updateData.permissions) body.permissions = updateData.permissions;
if (updateData.password !== undefined) body.password = updateData.password;
if (updateData.expires_at !== undefined) body.expires_at = updateData.expires_at;
const res = await fetch(`/api/shares/${shareId}`, {
method: 'PUT',
headers: this._headers(),
body: JSON.stringify(body)
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err.error || `Server error ${res.status}`);
}
return await res.json();
},
/**
* Delete a shared link
* @param {string} shareId
* @returns {Promise<boolean>}
*/
async removeSharedLink(shareId) {
try {
const res = await fetch(`/api/shares/${shareId}`, {
method: 'DELETE',
headers: this._headers(false)
});
return res.ok || res.status === 204;
} catch (error) {
console.error('Error removing shared link:', error);
return false;
}
},
/**
* Copy a shared link to clipboard
* @param {string} url - URL to copy
* @returns {boolean} - Success status
* @param {string} url
*/
copyLinkToClipboard(url) {
async copyLinkToClipboard(url) {
try {
navigator.clipboard.writeText(url);
await navigator.clipboard.writeText(url);
window.ui.showNotification('Link copied', 'Link copied to clipboard');
return true;
} catch (error) {
@@ -222,55 +149,42 @@ const fileSharing = {
return false;
}
},
/**
* Format expiration date for display
* @param {string} dateString - ISO date string
* @returns {string} - Formatted date string
* Format expiration date for display (Unix timestamp in seconds or ISO string)
* @param {number|string} value
* @returns {string}
*/
formatExpirationDate(dateString) {
if (!dateString) return 'No expiration';
const date = new Date(dateString);
return date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
formatExpirationDate(value) {
if (!value) return 'No expiration';
const date = typeof value === 'number' ? new Date(value * 1000) : new Date(value);
return date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
},
/**
* Send a notification about a shared resource
* @param {string} shareUrl - The URL of the shared resource
* @param {string} recipientEmail - Email of the recipient
* @param {string} message - Optional message to include
* @returns {boolean} - Success status
* Send a notification about a shared resource (stub — no backend endpoint yet)
* @param {string} shareUrl
* @param {string} recipientEmail
* @param {string} message
* @returns {Promise<boolean>}
*/
sendShareNotification(shareUrl, recipientEmail, message = '') {
try {
// In a real implementation, this would call the backend
// For now, we'll just simulate a successful notification
console.log(`Share notification for ${shareUrl} sent to ${recipientEmail}`);
console.log(`Message: ${message || 'No message included'}`);
// Simulate network delay
//await new Promise(resolve => setTimeout(resolve, 800));
async sendShareNotification(shareUrl, recipientEmail, message = '') {
// TODO: implement backend endpoint for email notifications
console.log(`Share notification for ${shareUrl} sent to ${recipientEmail}`);
if (window.ui) {
window.ui.showNotification('Notification sent', `Notification sent to ${recipientEmail}`);
return true;
} catch (error) {
console.error('Error sending share notification:', error);
window.ui.showNotification('Error', 'Could not send notification');
return false;
}
return true;
},
/**
* Initialize file sharing event listeners and UI elements
* Initialize file sharing event listeners
*/
init() {
// This will be called by the app.js initialization
console.log('File sharing module initialized');
// Add "Shared" view event listeners
console.log('File sharing module initialized (API-backed)');
document.querySelectorAll('.nav-item').forEach(item => {
if (item.querySelector('span').getAttribute('data-i18n') === 'nav.shared') {
const span = item.querySelector('span');
if (span && span.getAttribute('data-i18n') === 'nav.shared') {
item.addEventListener('click', () => {
if (window.switchToSharedView) {
window.switchToSharedView();
@@ -281,101 +195,11 @@ const fileSharing = {
}
};
/**
* Get all shared links
* @returns {Array} Array of shared links
*/
function getSharedLinks() {
try {
return JSON.parse(localStorage.getItem('oxicloud_shared_links') || '[]');
} catch (error) {
console.error('Error getting shared links:', error);
return [];
}
}
// Expose module globally
window.fileSharing = fileSharing;
/**
* Update a shared link
* @param {string} linkId - ID of the link to update
* @param {Object} updateData - Data to update
* @returns {boolean} Success status
*/
function updateSharedLink(linkId, updateData) {
try {
const links = getSharedLinks();
const index = links.findIndex(link => link.id === linkId);
if (index === -1) return false;
links[index] = {...links[index], ...updateData};
localStorage.setItem('oxicloud_shared_links', JSON.stringify(links));
return true;
} catch (error) {
console.error('Error updating shared link:', error);
return false;
}
}
/**
* Remove a shared link
* @param {string} linkId - ID of the link to remove
* @returns {boolean} Success status
*/
function removeSharedLink(linkId) {
try {
const links = getSharedLinks();
const filteredLinks = links.filter(link => link.id !== linkId);
localStorage.setItem('oxicloud_shared_links', JSON.stringify(filteredLinks));
return true;
} catch (error) {
console.error('Error removing shared link:', error);
return false;
}
}
/**
* Send a notification about a shared link
* @param {string} linkId - ID of the link
* @param {string} email - Recipient email
* @param {string} message - Optional message
* @returns {Promise<boolean>} Success status
*/
function sendShareNotification(linkId, email, message = '') {
return new Promise((resolve) => {
console.log(`Notification for link ${linkId} sent to ${email}`);
console.log(`Message: ${message || 'No message'}`);
setTimeout(() => resolve(true), 500);
});
}
/**
* Translate text using i18n if available
* @param {string} key - Translation key
* @param {string} defaultText - Default text if translation not found
* @returns {string} Translated text
*/
function translate(key, defaultText) {
if (window.i18n && window.i18n.t) {
return window.i18n.t(key, defaultText);
}
return defaultText;
}
/**
* Initialize i18n module
*/
function initializeI18n() {
if (window.i18n && window.i18n.init) {
window.i18n.init();
}
}
// Expose functions globally
window.getSharedLinks = getSharedLinks;
window.updateSharedLink = updateSharedLink;
window.removeSharedLink = removeSharedLink;
window.sendShareNotification = sendShareNotification;
window.translate = translate;
window.initializeI18n = initializeI18n;
// Expose file sharing module globally
window.fileSharing = fileSharing;
// Global convenience functions that delegate to the module
window.getSharedLinks = () => fileSharing.getSharedLinks();
window.updateSharedLink = (id, data) => fileSharing.updateSharedLink(id, data);
window.removeSharedLink = (id) => fileSharing.removeSharedLink(id);
window.sendShareNotification = (url, email, msg) => fileSharing.sendShareNotification(url, email, msg);
+54 -42
View File
@@ -308,46 +308,36 @@ const multiSelect = {
});
if (!confirmed) return;
let success = 0;
let errors = 0;
const fileIds = items.filter(i => i.type === 'file').map(i => i.id);
const folderIds = items.filter(i => i.type === 'folder').map(i => i.id);
for (const item of items) {
try {
const endpoint = item.type === 'folder'
? `/api/trash/folders/${item.id}`
: `/api/trash/files/${item.id}`;
try {
const response = await fetch('/api/batch/trash', {
method: 'POST',
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify({ file_ids: fileIds, folder_ids: folderIds })
});
const response = await fetch(endpoint, {
method: 'DELETE',
headers: getAuthHeaders()
});
const data = await response.json();
const success = data.stats?.successful || 0;
const errors = data.stats?.failed || 0;
if (response.ok) {
success++;
} else {
// Fallback to direct delete
const fallback = item.type === 'folder'
? `/api/folders/${item.id}`
: `/api/files/${item.id}`;
const r2 = await fetch(fallback, { method: 'DELETE', headers: getAuthHeaders() });
if (r2.ok) success++;
else errors++;
}
} catch (e) {
console.error('Error deleting item:', item, e);
errors++;
this.clear();
window.loadFiles();
if (errors > 0) {
const failedNames = (data.failed || []).map(f => f.id).join(', ');
window.ui.showNotification('Batch delete',
`${success} moved to trash, ${errors} failed`);
} else {
window.ui.showNotification('Moved to trash',
`${success} item${success !== 1 ? 's' : ''} moved to trash`);
}
}
this.clear();
window.loadFiles();
if (errors > 0) {
window.ui.showNotification('Batch delete',
`${success} moved to trash, ${errors} failed`);
} else {
window.ui.showNotification('Moved to trash',
`${success} item${success !== 1 ? 's' : ''} moved to trash`);
} catch (e) {
console.error('Batch trash error:', e);
window.ui.showNotification('Error', 'Could not move items to trash');
this.clear();
window.loadFiles();
}
},
@@ -379,17 +369,39 @@ const multiSelect = {
dialog.style.display = 'flex';
},
/** Batch download — downloads each item individually */
/** Batch download — downloads all selected items as a single ZIP */
async batchDownload() {
const items = this.items;
if (items.length === 0) return;
for (const item of items) {
if (item.type === 'folder') {
await window.fileOps.downloadFolder(item.id, item.name);
} else {
await window.fileOps.downloadFile(item.id, item.name);
window.ui.showNotification('Preparing download', 'Creating ZIP archive...');
try {
const fileIds = items.filter(i => i.type === 'file').map(i => i.id);
const folderIds = items.filter(i => i.type === 'folder').map(i => i.id);
const response = await fetch('/api/batch/download', {
method: 'POST',
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify({ file_ids: fileIds, folder_ids: folderIds })
});
if (!response.ok) {
throw new Error(`Server returned ${response.status}`);
}
const blob = await response.blob();
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = `oxicloud-download-${Date.now()}.zip`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
} catch (e) {
console.error('Batch download error:', e);
window.ui.showNotification('Error', 'Could not download selected items');
}
},
+100 -76
View File
@@ -1,22 +1,27 @@
/**
* OxiCloud - Search Module
* This file handles search functionality for files and folders
* OxiCloud - Search Module (thin client)
*
* All search processing (filtering, scoring, sorting, categorization,
* icon mapping, size formatting) is performed on the Rust backend.
* This module is a pure rendering client — it sends requests and
* displays the enriched results returned by the server.
*/
const search = {
/**
* Perform a basic search using query string
* Perform a search using query parameters.
* The backend handles all processing and returns enriched results with
* relevance_score, icon_class, category, size_formatted, etc.
*
* @param {string} query - Search query
* @param {Object} options - Additional search options
* @returns {Promise<Object>} - Search results
* @returns {Promise<Object>} - Enriched search results from backend
*/
async searchFiles(query, options = {}) {
try {
// Prepare search parameters
const params = new URLSearchParams();
params.append('query', query);
// Add optional parameters
if (options.folder_id) params.append('folder_id', options.folder_id);
if (options.recursive !== undefined) params.append('recursive', options.recursive);
if (options.file_types) params.append('type', options.file_types);
@@ -28,16 +33,13 @@ const search = {
if (options.modified_before) params.append('modified_before', options.modified_before);
if (options.limit) params.append('limit', options.limit);
if (options.offset) params.append('offset', options.offset);
if (options.sort_by) params.append('sort_by', options.sort_by);
// Create search URL
const url = `/api/search?${params.toString()}`;
console.log(`Performing search with URL: ${url}`);
// Perform the search request
const response = await fetch(url, {
headers: getAuthHeaders()
});
console.log(`[search] GET ${url}`);
const response = await fetch(url, { headers: getAuthHeaders() });
if (response.ok) {
return await response.json();
} else {
@@ -48,67 +50,62 @@ const search = {
} catch (e) {
errorText = response.statusText;
}
console.error(`Search error: ${errorText}`);
throw new Error(`Search failed: ${errorText}`);
}
} catch (error) {
console.error('Error performing search:', error);
window.ui.showNotification('Error', 'Error performing search');
return { files: [], folders: [], total_count: 0 };
return { files: [], folders: [], total_count: 0, query_time_ms: 0, sort_by: 'relevance' };
}
},
/**
* Perform advanced search with multiple criteria
* @param {Object} criteria - Search criteria
* @returns {Promise<Object>} - Search results
* Get autocomplete suggestions from the backend.
* Returns lightweight name suggestions without full search overhead.
*
* @param {string} query - Prefix to search for
* @param {Object} options - { folder_id, limit }
* @returns {Promise<Object>} - { suggestions: [...], query_time_ms }
*/
async advancedSearch(criteria) {
async getSuggestions(query, options = {}) {
try {
console.log('Performing advanced search with criteria:', criteria);
// Use POST endpoint for advanced search
const response = await fetch('/api/search', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders()
},
body: JSON.stringify(criteria)
});
const params = new URLSearchParams();
params.append('query', query);
if (options.folder_id) params.append('folder_id', options.folder_id);
if (options.limit) params.append('limit', options.limit);
const url = `/api/search/suggest?${params.toString()}`;
const response = await fetch(url, { headers: getAuthHeaders() });
if (response.ok) {
return await response.json();
} else {
let errorText = '';
try {
const errorJson = await response.json();
errorText = errorJson.error || response.statusText;
} catch (e) {
errorText = response.statusText;
}
console.error(`Advanced search error: ${errorText}`);
throw new Error(`Advanced search failed: ${errorText}`);
return { suggestions: [], query_time_ms: 0 };
}
} catch (error) {
console.error('Error performing advanced search:', error);
window.ui.showNotification('Error', 'Error performing advanced search');
return { files: [], folders: [], total_count: 0 };
console.error('Error getting suggestions:', error);
return { suggestions: [], query_time_ms: 0 };
}
},
/**
* Display search results in the UI
* @param {Object} results - Search results object with files and folders arrays
* Display search results in the UI.
*
* Uses server-computed enriched data:
* - icon_class: Font Awesome class for file type icon
* - size_formatted: Human-readable file size (e.g. "2.5 MB")
* - category: Content category (image, video, document, code, archive, audio, other)
* - relevance_score: 0-100 match quality
* - query_time_ms: Server-side query execution time
* - sort_by: Active sort order
*
* @param {Object} results - Enriched search results from backend
*/
displaySearchResults(results) {
// Get the files grid and list view elements
const filesGrid = document.getElementById('files-grid');
const filesListView = document.getElementById('files-list-view');
// Clear existing content
filesGrid.innerHTML = '';
filesListView.innerHTML = `
<div class="list-header">
@@ -119,61 +116,88 @@ const search = {
<div data-i18n="files.modified">Modified</div>
</div>
`;
// Add search results header
// Search results header with query time and sort controls
const totalCount = results.total_count || (results.files.length + results.folders.length);
const queryTimeText = results.query_time_ms !== undefined
? ` <span class="search-time">(${results.query_time_ms}ms)</span>`
: '';
const searchHeader = document.createElement('div');
searchHeader.className = 'search-results-header';
searchHeader.innerHTML = `
<h3>Search results (${results.total_count || (results.files.length + results.folders.length)})</h3>
<button class="btn btn-secondary" id="clear-search-btn">
<i class="fas fa-times"></i> Clear search
</button>
<h3>Search results (${totalCount})${queryTimeText}</h3>
<div class="search-controls">
<select id="search-sort-select" class="search-sort-select" title="Sort by">
<option value="relevance"${results.sort_by === 'relevance' ? ' selected' : ''}>Relevance</option>
<option value="name"${results.sort_by === 'name' ? ' selected' : ''}>Name A-Z</option>
<option value="name_desc"${results.sort_by === 'name_desc' ? ' selected' : ''}>Name Z-A</option>
<option value="date_desc"${results.sort_by === 'date_desc' ? ' selected' : ''}>Newest first</option>
<option value="date"${results.sort_by === 'date' ? ' selected' : ''}>Oldest first</option>
<option value="size_desc"${results.sort_by === 'size_desc' ? ' selected' : ''}>Largest first</option>
<option value="size"${results.sort_by === 'size' ? ' selected' : ''}>Smallest first</option>
</select>
<button class="btn btn-secondary" id="clear-search-btn">
<i class="fas fa-times"></i> Clear search
</button>
</div>
`;
filesGrid.appendChild(searchHeader);
// Add event listener to clear search button
// Sort dropdown — re-searches with new sort order (server-side)
const sortSelect = document.getElementById('search-sort-select');
if (sortSelect) {
sortSelect.addEventListener('change', () => {
const searchInput = document.querySelector('.search-container input');
if (searchInput && searchInput.value.trim()) {
const event = new CustomEvent('search-resort', {
detail: { sort_by: sortSelect.value }
});
document.dispatchEvent(event);
}
});
}
// Clear search
const clearSearchBtn = document.getElementById('clear-search-btn');
if (clearSearchBtn) {
clearSearchBtn.addEventListener('click', () => {
// Clear search input
document.querySelector('.search-container input').value = '';
// Load regular files view
window.app.currentPath = '';
window.app.isSearchMode = false;
window.ui.updateBreadcrumb('');
window.loadFiles();
});
}
// If no results, show empty state
// Empty state
if (results.files.length === 0 && results.folders.length === 0) {
const emptyState = document.createElement('div');
emptyState.className = 'empty-state';
emptyState.innerHTML = `
<i class="fas fa-search" style="font-size: 48px; color: #ddd; margin-bottom: 16px;"></i>
<p>No results found for this search</p>
<i class="fas fa-search" style="font-size: 48px; color: var(--empty-icon, #ccc); margin-bottom: 16px;"></i>
<p style="color: var(--text-secondary, #64748b);">No results found for this search</p>
`;
filesGrid.appendChild(emptyState);
return;
}
// Process folders
// Render folders (server-provided enriched data)
results.folders.forEach(folder => {
window.ui.addFolderToView(folder);
});
// Process files
// Render files (server-provided enriched data)
results.files.forEach(file => {
window.ui.addFileToView(file);
});
// Update file icons
window.ui.updateFileIcons();
},
/**
* Clear the search cache on the server
* @returns {Promise<boolean>} - Success status
* @returns {Promise<boolean>}
*/
async clearSearchCache() {
try {
@@ -181,7 +205,7 @@ const search = {
method: 'DELETE',
headers: getAuthHeaders()
});
if (response.ok) {
window.ui.showNotification('Cache cleared', 'Search cache cleared successfully');
return true;
@@ -198,4 +222,4 @@ const search = {
};
// Expose the search module globally
window.search = search;
window.search = search;
+269 -339
View File
@@ -1,44 +1,40 @@
/**
* OxiCloud Shared Resources Page
* Manages the display and interaction with shared files and folders
* OxiCloud - Shared Resources Page (/shared)
* All operations go through the backend API at /api/shares.
*/
// Authentication check function
// Authentication check
function checkAuthentication() {
// Names of variables from auth.js
const TOKEN_KEY = 'oxicloud_token';
const TOKEN_EXPIRY_KEY = 'oxicloud_token_expiry';
const USER_DATA_KEY = 'oxicloud_user';
const token = localStorage.getItem(TOKEN_KEY);
const tokenExpiry = localStorage.getItem(TOKEN_EXPIRY_KEY);
const token = localStorage.getItem('oxicloud_token');
const tokenExpiry = localStorage.getItem('oxicloud_token_expiry');
if (!token || !tokenExpiry || new Date(tokenExpiry) < new Date()) {
// No token or expired token
window.location.href = '/login';
return;
}
// Display username in notification if available
const userData = JSON.parse(localStorage.getItem(USER_DATA_KEY) || '{}');
if (userData.username) {
console.log(`Authenticated as ${userData.username}`);
}
}
document.addEventListener('DOMContentLoaded', async () => {
// Initialize i18n
await initializeI18n();
// Wait a moment for translations to fully load
setTimeout(() => {
// Manually translate all elements with data-i18n attribute
if (window.i18n && window.i18n.translatePage) {
window.i18n.translatePage();
}
}, 500);
// Elements
// ── i18n ──
if (window.i18n && window.i18n.init) {
await window.i18n.init();
setTimeout(() => {
if (window.i18n.translatePage) window.i18n.translatePage();
}, 500);
}
function t(key, fallback) {
return (window.i18n && window.i18n.t) ? window.i18n.t(key, fallback) : fallback;
}
// ── Auth headers helper ──
function authHeaders(json = false) {
const h = {};
const token = localStorage.getItem('oxicloud_token');
if (token) h['Authorization'] = `Bearer ${token}`;
if (json) h['Content-Type'] = 'application/json';
return h;
}
// ── Elements ──
const sharedItemsList = document.getElementById('shared-items-list');
const emptySharedState = document.getElementById('empty-shared-state');
const filterType = document.getElementById('filter-type');
@@ -46,10 +42,10 @@ document.addEventListener('DOMContentLoaded', async () => {
const sharedSearch = document.getElementById('shared-search');
const sharedSearchBtn = document.getElementById('shared-search-btn');
const goToFilesBtn = document.getElementById('go-to-files');
// Share dialog elements
const shareDialog = document.getElementById('share-dialog');
const shareDialogCloseBtn = shareDialog.querySelector('.close-dialog-btn');
const shareDialogCloseBtn = shareDialog ? shareDialog.querySelector('.close-dialog-btn') : null;
const shareDialogIcon = document.getElementById('share-dialog-icon');
const shareDialogName = document.getElementById('share-dialog-name');
const shareLinkUrl = document.getElementById('share-link-url');
@@ -64,414 +60,348 @@ document.addEventListener('DOMContentLoaded', async () => {
const permissionReshare = document.getElementById('permission-reshare');
const updateShareBtn = document.getElementById('update-share-btn');
const removeShareBtn = document.getElementById('remove-share-btn');
// Notification dialog elements
const notificationDialog = document.getElementById('share-notification-dialog');
const notificationCloseBtn = notificationDialog.querySelector('.close-dialog-btn');
const notificationCloseBtn = notificationDialog ? notificationDialog.querySelector('.close-dialog-btn') : null;
const notifyDialogIcon = document.getElementById('notify-dialog-icon');
const notifyDialogName = document.getElementById('notify-dialog-name');
const notificationEmail = document.getElementById('notification-email');
const notificationMessage = document.getElementById('notification-message');
const sendNotificationBtn = document.getElementById('send-notification-btn');
// Notification banner
const notificationBanner = document.getElementById('notification-banner');
const notificationBannerMessage = document.getElementById('notification-message');
const closeNotificationBtn = document.getElementById('close-notification');
// Current state
// ── State ──
let currentSharedItem = null;
let allSharedItems = [];
let filteredItems = [];
// Initialize the page
loadSharedItems();
// Event listeners
filterType.addEventListener('change', filterAndSortItems);
sortBy.addEventListener('change', filterAndSortItems);
sharedSearchBtn.addEventListener('click', filterAndSortItems);
sharedSearch.addEventListener('keyup', (e) => {
if (e.key === 'Enter') filterAndSortItems();
});
goToFilesBtn.addEventListener('click', () => window.location.href = '/');
// Check authentication before loading
// ── Init ──
checkAuthentication();
// Share dialog event listeners
shareDialogCloseBtn.addEventListener('click', () => closeShareDialog());
copyLinkBtn.addEventListener('click', copyShareLink);
enablePassword.addEventListener('change', () => {
sharePassword.disabled = !enablePassword.checked;
if (enablePassword.checked) sharePassword.focus();
await loadSharedItems();
// ── Event listeners ──
if (filterType) filterType.addEventListener('change', filterAndSortItems);
if (sortBy) sortBy.addEventListener('change', filterAndSortItems);
if (sharedSearchBtn) sharedSearchBtn.addEventListener('click', filterAndSortItems);
if (sharedSearch) sharedSearch.addEventListener('keyup', e => { if (e.key === 'Enter') filterAndSortItems(); });
if (goToFilesBtn) goToFilesBtn.addEventListener('click', () => window.location.href = '/');
if (shareDialogCloseBtn) shareDialogCloseBtn.addEventListener('click', closeShareDialog);
if (copyLinkBtn) copyLinkBtn.addEventListener('click', copyShareLink);
if (enablePassword) enablePassword.addEventListener('change', () => {
if (sharePassword) { sharePassword.disabled = !enablePassword.checked; if (enablePassword.checked) sharePassword.focus(); }
});
generatePasswordBtn.addEventListener('click', generatePassword);
enableExpiration.addEventListener('change', () => {
shareExpiration.disabled = !enableExpiration.checked;
if (enableExpiration.checked) shareExpiration.focus();
if (generatePasswordBtn) generatePasswordBtn.addEventListener('click', generatePassword);
if (enableExpiration) enableExpiration.addEventListener('change', () => {
if (shareExpiration) { shareExpiration.disabled = !enableExpiration.checked; if (enableExpiration.checked) shareExpiration.focus(); }
});
updateShareBtn.addEventListener('click', updateSharedItem);
removeShareBtn.addEventListener('click', removeSharedItem);
// Notification dialog event listeners
notificationCloseBtn.addEventListener('click', () => closeNotificationDialog());
sendNotificationBtn.addEventListener('click', sendNotification);
// Notification banner event listeners
closeNotificationBtn.addEventListener('click', () => {
notificationBanner.classList.remove('active');
if (updateShareBtn) updateShareBtn.addEventListener('click', updateSharedItem);
if (removeShareBtn) removeShareBtn.addEventListener('click', removeSharedItem);
if (notificationCloseBtn) notificationCloseBtn.addEventListener('click', closeNotificationDialog);
if (sendNotificationBtn) sendNotificationBtn.addEventListener('click', sendNotification);
if (closeNotificationBtn) closeNotificationBtn.addEventListener('click', () => {
if (notificationBanner) notificationBanner.classList.remove('active');
});
/**
* Loads all shared items and displays them
*/
function loadSharedItems() {
// Get shared links from storage
allSharedItems = getSharedLinks();
// Display items
// ── Load shares from backend ──
async function loadSharedItems() {
try {
const res = await fetch('/api/shares?page=1&per_page=1000', {
headers: authHeaders()
});
if (res.ok) {
const data = await res.json();
allSharedItems = data.items || [];
} else {
allSharedItems = [];
}
} catch (err) {
console.error('Error loading shared items:', err);
allSharedItems = [];
}
filterAndSortItems();
}
/**
* Filters and sorts the shared items based on current filters
*/
// ── Filter & sort ──
function filterAndSortItems() {
const type = filterType.value;
const sort = sortBy.value;
const searchTerm = sharedSearch.value.toLowerCase();
// Filter items
const type = filterType ? filterType.value : 'all';
const sort = sortBy ? sortBy.value : 'date';
const searchTerm = sharedSearch ? sharedSearch.value.toLowerCase() : '';
filteredItems = allSharedItems.filter(item => {
// Filter by type
if (type !== 'all' && item.type !== type) return false;
// Filter by search term
const nameMatch = item.name.toLowerCase().includes(searchTerm);
return nameMatch;
if (type !== 'all' && item.item_type !== type) return false;
const name = (item.item_name || item.item_id || '').toLowerCase();
return name.includes(searchTerm);
});
// Sort items
filteredItems.sort((a, b) => {
if (sort === 'name') {
return a.name.localeCompare(b.name);
return (a.item_name || a.item_id || '').localeCompare(b.item_name || b.item_id || '');
} else if (sort === 'date') {
return new Date(b.dateShared) - new Date(a.dateShared);
return (b.created_at || 0) - (a.created_at || 0);
} else if (sort === 'expiration') {
// Handle null expiration dates (items without expiration come last)
if (!a.expiration && !b.expiration) return 0;
if (!a.expiration) return 1;
if (!b.expiration) return -1;
return new Date(a.expiration) - new Date(b.expiration);
if (!a.expires_at && !b.expires_at) return 0;
if (!a.expires_at) return 1;
if (!b.expires_at) return -1;
return a.expires_at - b.expires_at;
}
return 0;
});
// Display filtered and sorted items
displaySharedItems();
}
/**
* Displays the filtered and sorted shared items
*/
// ── Display table ──
function displaySharedItems() {
// Clear the list
if (!sharedItemsList) return;
sharedItemsList.innerHTML = '';
// Show empty state if no items
if (filteredItems.length === 0) {
emptySharedState.style.display = 'flex';
document.querySelector('.shared-list-container').style.display = 'none';
if (emptySharedState) emptySharedState.style.display = 'flex';
const listContainer = document.querySelector('.shared-list-container');
if (listContainer) listContainer.style.display = 'none';
return;
}
// Hide empty state and show table
emptySharedState.style.display = 'none';
document.querySelector('.shared-list-container').style.display = 'block';
// Add items to the list
if (emptySharedState) emptySharedState.style.display = 'none';
const listContainer = document.querySelector('.shared-list-container');
if (listContainer) listContainer.style.display = 'block';
filteredItems.forEach(item => {
const row = document.createElement('tr');
// Icon and name
const displayName = item.item_name || item.item_id || 'Unknown';
// Name
const nameCell = document.createElement('td');
nameCell.className = 'shared-item-name';
const icon = document.createElement('span');
icon.className = 'item-icon';
icon.textContent = item.type === 'file' ? '📄' : '📁';
const name = document.createElement('span');
name.textContent = item.name;
nameCell.appendChild(icon);
nameCell.appendChild(name);
nameCell.innerHTML = `<span class="item-icon">${item.item_type === 'file' ? '📄' : '📁'}</span><span>${displayName}</span>`;
// Type
const typeCell = document.createElement('td');
typeCell.textContent = item.type === 'file' ? translate('shared_typeFile', 'File') : translate('shared_typeFolder', 'Folder');
// Date shared
typeCell.textContent = item.item_type === 'file' ? t('shared_typeFile', 'File') : t('shared_typeFolder', 'Folder');
// Date
const dateCell = document.createElement('td');
dateCell.textContent = formatDate(item.dateShared);
dateCell.textContent = formatDate(item.created_at);
// Expiration
const expirationCell = document.createElement('td');
expirationCell.textContent = item.expiration ? formatDate(item.expiration) : translate('shared_noExpiration', 'No expiration');
expirationCell.textContent = item.expires_at ? formatDate(item.expires_at) : t('shared_noExpiration', 'No expiration');
// Permissions
const permissionsCell = document.createElement('td');
const permissions = [];
if (item.permissions.read) permissions.push(translate('share_permissionRead', 'Read'));
if (item.permissions.write) permissions.push(translate('share_permissionWrite', 'Write'));
if (item.permissions.reshare) permissions.push(translate('share_permissionReshare', 'Reshare'));
permissionsCell.textContent = permissions.join(', ');
const perms = [];
if (item.permissions?.read) perms.push(t('share_permissionRead', 'Read'));
if (item.permissions?.write) perms.push(t('share_permissionWrite', 'Write'));
if (item.permissions?.reshare) perms.push(t('share_permissionReshare', 'Reshare'));
permissionsCell.textContent = perms.join(', ') || 'Read';
// Password
const passwordCell = document.createElement('td');
passwordCell.textContent = item.password ? translate('shared_hasPassword', 'Yes') : translate('shared_noPassword', 'No');
passwordCell.textContent = item.has_password ? t('shared_hasPassword', 'Yes') : t('shared_noPassword', 'No');
// Actions
const actionsCell = document.createElement('td');
actionsCell.className = 'shared-item-actions';
// Edit button
const editBtn = document.createElement('button');
editBtn.className = 'action-btn edit-btn';
editBtn.innerHTML = '<span class="action-icon">✏️</span>';
editBtn.title = translate('shared_editShare', 'Edit Share');
editBtn.title = t('shared_editShare', 'Edit Share');
editBtn.addEventListener('click', () => openShareDialog(item));
// Notify button
const notifyBtn = document.createElement('button');
notifyBtn.className = 'action-btn notify-btn';
notifyBtn.innerHTML = '<span class="action-icon">📧</span>';
notifyBtn.title = translate('shared_notifyShare', 'Notify Someone');
notifyBtn.title = t('shared_notifyShare', 'Notify Someone');
notifyBtn.addEventListener('click', () => openNotificationDialog(item));
// Copy link button
const copyBtn = document.createElement('button');
copyBtn.className = 'action-btn copy-btn';
copyBtn.innerHTML = '<span class="action-icon">📋</span>';
copyBtn.title = translate('shared_copyLink', 'Copy Link');
copyBtn.addEventListener('click', () => {
const cpBtn = document.createElement('button');
cpBtn.className = 'action-btn copy-btn';
cpBtn.innerHTML = '<span class="action-icon">📋</span>';
cpBtn.title = t('shared_copyLink', 'Copy Link');
cpBtn.addEventListener('click', () => {
navigator.clipboard.writeText(item.url)
.then(() => showNotification(translate('shared_linkCopied', 'Link copied to clipboard!')))
.catch(err => showNotification(translate('shared_linkCopyFailed', 'Failed to copy link'), 'error'));
.then(() => showNotification(t('shared_linkCopied', 'Link copied!')))
.catch(() => showNotification(t('shared_linkCopyFailed', 'Failed to copy link'), 'error'));
});
// Remove button
const removeBtn = document.createElement('button');
removeBtn.className = 'action-btn remove-btn';
removeBtn.innerHTML = '<span class="action-icon">🗑️</span>';
removeBtn.title = translate('shared_removeShare', 'Remove Share');
removeBtn.addEventListener('click', () => {
currentSharedItem = item;
removeSharedItem();
});
actionsCell.appendChild(editBtn);
actionsCell.appendChild(notifyBtn);
actionsCell.appendChild(copyBtn);
actionsCell.appendChild(removeBtn);
// Add cells to row
row.appendChild(nameCell);
row.appendChild(typeCell);
row.appendChild(dateCell);
row.appendChild(expirationCell);
row.appendChild(permissionsCell);
row.appendChild(passwordCell);
row.appendChild(actionsCell);
// Add row to table
const rmBtn = document.createElement('button');
rmBtn.className = 'action-btn remove-btn';
rmBtn.innerHTML = '<span class="action-icon">🗑️</span>';
rmBtn.title = t('shared_removeShare', 'Remove Share');
rmBtn.addEventListener('click', () => { currentSharedItem = item; removeSharedItem(); });
actionsCell.append(editBtn, notifyBtn, cpBtn, rmBtn);
row.append(nameCell, typeCell, dateCell, expirationCell, permissionsCell, passwordCell, actionsCell);
sharedItemsList.appendChild(row);
});
}
/**
* Opens the share dialog for the given item
*/
// ── Share dialog ──
function openShareDialog(item) {
currentSharedItem = item;
// Set dialog content
shareDialogIcon.textContent = item.type === 'file' ? '📄' : '📁';
shareDialogName.textContent = item.name;
shareLinkUrl.value = item.url;
// Set permissions
permissionRead.checked = item.permissions.read;
permissionWrite.checked = item.permissions.write;
permissionReshare.checked = item.permissions.reshare;
// Set password
enablePassword.checked = !!item.password;
sharePassword.disabled = !enablePassword.checked;
sharePassword.value = item.password || '';
// Set expiration
enableExpiration.checked = !!item.expiration;
shareExpiration.disabled = !enableExpiration.checked;
shareExpiration.value = item.expiration ? new Date(item.expiration).toISOString().split('T')[0] : '';
// Show dialog
shareDialog.classList.add('active');
const dn = item.item_name || item.item_id || 'Unknown';
if (shareDialogIcon) shareDialogIcon.textContent = item.item_type === 'file' ? '📄' : '📁';
if (shareDialogName) shareDialogName.textContent = dn;
if (shareLinkUrl) shareLinkUrl.value = item.url || '';
if (permissionRead) permissionRead.checked = item.permissions?.read !== false;
if (permissionWrite) permissionWrite.checked = !!item.permissions?.write;
if (permissionReshare) permissionReshare.checked = !!item.permissions?.reshare;
if (enablePassword) {
enablePassword.checked = item.has_password;
if (sharePassword) { sharePassword.disabled = !enablePassword.checked; sharePassword.value = ''; }
}
if (enableExpiration) {
enableExpiration.checked = !!item.expires_at;
if (shareExpiration) {
shareExpiration.disabled = !enableExpiration.checked;
shareExpiration.value = item.expires_at ? new Date(item.expires_at * 1000).toISOString().split('T')[0] : '';
}
}
if (shareDialog) shareDialog.classList.add('active');
}
/**
* Closes the share dialog
*/
function closeShareDialog() {
shareDialog.classList.remove('active');
if (shareDialog) shareDialog.classList.remove('active');
currentSharedItem = null;
}
/**
* Opens the notification dialog for the given item
*/
// ── Notification dialog ──
function openNotificationDialog(item) {
currentSharedItem = item;
// Set dialog content
notifyDialogIcon.textContent = item.type === 'file' ? '📄' : '📁';
notifyDialogName.textContent = item.name;
notificationEmail.value = '';
notificationMessage.value = '';
// Show dialog
notificationDialog.classList.add('active');
const dn = item.item_name || item.item_id || 'Unknown';
if (notifyDialogIcon) notifyDialogIcon.textContent = item.item_type === 'file' ? '📄' : '📁';
if (notifyDialogName) notifyDialogName.textContent = dn;
if (notificationEmail) notificationEmail.value = '';
if (notificationMessage) notificationMessage.value = '';
if (notificationDialog) notificationDialog.classList.add('active');
}
/**
* Closes the notification dialog
*/
function closeNotificationDialog() {
notificationDialog.classList.remove('active');
if (notificationDialog) notificationDialog.classList.remove('active');
currentSharedItem = null;
}
/**
* Copies the current share link to clipboard
*/
function copyShareLink() {
if (!shareLinkUrl) return;
navigator.clipboard.writeText(shareLinkUrl.value)
.then(() => showNotification(translate('shared_linkCopied', 'Link copied to clipboard!')))
.catch(err => showNotification(translate('shared_linkCopyFailed', 'Failed to copy link'), 'error'));
.then(() => showNotification(t('shared_linkCopied', 'Link copied!')))
.catch(() => showNotification(t('shared_linkCopyFailed', 'Failed to copy link'), 'error'));
}
/**
* Generates a random password for the share
*/
// ── Generate secure password with crypto API ──
function generatePassword() {
if (!sharePassword || !enablePassword) return;
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*';
const array = new Uint32Array(16);
crypto.getRandomValues(array);
let password = '';
for (let i = 0; i < 12; i++) {
password += chars.charAt(Math.floor(Math.random() * chars.length));
for (let i = 0; i < 16; i++) {
password += chars[array[i] % chars.length];
}
sharePassword.value = password;
enablePassword.checked = true;
sharePassword.disabled = false;
}
/**
* Updates the current shared item with new settings
*/
function updateSharedItem() {
// ── Update share via API ──
async function updateSharedItem() {
if (!currentSharedItem) return;
// Get updated settings
const permissions = {
read: permissionRead.checked,
write: permissionWrite.checked,
reshare: permissionReshare.checked
const body = {
permissions: {
read: permissionRead ? permissionRead.checked : true,
write: permissionWrite ? permissionWrite.checked : false,
reshare: permissionReshare ? permissionReshare.checked : false
},
password: (enablePassword && enablePassword.checked && sharePassword && sharePassword.value) ? sharePassword.value : null,
expires_at: (enableExpiration && enableExpiration.checked && shareExpiration && shareExpiration.value)
? Math.floor(new Date(shareExpiration.value).getTime() / 1000)
: null
};
const password = enablePassword.checked ? sharePassword.value : null;
const expiration = enableExpiration.checked ? shareExpiration.value : null;
// Update the shared link
updateSharedLink(currentSharedItem.id, {
permissions,
password,
expiration: expiration ? new Date(expiration).toISOString() : null
});
// Reload items and close dialog
loadSharedItems();
try {
const res = await fetch(`/api/shares/${currentSharedItem.id}`, {
method: 'PUT',
headers: authHeaders(true),
body: JSON.stringify(body)
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err.error || `Server error ${res.status}`);
}
showNotification(t('shared_itemUpdated', 'Share settings updated'));
} catch (err) {
console.error('Error updating share:', err);
showNotification(err.message || 'Error updating share', 'error');
}
closeShareDialog();
// Show notification
showNotification(translate('shared_itemUpdated', 'Share settings updated successfully'));
await loadSharedItems();
}
/**
* Removes the current shared item
*/
function removeSharedItem() {
// ── Remove share via API ──
async function removeSharedItem() {
if (!currentSharedItem) return;
// Remove the shared link
removeSharedLink(currentSharedItem.id);
// Reload items and close dialog if open
loadSharedItems();
try {
const res = await fetch(`/api/shares/${currentSharedItem.id}`, {
method: 'DELETE',
headers: authHeaders()
});
if (!res.ok && res.status !== 204) throw new Error(`Server error ${res.status}`);
showNotification(t('shared_itemRemoved', 'Share removed'));
} catch (err) {
console.error('Error removing share:', err);
showNotification('Error removing share', 'error');
}
closeShareDialog();
// Show notification
showNotification(translate('shared_itemRemoved', 'Share removed successfully'));
await loadSharedItems();
}
/**
* Sends a notification email for the current shared item
*/
// ── Send notification (stub) ──
function sendNotification() {
if (!currentSharedItem) return;
const email = notificationEmail.value.trim();
const message = notificationMessage.value.trim();
// Validate email
if (!email || !validateEmail(email)) {
showNotification(translate('shared_invalidEmail', 'Please enter a valid email address'), 'error');
const email = notificationEmail ? notificationEmail.value.trim() : '';
const message = notificationMessage ? notificationMessage.value.trim() : '';
if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
showNotification(t('shared_invalidEmail', 'Please enter a valid email address'), 'error');
return;
}
// Send notification
sendShareNotification(currentSharedItem.id, email, message)
.then(() => {
closeNotificationDialog();
showNotification(translate('shared_notificationSent', 'Notification sent successfully'));
})
.catch(error => {
showNotification(translate('shared_notificationFailed', 'Failed to send notification'), 'error');
});
if (window.fileSharing && window.fileSharing.sendShareNotification) {
window.fileSharing.sendShareNotification(currentSharedItem.url, email, message)
.then(() => { closeNotificationDialog(); showNotification(t('shared_notificationSent', 'Notification sent')); })
.catch(() => showNotification(t('shared_notificationFailed', 'Failed to send notification'), 'error'));
}
}
/**
* Shows a notification banner with the given message
*/
// ── Helpers ──
function showNotification(message, type = 'success') {
notificationBannerMessage.textContent = message;
notificationBanner.className = 'notification-banner active ' + type;
// Auto-hide after 5 seconds
setTimeout(() => {
notificationBanner.classList.remove('active');
}, 5000);
if (notificationBannerMessage && notificationBanner) {
notificationBannerMessage.textContent = message;
notificationBanner.className = 'notification-banner active ' + type;
setTimeout(() => notificationBanner.classList.remove('active'), 5000);
} else if (window.ui && window.ui.showNotification) {
window.ui.showNotification(message, type);
} else {
alert(message);
}
}
/**
* Validates an email address
*/
function validateEmail(email) {
const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return re.test(email);
}
/**
* Formats a date string to a user-friendly format
*/
function formatDate(dateString) {
const options = { year: 'numeric', month: 'short', day: 'numeric' };
return new Date(dateString).toLocaleDateString(undefined, options);
function formatDate(value) {
if (!value) return 'N/A';
const date = typeof value === 'number' ? new Date(value * 1000) : new Date(value);
return date.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' });
}
});
+2
View File
@@ -4,6 +4,8 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title data-i18n="app.title">OxiCloud - Login</title>
<!-- Apply saved theme immediately to prevent flash of light mode -->
<script>if(localStorage.getItem('oxicloud_theme')==='dark')document.documentElement.setAttribute('data-theme','dark');</script>
<!-- Styles -->
<link rel="stylesheet" href="/css/style.css">
+33
View File
@@ -4,6 +4,8 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>OxiCloud — My Profile</title>
<!-- Apply saved theme immediately to prevent flash of light mode -->
<script>if(localStorage.getItem('oxicloud_theme')==='dark')document.documentElement.setAttribute('data-theme','dark');</script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
<style>
*{box-sizing:border-box;margin:0;padding:0;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Oxygen,Ubuntu,Cantarell,'Open Sans','Helvetica Neue',sans-serif}
@@ -118,6 +120,37 @@ body{background:#f5f7fa;color:#1e293b;min-height:100vh;display:flex;flex-directi
#auth-error p{color:#64748b;margin-bottom:20px;font-size:14px}
#auth-error a{display:inline-flex;align-items:center;gap:6px;padding:10px 24px;background:linear-gradient(135deg,#ff5e3a,#ff2d55);color:#fff;text-decoration:none;border-radius:10px;font-weight:600;font-size:14px;box-shadow:0 3px 12px rgba(255,94,58,.3);transition:all .2s}
#auth-error a:hover{transform:translateY(-1px);box-shadow:0 5px 18px rgba(255,94,58,.4)}
/* ── Dark Mode ── */
[data-theme="dark"] body{background:#0f172a;color:#e2e8f0}
[data-theme="dark"] ::-webkit-scrollbar-thumb{background:rgba(255,255,255,.15)}
[data-theme="dark"] *{scrollbar-color:rgba(255,255,255,.15) transparent}
[data-theme="dark"] .profile-card{background:#1e293b;box-shadow:0 1px 4px rgba(0,0,0,.2),0 0 0 1px rgba(255,255,255,.03)}
[data-theme="dark"] .profile-card h2{color:#f1f5f9}
[data-theme="dark"] .avatar-info h1{color:#f1f5f9}
[data-theme="dark"] .avatar-info .email{color:#94a3b8}
[data-theme="dark"] .role-badge-admin{background:#1e3a5f;color:#60a5fa}
[data-theme="dark"] .role-badge-user{background:#334155;color:#94a3b8}
[data-theme="dark"] .info-item{background:#162032;border-color:#334155}
[data-theme="dark"] .info-item .info-label{color:#64748b}
[data-theme="dark"] .info-item .info-label i{color:#475569}
[data-theme="dark"] .info-item .info-value{color:#f1f5f9}
[data-theme="dark"] .storage-stat{background:#162032;border-color:#334155}
[data-theme="dark"] .storage-stat .stat-value{color:#f1f5f9}
[data-theme="dark"] .storage-stat .stat-label{color:#64748b}
[data-theme="dark"] .storage-bar{background:#334155}
[data-theme="dark"] .storage-text{color:#64748b}
[data-theme="dark"] .form-group label{color:#94a3b8}
[data-theme="dark"] .form-group input{background:#0f172a;border-color:#334155;color:#e2e8f0}
[data-theme="dark"] .form-group input:focus{border-color:#ff5e3a;background:#0f172a;box-shadow:0 0 0 3px rgba(255,94,58,.15)}
[data-theme="dark"] .form-group small{color:#64748b}
[data-theme="dark"] .alert-success{background:#052e16;color:#86efac;border-color:#065f46}
[data-theme="dark"] .alert-error{background:#3b1111;color:#fca5a5;border-color:#991b1b}
[data-theme="dark"] #auth-error{background:transparent}
[data-theme="dark"] #auth-error .err-icon{background:#3b1111}
[data-theme="dark"] #auth-error h2{color:#fca5a5}
[data-theme="dark"] #auth-error p{color:#94a3b8}
[data-theme="dark"] #loading{color:#64748b}
</style>
</head>
<body>
+24
View File
@@ -4,6 +4,8 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>OxiCloud - Shared Resources</title>
<!-- Apply saved theme immediately to prevent flash of light mode -->
<script>if(localStorage.getItem('oxicloud_theme')==='dark')document.documentElement.setAttribute('data-theme','dark');</script>
<link rel="stylesheet" href="/css/style.css">
<link rel="icon" href="/favicon.ico" type="image/x-icon">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
@@ -74,6 +76,13 @@
<span class="user-email" id="user-menu-email">admin@oxicloud.local</span>
</div>
<div class="user-menu-divider"></div>
<div class="user-menu-item" id="menu-theme">
<i class="fas fa-moon"></i>
<span data-i18n="user_menu.appearance">Appearance</span>
<div class="theme-toggle-pill" id="theme-toggle-pill">
<div class="theme-toggle-knob"></div>
</div>
</div>
<div class="user-menu-item" id="menu-logout">
<i class="fas fa-sign-out-alt"></i>
<span data-i18n="actions.logout">Log out</span>
@@ -284,6 +293,21 @@
window.location.href = '/login';
});
}
// Theme toggle (dark mode)
const themeBtn = document.getElementById('menu-theme');
const pill = document.getElementById('theme-toggle-pill');
if (themeBtn && pill) {
const isDark = localStorage.getItem('oxicloud_theme') === 'dark';
if (isDark) pill.classList.add('active');
themeBtn.addEventListener('click', (e) => {
e.stopPropagation();
pill.classList.toggle('active');
const dark = pill.classList.contains('active');
localStorage.setItem('oxicloud_theme', dark ? 'dark' : 'light');
document.documentElement.setAttribute('data-theme', dark ? 'dark' : 'light');
});
}
})();
</script>
<script src="/js/shared.js"></script>