Update v1.1.1-beta1
This commit is contained in:
@@ -32,9 +32,42 @@ function sendDiscordWebhook(url, req, statusCode) {
|
||||
const allowedIps = setupData[0].allowedIps || [];
|
||||
const ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
|
||||
|
||||
// Skip monitoring for localhost/local IPs
|
||||
const localIps = ['127.0.0.1', '::1', 'localhost', '::ffff:127.0.0.1'];
|
||||
if (localIps.includes(ip)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Skip monitoring for Chrome DevTools requests
|
||||
if (req.originalUrl.includes('.well-known/appspecific/com.chrome.devtools.json')) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Skip monitoring for legitimate API endpoints
|
||||
const legitimateEndpoints = [
|
||||
'/api/dpanel/dashboard/profilpicture',
|
||||
'/api/dpanel/dashboard/backgroundcustom',
|
||||
'/api/dpanel/collaboration',
|
||||
'/api/dpanel/users/search',
|
||||
'/dpanel/dashboard/profil',
|
||||
'/build-metadata',
|
||||
'/api/dpanel/collaboration/add',
|
||||
'/api/dpanel/collaboration/remove',
|
||||
'/api/dpanel/collaboration/users'
|
||||
];
|
||||
|
||||
if (legitimateEndpoints.some(endpoint => req.originalUrl.includes(endpoint))) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Skip monitoring if IP is allowed
|
||||
if (isIpAllowed(ip, allowedIps)) {
|
||||
return;
|
||||
} else {
|
||||
}
|
||||
|
||||
// Skip monitoring for authenticated users on dashboard routes
|
||||
if (req.user && req.originalUrl.startsWith('/dpanel/dashboard')) {
|
||||
return;
|
||||
}
|
||||
|
||||
const fullUrl = `${req.protocol}://${req.get('host')}${req.originalUrl}`;
|
||||
|
||||
@@ -3,49 +3,65 @@ const chokidar = require('chokidar');
|
||||
const fs = require('fs');
|
||||
const { logger, ErrorLogger, logRequestInfo } = require('../config/logs');
|
||||
|
||||
// Define file paths
|
||||
const userFilePath = path.resolve(__dirname, '../data/user.json');
|
||||
const setupFilePath = path.resolve(__dirname, '../data/setup.json');
|
||||
const collaborationFilePath = path.resolve(__dirname, '../data/collaboration.json');
|
||||
|
||||
let userData, setupData;
|
||||
// Initialize data objects
|
||||
let userData, setupData, collaborationData;
|
||||
|
||||
// Load initial user data
|
||||
try {
|
||||
userData = JSON.parse(fs.readFileSync(userFilePath, 'utf-8'));
|
||||
} catch (error) {
|
||||
ErrorLogger.error(`Error parsing user.json: ${error}`);
|
||||
}
|
||||
|
||||
// Load initial setup data
|
||||
try {
|
||||
setupData = JSON.parse(fs.readFileSync(setupFilePath, 'utf-8'));
|
||||
} catch (error) {
|
||||
ErrorLogger.error(`Error parsing setup.json: ${error}`);
|
||||
}
|
||||
|
||||
const watcher = chokidar.watch([userFilePath, setupFilePath], {
|
||||
// Load initial collaboration data
|
||||
try {
|
||||
collaborationData = JSON.parse(fs.readFileSync(collaborationFilePath, 'utf-8'));
|
||||
} catch (error) {
|
||||
ErrorLogger.error(`Error parsing collaboration.json: ${error}`);
|
||||
}
|
||||
|
||||
// Set up file watcher
|
||||
const watcher = chokidar.watch([userFilePath, setupFilePath, collaborationFilePath], {
|
||||
persistent: true
|
||||
});
|
||||
|
||||
// Handle file changes
|
||||
watcher.on('change', (filePath) => {
|
||||
let modifiedFile;
|
||||
if (filePath === userFilePath) {
|
||||
try {
|
||||
|
||||
try {
|
||||
if (filePath === userFilePath) {
|
||||
userData = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
|
||||
modifiedFile = 'user.json';
|
||||
} catch (error) {
|
||||
logger.error(`Error parsing user.json: ${error}`);
|
||||
}
|
||||
} else if (filePath === setupFilePath) {
|
||||
try {
|
||||
} else if (filePath === setupFilePath) {
|
||||
setupData = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
|
||||
modifiedFile = 'setup.json';
|
||||
} catch (error) {
|
||||
logger.error(`Error parsing setup.json: ${error}`);
|
||||
} else if (filePath === collaborationFilePath) {
|
||||
collaborationData = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
|
||||
modifiedFile = 'collaboration.json';
|
||||
}
|
||||
|
||||
logger.info(`File ${modifiedFile} has been modified`);
|
||||
} catch (error) {
|
||||
ErrorLogger.error(`Error parsing ${modifiedFile}: ${error}`);
|
||||
}
|
||||
|
||||
logger.info(`File ${modifiedFile} has been modified`);
|
||||
});
|
||||
|
||||
// Export data access functions
|
||||
module.exports = {
|
||||
getUserData: () => Promise.resolve(userData),
|
||||
getSetupData: () => Promise.resolve(setupData)
|
||||
getSetupData: () => Promise.resolve(setupData),
|
||||
getCollaborationData: () => Promise.resolve(collaborationData)
|
||||
};
|
||||
@@ -10,10 +10,24 @@ const logAndBanSuspiciousActivity = async (req, res, next) => {
|
||||
const ip = req.headers['cf-connecting-ip'] || req.headers['x-forwarded-for'] || req.connection.remoteAddress;
|
||||
const url = `${req.protocol}://${req.get('host')}${req.originalUrl}`;
|
||||
|
||||
if (req.originalUrl === '/auth/activedirectory', "/favicon.ico" && req.method === 'POST') {
|
||||
// Skip monitoring for localhost/local IPs
|
||||
const localIps = ['127.0.0.1', '::1', 'localhost', '::ffff:127.0.0.1'];
|
||||
if (localIps.includes(ip)) {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Skip monitoring for Chrome DevTools requests
|
||||
if (req.originalUrl.includes('.well-known/appspecific/com.chrome.devtools.json')) {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
|
||||
// Skip monitoring for specific endpoints
|
||||
if (req.originalUrl === '/auth/activedirectory' || req.originalUrl === '/favicon.ico') {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
|
||||
let bans;
|
||||
try {
|
||||
|
||||
90
models/websocketManager.js
Normal file
90
models/websocketManager.js
Normal file
@@ -0,0 +1,90 @@
|
||||
const WebSocket = require('ws');
|
||||
const { logger } = require('../config/logs');
|
||||
|
||||
class WebSocketManager {
|
||||
constructor(server) {
|
||||
this.wss = new WebSocket.Server({ server });
|
||||
this.connections = new Map(); // Pour stocker les connexions utilisateur
|
||||
this.init();
|
||||
}
|
||||
|
||||
init() {
|
||||
this.wss.on('connection', (ws, req) => {
|
||||
|
||||
ws.on('message', (message) => {
|
||||
try {
|
||||
const data = JSON.parse(message);
|
||||
this.handleMessage(ws, data);
|
||||
} catch (error) {
|
||||
logger.error('Error handling WebSocket message:', error);
|
||||
}
|
||||
});
|
||||
|
||||
ws.on('close', () => {
|
||||
this.handleDisconnect(ws);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
handleMessage(ws, data) {
|
||||
switch (data.type) {
|
||||
case 'join':
|
||||
this.handleJoin(ws, data);
|
||||
break;
|
||||
case 'leave':
|
||||
this.handleLeave(ws, data);
|
||||
break;
|
||||
default:
|
||||
logger.warn('Unknown message type:', data.type);
|
||||
}
|
||||
}
|
||||
|
||||
handleJoin(ws, data) {
|
||||
const { userId, fileId } = data;
|
||||
this.connections.set(ws, { userId, fileId });
|
||||
this.broadcastFileStatus(fileId);
|
||||
}
|
||||
|
||||
handleLeave(ws, data) {
|
||||
const { fileId } = data;
|
||||
this.connections.delete(ws);
|
||||
this.broadcastFileStatus(fileId);
|
||||
}
|
||||
|
||||
handleDisconnect(ws) {
|
||||
const connection = this.connections.get(ws);
|
||||
if (connection) {
|
||||
this.broadcastFileStatus(connection.fileId);
|
||||
this.connections.delete(ws);
|
||||
}
|
||||
}
|
||||
|
||||
broadcastFileStatus(fileId) {
|
||||
const activeUsers = Array.from(this.connections.values())
|
||||
.filter(conn => conn.fileId === fileId)
|
||||
.map(conn => conn.userId);
|
||||
|
||||
const message = JSON.stringify({
|
||||
type: 'fileStatus',
|
||||
fileId,
|
||||
activeUsers
|
||||
});
|
||||
|
||||
this.wss.clients.forEach(client => {
|
||||
if (client.readyState === WebSocket.OPEN) {
|
||||
client.send(message);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Méthode pour envoyer une mise à jour à tous les clients
|
||||
broadcast(data) {
|
||||
this.wss.clients.forEach(client => {
|
||||
if (client.readyState === WebSocket.OPEN) {
|
||||
client.send(JSON.stringify(data));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WebSocketManager;
|
||||
725
package-lock.json
generated
725
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@cdn-app/insider-myaxrin-labs-dinawo",
|
||||
"version": "1.1.0-beta.1",
|
||||
"version": "1.1.1-beta.1",
|
||||
"description": "",
|
||||
"main": "server.js",
|
||||
"scripts": {
|
||||
@@ -63,7 +63,8 @@
|
||||
"tailwindcss": "^3.3.5",
|
||||
"toastify-js": "^1.12.0",
|
||||
"winston": "^3.11.0",
|
||||
"winston-daily-rotate-file": "^4.7.1"
|
||||
"winston-daily-rotate-file": "^4.7.1",
|
||||
"ws": "^8.18.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"daisyui": "^4.5.0",
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 28 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 54 KiB |
File diff suppressed because it is too large
Load Diff
2169
public/js/dashboard-old.js
Normal file
2169
public/js/dashboard-old.js
Normal file
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
268
public/js/profile.script.js
Normal file
268
public/js/profile.script.js
Normal file
@@ -0,0 +1,268 @@
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
initTheme();
|
||||
initTabs();
|
||||
initForms();
|
||||
updateTokenDisplay();
|
||||
});
|
||||
|
||||
// Gestion du thème
|
||||
function initTheme() {
|
||||
const body = document.body;
|
||||
const themeSwitcher = document.getElementById('themeSwitcher');
|
||||
|
||||
function setTheme(theme) {
|
||||
if (theme === 'dark') {
|
||||
body.classList.add('dark');
|
||||
} else {
|
||||
body.classList.remove('dark');
|
||||
}
|
||||
localStorage.setItem('theme', theme);
|
||||
updateThemeIcon(theme);
|
||||
}
|
||||
|
||||
function updateThemeIcon(theme) {
|
||||
const icon = themeSwitcher.querySelector('i');
|
||||
icon.className = theme === 'dark' ? 'fas fa-moon' : 'fas fa-sun';
|
||||
}
|
||||
|
||||
const savedTheme = localStorage.getItem('theme');
|
||||
if (savedTheme) {
|
||||
setTheme(savedTheme);
|
||||
} else if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
|
||||
setTheme('dark');
|
||||
}
|
||||
|
||||
themeSwitcher.addEventListener('click', () => {
|
||||
setTheme(body.classList.contains('dark') ? 'light' : 'dark');
|
||||
});
|
||||
}
|
||||
|
||||
// Gestion des onglets
|
||||
function initTabs() {
|
||||
const tabs = document.querySelectorAll('.tab');
|
||||
tabs.forEach(tab => {
|
||||
tab.addEventListener('click', () => switchTab(tab));
|
||||
});
|
||||
}
|
||||
|
||||
function switchTab(selectedTab) {
|
||||
document.querySelectorAll('.tab, .tab-content').forEach(el => {
|
||||
el.classList.remove('active');
|
||||
});
|
||||
|
||||
selectedTab.classList.add('active');
|
||||
const targetContent = document.querySelector(`[data-tab-content="${selectedTab.dataset.tab}"]`);
|
||||
targetContent.classList.add('active');
|
||||
}
|
||||
|
||||
// Gestion des formulaires et actions
|
||||
function initForms() {
|
||||
const profileCustomizationForm = document.getElementById('profileCustomization');
|
||||
|
||||
if (profileCustomizationForm) {
|
||||
profileCustomizationForm.addEventListener('submit', handleProfileCustomizationUpdate);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleProfileCustomizationUpdate(e) {
|
||||
e.preventDefault();
|
||||
const wallpaperUrl = document.getElementById('wallpaperUrl').value;
|
||||
const profilePictureUrl = document.getElementById('profilePictureUrl').value;
|
||||
|
||||
try {
|
||||
let promises = []; // Mise à jour du fond d'écran si l'URL est fournie
|
||||
if (wallpaperUrl && wallpaperUrl.trim()) {
|
||||
promises.push(
|
||||
fetch('/api/dpanel/dashboard/backgroundcustom/wallpaper', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
wallpaperUrl: wallpaperUrl
|
||||
})
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
// Mise à jour de la photo de profil si l'URL est fournie
|
||||
if (profilePictureUrl && profilePictureUrl.trim()) {
|
||||
promises.push(
|
||||
fetch('/api/dpanel/dashboard/profilpicture', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
profilePictureUrl: profilePictureUrl
|
||||
})
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
if (promises.length === 0) {
|
||||
showToast('error', 'Veuillez remplir au moins un champ');
|
||||
return;
|
||||
}
|
||||
|
||||
// Attendre toutes les requêtes
|
||||
const responses = await Promise.all(promises);
|
||||
// Vérifier toutes les réponses
|
||||
let wallpaperData = null;
|
||||
let profilePictureData = null;
|
||||
|
||||
for (let i = 0; i < responses.length; i++) {
|
||||
const response = responses[i];
|
||||
|
||||
// Vérifier le type de contenu
|
||||
const contentType = response.headers.get('content-type');
|
||||
if (!contentType || !contentType.includes('application/json')) {
|
||||
throw new Error('Le serveur a renvoyé une réponse non-JSON. Vérifiez votre authentification.');
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(data.error || `Erreur ${response.status}: ${response.statusText}`);
|
||||
}
|
||||
|
||||
// Identifier quelle réponse correspond à quoi
|
||||
if (data.wallpaper) {
|
||||
wallpaperData = data;
|
||||
} else if (data.profilePicture) {
|
||||
profilePictureData = data;
|
||||
}
|
||||
}
|
||||
|
||||
// Appliquer les changements visuels
|
||||
if (wallpaperData) {
|
||||
document.body.style.backgroundImage = `url('${wallpaperData.wallpaper}')`;
|
||||
}
|
||||
|
||||
if (profilePictureData) {
|
||||
const profileImages = document.querySelectorAll('.avatar-container img, .profile-picture img, .user-avatar');
|
||||
profileImages.forEach(img => {
|
||||
img.src = profilePictureData.profilePicture;
|
||||
});
|
||||
}
|
||||
|
||||
showToast('success', 'Profil mis à jour avec succès');
|
||||
|
||||
// Vider les champs après la mise à jour réussie
|
||||
document.getElementById('wallpaperUrl').value = '';
|
||||
document.getElementById('profilePictureUrl').value = '';
|
||||
|
||||
} catch (error) {
|
||||
showToast('error', error.message);
|
||||
}
|
||||
}
|
||||
|
||||
// Fonctions utilitaires
|
||||
function maskToken(token) {
|
||||
if (!token || token === 'Aucun token') return 'Aucun token';
|
||||
// Prendre les 8 premiers caractères et remplacer le reste par des points
|
||||
return token.substring(0, 8) + '••••••••••••';
|
||||
}
|
||||
|
||||
function updateTokenDisplay() {
|
||||
const tokenDisplay = document.querySelector('.token-display code');
|
||||
const fullToken = tokenDisplay.getAttribute('data-full-token');
|
||||
|
||||
if (!fullToken || fullToken === 'Aucun token') {
|
||||
tokenDisplay.textContent = 'Aucun token';
|
||||
} else {
|
||||
// Afficher la version masquée mais conserver le token complet dans data-full-token
|
||||
tokenDisplay.textContent = maskToken(fullToken);
|
||||
}
|
||||
}
|
||||
|
||||
function copyToken() {
|
||||
const tokenElement = document.querySelector('.token-display code');
|
||||
const fullToken = tokenElement.getAttribute('data-full-token'); // Récupère le token complet depuis l'attribut data-full-token
|
||||
|
||||
if (!fullToken || fullToken === 'Aucun token') {
|
||||
showToast('error', 'Aucun token à copier');
|
||||
return;
|
||||
}
|
||||
|
||||
// Copier le token complet, pas le texte affiché
|
||||
navigator.clipboard.writeText(fullToken);
|
||||
showToast('success', 'Token complet copié !');
|
||||
}
|
||||
|
||||
async function regenerateToken() {
|
||||
const userName = document.querySelector('meta[name="user-name"]').content;
|
||||
const userId = document.querySelector('meta[name="user-id"]').content;
|
||||
|
||||
const result = await Swal.fire({
|
||||
title: 'Êtes-vous sûr ?',
|
||||
text: "Cette action va générer un nouveau token",
|
||||
icon: 'warning',
|
||||
showCancelButton: true,
|
||||
confirmButtonColor: '#3085d6',
|
||||
cancelButtonColor: '#d33',
|
||||
confirmButtonText: 'Oui, continuer',
|
||||
cancelButtonText: 'Annuler'
|
||||
});
|
||||
|
||||
if (result.isConfirmed) {
|
||||
try {
|
||||
const response = await fetch('/api/dpanel/generate-token', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
name: userName,
|
||||
id: userId
|
||||
})
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.token) {
|
||||
const tokenDisplay = document.querySelector('.token-display code');
|
||||
// D'abord stocker le token complet dans l'attribut
|
||||
tokenDisplay.setAttribute('data-full-token', data.token);
|
||||
// Ensuite afficher la version masquée
|
||||
tokenDisplay.textContent = maskToken(data.token);
|
||||
|
||||
// Mettre à jour les boutons
|
||||
const securityContent = document.querySelector('[data-tab-content="security"] .settings-card-content .flex');
|
||||
securityContent.innerHTML = `
|
||||
<button onclick="copyToken()" class="btn btn-secondary flex-1">
|
||||
<i class="fas fa-copy mr-2"></i>Copier
|
||||
</button>
|
||||
<button onclick="regenerateToken()" class="btn btn-warning flex-1">
|
||||
<i class="fas fa-sync-alt mr-2"></i>Régénérer
|
||||
</button>
|
||||
`;
|
||||
|
||||
// Copier le token complet
|
||||
navigator.clipboard.writeText(data.token);
|
||||
|
||||
Swal.fire({
|
||||
title: 'Token généré avec succès',
|
||||
text: 'Le token complet a été copié dans votre presse-papiers.',
|
||||
icon: 'success',
|
||||
confirmButtonText: 'OK'
|
||||
});
|
||||
} else {
|
||||
throw new Error(data.error || 'Erreur lors de la génération du token');
|
||||
}
|
||||
} catch (error) {
|
||||
Swal.fire('Erreur', error.message, 'error');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function showToast(icon, title) {
|
||||
Swal.fire({
|
||||
icon,
|
||||
title,
|
||||
toast: true,
|
||||
position: 'top-end',
|
||||
showConfirmButton: false,
|
||||
timer: 3000
|
||||
});
|
||||
}
|
||||
358
routes/Dpanel/API/Collaboration.js
Normal file
358
routes/Dpanel/API/Collaboration.js
Normal file
@@ -0,0 +1,358 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const path = require('path');
|
||||
const fs = require('fs').promises;
|
||||
const { logger } = require('../../../config/logs');
|
||||
|
||||
const collaborationFilePath = path.join(__dirname, '../../../data', 'collaboration.json');
|
||||
|
||||
// Fonction utilitaire pour lire le fichier de collaboration
|
||||
async function readCollaborationFile() {
|
||||
try {
|
||||
const exists = await fs.access(collaborationFilePath)
|
||||
.then(() => true)
|
||||
.catch(() => false);
|
||||
|
||||
if (!exists) {
|
||||
await fs.writeFile(collaborationFilePath, JSON.stringify({ activeFiles: {} }));
|
||||
return { activeFiles: {} };
|
||||
}
|
||||
|
||||
const data = await fs.readFile(collaborationFilePath, 'utf8');
|
||||
return JSON.parse(data);
|
||||
} catch (error) {
|
||||
logger.error('Error reading collaboration file:', error);
|
||||
return { activeFiles: {} };
|
||||
}
|
||||
}
|
||||
|
||||
// Fonction utilitaire pour écrire dans le fichier de collaboration
|
||||
async function writeCollaborationFile(data) {
|
||||
try {
|
||||
await fs.writeFile(collaborationFilePath, JSON.stringify(data, null, 2));
|
||||
return true;
|
||||
} catch (error) {
|
||||
logger.error('Error writing collaboration file:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
router.post('/toggle', async (req, res) => {
|
||||
try {
|
||||
const { itemName, itemType, enable } = req.body;
|
||||
|
||||
// Lire ou créer le fichier de collaboration
|
||||
let collaborationData = await readCollaborationFile();
|
||||
|
||||
// S'assurer que la structure est correcte
|
||||
if (!collaborationData.activeFiles) {
|
||||
collaborationData.activeFiles = {};
|
||||
}
|
||||
|
||||
// Mettre à jour le statut de collaboration
|
||||
const itemId = `${itemType}-${itemName}`;
|
||||
if (enable) {
|
||||
collaborationData.activeFiles[itemId] = {
|
||||
name: itemName,
|
||||
type: itemType,
|
||||
isCollaborative: true,
|
||||
activeUsers: [],
|
||||
lastModified: new Date().toISOString()
|
||||
};
|
||||
} else {
|
||||
delete collaborationData.activeFiles[itemId];
|
||||
}
|
||||
|
||||
// Sauvegarder les changements
|
||||
await writeCollaborationFile(collaborationData);
|
||||
|
||||
// Notifier via WebSocket si disponible
|
||||
if (req.app.get('wsManager')) {
|
||||
req.app.get('wsManager').broadcast({
|
||||
type: 'collaborationStatus',
|
||||
itemName,
|
||||
itemType,
|
||||
isCollaborative: enable,
|
||||
activeUsers: collaborationData.activeFiles[itemId]?.activeUsers || []
|
||||
});
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
isCollaborative: enable,
|
||||
activeUsers: collaborationData.activeFiles[itemId]?.activeUsers || []
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
logger.error('Error in collaboration toggle:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error: 'Internal server error'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Route pour obtenir le statut d'un fichier
|
||||
router.get('/file-status/:fileId', async (req, res) => {
|
||||
try {
|
||||
const { fileId } = req.params;
|
||||
const collaboration = await readCollaborationFile();
|
||||
|
||||
res.json({
|
||||
fileId,
|
||||
isCollaborative: true,
|
||||
activeUsers: collaboration.activeFiles[fileId]?.activeUsers || [],
|
||||
lastModified: collaboration.activeFiles[fileId]?.lastModified || null
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error('Error getting file status:', error);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
}
|
||||
});
|
||||
|
||||
router.get('/searchuser', async (req, res) => {
|
||||
try {
|
||||
const { username } = req.query;
|
||||
const userFilePath = path.join(__dirname, '../../../data', 'user.json');
|
||||
const users = JSON.parse(await fs.readFile(userFilePath, 'utf8'));
|
||||
|
||||
const user = users.find(u => u.name.toLowerCase() === username.toLowerCase());
|
||||
|
||||
if (user) {
|
||||
res.json({
|
||||
found: true,
|
||||
user: {
|
||||
id: user.id,
|
||||
name: user.name,
|
||||
profilePicture: user.profilePicture
|
||||
}
|
||||
});
|
||||
} else {
|
||||
res.json({ found: false });
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('Error searching user:', error);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
}
|
||||
});
|
||||
|
||||
// Route pour rejoindre un fichier
|
||||
router.post('/join', async (req, res) => {
|
||||
try {
|
||||
const { itemName, itemType, userId } = req.body;
|
||||
const collaboration = await readCollaborationFile();
|
||||
|
||||
const itemId = `${itemType}-${itemName}`;
|
||||
|
||||
if (!collaboration.activeFiles[itemId]) {
|
||||
collaboration.activeFiles[itemId] = {
|
||||
name: itemName,
|
||||
type: itemType,
|
||||
isCollaborative: true,
|
||||
activeUsers: [],
|
||||
lastModified: new Date().toISOString()
|
||||
};
|
||||
}
|
||||
|
||||
// Ajouter l'utilisateur si pas déjà présent
|
||||
if (!collaboration.activeFiles[itemId].activeUsers.find(u => u.id === userId)) {
|
||||
// Récupérer les infos de l'utilisateur
|
||||
const userFilePath = path.join(__dirname, '../../../data', 'user.json');
|
||||
const users = JSON.parse(await fs.readFile(userFilePath, 'utf8'));
|
||||
const user = users.find(u => u.id === userId);
|
||||
|
||||
if (user) {
|
||||
collaboration.activeFiles[itemId].activeUsers.push({
|
||||
id: user.id,
|
||||
name: user.name,
|
||||
profilePicture: user.profilePicture,
|
||||
lastActive: new Date().toISOString()
|
||||
});
|
||||
|
||||
await writeCollaborationFile(collaboration);
|
||||
|
||||
// Notifier via WebSocket
|
||||
if (req.app.get('wsManager')) {
|
||||
req.app.get('wsManager').broadcast({
|
||||
type: 'collaborationStatus',
|
||||
itemName,
|
||||
itemType,
|
||||
isCollaborative: true,
|
||||
activeUsers: collaboration.activeFiles[itemId].activeUsers
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
res.json({ success: true });
|
||||
} catch (error) {
|
||||
logger.error('Error in join collaboration:', error);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
}
|
||||
});
|
||||
|
||||
// Route pour ajouter un collaborateur
|
||||
router.post('/add', async (req, res) => {
|
||||
try {
|
||||
const { itemName, itemType, userId } = req.body;
|
||||
const collaboration = await readCollaborationFile();
|
||||
|
||||
const itemId = `${itemType}-${itemName}`;
|
||||
|
||||
if (!collaboration.activeFiles[itemId]) {
|
||||
return res.status(404).json({ error: 'Item not found in collaboration' });
|
||||
}
|
||||
|
||||
// Vérifier si l'utilisateur n'est pas déjà dans la liste
|
||||
if (!collaboration.activeFiles[itemId].activeUsers.find(u => u.id === userId)) {
|
||||
// Récupérer les infos de l'utilisateur
|
||||
const userFilePath = path.join(__dirname, '../../../data', 'user.json');
|
||||
const users = JSON.parse(await fs.readFile(userFilePath, 'utf8'));
|
||||
const user = users.find(u => u.id === userId);
|
||||
|
||||
if (user) {
|
||||
collaboration.activeFiles[itemId].activeUsers.push({
|
||||
id: user.id,
|
||||
name: user.name,
|
||||
profilePicture: user.profilePicture,
|
||||
lastActive: new Date().toISOString()
|
||||
});
|
||||
|
||||
await writeCollaborationFile(collaboration);
|
||||
|
||||
// Notifier via WebSocket
|
||||
if (req.app.get('wsManager')) {
|
||||
req.app.get('wsManager').broadcast({
|
||||
type: 'collaborationStatus',
|
||||
itemName,
|
||||
itemType,
|
||||
isCollaborative: true,
|
||||
activeUsers: collaboration.activeFiles[itemId].activeUsers
|
||||
});
|
||||
}
|
||||
|
||||
res.json({ success: true });
|
||||
} else {
|
||||
res.status(404).json({ error: 'User not found' });
|
||||
}
|
||||
} else {
|
||||
res.status(400).json({ error: 'User already in collaboration' });
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('Error adding collaborator:', error);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
}
|
||||
});
|
||||
|
||||
// Route pour retirer un collaborateur
|
||||
router.post('/remove', async (req, res) => {
|
||||
try {
|
||||
const { itemName, itemType, userId } = req.body;
|
||||
const collaboration = await readCollaborationFile();
|
||||
|
||||
const itemId = `${itemType}-${itemName}`;
|
||||
|
||||
if (!collaboration.activeFiles[itemId]) {
|
||||
return res.status(404).json({ error: 'Item not found in collaboration' });
|
||||
}
|
||||
|
||||
// Retirer l'utilisateur de la liste
|
||||
collaboration.activeFiles[itemId].activeUsers =
|
||||
collaboration.activeFiles[itemId].activeUsers.filter(user => user.id !== userId);
|
||||
|
||||
await writeCollaborationFile(collaboration);
|
||||
|
||||
// Notifier via WebSocket
|
||||
if (req.app.get('wsManager')) {
|
||||
req.app.get('wsManager').broadcast({
|
||||
type: 'collaborationStatus',
|
||||
itemName,
|
||||
itemType,
|
||||
isCollaborative: true,
|
||||
activeUsers: collaboration.activeFiles[itemId].activeUsers
|
||||
});
|
||||
}
|
||||
|
||||
res.json({ success: true });
|
||||
} catch (error) {
|
||||
logger.error('Error removing collaborator:', error);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
}
|
||||
});
|
||||
|
||||
// Route pour quitter un fichier
|
||||
router.post('/leave', async (req, res) => {
|
||||
try {
|
||||
const { fileId } = req.body;
|
||||
const userId = req.user.id;
|
||||
|
||||
if (!fileId || !userId) {
|
||||
return res.status(400).json({ error: 'FileId and userId are required' });
|
||||
}
|
||||
|
||||
const collaboration = await readCollaborationFile();
|
||||
|
||||
if (collaboration.activeFiles[fileId]) {
|
||||
collaboration.activeFiles[fileId].activeUsers =
|
||||
collaboration.activeFiles[fileId].activeUsers.filter(user => user.id !== userId);
|
||||
|
||||
if (collaboration.activeFiles[fileId].activeUsers.length === 0) {
|
||||
delete collaboration.activeFiles[fileId];
|
||||
}
|
||||
|
||||
await writeCollaborationFile(collaboration);
|
||||
if (req.app.get('wsManager')) {
|
||||
req.app.get('wsManager').broadcastFileStatus(fileId);
|
||||
}
|
||||
}
|
||||
|
||||
res.json({ success: true });
|
||||
} catch (error) {
|
||||
logger.error('Error leaving file:', error);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
}
|
||||
});
|
||||
|
||||
router.get('/status', async (req, res) => {
|
||||
try {
|
||||
const collaboration = await readCollaborationFile();
|
||||
res.json({ items: collaboration.activeFiles });
|
||||
} catch (error) {
|
||||
logger.error('Error getting collaboration status:', error);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
}
|
||||
});
|
||||
|
||||
// Route pour obtenir les détails d'un élément collaboratif
|
||||
router.get('/details/:type/:name', async (req, res) => {
|
||||
try {
|
||||
const { type, name } = req.params;
|
||||
const collaboration = await readCollaborationFile();
|
||||
const itemId = `${type}-${name}`;
|
||||
|
||||
res.json(collaboration.activeFiles[itemId] || {
|
||||
isCollaborative: false,
|
||||
activeUsers: []
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error('Error getting collaboration details:', error);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
}
|
||||
});
|
||||
|
||||
// Route pour obtenir les utilisateurs actifs d'un élément
|
||||
router.get('/users/:type/:name', async (req, res) => {
|
||||
try {
|
||||
const { type, name } = req.params;
|
||||
const collaboration = await readCollaborationFile();
|
||||
const itemId = `${type}-${name}`;
|
||||
|
||||
const activeUsers = collaboration.activeFiles[itemId]?.activeUsers || [];
|
||||
res.json({ users: activeUsers });
|
||||
} catch (error) {
|
||||
logger.error('Error getting active users:', error);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -141,13 +141,48 @@ router.get('/', (req, res) => {
|
||||
});
|
||||
|
||||
router.post('/', authenticateToken, async (req, res) => {
|
||||
console.log('MoveFile API - Raw request body:', req.body);
|
||||
console.log('MoveFile API - Request body keys:', Object.keys(req.body));
|
||||
|
||||
const fileName = req.body.fileName;
|
||||
const folderName = req.body.folderName;
|
||||
|
||||
if (!fileName || fileName.trim() === '') {
|
||||
console.log('MoveFile API - Received data:', {
|
||||
fileName: fileName,
|
||||
folderName: folderName,
|
||||
typeOfFileName: typeof fileName,
|
||||
typeOfFolderName: typeof folderName,
|
||||
fileNameStringified: JSON.stringify(fileName),
|
||||
folderNameStringified: JSON.stringify(folderName),
|
||||
fullBody: req.body
|
||||
});
|
||||
|
||||
// Forcer la conversion en string si ce sont des objets
|
||||
let finalFileName = fileName;
|
||||
let finalFolderName = folderName;
|
||||
|
||||
if (typeof fileName === 'object' && fileName !== null) {
|
||||
console.log('fileName is an object, attempting conversion:', fileName);
|
||||
finalFileName = String(fileName);
|
||||
console.log('Converted fileName to:', finalFileName, typeof finalFileName);
|
||||
}
|
||||
|
||||
if (typeof folderName === 'object' && folderName !== null) {
|
||||
console.log('folderName is an object, attempting conversion:', folderName);
|
||||
finalFolderName = String(folderName);
|
||||
console.log('Converted folderName to:', finalFolderName, typeof finalFolderName);
|
||||
}
|
||||
|
||||
if (!finalFileName || (typeof finalFileName === 'string' && finalFileName.trim() === '')) {
|
||||
return res.status(400).json({ error: 'No file selected for moving.' });
|
||||
}
|
||||
|
||||
// Vérifier que folderName est une chaîne de caractères
|
||||
if (finalFolderName && typeof finalFolderName !== 'string') {
|
||||
console.error('folderName is not a string after conversion:', finalFolderName, typeof finalFolderName);
|
||||
return res.status(400).json({ error: 'Invalid folder name format.' });
|
||||
}
|
||||
|
||||
try {
|
||||
const data = await fs.promises.readFile(path.join(__dirname, '../../../data', 'user.json'), 'utf-8');
|
||||
const users = JSON.parse(data);
|
||||
@@ -160,21 +195,21 @@ router.post('/', authenticateToken, async (req, res) => {
|
||||
|
||||
const userId = user.name;
|
||||
|
||||
if (!fileName || !userId) {
|
||||
console.error('fileName or userId is undefined');
|
||||
if (!finalFileName || !userId) {
|
||||
console.error('finalFileName or userId is undefined');
|
||||
return res.status(500).json({ error: 'Error moving the file.' });
|
||||
}
|
||||
|
||||
const sourcePath = path.join('cdn-files', userId, fileName);
|
||||
const sourcePath = path.join('cdn-files', userId, finalFileName);
|
||||
|
||||
let destinationDir;
|
||||
if (folderName && folderName.trim() !== '') {
|
||||
destinationDir = path.join('cdn-files', userId, folderName);
|
||||
if (finalFolderName && finalFolderName.trim() !== '') {
|
||||
destinationDir = path.join('cdn-files', userId, finalFolderName);
|
||||
} else {
|
||||
destinationDir = path.join('cdn-files', userId);
|
||||
}
|
||||
|
||||
const destinationPath = path.join(destinationDir, fileName);
|
||||
const destinationPath = path.join(destinationDir, finalFileName);
|
||||
|
||||
if (!destinationPath.startsWith(path.join('cdn-files', userId))) {
|
||||
return res.status(403).json({ error: 'Unauthorized: Cannot move file outside of user directory.' });
|
||||
|
||||
205
routes/Dpanel/API/RenameFolder.js
Normal file
205
routes/Dpanel/API/RenameFolder.js
Normal file
@@ -0,0 +1,205 @@
|
||||
const express = require('express');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const router = express.Router();
|
||||
const authMiddleware = require('../../../Middlewares/authMiddleware');
|
||||
const { logger, logRequestInfo, ErrorLogger, authLogger } = require('../../../config/logs');
|
||||
const bodyParser = require('body-parser');
|
||||
|
||||
router.use(bodyParser.json());
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /folders/rename:
|
||||
* post:
|
||||
* security:
|
||||
* - bearerAuth: []
|
||||
* tags:
|
||||
* - Folder
|
||||
* summary: Rename a folder
|
||||
* description: This route allows you to rename a folder. It requires authentication.
|
||||
* requestBody:
|
||||
* required: true
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* oldName:
|
||||
* type: string
|
||||
* description: The current name of the folder
|
||||
* newName:
|
||||
* type: string
|
||||
* description: The new name for the folder
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Success
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* success:
|
||||
* type: boolean
|
||||
* message:
|
||||
* type: string
|
||||
* 400:
|
||||
* description: Bad Request
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* success:
|
||||
* type: boolean
|
||||
* message:
|
||||
* type: string
|
||||
* 401:
|
||||
* description: Unauthorized
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* message:
|
||||
* type: string
|
||||
* 403:
|
||||
* description: Forbidden
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* success:
|
||||
* type: boolean
|
||||
* message:
|
||||
* type: string
|
||||
* 404:
|
||||
* description: Folder not found
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* success:
|
||||
* type: boolean
|
||||
* message:
|
||||
* type: string
|
||||
* 500:
|
||||
* description: Internal server error
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* success:
|
||||
* type: boolean
|
||||
* message:
|
||||
* type: string
|
||||
*/
|
||||
|
||||
router.post('/', authMiddleware, async (req, res) => {
|
||||
try {
|
||||
const userId = req.userData.name;
|
||||
const { oldName, newName } = req.body;
|
||||
|
||||
// Validation des paramètres
|
||||
if (!oldName || !newName) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Les noms de dossier ancien et nouveau sont requis.'
|
||||
});
|
||||
}
|
||||
|
||||
if (typeof oldName !== 'string' || typeof newName !== 'string') {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Les noms de dossier doivent être des chaînes de caractères.'
|
||||
});
|
||||
}
|
||||
|
||||
// Nettoyer les noms (éviter les traversées de répertoire)
|
||||
const sanitizedOldName = path.basename(oldName.trim());
|
||||
const sanitizedNewName = path.basename(newName.trim());
|
||||
|
||||
if (!sanitizedOldName || !sanitizedNewName) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Les noms de dossier ne peuvent pas être vides.'
|
||||
});
|
||||
}
|
||||
|
||||
// Construire les chemins
|
||||
const userDir = path.join('cdn-files', userId);
|
||||
const oldFolderPath = path.join(userDir, sanitizedOldName);
|
||||
const newFolderPath = path.join(userDir, sanitizedNewName);
|
||||
|
||||
// Vérifier que les chemins sont dans le répertoire de l'utilisateur
|
||||
if (!oldFolderPath.startsWith(userDir) || !newFolderPath.startsWith(userDir)) {
|
||||
ErrorLogger.error(`Unauthorized directory access attempt by user ${userId}`);
|
||||
return res.status(403).json({
|
||||
success: false,
|
||||
message: 'Accès non autorisé.'
|
||||
});
|
||||
}
|
||||
|
||||
// Vérifier que le dossier source existe
|
||||
if (!fs.existsSync(oldFolderPath)) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: 'Le dossier à renommer n\'existe pas.'
|
||||
});
|
||||
}
|
||||
|
||||
// Vérifier que c'est bien un dossier
|
||||
const stats = await fs.promises.stat(oldFolderPath);
|
||||
if (!stats.isDirectory()) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Le chemin spécifié n\'est pas un dossier.'
|
||||
});
|
||||
}
|
||||
|
||||
// Vérifier que le nouveau nom n'existe pas déjà
|
||||
if (fs.existsSync(newFolderPath)) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Un dossier avec ce nom existe déjà.'
|
||||
});
|
||||
}
|
||||
|
||||
// Renommer le dossier
|
||||
await fs.promises.rename(oldFolderPath, newFolderPath);
|
||||
|
||||
logger.info(`Folder renamed successfully by user ${userId}: ${sanitizedOldName} -> ${sanitizedNewName}`);
|
||||
|
||||
res.status(200).json({
|
||||
success: true,
|
||||
message: 'Dossier renommé avec succès.'
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
ErrorLogger.error('Error renaming folder:', error);
|
||||
|
||||
if (error.code === 'ENOENT') {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: 'Le dossier spécifié n\'existe pas.'
|
||||
});
|
||||
}
|
||||
|
||||
if (error.code === 'EACCES') {
|
||||
return res.status(403).json({
|
||||
success: false,
|
||||
message: 'Permission refusée pour renommer ce dossier.'
|
||||
});
|
||||
}
|
||||
|
||||
return res.status(500).json({
|
||||
success: false,
|
||||
message: 'Erreur lors du renommage du dossier.'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
64
routes/Dpanel/API/RevokeToken.js
Normal file
64
routes/Dpanel/API/RevokeToken.js
Normal file
@@ -0,0 +1,64 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const router = require('express').Router();
|
||||
|
||||
router.post('/', (req, res) => {
|
||||
if (!req.body.userId) {
|
||||
return res.status(400).json({
|
||||
error: 'Bad Request. User ID is required.'
|
||||
});
|
||||
}
|
||||
|
||||
fs.readFile(path.join(__dirname, '../../../data', 'user.json'), 'utf8', (err, data) => {
|
||||
if (err) {
|
||||
console.error('Error reading user.json:', err);
|
||||
return res.status(500).json({
|
||||
error: 'Internal server error while reading user data.'
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const users = JSON.parse(data);
|
||||
|
||||
// Trouver l'utilisateur par ID
|
||||
const userIndex = users.findIndex(u => u.id === req.body.userId);
|
||||
|
||||
if (userIndex === -1) {
|
||||
return res.status(404).json({
|
||||
error: 'User not found.'
|
||||
});
|
||||
}
|
||||
|
||||
// Supprimer le token de l'utilisateur
|
||||
if (users[userIndex].token) {
|
||||
delete users[userIndex].token;
|
||||
} else {
|
||||
return res.status(404).json({
|
||||
error: 'No API key found for this user.'
|
||||
});
|
||||
}
|
||||
|
||||
// Sauvegarder les modifications
|
||||
fs.writeFile(path.join(__dirname, '../../../data', 'user.json'), JSON.stringify(users, null, 2), (err) => {
|
||||
if (err) {
|
||||
console.error('Error writing user.json:', err);
|
||||
return res.status(500).json({
|
||||
error: 'Internal server error while saving user data.'
|
||||
});
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'API key successfully revoked.'
|
||||
});
|
||||
});
|
||||
} catch (parseErr) {
|
||||
console.error('Error parsing user.json:', parseErr);
|
||||
return res.status(500).json({
|
||||
error: 'Internal server error while parsing user data.'
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
98
routes/Dpanel/API/UserSearch.js
Normal file
98
routes/Dpanel/API/UserSearch.js
Normal file
@@ -0,0 +1,98 @@
|
||||
const express = require('express');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const router = express.Router();
|
||||
const authMiddleware = require('../../../Middlewares/authMiddleware');
|
||||
const { logger } = require('../../../config/logs');
|
||||
|
||||
/**
|
||||
* @swagger
|
||||
* /api/dpanel/users/search:
|
||||
* get:
|
||||
* tags:
|
||||
* - Users
|
||||
* summary: Search for users by name or ID
|
||||
* parameters:
|
||||
* - in: query
|
||||
* name: term
|
||||
* required: true
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Search term (name or ID)
|
||||
* - in: query
|
||||
* name: username
|
||||
* required: false
|
||||
* schema:
|
||||
* type: string
|
||||
* description: Exact username to search for
|
||||
* responses:
|
||||
* 200:
|
||||
* description: Search results
|
||||
* content:
|
||||
* application/json:
|
||||
* schema:
|
||||
* type: object
|
||||
* properties:
|
||||
* users:
|
||||
* type: array
|
||||
* items:
|
||||
* type: object
|
||||
* properties:
|
||||
* id:
|
||||
* type: string
|
||||
* name:
|
||||
* type: string
|
||||
* profilePicture:
|
||||
* type: string
|
||||
* found:
|
||||
* type: boolean
|
||||
* user:
|
||||
* type: object
|
||||
* 500:
|
||||
* description: Internal server error
|
||||
*/
|
||||
|
||||
router.get('/', authMiddleware, async (req, res) => {
|
||||
try {
|
||||
const { term, username } = req.query;
|
||||
const userFilePath = path.join(__dirname, '../../../data', 'user.json');
|
||||
const users = JSON.parse(fs.readFileSync(userFilePath, 'utf8'));
|
||||
|
||||
if (username) {
|
||||
// Search for exact username match (for collaboration search)
|
||||
const user = users.find(u => u.name.toLowerCase() === username.toLowerCase());
|
||||
if (user) {
|
||||
res.json({
|
||||
found: true,
|
||||
user: {
|
||||
id: user.id,
|
||||
name: user.name,
|
||||
profilePicture: user.profilePicture
|
||||
}
|
||||
});
|
||||
} else {
|
||||
res.json({ found: false });
|
||||
}
|
||||
} else if (term) {
|
||||
// Search for users by term (for general user search)
|
||||
const searchTerm = term.toLowerCase();
|
||||
const filteredUsers = users.filter(user =>
|
||||
user.name.toLowerCase().includes(searchTerm) ||
|
||||
user.id.toLowerCase().includes(searchTerm)
|
||||
).map(user => ({
|
||||
id: user.id,
|
||||
name: user.name,
|
||||
profilePicture: user.profilePicture
|
||||
}));
|
||||
|
||||
res.json({ users: filteredUsers });
|
||||
} else {
|
||||
res.status(400).json({ error: 'Search term or username required' });
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error('Error searching users:', error);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -6,95 +6,146 @@ const fileUpload = require('express-fileupload');
|
||||
const authMiddleware = require('../../../Middlewares/authMiddleware');
|
||||
const { loggers } = require('winston');
|
||||
const ncp = require('ncp').ncp;
|
||||
let configFile = fs.readFileSync(path.join(__dirname, '../../../data', 'setup.json'), 'utf-8')
|
||||
let config = JSON.parse(configFile)[0];
|
||||
const bodyParser = require('body-parser');
|
||||
const crypto = require('crypto');
|
||||
const os = require('os');
|
||||
const { getUserData, getSetupData } = require('../../../Middlewares/watcherMiddleware');
|
||||
|
||||
let configFile = fs.readFileSync(path.join(__dirname, '../../../data', 'setup.json'), 'utf-8');
|
||||
let config = JSON.parse(configFile)[0];
|
||||
let setupData = getSetupData();
|
||||
let userData = getUserData();
|
||||
|
||||
// Fonction utilitaire pour lire le fichier de collaboration
|
||||
async function getCollaborativeAccess(userId) {
|
||||
try {
|
||||
const collaborationFilePath = path.join(__dirname, '../../../data', 'collaboration.json');
|
||||
if (!fs.existsSync(collaborationFilePath)) {
|
||||
return [];
|
||||
}
|
||||
const data = JSON.parse(await fs.promises.readFile(collaborationFilePath, 'utf8'));
|
||||
|
||||
const sharedFolders = [];
|
||||
|
||||
for (const [itemId, item] of Object.entries(data.activeFiles)) {
|
||||
// Ne chercher que les utilisateurs qui ne sont pas le propriétaire
|
||||
if (item.type === 'folder' &&
|
||||
item.isCollaborative &&
|
||||
item.activeUsers.some(u => u.id === userId)) {
|
||||
|
||||
// Extraire le nom du propriétaire du dossier depuis cdn-files
|
||||
const folderPath = item.name;
|
||||
const ownerFolder = path.join(__dirname, '../../../cdn-files');
|
||||
|
||||
// Parcourir tous les dossiers utilisateurs
|
||||
const users = await fs.promises.readdir(ownerFolder);
|
||||
for (const user of users) {
|
||||
const userFolderPath = path.join(ownerFolder, user, folderPath);
|
||||
if (fs.existsSync(userFolderPath)) {
|
||||
sharedFolders.push({
|
||||
originalPath: `${user}/${folderPath}`,
|
||||
displayName: `${user}/${folderPath}`,
|
||||
owner: user,
|
||||
folderName: folderPath,
|
||||
activeUsers: item.activeUsers
|
||||
});
|
||||
break; // On a trouvé le propriétaire, on peut arrêter
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return sharedFolders;
|
||||
} catch (error) {
|
||||
console.error('Error getting collaborative access:', error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
router.use(bodyParser.json());
|
||||
|
||||
router.get('/', authMiddleware, async (req, res) => {
|
||||
const folderName = req.params.folderName || '';
|
||||
|
||||
|
||||
if (!req.userData || !req.userData.name) {
|
||||
return res.render('error-recovery-file', { error: 'User data is undefined or incomplete' });
|
||||
}
|
||||
|
||||
const userId = req.userData.id;
|
||||
const userId = req.userData.id;
|
||||
const userName = req.userData.name;
|
||||
const downloadDir = path.join('cdn-files', userName);
|
||||
const domain = config.domain || 'swiftlogic-labs.com';
|
||||
|
||||
if (!config.domain) {
|
||||
console.error('Domain is not defined in setup.json');
|
||||
config.domain = 'swiftlogic-labs.com';
|
||||
}
|
||||
|
||||
if (!fs.existsSync(downloadDir)) {
|
||||
fs.mkdirSync(downloadDir, { recursive: true });
|
||||
}
|
||||
|
||||
try {
|
||||
fs.accessSync(downloadDir, fs.constants.R_OK | fs.constants.W_OK);
|
||||
} catch (err) {
|
||||
console.error('No access!', err);
|
||||
return res.render('error-recovery-file', { error: 'No access to directory' });
|
||||
}
|
||||
|
||||
let fileInfoNames = [];
|
||||
try {
|
||||
const fileInfo = JSON.parse(fs.readFileSync(path.join(__dirname, '../../../data', 'setup.json'), 'utf-8'))
|
||||
|
||||
if (!Array.isArray(fileInfo)) {
|
||||
console.error('fileInfo is not an array. Check the contents of file_info.json');
|
||||
} else {
|
||||
fileInfoNames = fileInfo.map(file => file.fileName);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error reading file_info.json:', err);
|
||||
}
|
||||
|
||||
try {
|
||||
// Lire les fichiers du répertoire de l'utilisateur
|
||||
const files = await fs.promises.readdir(downloadDir);
|
||||
|
||||
const folders = files.filter(file => fs.statSync(path.join(downloadDir, file)).isDirectory());
|
||||
|
||||
const fileDetails = files.map(file => {
|
||||
|
||||
// Séparer les fichiers et les dossiers
|
||||
const fileDetails = await Promise.all(files.map(async file => {
|
||||
const filePath = path.join(downloadDir, file);
|
||||
const stats = fs.statSync(filePath);
|
||||
const fileExtension = path.extname(file).toLowerCase();
|
||||
const stats = await fs.promises.stat(filePath);
|
||||
const isDirectory = stats.isDirectory();
|
||||
const fileExtension = isDirectory ? null : path.extname(file).toLowerCase();
|
||||
const encodedFileName = encodeURIComponent(file);
|
||||
const fileLink = `https://${domain}/attachments/${userId}/${encodedFileName}`;
|
||||
|
||||
const fileType = stats.isDirectory() ? 'folder' : 'file';
|
||||
|
||||
const fileLink = isDirectory ? null : `https://${domain}/attachments/${userId}/${encodedFileName}`;
|
||||
|
||||
return {
|
||||
name: file,
|
||||
size: stats.size,
|
||||
url: fileLink,
|
||||
extension: fileExtension,
|
||||
type: fileType
|
||||
type: isDirectory ? 'folder' : 'file',
|
||||
isPersonal: true,
|
||||
owner: userName,
|
||||
isCollaborative: false,
|
||||
activeUsers: []
|
||||
};
|
||||
}));
|
||||
|
||||
// Séparer les dossiers personnels et les fichiers
|
||||
const personalFolders = fileDetails.filter(item => item.type === 'folder');
|
||||
const personalFiles = fileDetails.filter(item => item.type === 'file');
|
||||
|
||||
// Obtenir les dossiers partagés
|
||||
const sharedFolders = await getCollaborativeAccess(userId);
|
||||
|
||||
// Formater les dossiers partagés
|
||||
const sharedFolderDetails = sharedFolders.map(folder => ({
|
||||
name: folder.displayName,
|
||||
type: 'shared-folder',
|
||||
isCollaborative: true,
|
||||
originalPath: folder.originalPath,
|
||||
owner: folder.owner,
|
||||
folderName: folder.folderName,
|
||||
activeUsers: folder.activeUsers
|
||||
}));
|
||||
|
||||
// Combiner tous les éléments dans l'ordre souhaité
|
||||
const allItems = [
|
||||
...personalFolders, // Dossiers personnels en premier
|
||||
...sharedFolderDetails, // Puis les dossiers partagés
|
||||
...personalFiles // Et enfin les fichiers
|
||||
];
|
||||
|
||||
const availableExtensions = Array.from(new Set(
|
||||
allItems
|
||||
.filter(item => item.type === 'file')
|
||||
.map(file => file.extension)
|
||||
));
|
||||
|
||||
res.render('dashboard', {
|
||||
files: allItems, // Liste complète pour la compatibilité
|
||||
folders: personalFolders, // Uniquement les dossiers personnels
|
||||
extensions: availableExtensions,
|
||||
allFolders: personalFolders,
|
||||
folderName: folderName,
|
||||
fileInfoNames: [],
|
||||
userData: userData,
|
||||
sharedFolders: sharedFolderDetails // Les dossiers partagés séparément
|
||||
});
|
||||
|
||||
function formatFileSize(fileSizeInBytes) {
|
||||
if (fileSizeInBytes < 1024 * 1024) {
|
||||
return `${(fileSizeInBytes / 1024).toFixed(2)} Ko`;
|
||||
} else if (fileSizeInBytes < 1024 * 1024 * 1024) {
|
||||
return `${(fileSizeInBytes / (1024 * 1024)).toFixed(2)} Mo`;
|
||||
} else {
|
||||
return `${(fileSizeInBytes / (1024 * 1024 * 1024)).toFixed(2)} Go`;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
const availableExtensions = Array.from(new Set(fileDetails.map(file => file.extension)));
|
||||
|
||||
res.render('dashboard', { files: fileDetails, folders, extensions: availableExtensions, allFolders: folders, folderName: folderName, fileInfoNames: fileInfoNames, userData: userData });
|
||||
} catch (err) {
|
||||
console.error('Error reading directory:', err);
|
||||
return res.render('error-recovery-file', { error: err.message });
|
||||
|
||||
@@ -17,6 +17,90 @@ let setupData = getSetupData();
|
||||
let userData = getUserData();
|
||||
router.use(bodyParser.json());
|
||||
|
||||
router.get('/shared/:ownerName/:folderName', authMiddleware, async (req, res) => {
|
||||
const { ownerName, folderName } = req.params;
|
||||
const userId = req.userData.id;
|
||||
const userName = req.userData.name;
|
||||
|
||||
try {
|
||||
// Vérifier l'accès collaboratif
|
||||
const collaborationFilePath = path.join(__dirname, '../../../data', 'collaboration.json');
|
||||
const collaborationData = JSON.parse(await fs.promises.readFile(collaborationFilePath, 'utf8'));
|
||||
|
||||
const itemId = `folder-${folderName}`;
|
||||
const folderInfo = collaborationData.activeFiles[itemId];
|
||||
|
||||
if (!folderInfo || !folderInfo.isCollaborative ||
|
||||
!folderInfo.activeUsers.some(u => u.id === userId)) {
|
||||
return res.status(403).render('error-recovery-file', {
|
||||
error: 'Vous n\'avez pas accès à ce dossier.'
|
||||
});
|
||||
}
|
||||
|
||||
// Accès au dossier partagé
|
||||
const folderPath = path.join('cdn-files', ownerName, folderName);
|
||||
const userFolderPath = path.join('cdn-files', ownerName);
|
||||
const domain = config.domain || 'swiftlogic-labs.com';
|
||||
|
||||
// Lecture des fichiers
|
||||
const entries = await fs.promises.readdir(folderPath, { withFileTypes: true });
|
||||
const allEntries = await fs.promises.readdir(userFolderPath, { withFileTypes: true });
|
||||
|
||||
const folders = entries
|
||||
.filter(entry => entry.isDirectory())
|
||||
.map(entry => entry.name);
|
||||
|
||||
const allFolders = allEntries
|
||||
.filter(entry => entry.isDirectory())
|
||||
.map(entry => entry.name);
|
||||
|
||||
// Lecture des informations de fichiers
|
||||
const fileInfoData = await fs.promises.readFile(
|
||||
path.join(__dirname, '../../../data', 'file_info.json'),
|
||||
'utf-8'
|
||||
);
|
||||
const fileInfo = JSON.parse(fileInfoData);
|
||||
const fileInfoNames = fileInfo.map(file => file.fileName);
|
||||
|
||||
// Récupération des détails des fichiers
|
||||
const fileDetails = await Promise.all(entries.map(async entry => {
|
||||
const filePath = path.join(folderPath, entry.name);
|
||||
const stats = await fs.promises.stat(filePath);
|
||||
const encodedFileName = encodeURIComponent(entry.name);
|
||||
const fileLink = `https://${domain}/attachments/${ownerName}/${encodedFileName}`;
|
||||
|
||||
return {
|
||||
name: entry.name,
|
||||
size: stats.size,
|
||||
url: fileLink,
|
||||
extension: path.extname(entry.name).toLowerCase(),
|
||||
type: entry.isDirectory() ? 'folder' : 'file'
|
||||
};
|
||||
}));
|
||||
|
||||
const availableExtensions = Array.from(new Set(fileDetails.map(file => file.extension)));
|
||||
|
||||
res.render('folder', {
|
||||
files: fileDetails,
|
||||
folders,
|
||||
allFolders,
|
||||
extensions: availableExtensions,
|
||||
currentFolder: folderName,
|
||||
folderName,
|
||||
fileInfoNames,
|
||||
userName,
|
||||
isSharedFolder: true,
|
||||
ownerName
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error accessing shared folder:', error);
|
||||
res.status(500).render('error-recovery-file', {
|
||||
error: 'Erreur lors de l\'accès au dossier partagé'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
router.get('/:folderName', authMiddleware, async (req, res) => {
|
||||
const userId = req.userData.name;
|
||||
const userName = req.userData.name;
|
||||
|
||||
@@ -11,12 +11,12 @@ const DpanelFolderRoute = require('./Dpanel/Folder/index.js');
|
||||
const DpanelUploadRoute = require('./Dpanel/Upload.js');
|
||||
const AttachmentsRoute = require('./attachments.js');
|
||||
const buildMetadataRoute = require('./BuildMetaData.js');
|
||||
const DpanelBackgroundCustomRoute = require('./Dpanel/API/BackgroundCustom.js');
|
||||
const getFileDashboardRoute = require('./Dpanel/API/getFile.js');
|
||||
const getFileFolderRoute = require('./Dpanel/API/getFileFolder.js');
|
||||
const swagger = require('../models/swagger.js');
|
||||
const NewFolderRoute = require('./Dpanel/API/NewFolder.js');
|
||||
const RenameFileRoute = require('./Dpanel/API/RenameFile.js');
|
||||
const RenameFolderRoute = require('./Dpanel/API/RenameFolder.js');
|
||||
const DeleteFileRoute = require('./Dpanel/API/DeleteFile.js');
|
||||
const MoveFileRoute = require('./Dpanel/API/MoveFile.js');
|
||||
const UploadRoute = require('./Dpanel/API/Upload.js');
|
||||
@@ -28,6 +28,8 @@ const GetMetaDataFileRoute = require('./Dpanel/API/GetMetaDataFile.js');
|
||||
const BackgroundCustom = require('./Dpanel/API/BackgroundCustom.js');
|
||||
const ProfilUser = require('./Dpanel/Dashboard/ProfilUser.js');
|
||||
const PofilPictureRoute = require('./Dpanel/API/ProfilPicture.js');
|
||||
const CollaborationRoute = require('./Dpanel/API/Collaboration.js');
|
||||
const UserSearchRoute = require('./Dpanel/API/UserSearch.js');
|
||||
|
||||
const loginRoute = require('./Auth/Login.js');
|
||||
const logoutRoute = require('./Auth/Logout.js');
|
||||
@@ -40,6 +42,7 @@ const AdminSettingSetupDpanelRoute = require('./Dpanel/Admin/SettingSetup.js');
|
||||
const AdminStatsLogsDpanelRoute = require('./Dpanel/Admin/Stats-Logs.js');
|
||||
const AdminPrivacySecurityDpanelRoute = require('./Dpanel/Admin/Privacy-Security.js');
|
||||
const GenerateTokenRoute = require('./Dpanel/API/GenerateToken.js');
|
||||
const RevokeTokenRoute = require('./Dpanel/API/RevokeToken.js');
|
||||
|
||||
router.use('/', indexRoute);
|
||||
router.use('/attachments', AttachmentsRoute);
|
||||
@@ -58,6 +61,7 @@ router.use('/dpanel/dashboard/profil', ProfilUser);
|
||||
|
||||
router.use('/api/dpanel/dashboard/newfolder',discordWebhookSuspisiousAlertMiddleware, logApiRequest, NewFolderRoute);
|
||||
router.use('/api/dpanel/dashboard/rename',discordWebhookSuspisiousAlertMiddleware, logApiRequest, RenameFileRoute);
|
||||
router.use('/api/dpanel/folders/rename',discordWebhookSuspisiousAlertMiddleware, logApiRequest, RenameFolderRoute);
|
||||
router.use('/api/dpanel/dashboard/delete',discordWebhookSuspisiousAlertMiddleware, logApiRequest, DeleteFileRoute);
|
||||
router.use('/api/dpanel/dashboard/movefile',discordWebhookSuspisiousAlertMiddleware, logApiRequest, MoveFileRoute);
|
||||
router.use('/api/dpanel/upload',discordWebhookSuspisiousAlertMiddleware, logApiRequest, UploadRoute);
|
||||
@@ -66,12 +70,14 @@ router.use('/api/dpanel/dashboard/admin/update-setup',discordWebhookSuspisiousAl
|
||||
router.use('/api/dpanel/dashboard/deletefolder',discordWebhookSuspisiousAlertMiddleware, logApiRequest, DeleteFolderRoute);
|
||||
router.use('/api/dpanel/dashboard/deletefile/', discordWebhookSuspisiousAlertMiddleware, logApiRequest,DeleteFileFolderRoute);
|
||||
router.use('/api/dpanel/dashboard/getmetadatafile',discordWebhookSuspisiousAlertMiddleware, logApiRequest, GetMetaDataFileRoute);
|
||||
router.use('/api/dpanel/dashboard/backgroundcustom',discordWebhookSuspisiousAlertMiddleware, logApiRequest, DpanelBackgroundCustomRoute);
|
||||
router.use('/api/dpanel/dashboard/backgroundcustom', BackgroundCustom, logApiRequest);
|
||||
router.use('/api/dpanel/generate-token',discordWebhookSuspisiousAlertMiddleware, logApiRequest, GenerateTokenRoute);
|
||||
router.use('/api/dpanel/revoke-token',discordWebhookSuspisiousAlertMiddleware, logApiRequest, RevokeTokenRoute);
|
||||
router.use('/api/dpanel/dashboard/getfile', getFileDashboardRoute, logApiRequest);
|
||||
router.use('/api/dpanel/dashboard/getfilefolder', getFileFolderRoute, logApiRequest);
|
||||
router.use('/api/dpanel/dashboard/backgroundcustom', BackgroundCustom, logApiRequest);
|
||||
router.use('/api/dpanel/dashboard/profilpicture', PofilPictureRoute, logApiRequest);
|
||||
router.use('/api/dpanel/collaboration', discordWebhookSuspisiousAlertMiddleware, logApiRequest, CollaborationRoute);
|
||||
router.use('/api/dpanel/users/search', UserSearchRoute, logApiRequest);
|
||||
|
||||
router.use('/auth/login', loginRoute);
|
||||
router.use('/auth/logout', logoutRoute);
|
||||
|
||||
10
server.js
10
server.js
@@ -37,8 +37,9 @@ const loadSetup = async () => {
|
||||
};
|
||||
|
||||
// Configuration de l'application
|
||||
const configureApp = async () => {
|
||||
const configureApp = async () => {
|
||||
const setup = await loadSetup();
|
||||
const WebSocketManager = require('./models/websocketManager.js');
|
||||
|
||||
// Configuration des stratégies d'authentification
|
||||
if (setup.discord) require('./models/Passport-Discord.js');
|
||||
@@ -90,7 +91,7 @@ const configureApp = async () => {
|
||||
app.use((err, req, res, next) => {
|
||||
ErrorLogger.error('Unhandled error:', err);
|
||||
|
||||
res.status(500).json(response);
|
||||
res.status(500).json({ error: 'Internal Server Error', message: err.message });
|
||||
});
|
||||
};
|
||||
|
||||
@@ -140,6 +141,11 @@ const startServer = () => {
|
||||
}
|
||||
});
|
||||
|
||||
// Initialiser le WebSocket Manager ici, après la création du serveur
|
||||
const WebSocketManager = require('./models/websocketManager.js');
|
||||
const wsManager = new WebSocketManager(server);
|
||||
app.set('wsManager', wsManager);
|
||||
|
||||
return server;
|
||||
};
|
||||
|
||||
|
||||
@@ -29,6 +29,33 @@
|
||||
</style>
|
||||
</head>
|
||||
<body class="animate">
|
||||
<div class="context-menu" style="display: none;">
|
||||
<button class="menu-item" data-action="open">
|
||||
<i class="fas fa-folder-open"></i>
|
||||
<span>Ouvrir</span>
|
||||
</button>
|
||||
<button class="menu-item" data-action="rename">
|
||||
<i class="fas fa-edit"></i>
|
||||
<span>Renommer</span>
|
||||
</button>
|
||||
<button class="menu-item" data-action="collaborate">
|
||||
<i class="fas fa-users"></i>
|
||||
<span>Collaborer</span>
|
||||
</button>
|
||||
<button class="menu-item" data-action="copy-link">
|
||||
<i class="fas fa-link"></i>
|
||||
<span>Copier le lien</span>
|
||||
</button>
|
||||
<button class="menu-item" data-action="move">
|
||||
<i class="fas fa-file-export"></i>
|
||||
<span>Déplacer</span>
|
||||
</button>
|
||||
<div class="menu-separator"></div>
|
||||
<button class="menu-item destructive" data-action="delete">
|
||||
<i class="fas fa-trash-alt"></i>
|
||||
<span>Supprimer</span>
|
||||
</button>
|
||||
</div>
|
||||
<nav class="navbar navbar-expand-md navbar-light bg-light header">
|
||||
<div class="container-fluid">
|
||||
<a class="navbar-brand" href="/dpanel/dashboard">
|
||||
@@ -61,10 +88,11 @@
|
||||
<li class="nav-item dropdown">
|
||||
<button class="btn dropdown-toggle nav-btn" id="accountDropdownBtn" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
|
||||
<img
|
||||
src="<%= user.profilePicture || 'https://api.dicebear.com/7.x/initials/svg?seed=' + encodeURIComponent(user.name) %>"
|
||||
alt="User Icon"
|
||||
class="rounded-full"
|
||||
style="max-width: 50px; max-height: 50px;"
|
||||
src="<%= user.profilePicture ? user.profilePicture : `https://api.dicebear.com/7.x/initials/svg?seed=${encodeURIComponent(user.name)}&background=%234e54c8&radius=50` %>"
|
||||
alt="<%= user.name %>"
|
||||
class="rounded-full user-avatar"
|
||||
style="width: 40px; height: 40px;"
|
||||
onerror="this.src=`https://api.dicebear.com/7.x/initials/svg?seed=${encodeURIComponent('<%= user.name %>')}&background=%234e54c8&radius=50`"
|
||||
/>
|
||||
</button>
|
||||
<div class="dropdown-menu dropdown-menu-right" id="accountDropdownMenu">
|
||||
@@ -97,77 +125,212 @@
|
||||
</nav>
|
||||
|
||||
|
||||
<div class="container mt-4 animate">
|
||||
<div class="form-container">
|
||||
<div class="flex justify-between items-center mb-4">
|
||||
<input type="text" id="searchInput" class="form-control w-1/2" placeholder="Rechercher par nom de fichier">
|
||||
<button id="searchButton" class="btn btn-primary">Rechercher</button>
|
||||
<div class="container mt-4 animate">
|
||||
<!-- Menu contextuel -->
|
||||
<div id="contextMenu" class="context-menu" style="display: none; position: fixed; z-index: 1000;">
|
||||
<div class="bg-white rounded-lg shadow-lg py-2 w-48">
|
||||
<a href="#" class="context-item-open w-full text-left px-4 py-2 hover:bg-gray-100 flex items-center">
|
||||
<i class="fas fa-folder-open mr-2"></i> Ouvrir
|
||||
</a>
|
||||
<button class="context-item-rename w-full text-left px-4 py-2 hover:bg-gray-100 flex items-center">
|
||||
<i class="fas fa-edit mr-2"></i> Renommer
|
||||
</button>
|
||||
<button class="context-item-collaborate w-full text-left px-4 py-2 hover:bg-gray-100 flex items-center">
|
||||
<i class="fas fa-users mr-2"></i> Collaborer
|
||||
</button>
|
||||
<button class="context-item-share w-full text-left px-4 py-2 hover:bg-gray-100 flex items-center">
|
||||
<i class="fas fa-share-alt mr-2"></i> Copier le lien
|
||||
</button>
|
||||
<button class="context-item-move w-full text-left px-4 py-2 hover:bg-gray-100 flex items-center">
|
||||
<i class="fas fa-file-export mr-2"></i> Déplacer
|
||||
</button>
|
||||
<div class="border-t border-gray-200 my-2"></div>
|
||||
<button class="context-item-delete w-full text-left px-4 py-2 hover:bg-gray-100 flex items-center text-red-600">
|
||||
<i class="fas fa-trash-alt mr-2"></i> Supprimer
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="table-responsive">
|
||||
<table class="table" id="fileTable">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Nom du fichier</th>
|
||||
<th>Taille</th>
|
||||
<th class="text-right">Action</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<% files.forEach(file => { %>
|
||||
<tr data-extension="<%= file.extension %>" data-type="<%= file.type %>">
|
||||
<% if (fileInfoNames.includes(file.name)) { %>
|
||||
<td><a href="#" onclick="showFileInfo('<%= file.name %>')"><%= file.name %></a></td>
|
||||
<% } else { %>
|
||||
<td><%= file.name %></td>
|
||||
|
||||
<div class="form-container">
|
||||
<div class="flex justify-between items-center mb-4">
|
||||
<input type="text" id="searchInput" class="form-control w-1/2" placeholder="Rechercher par nom de fichier">
|
||||
<button id="searchButton" class="btn btn-primary">Rechercher</button>
|
||||
</div>
|
||||
|
||||
<div class="table-responsive">
|
||||
<table class="table" id="fileTable">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Nom</th>
|
||||
<th class="text-center">Type</th>
|
||||
<th class="text-center">Propriétaire</th>
|
||||
<th class="text-center">Taille</th>
|
||||
<th class="text-right">Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<!-- Dossiers personnels -->
|
||||
<% files.filter(item => item.type === 'folder').forEach(folder => { %>
|
||||
<tr data-type="folder" data-name="<%= folder.name %>" data-url="/dpanel/dashboard/folder/<%= encodeURIComponent(folder.name) %>" class="hover:bg-gray-50">
|
||||
<td>
|
||||
<div class="d-flex align-items-center">
|
||||
<i class="fas fa-folder text-warning mr-2"></i>
|
||||
<%= folder.name %>
|
||||
<% if (folder.isCollaborative) { %>
|
||||
<span class="ml-2 badge badge-info collaboration-badge">
|
||||
<i class="fas fa-users"></i>
|
||||
<span class="active-users-count"><%= folder.activeUsers.length %></span>
|
||||
</span>
|
||||
<% } %>
|
||||
</div>
|
||||
</td>
|
||||
<td class="text-center">
|
||||
<span class="badge badge-warning">Dossier</span>
|
||||
</td>
|
||||
<td class="text-center">
|
||||
<span class="text-muted">
|
||||
<i class="fas fa-user"></i>
|
||||
moi
|
||||
</span>
|
||||
</td>
|
||||
<td class="text-center">-</td>
|
||||
<td class="text-right">
|
||||
<div class="dropdown">
|
||||
<button class="btn btn-link btn-sm dropdown-toggle" type="button" data-bs-toggle="dropdown">
|
||||
<i class="fas fa-ellipsis-v"></i>
|
||||
</button>
|
||||
<div class="dropdown-menu dropdown-menu-end">
|
||||
<a href="/dpanel/dashboard/folder/<%= encodeURIComponent(folder.name) %>"
|
||||
class="dropdown-item">
|
||||
<i class="fas fa-folder-open mr-2"></i> Ouvrir
|
||||
</a>
|
||||
<button class="dropdown-item rename-folder-btn" data-folder-name="<%= folder.name %>">
|
||||
<i class="fas fa-edit mr-2"></i> Renommer
|
||||
</button>
|
||||
<button class="dropdown-item text-primary toggle-collaboration-btn"
|
||||
data-item-name="<%= folder.name %>"
|
||||
data-item-type="folder"
|
||||
data-is-collaborative="<%= folder.isCollaborative ? 'true' : 'false' %>">
|
||||
<i class="fas fa-users mr-2"></i> Collaborer
|
||||
</button>
|
||||
<div class="dropdown-divider"></div>
|
||||
<button class="dropdown-item text-danger delete-folder-btn" data-folder-name="<%= folder.name %>">
|
||||
<i class="fas fa-trash-alt mr-2"></i> Supprimer
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
<% }); %>
|
||||
|
||||
<!-- Dossiers partagés -->
|
||||
<% if (sharedFolders && sharedFolders.length > 0) { %>
|
||||
<% sharedFolders.forEach(folder => { %>
|
||||
<tr data-type="shared-folder" data-name="<%= folder.folderName %>" data-url="/dpanel/dashboard/folder/shared/<%= folder.owner %>/<%= encodeURIComponent(folder.folderName) %>" class="hover:bg-gray-50">
|
||||
<td>
|
||||
<div class="d-flex align-items-center">
|
||||
<i class="fas fa-folder-open text-info mr-2"></i>
|
||||
<%= folder.folderName %>
|
||||
<span class="ml-2 badge badge-info collaboration-badge">
|
||||
<i class="fas fa-users"></i>
|
||||
<span class="active-users-count"><%= folder.activeUsers.length %></span>
|
||||
</span>
|
||||
</div>
|
||||
</td>
|
||||
<td class="text-center">
|
||||
<span class="badge badge-info">Dossier partagé</span>
|
||||
</td>
|
||||
<td class="text-center">
|
||||
<span class="text-muted">
|
||||
<i class="fas fa-user"></i>
|
||||
<%= folder.owner === userData.name ? 'moi' : folder.owner %>
|
||||
</span>
|
||||
</td>
|
||||
<td class="text-center">-</td>
|
||||
<td class="text-right">
|
||||
<div class="dropdown">
|
||||
<button class="btn btn-link btn-sm dropdown-toggle" type="button" data-bs-toggle="dropdown">
|
||||
<i class="fas fa-ellipsis-v"></i>
|
||||
</button>
|
||||
<div class="dropdown-menu dropdown-menu-end">
|
||||
<a href="/dpanel/dashboard/folder/shared/<%= folder.owner %>/<%= encodeURIComponent(folder.folderName) %>"
|
||||
class="dropdown-item">
|
||||
<i class="fas fa-folder-open mr-2"></i> Ouvrir
|
||||
</a>
|
||||
<button class="dropdown-item leave-folder-btn">
|
||||
<i class="fas fa-user-minus mr-2"></i> Quitter
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
<% }); %>
|
||||
<% } %>
|
||||
<td>
|
||||
<% if (file.type === 'folder') { %>
|
||||
Dossier
|
||||
<% } else { %>
|
||||
<span class="file-size" data-size="<%= file.size %>"><%= file.size %> octets</span>
|
||||
<% } %>
|
||||
</td>
|
||||
<td class="text-right">
|
||||
<div class="action-buttons">
|
||||
<% if (file.type === 'folder') { %>
|
||||
<button class="delete-folder-button btn btn-danger btn-sm" data-folder-name="<%= file.name %>">
|
||||
<i class="fas fa-trash-alt"></i>
|
||||
|
||||
<!-- Fichiers -->
|
||||
<% files.filter(item => item.type === 'file').forEach(file => { %>
|
||||
<tr data-type="file" data-name="<%= file.name %>" data-url="<%= file.url %>" class="hover:bg-gray-50">
|
||||
<td>
|
||||
<div class="d-flex align-items-center">
|
||||
<i class="fas fa-file text-secondary mr-2"></i>
|
||||
<%= file.name %>
|
||||
</div>
|
||||
</td>
|
||||
<td class="text-center">
|
||||
<span class="badge badge-secondary">Fichier</span>
|
||||
</td>
|
||||
<td class="text-center">
|
||||
<span class="text-muted">
|
||||
<i class="fas fa-user"></i>
|
||||
moi
|
||||
</span>
|
||||
</td>
|
||||
<td class="text-center">
|
||||
<span class="file-size" data-size="<%= file.size %>">
|
||||
<%= file.size %> octets
|
||||
</span>
|
||||
</td>
|
||||
<td class="text-right">
|
||||
<div class="dropdown">
|
||||
<button class="btn btn-link btn-sm dropdown-toggle" type="button" data-bs-toggle="dropdown">
|
||||
<i class="fas fa-ellipsis-v"></i>
|
||||
</button>
|
||||
<a href="/dpanel/dashboard/folder/<%= file.name %>" class="btn btn-primary btn-sm">
|
||||
<i class="fas fa-folder-open"></i>
|
||||
</a>
|
||||
<% } else { %>
|
||||
<button class="btn btn-primary btn-sm rename-file-btn" data-file-name="<%= file.name %>" data-folder-name="<%= folderName %>">
|
||||
<i class="fas fa-edit"></i>
|
||||
</button>
|
||||
<button class="delete-file-button btn btn-danger btn-sm" data-file-name="<%= file.name %>">
|
||||
<i class="fas fa-trash-alt"></i>
|
||||
</button>
|
||||
<button class="copy-button btn btn-success btn-sm" data-file-url="<%= file.url %>">
|
||||
<i class="fas fa-copy"></i>
|
||||
</button>
|
||||
<button class="btn btn-secondary btn-sm move-file-btn" data-file-name="<%= file.name %>">
|
||||
<i class="fas fa-file-export"></i>
|
||||
</button>
|
||||
<% } %>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
<% }); %>
|
||||
</tbody>
|
||||
</table>
|
||||
<div class="dropdown-menu dropdown-menu-end">
|
||||
<button class="dropdown-item rename-file-btn" data-file-name="<%= file.name %>">
|
||||
<i class="fas fa-edit mr-2"></i> Renommer
|
||||
</button>
|
||||
<button class="dropdown-item copy-button" data-file-url="<%= file.url %>">
|
||||
<i class="fas fa-copy mr-2"></i> Copier le lien
|
||||
</button>
|
||||
<button class="dropdown-item move-file-btn" data-file-name="<%= file.name %>">
|
||||
<i class="fas fa-file-export mr-2"></i> Déplacer
|
||||
</button>
|
||||
<div class="dropdown-divider"></div>
|
||||
<button class="dropdown-item text-danger delete-file-button" data-file-name="<%= file.name %>">
|
||||
<i class="fas fa-trash-alt mr-2"></i> Supprimer
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
<% }); %>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<footer class="footer mt-auto py-3 bg-light">
|
||||
<div class="container">
|
||||
<span class="text-muted">Version: <span id="version-number">...</span> | © 2024 Myaxrin Labs</span>
|
||||
<span class="text-muted">Version: <span id="version-number">...</span> | © <span id="current-year"></span> Myaxrin Labs</span>
|
||||
<a href="#" class="float-right" onclick="displayMetadata()">Metadata</a>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
<script>
|
||||
document.getElementById('current-year').textContent = new Date().getFullYear();
|
||||
</script>
|
||||
|
||||
<div class="modal fade" id="metadataModal" tabindex="-1" role="dialog" aria-labelledby="metadataModalLabel" aria-hidden="true">
|
||||
<div class="modal-dialog modal-dialog-centered" role="document">
|
||||
<div class="modal-content">
|
||||
@@ -207,7 +370,7 @@
|
||||
<select class="form-control" id="moveFolderSelect" name="folderName">
|
||||
<option value="" disabled selected>Choisir un dossier...</option>
|
||||
<% allFolders.forEach(folder => { %>
|
||||
<option value="<%= folder %>"><%= folder %></option>
|
||||
<option value="<%= folder.name %>"><%= folder.name %></option>
|
||||
<% }); %>
|
||||
</select>
|
||||
</form>
|
||||
@@ -220,6 +383,45 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Modal Collaboration -->
|
||||
<div class="modal fade" id="collaborationModal" tabindex="-1" aria-labelledby="collaborationModalLabel" aria-hidden="true">
|
||||
<div class="modal-dialog">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 class="modal-title" id="collaborationModalLabel">Gestion de la collaboration</h5>
|
||||
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
|
||||
<span aria-hidden="true">×</span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="modal-body">
|
||||
<div class="collaboration-users mb-4">
|
||||
<!-- Liste des utilisateurs -->
|
||||
</div>
|
||||
<div class="add-collaborator">
|
||||
<h6 class="mb-3">Ajouter un collaborateur</h6>
|
||||
<div class="input-group mb-3">
|
||||
<input type="text" id="searchCollabUser" class="form-control" placeholder="Rechercher un utilisateur">
|
||||
<div class="input-group-append">
|
||||
<button class="btn btn-outline-secondary" type="button" id="searchCollabBtn">
|
||||
<i class="fas fa-search"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="searchCollabResults" class="mb-3">
|
||||
<!-- Résultats de recherche -->
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer justify-content-between">
|
||||
<button type="button" class="btn btn-danger" id="disableCollabBtn">
|
||||
<i class="fas fa-users-slash"></i> Désactiver la collaboration
|
||||
</button>
|
||||
<button type="button" class="btn btn-secondary" data-dismiss="modal">Fermer</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
|
||||
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
|
||||
|
||||
1014
views/profile.ejs
1014
views/profile.ejs
File diff suppressed because it is too large
Load Diff
@@ -153,7 +153,7 @@
|
||||
</main>
|
||||
|
||||
<footer class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8 text-center text-gray-500 text-sm opacity-0 animate-fade-in-up">
|
||||
<p>Version: <span id="version-number">...</span> | © 2024 Myaxrin Labs</p>
|
||||
<p>Version: <span id="version-number">...</span> | © <span id="current-year"></span> Myaxrin Labs</p>
|
||||
</footer>
|
||||
|
||||
<script>
|
||||
@@ -163,6 +163,9 @@
|
||||
element.classList.add('animate-fade-in-up-visible');
|
||||
});
|
||||
|
||||
// Set current year
|
||||
document.getElementById('current-year').textContent = new Date().getFullYear();
|
||||
|
||||
// Fetch version from build-metadata API
|
||||
fetch('/build-metadata')
|
||||
.then(response => response.json())
|
||||
|
||||
Reference in New Issue
Block a user