icon
const dialogHeader = shareDialog.querySelector('.share-dialog-header');
if (dialogHeader) {
const headerSpan = dialogHeader.querySelector('span');
const titleText = itemType === 'file' ? i18n.t('dialogs.share_file') : i18n.t('dialogs.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 = /** @type HTMLInputElement */ (document.getElementById('share-password'));
const expField = /** @type HTMLInputElement */ (document.getElementById('share-expiration'));
if (pwField) pwField.value = '';
if (expField) expField.value = '';
const permRead = /** @type HTMLInputElement */ (document.getElementById('share-permission-read'));
const permWrite = /** @type HTMLInputElement */ (document.getElementById('share-permission-write'));
const permReshare = /** @type HTMLInputElement */ (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
app.shareDialogItem = item;
app.shareDialogItemType = itemType;
// Check if item already has shares (async API call)
const existingShares = await 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').classList.remove('hidden');
// 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: ${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 = ' 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 = ' 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 = ' 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');
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: i18n.t('dialogs.confirm_delete_share'),
message: i18n.t('dialogs.confirm_delete_share_msg'),
confirmText: i18n.t('actions.delete')
}).then(async (confirmed) => {
if (confirmed) {
await fileSharing.removeSharedLink(shareId);
btn.closest('.existing-share-item').remove();
if (existingSharesContainer.children.length === 0) {
document.getElementById('existing-shares-section').classList.add('hidden');
ui.setSharedVisualState(item.id, itemType, false);
}
}
});
});
});
} else {
document.getElementById('existing-shares-section').classList.add('hidden');
}
// Hide new-share section from previous use
const newShareSection = document.getElementById('new-share-section');
if (newShareSection) newShareSection.classList.add('hidden');
// Show dialog
shareDialog.classList.remove('hidden');
console.log('Share dialog opened for', itemType, item.name);
} catch (error) {
console.error('Error opening share dialog:', error);
ui.showNotification('Error', 'Could not open share dialog');
}
},
/**
* Create a shared link with the configured options
*/
async createSharedLink() {
if (!app.shareDialogItem || !app.shareDialogItemType) {
ui.showNotification('Error', 'Could not share the item');
return;
}
// Get values from form
const password = /** @type HTMLInputElement */ (document.getElementById('share-password')).value;
const expirationDate = /** @type HTMLInputElement */ (document.getElementById('share-expiration')).value;
const permissionRead = /** @type HTMLInputElement */ (document.getElementById('share-permission-read')).checked;
const permissionWrite = /** @type HTMLInputElement */ (document.getElementById('share-permission-write')).checked;
const permissionReshare = /** @type HTMLInputElement */ (document.getElementById('share-permission-reshare')).checked;
const item = app.shareDialogItem;
const itemType = 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 headers = {
'Content-Type': 'application/json',
...getCsrfHeaders()
};
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 = /** @type HTMLInputElement */ (document.getElementById('generated-share-url'));
if (shareUrl) {
shareUrl.value = shareInfo.url;
document.getElementById('new-share-section').classList.remove('hidden');
shareUrl.focus();
shareUrl.select();
}
// Update Item's shared badge
ui.setSharedVisualState(item.id, itemType, true);
// Show success message
ui.showNotification(i18n.t('notifications.link_created'), i18n.t('notifications.share_success'));
} catch (error) {
console.error('Error creating shared link:', error);
ui.showNotification('Error', /** @type {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;
/** @type HTMLInputElement */ (document.getElementById('notification-email')).value = '';
/** @type HTMLInputElement */ (document.getElementById('notification-message')).value = '';
// Store the URL for later use
app.notificationShareUrl = shareUrl;
// Show dialog
document.getElementById('notification-dialog')?.classList.remove('hidden');
},
/**
* Send share notification email
*/
sendShareNotification() {
const email = /** @type HTMLInputElement */ (document.getElementById('notification-email')).value.trim();
const message = /** @type HTMLInputElement */ (document.getElementById('notification-message')).value.trim();
const shareUrl = app.notificationShareUrl;
if (!email || !shareUrl) {
ui.showNotification('Error', 'Please enter a valid email address');
return;
}
// Validate email format
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
ui.showNotification('Error', 'Please enter a valid email address');
return;
}
try {
fileSharing.sendShareNotification(shareUrl, email, message);
document.getElementById('notification-dialog')?.classList.add('hidden');
} catch (error) {
console.error('Error sending notification:', error);
ui.showNotification('Error', 'Could not send notification');
}
},
/**
* Close share dialog
*/
closeShareDialog() {
const dialog = document.getElementById('share-dialog');
if (dialog) dialog.classList.add('hidden');
app.shareDialogItem = null;
app.shareDialogItemType = null;
},
/**
* Close notification dialog
*/
closeNotificationDialog() {
document.getElementById('notification-dialog')?.classList.add('hidden');
app.notificationShareUrl = null;
},
/** @type {String | null} */
_selectedPlaylistId: null,
/**
*
* @param {FileItem} file
* @returns
*/
async showPlaylistDialog(file) {
const dialog = document.getElementById('playlist-dialog');
const container = document.getElementById('playlist-select-container');
const filesInfo = document.getElementById('playlist-dialog-files-info');
if (!dialog || !container) {
console.error('Playlist dialog elements not found');
return;
}
// Store the file(s) to add
app.playlistDialogFiles = [file];
// Update files info
if (filesInfo) {
filesInfo.innerHTML = `${i18n.t('music.selected_files')} ${file.name}`;
}
// Reset selection
this._selectedPlaylistId = null;
container.innerHTML = '
';
// Reset add button state
const addBtn = /** @type {HTMLButtonElement} */ (document.getElementById('playlist-add-btn'));
if (addBtn) addBtn.disabled = true;
// Show dialog
dialog.classList.remove('hidden');
requestAnimationFrame(() => dialog.classList.add('active'));
// Load playlists
try {
const resp = await fetch('/api/playlists', { credentials: 'include' });
if (!resp.ok) throw new Error('Failed to load playlists');
/** @type {Playlist[]} */
const playlists = await resp.json();
this._renderPlaylistSelect(container, playlists);
} catch (err) {
console.error('Error loading playlists:', err);
container.innerHTML = `${i18n.t('music.load_error')}
`;
}
},
/**
*
* @param {HTMLElement} container
* @param {Playlist[]} playlists
* @returns
*/
_renderPlaylistSelect(container, playlists) {
container.innerHTML = '';
if (playlists.length === 0) {
container.innerHTML = `${i18n.t('music.no_playlists')}
`;
return;
}
playlists.forEach((playlist) => {
const item = document.createElement('div');
item.className = 'folder-select-item';
item.dataset.id = playlist.id;
item.innerHTML = `
${this._escapeHtml(playlist.name)}
${playlist.track_count || 0} ${i18n.t('music.tracks')}
`;
item.addEventListener('click', () => {
container.querySelectorAll('.folder-select-item').forEach((el) => {
el.classList.remove('selected');
});
item.classList.add('selected');
this._selectedPlaylistId = playlist.id;
const addBtn = /** @type {HTMLButtonElement} */ (document.getElementById('playlist-add-btn'));
if (addBtn) addBtn.disabled = false;
});
container.appendChild(item);
});
},
async addSelectedFilesToPlaylist() {
const playlistId = this._selectedPlaylistId;
const files = app.playlistDialogFiles || [];
if (!playlistId || files.length === 0) return;
const addBtn = /** @type {HTMLButtonElement} */ (document.getElementById('playlist-add-btn'));
if (addBtn) addBtn.disabled = true;
try {
const resp = await fetch(`/api/playlists/${playlistId}/tracks`, {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
...getCsrfHeaders()
},
body: JSON.stringify({ file_ids: files.map((f) => f.id) })
});
if (!resp.ok) {
const err = await resp.json().catch(() => ({}));
throw new Error(err.message || 'Failed to add tracks');
}
await resp.json();
ui.showNotification(i18n.t('music.added'), `${files.length} ${files.length === 1 ? 'track' : 'tracks'} ${i18n.t('music.added_to_playlist')}`);
this.closePlaylistDialog();
// Refresh music view if open
if (musicView?.playlists) {
musicView._loadPlaylists();
}
} catch (err) {
console.error('Error adding to playlist:', err);
ui.showNotification(i18n.t('music.error'), /** @type {Error} */ (err).message || i18n.t('music.add_error'));
if (addBtn) addBtn.disabled = false;
}
},
closePlaylistDialog() {
const dialog = document.getElementById('playlist-dialog');
if (dialog) {
dialog.classList.remove('active');
setTimeout(() => {
dialog.classList.add('hidden');
}, 200);
}
app.playlistDialogFiles = null;
this._selectedPlaylistId = null;
},
/**
*
* @param {string} str
* @returns
*/
//FIXME: move to common library
_escapeHtml(str) {
if (!str) return '';
return str.replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"');
}
};
export { contextMenus };