Certainly! I'll integrate your existing server-side and client-side code with the device-specific GIF functionality. Below is the complete implementation:
Server-side (Node.js with Express)
const express = require('express');
const path = require('path');
const fs = require('fs').promises;
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const app = express();
const port = 3000;
const JWT_SECRET = process.env.JWT_SECRET || 'your_secure_jwt_secret';
const ADMIN_PASSWORD_HASH = '$2a$10$ZGoPtwYYkpS3h0tUx.v4ue5X5P8zkd/ne6hJOJ4cY62jJLFV3GM4O';
app.use(express.json());
app.use(express.static(path.join(__dirname, 'public')));
app.post('/api/login', async (req, res) => {
const { password } = req.body;
if (!password) {
return res.status(400).send('Password is required');
}
try {
const isPasswordValid = await bcrypt.compare(password, ADMIN_PASSWORD_HASH);
if (!isPasswordValid) {
return res.status(401).send('Invalid password');
}
const token = jwt.sign({ role: 'admin' }, JWT_SECRET, { expiresIn: '1h' });
res.json({ token });
} catch (err) {
console.error('Failed to login:', err);
res.sendStatus(500);
}
});
function authenticateJWT(req, res, next) {
const authHeader = req.headers.authorization;
const token = authHeader && authHeader.split(' ')[1];
if (token) {
jwt.verify(token, JWT_SECRET, (err, user) => {
if (err) {
return res.sendStatus(403);
}
req.user = user;
next();
});
} else {
res.sendStatus(401);
}
}
app.get('/api/data', authenticateJWT, async (req, res) => {
if (req.user.role !== 'admin') {
return res.sendStatus(403);
}
try {
const visitorsData = await fs.readFile('visitors.json', 'utf8').catch(() => '[]');
const statsData = await fs.readFile('stats.json', 'utf8').catch(() => '{}');
res.json({
visitors: JSON.parse(visitorsData),
stats: JSON.parse(statsData)
});
} catch (err) {
console.error('Failed to retrieve data:', err);
res.sendStatus(500);
}
});
app.get('/api/check-new-user', async (req, res) => {
const visitorIp = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
try {
const content = await fs.readFile('visitors.json', 'utf8').catch(() => '[]');
const visitors = JSON.parse(content);
const newUser = !visitors.some(visitor => visitor.ip === visitorIp);
res.json(newUser);
} catch (err) {
console.error('Failed to check new user:', err);
res.sendStatus(500);
}
});
app.post('/api/track', async (req, res) => {
const visitorInfo = req.body;
const visitorIp = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
try {
let content = await fs.readFile('visitors.json', 'utf8').catch(() => '[]');
const visitors = JSON.parse(content);
const currentTime = new Date().toISOString();
let visitorRecord = visitors.find(visitor => visitor.ip === visitorIp);
if (visitorRecord) {
visitorRecord.count++;
visitorRecord.lastVisit = currentTime;
} else {
visitors.push({
ip: visitorIp,
deviceInfo: visitorInfo.deviceInfo,
firstVisit: currentTime,
lastVisit: currentTime,
count: 1
});
}
await fs.writeFile('visitors.json', JSON.stringify(visitors, null, 2));
res.sendStatus(200);
} catch (err) {
console.error('Failed to process visitor data:', err);
res.sendStatus(500);
}
});
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
HTML (Public/index.html)
Place this HTML in your public/index.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Welcome</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div id="introGif" class="intro-gif">
<img id="desktopGif" src="desktopIntro.gif" alt="Desktop Intro GIF" class="intro-image">
<img id="mobileGif" src="mobileIntro.gif" alt="Mobile Intro GIF" class="intro-image">
</div>
<div id="mainContent" style="opacity: 0;">
<!-- Main content goes here -->
</div>
<script src="script.js"></script>
</body>
</html>
CSS (Public/styles.css)
body {
margin: 0;
padding: 0;
height: 100vh;
width: 100vw;
overflow: hidden;
background-size: cover;
background-repeat: no-repeat;
background-position: center;
display: flex;
flex-direction: column;
justify-content: space-between;
}
.container {
position: relative;
z-index: 1;
color: white;
text-align: center;
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
justify-content: flex-start;
padding-top: 10vh;
}
.intro-gif {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: black;
display: none; /* Hidden by default */
justify-content: center;
align-items: center;
z-index: 1000;
}
.intro-image {
width: 100%;
height: 100%;
object-fit: cover;
display: none; /* Display only one based on the device */
}
.loading-wrapper {
position: absolute;
bottom: 50px;
left: 50%;
transform: translateX(-50%);
z-index: 2;
}
.loading-gif {
width: 50px;
height: 50px;
border-radius: 50%;
}
.title {
font-size: 3vw;
font-weight: bold;
margin-bottom: 10px;
}
.countdown-timer {
font-size: 2.5vw;
font-weight: bold;
}
.random-text {
font-size: 2vw;
margin-top: 10px;
}
@media (max-width: 768px) {
.loading-wrapper {
bottom: auto;
top: 70%;
}
.random-text {
margin-top: 20px;
}
.title {
font-size: 9vw;
}
.countdown-timer {
font-size: 7vw;
}
.random-text {
font-size: 6vw;
}
}
JavaScript (Public/script.js)
function detectDeviceType() {
const userAgent = navigator.userAgent || navigator.vendor || window.opera;
if (/android|iP(hone|od|ad)|mobile|tablet/i.test(userAgent)) {
return 'mobile';
} else {
return 'desktop';
}
}
async function isUserNew() {
const response = await fetch('/api/check-new-user');
if (!response.ok) {
console.error('Failed to check new user');
return false;
}
return response.json();
}
async function showIntroGif() {
const newUser = await isUserNew();
const introElement = document.getElementById('introGif');
const mainContent = document.getElementById('mainContent');
const deviceType = detectDeviceType();
if (newUser) {
introElement.style.display = 'flex';
if (deviceType === 'mobile') {
document.getElementById('mobileGif').style.display = 'block';
} else {
document.getElementById('desktopGif').style.display = 'block';
}
setTimeout(() => {
introElement.style.display = 'none';
document.body.style.overflow = 'auto';
mainContent.style.opacity = 1;
}, 5000);
} else {
mainContent.style.opacity = 1;
document.body.style.overflow = 'auto';
}
}
showIntroGif();
function getDeviceInfo() {
return {
userAgent: navigator.userAgent,
platform: navigator.platform
};
}
async function sendVisitorInfo() {
const deviceInfo = getDeviceInfo();
const response = await fetch('/api/track', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
deviceInfo: deviceInfo,
timestamp: new Date().toISOString()
})
});
if (!response.ok) {
console.error('Failed to send visitor info');
}
}
function startCountdown(startDate, endDate) {
const countdownElement = document.getElementById("countdown");
function updateCountdown() {
const now = new Date().getTime();
const distance = endDate - now;
let totalSeconds = Math.floor(distance / 1000);
const hours = Math.floor(totalSeconds / 3600);
totalSeconds %= 3600;
const minutes = Math.floor(totalSeconds / 60);
const seconds = totalSeconds % 60;
countdownElement.innerHTML =
(hours < 10 ? '0' : '') + hours + ":" +
(minutes < 10 ? '0' : '') + minutes + ":" +
(seconds < 10 ? '0' : '') + seconds;
if (distance < 0) {
clearInterval(interval);
countdownElement.innerHTML = "00:00:00";
}
}
const interval = setInterval(updateCountdown, 1000);
updateCountdown();
}
const words = ["Когда то загрузиться!", "М...", "Город? Разница?", "🤔", "Скоро?", "Время покажет?", ":)", "Как бы ни так!", "Что нового?", "MMY"];
const randomTextElement = document.getElementById("random-text");
let shuffledWords = [];
let currentIndex = 0;
function shuffleWords(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
}
function updateRandomText() {
if (currentIndex >= shuffledWords.length) {
shuffledWords = [...words];
shuffleWords(shuffledWords);
currentIndex = 0;
}
randomTextElement.innerHTML = shuffledWords[currentIndex];
currentIndex++;
}
setInterval(updateRandomText, 6000);
updateRandomText();
window.onload = () => {
sendVisitorInfo();
const startDate = new Date('2024-10-01T00:00:00').getTime();
const endDate = new Date('2024-10-10T00:00:00').getTime();
startCountdown(startDate, endDate);
};
Explanation
- Server: Handles authentication, visitor tracking, and serves static files.
- HTML: Basic structure for the webpage, including different GIFs for mobile and desktop.
- CSS: Styles including responsiveness for smaller screens.
- JavaScript: Device detection logic to toggle between desktop and mobile GIFs, along with additional functionality such as visitor tracking and countdown logic.
Ensure all file paths are correctly set up and that desktopIntro.gif and mobileIntro.gif are in the appropriate location in your public directory.