adding ui sharing

This commit is contained in:
DioCrafts
2025-03-28 08:09:18 +01:00
parent f9955bb710
commit fb276d9b24
18 changed files with 2452 additions and 295 deletions
+22 -2
View File
@@ -15,6 +15,10 @@ const app = {
isTrashView: false, // Whether we're in trash view
currentSection: 'files', // Current section: 'files' or 'trash'
isSearchMode: false, // Whether we're in search mode
// File sharing related properties
shareDialogItem: null, // Item being shared in share dialog
shareDialogItemType: null, // Type of item being shared ('file' or 'folder')
notificationShareUrl: null // URL for notification dialog
};
// DOM elements
@@ -29,8 +33,17 @@ function initApp() {
// Cache DOM elements
cacheElements();
// Create menus and dialogs
ui.initializeContextMenus();
// Initialize file sharing module first
if (window.fileSharing && window.fileSharing.init) {
window.fileSharing.init();
} else {
console.warn('fileSharing module not fully initialized');
}
// Then create menus and dialogs after modules have initialized
setTimeout(() => {
ui.initializeContextMenus();
}, 100);
// Setup event listeners
setupEventListeners();
@@ -152,6 +165,13 @@ function setupEventListeners() {
// Add active class to clicked item
item.classList.add('active');
// Check if this is the shared item
if (item.querySelector('span').getAttribute('data-i18n') === 'nav.shared') {
// Navigate to the shared page
window.location.href = '/shared.html';
return;
}
// Check if this is the trash item
if (item === elements.trashBtn) {
// Show trash view
+81 -42
View File
@@ -17,46 +17,78 @@ const TOKEN_EXPIRY_KEY = 'oxicloud_token_expiry';
const USER_DATA_KEY = 'oxicloud_user';
// DOM elements
const loginPanel = document.getElementById('login-panel');
const registerPanel = document.getElementById('register-panel');
const adminSetupPanel = document.getElementById('admin-setup-panel');
let loginPanel, registerPanel, adminSetupPanel;
let loginForm, registerForm, adminSetupForm;
let loginError, registerError, registerSuccess, adminSetupError;
const loginForm = document.getElementById('login-form');
const registerForm = document.getElementById('register-form');
const adminSetupForm = document.getElementById('admin-setup-form');
// Initialize DOM elements only if we're on the login page
function initLoginElements() {
// Check if we're on the login page
if (!document.getElementById('login-form')) {
console.log('Not on login page, skipping element initialization');
return false;
}
loginPanel = document.getElementById('login-panel');
registerPanel = document.getElementById('register-panel');
adminSetupPanel = document.getElementById('admin-setup-panel');
const loginError = document.getElementById('login-error');
const registerError = document.getElementById('register-error');
const registerSuccess = document.getElementById('register-success');
const adminSetupError = document.getElementById('admin-setup-error');
loginForm = document.getElementById('login-form');
registerForm = document.getElementById('register-form');
adminSetupForm = document.getElementById('admin-setup-form');
// Panel toggles
document.getElementById('show-register').addEventListener('click', () => {
loginPanel.style.display = 'none';
registerPanel.style.display = 'block';
adminSetupPanel.style.display = 'none';
});
loginError = document.getElementById('login-error');
registerError = document.getElementById('register-error');
registerSuccess = document.getElementById('register-success');
adminSetupError = document.getElementById('admin-setup-error');
document.getElementById('show-login').addEventListener('click', () => {
loginPanel.style.display = 'block';
registerPanel.style.display = 'none';
adminSetupPanel.style.display = 'none';
});
// Panel toggles
document.getElementById('show-register').addEventListener('click', () => {
loginPanel.style.display = 'none';
registerPanel.style.display = 'block';
adminSetupPanel.style.display = 'none';
});
document.getElementById('show-admin-setup').addEventListener('click', () => {
loginPanel.style.display = 'none';
registerPanel.style.display = 'none';
adminSetupPanel.style.display = 'block';
});
document.getElementById('show-login').addEventListener('click', () => {
loginPanel.style.display = 'block';
registerPanel.style.display = 'none';
adminSetupPanel.style.display = 'none';
});
document.getElementById('back-to-login').addEventListener('click', () => {
loginPanel.style.display = 'block';
registerPanel.style.display = 'none';
adminSetupPanel.style.display = 'none';
});
document.getElementById('show-admin-setup').addEventListener('click', () => {
loginPanel.style.display = 'none';
registerPanel.style.display = 'none';
adminSetupPanel.style.display = 'block';
});
document.getElementById('back-to-login').addEventListener('click', () => {
loginPanel.style.display = 'block';
registerPanel.style.display = 'none';
adminSetupPanel.style.display = 'none';
});
return true;
}
// Initialize login elements if on login page
const isLoginPage = initLoginElements();
// Check if we already have a valid token
document.addEventListener('DOMContentLoaded', async () => {
let authInitialized = false;
document.addEventListener('DOMContentLoaded', () => {
// Check if we're on the login page
if (!document.getElementById('login-form')) {
console.log('Not on login page, skipping auth check');
return;
}
if (authInitialized) {
console.log('Auth already initialized, skipping');
return;
}
authInitialized = true;
(async () => {
try {
const tokenExpiry = localStorage.getItem(TOKEN_EXPIRY_KEY);
if (tokenExpiry && new Date(tokenExpiry) > new Date()) {
@@ -87,17 +119,19 @@ document.addEventListener('DOMContentLoaded', async () => {
} catch (error) {
console.error('Authentication check failed:', error);
}
})();
});
// Login form submission
loginForm.addEventListener('submit', async (e) => {
e.preventDefault();
// Clear previous errors
loginError.style.display = 'none';
const username = document.getElementById('login-username').value;
const password = document.getElementById('login-password').value;
if (isLoginPage && loginForm) {
loginForm.addEventListener('submit', async (e) => {
e.preventDefault();
// Clear previous errors
loginError.style.display = 'none';
const username = document.getElementById('login-username').value;
const password = document.getElementById('login-password').value;
try {
const data = await login(username, password);
@@ -161,9 +195,11 @@ loginForm.addEventListener('submit', async (e) => {
loginError.style.display = 'block';
}
});
}
// Register form submission
registerForm.addEventListener('submit', async (e) => {
if (isLoginPage && registerForm) {
registerForm.addEventListener('submit', async (e) => {
e.preventDefault();
// Clear previous messages
@@ -202,9 +238,11 @@ registerForm.addEventListener('submit', async (e) => {
registerError.style.display = 'block';
}
});
}
// Admin setup form submission
adminSetupForm.addEventListener('submit', async (e) => {
if (isLoginPage && adminSetupForm) {
adminSetupForm.addEventListener('submit', async (e) => {
e.preventDefault();
// Clear previous errors
@@ -235,6 +273,7 @@ adminSetupForm.addEventListener('submit', async (e) => {
adminSetupError.style.display = 'block';
}
});
}
// API Functions
+234
View File
@@ -23,6 +23,13 @@ const contextMenus = {
}
window.ui.closeContextMenu();
});
document.getElementById('share-folder-option').addEventListener('click', () => {
if (window.app.contextMenuTargetFolder) {
this.showShareDialog(window.app.contextMenuTargetFolder, 'folder');
}
window.ui.closeContextMenu();
});
document.getElementById('delete-folder-option').addEventListener('click', async () => {
if (window.app.contextMenuTargetFolder) {
@@ -42,6 +49,13 @@ const contextMenus = {
window.ui.closeFileContextMenu();
});
document.getElementById('share-file-option').addEventListener('click', () => {
if (window.app.contextMenuTargetFile) {
this.showShareDialog(window.app.contextMenuTargetFile, 'file');
}
window.ui.closeFileContextMenu();
});
document.getElementById('delete-file-option').addEventListener('click', async () => {
if (window.app.contextMenuTargetFile) {
await window.fileOps.deleteFile(
@@ -249,6 +263,226 @@ const contextMenus = {
} 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'
*/
showShareDialog(item, itemType) {
// Update dialog title based on item type
const dialogHeader = document.getElementById('share-dialog').querySelector('.share-dialog-header');
const itemName = document.getElementById('shared-item-name');
// Update dialog content
dialogHeader.textContent = itemType === 'file' ?
(window.i18n ? window.i18n.t('dialogs.share_file') : 'Compartir archivo') :
(window.i18n ? window.i18n.t('dialogs.share_folder') : 'Compartir carpeta');
itemName.textContent = item.name;
// Reset form
document.getElementById('share-password').value = '';
document.getElementById('share-expiration').value = '';
document.getElementById('share-permission-read').checked = true;
document.getElementById('share-permission-write').checked = false;
document.getElementById('share-permission-reshare').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
const existingShares = 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 ?
`Vence: ${window.fileSharing.formatExpirationDate(share.expires_at)}` :
'Sin vencimiento';
shareEl.innerHTML = `
<div class="share-url">${share.url}</div>
<div class="share-info">
${share.password_protected ? '<span class="share-protected"><i class="fas fa-lock"></i> Con contraseña</span>' : ''}
<span class="share-expiration">${expiresText}</span>
</div>
<div class="share-actions">
<button class="btn btn-small copy-link-btn" data-share-url="${share.url}">
<i class="fas fa-copy"></i> Copiar
</button>
<button class="btn btn-small btn-danger delete-link-btn" data-share-id="${share.id}">
<i class="fas fa-trash"></i> Eliminar
</button>
</div>
`;
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');
if (confirm('¿Estás seguro de que quieres eliminar este enlace compartido?')) {
window.fileSharing.removeSharedLink(shareId);
btn.closest('.existing-share-item').remove();
// Check if we still have shares
if (existingSharesContainer.children.length === 0) {
document.getElementById('existing-shares-section').style.display = 'none';
}
}
});
});
} else {
document.getElementById('existing-shares-section').style.display = 'none';
}
// Show dialog
document.getElementById('share-dialog').style.display = 'flex';
},
/**
* Create a shared link with the configured options
*/
createSharedLink() {
if (!window.app.shareDialogItem || !window.app.shareDialogItemType) {
window.ui.showNotification('Error', 'No se pudo compartir el elemento');
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;
// Prepare options
const options = {
password: password || null,
expirationDate: expirationDate || null,
permissions: {
read: permissionRead,
write: permissionWrite,
reshare: permissionReshare
}
};
try {
const item = window.app.shareDialogItem;
const itemType = window.app.shareDialogItemType;
// Create share
const shareInfo = window.fileSharing.generateSharedLink(
item.id,
itemType,
options
);
// Update UI with new share
const shareUrl = document.getElementById('generated-share-url');
shareUrl.value = shareInfo.url;
document.getElementById('new-share-section').style.display = 'block';
// Focus and select for easy copying
shareUrl.focus();
shareUrl.select();
// Show success message
window.ui.showNotification('Enlace creado', 'Enlace compartido creado correctamente');
// Reload existing shares
this.showShareDialog(item, itemType);
} catch (error) {
console.error('Error creating shared link:', error);
window.ui.showNotification('Error', 'No se pudo crear el enlace compartido');
}
},
/**
* 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', 'Por favor, ingresa un correo electrónico válido');
return;
}
// Validate email format
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
window.ui.showNotification('Error', 'Por favor, ingresa un correo electrónico válido');
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', 'No se pudo enviar la notificación');
}
},
/**
* Close share dialog
*/
closeShareDialog() {
document.getElementById('share-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;
}
};
+379
View File
@@ -0,0 +1,379 @@
/**
* OxiCloud - File Sharing Module
* This file handles file sharing functionality (shared links, permissions, etc.)
*/
// File Sharing Module
const fileSharing = {
/**
* Generate a shared link for a file or folder
* @param {string} itemId - ID of the file or folder
* @param {string} itemType - Type ('file' or 'folder')
* @param {Object} options - Sharing options (password, expiration, etc.)
* @returns {Object} - Shared link information
*/
generateSharedLink(itemId, itemType, options = {}) {
try {
// In a real implementation, this would be a call to the backend
// But for now, we'll simulate it with a mock response
// Default options
const defaultOptions = {
password: null,
expirationDate: null,
permissions: {
read: true,
write: false,
reshare: false
}
};
// Merge options
const finalOptions = { ...defaultOptions, ...options };
// Generate a mock link (would normally come from server)
const linkId = Math.random().toString(36).substring(2, 15);
const shareToken = Math.random().toString(36).substring(2, 20);
const baseUrl = window.location.origin;
const sharedUrl = `${baseUrl}/s/${shareToken}`;
// Create expiration date if set
let expiresAt = null;
if (finalOptions.expirationDate) {
expiresAt = new Date(finalOptions.expirationDate);
}
// Create a mock response that matches what we'd expect from the server
const response = {
id: linkId,
type: itemType,
itemId: itemId,
url: sharedUrl,
token: shareToken,
password_protected: !!finalOptions.password,
expires_at: expiresAt ? expiresAt.toISOString() : null,
permissions: finalOptions.permissions,
created_at: new Date().toISOString(),
created_by: {
id: "current-user-id", // Would be the actual user ID
username: "current-user" // Would be the actual username
},
access_count: 0,
// Add some UI friendly properties for shared.js compatibility
name: options.name || "Shared Item",
dateShared: new Date().toISOString(),
expiration: expiresAt ? expiresAt.toISOString() : null,
password: finalOptions.password
};
// In a real implementation, we would store this link in localStorage for now
// until backend implementation is ready
this.saveSharedLink(response);
// Return the "response" as if it came from the server
return response;
} catch (error) {
console.error('Error generating shared link:', error);
throw error;
}
},
/**
* Save a shared link to localStorage (temporary storage until backend is ready)
* @param {Object} linkData - Shared link data
*/
saveSharedLink(linkData) {
try {
// Get existing shared links
const existingLinks = JSON.parse(localStorage.getItem('oxicloud_shared_links') || '[]');
// Add new link
existingLinks.push(linkData);
// Save back to localStorage
localStorage.setItem('oxicloud_shared_links', JSON.stringify(existingLinks));
} catch (error) {
console.error('Error saving shared link to local storage:', error);
}
},
/**
* Remove a shared link
* @param {string} linkId - ID of the shared link to remove
* @returns {Promise<boolean>} - Success status
*/
removeSharedLink(linkId) {
try {
// Get existing shared links
const existingLinks = JSON.parse(localStorage.getItem('oxicloud_shared_links') || '[]');
// Filter out the link to remove
const updatedLinks = existingLinks.filter(link => link.id !== linkId);
// Save back to localStorage
localStorage.setItem('oxicloud_shared_links', JSON.stringify(updatedLinks));
// Removed network delay simulation
return true;
} catch (error) {
console.error('Error removing shared link:', error);
return false;
}
},
/**
* Update a shared link's properties
* @param {string} linkId - ID of the shared link to update
* @param {Object} updateData - Properties to update
* @returns {Promise<Object>} - Updated shared link
*/
updateSharedLink(linkId, updateData) {
try {
// Get existing shared links
const existingLinks = JSON.parse(localStorage.getItem('oxicloud_shared_links') || '[]');
// Find the link to update
const linkIndex = existingLinks.findIndex(link => link.id === linkId);
if (linkIndex === -1) {
throw new Error('Shared link not found');
}
// Update link data
existingLinks[linkIndex] = {
...existingLinks[linkIndex],
...updateData,
updated_at: new Date().toISOString()
};
// Save back to localStorage
localStorage.setItem('oxicloud_shared_links', JSON.stringify(existingLinks));
// Removed network delay simulation
return existingLinks[linkIndex];
} catch (error) {
console.error('Error updating shared link:', error);
throw error;
}
},
/**
* Get all shared links for the current user
* @returns {Promise<Array>} - Array of shared links
*/
getSharedLinks() {
try {
// Get shared links from localStorage
const links = JSON.parse(localStorage.getItem('oxicloud_shared_links') || '[]');
// Removed network delay simulation
return links;
} catch (error) {
console.error('Error getting shared links:', error);
return [];
}
},
/**
* Get shared links for a specific item
* @param {string} itemId - ID of the file or folder
* @param {string} itemType - Type ('file' or 'folder')
* @returns {Promise<Array>} - Array of shared links for the item
*/
getSharedLinksForItem(itemId, itemType) {
try {
// Get all shared links
const allLinks = this.getSharedLinks();
// Filter by item ID and type
return allLinks.filter(link => link.itemId === itemId && link.type === itemType);
} catch (error) {
console.error('Error getting shared links for item:', error);
return [];
}
},
/**
* Check if an item has any shared links
* @param {string} itemId - ID of the file or folder
* @param {string} itemType - Type ('file' or 'folder')
* @returns {Promise<boolean>} - True if the item has shared links
*/
hasSharedLinks(itemId, itemType) {
const links = this.getSharedLinksForItem(itemId, itemType);
return links.length > 0;
},
/**
* Copy a shared link to clipboard
* @param {string} url - URL to copy
* @returns {boolean} - Success status
*/
copyLinkToClipboard(url) {
try {
navigator.clipboard.writeText(url);
window.ui.showNotification('Enlace copiado', 'Enlace copiado al portapapeles');
return true;
} catch (error) {
console.error('Error copying to clipboard:', error);
window.ui.showNotification('Error', 'No se pudo copiar el enlace');
return false;
}
},
/**
* Format expiration date for display
* @param {string} dateString - ISO date string
* @returns {string} - Formatted date string
*/
formatExpirationDate(dateString) {
if (!dateString) return 'Sin vencimiento';
const date = new Date(dateString);
return date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
},
/**
* Send a notification about a shared resource
* @param {string} shareUrl - The URL of the shared resource
* @param {string} recipientEmail - Email of the recipient
* @param {string} message - Optional message to include
* @returns {boolean} - Success status
*/
sendShareNotification(shareUrl, recipientEmail, message = '') {
try {
// In a real implementation, this would call the backend
// For now, we'll just simulate a successful notification
console.log(`Share notification for ${shareUrl} sent to ${recipientEmail}`);
console.log(`Message: ${message || 'No message included'}`);
// Simulate network delay
//await new Promise(resolve => setTimeout(resolve, 800));
window.ui.showNotification('Notificación enviada', `Se envió notificación a ${recipientEmail}`);
return true;
} catch (error) {
console.error('Error sending share notification:', error);
window.ui.showNotification('Error', 'No se pudo enviar la notificación');
return false;
}
},
/**
* Initialize file sharing event listeners and UI elements
*/
init() {
// This will be called by the app.js initialization
console.log('File sharing module initialized');
// Add "Shared" view event listeners
document.querySelectorAll('.nav-item').forEach(item => {
if (item.querySelector('span').getAttribute('data-i18n') === 'nav.shared') {
item.addEventListener('click', () => {
window.location.href = '/shared.html';
});
}
});
}
};
/**
* Get all shared links
* @returns {Array} Array of shared links
*/
function getSharedLinks() {
try {
return JSON.parse(localStorage.getItem('oxicloud_shared_links') || '[]');
} catch (error) {
console.error('Error getting shared links:', error);
return [];
}
}
/**
* Update a shared link
* @param {string} linkId - ID of the link to update
* @param {Object} updateData - Data to update
* @returns {boolean} Success status
*/
function updateSharedLink(linkId, updateData) {
try {
const links = getSharedLinks();
const index = links.findIndex(link => link.id === linkId);
if (index === -1) return false;
links[index] = {...links[index], ...updateData};
localStorage.setItem('oxicloud_shared_links', JSON.stringify(links));
return true;
} catch (error) {
console.error('Error updating shared link:', error);
return false;
}
}
/**
* Remove a shared link
* @param {string} linkId - ID of the link to remove
* @returns {boolean} Success status
*/
function removeSharedLink(linkId) {
try {
const links = getSharedLinks();
const filteredLinks = links.filter(link => link.id !== linkId);
localStorage.setItem('oxicloud_shared_links', JSON.stringify(filteredLinks));
return true;
} catch (error) {
console.error('Error removing shared link:', error);
return false;
}
}
/**
* Send a notification about a shared link
* @param {string} linkId - ID of the link
* @param {string} email - Recipient email
* @param {string} message - Optional message
* @returns {Promise<boolean>} Success status
*/
function sendShareNotification(linkId, email, message = '') {
return new Promise((resolve) => {
console.log(`Notification for link ${linkId} sent to ${email}`);
console.log(`Message: ${message || 'No message'}`);
setTimeout(() => resolve(true), 500);
});
}
/**
* Translate text using i18n if available
* @param {string} key - Translation key
* @param {string} defaultText - Default text if translation not found
* @returns {string} Translated text
*/
function translate(key, defaultText) {
if (window.i18n && window.i18n.t) {
return window.i18n.t(key, defaultText);
}
return defaultText;
}
/**
* Initialize i18n module
*/
function initializeI18n() {
if (window.i18n && window.i18n.init) {
window.i18n.init();
}
}
// Expose functions globally
window.getSharedLinks = getSharedLinks;
window.updateSharedLink = updateSharedLink;
window.removeSharedLink = removeSharedLink;
window.sendShareNotification = sendShareNotification;
window.translate = translate;
window.initializeI18n = initializeI18n;
// Expose file sharing module globally
window.fileSharing = fileSharing;
+469
View File
@@ -0,0 +1,469 @@
/**
* OxiCloud Shared Resources Page
* Manages the display and interaction with shared files and folders
*/
// Authentication check function
function checkAuthentication() {
// Names of variables from auth.js
const TOKEN_KEY = 'oxicloud_token';
const TOKEN_EXPIRY_KEY = 'oxicloud_token_expiry';
const USER_DATA_KEY = 'oxicloud_user';
const token = localStorage.getItem(TOKEN_KEY);
const tokenExpiry = localStorage.getItem(TOKEN_EXPIRY_KEY);
if (!token || !tokenExpiry || new Date(tokenExpiry) < new Date()) {
// No token or expired token
window.location.href = '/login.html';
return;
}
// Display username in notification if available
const userData = JSON.parse(localStorage.getItem(USER_DATA_KEY) || '{}');
if (userData.username) {
console.log(`Authenticated as ${userData.username}`);
}
}
document.addEventListener('DOMContentLoaded', () => {
// Initialize i18n
initializeI18n();
// Elements
const sharedItemsList = document.getElementById('shared-items-list');
const emptySharedState = document.getElementById('empty-shared-state');
const filterType = document.getElementById('filter-type');
const sortBy = document.getElementById('sort-by');
const sharedSearch = document.getElementById('shared-search');
const sharedSearchBtn = document.getElementById('shared-search-btn');
const goToFilesBtn = document.getElementById('go-to-files');
// Share dialog elements
const shareDialog = document.getElementById('share-dialog');
const shareDialogCloseBtn = shareDialog.querySelector('.close-dialog-btn');
const shareDialogIcon = document.getElementById('share-dialog-icon');
const shareDialogName = document.getElementById('share-dialog-name');
const shareLinkUrl = document.getElementById('share-link-url');
const copyLinkBtn = document.getElementById('copy-link-btn');
const enablePassword = document.getElementById('enable-password');
const sharePassword = document.getElementById('share-password');
const generatePasswordBtn = document.getElementById('generate-password');
const enableExpiration = document.getElementById('enable-expiration');
const shareExpiration = document.getElementById('share-expiration');
const permissionRead = document.getElementById('permission-read');
const permissionWrite = document.getElementById('permission-write');
const permissionReshare = document.getElementById('permission-reshare');
const updateShareBtn = document.getElementById('update-share-btn');
const removeShareBtn = document.getElementById('remove-share-btn');
// Notification dialog elements
const notificationDialog = document.getElementById('share-notification-dialog');
const notificationCloseBtn = notificationDialog.querySelector('.close-dialog-btn');
const notifyDialogIcon = document.getElementById('notify-dialog-icon');
const notifyDialogName = document.getElementById('notify-dialog-name');
const notificationEmail = document.getElementById('notification-email');
const notificationMessage = document.getElementById('notification-message');
const sendNotificationBtn = document.getElementById('send-notification-btn');
// Notification banner
const notificationBanner = document.getElementById('notification-banner');
const notificationBannerMessage = document.getElementById('notification-message');
const closeNotificationBtn = document.getElementById('close-notification');
// Current state
let currentSharedItem = null;
let allSharedItems = [];
let filteredItems = [];
// Initialize the page
loadSharedItems();
// Event listeners
filterType.addEventListener('change', filterAndSortItems);
sortBy.addEventListener('change', filterAndSortItems);
sharedSearchBtn.addEventListener('click', filterAndSortItems);
sharedSearch.addEventListener('keyup', (e) => {
if (e.key === 'Enter') filterAndSortItems();
});
goToFilesBtn.addEventListener('click', () => window.location.href = '/');
// Check authentication before loading
checkAuthentication();
// Share dialog event listeners
shareDialogCloseBtn.addEventListener('click', () => closeShareDialog());
copyLinkBtn.addEventListener('click', copyShareLink);
enablePassword.addEventListener('change', () => {
sharePassword.disabled = !enablePassword.checked;
if (enablePassword.checked) sharePassword.focus();
});
generatePasswordBtn.addEventListener('click', generatePassword);
enableExpiration.addEventListener('change', () => {
shareExpiration.disabled = !enableExpiration.checked;
if (enableExpiration.checked) shareExpiration.focus();
});
updateShareBtn.addEventListener('click', updateSharedItem);
removeShareBtn.addEventListener('click', removeSharedItem);
// Notification dialog event listeners
notificationCloseBtn.addEventListener('click', () => closeNotificationDialog());
sendNotificationBtn.addEventListener('click', sendNotification);
// Notification banner event listeners
closeNotificationBtn.addEventListener('click', () => {
notificationBanner.classList.remove('active');
});
/**
* Loads all shared items and displays them
*/
function loadSharedItems() {
// Get shared links from storage
allSharedItems = getSharedLinks();
// Display items
filterAndSortItems();
}
/**
* Filters and sorts the shared items based on current filters
*/
function filterAndSortItems() {
const type = filterType.value;
const sort = sortBy.value;
const searchTerm = sharedSearch.value.toLowerCase();
// Filter items
filteredItems = allSharedItems.filter(item => {
// Filter by type
if (type !== 'all' && item.type !== type) return false;
// Filter by search term
const nameMatch = item.name.toLowerCase().includes(searchTerm);
return nameMatch;
});
// Sort items
filteredItems.sort((a, b) => {
if (sort === 'name') {
return a.name.localeCompare(b.name);
} else if (sort === 'date') {
return new Date(b.dateShared) - new Date(a.dateShared);
} else if (sort === 'expiration') {
// Handle null expiration dates (items without expiration come last)
if (!a.expiration && !b.expiration) return 0;
if (!a.expiration) return 1;
if (!b.expiration) return -1;
return new Date(a.expiration) - new Date(b.expiration);
}
return 0;
});
// Display filtered and sorted items
displaySharedItems();
}
/**
* Displays the filtered and sorted shared items
*/
function displaySharedItems() {
// Clear the list
sharedItemsList.innerHTML = '';
// Show empty state if no items
if (filteredItems.length === 0) {
emptySharedState.style.display = 'flex';
document.querySelector('.shared-list-container').style.display = 'none';
return;
}
// Hide empty state and show table
emptySharedState.style.display = 'none';
document.querySelector('.shared-list-container').style.display = 'block';
// Add items to the list
filteredItems.forEach(item => {
const row = document.createElement('tr');
// Icon and name
const nameCell = document.createElement('td');
nameCell.className = 'shared-item-name';
const icon = document.createElement('span');
icon.className = 'item-icon';
icon.textContent = item.type === 'file' ? '📄' : '📁';
const name = document.createElement('span');
name.textContent = item.name;
nameCell.appendChild(icon);
nameCell.appendChild(name);
// Type
const typeCell = document.createElement('td');
typeCell.textContent = item.type === 'file' ? translate('shared_typeFile', 'File') : translate('shared_typeFolder', 'Folder');
// Date shared
const dateCell = document.createElement('td');
dateCell.textContent = formatDate(item.dateShared);
// Expiration
const expirationCell = document.createElement('td');
expirationCell.textContent = item.expiration ? formatDate(item.expiration) : translate('shared_noExpiration', 'No expiration');
// Permissions
const permissionsCell = document.createElement('td');
const permissions = [];
if (item.permissions.read) permissions.push(translate('share_permissionRead', 'Read'));
if (item.permissions.write) permissions.push(translate('share_permissionWrite', 'Write'));
if (item.permissions.reshare) permissions.push(translate('share_permissionReshare', 'Reshare'));
permissionsCell.textContent = permissions.join(', ');
// Password
const passwordCell = document.createElement('td');
passwordCell.textContent = item.password ? translate('shared_hasPassword', 'Yes') : translate('shared_noPassword', 'No');
// Actions
const actionsCell = document.createElement('td');
actionsCell.className = 'shared-item-actions';
// Edit button
const editBtn = document.createElement('button');
editBtn.className = 'action-btn edit-btn';
editBtn.innerHTML = '<span class="action-icon">✏️</span>';
editBtn.title = translate('shared_editShare', 'Edit Share');
editBtn.addEventListener('click', () => openShareDialog(item));
// Notify button
const notifyBtn = document.createElement('button');
notifyBtn.className = 'action-btn notify-btn';
notifyBtn.innerHTML = '<span class="action-icon">📧</span>';
notifyBtn.title = translate('shared_notifyShare', 'Notify Someone');
notifyBtn.addEventListener('click', () => openNotificationDialog(item));
// Copy link button
const copyBtn = document.createElement('button');
copyBtn.className = 'action-btn copy-btn';
copyBtn.innerHTML = '<span class="action-icon">📋</span>';
copyBtn.title = translate('shared_copyLink', 'Copy Link');
copyBtn.addEventListener('click', () => {
navigator.clipboard.writeText(item.url)
.then(() => showNotification(translate('shared_linkCopied', 'Link copied to clipboard!')))
.catch(err => showNotification(translate('shared_linkCopyFailed', 'Failed to copy link'), 'error'));
});
// Remove button
const removeBtn = document.createElement('button');
removeBtn.className = 'action-btn remove-btn';
removeBtn.innerHTML = '<span class="action-icon">🗑️</span>';
removeBtn.title = translate('shared_removeShare', 'Remove Share');
removeBtn.addEventListener('click', () => {
currentSharedItem = item;
removeSharedItem();
});
actionsCell.appendChild(editBtn);
actionsCell.appendChild(notifyBtn);
actionsCell.appendChild(copyBtn);
actionsCell.appendChild(removeBtn);
// Add cells to row
row.appendChild(nameCell);
row.appendChild(typeCell);
row.appendChild(dateCell);
row.appendChild(expirationCell);
row.appendChild(permissionsCell);
row.appendChild(passwordCell);
row.appendChild(actionsCell);
// Add row to table
sharedItemsList.appendChild(row);
});
}
/**
* Opens the share dialog for the given item
*/
function openShareDialog(item) {
currentSharedItem = item;
// Set dialog content
shareDialogIcon.textContent = item.type === 'file' ? '📄' : '📁';
shareDialogName.textContent = item.name;
shareLinkUrl.value = item.url;
// Set permissions
permissionRead.checked = item.permissions.read;
permissionWrite.checked = item.permissions.write;
permissionReshare.checked = item.permissions.reshare;
// Set password
enablePassword.checked = !!item.password;
sharePassword.disabled = !enablePassword.checked;
sharePassword.value = item.password || '';
// Set expiration
enableExpiration.checked = !!item.expiration;
shareExpiration.disabled = !enableExpiration.checked;
shareExpiration.value = item.expiration ? new Date(item.expiration).toISOString().split('T')[0] : '';
// Show dialog
shareDialog.classList.add('active');
}
/**
* Closes the share dialog
*/
function closeShareDialog() {
shareDialog.classList.remove('active');
currentSharedItem = null;
}
/**
* Opens the notification dialog for the given item
*/
function openNotificationDialog(item) {
currentSharedItem = item;
// Set dialog content
notifyDialogIcon.textContent = item.type === 'file' ? '📄' : '📁';
notifyDialogName.textContent = item.name;
notificationEmail.value = '';
notificationMessage.value = '';
// Show dialog
notificationDialog.classList.add('active');
}
/**
* Closes the notification dialog
*/
function closeNotificationDialog() {
notificationDialog.classList.remove('active');
currentSharedItem = null;
}
/**
* Copies the current share link to clipboard
*/
function copyShareLink() {
navigator.clipboard.writeText(shareLinkUrl.value)
.then(() => showNotification(translate('shared_linkCopied', 'Link copied to clipboard!')))
.catch(err => showNotification(translate('shared_linkCopyFailed', 'Failed to copy link'), 'error'));
}
/**
* Generates a random password for the share
*/
function generatePassword() {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*';
let password = '';
for (let i = 0; i < 12; i++) {
password += chars.charAt(Math.floor(Math.random() * chars.length));
}
sharePassword.value = password;
enablePassword.checked = true;
sharePassword.disabled = false;
}
/**
* Updates the current shared item with new settings
*/
function updateSharedItem() {
if (!currentSharedItem) return;
// Get updated settings
const permissions = {
read: permissionRead.checked,
write: permissionWrite.checked,
reshare: permissionReshare.checked
};
const password = enablePassword.checked ? sharePassword.value : null;
const expiration = enableExpiration.checked ? shareExpiration.value : null;
// Update the shared link
updateSharedLink(currentSharedItem.id, {
permissions,
password,
expiration: expiration ? new Date(expiration).toISOString() : null
});
// Reload items and close dialog
loadSharedItems();
closeShareDialog();
// Show notification
showNotification(translate('shared_itemUpdated', 'Share settings updated successfully'));
}
/**
* Removes the current shared item
*/
function removeSharedItem() {
if (!currentSharedItem) return;
// Remove the shared link
removeSharedLink(currentSharedItem.id);
// Reload items and close dialog if open
loadSharedItems();
closeShareDialog();
// Show notification
showNotification(translate('shared_itemRemoved', 'Share removed successfully'));
}
/**
* Sends a notification email for the current shared item
*/
function sendNotification() {
if (!currentSharedItem) return;
const email = notificationEmail.value.trim();
const message = notificationMessage.value.trim();
// Validate email
if (!email || !validateEmail(email)) {
showNotification(translate('shared_invalidEmail', 'Please enter a valid email address'), 'error');
return;
}
// Send notification
sendShareNotification(currentSharedItem.id, email, message)
.then(() => {
closeNotificationDialog();
showNotification(translate('shared_notificationSent', 'Notification sent successfully'));
})
.catch(error => {
showNotification(translate('shared_notificationFailed', 'Failed to send notification'), 'error');
});
}
/**
* Shows a notification banner with the given message
*/
function showNotification(message, type = 'success') {
notificationBannerMessage.textContent = message;
notificationBanner.className = 'notification-banner active ' + type;
// Auto-hide after 5 seconds
setTimeout(() => {
notificationBanner.classList.remove('active');
}, 5000);
}
/**
* Validates an email address
*/
function validateEmail(email) {
const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return re.test(email);
}
/**
* Formats a date string to a user-friendly format
*/
function formatDate(dateString) {
const options = { year: 'numeric', month: 'short', day: 'numeric' };
return new Date(dateString).toLocaleDateString(undefined, options);
}
});
+142 -1
View File
@@ -21,6 +21,9 @@ const ui = {
<div class="context-menu-item" id="move-folder-option">
<i class="fas fa-exchange-alt"></i> <span data-i18n="actions.move">Mover a...</span>
</div>
<div class="context-menu-item" id="share-folder-option">
<i class="fas fa-share-alt"></i> <span data-i18n="actions.share">Compartir</span>
</div>
<div class="context-menu-item" id="delete-folder-option">
<i class="fas fa-trash"></i> <span data-i18n="actions.delete">Eliminar</span>
</div>
@@ -34,6 +37,9 @@ const ui = {
fileMenu.className = 'context-menu';
fileMenu.id = 'file-context-menu';
fileMenu.innerHTML = `
<div class="context-menu-item" id="share-file-option">
<i class="fas fa-share-alt"></i> <span data-i18n="actions.share">Compartir</span>
</div>
<div class="context-menu-item" id="move-file-option">
<i class="fas fa-exchange-alt"></i> <span data-i18n="actions.move">Mover a...</span>
</div>
@@ -85,9 +91,144 @@ const ui = {
`;
document.body.appendChild(moveDialog);
}
// Share dialog
if (!document.getElementById('share-dialog')) {
const shareDialog = document.createElement('div');
shareDialog.className = 'share-dialog';
shareDialog.id = 'share-dialog';
shareDialog.innerHTML = `
<div class="share-dialog-content">
<div class="share-dialog-header" data-i18n="dialogs.share_file">Compartir archivo</div>
<div class="shared-item-info">
<strong>Elemento:</strong> <span id="shared-item-name"></span>
</div>
<div id="existing-shares-section" style="display:none; margin: 15px 0;">
<h3 data-i18n="dialogs.existing_shares">Enlaces compartidos existentes</h3>
<div id="existing-shares-container"></div>
</div>
<div class="share-options">
<h3 data-i18n="dialogs.share_options">Opciones de compartición</h3>
<div class="form-group">
<label for="share-password" data-i18n="dialogs.password">Contraseña (opcional):</label>
<input type="password" id="share-password" placeholder="Proteger con contraseña">
</div>
<div class="form-group">
<label for="share-expiration" data-i18n="dialogs.expiration">Fecha de vencimiento (opcional):</label>
<input type="date" id="share-expiration">
</div>
<div class="form-group">
<label data-i18n="dialogs.permissions">Permisos:</label>
<div class="permission-options">
<div class="permission-option">
<input type="checkbox" id="share-permission-read" checked>
<label for="share-permission-read" data-i18n="permissions.read">Lectura</label>
</div>
<div class="permission-option">
<input type="checkbox" id="share-permission-write">
<label for="share-permission-write" data-i18n="permissions.write">Escritura</label>
</div>
<div class="permission-option">
<input type="checkbox" id="share-permission-reshare">
<label for="share-permission-reshare" data-i18n="permissions.reshare">Permitir compartir</label>
</div>
</div>
</div>
</div>
<div id="new-share-section" style="display:none; margin: 15px 0;">
<h3 data-i18n="dialogs.generated_link">Enlace generado</h3>
<div class="form-group">
<input type="text" id="generated-share-url" readonly>
<div class="share-link-actions">
<button class="btn btn-small" id="copy-share-btn">
<i class="fas fa-copy"></i> <span data-i18n="actions.copy">Copiar</span>
</button>
<button class="btn btn-small" id="notify-share-btn">
<i class="fas fa-envelope"></i> <span data-i18n="actions.notify">Notificar</span>
</button>
</div>
</div>
</div>
<div class="share-dialog-buttons">
<button class="btn" id="share-cancel-btn" data-i18n="actions.cancel">Cancelar</button>
<button class="btn btn-primary" id="share-confirm-btn" data-i18n="actions.share">Compartir</button>
</div>
</div>
`;
document.body.appendChild(shareDialog);
// Add event listeners for share dialog
document.getElementById('share-cancel-btn').addEventListener('click', () => {
contextMenus.closeShareDialog();
});
document.getElementById('share-confirm-btn').addEventListener('click', () => {
contextMenus.createSharedLink();
});
document.getElementById('copy-share-btn').addEventListener('click', async () => {
const shareUrl = document.getElementById('generated-share-url').value;
await fileSharing.copyLinkToClipboard(shareUrl);
});
document.getElementById('notify-share-btn').addEventListener('click', () => {
const shareUrl = document.getElementById('generated-share-url').value;
contextMenus.showEmailNotificationDialog(shareUrl);
});
}
// Notification dialog
if (!document.getElementById('notification-dialog')) {
const notificationDialog = document.createElement('div');
notificationDialog.className = 'share-dialog';
notificationDialog.id = 'notification-dialog';
notificationDialog.innerHTML = `
<div class="share-dialog-content">
<div class="share-dialog-header" data-i18n="dialogs.notify">Notificar enlace compartido</div>
<p><strong>URL:</strong> <span id="notification-share-url"></span></p>
<div class="form-group">
<label for="notification-email" data-i18n="dialogs.recipient">Destinatario:</label>
<input type="email" id="notification-email" placeholder="Correo electrónico">
</div>
<div class="form-group">
<label for="notification-message" data-i18n="dialogs.message">Mensaje (opcional):</label>
<textarea id="notification-message" rows="3"></textarea>
</div>
<div class="share-dialog-buttons">
<button class="btn" id="notification-cancel-btn" data-i18n="actions.cancel">Cancelar</button>
<button class="btn btn-primary" id="notification-send-btn" data-i18n="actions.send">Enviar</button>
</div>
</div>
`;
document.body.appendChild(notificationDialog);
// Add event listeners for notification dialog
document.getElementById('notification-cancel-btn').addEventListener('click', () => {
contextMenus.closeNotificationDialog();
});
document.getElementById('notification-send-btn').addEventListener('click', () => {
contextMenus.sendShareNotification();
});
}
// Assign events to menu items
contextMenus.assignMenuEvents();
if (window.contextMenus) {
window.contextMenus.assignMenuEvents();
} else {
console.warn('contextMenus module not loaded');
}
},
/**