Sửa lỗi tạo docker
This commit is contained in:
@@ -0,0 +1,22 @@
|
||||
FROM node:18-slim
|
||||
|
||||
# Cài đặt các công cụ biên dịch và thư viện cần thiết cho các module native (sharp, bcrypt)
|
||||
RUN apt-get update && apt-get install -y \
|
||||
python3 \
|
||||
make \
|
||||
g++ \
|
||||
libvips-dev \
|
||||
perl \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY package*.json ./
|
||||
RUN npm install --omit=dev
|
||||
|
||||
COPY . .
|
||||
|
||||
EXPOSE 3000
|
||||
|
||||
ENV NODE_ENV=production
|
||||
CMD ["node", "backend/server.js"]
|
||||
@@ -2,9 +2,6 @@ const mongoose = require('mongoose');
|
||||
const path = require('path');
|
||||
const dotenv = require('dotenv');
|
||||
|
||||
// Tự động tìm và nạp file .env nằm cùng thư mục với folder config (tức là trong backend/.env)
|
||||
dotenv.config({ path: path.join(__dirname, '../.env') });
|
||||
|
||||
const connectDB = async () => {
|
||||
try {
|
||||
const dbURI = process.env.MONGODB_URI;
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
"bullmq": "^5.8.0",
|
||||
"cors": "^2.8.6",
|
||||
"dotenv": "^17.4.2",
|
||||
"exiftool-vendored": "^26.4.0",
|
||||
"exiftool-vendored": "^29.2.0",
|
||||
"express": "^5.2.1",
|
||||
"express-fileupload": "^1.5.2",
|
||||
"jsonwebtoken": "^9.0.3",
|
||||
|
||||
@@ -4,6 +4,20 @@ const User = require('../models/User');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
/**
|
||||
* @route GET /api/auth/init-status
|
||||
* @desc Check if the system has at least one admin
|
||||
* @access Public
|
||||
*/
|
||||
router.get('/init-status', async (req, res) => {
|
||||
try {
|
||||
const userCount = await User.countDocuments();
|
||||
res.json({ initialized: userCount > 0 });
|
||||
} catch (error) {
|
||||
res.status(500).json({ message: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* @route POST /api/auth/register
|
||||
* @desc Register a new user
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
const { Queue } = require('bullmq');
|
||||
const IORedis = require('ioredis');
|
||||
|
||||
// Cấu hình kết nối Redis (Mặc định localhost:6379)
|
||||
// Cấu hình kết nối Redis sử dụng biến môi trường từ Docker
|
||||
const connection = new IORedis({
|
||||
host: process.env.REDIS_HOST || '127.0.0.1',
|
||||
port: process.env.REDIS_PORT || 6379,
|
||||
maxRetriesPerRequest: null
|
||||
});
|
||||
|
||||
|
||||
@@ -17,10 +17,17 @@ const { imageQueue } = require('./imageQueue');
|
||||
const { deleteSceneCascade, propagateScenePrivacy } = require('../utils/sceneHelper');
|
||||
|
||||
const uploadDir = process.env.UPLOAD_DIR ? path.resolve(process.env.UPLOAD_DIR) : path.join(__dirname, '../uploads');
|
||||
const tempDir = path.join(uploadDir, 'temp');
|
||||
|
||||
const storage = multer.diskStorage({
|
||||
destination: (req, file, cb) => cb(null, tempDir),
|
||||
destination: (req, file, cb) => {
|
||||
// req.user đã được populate bởi protect middleware
|
||||
const userId = req.user._id.toString();
|
||||
const userTempDir = path.join(uploadDir, userId, 'temp');
|
||||
if (!fs.existsSync(userTempDir)) {
|
||||
fs.mkdirSync(userTempDir, { recursive: true });
|
||||
}
|
||||
cb(null, userTempDir);
|
||||
},
|
||||
filename: (req, file, cb) => cb(null, `${Date.now()}_${crypto.randomBytes(4).toString('hex')}${path.extname(file.originalname)}`)
|
||||
});
|
||||
const upload = multer({ storage });
|
||||
@@ -54,8 +61,16 @@ router.post('/', protect, uploadSinglePanorama, checkQuota, async (req, res) =>
|
||||
const latitude = Number(lat) || 0;
|
||||
const longitude = Number(lng) || 0;
|
||||
const tempFilePath = req.file.path;
|
||||
|
||||
// Tạo thư mục lưu trữ chính cho User nếu chưa có
|
||||
const userId = req.user._id.toString();
|
||||
const userUploadDir = path.join(uploadDir, userId);
|
||||
if (!fs.existsSync(userUploadDir)) {
|
||||
fs.mkdirSync(userUploadDir, { recursive: true });
|
||||
}
|
||||
|
||||
const processedFileName = `processed_${req.file.filename}.jpg`;
|
||||
const processedFilePath = path.join(uploadDir, processedFileName);
|
||||
const processedFilePath = path.join(userUploadDir, processedFileName);
|
||||
|
||||
const asset = new Asset({
|
||||
filePath: tempFilePath,
|
||||
@@ -143,7 +158,6 @@ router.get('/', optionalAuth, async (req, res) => {
|
||||
};
|
||||
}
|
||||
|
||||
console.log(`[SceneRoutes] GET /api/scenes - Final Query for user ${req.user?._id || 'Guest'}:`, JSON.stringify(finalQuery));
|
||||
const scenes = await Scene.find(finalQuery)
|
||||
.populate('createdBy', 'username')
|
||||
.populate('tourId') // Nạp thông tin Tour để Frontend nhận diện
|
||||
@@ -154,6 +168,70 @@ router.get('/', optionalAuth, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// @route GET /api/share/:id
|
||||
// @desc Trang trung gian hỗ trợ Open Graph (Facebook, Zalo,...)
|
||||
router.get('/share/:id', async (req, res) => {
|
||||
try {
|
||||
const scene = await Scene.findById(req.params.id).populate('tourId');
|
||||
if (!scene) return res.status(404).send('Không tìm thấy cảnh 3D');
|
||||
|
||||
const tour = scene.tourId;
|
||||
const title = tour ? tour.name : (scene.name || 'Virtual Tour 3D');
|
||||
const description = tour ? tour.description : (scene.description || 'Khám phá không gian 360 độ chân thực');
|
||||
|
||||
// Xác định token (ưu tiên query token, sau đó là token của tour/scene nếu có)
|
||||
const token = req.query.token || scene.shareToken || (tour && tour.shareToken) || '';
|
||||
|
||||
// Xử lý Protocol/Host để tạo URL tuyệt đối
|
||||
const protocol = req.headers['x-forwarded-proto'] || req.protocol;
|
||||
const host = req.get('host');
|
||||
const baseUrl = `${protocol}://${host}`;
|
||||
|
||||
// URL ảnh thumbnail gọi sang Asset API với cờ watermark
|
||||
const imageUrl = `${baseUrl}/api/assets/view/${scene.assetId}?watermark=true${token ? '&token=' + token : ''}`;
|
||||
|
||||
// URL thực tế của ứng dụng để redirect người dùng
|
||||
const appUrl = `${baseUrl}/?sceneId=${scene._id}${token ? '&token=' + token : ''}`;
|
||||
|
||||
res.send(`
|
||||
<!DOCTYPE html>
|
||||
<html lang="vi">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>${title}</title>
|
||||
|
||||
<!-- Open Graph / Facebook -->
|
||||
<meta property="og:type" content="website">
|
||||
<meta property="og:url" content="${appUrl}">
|
||||
<meta property="og:title" content="${title}">
|
||||
<meta property="og:description" content="${description}">
|
||||
<meta property="og:image" content="${imageUrl}">
|
||||
<meta property="og:image:width" content="1200">
|
||||
<meta property="og:image:height" content="630">
|
||||
|
||||
<!-- Twitter -->
|
||||
<meta property="twitter:card" content="summary_large_image">
|
||||
<meta property="twitter:title" content="${title}">
|
||||
<meta property="twitter:description" content="${description}">
|
||||
<meta property="twitter:image" content="${imageUrl}">
|
||||
|
||||
<!-- Chuyển hướng người dùng về trang chủ để mở viewer -->
|
||||
<script type="text/javascript">
|
||||
window.location.href = "${appUrl}";
|
||||
</script>
|
||||
</head>
|
||||
<body style="font-family: sans-serif; text-align: center; padding-top: 50px; background: #1a1a1a; color: #fff;">
|
||||
<h2>${title}</h2>
|
||||
<p>Đang tải không gian 3D, vui lòng đợi...</p>
|
||||
</body>
|
||||
</html>`);
|
||||
} catch (error) {
|
||||
console.error("[Share Error]", error);
|
||||
res.status(500).send('Lỗi máy chủ');
|
||||
}
|
||||
});
|
||||
|
||||
// @route GET /api/scenes/:id
|
||||
router.get('/:id', optionalAuth, async (req, res) => {
|
||||
try {
|
||||
@@ -294,8 +372,14 @@ router.put('/:id', protect, uploadSinglePanorama, async (req, res) => {
|
||||
}
|
||||
|
||||
if (req.file) {
|
||||
const userId = req.user._id.toString();
|
||||
const userUploadDir = path.join(uploadDir, userId);
|
||||
if (!fs.existsSync(userUploadDir)) {
|
||||
fs.mkdirSync(userUploadDir, { recursive: true });
|
||||
}
|
||||
|
||||
const processedFileName = `processed_${req.file.filename}.jpg`;
|
||||
const processedFilePath = path.join(uploadDir, processedFileName);
|
||||
const processedFilePath = path.join(userUploadDir, processedFileName);
|
||||
await resizeTo8K(req.file.path, processedFilePath);
|
||||
await injectGPSCoordinates(processedFilePath, scene.gps.lat, scene.gps.lng);
|
||||
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
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();
|
||||
+4
-1
@@ -1,9 +1,12 @@
|
||||
const crypto = require('crypto');
|
||||
// Đảm bảo crypto có sẵn toàn cục cho các thư viện cũ hoặc plugin mongoose
|
||||
global.crypto = crypto;
|
||||
|
||||
const express = require('express');
|
||||
const cors = require('cors');
|
||||
const path = require('path');
|
||||
const dotenv = require('dotenv');
|
||||
const connectDB = require('./config/db');
|
||||
|
||||
// Cấu hình môi trường
|
||||
dotenv.config();
|
||||
|
||||
|
||||
Reference in New Issue
Block a user