`;
// Add action buttons event listeners for list view
listElement.querySelector('.btn-restore').addEventListener('click', async (e) => {
e.stopPropagation();
if (await fileOps.restoreFromTrash(item.id)) {
loadTrashItems();
}
});
listElement.querySelector('.btn-delete').addEventListener('click', async (e) => {
e.stopPropagation();
if (await fileOps.deletePermanently(item.id)) {
loadTrashItems();
}
});
elements.filesListView.appendChild(listElement);
}
/**
* Perform search with the given query
* @param {string} query - Search query
*/
async function performSearch(query) {
console.log(`Performing search for: "${query}"`);
try {
// Update UI to indicate search mode
app.isSearchMode = true;
// Set breadcrumb for search
ui.updateBreadcrumb(`Búsqueda: "${query}"`);
// Prepare search options
const options = {
recursive: true, // Search in all subfolders
limit: 100 // Limit results for performance
};
// Always restrict search to the user's current folder context
// This ensures users can't search outside their personal folder
if (!app.isTrashView) {
// If we're in a subfolder, search from there, otherwise use the user's home folder
options.folder_id = app.currentPath;
// Always include folder_id even if it's the root of user's home folder
// so user cannot search outside their allowed scope
if (!options.folder_id || options.folder_id === '') {
// Fall back to user's home folder - we should never be here
// because findUserHomeFolder should have set app.currentPath
console.warn("Search without folder_id - this shouldn't happen with proper user context");
// Try to get folder from localStorage if available
const USER_DATA_KEY = 'oxicloud_user';
const userData = JSON.parse(localStorage.getItem(USER_DATA_KEY) || '{}');
if (userData.username) {
console.log("Retrieving home folder for user before search");
await findUserHomeFolder(userData.username);
options.folder_id = app.currentPath;
}
}
}
console.log(`Searching with options:`, options);
// Perform the search
const searchResults = await window.search.searchFiles(query, options);
// Display search results
window.search.displaySearchResults(searchResults);
} catch (error) {
console.error('Search error:', error);
window.ui.showNotification('Error', 'Error al realizar la búsqueda');
}
}
// Expose needed functions to global scope
window.app = app;
window.loadFiles = loadFiles;
window.loadTrashItems = loadTrashItems;
window.formatFileSize = formatFileSize;
window.performSearch = performSearch;
// Set up global selectFolder function for navigation
window.selectFolder = (id, name) => {
app.currentPath = id;
ui.updateBreadcrumb(name);
loadFiles();
};
/**
* Check if user is authenticated and load user's home folder
*/
function checkAuthentication() {
// Nombres de variables según auth.js
const TOKEN_KEY = 'oxicloud_token';
const TOKEN_EXPIRY_KEY = 'oxicloud_token_expiry';
const USER_DATA_KEY = 'oxicloud_user';
const token = localStorage.getItem(TOKEN_KEY);
const tokenExpiry = localStorage.getItem(TOKEN_EXPIRY_KEY);
if (!token || !tokenExpiry || new Date(tokenExpiry) < new Date()) {
// No token or expired token
window.location.href = '/login';
return;
}
// Display user information if available
const userData = JSON.parse(localStorage.getItem(USER_DATA_KEY) || '{}');
if (userData.username) {
// Update user avatar with initials
const userInitials = userData.username.substring(0, 2).toUpperCase();
const userAvatar = document.querySelector('.user-avatar');
if (userAvatar) {
userAvatar.textContent = userInitials;
}
// Find and load the user's home folder
findUserHomeFolder(userData.username);
} else {
// If no user data, fallback to standard load
app.currentPath = '';
ui.updateBreadcrumb('');
loadFiles();
}
}
/**
* Find the user's home folder and load it
* @param {string} username - The current user's username
*/
async function findUserHomeFolder(username) {
try {
console.log("Finding home folder for user:", username);
// First, load all folders at the root
const response = await fetch('/api/folders');
if (!response.ok) {
throw new Error(`Error loading folders: ${response.status}`);
}
const folders = await response.json();
const folderList = Array.isArray(folders) ? folders : [];
// Look for a folder with a name pattern that matches the user's home folder
// Typically named "Mi Carpeta - username"
const homeFolderPattern = `Mi Carpeta - ${username}`;
let homeFolder = folderList.find(folder => folder.name === homeFolderPattern);
// If exact match not found, try a more flexible match
if (!homeFolder) {
homeFolder = folderList.find(folder =>
folder.name.toLowerCase().includes(username.toLowerCase()) ||
folder.name.startsWith('Mi Carpeta -')
);
}
if (homeFolder) {
console.log(`Found user's home folder: ${homeFolder.name} (${homeFolder.id})`);
// Store the home folder ID and name in the app state
// This is used for breadcrumb navigation and restricting user access
app.userHomeFolderId = homeFolder.id;
app.userHomeFolderName = homeFolder.name;
// Set this as the current path and load its contents
app.currentPath = homeFolder.id;
ui.updateBreadcrumb(homeFolder.name);
loadFiles();
} else {
console.warn("Could not find user's home folder, fallback to first folder or root");
// If we can't find a specific home folder but there are folders,
// use the first folder as the user's home
if (folderList.length > 0) {
const fallbackFolder = folderList[0];
console.log(`Using first folder as fallback: ${fallbackFolder.name} (${fallbackFolder.id})`);
app.userHomeFolderId = fallbackFolder.id;
app.userHomeFolderName = fallbackFolder.name;
app.currentPath = fallbackFolder.id;
ui.updateBreadcrumb(fallbackFolder.name);
loadFiles();
} else {
// No folders at all - this is an edge case
console.warn("No folders found, using root");
app.currentPath = '';
ui.updateBreadcrumb('');
loadFiles();
}
}
} catch (error) {
console.error('Error finding user home folder:', error);
// Fall back to loading root in case of error
app.currentPath = '';
ui.updateBreadcrumb('');
loadFiles();
}
}
/**
* Logout - clear all auth data and redirect to login
*/
function logout() {
// Nombres de variables según auth.js
const TOKEN_KEY = 'oxicloud_token';
const REFRESH_TOKEN_KEY = 'oxicloud_refresh_token';
const TOKEN_EXPIRY_KEY = 'oxicloud_token_expiry';
const USER_DATA_KEY = 'oxicloud_user';
// Clear all authentication data
localStorage.removeItem(TOKEN_KEY);
localStorage.removeItem(REFRESH_TOKEN_KEY);
localStorage.removeItem(TOKEN_EXPIRY_KEY);
localStorage.removeItem(USER_DATA_KEY);
// Redirect to login page
window.location.href = '/login';
}
// Initialize app when DOM is ready
document.addEventListener('DOMContentLoaded', initApp);