fix: folder trash/delete operations & frontend refactoring
- Fix recursive CTE: add missing RECURSIVE keyword in move_to_trash and restore_from_trash SQL queries (relation 'descendants' does not exist) - Fix folder deletion: delete descendant files before folder to avoid 'duplicate key violates unique constraint idx_files_unique_name_at_root' - Simplify trash model: only mark the folder as trashed, not child files (implicit trash via parent) - Update trash_items view: filter to show only top-level trashed items - Update schema.sql: change files.folder_id FK from ON DELETE SET NULL to ON DELETE CASCADE - Fix trash view icons: folders and files now show correct visual icons (folder-icon, pdf-icon, etc.) in trash view - Frontend refactoring: extract inline CSS/JS from admin.html and profile.html into dedicated external files - Frontend cleanup: replace all inline style attributes with CSS classes - Frontend cleanup: replace style.display JS - Fix recursive CTE: add missing RECURSIVE keyword in move_to_trash and restore_from_trash SQL queries (relation 'descendants' d
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,799 @@
|
||||
/**
|
||||
* OxiCloud - Context Menus and Dialogs Module
|
||||
* This file handles context menus and dialog functionality
|
||||
*/
|
||||
|
||||
// Context Menus Module
|
||||
const contextMenus = {
|
||||
_setFavoriteOptionLabel(optionId, isFavorite) {
|
||||
const option = document.getElementById(optionId);
|
||||
if (!option) return;
|
||||
const label = option.querySelector('span');
|
||||
if (!label) return;
|
||||
label.textContent = window.i18n
|
||||
? window.i18n.t(isFavorite ? 'actions.unfavorite' : 'actions.favorite')
|
||||
: (isFavorite ? 'Remove from favorites' : 'Add to favorites');
|
||||
},
|
||||
|
||||
syncFavoriteOptionLabels() {
|
||||
if (!window.favorites) return;
|
||||
|
||||
const targetFile = window.app && window.app.contextMenuTargetFile;
|
||||
const targetFolder = window.app && window.app.contextMenuTargetFolder;
|
||||
|
||||
if (targetFile) {
|
||||
const isFav = window.favorites.isFavorite(targetFile.id, 'file');
|
||||
this._setFavoriteOptionLabel('favorite-file-option', isFav);
|
||||
}
|
||||
|
||||
if (targetFolder) {
|
||||
const isFav = window.favorites.isFavorite(targetFolder.id, 'folder');
|
||||
this._setFavoriteOptionLabel('favorite-folder-option', isFav);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Assign events to menu items and dialogs
|
||||
*/
|
||||
assignMenuEvents() {
|
||||
// Folder context menu options
|
||||
document.getElementById('download-folder-option').addEventListener('click', () => {
|
||||
if (window.app.contextMenuTargetFolder) {
|
||||
window.fileOps.downloadFolder(
|
||||
window.app.contextMenuTargetFolder.id,
|
||||
window.app.contextMenuTargetFolder.name
|
||||
);
|
||||
}
|
||||
window.ui.closeContextMenu();
|
||||
});
|
||||
|
||||
document.getElementById('favorite-folder-option').addEventListener('click', async () => {
|
||||
if (window.app.contextMenuTargetFolder) {
|
||||
const folder = window.app.contextMenuTargetFolder;
|
||||
|
||||
// Check if folder is already in favorites to toggle
|
||||
if (window.favorites && window.favorites.isFavorite(folder.id, 'folder')) {
|
||||
// Remove from favorites
|
||||
const ok = await window.favorites.removeFromFavorites(folder.id, 'folder');
|
||||
if (ok && window.ui && typeof window.ui.setFavoriteVisualState === 'function') {
|
||||
window.ui.setFavoriteVisualState(folder.id, 'folder', false);
|
||||
}
|
||||
} else {
|
||||
// Add to favorites
|
||||
const ok = await window.favorites.addToFavorites(
|
||||
folder.id,
|
||||
folder.name,
|
||||
'folder',
|
||||
folder.parent_id
|
||||
);
|
||||
if (ok && window.ui && typeof window.ui.setFavoriteVisualState === 'function') {
|
||||
window.ui.setFavoriteVisualState(folder.id, 'folder', true);
|
||||
}
|
||||
}
|
||||
this.syncFavoriteOptionLabels();
|
||||
}
|
||||
window.ui.closeContextMenu();
|
||||
});
|
||||
|
||||
document.getElementById('rename-folder-option').addEventListener('click', () => {
|
||||
if (window.app.contextMenuTargetFolder) {
|
||||
this.showRenameDialog(window.app.contextMenuTargetFolder);
|
||||
}
|
||||
window.ui.closeContextMenu();
|
||||
});
|
||||
|
||||
document.getElementById('move-folder-option').addEventListener('click', () => {
|
||||
if (window.app.contextMenuTargetFolder) {
|
||||
this.showMoveDialog(window.app.contextMenuTargetFolder, 'folder');
|
||||
}
|
||||
window.ui.closeContextMenu();
|
||||
});
|
||||
|
||||
document.getElementById('share-folder-option').addEventListener('click', () => {
|
||||
const folder = window.app.contextMenuTargetFolder;
|
||||
if (folder) {
|
||||
this.showShareDialog(folder, 'folder');
|
||||
}
|
||||
window.ui.closeContextMenu();
|
||||
});
|
||||
|
||||
document.getElementById('delete-folder-option').addEventListener('click', async () => {
|
||||
const folder = window.app.contextMenuTargetFolder;
|
||||
window.ui.closeContextMenu();
|
||||
if (folder) {
|
||||
await window.fileOps.deleteFolder(folder.id, folder.name);
|
||||
}
|
||||
});
|
||||
|
||||
// File context menu options
|
||||
document.getElementById('view-file-option').addEventListener('click', () => {
|
||||
if (window.app.contextMenuTargetFile) {
|
||||
// Capture reference before context menu cleanup nullifies it
|
||||
const file = window.app.contextMenuTargetFile;
|
||||
const token = localStorage.getItem('oxicloud_token');
|
||||
const headers = token ? { 'Authorization': `Bearer ${token}` } : {};
|
||||
fetch(`/api/files/${file.id}?metadata=true`, { headers })
|
||||
.then(response => response.json())
|
||||
.then(fileDetails => {
|
||||
// Check if viewable file type (images, PDFs, text files)
|
||||
if (window.ui && window.ui.isViewableFile(fileDetails)) {
|
||||
// Open with inline viewer
|
||||
if (window.inlineViewer) {
|
||||
window.inlineViewer.openFile(fileDetails);
|
||||
} else {
|
||||
// If no viewer is available, download directly
|
||||
window.fileOps.downloadFile(file.id, file.name);
|
||||
}
|
||||
} else {
|
||||
// For non-viewable files, download
|
||||
window.fileOps.downloadFile(file.id, file.name);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error fetching file details:', error);
|
||||
// On error, fallback to download
|
||||
window.fileOps.downloadFile(file.id, file.name);
|
||||
});
|
||||
}
|
||||
window.ui.closeFileContextMenu();
|
||||
});
|
||||
|
||||
document.getElementById('download-file-option').addEventListener('click', () => {
|
||||
if (window.app.contextMenuTargetFile) {
|
||||
window.fileOps.downloadFile(
|
||||
window.app.contextMenuTargetFile.id,
|
||||
window.app.contextMenuTargetFile.name
|
||||
);
|
||||
}
|
||||
window.ui.closeFileContextMenu();
|
||||
});
|
||||
|
||||
document.getElementById('favorite-file-option').addEventListener('click', async () => {
|
||||
if (window.app.contextMenuTargetFile) {
|
||||
const file = window.app.contextMenuTargetFile;
|
||||
|
||||
// Check if file is already in favorites to toggle
|
||||
if (window.favorites && window.favorites.isFavorite(file.id, 'file')) {
|
||||
// Remove from favorites
|
||||
const ok = await window.favorites.removeFromFavorites(file.id, 'file');
|
||||
if (ok && window.ui && typeof window.ui.setFavoriteVisualState === 'function') {
|
||||
window.ui.setFavoriteVisualState(file.id, 'file', false);
|
||||
}
|
||||
} else {
|
||||
// Add to favorites
|
||||
const ok = await window.favorites.addToFavorites(
|
||||
file.id,
|
||||
file.name,
|
||||
'file',
|
||||
file.folder_id
|
||||
);
|
||||
if (ok && window.ui && typeof window.ui.setFavoriteVisualState === 'function') {
|
||||
window.ui.setFavoriteVisualState(file.id, 'file', true);
|
||||
}
|
||||
}
|
||||
this.syncFavoriteOptionLabels();
|
||||
}
|
||||
window.ui.closeFileContextMenu();
|
||||
});
|
||||
|
||||
document.getElementById('rename-file-option').addEventListener('click', () => {
|
||||
if (window.app.contextMenuTargetFile) {
|
||||
this.showRenameFileDialog(window.app.contextMenuTargetFile);
|
||||
}
|
||||
window.ui.closeFileContextMenu();
|
||||
});
|
||||
|
||||
document.getElementById('move-file-option').addEventListener('click', () => {
|
||||
if (window.app.contextMenuTargetFile) {
|
||||
this.showMoveDialog(window.app.contextMenuTargetFile, 'file');
|
||||
}
|
||||
window.ui.closeFileContextMenu();
|
||||
});
|
||||
|
||||
document.getElementById('share-file-option').addEventListener('click', () => {
|
||||
const file = window.app.contextMenuTargetFile;
|
||||
if (file) {
|
||||
this.showShareDialog(file, 'file');
|
||||
}
|
||||
window.ui.closeFileContextMenu();
|
||||
});
|
||||
|
||||
document.getElementById('delete-file-option').addEventListener('click', async () => {
|
||||
const file = window.app.contextMenuTargetFile;
|
||||
window.ui.closeFileContextMenu();
|
||||
if (file) {
|
||||
await window.fileOps.deleteFile(file.id, file.name);
|
||||
}
|
||||
});
|
||||
|
||||
// Rename dialog events
|
||||
const renameCancelBtn = document.getElementById('rename-cancel-btn');
|
||||
const renameConfirmBtn = document.getElementById('rename-confirm-btn');
|
||||
const renameInput = document.getElementById('rename-input');
|
||||
|
||||
renameCancelBtn.addEventListener('click', this.closeRenameDialog);
|
||||
renameConfirmBtn.addEventListener('click', () => contextMenus.renameItem());
|
||||
|
||||
// Rename on Enter key
|
||||
renameInput.addEventListener('keyup', (e) => {
|
||||
if (e.key === 'Enter') {
|
||||
contextMenus.renameItem();
|
||||
} else if (e.key === 'Escape') {
|
||||
this.closeRenameDialog();
|
||||
}
|
||||
});
|
||||
|
||||
// Move dialog events
|
||||
const moveCancelBtn = document.getElementById('move-cancel-btn');
|
||||
const moveConfirmBtn = document.getElementById('move-confirm-btn');
|
||||
|
||||
moveCancelBtn.addEventListener('click', this.closeMoveDialog);
|
||||
moveConfirmBtn.addEventListener('click', async () => {
|
||||
// Batch move mode (from multiSelect)
|
||||
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;
|
||||
|
||||
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();
|
||||
window.multiSelect.clear();
|
||||
window.loadFiles();
|
||||
|
||||
if (errors > 0) {
|
||||
window.ui.showNotification('Batch move', `${success} moved, ${errors} failed`);
|
||||
} else {
|
||||
window.ui.showNotification('Items moved',
|
||||
`${success} item${success !== 1 ? 's' : ''} moved successfully`);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (window.app.moveDialogMode === 'file' && window.app.contextMenuTargetFile) {
|
||||
const success = await window.fileOps.moveFile(
|
||||
window.app.contextMenuTargetFile.id,
|
||||
window.app.selectedTargetFolderId
|
||||
);
|
||||
if (success) {
|
||||
this.closeMoveDialog();
|
||||
}
|
||||
} else if (window.app.moveDialogMode === 'folder' && window.app.contextMenuTargetFolder) {
|
||||
const success = await window.fileOps.moveFolder(
|
||||
window.app.contextMenuTargetFolder.id,
|
||||
window.app.selectedTargetFolderId
|
||||
);
|
||||
if (success) {
|
||||
this.closeMoveDialog();
|
||||
}
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Show rename dialog for a folder
|
||||
* @param {Object} folder - Folder object
|
||||
*/
|
||||
showRenameDialog(folder) {
|
||||
const renameInput = document.getElementById('rename-input');
|
||||
const renameDialog = document.getElementById('rename-dialog');
|
||||
|
||||
window.app.renameMode = 'folder';
|
||||
// Store the folder reference so it survives context menu cleanup
|
||||
window.app.renameTarget = folder;
|
||||
renameInput.value = folder.name;
|
||||
// Update header text
|
||||
const headerSpan = renameDialog.querySelector('.rename-dialog-header span');
|
||||
if (headerSpan) headerSpan.textContent = window.i18n ? window.i18n.t('dialogs.rename_folder') : 'Rename folder';
|
||||
renameDialog.style.display = 'flex';
|
||||
renameInput.focus();
|
||||
renameInput.select();
|
||||
},
|
||||
|
||||
/**
|
||||
* Show rename dialog for a file
|
||||
* @param {Object} file - File object
|
||||
*/
|
||||
showRenameFileDialog(file) {
|
||||
const renameInput = document.getElementById('rename-input');
|
||||
const renameDialog = document.getElementById('rename-dialog');
|
||||
|
||||
window.app.renameMode = 'file';
|
||||
// Store the file reference so it survives context menu cleanup
|
||||
window.app.renameTarget = file;
|
||||
renameInput.value = file.name;
|
||||
// Update header text
|
||||
const headerSpan = renameDialog.querySelector('.rename-dialog-header span');
|
||||
if (headerSpan) headerSpan.textContent = window.i18n ? window.i18n.t('dialogs.rename_file') : 'Rename file';
|
||||
renameDialog.style.display = 'flex';
|
||||
renameInput.focus();
|
||||
renameInput.select();
|
||||
},
|
||||
|
||||
/**
|
||||
* Close rename dialog
|
||||
*/
|
||||
closeRenameDialog() {
|
||||
document.getElementById('rename-dialog').style.display = 'none';
|
||||
window.app.contextMenuTargetFolder = null;
|
||||
window.app.renameTarget = null;
|
||||
},
|
||||
|
||||
/**
|
||||
* Show move dialog for a file or folder
|
||||
* @param {Object} item - File or folder object
|
||||
* @param {string} mode - 'file' or 'folder'
|
||||
*/
|
||||
async showMoveDialog(item, mode) {
|
||||
// Set mode
|
||||
window.app.moveDialogMode = mode;
|
||||
|
||||
// Reset selection
|
||||
window.app.selectedTargetFolderId = "";
|
||||
|
||||
// Update dialog title (preserve icon)
|
||||
const dialogHeader = document.getElementById('move-file-dialog').querySelector('.rename-dialog-header');
|
||||
const titleText = mode === 'file' ?
|
||||
(window.i18n ? window.i18n.t('dialogs.move_file') : 'Move file') :
|
||||
(window.i18n ? window.i18n.t('dialogs.move_folder') : 'Move folder');
|
||||
dialogHeader.innerHTML = `<i class="fas fa-arrows-alt" style="color:#ff5e3a"></i> <span>${titleText}</span>`;
|
||||
|
||||
// Load all available folders
|
||||
await this.loadAllFolders(item.id, mode);
|
||||
|
||||
// Show dialog
|
||||
document.getElementById('move-file-dialog').style.display = 'flex';
|
||||
},
|
||||
|
||||
/**
|
||||
* Close move dialog
|
||||
*/
|
||||
closeMoveDialog() {
|
||||
document.getElementById('move-file-dialog').style.display = 'none';
|
||||
window.app.contextMenuTargetFile = null;
|
||||
window.app.contextMenuTargetFolder = null;
|
||||
},
|
||||
|
||||
/**
|
||||
* Rename the selected folder or file
|
||||
*/
|
||||
async renameItem() {
|
||||
const newName = document.getElementById('rename-input').value.trim();
|
||||
if (!newName) {
|
||||
alert(window.i18n ? window.i18n.t('errors.empty_name') : 'Name cannot be empty');
|
||||
return;
|
||||
}
|
||||
|
||||
// Use renameTarget which was saved before the context menu was closed
|
||||
const target = window.app.renameTarget;
|
||||
if (!target) {
|
||||
console.error('No rename target available');
|
||||
return;
|
||||
}
|
||||
|
||||
if (window.app.renameMode === 'file') {
|
||||
const success = await window.fileOps.renameFile(target.id, newName);
|
||||
if (success) {
|
||||
contextMenus.closeRenameDialog();
|
||||
window.loadFiles();
|
||||
}
|
||||
} else if (window.app.renameMode === 'folder') {
|
||||
const success = await window.fileOps.renameFolder(target.id, newName);
|
||||
if (success) {
|
||||
contextMenus.closeRenameDialog();
|
||||
window.loadFiles();
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
// Keep backward compat
|
||||
renameFolder() {
|
||||
return contextMenus.renameItem();
|
||||
},
|
||||
|
||||
/**
|
||||
* Load all folders for the move dialog
|
||||
* @param {string} itemId - ID of the item being moved
|
||||
* @param {string} mode - 'file' or 'folder'
|
||||
*/
|
||||
async loadAllFolders(itemId, mode) {
|
||||
try {
|
||||
const token = localStorage.getItem('oxicloud_token');
|
||||
const headers = token ? { 'Authorization': `Bearer ${token}` } : {};
|
||||
const response = await fetch('/api/folders', { headers });
|
||||
if (response.ok) {
|
||||
const folders = await response.json();
|
||||
const folderSelectContainer = document.getElementById('folder-select-container');
|
||||
|
||||
// Clear container except root option
|
||||
folderSelectContainer.innerHTML = `
|
||||
<div class="folder-select-item selected" data-folder-id="">
|
||||
<i class="fas fa-folder"></i> <span data-i18n="dialogs.root">Root</span>
|
||||
</div>
|
||||
`;
|
||||
|
||||
// Select root by default
|
||||
window.app.selectedTargetFolderId = "";
|
||||
|
||||
// Add all available folders
|
||||
if (Array.isArray(folders)) {
|
||||
folders.forEach(folder => {
|
||||
// Skip folders that would create cycles
|
||||
if (mode === 'folder' && folder.id === itemId) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Skip current folder of the item
|
||||
if (mode === 'file' && window.app.contextMenuTargetFile &&
|
||||
folder.id === window.app.contextMenuTargetFile.folder_id) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (mode === 'folder' && window.app.contextMenuTargetFolder &&
|
||||
folder.id === window.app.contextMenuTargetFolder.parent_id) {
|
||||
return;
|
||||
}
|
||||
|
||||
const folderItem = document.createElement('div');
|
||||
folderItem.className = 'folder-select-item';
|
||||
folderItem.dataset.folderId = folder.id;
|
||||
folderItem.innerHTML = `<i class="fas fa-folder"></i> ${escapeHtml(folder.name)}`;
|
||||
|
||||
folderItem.addEventListener('click', () => {
|
||||
// Deselect all
|
||||
document.querySelectorAll('.folder-select-item').forEach(item => {
|
||||
item.classList.remove('selected');
|
||||
});
|
||||
|
||||
// Select this one
|
||||
folderItem.classList.add('selected');
|
||||
window.app.selectedTargetFolderId = folder.id;
|
||||
});
|
||||
|
||||
folderSelectContainer.appendChild(folderItem);
|
||||
});
|
||||
}
|
||||
|
||||
// Event for root option
|
||||
const rootOption = folderSelectContainer.querySelector('.folder-select-item');
|
||||
rootOption.addEventListener('click', () => {
|
||||
document.querySelectorAll('.folder-select-item').forEach(item => {
|
||||
item.classList.remove('selected');
|
||||
});
|
||||
rootOption.classList.add('selected');
|
||||
window.app.selectedTargetFolderId = "";
|
||||
});
|
||||
|
||||
// Translate new elements (scoped to container)
|
||||
if (window.i18n && window.i18n.translateElement) {
|
||||
window.i18n.translateElement(folderSelectContainer);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error loading folders:', error);
|
||||
}
|
||||
},
|
||||
/**
|
||||
* Show share dialog for files or folders
|
||||
* @param {Object} item - File or folder object
|
||||
* @param {string} itemType - 'file' or 'folder'
|
||||
*/
|
||||
async showShareDialog(item, itemType) {
|
||||
try {
|
||||
const shareDialog = document.getElementById('share-dialog');
|
||||
if (!shareDialog) {
|
||||
console.error('Share dialog element not found in DOM');
|
||||
window.ui.showNotification('Error', 'Share dialog not available');
|
||||
return;
|
||||
}
|
||||
|
||||
// Update dialog title — use the <span> inside header to preserve <i> icon
|
||||
const dialogHeader = shareDialog.querySelector('.share-dialog-header');
|
||||
if (dialogHeader) {
|
||||
const headerSpan = dialogHeader.querySelector('span');
|
||||
const titleText = itemType === 'file' ?
|
||||
(window.i18n ? window.i18n.t('dialogs.share_file') : 'Share file') :
|
||||
(window.i18n ? window.i18n.t('dialogs.share_folder') : 'Share folder');
|
||||
if (headerSpan) {
|
||||
headerSpan.textContent = titleText;
|
||||
} else {
|
||||
dialogHeader.textContent = titleText;
|
||||
}
|
||||
}
|
||||
|
||||
const itemName = document.getElementById('shared-item-name');
|
||||
if (itemName) itemName.textContent = item.name;
|
||||
|
||||
// Reset form
|
||||
const pwField = document.getElementById('share-password');
|
||||
const expField = document.getElementById('share-expiration');
|
||||
if (pwField) pwField.value = '';
|
||||
if (expField) expField.value = '';
|
||||
const permRead = document.getElementById('share-permission-read');
|
||||
const permWrite = document.getElementById('share-permission-write');
|
||||
const permReshare = document.getElementById('share-permission-reshare');
|
||||
if (permRead) permRead.checked = true;
|
||||
if (permWrite) permWrite.checked = false;
|
||||
if (permReshare) permReshare.checked = false;
|
||||
|
||||
// Store the current item and type for use when creating the share
|
||||
window.app.shareDialogItem = item;
|
||||
window.app.shareDialogItemType = 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
|
||||
existingSharesContainer.innerHTML = '';
|
||||
|
||||
if (existingShares.length > 0) {
|
||||
document.getElementById('existing-shares-section').style.display = 'block';
|
||||
|
||||
// Create elements for each existing share
|
||||
existingShares.forEach(share => {
|
||||
const shareEl = document.createElement('div');
|
||||
shareEl.className = 'existing-share-item';
|
||||
|
||||
const expiresText = share.expires_at ?
|
||||
`Expires: ${window.fileSharing.formatExpirationDate(share.expires_at)}` :
|
||||
'No expiration';
|
||||
|
||||
// Share URL
|
||||
const urlDiv = document.createElement('div');
|
||||
urlDiv.className = 'share-url';
|
||||
urlDiv.textContent = share.url;
|
||||
shareEl.appendChild(urlDiv);
|
||||
|
||||
// Share info
|
||||
const infoDiv = document.createElement('div');
|
||||
infoDiv.className = 'share-info';
|
||||
if (share.has_password) {
|
||||
const protectedSpan = document.createElement('span');
|
||||
protectedSpan.className = 'share-protected';
|
||||
protectedSpan.innerHTML = '<i class="fas fa-lock"></i> Password protected';
|
||||
infoDiv.appendChild(protectedSpan);
|
||||
}
|
||||
const expirationSpan = document.createElement('span');
|
||||
expirationSpan.className = 'share-expiration';
|
||||
expirationSpan.textContent = expiresText;
|
||||
infoDiv.appendChild(expirationSpan);
|
||||
shareEl.appendChild(infoDiv);
|
||||
|
||||
// Share actions
|
||||
const actionsDiv = document.createElement('div');
|
||||
actionsDiv.className = 'share-actions';
|
||||
|
||||
const copyBtn = document.createElement('button');
|
||||
copyBtn.className = 'btn btn-small copy-link-btn';
|
||||
copyBtn.dataset.shareUrl = share.url;
|
||||
copyBtn.innerHTML = '<i class="fas fa-copy"></i> Copy';
|
||||
actionsDiv.appendChild(copyBtn);
|
||||
|
||||
const deleteBtn = document.createElement('button');
|
||||
deleteBtn.className = 'btn btn-small btn-danger delete-link-btn';
|
||||
deleteBtn.dataset.shareId = share.id;
|
||||
deleteBtn.innerHTML = '<i class="fas fa-trash"></i> Delete';
|
||||
actionsDiv.appendChild(deleteBtn);
|
||||
|
||||
shareEl.appendChild(actionsDiv);
|
||||
|
||||
existingSharesContainer.appendChild(shareEl);
|
||||
});
|
||||
|
||||
// Add event listeners for copy and delete buttons
|
||||
document.querySelectorAll('.copy-link-btn').forEach(btn => {
|
||||
btn.addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
const url = btn.getAttribute('data-share-url');
|
||||
window.fileSharing.copyLinkToClipboard(url);
|
||||
});
|
||||
});
|
||||
|
||||
document.querySelectorAll('.delete-link-btn').forEach(btn => {
|
||||
btn.addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
const shareId = btn.getAttribute('data-share-id');
|
||||
|
||||
showConfirmDialog({
|
||||
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(async (confirmed) => {
|
||||
if (confirmed) {
|
||||
await window.fileSharing.removeSharedLink(shareId);
|
||||
btn.closest('.existing-share-item').remove();
|
||||
if (existingSharesContainer.children.length === 0) {
|
||||
document.getElementById('existing-shares-section').style.display = 'none';
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
} else {
|
||||
document.getElementById('existing-shares-section').style.display = 'none';
|
||||
}
|
||||
|
||||
// Hide new-share section from previous use
|
||||
const newShareSection = document.getElementById('new-share-section');
|
||||
if (newShareSection) newShareSection.style.display = 'none';
|
||||
|
||||
// Show dialog
|
||||
shareDialog.style.display = 'flex';
|
||||
console.log('Share dialog opened for', itemType, item.name);
|
||||
} catch (error) {
|
||||
console.error('Error opening share dialog:', error);
|
||||
window.ui.showNotification('Error', 'Could not open share dialog');
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Create a shared link with the configured options
|
||||
*/
|
||||
async createSharedLink() {
|
||||
if (!window.app.shareDialogItem || !window.app.shareDialogItemType) {
|
||||
window.ui.showNotification('Error', 'Could not share the item');
|
||||
return;
|
||||
}
|
||||
|
||||
// Get values from form
|
||||
const password = document.getElementById('share-password').value;
|
||||
const expirationDate = document.getElementById('share-expiration').value;
|
||||
const permissionRead = document.getElementById('share-permission-read').checked;
|
||||
const permissionWrite = document.getElementById('share-permission-write').checked;
|
||||
const permissionReshare = document.getElementById('share-permission-reshare').checked;
|
||||
|
||||
const item = window.app.shareDialogItem;
|
||||
const itemType = window.app.shareDialogItemType;
|
||||
|
||||
// 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,
|
||||
permissions: {
|
||||
read: permissionRead,
|
||||
write: permissionWrite,
|
||||
reshare: permissionReshare
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
const token = localStorage.getItem('oxicloud_token');
|
||||
const headers = { 'Content-Type': 'application/json' };
|
||||
if (token) headers['Authorization'] = `Bearer ${token}`;
|
||||
|
||||
const response = await fetch('/api/shares', {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify(createDto)
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errBody = await response.json().catch(() => ({}));
|
||||
throw new Error(errBody.error || `Server error ${response.status}`);
|
||||
}
|
||||
|
||||
const shareInfo = await response.json();
|
||||
|
||||
// Update UI with new share
|
||||
const shareUrl = document.getElementById('generated-share-url');
|
||||
if (shareUrl) {
|
||||
shareUrl.value = shareInfo.url;
|
||||
document.getElementById('new-share-section').style.display = 'block';
|
||||
shareUrl.focus();
|
||||
shareUrl.select();
|
||||
}
|
||||
|
||||
// Show success message
|
||||
window.ui.showNotification(
|
||||
window.i18n ? window.i18n.t('notifications.link_created') : 'Link created',
|
||||
window.i18n ? window.i18n.t('notifications.share_success') : 'Shared link created successfully'
|
||||
);
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error creating shared link:', error);
|
||||
window.ui.showNotification('Error', error.message || 'Could not create shared link');
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Show email notification dialog
|
||||
* @param {string} shareUrl - URL to share
|
||||
*/
|
||||
showEmailNotificationDialog(shareUrl) {
|
||||
// Update dialog content
|
||||
document.getElementById('notification-share-url').textContent = shareUrl;
|
||||
document.getElementById('notification-email').value = '';
|
||||
document.getElementById('notification-message').value = '';
|
||||
|
||||
// Store the URL for later use
|
||||
window.app.notificationShareUrl = shareUrl;
|
||||
|
||||
// Show dialog
|
||||
document.getElementById('notification-dialog').style.display = 'flex';
|
||||
},
|
||||
|
||||
/**
|
||||
* Send share notification email
|
||||
*/
|
||||
sendShareNotification() {
|
||||
const email = document.getElementById('notification-email').value.trim();
|
||||
const message = document.getElementById('notification-message').value.trim();
|
||||
const shareUrl = window.app.notificationShareUrl;
|
||||
|
||||
if (!email || !shareUrl) {
|
||||
window.ui.showNotification('Error', 'Please enter a valid email address');
|
||||
return;
|
||||
}
|
||||
|
||||
// Validate email format
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
if (!emailRegex.test(email)) {
|
||||
window.ui.showNotification('Error', 'Please enter a valid email address');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
window.fileSharing.sendShareNotification(shareUrl, email, message);
|
||||
document.getElementById('notification-dialog').style.display = 'none';
|
||||
} catch (error) {
|
||||
console.error('Error sending notification:', error);
|
||||
window.ui.showNotification('Error', 'Could not send notification');
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Close share dialog
|
||||
*/
|
||||
closeShareDialog() {
|
||||
const dialog = document.getElementById('share-dialog');
|
||||
if (dialog) dialog.style.display = 'none';
|
||||
window.app.shareDialogItem = null;
|
||||
window.app.shareDialogItemType = null;
|
||||
},
|
||||
|
||||
/**
|
||||
* Close notification dialog
|
||||
*/
|
||||
closeNotificationDialog() {
|
||||
document.getElementById('notification-dialog').style.display = 'none';
|
||||
window.app.notificationShareUrl = null;
|
||||
}
|
||||
};
|
||||
|
||||
// Expose context menus module globally
|
||||
window.contextMenus = contextMenus;
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,427 @@
|
||||
/**
|
||||
* OxiCloud Inline Viewer
|
||||
* A simpler approach to viewing files that doesn't rely on complex DOM manipulation
|
||||
*/
|
||||
|
||||
class InlineViewer {
|
||||
constructor() {
|
||||
this.setupViewer();
|
||||
this.currentFile = null;
|
||||
}
|
||||
|
||||
setupViewer() {
|
||||
// Create the viewer modal if it doesn't exist
|
||||
if (document.getElementById('inline-viewer-modal')) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Verify document.body exists
|
||||
if (!document.body) {
|
||||
console.warn('Document body not available yet for inline viewer, will retry later');
|
||||
setTimeout(() => this.setupViewer(), 200);
|
||||
return;
|
||||
}
|
||||
|
||||
// Create modal container
|
||||
const modal = document.createElement('div');
|
||||
modal.id = 'inline-viewer-modal';
|
||||
modal.className = 'inline-viewer-modal';
|
||||
modal.innerHTML = `
|
||||
<div class="inline-viewer-content">
|
||||
<div class="inline-viewer-header">
|
||||
<div class="inline-viewer-title">File Viewer</div>
|
||||
<button class="inline-viewer-close"><i class="fas fa-times"></i></button>
|
||||
</div>
|
||||
<div class="inline-viewer-container"></div>
|
||||
<div class="inline-viewer-toolbar">
|
||||
<button class="inline-viewer-download"><i class="fas fa-download"></i> Download</button>
|
||||
<div class="inline-viewer-controls">
|
||||
<button class="inline-viewer-zoom-out" title="Zoom Out"><i class="fas fa-search-minus"></i></button>
|
||||
<button class="inline-viewer-zoom-reset" title="Reset Zoom"><i class="fas fa-expand"></i></button>
|
||||
<button class="inline-viewer-zoom-in" title="Zoom In"><i class="fas fa-search-plus"></i></button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
// Add to document
|
||||
document.body.appendChild(modal);
|
||||
|
||||
// Add event listeners
|
||||
modal.querySelector('.inline-viewer-close').addEventListener('click', () => {
|
||||
this.closeViewer();
|
||||
});
|
||||
|
||||
modal.querySelector('.inline-viewer-download').addEventListener('click', () => {
|
||||
if (this.currentFile) {
|
||||
this.downloadFile(this.currentFile);
|
||||
}
|
||||
});
|
||||
|
||||
// Add zoom controls for images
|
||||
modal.querySelector('.inline-viewer-zoom-in').addEventListener('click', () => {
|
||||
this.zoomImage(1.2);
|
||||
});
|
||||
|
||||
modal.querySelector('.inline-viewer-zoom-out').addEventListener('click', () => {
|
||||
this.zoomImage(0.8);
|
||||
});
|
||||
|
||||
modal.querySelector('.inline-viewer-zoom-reset').addEventListener('click', () => {
|
||||
this.resetZoom();
|
||||
});
|
||||
|
||||
// Close on ESC key
|
||||
document.addEventListener('keydown', (e) => {
|
||||
if (e.key === 'Escape' && modal.classList.contains('active')) {
|
||||
this.closeViewer();
|
||||
}
|
||||
});
|
||||
|
||||
// Click outside to close
|
||||
modal.addEventListener('click', (e) => {
|
||||
if (e.target === modal) {
|
||||
this.closeViewer();
|
||||
}
|
||||
});
|
||||
|
||||
console.log('Inline viewer initialized');
|
||||
}
|
||||
|
||||
openFile(file) {
|
||||
console.log('Opening file:', file);
|
||||
this.currentFile = file;
|
||||
|
||||
// Get container
|
||||
const modal = document.getElementById('inline-viewer-modal');
|
||||
const container = modal.querySelector('.inline-viewer-container');
|
||||
const title = modal.querySelector('.inline-viewer-title');
|
||||
|
||||
// Clear container
|
||||
container.innerHTML = '';
|
||||
|
||||
// Set title
|
||||
title.textContent = file.name;
|
||||
|
||||
// Set controls visibility
|
||||
const controls = modal.querySelector('.inline-viewer-controls');
|
||||
|
||||
// Show viewer based on file type
|
||||
if (file.mime_type && file.mime_type.startsWith('image/')) {
|
||||
// Show zoom controls
|
||||
controls.style.display = 'flex';
|
||||
|
||||
// Show loading indicator
|
||||
const loader = document.createElement('div');
|
||||
loader.className = 'inline-viewer-loader';
|
||||
loader.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
|
||||
container.appendChild(loader);
|
||||
|
||||
// Create image viewer using a blob URL
|
||||
this.createBlobUrlViewer(file, 'image', container, loader);
|
||||
}
|
||||
else if (file.mime_type && file.mime_type === 'application/pdf') {
|
||||
// Hide zoom controls for PDFs
|
||||
controls.style.display = 'none';
|
||||
|
||||
// Show loading indicator
|
||||
const loader = document.createElement('div');
|
||||
loader.className = 'inline-viewer-loader';
|
||||
loader.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
|
||||
container.appendChild(loader);
|
||||
|
||||
// Create PDF viewer using object tag with blob URL
|
||||
this.createBlobUrlViewer(file, 'pdf', container, loader);
|
||||
}
|
||||
else if (file.mime_type && this.isTextViewable(file.mime_type)) {
|
||||
// Hide zoom controls for text files
|
||||
controls.style.display = 'none';
|
||||
|
||||
// Show loading indicator
|
||||
const loader = document.createElement('div');
|
||||
loader.className = 'inline-viewer-loader';
|
||||
loader.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';
|
||||
container.appendChild(loader);
|
||||
|
||||
// Create text viewer using authenticated fetch
|
||||
this.createTextViewer(file, container, loader);
|
||||
}
|
||||
else {
|
||||
// Hide zoom controls for unsupported files
|
||||
controls.style.display = 'none';
|
||||
|
||||
// Show unsupported file message
|
||||
const message = document.createElement('div');
|
||||
message.className = 'inline-viewer-message';
|
||||
message.innerHTML = `
|
||||
<div class="inline-viewer-icon"><i class="fas fa-file"></i></div>
|
||||
<div class="inline-viewer-text">
|
||||
<p>This file type cannot be previewed.</p>
|
||||
<p>Click "Download" to get the file.</p>
|
||||
</div>
|
||||
`;
|
||||
container.appendChild(message);
|
||||
}
|
||||
|
||||
// Show modal
|
||||
modal.classList.add('active');
|
||||
}
|
||||
|
||||
// Check if a MIME type is text-viewable — delegates to window.isTextViewable
|
||||
isTextViewable(mimeType) {
|
||||
return window.isTextViewable ? window.isTextViewable(mimeType) : false;
|
||||
}
|
||||
|
||||
// Creates a text viewer using authenticated fetch
|
||||
async createTextViewer(file, container, loader) {
|
||||
try {
|
||||
console.log('Creating text viewer for:', file.name);
|
||||
|
||||
const token = localStorage.getItem('oxicloud_token');
|
||||
const headers = token ? { 'Authorization': `Bearer ${token}` } : {};
|
||||
|
||||
const response = await fetch(`/api/files/${file.id}?inline=true`, { headers });
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Error fetching file: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
||||
const text = await response.text();
|
||||
|
||||
// Remove loader
|
||||
if (loader && loader.parentNode) {
|
||||
loader.parentNode.removeChild(loader);
|
||||
}
|
||||
|
||||
// Create text viewer element
|
||||
const pre = document.createElement('pre');
|
||||
pre.className = 'inline-viewer-text-content';
|
||||
pre.textContent = text;
|
||||
container.appendChild(pre);
|
||||
|
||||
console.log('Text viewer created successfully');
|
||||
} catch (error) {
|
||||
console.error('Error creating text viewer:', error);
|
||||
|
||||
// Remove loader
|
||||
if (loader && loader.parentNode) {
|
||||
loader.parentNode.removeChild(loader);
|
||||
}
|
||||
|
||||
this.showErrorMessage(container);
|
||||
}
|
||||
}
|
||||
|
||||
// Creates a viewer using a Blob URL to avoid content-disposition header
|
||||
async createBlobUrlViewer(file, type, container, loader) {
|
||||
try {
|
||||
console.log('Creating blob URL viewer for:', file.name, 'type:', type);
|
||||
|
||||
// Use XMLHttpRequest instead of fetch to get better control over the response
|
||||
const xhr = new XMLHttpRequest();
|
||||
xhr.open('GET', `/api/files/${file.id}?inline=true`, true);
|
||||
xhr.responseType = 'blob';
|
||||
|
||||
// Add auth header
|
||||
const token = localStorage.getItem('oxicloud_token');
|
||||
if (token) {
|
||||
xhr.setRequestHeader('Authorization', `Bearer ${token}`);
|
||||
}
|
||||
|
||||
// Create a promise to handle the XHR
|
||||
const response = await new Promise((resolve, reject) => {
|
||||
xhr.onload = function() {
|
||||
if (this.status >= 200 && this.status < 300) {
|
||||
resolve(this.response);
|
||||
} else {
|
||||
reject(new Error(`Error fetching file: ${this.status} ${this.statusText}`));
|
||||
}
|
||||
};
|
||||
|
||||
xhr.onerror = function() {
|
||||
reject(new Error('Network error'));
|
||||
};
|
||||
|
||||
xhr.send();
|
||||
});
|
||||
|
||||
// Create blob URL from response
|
||||
const blob = response;
|
||||
const blobUrl = URL.createObjectURL(blob);
|
||||
|
||||
console.log('Created blob URL:', blobUrl.substring(0, 30) + '...');
|
||||
|
||||
// Remove loader
|
||||
if (loader && loader.parentNode) {
|
||||
loader.parentNode.removeChild(loader);
|
||||
}
|
||||
|
||||
if (type === 'image') {
|
||||
console.log('Creating image viewer');
|
||||
// Create image element
|
||||
const img = document.createElement('img');
|
||||
img.className = 'inline-viewer-image';
|
||||
img.src = blobUrl;
|
||||
img.alt = file.name;
|
||||
container.appendChild(img);
|
||||
|
||||
// Add loading indicator until image loads
|
||||
img.style.opacity = 0;
|
||||
img.onload = () => {
|
||||
console.log('Image loaded successfully');
|
||||
img.style.opacity = 1;
|
||||
};
|
||||
|
||||
img.onerror = () => {
|
||||
console.error('Failed to load image');
|
||||
container.removeChild(img);
|
||||
this.showErrorMessage(container);
|
||||
};
|
||||
}
|
||||
else if (type === 'pdf') {
|
||||
console.log('Creating PDF viewer');
|
||||
|
||||
// Create iframe for PDF (more reliable than object tag)
|
||||
const iframe = document.createElement('iframe');
|
||||
iframe.className = 'inline-viewer-pdf';
|
||||
iframe.src = blobUrl;
|
||||
iframe.setAttribute('allowfullscreen', 'true');
|
||||
container.appendChild(iframe);
|
||||
|
||||
// Monitor iframe for loading issues
|
||||
setTimeout(() => {
|
||||
if (!iframe.contentDocument ||
|
||||
iframe.contentDocument.body.innerHTML === '') {
|
||||
console.warn('PDF viewer might be having issues, adding fallback');
|
||||
|
||||
// Add fallback embed
|
||||
const embed = document.createElement('embed');
|
||||
embed.className = 'inline-viewer-pdf-fallback';
|
||||
embed.type = 'application/pdf';
|
||||
embed.src = blobUrl;
|
||||
container.appendChild(embed);
|
||||
}
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
// Store blob URL for cleaning up later
|
||||
this.currentBlobUrl = blobUrl;
|
||||
}
|
||||
catch (error) {
|
||||
console.error('Error creating blob URL viewer:', error);
|
||||
|
||||
// Remove loader
|
||||
if (loader && loader.parentNode) {
|
||||
loader.parentNode.removeChild(loader);
|
||||
}
|
||||
|
||||
this.showErrorMessage(container);
|
||||
}
|
||||
}
|
||||
|
||||
// Helper to show error message
|
||||
showErrorMessage(container) {
|
||||
// Show error message
|
||||
const message = document.createElement('div');
|
||||
message.className = 'inline-viewer-message';
|
||||
message.innerHTML = `
|
||||
<div class="inline-viewer-icon"><i class="fas fa-exclamation-triangle"></i></div>
|
||||
<div class="inline-viewer-text">
|
||||
<p>Error loading the file.</p>
|
||||
<p>Try downloading it directly.</p>
|
||||
</div>
|
||||
`;
|
||||
container.appendChild(message);
|
||||
}
|
||||
|
||||
closeViewer() {
|
||||
// Get modal
|
||||
const modal = document.getElementById('inline-viewer-modal');
|
||||
|
||||
// Hide modal
|
||||
modal.classList.remove('active');
|
||||
|
||||
// Clean up blob URL if exists
|
||||
if (this.currentBlobUrl) {
|
||||
URL.revokeObjectURL(this.currentBlobUrl);
|
||||
this.currentBlobUrl = null;
|
||||
}
|
||||
|
||||
// Clear references
|
||||
this.currentFile = null;
|
||||
}
|
||||
|
||||
downloadFile(file) {
|
||||
const token = localStorage.getItem('oxicloud_token');
|
||||
const headers = token ? { 'Authorization': `Bearer ${token}` } : {};
|
||||
|
||||
fetch(`/api/files/${file.id}`, { headers })
|
||||
.then(res => {
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
return res.blob();
|
||||
})
|
||||
.then(blob => {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = file.name;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
URL.revokeObjectURL(url);
|
||||
})
|
||||
.catch(err => console.error('Download error:', err));
|
||||
}
|
||||
|
||||
zoomImage(factor) {
|
||||
const container = document.querySelector('.inline-viewer-container');
|
||||
const img = container.querySelector('.inline-viewer-image');
|
||||
|
||||
if (!img) return;
|
||||
|
||||
// Get current scale
|
||||
let scale = img.dataset.scale ? parseFloat(img.dataset.scale) : 1.0;
|
||||
|
||||
// Apply zoom factor
|
||||
scale *= factor;
|
||||
|
||||
// Limit scale
|
||||
scale = Math.max(0.1, Math.min(5.0, scale));
|
||||
|
||||
// Save scale
|
||||
img.dataset.scale = scale;
|
||||
|
||||
// Apply scale
|
||||
img.style.transform = `scale(${scale})`;
|
||||
}
|
||||
|
||||
resetZoom() {
|
||||
const container = document.querySelector('.inline-viewer-container');
|
||||
const img = container.querySelector('.inline-viewer-image');
|
||||
|
||||
if (!img) return;
|
||||
|
||||
// Reset scale
|
||||
img.dataset.scale = 1.0;
|
||||
img.style.transform = 'scale(1.0)';
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize viewer when document is ready
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
// Check if it's already initialized
|
||||
if (!window.inlineViewer) {
|
||||
console.log('Initializing inline viewer on DOMContentLoaded');
|
||||
window.inlineViewer = new InlineViewer();
|
||||
}
|
||||
});
|
||||
|
||||
// Fallback initialization for cases where DOMContentLoaded already fired
|
||||
if (document.readyState === 'complete' || document.readyState === 'interactive') {
|
||||
if (!window.inlineViewer) {
|
||||
console.log('Fallback initialization for inline viewer');
|
||||
setTimeout(() => {
|
||||
window.inlineViewer = new InlineViewer();
|
||||
}, 100);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,542 @@
|
||||
/**
|
||||
* OxiCloud - Multi-Select & Batch Actions Module
|
||||
*
|
||||
* Adds checkboxes to grid and list views, replaces the list-view header
|
||||
* with a NextCloud-style selection bar when items are selected, and
|
||||
* provides batch delete / move / download / favorites operations.
|
||||
*/
|
||||
|
||||
const multiSelect = {
|
||||
/** Currently selected items: Map<id, { id, name, type, parentId }> */
|
||||
_selected: new Map(),
|
||||
|
||||
/** Last clicked index for Shift-range selection */
|
||||
_lastClickedIndex: -1,
|
||||
|
||||
/** Whether the selection bar is currently visible */
|
||||
_barVisible: false,
|
||||
|
||||
/** Saved original list-header HTML so we can restore it */
|
||||
_savedHeaderHTML: '',
|
||||
|
||||
// ── Public API ──────────────────────────────────────────
|
||||
|
||||
get count() { return this._selected.size; },
|
||||
get items() { return Array.from(this._selected.values()); },
|
||||
get hasSelection() { return this._selected.size > 0; },
|
||||
get files() { return this.items.filter(i => i.type === 'file'); },
|
||||
get folders() { return this.items.filter(i => i.type === 'folder'); },
|
||||
|
||||
// ── Helpers for i18n ────────────────────────────────────
|
||||
|
||||
_t(key, vars) {
|
||||
if (window.i18n && typeof window.i18n.t === 'function') {
|
||||
const val = window.i18n.t(key, vars);
|
||||
// If i18n returned the key itself, it's missing → fall back
|
||||
if (val && val !== key) return val;
|
||||
}
|
||||
return null;
|
||||
},
|
||||
|
||||
// ── Selection state management ──────────────────────────
|
||||
|
||||
toggle(id, name, type, parentId) {
|
||||
if (this._selected.has(id)) { this._selected.delete(id); return false; }
|
||||
this._selected.set(id, { id, name, type, parentId });
|
||||
return true;
|
||||
},
|
||||
|
||||
select(id, name, type, parentId) {
|
||||
this._selected.set(id, { id, name, type, parentId });
|
||||
},
|
||||
|
||||
deselect(id) { this._selected.delete(id); },
|
||||
|
||||
clear() {
|
||||
this._selected.clear();
|
||||
this._lastClickedIndex = -1;
|
||||
document.querySelectorAll('.file-card.selected, .file-item.selected')
|
||||
.forEach(el => el.classList.remove('selected'));
|
||||
document.querySelectorAll('.item-checkbox').forEach(cb => cb.checked = false);
|
||||
this._syncUI();
|
||||
},
|
||||
|
||||
selectAll() {
|
||||
this._selectAllInContainer('files-grid', '.file-card');
|
||||
this._selectAllInContainer('files-list-view', '.file-item');
|
||||
this._syncUI();
|
||||
},
|
||||
|
||||
toggleAll() {
|
||||
const allItems = this._getAllVisibleItems();
|
||||
if (this._selected.size >= allItems.length && allItems.length > 0) {
|
||||
this.clear();
|
||||
} else {
|
||||
this.selectAll();
|
||||
}
|
||||
},
|
||||
|
||||
// ── DOM helpers ─────────────────────────────────────────
|
||||
|
||||
_selectElement(el) {
|
||||
const info = this._extractInfo(el);
|
||||
if (info) {
|
||||
this.select(info.id, info.name, info.type, info.parentId);
|
||||
el.classList.add('selected');
|
||||
}
|
||||
},
|
||||
|
||||
_selectAllInContainer(containerId, selector) {
|
||||
const container = document.getElementById(containerId);
|
||||
if (!container) return;
|
||||
container.querySelectorAll(selector).forEach(el => this._selectElement(el));
|
||||
},
|
||||
|
||||
_getAllVisibleItems() {
|
||||
const grid = document.getElementById('files-grid');
|
||||
if (grid && grid.style.display !== 'none') {
|
||||
return [...grid.querySelectorAll('.file-card')];
|
||||
}
|
||||
return [...document.querySelectorAll('#files-list-view .file-item')];
|
||||
},
|
||||
|
||||
_extractInfo(el) {
|
||||
if (el.dataset.folderId && el.dataset.folderName !== undefined) {
|
||||
return { id: el.dataset.folderId, name: el.dataset.folderName, type: 'folder', parentId: el.dataset.parentId || '' };
|
||||
}
|
||||
if (el.dataset.fileId) {
|
||||
return { id: el.dataset.fileId, name: el.dataset.fileName, type: 'file', parentId: el.dataset.folderId || '' };
|
||||
}
|
||||
return null;
|
||||
},
|
||||
|
||||
// ── Click handler (shared by grid + list) ───────────────
|
||||
|
||||
handleItemClick(el, event) {
|
||||
const items = this._getAllVisibleItems();
|
||||
const index = items.indexOf(el);
|
||||
const info = this._extractInfo(el);
|
||||
if (!info) return;
|
||||
|
||||
const selectorOther = info.type === 'folder'
|
||||
? `[data-folder-id="${info.id}"]`
|
||||
: `[data-file-id="${info.id}"]`;
|
||||
const otherEl = [...document.querySelectorAll(selectorOther)].find(e => e !== el);
|
||||
|
||||
if (event && event.shiftKey && this._lastClickedIndex >= 0 && index >= 0) {
|
||||
const start = Math.min(this._lastClickedIndex, index);
|
||||
const end = Math.max(this._lastClickedIndex, index);
|
||||
for (let i = start; i <= end; i++) {
|
||||
this._selectElement(items[i]);
|
||||
const iInfo = this._extractInfo(items[i]);
|
||||
if (iInfo) {
|
||||
const sel = iInfo.type === 'folder'
|
||||
? `[data-folder-id="${iInfo.id}"]`
|
||||
: `[data-file-id="${iInfo.id}"]`;
|
||||
document.querySelectorAll(sel).forEach(e => e.classList.add('selected'));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const nowSelected = this.toggle(info.id, info.name, info.type, info.parentId);
|
||||
el.classList.toggle('selected', nowSelected);
|
||||
if (otherEl) otherEl.classList.toggle('selected', nowSelected);
|
||||
}
|
||||
this._lastClickedIndex = index;
|
||||
this._syncUI();
|
||||
},
|
||||
|
||||
// ── Selection bar (replaces list-header when items selected) ────
|
||||
|
||||
/**
|
||||
* Build the inner HTML for the selection bar that replaces the
|
||||
* normal list-header columns (Name / Type / Size / Modified).
|
||||
*/
|
||||
_buildSelectionBarHTML(n) {
|
||||
const countText = n === 1
|
||||
? (this._t('batch.one_selected') || '1 item selected')
|
||||
: (this._t('batch.n_selected', { count: n }) || `${n} items selected`);
|
||||
|
||||
const favLabel = this._t('batch.add_favorites') || 'Add to favorites';
|
||||
const moveLabel = this._t('batch.move_copy') || 'Move or copy';
|
||||
const dlLabel = this._t('actions.download') || 'Download';
|
||||
const delLabel = this._t('actions.delete') || 'Delete';
|
||||
|
||||
return `
|
||||
<div class="list-header-checkbox">
|
||||
<input type="checkbox" id="select-all-checkbox" title="Toggle all" checked>
|
||||
</div>
|
||||
<div class="batch-selection-info">
|
||||
<span class="batch-bar-count">${countText}</span>
|
||||
<div class="batch-bar-actions">
|
||||
<button class="batch-btn" id="batch-fav" title="${favLabel}">
|
||||
<i class="fas fa-star"></i>
|
||||
<span>${favLabel}</span>
|
||||
</button>
|
||||
<button class="batch-btn" id="batch-move" title="${moveLabel}">
|
||||
<i class="fas fa-arrows-alt"></i>
|
||||
<span>${moveLabel}</span>
|
||||
</button>
|
||||
<button class="batch-btn" id="batch-download" title="${dlLabel}">
|
||||
<i class="fas fa-download"></i>
|
||||
<span>${dlLabel}</span>
|
||||
</button>
|
||||
<button class="batch-btn batch-btn-danger" id="batch-delete" title="${delLabel}">
|
||||
<i class="fas fa-trash-alt"></i>
|
||||
<span>${delLabel}</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
},
|
||||
|
||||
/** Ensure the grid-view batch bar exists (shown only when grid is visible) */
|
||||
_ensureGridBar() {
|
||||
if (document.getElementById('batch-grid-bar')) return;
|
||||
const bar = document.createElement('div');
|
||||
bar.id = 'batch-grid-bar';
|
||||
bar.className = 'batch-action-bar'; // reuse same styles
|
||||
const container = document.querySelector('.files-container');
|
||||
if (container) {
|
||||
container.insertBefore(bar, container.firstChild);
|
||||
}
|
||||
},
|
||||
|
||||
/** Main UI sync — called after every selection change */
|
||||
_syncUI() {
|
||||
const listHeader = document.querySelector('.list-header');
|
||||
const n = this._selected.size;
|
||||
|
||||
// ── Save original header HTML on first use ──
|
||||
if (listHeader && !this._savedHeaderHTML) {
|
||||
this._savedHeaderHTML = listHeader.innerHTML;
|
||||
}
|
||||
|
||||
if (n > 0) {
|
||||
this._barVisible = true;
|
||||
|
||||
// ── List view: replace header with selection bar ──
|
||||
if (listHeader) {
|
||||
listHeader.classList.add('selection-mode');
|
||||
listHeader.innerHTML = this._buildSelectionBarHTML(n);
|
||||
|
||||
// Wire checkbox
|
||||
const cb = document.getElementById('select-all-checkbox');
|
||||
if (cb) cb.addEventListener('change', () => this.toggleAll());
|
||||
|
||||
// Wire action buttons
|
||||
this._wireBarButtons();
|
||||
}
|
||||
|
||||
// ── Grid view: show floating bar ──
|
||||
this._ensureGridBar();
|
||||
const gridBar = document.getElementById('batch-grid-bar');
|
||||
if (gridBar) {
|
||||
const grid = document.getElementById('files-grid');
|
||||
const gridVisible = grid && grid.style.display !== 'none';
|
||||
if (gridVisible) {
|
||||
gridBar.classList.add('visible');
|
||||
gridBar.innerHTML = `
|
||||
<div class="batch-bar-left">
|
||||
<button class="batch-bar-close" id="batch-grid-close" title="Cancel selection">
|
||||
<i class="fas fa-times"></i>
|
||||
</button>
|
||||
<span class="batch-bar-count">${
|
||||
n === 1
|
||||
? (this._t('batch.one_selected') || '1 item selected')
|
||||
: (this._t('batch.n_selected', { count: n }) || `${n} items selected`)
|
||||
}</span>
|
||||
</div>
|
||||
<div class="batch-bar-actions">
|
||||
<button class="batch-btn" id="batch-fav" title="Add to favorites">
|
||||
<i class="fas fa-star"></i>
|
||||
<span>${this._t('batch.add_favorites') || 'Add to favorites'}</span>
|
||||
</button>
|
||||
<button class="batch-btn" id="batch-move" title="Move or copy">
|
||||
<i class="fas fa-arrows-alt"></i>
|
||||
<span>${this._t('batch.move_copy') || 'Move or copy'}</span>
|
||||
</button>
|
||||
<button class="batch-btn" id="batch-download" title="Download">
|
||||
<i class="fas fa-download"></i>
|
||||
<span>${this._t('actions.download') || 'Download'}</span>
|
||||
</button>
|
||||
<button class="batch-btn batch-btn-danger" id="batch-delete" title="Delete">
|
||||
<i class="fas fa-trash-alt"></i>
|
||||
<span>${this._t('actions.delete') || 'Delete'}</span>
|
||||
</button>
|
||||
</div>
|
||||
`;
|
||||
const closeBtn = document.getElementById('batch-grid-close');
|
||||
if (closeBtn) closeBtn.addEventListener('click', () => this.clear());
|
||||
this._wireBarButtons();
|
||||
} else {
|
||||
gridBar.classList.remove('visible');
|
||||
}
|
||||
}
|
||||
} else {
|
||||
this._barVisible = false;
|
||||
|
||||
// Restore original list header
|
||||
if (listHeader) {
|
||||
listHeader.classList.remove('selection-mode');
|
||||
if (this._savedHeaderHTML) {
|
||||
listHeader.innerHTML = this._savedHeaderHTML;
|
||||
}
|
||||
// Re-wire the select-all checkbox
|
||||
const cb = document.getElementById('select-all-checkbox');
|
||||
if (cb) cb.addEventListener('change', () => this.toggleAll());
|
||||
// Translate restored header (scoped to list header)
|
||||
if (window.i18n && window.i18n.translateElement) window.i18n.translateElement(listHeader);
|
||||
}
|
||||
|
||||
// Hide grid bar
|
||||
const gridBar = document.getElementById('batch-grid-bar');
|
||||
if (gridBar) gridBar.classList.remove('visible');
|
||||
}
|
||||
|
||||
// Sync individual item checkboxes
|
||||
this._syncItemCheckboxes();
|
||||
// Sync select-all checkbox state (for non-selection-mode)
|
||||
if (!this._barVisible) this._syncSelectAllCheckbox();
|
||||
},
|
||||
|
||||
/** Wire click handlers on batch action buttons (idempotent per render) */
|
||||
_wireBarButtons() {
|
||||
const del = document.getElementById('batch-delete');
|
||||
const move = document.getElementById('batch-move');
|
||||
const dl = document.getElementById('batch-download');
|
||||
const fav = document.getElementById('batch-fav');
|
||||
if (del) del.onclick = () => this.batchDelete();
|
||||
if (move) move.onclick = () => this.batchMove();
|
||||
if (dl) dl.onclick = () => this.batchDownload();
|
||||
if (fav) fav.onclick = () => this.batchFavorites();
|
||||
},
|
||||
|
||||
_syncItemCheckboxes() {
|
||||
document.querySelectorAll('.file-item').forEach(el => {
|
||||
const cb = el.querySelector('.item-checkbox');
|
||||
if (cb) cb.checked = el.classList.contains('selected');
|
||||
});
|
||||
},
|
||||
|
||||
_syncSelectAllCheckbox() {
|
||||
const cb = document.getElementById('select-all-checkbox');
|
||||
if (!cb) return;
|
||||
const all = this._getAllVisibleItems();
|
||||
if (all.length === 0) {
|
||||
cb.checked = false;
|
||||
cb.indeterminate = false;
|
||||
} else if (this._selected.size >= all.length) {
|
||||
cb.checked = true;
|
||||
cb.indeterminate = false;
|
||||
} else if (this._selected.size > 0) {
|
||||
cb.checked = false;
|
||||
cb.indeterminate = true;
|
||||
} else {
|
||||
cb.checked = false;
|
||||
cb.indeterminate = false;
|
||||
}
|
||||
},
|
||||
|
||||
// ── Batch operations ────────────────────────────────────
|
||||
|
||||
/** Batch delete (move to trash) */
|
||||
async batchDelete() {
|
||||
const items = this.items;
|
||||
if (items.length === 0) return;
|
||||
|
||||
const n = items.length;
|
||||
const msg = n === 1
|
||||
? (this._t('dialogs.confirm_delete_file', { name: items[0].name })
|
||||
|| `Are you sure you want to move "${items[0].name}" to trash?`)
|
||||
: (this._t('batch.confirm_delete', { count: n })
|
||||
|| `Are you sure you want to move ${n} items to trash?`);
|
||||
|
||||
const confirmed = await showConfirmDialog({
|
||||
title: this._t('dialogs.confirm_delete') || 'Move to trash',
|
||||
message: msg,
|
||||
confirmText: this._t('actions.delete') || 'Delete',
|
||||
});
|
||||
if (!confirmed) return;
|
||||
|
||||
const fileIds = items.filter(i => i.type === 'file').map(i => i.id);
|
||||
const folderIds = items.filter(i => i.type === 'folder').map(i => i.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 data = await response.json();
|
||||
const success = data.stats?.successful || 0;
|
||||
const errors = data.stats?.failed || 0;
|
||||
|
||||
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();
|
||||
}
|
||||
},
|
||||
|
||||
/** Batch move — reuse existing move dialog */
|
||||
async batchMove() {
|
||||
const items = this.items;
|
||||
if (items.length === 0) return;
|
||||
|
||||
window.app.moveDialogMode = 'batch';
|
||||
window.app.batchMoveItems = items;
|
||||
window.app.selectedTargetFolderId = "";
|
||||
|
||||
const dialog = document.getElementById('move-file-dialog');
|
||||
const dialogHeader = dialog.querySelector('.rename-dialog-header');
|
||||
const n = items.length;
|
||||
const titleText = this._t('batch.move_title', { count: n })
|
||||
|| `Move ${n} item${n !== 1 ? 's' : ''}`;
|
||||
dialogHeader.innerHTML = `<i class="fas fa-arrows-alt" style="color:#ff5e3a"></i> <span>${titleText}</span>`;
|
||||
|
||||
const excludeIds = items.filter(i => i.type === 'folder').map(i => i.id);
|
||||
await contextMenus.loadAllFolders(excludeIds[0] || null, 'batch');
|
||||
dialog.style.display = 'flex';
|
||||
},
|
||||
|
||||
/** Batch download — downloads all selected items as a single ZIP */
|
||||
async batchDownload() {
|
||||
const items = this.items;
|
||||
if (items.length === 0) return;
|
||||
|
||||
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');
|
||||
}
|
||||
},
|
||||
|
||||
/** Batch add to favorites — single API call */
|
||||
async batchFavorites() {
|
||||
const items = this.items;
|
||||
if (items.length === 0 || !window.favorites) return;
|
||||
|
||||
// Filter out items already in favourites
|
||||
const toAdd = items.filter(i => !window.favorites.isFavorite(i.id, i.type));
|
||||
if (toAdd.length === 0) {
|
||||
this.clear();
|
||||
window.ui.showNotification(
|
||||
this._t('favorites.add') || 'Favorites',
|
||||
'All selected items are already favorites'
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/favorites/batch', {
|
||||
method: 'POST',
|
||||
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
items: toAdd.map(i => ({ item_id: i.id, item_type: i.type }))
|
||||
})
|
||||
});
|
||||
|
||||
if (!response.ok) throw new Error(`Server returned ${response.status}`);
|
||||
|
||||
const data = await response.json();
|
||||
const inserted = data.stats?.inserted || 0;
|
||||
|
||||
// Replace cache directly from response (no extra GET)
|
||||
if (data.favorites && window.favorites._replaceCacheFromResponse) {
|
||||
window.favorites._replaceCacheFromResponse(data.favorites);
|
||||
} else {
|
||||
await window.favorites._fetchFromServer();
|
||||
}
|
||||
|
||||
this.clear();
|
||||
if (typeof window.loadFiles === 'function') window.loadFiles();
|
||||
|
||||
if (inserted > 0) {
|
||||
window.ui.showNotification(
|
||||
this._t('favorites.add') || 'Added to favorites',
|
||||
`${inserted} item${inserted !== 1 ? 's' : ''} added to favorites`
|
||||
);
|
||||
} else {
|
||||
window.ui.showNotification(
|
||||
this._t('favorites.add') || 'Favorites',
|
||||
'All selected items are already favorites'
|
||||
);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Batch favorites error:', e);
|
||||
window.ui.showNotification('Error', 'Could not add items to favorites');
|
||||
}
|
||||
},
|
||||
|
||||
// ── Initialization ──────────────────────────────────────
|
||||
|
||||
init() {
|
||||
// Wire the initial select-all checkbox
|
||||
this._injectListHeaderCheckbox();
|
||||
|
||||
// Global deselect on empty-area click
|
||||
this._hookGlobalDeselect();
|
||||
|
||||
// Keyboard shortcuts
|
||||
document.addEventListener('keydown', (e) => {
|
||||
if (e.target.closest('input, textarea, [contenteditable], .rename-dialog, .share-dialog, .confirm-dialog')) return;
|
||||
|
||||
if ((e.ctrlKey || e.metaKey) && e.key === 'a') {
|
||||
const grid = document.getElementById('files-grid');
|
||||
if (grid && grid.closest('.files-container')) {
|
||||
e.preventDefault();
|
||||
this.selectAll();
|
||||
}
|
||||
}
|
||||
if (e.key === 'Escape' && this.hasSelection) this.clear();
|
||||
if (e.key === 'Delete' && this.hasSelection) this.batchDelete();
|
||||
});
|
||||
},
|
||||
|
||||
_injectListHeaderCheckbox() {
|
||||
const cb = document.getElementById('select-all-checkbox');
|
||||
if (!cb) return;
|
||||
cb.addEventListener('change', () => this.toggleAll());
|
||||
},
|
||||
|
||||
_hookGlobalDeselect() {
|
||||
document.addEventListener('click', (e) => {
|
||||
if (e.target.closest('.file-card, .file-item, .context-menu, .batch-action-bar, .list-header.selection-mode, .about-modal, .rename-dialog, .share-dialog, .confirm-dialog, .modal-overlay, input, button')) return;
|
||||
if (this.hasSelection) this.clear();
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Expose globally
|
||||
window.multiSelect = multiSelect;
|
||||
@@ -0,0 +1,223 @@
|
||||
/**
|
||||
* 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 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>} - Enriched search results from backend
|
||||
*/
|
||||
async searchFiles(query, options = {}) {
|
||||
try {
|
||||
const params = new URLSearchParams();
|
||||
params.append('query', query);
|
||||
|
||||
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);
|
||||
if (options.min_size) params.append('min_size', options.min_size);
|
||||
if (options.max_size) params.append('max_size', options.max_size);
|
||||
if (options.created_after) params.append('created_after', options.created_after);
|
||||
if (options.created_before) params.append('created_before', options.created_before);
|
||||
if (options.modified_after) params.append('modified_after', options.modified_after);
|
||||
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);
|
||||
|
||||
const url = `/api/search?${params.toString()}`;
|
||||
console.log(`[search] GET ${url}`);
|
||||
|
||||
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(`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, query_time_ms: 0, sort_by: 'relevance' };
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* 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 getSuggestions(query, options = {}) {
|
||||
try {
|
||||
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 {
|
||||
return { suggestions: [], query_time_ms: 0 };
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error getting suggestions:', error);
|
||||
return { suggestions: [], query_time_ms: 0 };
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* 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) {
|
||||
const filesGrid = document.getElementById('files-grid');
|
||||
const filesListView = document.getElementById('files-list-view');
|
||||
|
||||
filesGrid.innerHTML = '';
|
||||
filesListView.innerHTML = `
|
||||
<div class="list-header">
|
||||
<div class="list-header-checkbox"><input type="checkbox" id="select-all-checkbox" title="Select all"></div>
|
||||
<div data-i18n="files.name">Name</div>
|
||||
<div data-i18n="files.type">Type</div>
|
||||
<div data-i18n="files.size">Size</div>
|
||||
<div data-i18n="files.modified">Modified</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
// 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 (${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);
|
||||
|
||||
// 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', () => {
|
||||
document.querySelector('.search-container input').value = '';
|
||||
window.app.currentPath = '';
|
||||
window.app.isSearchMode = false;
|
||||
window.ui.updateBreadcrumb('');
|
||||
window.loadFiles();
|
||||
});
|
||||
}
|
||||
|
||||
// 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: 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;
|
||||
}
|
||||
|
||||
// Render folders (server-provided enriched data)
|
||||
results.folders.forEach(folder => {
|
||||
window.ui.addFolderToView(folder);
|
||||
});
|
||||
|
||||
// Render files (server-provided enriched data)
|
||||
results.files.forEach(file => {
|
||||
window.ui.addFileToView(file);
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Clear the search cache on the server
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
async clearSearchCache() {
|
||||
try {
|
||||
const response = await fetch('/api/search/cache', {
|
||||
method: 'DELETE',
|
||||
headers: getAuthHeaders()
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
window.ui.showNotification('Cache cleared', 'Search cache cleared successfully');
|
||||
return true;
|
||||
} else {
|
||||
window.ui.showNotification('Error', 'Error clearing search cache');
|
||||
return false;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error clearing search cache:', error);
|
||||
window.ui.showNotification('Error', 'Error clearing search cache');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Expose the search module globally
|
||||
window.search = search;
|
||||
@@ -0,0 +1,238 @@
|
||||
/**
|
||||
* OxiCloud - Favorites Module (server-authoritative)
|
||||
*
|
||||
* Source of truth: GET /api/favorites (enriched with name/size/mime via SQL JOIN).
|
||||
* Local in-memory cache (`_cache`) keeps `isFavorite()` synchronous for the
|
||||
* rendering path so star icons can be painted without a round-trip.
|
||||
*/
|
||||
|
||||
const favorites = {
|
||||
/** @type {Map<string, object>} key = "file:<id>" | "folder:<id>" */
|
||||
_cache: new Map(),
|
||||
|
||||
/** Whether the initial fetch from the server has completed */
|
||||
_ready: false,
|
||||
|
||||
// ───────────────────── helpers ─────────────────────
|
||||
|
||||
_authHeaders() {
|
||||
const token = localStorage.getItem('oxicloud_token');
|
||||
const h = {};
|
||||
if (token) h['Authorization'] = `Bearer ${token}`;
|
||||
return h;
|
||||
},
|
||||
|
||||
_cacheKey(id, type) {
|
||||
return `${type}:${id}`;
|
||||
},
|
||||
|
||||
/**
|
||||
* Replace the entire in-memory cache from an array of FavoriteItemDto
|
||||
* objects (as returned by the batch endpoint). Avoids an extra
|
||||
* GET /api/favorites round-trip.
|
||||
*/
|
||||
_replaceCacheFromResponse(items) {
|
||||
this._cache.clear();
|
||||
for (const item of items) {
|
||||
this._cache.set(this._cacheKey(item.item_id, item.item_type), item);
|
||||
}
|
||||
this._ready = true;
|
||||
console.log(`Favorites cache replaced from response: ${this._cache.size} items`);
|
||||
},
|
||||
|
||||
// ───────────────────── lifecycle ─────────────────────
|
||||
|
||||
/**
|
||||
* Initialise the module: fetch the full list from the server and populate
|
||||
* the in-memory cache. Called once from app.js on startup.
|
||||
*/
|
||||
async init() {
|
||||
console.log('Initializing favorites module (server-authoritative)');
|
||||
await this._fetchFromServer();
|
||||
},
|
||||
|
||||
/**
|
||||
* Fetch favourites from the backend and rebuild the cache.
|
||||
*/
|
||||
async _fetchFromServer() {
|
||||
try {
|
||||
const response = await fetch('/api/favorites', {
|
||||
headers: this._authHeaders()
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
console.warn(`Favorites API returned ${response.status}`);
|
||||
this._ready = true;
|
||||
return;
|
||||
}
|
||||
|
||||
const items = await response.json();
|
||||
this._cache.clear();
|
||||
for (const item of items) {
|
||||
this._cache.set(this._cacheKey(item.item_id, item.item_type), item);
|
||||
}
|
||||
|
||||
this._ready = true;
|
||||
console.log(`Favorites cache loaded: ${this._cache.size} items`);
|
||||
} catch (err) {
|
||||
console.error('Error fetching favorites:', err);
|
||||
this._ready = true;
|
||||
}
|
||||
},
|
||||
|
||||
// ───────────────────── public API ─────────────────────
|
||||
|
||||
/**
|
||||
* Synchronous check used by ui.js to paint star icons.
|
||||
*/
|
||||
isFavorite(id, type) {
|
||||
return this._cache.has(this._cacheKey(id, type));
|
||||
},
|
||||
|
||||
/**
|
||||
* Add an item to favourites (server-first).
|
||||
*/
|
||||
async addToFavorites(id, name, type, _parentId) {
|
||||
try {
|
||||
const response = await fetch(`/api/favorites/${type}/${id}`, {
|
||||
method: 'POST',
|
||||
headers: this._authHeaders()
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Server returned ${response.status}`);
|
||||
}
|
||||
|
||||
// Refresh cache from server to get enriched data
|
||||
await this._fetchFromServer();
|
||||
|
||||
// Notify user
|
||||
if (window.ui && window.ui.showNotification) {
|
||||
window.ui.showNotification(
|
||||
window.i18n ? window.i18n.t('favorites.added_title') : 'Added to favorites',
|
||||
`"${name}" ${window.i18n ? window.i18n.t('favorites.added_msg') : 'added to favorites'}`
|
||||
);
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Error adding to favorites:', error);
|
||||
return false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Remove an item from favourites (server-first).
|
||||
*/
|
||||
async removeFromFavorites(id, type) {
|
||||
try {
|
||||
// Remember name for notification before removing from cache
|
||||
const cached = this._cache.get(this._cacheKey(id, type));
|
||||
const itemName = cached?.item_name || id;
|
||||
|
||||
const response = await fetch(`/api/favorites/${type}/${id}`, {
|
||||
method: 'DELETE',
|
||||
headers: this._authHeaders()
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Server returned ${response.status}`);
|
||||
}
|
||||
|
||||
// Remove from local cache
|
||||
this._cache.delete(this._cacheKey(id, type));
|
||||
|
||||
if (window.ui && window.ui.showNotification) {
|
||||
window.ui.showNotification(
|
||||
window.i18n ? window.i18n.t('favorites.removed_title') : 'Removed from favorites',
|
||||
`"${itemName}" ${window.i18n ? window.i18n.t('favorites.removed_msg') : 'removed from favorites'}`
|
||||
);
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Error removing from favorites:', error);
|
||||
return false;
|
||||
}
|
||||
},
|
||||
|
||||
// ───────────────────── display ─────────────────────
|
||||
|
||||
/**
|
||||
* Render the favourites view. All data comes from the in-memory cache
|
||||
* (which was populated from the enriched backend response — zero extra
|
||||
* fetches).
|
||||
*/
|
||||
async displayFavorites() {
|
||||
try {
|
||||
// Ensure cache is fresh
|
||||
if (!this._ready) {
|
||||
await this._fetchFromServer();
|
||||
}
|
||||
|
||||
const filesGrid = document.getElementById('files-grid');
|
||||
const filesListView = document.getElementById('files-list-view');
|
||||
|
||||
filesGrid.innerHTML = '';
|
||||
filesListView.innerHTML = `
|
||||
<div class="list-header">
|
||||
<div class="list-header-checkbox"><input type="checkbox" id="select-all-checkbox" title="Select all"></div>
|
||||
<div data-i18n="files.name">Name</div>
|
||||
<div data-i18n="files.type">Type</div>
|
||||
<div data-i18n="files.size">Size</div>
|
||||
<div data-i18n="files.modified">Modified</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
window.ui.updateBreadcrumb('');
|
||||
|
||||
if (this._cache.size === 0) {
|
||||
const emptyState = document.createElement('div');
|
||||
emptyState.className = 'empty-state';
|
||||
emptyState.innerHTML = `
|
||||
<i class="fas fa-star" style="font-size: 48px; color: #ddd; margin-bottom: 16px;"></i>
|
||||
<p>${window.i18n ? window.i18n.t('favorites.empty_state') : 'No favorite items'}</p>
|
||||
<p>${window.i18n ? window.i18n.t('favorites.empty_hint') : 'To mark as favorite, right-click on any file or folder'}</p>
|
||||
`;
|
||||
filesGrid.appendChild(emptyState);
|
||||
return;
|
||||
}
|
||||
|
||||
const folders = [];
|
||||
const files = [];
|
||||
for (const item of this._cache.values()) {
|
||||
if (item.item_type === 'folder') {
|
||||
folders.push({
|
||||
id: item.item_id,
|
||||
name: item.item_name || item.item_id,
|
||||
parent_id: item.parent_id || '',
|
||||
modified_at: item.modified_at || item.created_at
|
||||
});
|
||||
} else {
|
||||
files.push({
|
||||
id: item.item_id,
|
||||
name: item.item_name || item.item_id,
|
||||
folder_id: item.parent_id || '',
|
||||
mime_type: item.item_mime_type,
|
||||
icon_class: item.icon_class,
|
||||
icon_special_class: item.icon_special_class,
|
||||
category: item.category,
|
||||
size: item.item_size || 0,
|
||||
size_formatted: item.size_formatted,
|
||||
modified_at: item.modified_at || item.created_at
|
||||
});
|
||||
}
|
||||
}
|
||||
if (folders.length) window.ui.renderFolders(folders);
|
||||
if (files.length) window.ui.renderFiles(files);
|
||||
} catch (error) {
|
||||
console.error('Error displaying favorites:', error);
|
||||
if (window.ui && window.ui.showNotification) {
|
||||
window.ui.showNotification('Error', 'Error loading favorite items');
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Expose globally
|
||||
window.favorites = favorites;
|
||||
@@ -0,0 +1,158 @@
|
||||
/**
|
||||
* OxiCloud - Recent Files Module (server-authoritative)
|
||||
*
|
||||
* Source of truth: GET /api/recent (enriched with name/size/mime via SQL JOIN).
|
||||
* File-access events are forwarded to the backend with POST /api/recent/{type}/{id}.
|
||||
* No localStorage usage — the server persists and prunes recent items.
|
||||
*/
|
||||
|
||||
const recent = {
|
||||
/** Maximum items to request from the server */
|
||||
MAX_RECENT_FILES: 20,
|
||||
|
||||
// ───────────────────── helpers ─────────────────────
|
||||
|
||||
_authHeaders() {
|
||||
const token = localStorage.getItem('oxicloud_token');
|
||||
const h = {};
|
||||
if (token) h['Authorization'] = `Bearer ${token}`;
|
||||
return h;
|
||||
},
|
||||
|
||||
// ───────────────────── lifecycle ─────────────────────
|
||||
|
||||
/**
|
||||
* Initialise the module. Called once from app.js on startup.
|
||||
*/
|
||||
init() {
|
||||
console.log('Initializing recent files module (server-authoritative)');
|
||||
this.setupEventListeners();
|
||||
},
|
||||
|
||||
/**
|
||||
* Listen for file-accessed events dispatched by ui.js and forward
|
||||
* them to the backend.
|
||||
*/
|
||||
setupEventListeners() {
|
||||
document.addEventListener('file-accessed', (event) => {
|
||||
if (event.detail && event.detail.file) {
|
||||
const file = event.detail.file;
|
||||
const itemType = file.item_type || 'file';
|
||||
this._recordAccess(file.id, itemType);
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Record an access event on the server.
|
||||
*/
|
||||
async _recordAccess(itemId, itemType) {
|
||||
try {
|
||||
await fetch(`/api/recent/${itemType}/${itemId}`, {
|
||||
method: 'POST',
|
||||
headers: this._authHeaders()
|
||||
});
|
||||
} catch (err) {
|
||||
console.warn('Failed to record recent access:', err);
|
||||
}
|
||||
},
|
||||
|
||||
// ───────────────────── public API ─────────────────────
|
||||
|
||||
/**
|
||||
* Clear all recent items (delegates to the server).
|
||||
*/
|
||||
async clearRecentFiles() {
|
||||
try {
|
||||
await fetch('/api/recent/clear', {
|
||||
method: 'DELETE',
|
||||
headers: this._authHeaders()
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Error clearing recent files:', err);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Fetch and display recent files. Data comes directly from the
|
||||
* enriched backend response — zero extra per-item fetches.
|
||||
*/
|
||||
async displayRecentFiles() {
|
||||
try {
|
||||
const response = await fetch(`/api/recent?limit=${this.MAX_RECENT_FILES}`, {
|
||||
headers: this._authHeaders()
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Server returned ${response.status}`);
|
||||
}
|
||||
|
||||
const recentItems = await response.json();
|
||||
|
||||
const filesGrid = document.getElementById('files-grid');
|
||||
const filesListView = document.getElementById('files-list-view');
|
||||
|
||||
filesGrid.innerHTML = '';
|
||||
filesListView.innerHTML = `
|
||||
<div class="list-header">
|
||||
<div class="list-header-checkbox"><input type="checkbox" id="select-all-checkbox" title="Select all"></div>
|
||||
<div data-i18n="files.name">Name</div>
|
||||
<div data-i18n="files.type">Type</div>
|
||||
<div data-i18n="files.size">Size</div>
|
||||
<div data-i18n="recent.accessed">Accessed</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
window.ui.updateBreadcrumb('');
|
||||
|
||||
if (recentItems.length === 0) {
|
||||
const emptyState = document.createElement('div');
|
||||
emptyState.className = 'empty-state';
|
||||
emptyState.innerHTML = `
|
||||
<i class="fas fa-clock" style="font-size: 48px; color: #ddd; margin-bottom: 16px;"></i>
|
||||
<p>${window.i18n ? window.i18n.t('recent.empty_state') : 'No recent files'}</p>
|
||||
<p>${window.i18n ? window.i18n.t('recent.empty_hint') : 'Files you open will appear here'}</p>
|
||||
`;
|
||||
filesGrid.appendChild(emptyState);
|
||||
return;
|
||||
}
|
||||
|
||||
const folders = [];
|
||||
const files = [];
|
||||
for (const item of recentItems) {
|
||||
const isFolder = item.item_type === 'folder';
|
||||
if (isFolder) {
|
||||
folders.push({
|
||||
id: item.item_id,
|
||||
name: item.item_name || item.item_id,
|
||||
parent_id: item.parent_id || '',
|
||||
modified_at: item.accessed_at
|
||||
});
|
||||
} else {
|
||||
files.push({
|
||||
id: item.item_id,
|
||||
name: item.item_name || item.item_id,
|
||||
folder_id: item.parent_id || '',
|
||||
mime_type: item.item_mime_type,
|
||||
icon_class: item.icon_class,
|
||||
icon_special_class: item.icon_special_class,
|
||||
category: item.category,
|
||||
size: item.item_size || 0,
|
||||
size_formatted: item.size_formatted,
|
||||
modified_at: item.accessed_at
|
||||
});
|
||||
}
|
||||
}
|
||||
if (folders.length) window.ui.renderFolders(folders);
|
||||
if (files.length) window.ui.renderFiles(files);
|
||||
} catch (error) {
|
||||
console.error('Error displaying recent files:', error);
|
||||
if (window.ui && window.ui.showNotification) {
|
||||
window.ui.showNotification('Error', 'Error loading recent files');
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Expose globally
|
||||
window.recent = recent;
|
||||
@@ -0,0 +1,209 @@
|
||||
/**
|
||||
* OxiCloud - File Sharing Module
|
||||
* All operations go through the backend API at /api/shares.
|
||||
* No localStorage is used for share data.
|
||||
*/
|
||||
|
||||
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;
|
||||
},
|
||||
|
||||
/**
|
||||
* Create a shared link via backend API
|
||||
* @param {string} itemId - ID of the file or folder
|
||||
* @param {string} itemType - 'file' or 'folder'
|
||||
* @param {Object} options - { name, password, expirationDate, permissions }
|
||||
* @returns {Promise<Object>} ShareDto from backend
|
||||
*/
|
||||
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();
|
||||
},
|
||||
|
||||
/**
|
||||
* Get all shared links for the current user
|
||||
* @returns {Promise<Array>} Array of ShareDto
|
||||
*/
|
||||
async getSharedLinks() {
|
||||
try {
|
||||
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 fetching shared links:', error);
|
||||
return [];
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Get shared links for a specific item (server-side filtered)
|
||||
* @param {string} itemId
|
||||
* @param {string} itemType - 'file' or 'folder'
|
||||
* @returns {Promise<Array>} Shares for this item
|
||||
*/
|
||||
async getSharedLinksForItem(itemId, itemType) {
|
||||
try {
|
||||
const params = new URLSearchParams({ item_id: itemId, item_type: itemType });
|
||||
const res = await fetch(`/api/shares?${params}`, {
|
||||
headers: this._headers(false)
|
||||
});
|
||||
if (!res.ok) return [];
|
||||
const data = await res.json();
|
||||
return Array.isArray(data) ? data : (data.items || []);
|
||||
} catch (error) {
|
||||
console.error('Error getting shared links for item:', error);
|
||||
return [];
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Check if an item has any shared links
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
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
|
||||
*/
|
||||
async copyLinkToClipboard(url) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(url);
|
||||
window.ui.showNotification('Link copied', 'Link copied to clipboard');
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Error copying to clipboard:', error);
|
||||
window.ui.showNotification('Error', 'Could not copy link');
|
||||
return false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Format expiration date for display (Unix timestamp in seconds or ISO string)
|
||||
* @param {number|string} value
|
||||
* @returns {string}
|
||||
*/
|
||||
formatExpirationDate(value) {
|
||||
if (!value) return 'No expiration';
|
||||
return window.formatDateTime(value);
|
||||
},
|
||||
|
||||
/**
|
||||
* Send a notification about a shared resource (stub — no backend endpoint yet)
|
||||
* @param {string} shareUrl
|
||||
* @param {string} recipientEmail
|
||||
* @param {string} message
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
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;
|
||||
},
|
||||
|
||||
/**
|
||||
* Initialize file sharing event listeners
|
||||
*/
|
||||
init() {
|
||||
console.log('File sharing module initialized (API-backed)');
|
||||
document.querySelectorAll('.nav-item').forEach(item => {
|
||||
const span = item.querySelector('span');
|
||||
if (span && span.getAttribute('data-i18n') === 'nav.shared') {
|
||||
item.addEventListener('click', () => {
|
||||
if (window.switchToSharedView) {
|
||||
window.switchToSharedView();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Expose 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);
|
||||
Reference in New Issue
Block a user