const mongoose = require('mongoose'); const fs = require('fs'); const path = require('path'); require('dotenv').config({ path: path.resolve(__dirname, '../../.env') }); // Load .env for UPLOAD_DIR const connectDB = require('../config/db'); const Asset = require('../models/Asset'); const User = require('../models/User'); // Required for Asset model's 'uploadedBy' reference // Xác định thư mục uploads gốc const uploadDir = process.env.UPLOAD_DIR ? path.resolve(process.env.UPLOAD_DIR) : path.join(__dirname, '../../uploads'); const migrateAssetsToUserFolders = async () => { try { console.log('--- Bắt đầu quy trình di chuyển Assets vào thư mục người dùng ---'); await connectDB(); const allAssets = await Asset.find({}); console.log(`Tìm thấy ${allAssets.length} Assets cần kiểm tra.`); let movedCount = 0; let updatedDbCount = 0; let skippedCount = 0; let errorCount = 0; for (const asset of allAssets) { const currentFilePath = asset.filePath; const userId = asset.uploadedBy ? asset.uploadedBy.toString() : null; if (!userId) { console.warn(`[WARN] Asset ${asset._id}: Không có thông tin người tải lên. Bỏ qua.`); skippedCount++; continue; } // Kiểm tra xem đường dẫn hiện tại đã có userId trong cấu trúc chưa // Ví dụ: uploads/654321abcdef/processed_123.jpg const relativePathSegments = path.relative(uploadDir, currentFilePath).split(path.sep); if (relativePathSegments.length > 1 && relativePathSegments[0] === userId) { console.log(`[SKIP] Asset ${asset._id}: Đường dẫn đã ở đúng định dạng người dùng (${currentFilePath}).`); skippedCount++; continue; } const fileName = path.basename(currentFilePath); const userUploadSubDir = path.join(uploadDir, userId); // e.g., /app/uploads/654321abcdef const newFilePath = path.join(userUploadSubDir, fileName); // e.g., /app/uploads/654321abcdef/processed_123.jpg if (!fs.existsSync(userUploadSubDir)) { console.log(`[MKDIR] Tạo thư mục: ${userUploadSubDir}`); fs.mkdirSync(userUploadSubDir, { recursive: true }); } try { // Kiểm tra sự tồn tại của tệp tin vật lý trước khi di chuyển if (fs.existsSync(currentFilePath)) { fs.renameSync(currentFilePath, newFilePath); movedCount++; console.log(`[MOVE] Asset ${asset._id}: Di chuyển từ ${currentFilePath} sang ${newFilePath}`); } else { console.warn(`[WARN] Tệp tin vật lý không tồn tại: ${currentFilePath} cho Asset ${asset._id}.`); } // Cập nhật đường dẫn trong bản ghi Asset trong cơ sở dữ liệu asset.filePath = newFilePath; await asset.save(); updatedDbCount++; } catch (fileError) { console.error(`[ERROR] Lỗi khi xử lý file cho Asset ${asset._id} (${currentFilePath}): ${fileError.message}`); errorCount++; } } console.log('--- Hoàn tất quy trình di chuyển Assets ---'); console.log(`Tổng Assets kiểm tra: ${allAssets.length}`); console.log(`Assets đã di chuyển file: ${movedCount}`); console.log(`Assets đã cập nhật DB: ${updatedDbCount}`); console.log(`Assets đã bỏ qua (đã đúng định dạng hoặc không có userId): ${skippedCount}`); console.log(`Assets gặp lỗi: ${errorCount}`); } catch (dbError) { console.error('Lỗi kết nối hoặc truy vấn Database:', dbError.message); process.exit(1); } finally { if (mongoose.connection) { await mongoose.connection.close(); } process.exit(0); } }; migrateAssetsToUserFolders();