This commit is contained in:
Ccjcarkbla
2026-06-10 21:34:22 -04:00
parent 74c53de8c5
commit eb607dfe5e
21 changed files with 4758 additions and 0 deletions
+797
View File
@@ -0,0 +1,797 @@
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const bodyParser = require('body-parser');
const { Sequelize, DataTypes } = require('sequelize');
const path = require('path');
const multer = require('multer');
const fs = require('fs');
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(express.static('public'));
const authenticateToken = (req, res, next) => {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
console.log('Received token:', token);
if (!token) {
console.log('No token provided');
return res.sendStatus(401);
}
jwt.verify(token, process.env.JWT_SECRET, (err, user) => {
if (err) {
console.log('Token verification failed:', err);
return res.sendStatus(403);
}
console.log('Token verified, user:', user);
req.user = user;
next();
});
};
// Middleware to check admin role
const authenticateAdmin = async (req, res, next) => {
console.log('Checking admin role for user:', req.user);
try {
const user = await User.findByPk(req.user.id);
if (user && user.role === 'Admin') {
console.log('User is admin');
next();
} else {
console.log('User is not admin');
return res.sendStatus(403); // Forbidden
}
} catch (error) {
console.log('Error verifying admin role:', error);
return res.sendStatus(500);
}
};
const sequelize = new Sequelize({
dialect: 'sqlite',
storage: path.join(__dirname, 'database.sqlite'),
retry: {
match: [
/SQLITE_BUSY/,
],
name: 'query',
max: 5
}
});
const User = sequelize.define('User', {
username: {
type: DataTypes.STRING,
allowNull: false,
unique: true
},
password: {
type: DataTypes.STRING,
allowNull: false
},
role: {
type: DataTypes.ENUM('Admin', 'Coach'),
allowNull: false,
defaultValue: 'Coach'
}
});
const Video = sequelize.define('Video', {
filename: {
type: DataTypes.STRING,
allowNull: false
},
description: {
type: DataTypes.STRING,
allowNull: true
},
category: {
type: DataTypes.STRING,
allowNull: true
}
});
const Category = sequelize.define('Category', {
name: {
type: DataTypes.STRING,
allowNull: false,
unique: true
}
});
const Workout = sequelize.define('Workout', {
video1: {
type: DataTypes.INTEGER,
allowNull: false,
references: {
model: Video,
key: 'id'
}
},
video2: {
type: DataTypes.INTEGER,
allowNull: true, // Allow null values
references: {
model: Video,
key: 'id'
}
},
video3: {
type: DataTypes.INTEGER,
allowNull: true,
references: {
model: Video,
key: 'id'
}
},
video4: {
type: DataTypes.INTEGER,
allowNull: true,
references: {
model: Video,
key: 'id'
}
},
number1: {
type: DataTypes.INTEGER,
allowNull: false
},
number2: {
type: DataTypes.INTEGER,
allowNull: true // Allow null values
},
number3: {
type: DataTypes.INTEGER,
allowNull: true
},
number4: {
type: DataTypes.INTEGER,
allowNull: true
},
name: {
type: DataTypes.STRING,
allowNull: false
},
workoutDate: {
type: DataTypes.DATE,
allowNull: false
},
createdAt: {
type: DataTypes.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP')
}
}, {
timestamps: true,
updatedAt: false
});
const Timer = sequelize.define('Timer', {
totalTime: {
type: DataTypes.INTEGER,
allowNull: false
},
setTime: {
type: DataTypes.INTEGER,
allowNull: false
},
restTime: {
type: DataTypes.INTEGER,
allowNull: false
},
moveTime: {
type: DataTypes.INTEGER,
allowNull: false
},
setCount: {
type: DataTypes.INTEGER,
allowNull: false
},
exerciseCount: {
type: DataTypes.INTEGER,
allowNull: false
},
lapCount: {
type: DataTypes.INTEGER,
allowNull: false
},
createdAt: {
type: DataTypes.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP')
}
}, {
timestamps: true,
updatedAt: false
});
Workout.belongsTo(Video, { as: 'video1Details', foreignKey: 'video1' });
Workout.belongsTo(Video, { as: 'video2Details', foreignKey: 'video2' });
Workout.belongsTo(Video, { as: 'video3Details', foreignKey: 'video3' });
Workout.belongsTo(Video, { as: 'video4Details', foreignKey: 'video4' });
//Crossfit DB
const CrossfitWorkout = sequelize.define('CrossfitWorkout', {
name: {
type: DataTypes.STRING,
allowNull: false
},
workoutDate: {
type: DataTypes.DATE,
allowNull: false
},
workoutItems: {
type: DataTypes.JSON, // Storing as JSON to handle ordered lists
allowNull: false
},
createdAt: {
type: DataTypes.DATE,
allowNull: false,
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP')
}
}, {
timestamps: true,
updatedAt: false
});
sequelize.sync().then(() => {
console.log('Database synchronized!');
const initialCategories = [
'Arm Exercises',
'Leg Exercises',
'Push Exercises',
'Pull Exercises',
'Cardio Exercises',
'Core Exercises'
];
initialCategories.forEach(async (name) => {
try {
const [category, created] = await Category.findOrCreate({ where: { name } });
if (created) {
console.log(`Category '${name}' created`);
}
} catch (error) {
console.error(`Failed to create initial category '${name}':`, error);
}
});
});
const storage = multer.diskStorage({
destination: './public/uploads/',
filename: (req, file, cb) => {
cb(null, Date.now() + path.extname(file.originalname));
}
});
const upload = multer({ storage: storage });
// Route definitions...
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.get('/register', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'register.html'));
});
app.get('/dashboard.html', authenticateToken, (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'dashboard.html'));
});
app.get('/upload.html', authenticateToken, (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'upload.html'));
});
app.get('/create-workout.html', authenticateToken, (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'create-workout.html'));
});
app.get('/videos.html', authenticateToken, (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'videos.html'));
});
app.get('/workouts.html', authenticateToken, (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'workouts.html'));
});
app.get('/categories.html', authenticateToken, (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'categories.html'));
});
app.get('/create-timer.html', authenticateToken, (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'create-timer.html'));
});
app.get('/manage-timers.html', authenticateToken, (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'manage-timers.html'));
});
app.get('/timer.html', authenticateToken, (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'timer.html'));
});
app.get('/workout/:id', authenticateToken, (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'workout.html'));
});
app.get('/create-crossfit-workout.html', authenticateToken, (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'create-crossfit-workout.html'));
});
app.get('/crossfit-workouts.html', authenticateToken, (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'crossfit-workouts.html'));
});
// Route to fetch all users
app.get('/users', authenticateToken, authenticateAdmin, async (req, res) => {
try {
const users = await User.findAll({ attributes: ['id', 'username', 'role'] });
res.json(users);
} catch (error) {
console.error('Error fetching users:', error);
res.status(500).send('Internal Server Error');
}
});
// Create user endpoint
app.post('/users', authenticateToken, authenticateAdmin, async (req, res) => {
const { username, password, role } = req.body;
const hashedPassword = await bcrypt.hash(password, 10);
try {
const user = await User.create({ username, password: hashedPassword, role });
res.json(user);
} catch (error) {
console.error('Error creating user:', error);
res.status(400).send('Username already taken');
}
});
// Delete user endpoint
app.delete('/users/:id', authenticateToken, authenticateAdmin, async (req, res) => {
try {
const user = await User.findByPk(req.params.id);
if (user) {
await user.destroy();
res.send('User deleted');
} else {
res.status(404).send('User not found');
}
} catch (error) {
console.error('Error deleting user:', error);
res.status(500).send('Internal Server Error');
}
});
// Change role endpoint
app.put('/users/:id/role', authenticateToken, authenticateAdmin, async (req, res) => {
const { role } = req.body;
try {
const user = await User.findByPk(req.params.id);
if (user) {
user.role = role;
await user.save();
res.json(user);
} else {
res.status(404).send('User not found');
}
} catch (error) {
console.error('Error changing role:', error);
res.status(500).send('Internal Server Error');
}
});
// Reset password endpoint
app.put('/users/:id/password', authenticateToken, authenticateAdmin, async (req, res) => {
const { password } = req.body;
const hashedPassword = await bcrypt.hash(password, 10);
try {
const user = await User.findByPk(req.params.id);
if (user) {
user.password = hashedPassword;
await user.save();
res.json(user);
} else {
res.status(404).send('User not found');
}
} catch (error) {
console.error('Error resetting password:', error);
res.status(500).send('Internal Server Error');
}
});
app.get('/workout-data/:id', authenticateToken, async (req, res) => {
try {
const workout = await Workout.findByPk(req.params.id, {
include: [
{ model: Video, as: 'video1Details', attributes: ['filename'] },
{ model: Video, as: 'video2Details', attributes: ['filename'] },
{ model: Video, as: 'video3Details', attributes: ['filename'] },
{ model: Video, as: 'video4Details', attributes: ['filename'] }
]
});
if (!workout) {
return res.status(404).send('Workout not found');
}
// Respond with the workout and its associated videos
res.json({
video1: workout.video1Details ? workout.video1Details.filename : null,
video2: workout.video2Details ? workout.video2Details.filename : null,
video3: workout.video3Details ? workout.video3Details.filename : null,
video4: workout.video4Details ? workout.video4Details.filename : null,
number1: workout.number1,
number2: workout.number2,
number3: workout.number3,
number4: workout.number4
});
} catch (error) {
console.error('Error fetching workout data:', error);
res.status(500).send('Internal Server Error');
}
});
// Profile route to return user info
app.get('/profile', authenticateToken, async (req, res) => {
const user = await User.findByPk(req.user.id);
if (user) {
console.log('User fetched:', user);
res.json({ id: user.id, username: user.username, role: user.role });
} else {
res.status(404).send('User not found');
}
});
app.get('/workouts-details', authenticateToken, async (req, res) => {
try {
const page = parseInt(req.query.page) || 1; // Default to page 1
const limit = parseInt(req.query.limit) || 50; // Default to 20 items per page
const offset = (page - 1) * limit;
const { count, rows: workouts } = await Workout.findAndCountAll({
include: [
{ model: Video, as: 'video1Details', attributes: ['filename', 'description', 'category'] },
{ model: Video, as: 'video2Details', attributes: ['filename', 'description', 'category'] },
{ model: Video, as: 'video3Details', attributes: ['filename', 'description', 'category'] },
{ model: Video, as: 'video4Details', attributes: ['filename', 'description', 'category'] }
],
attributes: ['id', 'name', 'createdAt'],
offset,
limit
});
res.json({
workouts,
total: count,
totalPages: Math.ceil(count / limit),
currentPage: page
});
} catch (error) {
console.error('Error fetching workouts:', error);
res.status(500).send('Internal Server Error');
}
});
app.get('/today-workouts', authenticateToken, async (req, res) => {
try {
const today = new Date();
today.setHours(0, 0, 0, 0);
const tomorrow = new Date(today);
tomorrow.setDate(today.getDate() + 1);
const workouts = await Workout.findAll({
where: {
workoutDate: {
[Sequelize.Op.gte]: today,
[Sequelize.Op.lt]: tomorrow
}
},
include: [
{ model: Video, as: 'video1Details', attributes: ['filename', 'description', 'category'] },
{ model: Video, as: 'video2Details', attributes: ['filename', 'description', 'category'] },
{ model: Video, as: 'video3Details', attributes: ['filename', 'description', 'category'] },
{ model: Video, as: 'video4Details', attributes: ['filename', 'description', 'category'] }
]
});
res.json(workouts);
} catch (error) {
console.error('Error fetching workouts:', error);
res.status(500).send('Internal Server Error');
}
});
app.get('/total-workouts', authenticateToken, async (req, res) => {
try {
const totalWorkouts = await Workout.count();
res.json({ count: totalWorkouts });
} catch (error) {
console.error('Error fetching total workouts:', error);
res.status(500).send('Internal Server Error');
}
});
app.get('/videos', authenticateToken, async (req, res) => {
try {
const { category } = req.query;
const whereClause = category && category !== 'All' ? { category } : {};
const videos = await Video.findAll({
where: whereClause,
attributes: ['id', 'filename', 'description', 'category'],
order: [['category', 'ASC']]
});
res.json(videos);
} catch (error) {
console.error('Error fetching videos:', error);
res.status(500).send('Internal Server Error');
}
});
app.get('/categories', authenticateToken, async (req, res) => {
try {
const categories = await Category.findAll({ attributes: ['id', 'name'] });
res.json(categories);
} catch (error) {
console.error('Error fetching categories:', error);
res.status(500).send('Internal Server Error');
}
});
app.post('/categories', authenticateToken, async (req, res) => {
const { name } = req.body;
try {
const category = await Category.create({ name });
res.json(category);
} catch (error) {
console.error('Error adding category:', error);
res.status(500).send('Internal Server Error');
}
});
app.delete('/categories/:id', authenticateToken, async (req, res) => {
try {
const category = await Category.findByPk(req.params.id);
if (category) {
await category.destroy();
res.send('Category deleted');
} else {
res.status(404).send('Category not found');
}
} catch (error) {
console.error('Error deleting category:', error);
res.status(500).send('Internal Server Error');
}
});
app.post('/register', async (req, res) => {
const { username, password } = req.body;
const hashedPassword = await bcrypt.hash(password, 10);
try {
const user = await User.create({ username, password: hashedPassword });
res.send('User registered');
} catch (error) {
console.error('Error registering user:', error);
res.status(400).send('Username already taken');
}
});
app.post('/login', async (req, res) => {
const { username, password } = req.body;
const user = await User.findOne({ where: { username } });
if (!user) {
console.log('User not found');
return res.status(400).send('User not found');
}
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
console.log('Invalid credentials');
return res.status(400).send('Invalid credentials');
}
const token = jwt.sign({ id: user.id }, process.env.JWT_SECRET, {expiresIn: '7d'});
console.log('Token generated:', token);
res.json({ token });
});
app.post('/upload', authenticateToken, upload.single('video'), async (req, res) => {
console.log('Upload attempt');
console.log('Request body:', req.body);
console.log('Uploaded file:', req.file);
const { description, category } = req.body;
if (!req.file) {
return res.status(400).send('No file uploaded');
}
try {
const video = await Video.create({ filename: req.file.filename, description, category });
res.send('Video uploaded');
} catch (error) {
console.error('Error uploading video:', error);
res.status(500).send('Internal Server Error');
}
});
app.post('/create-workout', authenticateToken, async (req, res) => {
const { name, workoutDate, video1, video2, video3, video4, number1, number2, number3, number4 } = req.body;
try {
const workout = await Workout.create({
name,
workoutDate,
video1,
number1,
video2: video2 || null,
number2: number2 || null,
video3: video3 || null,
number3: number3 || null,
video4: video4 || null,
number4: number4 || null,
});
res.json({ workoutId: workout.id });
} catch (error) {
console.error('Error creating workout:', error);
res.status(500).send('Internal Server Error');
}
});
// Fetch all CrossFit workouts
app.get('/crossfit-workouts', authenticateToken, async (req, res) => {
try {
const workouts = await CrossfitWorkout.findAll();
res.json(workouts);
} catch (error) {
console.error('Error fetching CrossFit workouts:', error);
res.status(500).send('Internal Server Error');
}
});
// Endpoint to handle creation of CrossFit workout
app.post('/create-crossfit-workout', authenticateToken, async (req, res) => {
console.log('Received request body:', req.body);
const { name, workoutDate, rawText } = req.body;
try {
if (!name || !workoutDate || !rawText) {
console.error('Validation failed: Missing required fields');
return res.status(400).send('All fields are required');
}
// Convert raw text into an ordered list
const workoutItems = rawText.split('\n').map(item => item.trim()).filter(item => item);
const crossfitWorkout = await CrossfitWorkout.create({
name,
workoutDate,
workoutItems
});
res.json({ workoutId: crossfitWorkout.id });
} catch (error) {
console.error('Error creating CrossFit workout:', error.message); // Log the error message
console.error('Error details:', error); // Log the entire error object
res.status(500).send('Internal Server Error');
}
});
app.post('/create-timer', authenticateToken, async (req, res) => {
console.log('Create timer request received:', req.body);
const { totalTime, setTime, restTime, moveTime, setCount, exerciseCount, lapCount } = req.body;
try {
const timer = await Timer.create({ totalTime, setTime, restTime, moveTime, setCount, exerciseCount, lapCount });
console.log('Timer created:', timer);
res.json(timer);
} catch (error) {
console.error('Error creating timer:', error);
res.status(500).send('Internal Server Error');
}
});
app.get('/timers', authenticateToken, async (req, res) => {
try {
const timers = await Timer.findAll();
res.json(timers);
} catch (error) {
console.error('Error fetching timers:', error);
res.status(500).send('Internal Server Error');
}
});
app.get('/timers/:id', authenticateToken, async (req, res) => {
try {
const timer = await Timer.findByPk(req.params.id);
if (!timer) {
return res.status(404).send('Timer not found');
}
res.json(timer);
} catch (error) {
console.error('Error fetching timer:', error);
res.status(500).send('Internal Server Error');
}
});
app.delete('/timers/:id', authenticateToken, async (req, res) => {
try {
const timer = await Timer.findByPk(req.params.id);
if (timer) {
await timer.destroy();
res.send('Timer deleted');
} else {
res.status(404).send('Timer not found');
}
} catch (error) {
console.error('Error deleting timer:', error);
res.status(500).send('Internal Server Error');
}
});
app.delete('/videos/:id', authenticateToken, async (req, res) => {
try {
const video = await Video.findByPk(req.params.id);
if (video) {
await video.destroy();
res.send('Video deleted');
} else {
res.status(404).send('Video not found');
}
} catch (error) {
console.error('Error deleting video:', error);
res.status(500).send('Internal Server Error');
}
});
app.delete('/workouts/:id', authenticateToken, async (req, res) => {
try {
const workout = await Workout.findByPk(req.params.id);
if (workout) {
await workout.destroy();
res.send('Workout deleted');
} else {
res.status(404).send('Workout not found');
}
} catch (error) {
console.error('Error deleting workout:', error);
res.status(500).send('Internal Server Error');
}
});
// Endpoint to delete a CrossFit workout
app.delete('/crossfit-workout/:id', authenticateToken, authenticateAdmin, async (req, res) => {
try {
const workout = await CrossfitWorkout.findByPk(req.params.id);
if (!workout) {
return res.status(404).send('Workout not found');
}
await workout.destroy();
res.send('Workout deleted successfully');
} catch (error) {
console.error('Error deleting CrossFit workout:', error);
res.status(500).send('Internal Server Error');
}
});
// Endpoint to handle logo upload
app.post('/upload-logo', authenticateToken, authenticateAdmin, upload.single('logo'), (req, res) => {
if (!req.file) {
return res.status(400).send('No file uploaded');
}
const logoPath = path.join(__dirname, 'public', 'VitLogo.png');
fs.rename(req.file.path, logoPath, (err) => {
if (err) {
console.error('Error replacing logo:', err);
return res.status(500).send('Internal Server Error');
}
res.send('Logo uploaded');
});
});
app.post('/logout', authenticateToken, (req, res) => {
// Clear the token on the client side
res.json({ message: 'Logged out successfully' });
});
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
+63
View File
@@ -0,0 +1,63 @@
nohup: ignoring input
Server running on http://localhost:3000
Executing (default): SELECT name FROM sqlite_master WHERE type='table' AND name='Users';
Executing (default): PRAGMA INDEX_LIST(`Users`)
Executing (default): PRAGMA INDEX_INFO(`sqlite_autoindex_Users_1`)
Executing (default): SELECT name FROM sqlite_master WHERE type='table' AND name='Videos';
Executing (default): PRAGMA INDEX_LIST(`Videos`)
Executing (default): SELECT name FROM sqlite_master WHERE type='table' AND name='Categories';
Executing (default): PRAGMA INDEX_LIST(`Categories`)
Executing (default): PRAGMA INDEX_INFO(`sqlite_autoindex_Categories_1`)
Executing (default): SELECT name FROM sqlite_master WHERE type='table' AND name='Workouts';
Executing (default): PRAGMA INDEX_LIST(`Workouts`)
Executing (default): SELECT name FROM sqlite_master WHERE type='table' AND name='Timers';
Executing (default): PRAGMA INDEX_LIST(`Timers`)
Database synchronized!
Executing (f3127069-80dc-4acf-9144-25766b20537c): BEGIN DEFERRED TRANSACTION;
Executing (8ab7629c-5dda-4aff-ac62-607b03ec0c4e): BEGIN DEFERRED TRANSACTION;
Executing (d816c048-7c0a-487b-a0aa-d4397b972ef9): BEGIN DEFERRED TRANSACTION;
Executing (cfc63f51-a817-4979-ade8-9158ba6e6fec): BEGIN DEFERRED TRANSACTION;
Executing (31970bb6-aa44-4789-8f24-ee3d11e0d718): BEGIN DEFERRED TRANSACTION;
Executing (37ec246f-8937-4596-a959-9c8dd979ccf7): BEGIN DEFERRED TRANSACTION;
Executing (f3127069-80dc-4acf-9144-25766b20537c): SELECT `id`, `name`, `createdAt`, `updatedAt` FROM `Categories` AS `Category` WHERE `Category`.`name` = 'Arm Exercises';
Executing (8ab7629c-5dda-4aff-ac62-607b03ec0c4e): SELECT `id`, `name`, `createdAt`, `updatedAt` FROM `Categories` AS `Category` WHERE `Category`.`name` = 'Leg Exercises';
Executing (d816c048-7c0a-487b-a0aa-d4397b972ef9): SELECT `id`, `name`, `createdAt`, `updatedAt` FROM `Categories` AS `Category` WHERE `Category`.`name` = 'Pull Exercises';
Executing (cfc63f51-a817-4979-ade8-9158ba6e6fec): SELECT `id`, `name`, `createdAt`, `updatedAt` FROM `Categories` AS `Category` WHERE `Category`.`name` = 'Push Exercises';
Executing (31970bb6-aa44-4789-8f24-ee3d11e0d718): SELECT `id`, `name`, `createdAt`, `updatedAt` FROM `Categories` AS `Category` WHERE `Category`.`name` = 'Cardio Exercises';
Executing (37ec246f-8937-4596-a959-9c8dd979ccf7): SELECT `id`, `name`, `createdAt`, `updatedAt` FROM `Categories` AS `Category` WHERE `Category`.`name` = 'Core Exercises';
Executing (8ab7629c-5dda-4aff-ac62-607b03ec0c4e): COMMIT;
Executing (f3127069-80dc-4acf-9144-25766b20537c): COMMIT;
Executing (d816c048-7c0a-487b-a0aa-d4397b972ef9): COMMIT;
Executing (cfc63f51-a817-4979-ade8-9158ba6e6fec): COMMIT;
Executing (37ec246f-8937-4596-a959-9c8dd979ccf7): COMMIT;
Executing (31970bb6-aa44-4789-8f24-ee3d11e0d718): COMMIT;
Received token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNzIxNDg1MDkyfQ.IcjQPVYdy1bHZRmCXC7QNGQqZC0b2GjAUOvUP5FSd2U
Token verified, user: { id: 1, iat: 1721485092 }
Executing (default): SELECT `Workout`.`id`, `Workout`.`name`, `Workout`.`createdAt`, `video1Details`.`id` AS `video1Details.id`, `video1Details`.`filename` AS `video1Details.filename`, `video1Details`.`description` AS `video1Details.description`, `video1Details`.`category` AS `video1Details.category`, `video2Details`.`id` AS `video2Details.id`, `video2Details`.`filename` AS `video2Details.filename`, `video2Details`.`description` AS `video2Details.description`, `video2Details`.`category` AS `video2Details.category`, `video3Details`.`id` AS `video3Details.id`, `video3Details`.`filename` AS `video3Details.filename`, `video3Details`.`description` AS `video3Details.description`, `video3Details`.`category` AS `video3Details.category`, `video4Details`.`id` AS `video4Details.id`, `video4Details`.`filename` AS `video4Details.filename`, `video4Details`.`description` AS `video4Details.description`, `video4Details`.`category` AS `video4Details.category` FROM `Workouts` AS `Workout` LEFT OUTER JOIN `Videos` AS `video1Details` ON `Workout`.`video1` = `video1Details`.`id` LEFT OUTER JOIN `Videos` AS `video2Details` ON `Workout`.`video2` = `video2Details`.`id` LEFT OUTER JOIN `Videos` AS `video3Details` ON `Workout`.`video3` = `video3Details`.`id` LEFT OUTER JOIN `Videos` AS `video4Details` ON `Workout`.`video4` = `video4Details`.`id`;
Received token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNzIxNDg1MDkyfQ.IcjQPVYdy1bHZRmCXC7QNGQqZC0b2GjAUOvUP5FSd2U
Token verified, user: { id: 1, iat: 1721485092 }
Executing (default): SELECT `id`, `filename`, `description`, `category` FROM `Videos` AS `Video` ORDER BY `Video`.`category` ASC;
Received token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNzIxNDg1MDkyfQ.IcjQPVYdy1bHZRmCXC7QNGQqZC0b2GjAUOvUP5FSd2U
Token verified, user: { id: 1, iat: 1721485092 }
Executing (default): SELECT `Workout`.`id`, `Workout`.`name`, `Workout`.`createdAt`, `video1Details`.`id` AS `video1Details.id`, `video1Details`.`filename` AS `video1Details.filename`, `video1Details`.`description` AS `video1Details.description`, `video1Details`.`category` AS `video1Details.category`, `video2Details`.`id` AS `video2Details.id`, `video2Details`.`filename` AS `video2Details.filename`, `video2Details`.`description` AS `video2Details.description`, `video2Details`.`category` AS `video2Details.category`, `video3Details`.`id` AS `video3Details.id`, `video3Details`.`filename` AS `video3Details.filename`, `video3Details`.`description` AS `video3Details.description`, `video3Details`.`category` AS `video3Details.category`, `video4Details`.`id` AS `video4Details.id`, `video4Details`.`filename` AS `video4Details.filename`, `video4Details`.`description` AS `video4Details.description`, `video4Details`.`category` AS `video4Details.category` FROM `Workouts` AS `Workout` LEFT OUTER JOIN `Videos` AS `video1Details` ON `Workout`.`video1` = `video1Details`.`id` LEFT OUTER JOIN `Videos` AS `video2Details` ON `Workout`.`video2` = `video2Details`.`id` LEFT OUTER JOIN `Videos` AS `video3Details` ON `Workout`.`video3` = `video3Details`.`id` LEFT OUTER JOIN `Videos` AS `video4Details` ON `Workout`.`video4` = `video4Details`.`id`;
Received token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNzIxNDg1MDkyfQ.IcjQPVYdy1bHZRmCXC7QNGQqZC0b2GjAUOvUP5FSd2U
Token verified, user: { id: 1, iat: 1721485092 }
Executing (default): SELECT `id`, `filename`, `description`, `category` FROM `Videos` AS `Video` ORDER BY `Video`.`category` ASC;
Received token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNzIxNDg1MDkyfQ.IcjQPVYdy1bHZRmCXC7QNGQqZC0b2GjAUOvUP5FSd2U
Token verified, user: { id: 1, iat: 1721485092 }
Executing (default): SELECT `Workout`.`id`, `Workout`.`name`, `Workout`.`createdAt`, `video1Details`.`id` AS `video1Details.id`, `video1Details`.`filename` AS `video1Details.filename`, `video1Details`.`description` AS `video1Details.description`, `video1Details`.`category` AS `video1Details.category`, `video2Details`.`id` AS `video2Details.id`, `video2Details`.`filename` AS `video2Details.filename`, `video2Details`.`description` AS `video2Details.description`, `video2Details`.`category` AS `video2Details.category`, `video3Details`.`id` AS `video3Details.id`, `video3Details`.`filename` AS `video3Details.filename`, `video3Details`.`description` AS `video3Details.description`, `video3Details`.`category` AS `video3Details.category`, `video4Details`.`id` AS `video4Details.id`, `video4Details`.`filename` AS `video4Details.filename`, `video4Details`.`description` AS `video4Details.description`, `video4Details`.`category` AS `video4Details.category` FROM `Workouts` AS `Workout` LEFT OUTER JOIN `Videos` AS `video1Details` ON `Workout`.`video1` = `video1Details`.`id` LEFT OUTER JOIN `Videos` AS `video2Details` ON `Workout`.`video2` = `video2Details`.`id` LEFT OUTER JOIN `Videos` AS `video3Details` ON `Workout`.`video3` = `video3Details`.`id` LEFT OUTER JOIN `Videos` AS `video4Details` ON `Workout`.`video4` = `video4Details`.`id`;
Received token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNzIxNDg1MDkyfQ.IcjQPVYdy1bHZRmCXC7QNGQqZC0b2GjAUOvUP5FSd2U
Token verified, user: { id: 1, iat: 1721485092 }
Executing (default): SELECT `id`, `filename`, `description`, `category` FROM `Videos` AS `Video` ORDER BY `Video`.`category` ASC;
Received token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNzIxNDg1MDkyfQ.IcjQPVYdy1bHZRmCXC7QNGQqZC0b2GjAUOvUP5FSd2U
Token verified, user: { id: 1, iat: 1721485092 }
Executing (default): SELECT `Workout`.`id`, `Workout`.`name`, `Workout`.`createdAt`, `video1Details`.`id` AS `video1Details.id`, `video1Details`.`filename` AS `video1Details.filename`, `video1Details`.`description` AS `video1Details.description`, `video1Details`.`category` AS `video1Details.category`, `video2Details`.`id` AS `video2Details.id`, `video2Details`.`filename` AS `video2Details.filename`, `video2Details`.`description` AS `video2Details.description`, `video2Details`.`category` AS `video2Details.category`, `video3Details`.`id` AS `video3Details.id`, `video3Details`.`filename` AS `video3Details.filename`, `video3Details`.`description` AS `video3Details.description`, `video3Details`.`category` AS `video3Details.category`, `video4Details`.`id` AS `video4Details.id`, `video4Details`.`filename` AS `video4Details.filename`, `video4Details`.`description` AS `video4Details.description`, `video4Details`.`category` AS `video4Details.category` FROM `Workouts` AS `Workout` LEFT OUTER JOIN `Videos` AS `video1Details` ON `Workout`.`video1` = `video1Details`.`id` LEFT OUTER JOIN `Videos` AS `video2Details` ON `Workout`.`video2` = `video2Details`.`id` LEFT OUTER JOIN `Videos` AS `video3Details` ON `Workout`.`video3` = `video3Details`.`id` LEFT OUTER JOIN `Videos` AS `video4Details` ON `Workout`.`video4` = `video4Details`.`id`;
Received token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNzIxNDg1MDkyfQ.IcjQPVYdy1bHZRmCXC7QNGQqZC0b2GjAUOvUP5FSd2U
Token verified, user: { id: 1, iat: 1721485092 }
Executing (default): SELECT `id`, `filename`, `description`, `category` FROM `Videos` AS `Video` ORDER BY `Video`.`category` ASC;
Received token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNzIxNDg1MDkyfQ.IcjQPVYdy1bHZRmCXC7QNGQqZC0b2GjAUOvUP5FSd2U
Token verified, user: { id: 1, iat: 1721485092 }
Executing (default): SELECT `Workout`.`id`, `Workout`.`name`, `Workout`.`createdAt`, `video1Details`.`id` AS `video1Details.id`, `video1Details`.`filename` AS `video1Details.filename`, `video1Details`.`description` AS `video1Details.description`, `video1Details`.`category` AS `video1Details.category`, `video2Details`.`id` AS `video2Details.id`, `video2Details`.`filename` AS `video2Details.filename`, `video2Details`.`description` AS `video2Details.description`, `video2Details`.`category` AS `video2Details.category`, `video3Details`.`id` AS `video3Details.id`, `video3Details`.`filename` AS `video3Details.filename`, `video3Details`.`description` AS `video3Details.description`, `video3Details`.`category` AS `video3Details.category`, `video4Details`.`id` AS `video4Details.id`, `video4Details`.`filename` AS `video4Details.filename`, `video4Details`.`description` AS `video4Details.description`, `video4Details`.`category` AS `video4Details.category` FROM `Workouts` AS `Workout` LEFT OUTER JOIN `Videos` AS `video1Details` ON `Workout`.`video1` = `video1Details`.`id` LEFT OUTER JOIN `Videos` AS `video2Details` ON `Workout`.`video2` = `video2Details`.`id` LEFT OUTER JOIN `Videos` AS `video3Details` ON `Workout`.`video3` = `video3Details`.`id` LEFT OUTER JOIN `Videos` AS `video4Details` ON `Workout`.`video4` = `video4Details`.`id`;
Received token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNzIxNDg1MDkyfQ.IcjQPVYdy1bHZRmCXC7QNGQqZC0b2GjAUOvUP5FSd2U
Token verified, user: { id: 1, iat: 1721485092 }
Executing (default): SELECT `id`, `filename`, `description`, `category` FROM `Videos` AS `Video` ORDER BY `Video`.`category` ASC;
Binary file not shown.
+24
View File
@@ -0,0 +1,24 @@
{
"name": "vit-site",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"body-parser": "^1.20.2",
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.19.2",
"jsonwebtoken": "^9.0.2",
"multer": "^1.4.5-lts.1",
"node-schedule": "^2.1.1",
"sequelize": "^6.37.3",
"sqlite3": "^5.1.7"
},
"description": ""
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

+354
View File
@@ -0,0 +1,354 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Manage Categories</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
height: 100vh;
overflow: hidden;
}
.banner {
width: 100%;
background-color: #f1f1f1;
display: flex;
align-items: center;
justify-content: space-between;
padding: 20px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
position: relative;
}
.banner img {
max-height: 200px;
}
.menu-button {
background: none;
border: none;
font-size: 24px;
cursor: pointer;
position: absolute;
top: 0;
left: 20px;
}
.drawer {
width: 250px;
background-color: #f9f9f9;
color: black;
height: 100%;
position: fixed;
top: 0;
left: -250px;
transition: left 0.3s;
z-index: 1000;
}
.drawer.open {
left: 0;
}
.drawer-header {
display: flex;
flex-direction: column;
align-items: center;
padding: 15px;
background-color: #f9f9f9;
}
.drawer-header img {
max-height: 200px;
margin-bottom: 15px;
}
.drawer-header button {
background: none;
border: none;
color: black;
font-size: 24px;
cursor: pointer;
align-self: flex-end;
}
.drawer-content {
padding: 20px;
}
.drawer-content a {
display: block;
color: black;
text-decoration: none;
padding: 10px 0;
border-bottom: 1px solid #ddd;
}
.main-content {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
transition: margin-left 0.3s;
}
.main-content.open {
margin-left: 250px;
}
.main-header {
display: flex;
flex-direction: column;
align-items: center;
padding: 15px;
width: 100%;
}
.main-header img {
max-height: 200px;
}
.main-header h1 {
margin: 10px 0;
}
.content {
padding: 20px;
width: 100%;
max-width: 800px; /* Center the content */
}
.content form {
display: flex;
flex-direction: row; /* Change to row */
align-items: center;
justify-content: center; /* Center the form */
width: 100%;
}
.content form .input-group {
display: flex;
align-items: center;
margin: 10px 0;
}
.content form input {
padding: 10px;
font-size: 16px;
width: 100%;
max-width: 400px;
}
.content form button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
background-color: #007BFF;
color: white;
border: none;
border-radius: 5px;
margin-left: 10px; /* Margin to separate the button from the input */
}
.category-list {
list-style: none;
padding: 0;
text-align: center; /* Center the list */
width: 100%;
}
.category-list li {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px;
border-bottom: 1px solid #ddd;
background-color: #f9f9f9;
}
.category-list button {
background-color: #ff4b5c;
color: white;
border: none;
border-radius: 5px;
padding: 5px 10px;
cursor: pointer;
}
</style>
</head>
<body>
<div class="banner">
<button class="menu-button" onclick="toggleDrawer()">&#9776;</button>
</div>
<div class="drawer" id="drawer">
<div class="drawer-header">
<img src="VitLogo.png" alt="Logo">
<button onclick="toggleDrawer()">&#10005;</button>
</div>
<div class="drawer-content">
<a href="/dashboard.html">Dashboard</a>
<a href="/upload.html">Upload Video</a>
<a href="/videos.html">Manage Videos</a>
<a href="/create-workout.html">Create Workout</a>
<a href="/workouts.html">Manage Workouts</a>
<a href="/create-crossfit-workout.html">Create CrossFit Workout</a>
<a href="/crossfit-workouts.html">Manage CrossFit Workouts</a>
<a href="/categories.html">Manage Categories</a>
<a href="/manage-timers.html">Manage Timers</a>
<a href="/create-timer.html">Create Timer</a>
<a href="/settings.html" id="settingsLink" style="display:none;">Settings</a>
<a href="#" onclick="logout()">Logout</a>
</div>
</div>
<div class="main-content" id="main-content">
<div class="main-header">
<img src="VitLogo.png" alt="Logo">
<h1>Manage Categories</h1>
</div>
<div class="content">
<form id="categoryForm">
<div class="input-group">
<input type="text" id="categoryName" placeholder="Category Name" required>
<button type="submit">Add Category</button>
</div>
</form>
<ul id="categoryList" class="category-list"></ul>
</div>
</div>
<script>
const drawer = document.getElementById('drawer');
const mainContent = document.getElementById('main-content');
const categoryForm = document.getElementById('categoryForm');
const categoryList = document.getElementById('categoryList');
function toggleDrawer() {
drawer.classList.toggle('open');
mainContent.classList.toggle('open');
}
function logout() {
localStorage.removeItem('token');
window.location.href = '/';
}
async function checkAdmin() {
const token = localStorage.getItem('token');
if (!token) {
alert('No token found, redirecting to login');
window.location.href = '/';
return;
}
const response = await fetch('/profile', {
headers: {
'Authorization': `Bearer ${token}`
}
});
const user = await response.json();
console.log('User fetched:', user); // Log the fetched user
if (user.role === 'Admin') {
document.getElementById('settingsLink').style.display = 'block';
} else {
console.log('User is not an admin'); // Log if user is not admin
}
}
document.addEventListener('DOMContentLoaded', async () => {
const token = localStorage.getItem('token');
if (!token) {
alert('No token found, redirecting to login');
window.location.href = '/';
return;
}
// Fetch categories
async function fetchCategories() {
try {
const response = await fetch('/categories', {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
});
if (!response.ok) {
throw new Error('Failed to fetch categories');
}
const categories = await response.json();
categoryList.innerHTML = '';
categories.forEach(category => {
const li = document.createElement('li');
li.textContent = category.name;
const button = document.createElement('button');
button.textContent = 'Delete';
button.onclick = async () => {
await deleteCategory(category.id);
};
li.appendChild(button);
categoryList.appendChild(li);
});
} catch (error) {
console.error('Error fetching categories:', error);
alert('An error occurred while fetching categories');
}
}
// Add category
categoryForm.addEventListener('submit', async (event) => {
event.preventDefault();
const categoryName = document.getElementById('categoryName').value;
try {
const response = await fetch('/categories', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ name: categoryName })
});
if (!response.ok) {
throw new Error('Failed to add category');
}
document.getElementById('categoryName').value = '';
fetchCategories();
} catch (error) {
console.error('Error adding category:', error);
alert('An error occurred while adding the category');
}
});
// Delete category
async function deleteCategory(categoryId) {
try {
const response = await fetch(`/categories/${categoryId}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
});
if (!response.ok) {
throw new Error('Failed to delete category');
}
fetchCategories();
} catch (error) {
console.error('Error deleting category:', error);
alert('An error occurred while deleting the category');
}
}
fetchCategories();
checkAdmin();
});
</script>
</body>
</html>
+236
View File
@@ -0,0 +1,236 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create CrossFit Workout</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
height: 100vh;
overflow: hidden;
}
.banner {
width: 100%;
background-color: #f1f1f1;
display: flex;
align-items: center;
justify-content: space-between;
padding: 20px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
position: relative;
}
.banner img {
max-height: 200px;
}
.menu-button {
background: none;
border: none;
font-size: 24px;
cursor: pointer;
position: absolute;
top: 0;
left: 20px;
}
.drawer {
width: 250px;
background-color: #f9f9f9;
color: black;
height: 100%;
position: fixed;
top: 0;
left: -250px;
transition: left 0.3s;
z-index: 1000;
}
.drawer.open {
left: 0;
}
.drawer-header {
display: flex;
flex-direction: column;
align-items: center;
padding: 15px;
background-color: #f9f9f9;
}
.drawer-header img {
max-height: 200px;
margin-bottom: 15px;
}
.drawer-header button {
background: none;
border: none;
color: black;
font-size: 24px;
cursor: pointer;
align-self: flex-end;
}
.drawer-content {
padding: 20px;
}
.drawer-content a {
display: block;
color: black;
text-decoration: none;
padding: 10px 0;
border-bottom: 1px solid #ddd;
}
.main-content {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
transition: margin-left 0.3s;
}
.main-content.open {
margin-left: 250px;
}
.main-header {
display: flex;
flex-direction: column;
align-items: center;
padding: 15px;
width: 100%;
}
.main-header img {
max-height: 200px;
}
.main-header h1 {
margin: 10px 0;
}
.content {
padding: 20px;
width: 100%;
max-width: 1200px;
align-items: center;
}
.content form {
display: flex;
flex-direction: column;
align-items: center;
}
.content form .input-group {
display: flex;
flex-direction: column;
margin: 10px 0;
width: 100%;
max-width: 800px;
align-items: center;
}
.content form input,
.content form textarea {
padding: 10px;
font-size: 16px;
width: 100%;
max-width: 400px;
margin-bottom: 10px;
}
.content form button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
background-color: #007BFF;
color: white;
border: none;
border-radius: 5px;
margin-top: 20px;
}
.error-message {
color: red;
font-weight: bold;
}
</style>
</head>
<body>
<div class="banner">
<button class="menu-button" onclick="toggleDrawer()">&#9776;</button>
</div>
<div class="drawer" id="drawer">
<div class="drawer-header">
<img src="VitLogo.png" alt="Logo">
<button onclick="toggleDrawer()">&#10005;</button>
</div>
<div class="drawer-content">
<a href="/dashboard.html">Dashboard</a>
<a href="/upload.html">Upload Video</a>
<a href="/videos.html">Manage Videos</a>
<a href="/create-workout.html">Create Workout</a>
<a href="/workouts.html">Manage Workouts</a>
<a href="/create-crossfit-workout.html">Create CrossFit Workout</a>
<a href="/crossfit-workouts.html">Manage CrossFit Workouts</a>
<a href="/categories.html">Manage Categories</a>
<a href="/manage-timers.html">Manage Timers</a>
<a href="/create-timer.html">Create Timer</a>
</div>
</div>
<div class="main-content" id="main-content">
<div class="main-header">
<img src="VitLogo.png" alt="Logo">
<h1>Create CrossFit Workout</h1>
</div>
<div class="content">
<form id="createCrossfitWorkoutForm">
<div class="input-group">
<input type="text" id="name" name="name" placeholder="Workout Name" required>
</div>
<div class="input-group">
<input type="date" id="workoutDate" name="workoutDate" required>
</div>
<div class="input-group">
<textarea id="rawText" name="rawText" rows="10" placeholder="Paste raw workout text here..." required></textarea>
</div>
<button type="submit">Create CrossFit Workout</button>
<div id="errorMessage" class="error-message"></div>
</form>
</div>
</div>
<script>
const drawer = document.getElementById('drawer');
const mainContent = document.getElementById('main-content');
function toggleDrawer() {
drawer.classList.toggle('open');
mainContent.classList.toggle('open');
}
document.getElementById('createCrossfitWorkoutForm').addEventListener('submit', async (e) => {
e.preventDefault();
const formData = new FormData(e.target);
const workoutData = {
name: formData.get('name'),
workoutDate: formData.get('workoutDate'),
rawText: formData.get('rawText')
};
try {
const token = localStorage.getItem('token');
const response = await fetch('/create-crossfit-workout', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(workoutData)
});
if (response.ok) {
alert('CrossFit workout created successfully');
window.location.href = '/crossfit-workouts.html';
} else {
const error = await response.text();
document.getElementById('errorMessage').textContent = error;
}
} catch (error) {
console.error('Error creating CrossFit workout:', error);
document.getElementById('errorMessage').textContent = 'An error occurred. Please try again later.';
}
});
</script>
</body>
</html>
+241
View File
@@ -0,0 +1,241 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create Timer</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
height: 100vh;
overflow: hidden;
}
.banner {
width: 100%;
background-color: #f1f1f1;
display: flex;
align-items: center;
justify-content: space-between;
padding: 20px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
position: relative;
}
.banner img {
max-height: 200px;
}
.menu-button {
background: none;
border: none;
font-size: 24px;
cursor: pointer;
position: absolute;
top: 0;
left: 20px;
}
.drawer {
width: 250px;
background-color: #f9f9f9;
color: black;
height: 100%;
position: fixed;
top: 0;
left: -250px;
transition: left 0.3s;
z-index: 1000;
}
.drawer.open {
left: 0;
}
.drawer-header {
display: flex;
flex-direction: column;
align-items: center;
padding: 15px;
background-color: #f9f9f9;
}
.drawer-header img {
max-height: 200px;
margin-bottom: 15px;
}
.drawer-header button {
background: none;
border: none;
color: black;
font-size: 24px;
cursor: pointer;
align-self: flex-end;
}
.drawer-content {
padding: 20px;
}
.drawer-content a {
display: block;
color: black;
text-decoration: none;
padding: 10px 0;
border-bottom: 1px solid #007BFF;
}
.main-header {
display: flex;
flex-direction: column;
align-items: center;
padding: 15px;
width: 100%;
}
.main-content.open {
margin-left: 250px;
}
.main-header {
display: flex;
flex-direction: column;
align-items: center;
padding: 15px;
width: 100%;
}
.main-header img {
max-height: 200px;
}
.main-header h1 {
margin: 10px 0;
}
.content {
padding: 20px;
width: 100%;
display: flex;
justify-content: center;
flex-wrap: wrap;
text-align: center;
}
.form-group {
margin-bottom: 15px;
text-align: center;
}
.form-group label {
display: block;
margin-bottom: 5px;
}
.form-group input {
width: 100%;
padding: 8px;
box-sizing: border-box;
}
.form-group button {
padding: 10px 20px;
background-color: #007BFF;
color: white;
border: none;
cursor: pointer;
border-radius: 5px;
}
</style>
</head>
<body>
<div class="banner">
<button class="menu-button" onclick="toggleDrawer()">&#9776;</button>
</div>
<div class="drawer" id="drawer">
<div class="drawer-header">
<img src="VitLogo.png" alt="Logo">
<button onclick="toggleDrawer()">&#10005;</button>
</div>
<div class="drawer-content">
<a href="/dashboard.html">Dashboard</a>
<a href="/upload.html">Upload Video</a>
<a href="/videos.html">Manage Videos</a>
<a href="/create-workout.html">Create Workout</a>
<a href="/workouts.html">Manage Workouts</a>
<a href="/create-crossfit-workout.html">Create CrossFit Workout</a>
<a href="/crossfit-workouts.html">Manage CrossFit Workouts</a>
<a href="/categories.html">Manage Categories</a>
<a href="/manage-timers.html">Manage Timers</a>
<a href="/create-timer.html">Create Timer</a>
</div>
</div>
<div class="main-content" id="main-content">
<div class="main-header">
<img src="VitLogo.png" alt="Logo">
<h1>Create Timer</h1>
</div>
<div class="content">
<form id="createTimerForm">
<div class="form-group">
<label for="totalTime">Total Workout Time (seconds)</label>
<input type="number" id="totalTime" name="totalTime" required>
</div>
<div class="form-group">
<label for="setTime">Set Time (seconds)</label>
<input type="number" id="setTime" name="setTime" required>
</div>
<div class="form-group">
<label for="restTime">Rest Time (seconds)</label>
<input type="number" id="restTime" name="restTime" required>
</div>
<div class="form-group">
<label for="moveTime">Transition Time (seconds)</label>
<input type="number" id="moveTime" name="moveTime" required>
</div>
<div class="form-group">
<label for="setCount">Number of Sets</label>
<input type="number" id="setCount" name="setCount" required>
</div>
<div class="form-group">
<label for="exerciseCount">Number of Exercises</label>
<input type="number" id="exerciseCount" name="exerciseCount" required>
</div>
<div class="form-group">
<label for="lapCount">Number of Laps</label>
<input type="number" id="lapCount" name="lapCount" required>
</div>
<div class="form-group">
<button type="submit">Create Timer</button>
</div>
</form>
</div>
</div>
<script>
const drawer = document.getElementById('drawer');
const mainContent = document.getElementById('main-content');
function toggleDrawer() {
drawer.classList.toggle('open');
mainContent.classList.toggle('open');
}
document.getElementById('createTimerForm').addEventListener('submit', async function (event) {
event.preventDefault();
const formData = new FormData(this);
const timerData = {
totalTime: formData.get('totalTime'),
setTime: formData.get('setTime'),
restTime: formData.get('restTime'),
moveTime: formData.get('moveTime'),
setCount: formData.get('setCount'),
exerciseCount: formData.get('exerciseCount'),
lapCount: formData.get('lapCount')
};
console.log('Timer Data:', timerData);
try {
const response = await fetch('/create-timer', {
method: 'POST',
headers: {
'Authorization': `Bearer ${localStorage.getItem('token')}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(timerData)
});
if (!response.ok) throw new Error('Failed to create timer');
console.log('Timer created successfully');
window.location.href = '/manage-timers.html';
} catch (error) {
console.error('Error creating timer:', error);
alert('Failed to create timer');
}
});
</script>
</body>
</html>
+355
View File
@@ -0,0 +1,355 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create Workout</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
height: 100vh;
overflow: hidden; /* Prevent multiple scroll bars */
}
.banner {
width: 100%;
background-color: #f1f1f1;
display: flex;
align-items: center;
justify-content: space-between;
padding: 20px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
position: relative;
}
.banner img {
max-height: 200px;
}
.menu-button {
background: none;
border: none;
font-size: 24px;
cursor: pointer;
position: absolute;
top: 0;
left: 20px;
}
.drawer {
width: 250px;
background-color: #f9f9f9;
color: black;
height: 100%;
position: fixed;
top: 0;
left: -250px;
transition: left 0.3s;
z-index: 1000;
}
.drawer.open {
left: 0;
}
.drawer-header {
display: flex;
flex-direction: column;
align-items: center;
padding: 15px;
background-color: #f9f9f9;
}
.drawer-header img {
max-height: 200px;
margin-bottom: 15px;
}
.drawer-header button {
background: none;
border: none;
color: black;
font-size: 24px;
cursor: pointer;
align-self: flex-end;
}
.drawer-content {
padding: 20px;
}
.drawer-content a {
display: block;
color: black;
text-decoration: none;
padding: 10px 0;
border-bottom: 1px solid #ddd;
}
.main-content {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
transition: margin-left 0.3s;
}
.main-content.open {
margin-left: 250px;
}
.main-header {
display: flex;
flex-direction: column;
align-items: center;
padding: 15px;
width: 100%;
}
.main-header img {
max-height: 200px;
}
.main-header h1 {
margin: 10px 0;
}
.content {
padding: 20px;
width: 100%;
max-width: 1200px;
}
.content form {
display: flex;
flex-direction: column;
align-items: center;
}
.content form .input-group {
display: flex;
align-items: center;
margin: 10px 0;
width: 100%;
max-width: 800px;
}
.content form select,
.content form input {
padding: 10px;
font-size: 16px;
width: 100%;
max-width: 400px;
}
.content form input {
margin-left: 10px;
}
.content form button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
background-color: #007BFF;
color: white;
border: none;
border-radius: 5px;
margin-top: 20px;
}
.error-message {
color: red;
font-weight: bold;
}
</style>
</head>
<body>
<div class="banner">
<button class="menu-button" onclick="toggleDrawer()">&#9776;</button>
</div>
<div class="drawer" id="drawer">
<div class="drawer-header">
<img src="VitLogo.png" alt="Logo">
<button onclick="toggleDrawer()">&#10005;</button>
</div>
<div class="drawer-content">
<a href="/dashboard.html">Dashboard</a>
<a href="/upload.html">Upload Video</a>
<a href="/videos.html">Manage Videos</a>
<a href="/create-workout.html">Create Workout</a>
<a href="/workouts.html">Manage Workouts</a>
<a href="/create-crossfit-workout.html">Create CrossFit Workout</a>
<a href="/crossfit-workouts.html">Manage CrossFit Workouts</a>
<a href="/categories.html">Manage Categories</a>
<a href="/manage-timers.html">Manage Timers</a>
<a href="/create-timer.html">Create Timer</a>
<a href="/settings.html" id="settingsLink" style="display:none;">Settings</a>
<a href="#" onclick="logout()">Logout</a>
</div>
</div>
<div class="main-content" id="main-content">
<div class="main-header">
<img src="VitLogo.png" alt="Logo">
<h1>Create Workout</h1>
</div>
<div class="content">
<form id="createWorkoutForm">
<div class="input-group">
<input type="text" id="name" name="name" placeholder="Workout Name" required>
<input type="date" id="workoutDate" name="workoutDate" required>
</div>
<div class="input-group">
<select id="videoCount" name="videoCount" required>
<option value="1">1 Video</option>
<option value="2">2 Videos</option>
<option value="3">3 Videos</option>
<option value="4">4 Videos</option>
</select>
</div>
<div class="input-group" id="video1-group">
<select id="video1" name="video1" required>
<option value="">Select Video 1</option>
<!-- Options loaded dynamically -->
</select>
<input type="number" name="number1" placeholder="Number for Video 1" required>
</div>
<div class="input-group" id="video2-group">
<select id="video2" name="video2">
<option value="">Select Video 2</option>
<!-- Options loaded dynamically -->
</select>
<input type="number" name="number2" placeholder="Number for Video 2">
</div>
<div class="input-group" id="video3-group">
<select id="video3" name="video3">
<option value="">Select Video 3</option>
<!-- Options loaded dynamically -->
</select>
<input type="number" name="number3" placeholder="Number for Video 3">
</div>
<div class="input-group" id="video4-group">
<select id="video4" name="video4">
<option value="">Select Video 4</option>
<!-- Options loaded dynamically -->
</select>
<input type="number" name="number4" placeholder="Number for Video 4">
</div>
<button type="submit">Create Workout</button>
<div id="errorMessage" class="error-message"></div>
</form>
</div>
</div>
<script>
const drawer = document.getElementById('drawer');
const mainContent = document.getElementById('main-content');
const createWorkoutForm = document.getElementById('createWorkoutForm');
const errorMessage = document.getElementById('errorMessage');
function toggleDrawer() {
drawer.classList.toggle('open');
mainContent.classList.toggle('open');
}
function logout() {
localStorage.removeItem('token');
window.location.href = '/';
}
async function checkAdmin() {
const token = localStorage.getItem('token');
if (!token) {
alert('No token found, redirecting to login');
window.location.href = '/';
return;
}
const response = await fetch('/profile', {
headers: {
'Authorization': `Bearer ${token}`
}
});
const user = await response.json();
console.log('User fetched:', user); // Log the fetched user
if (user.role === 'Admin') {
document.getElementById('settingsLink').style.display = 'block';
} else {
console.log('User is not an admin'); // Log if user is not admin
}
}
document.addEventListener('DOMContentLoaded', async () => {
const token = localStorage.getItem('token');
if (!token) {
alert('No token found, redirecting to login');
window.location.href = '/';
return;
}
await checkAdmin();
const videoCountSelector = document.getElementById('videoCount');
const video2Group = document.getElementById('video2-group');
const video3Group = document.getElementById('video3-group');
const video4Group = document.getElementById('video4-group');
videoCountSelector.addEventListener('change', (e) => {
const count = parseInt(e.target.value);
video2Group.style.display = count >= 2 ? 'flex' : 'none';
video3Group.style.display = count >= 3 ? 'flex' : 'none';
video4Group.style.display = count >= 4 ? 'flex' : 'none';
});
// Initial hide
video2Group.style.display = 'none';
video3Group.style.display = 'none';
video4Group.style.display = 'none';
// Fetch and populate video options
const fetchVideos = async () => {
const response = await fetch('/videos', {
headers: {
'Authorization': `Bearer ${token}`
}
});
const videos = await response.json();
videos.sort((a, b) => a.description.localeCompare(b.description));
videos.forEach(video => {
const option = new Option(`${video.description} - ${video.category}`, video.id);
document.getElementById('video1').appendChild(option.cloneNode(true));
document.getElementById('video2').appendChild(option.cloneNode(true));
document.getElementById('video3').appendChild(option.cloneNode(true));
document.getElementById('video4').appendChild(option.cloneNode(true));
});
};
await fetchVideos();
document.getElementById('createWorkoutForm').addEventListener('submit', async (e) => {
e.preventDefault();
const formData = new FormData(e.target);
const workoutData = {
name: formData.get('name'),
workoutDate: formData.get('workoutDate'),
video1: formData.get('video1'),
number1: formData.get('number1'),
video2: formData.get('video2') || null,
number2: formData.get('number2') || null,
video3: formData.get('video3') || null,
number3: formData.get('number3') || null,
video4: formData.get('video4') || null,
number4: formData.get('number4') || null
};
try {
const response = await fetch('/create-workout', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(workoutData)
});
if (response.ok) {
window.location.href = '/workouts.html';
} else {
const error = await response.text();
document.getElementById('errorMessage').textContent = error;
}
} catch (error) {
console.error('Error creating workout:', error);
}
});
});
</script>
</body>
</html>
+256
View File
@@ -0,0 +1,256 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CrossFit Workouts</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
height: 100vh;
overflow: hidden;
}
.banner {
width: 100%;
background-color: #f1f1f1;
display: flex;
align-items: center;
justify-content: space-between;
padding: 20px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
position: relative;
}
.banner img {
max-height: 200px;
}
.menu-button {
background: none;
border: none;
font-size: 24px;
cursor: pointer;
position: absolute;
top: 0;
left: 20px;
}
.drawer {
width: 250px;
background-color: #f9f9f9;
color: black;
height: 100%;
position: fixed;
top: 0;
left: -250px;
transition: left 0.3s;
z-index: 1000;
}
.drawer.open {
left: 0;
}
.drawer-header {
display: flex;
flex-direction: column;
align-items: center;
padding: 15px;
background-color: #f9f9f9;
}
.drawer-header img {
max-height: 200px;
margin-bottom: 15px;
}
.drawer-header button {
background: none;
border: none;
color: black;
font-size: 24px;
cursor: pointer;
align-self: flex-end;
}
.drawer-content {
padding: 20px;
}
.drawer-content a {
display: block;
color: black;
text-decoration: none;
padding: 10px 0;
border-bottom: 1px solid #007BFF;
}
.main-content {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: flex-start;
transition: margin-left 0.3s;
overflow-y: auto; /* Enable vertical scrolling */
}
.main-content.open {
margin-left: 250px;
}
.main-header {
display: flex;
flex-direction: column;
align-items: center;
padding: 15px;
width: 100%;
}
.main-header img {
max-height: 200px;
}
.main-header h1 {
margin: 10px 0;
}
.content {
padding: 20px;
width: 100%;
max-width: 1200px;
}
.workout-item {
background-color: #f9f9f9;
padding: 15px;
border: 1px solid #ddd;
border-radius: 8px;
margin-bottom: 10px;
position: relative;
}
.workout-item h3 {
margin: 0;
}
.workout-item ul {
padding-left: 20px;
}
.delete-button {
background-color: #FF4136;
color: white;
border: none;
padding: 5px 10px;
border-radius: 4px;
cursor: pointer;
position: absolute;
top: 15px;
right: 15px;
}
</style>
</head>
<body>
<div class="banner">
<button class="menu-button" onclick="toggleDrawer()">&#9776;</button>
</div>
<div class="drawer" id="drawer">
<div class="drawer-header">
<img src="VitLogo.png" alt="Logo">
<button onclick="toggleDrawer()">&#10005;</button>
</div>
<div class="drawer-content">
<a href="/dashboard.html">Dashboard</a>
<a href="/upload.html">Upload Video</a>
<a href="/videos.html">Manage Videos</a>
<a href="/create-workout.html">Create Workout</a>
<a href="/workouts.html">Manage Workouts</a>
<a href="/create-crossfit-workout.html">Create CrossFit Workout</a>
<a href="/crossfit-workouts.html">Manage CrossFit Workouts</a>
<a href="/categories.html">Manage Categories</a>
<a href="/manage-timers.html">Manage Timers</a>
<a href="/create-timer.html">Create Timer</a>
<a href="/create-crossfit-workout.html">Create CrossFit Workout</a>
</div>
</div>
<div class="main-content" id="main-content">
<div class="main-header">
<img src="VitLogo.png" alt="Logo">
<h1>CrossFit Workouts</h1>
</div>
<div class="content" id="workoutContent">
<!-- Workouts will be dynamically loaded here -->
</div>
</div>
<script>
const drawer = document.getElementById('drawer');
const mainContent = document.getElementById('main-content');
function toggleDrawer() {
drawer.classList.toggle('open');
mainContent.classList.toggle('open');
}
async function deleteWorkout(workoutId) {
const token = localStorage.getItem('token');
if (!token) {
alert('No token found, redirecting to login');
window.location.href = '/';
return;
}
if (!confirm('Are you sure you want to delete this workout?')) {
return;
}
try {
const response = await fetch(`/crossfit-workout/${workoutId}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${token}`
}
});
if (!response.ok) {
throw new Error('Failed to delete workout');
}
alert('Workout deleted successfully');
document.getElementById(`workout-${workoutId}`).remove(); // Remove the workout from the DOM
} catch (error) {
console.error('Error deleting workout:', error);
alert('Failed to delete workout');
}
}
document.addEventListener('DOMContentLoaded', async () => {
const token = localStorage.getItem('token');
if (!token) {
alert('No token found, redirecting to login');
window.location.href = '/';
return;
}
try {
const response = await fetch('/crossfit-workouts', {
headers: {
'Authorization': `Bearer ${token}`
}
});
if (!response.ok) {
throw new Error('Failed to fetch workouts');
}
const workouts = await response.json();
const workoutContent = document.getElementById('workoutContent');
workouts.forEach(workout => {
const workoutItem = document.createElement('div');
workoutItem.className = 'workout-item';
workoutItem.id = `workout-${workout.id}`;
workoutItem.innerHTML = `
<h3>${workout.name}</h3>
<p>Date: ${new Date(workout.workoutDate).toLocaleDateString()}</p>
<ul>
${workout.workoutItems.map(item => `<li>${item}</li>`).join('')}
</ul>
<button class="delete-button" onclick="deleteWorkout(${workout.id})">Delete</button>
`;
workoutContent.appendChild(workoutItem);
});
} catch (error) {
console.error('Error fetching workouts:', error);
alert('Failed to load CrossFit workouts');
}
});
</script>
</body>
</html>
+310
View File
@@ -0,0 +1,310 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dashboard</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
height: 100vh;
overflow: hidden;
}
.banner {
width: 100%;
background-color: #f1f1f1;
display: flex;
align-items: center;
justify-content: space-between;
padding: 20px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
position: relative;
}
.banner img {
max-height: 200px;
}
.menu-button {
background: none;
border: none;
font-size: 24px;
cursor: pointer;
position: absolute;
top: 0;
left: 20px;
}
.drawer {
width: 250px;
background-color: #f9f9f9;
color: black;
height: 100%;
position: fixed;
top: 0;
left: -250px;
transition: left 0.3s;
z-index: 1000;
}
.drawer.open {
left: 0;
}
.drawer-header {
display: flex;
flex-direction: column;
align-items: center;
padding: 15px;
background-color: #f9f9f9;
}
.drawer-header img {
max-height: 200px;
margin-bottom: 15px;
}
.drawer-header button {
background: none;
border: none;
color: black;
font-size: 24px;
cursor: pointer;
align-self: flex-end;
}
.drawer-content {
padding: 20px;
}
.drawer-content a {
display: block;
color: black;
text-decoration: none;
padding: 10px 0;
border-bottom: 1px solid #007BFF;
}
.main-content {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: flex-start;
transition: margin-left 0.3s;
overflow-y: auto; /* Enable vertical scrolling */
}
.main-content.open {
margin-left: 250px;
}
.main-header {
display: flex;
flex-direction: column;
align-items: center;
padding: 15px;
width: 100%;
}
.main-header img {
max-height: 200px;
}
.main-header h1 {
margin: 10px 0;
}
.content {
padding: 20px;
width: 100%;
max-width: 1200px;
display: flex;
justify-content: space-around;
flex-wrap: wrap;
}
.content div {
background-color: #f9f9f9;
padding: 20px;
border: 1px solid #ddd;
border-radius: 8px;
width: 45%;
text-align: center;
margin: 10px 0;
}
.content h3 {
margin: 0;
margin-bottom: 10px;
}
.content p {
font-size: 24px;
margin: 0;
}
.workout-list {
width: 100%;
max-width: 1200px;
padding: 20px;
}
.workout-list h3 {
text-align: center;
}
.workout-item {
background-color: #f9f9f9;
padding: 15px;
border: 1px solid #ddd;
border-radius: 8px;
margin-bottom: 10px;
display: flex;
justify-content: space-between;
align-items: center;
}
.workout-item a {
text-decoration: none;
color: #007BFF;
font-weight: bold;
}
</style>
</head>
<body>
<div class="banner">
<button class="menu-button" onclick="toggleDrawer()">&#9776;</button>
</div>
<div class="drawer" id="drawer">
<div class="drawer-header">
<img src="VitLogo.png" alt="Logo">
<button onclick="toggleDrawer()">&#10005;</button>
</div>
<div class="drawer-content">
<a href="/upload.html">Upload Video</a>
<a href="/videos.html">Manage Videos</a>
<a href="/create-workout.html">Create Workout</a>
<a href="/workouts.html">Manage Workouts</a>
<a href="/create-crossfit-workout.html">Create CrossFit Workout</a>
<a href="/crossfit-workouts.html">Manage CrossFit Workouts</a>
<a href="/categories.html">Manage Categories</a>
<a href="/manage-timers.html">Manage Timers</a>
<a href="/create-timer.html">Create Timer</a>
<a href="/settings.html" id="settingsLink" style="display:none;">Settings</a>
<a href="#" onclick="logout()">Logout</a>
</div>
</div>
<div class="main-content" id="main-content">
<div class="main-header">
<img src="VitLogo.png" alt="Logo">
<h1>Dashboard</h1>
</div>
<div class="content">
<div>
<h3>Number of Workouts Created</h3>
<p id="workoutsCount">0</p>
</div>
<div>
<h3>Number of Videos Uploaded</h3>
<p id="videosCount">0</p>
</div>
</div>
<div class="workout-list" id="workoutList">
<h3>Workouts</h3>
</div>
</div>
<script>
const drawer = document.getElementById('drawer');
const mainContent = document.getElementById('main-content');
function toggleDrawer() {
drawer.classList.toggle('open');
mainContent.classList.toggle('open');
}
async function checkAdmin() {
const token = localStorage.getItem('token');
if (!token) {
alert('No token found, redirecting to login');
window.location.href = '/';
return;
}
const response = await fetch('/profile', {
headers: {
'Authorization': `Bearer ${token}`
}
});
const user = await response.json();
console.log('User fetched:', user); // Log the fetched user
if (user.role === 'Admin') {
document.getElementById('settingsLink').style.display = 'block';
} else {
console.log('User is not an admin'); // Log if user is not admin
}
}
document.addEventListener('DOMContentLoaded', async () => {
const token = localStorage.getItem('token');
if (!token) {
alert('No token found, redirecting to login');
window.location.href = '/';
return;
}
await checkAdmin();
try {
const today = new Date().toISOString().split('T')[0];
const workoutsResponse = await fetch('/today-workouts', {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
});
const allWorkoutsResponse = await fetch('/workouts-details', {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
});
const videosResponse = await fetch('/videos', {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
});
if (!workoutsResponse.ok || !allWorkoutsResponse.ok || !videosResponse.ok) {
alert('Failed to load data');
window.location.href = '/';
return;
}
const workouts = await workoutsResponse.json();
const allWorkouts = await allWorkoutsResponse.json();
const videos = await videosResponse.json();
document.getElementById('workoutsCount').innerText = 'A LOT!'//allWorkouts.length;
document.getElementById('videosCount').innerText = videos.length;
const workoutList = document.getElementById('workoutList');
workoutList.innerHTML = '';
workouts.forEach(workout => {
const workoutItem = document.createElement('div');
workoutItem.className = 'workout-item';
workoutItem.innerHTML = `
<span>Workout ID: ${workout.id}</span>
<span>Name : ${workout.name}</span>
<span>Created: ${new Date(workout.createdAt).toLocaleString()}</span>
<a href="#" onclick="event.preventDefault(); viewWorkout(${workout.id});">View Workout</a>
`;
workoutList.appendChild(workoutItem);
});
} catch (error) {
console.error('Error during fetch:', error);
alert('An error occurred, redirecting to login');
window.location.href = '/';
}
});
function viewWorkout(workoutId) {
window.location.href = `/workout.html?workoutId=${workoutId}`;
}
function logout() {
localStorage.removeItem('token');
window.location.href = '/';
}
</script>
</body>
</html>
+96
View File
@@ -0,0 +1,96 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f1f1f1;
}
.container {
display: flex;
flex-direction: column;
align-items: center;
background-color: white;
padding: 40px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.container img {
max-height: 150px;
margin-bottom: 20px;
}
.container form {
display: flex;
flex-direction: column;
width: 100%;
max-width: 300px;
}
.container form label {
margin-bottom: 8px;
font-weight: bold;
}
.container form input {
padding: 10px;
margin-bottom: 20px;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 16px;
}
.container form button {
padding: 10px;
font-size: 16px;
cursor: pointer;
background-color: #007BFF;
color: white;
border: none;
border-radius: 4px;
}
</style>
</head>
<body>
<div class="container">
<img src="VitLogo.png" alt="Logo">
<form id="loginForm">
<label for="username">Username:</label>
<input type="text" id="username" required>
<label for="password">Password:</label>
<input type="password" id="password" required>
<button type="submit">Login</button>
</form>
</div>
<script>
document.getElementById('loginForm').addEventListener('submit', async (e) => {
e.preventDefault();
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
const response = await fetch('/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ username, password })
});
if (response.ok) {
const data = await response.json();
console.log('Received token:', data.token);
localStorage.setItem('token', data.token);
window.location.href = '/dashboard.html';
} else {
alert('Login failed');
}
});
</script>
</body>
</html>
+262
View File
@@ -0,0 +1,262 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Manage Timers</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
height: 100vh;
overflow: hidden;
}
.banner {
width: 100%;
background-color: #f1f1f1;
display: flex;
align-items: center;
justify-content: space-between;
padding: 20px; /* Increased banner size */
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
position: relative;
}
.banner img {
max-height: 200px;
}
.menu-button {
background: none;
border: none;
font-size: 24px;
cursor: pointer;
position: absolute;
top: 0; /* Adjusted to 0 */
left: 20px;
}
.drawer {
width: 250px;
background-color: #f9f9f9;
color: black;
height: 100%;
position: fixed;
top: 0;
left: -250px;
transition: left 0.3s;
z-index: 1000;
}
.drawer.open {
left: 0;
}
.drawer-header {
display: flex;
flex-direction: column;
align-items: center;
padding: 15px;
background-color: #f9f9f9;
}
.drawer-header img {
max-height: 200px;
margin-bottom: 15px;
}
.drawer-header button {
background: none;
border: none;
color: black;
font-size: 24px;
cursor: pointer;
align-self: flex-end;
}
.drawer-content {
padding: 20px;
}
.drawer-content a {
display: block;
color: black;
text-decoration: none;
padding: 10px 0;
border-bottom: 1px solid #007BFF;
}
.main-content {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
transition: margin-left 0.3s;
overflow-y: auto; /* Enable vertical scrolling */
}
.main-content.open {
margin-left: 250px;
}
.main-header {
display: flex;
flex-direction: column;
align-items: center;
padding: 15px;
width: 100%;
}
.main-header img {
max-height: 200px;
}
.main-header h1 {
margin: 10px 0;
}
.content {
padding: 20px;
width: 100%;
max-width: 1200px;
display: flex;
justify-content: space-around;
flex-wrap: wrap;
}
.content div {
background-color: #f9f9f9;
padding: 20px;
border: 1px solid #ddd;
border-radius: 8px;
width: 45%;
text-align: center;
margin: 10px 0;
}
.content h3 {
margin: 0;
margin-bottom: 10px;
}
.content p {
font-size: 24px;
margin: 0;
}
.timer-list {
list-style: none;
padding: 0;
width: 100%;
}
.timer-list li {
display: flex;
justify-content: space-between;
align-items: center;
padding: 15px;
border-bottom: 1px solid #ddd;
background-color: #f9f9f9;
margin-bottom: 10px;
border-radius: 5px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.timer-list a {
color: #007BFF;
text-decoration: none;
}
</style>
</head>
<body>
<div class="banner">
<button class="menu-button" onclick="toggleDrawer()">&#9776;</button>
</div>
<div class="drawer" id="drawer">
<div class="drawer-header">
<img src="VitLogo.png" alt="Logo">
<button onclick="toggleDrawer()">&#10005;</button>
</div>
<div class="drawer-content">
<a href="/dashboard.html">Dashboard</a>
<a href="/upload.html">Upload Video</a>
<a href="/videos.html">Manage Videos</a>
<a href="/create-workout.html">Create Workout</a>
<a href="/workouts.html">Manage Workouts</a>
<a href="/create-crossfit-workout.html">Create CrossFit Workout</a>
<a href="/crossfit-workouts.html">Manage CrossFit Workouts</a>
<a href="/categories.html">Manage Categories</a>
<a href="/manage-timers.html">Manage Timers</a>
<a href="/create-timer.html">Create Timer</a>
</div>
</div>
<div class="main-content" id="main-content">
<div class="main-header">
<img src="VitLogo.png" alt="Logo">
<h1>Manage Timers</h1>
</div>
<div class="content">
<ul id="timerList" class="timer-list"></ul>
</div>
</div>
<script>
const drawer = document.getElementById('drawer');
const mainContent = document.getElementById('main-content');
const timerList = document.getElementById('timerList');
function toggleDrawer() {
drawer.classList.toggle('open');
mainContent.classList.toggle('open');
}
async function fetchTimers() {
const token = localStorage.getItem('token');
if (!token) {
alert('No token found, redirecting to login');
window.location.href = '/';
return;
}
try {
const response = await fetch('/timers', {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
});
if (!response.ok) throw new Error('Failed to fetch timers');
const timers = await response.json();
timerList.innerHTML = '';
timers.forEach(timer => {
const listItem = document.createElement('li');
listItem.innerHTML = `
<span>Timer ID: ${timer.id}</span>
<span>Total Time: ${new Date(timer.totalTime * 1000).toISOString().substr(11, 8)}</span>
<button onclick="deleteTimer(${timer.id})">Delete</button>
<a href="/timer.html?id=${timer.id}">View Timer</a>
`;
timerList.appendChild(listItem);
});
} catch (error) {
console.error('Error fetching timers:', error);
alert('Failed to fetch timers');
}
}
async function deleteTimer(timerId) {
const token = localStorage.getItem('token');
if (!token) {
alert('No token found, redirecting to login');
window.location.href = '/';
return;
}
try {
const response = await fetch(`/timers/${timerId}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
});
if (!response.ok) throw new Error('Failed to delete timer');
fetchTimers();
} catch (error) {
console.error('Error deleting timer:', error);
alert('Failed to delete timer');
}
}
document.addEventListener('DOMContentLoaded', fetchTimers);
</script>
</body>
</html>
+25
View File
@@ -0,0 +1,25 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Redirecting...</title>
<script>
document.addEventListener('DOMContentLoaded', () => {
const params = new URLSearchParams(window.location.search);
const token = params.get('token');
const workoutId = params.get('workoutId');
if (token && workoutId) {
localStorage.setItem('redirectToken', token);
window.location.href = `/workout/${workoutId}`;
} else {
alert('Missing token or workout ID');
window.location.href = '/dashboard.html';
}
});
</script>
</head>
<body>
<p>Redirecting...</p>
</body>
</html>
+413
View File
@@ -0,0 +1,413 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Settings</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
height: 100vh;
overflow: hidden;
}
.banner {
width: 100%;
background-color: #f1f1f1;
display: flex;
align-items: center;
justify-content: space-between;
padding: 20px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
position: relative;
}
.banner img {
max-height: 200px;
}
.menu-button {
background: none;
border: none;
font-size: 24px;
cursor: pointer;
position: absolute;
top: 0;
left: 20px;
}
.drawer {
width: 250px;
background-color: #f9f9f9;
color: black;
height: 100%;
position: fixed;
top: 0;
left: -250px;
transition: left 0.3s;
z-index: 1000;
}
.drawer.open {
left: 0;
}
.drawer-header {
display: flex;
flex-direction: column;
align-items: center;
padding: 15px;
background-color: #f9f9f9;
}
.drawer-header img {
max-height: 200px;
margin-bottom: 15px;
}
.drawer-header button {
background: none;
border: none;
color: black;
font-size: 24px;
cursor: pointer;
align-self: flex-end;
}
.drawer-content {
padding: 20px;
}
.drawer-content a {
display: block;
color: black;
text-decoration: none;
padding: 10px 0;
border-bottom: 1px solid #007BFF;
}
.main-content {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: flex-start;
transition: margin-left 0.3s;
overflow-y: auto;
width: 100%;
}
.main-content.open {
margin-left: 250px;
}
.main-header {
display: flex;
flex-direction: column;
align-items: center;
padding: 15px;
width: 100%;
}
.main-header img {
max-height: 200px;
}
.main-header h1 {
margin: 10px 0;
}
.content {
padding: 20px;
width: 100%;
max-width: 1200px;
}
.content form {
display: flex;
flex-direction: column;
align-items: center;
margin-bottom: 20px;
}
.content form .input-group {
display: flex;
align-items: center;
margin: 10px 0;
width: 100%;
max-width: 800px;
}
.content form select,
.content form input {
padding: 10px;
font-size: 16px;
width: 100%;
max-width: 400px;
}
.content form input {
margin-left: 10px;
}
.content form button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
background-color: #007BFF;
color: white;
border: none;
border-radius: 5px;
margin-top: 20px;
}
.user-list {
display: flex;
flex-direction: column;
align-items: center;
width: 100%;
max-width: 1200px;
}
.user-item {
display: flex;
justify-content: space-between;
align-items: center;
width: 100%;
padding: 10px;
border: 1px solid #ddd;
border-radius: 8px;
margin-bottom: 10px;
}
.user-item span {
flex: 1;
}
.user-item select, .user-item button {
margin-left: 10px;
}
.error-message {
color: red;
font-weight: bold;
}
.logo-upload {
display: flex;
flex-direction: column;
align-items: center;
margin-top: 20px;
}
</style>
</head>
<body>
<div class="banner">
<button class="menu-button" onclick="toggleDrawer()">&#9776;</button>
</div>
<div class="drawer" id="drawer">
<div class="drawer-header">
<img src="VitLogo.png" alt="Logo">
<button onclick="toggleDrawer()">&#10005;</button>
</div>
<div class="drawer-content">
<a href="/dashboard.html">Dashboard</a>
<a href="/upload.html">Upload Video</a>
<a href="/videos.html">Manage Videos</a>
<a href="/create-workout.html">Create Workout</a>
<a href="/workouts.html">Manage Workouts</a>
<a href="/create-crossfit-workout.html">Create CrossFit Workout</a>
<a href="/crossfit-workouts.html">Manage CrossFit Workouts</a>
<a href="/categories.html">Manage Categories</a>
<a href="/manage-timers.html">Manage Timers</a>
<a href="/create-timer.html">Create Timer</a>
<a href="/settings.html" id="settingsLink">Settings</a>
<a href="#" onclick="logout()">Logout</a>
</div>
</div>
<div class="main-content" id="main-content">
<div class="main-header">
<img src="VitLogo.png" alt="Logo">
<h1>Settings</h1>
</div>
<div class="content">
<form id="createUserForm">
<div class="input-group">
<input type="text" id="username" placeholder="Username" required>
<input type="password" id="password" placeholder="Password" required>
<div class="content">
<select id="role">
<option value="Coach">Coach</option>
<option value="Admin">Admin</option>
</select>
</div>
</div>
<button type="submit">Create User</button>
<div id="errorMessage" class="error-message"></div>
</form>
<div class="user-list" id="userList"></div>
<div class="logo-upload">
<h3>Current Logo:</h3>
<img src="VitLogo.png" alt="Current Logo" id="currentLogo" style="max-height: 200px; margin-bottom: 20px;">
<form id="uploadLogoForm" enctype="multipart/form-data">
<input type="file" id="logo" name="logo" accept="image/*">
<button type="submit">Upload New Logo</button>
</form>
<div id="uploadMessage" class="error-message"></div>
</div>
</div>
</div>
<script>
const drawer = document.getElementById('drawer');
const mainContent = document.getElementById('main-content');
const createUserForm = document.getElementById('createUserForm');
const errorMessage = document.getElementById('errorMessage');
const userList = document.getElementById('userList');
const uploadLogoForm = document.getElementById('uploadLogoForm');
const uploadMessage = document.getElementById('uploadMessage');
function toggleDrawer() {
drawer.classList.toggle('open');
mainContent.classList.toggle('open');
}
function logout() {
localStorage.removeItem('token');
window.location.href = '/';
}
async function fetchUsers() {
const token = localStorage.getItem('token');
try {
const response = await fetch('/users', {
headers: {
'Authorization': `Bearer ${token}`
}
});
if (!response.ok) {
throw new Error('Failed to fetch users');
}
const users = await response.json();
userList.innerHTML = '';
users.forEach(user => {
const userItem = document.createElement('div');
userItem.className = 'user-item';
userItem.innerHTML = `
<span>${user.username}</span>
<select data-user-id="${user.id}">
<option value="Coach" ${user.role === 'Coach' ? 'selected' : ''}>Coach</option>
<option value="Admin" ${user.role === 'Admin' ? 'selected' : ''}>Admin</option>
</select>
<button onclick="resetPassword(${user.id})">Reset Password</button>
<button onclick="deleteUser(${user.id})">Delete</button>
`;
userList.appendChild(userItem);
const roleSelect = userItem.querySelector('select');
roleSelect.addEventListener('change', async () => {
const newRole = roleSelect.value;
await updateUserRole(user.id, newRole);
alert('User role updated successfully');
});
});
} catch (error) {
console.error('Error fetching users:', error);
errorMessage.textContent = 'Error fetching users';
}
}
async function updateUserRole(userId, newRole) {
const token = localStorage.getItem('token');
try {
const response = await fetch(`/users/${userId}/role`, {
method: 'PUT',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ role: newRole })
});
if (!response.ok) {
throw new Error('Failed to update user role');
}
} catch (error) {
console.error('Error updating user role:', error);
errorMessage.textContent = 'Error updating user role';
}
}
async function deleteUser(userId) {
const token = localStorage.getItem('token');
if (confirm('Are you sure you want to delete this user?')) {
try {
const response = await fetch(`/users/${userId}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${token}`
}
});
if (!response.ok) {
throw new Error('Failed to delete user');
}
fetchUsers();
} catch (error) {
console.error('Error deleting user:', error);
errorMessage.textContent = 'Error deleting user';
}
}
}
async function resetPassword(userId) {
const token = localStorage.getItem('token');
const newPassword = prompt('Enter new password:');
if (newPassword) {
try {
const response = await fetch(`/users/${userId}/password`, {
method: 'PUT',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ password: newPassword })
});
if (!response.ok) {
throw new Error('Failed to reset password');
}
alert('Password reset successfully');
} catch (error) {
console.error('Error resetting password:', error);
errorMessage.textContent = 'Error resetting password';
}
}
}
createUserForm.addEventListener('submit', async (e) => {
e.preventDefault();
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
const role = document.getElementById('role').value;
const token = localStorage.getItem('token');
try {
const response = await fetch('/users', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ username, password, role })
});
if (!response.ok) {
throw new Error('Failed to create user');
}
createUserForm.reset();
fetchUsers();
} catch (error) {
console.error('Error creating user:', error);
errorMessage.textContent = 'Error creating user';
}
});
uploadLogoForm.addEventListener('submit', async (e) => {
e.preventDefault();
const token = localStorage.getItem('token');
const formData = new FormData(uploadLogoForm);
try {
const response = await fetch('/upload-logo', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`
},
body: formData
});
if (!response.ok) {
throw new Error('Failed to upload logo');
}
uploadMessage.textContent = 'Logo uploaded successfully';
document.getElementById('currentLogo').src = 'VitLogo.png';
} catch (error) {
console.error('Error uploading logo:', error);
uploadMessage.textContent = 'Error uploading logo';
}
});
document.addEventListener('DOMContentLoaded', fetchUsers);
</script>
</body>
</html>
+177
View File
@@ -0,0 +1,177 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Timer</title>
<style>
body, html {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
background-color: #f9f9f9;
}
.timer {
font-size: 2em;
font-weight: bold;
padding: 20px;
border: 2px solid #ddd;
border-radius: 10px;
background-color: white;
margin-bottom: 20px;
}
.timer.green {
background-color: green;
color: white;
}
.timer.blue {
background-color: blue;
color: white;
}
.timer.red {
background-color: red;
color: white;
}
.controls {
margin-top: 20px;
}
.controls button {
padding: 10px 20px;
font-size: 1em;
margin: 0 10px;
cursor: pointer;
}
</style>
</head>
<body>
<div id="totalTimeDisplay" class="timer"></div>
<div id="exerciseDisplay" class="timer"></div>
<div id="setDisplay" class="timer"></div>
<div id="lapDisplay" class="timer"></div>
<div class="controls">
<button id="startButton">Start</button>
<button id="stopButton" disabled>Stop</button>
</div>
<script>
const urlParams = new URLSearchParams(window.location.search);
const timerId = urlParams.get('id');
let totalTime, setTime, restTime, moveTime, setCount, exerciseCount, lapCount;
let currentLap = 0;
let currentExercise = 0;
let currentSet = 0;
let currentPhase = 'set';
let timeLeft, totalTimeLeft;
let interval;
const totalTimeDisplay = document.getElementById('totalTimeDisplay');
const exerciseDisplay = document.getElementById('exerciseDisplay');
const setDisplay = document.getElementById('setDisplay');
const lapDisplay = document.getElementById('lapDisplay');
const startButton = document.getElementById('startButton');
const stopButton = document.getElementById('stopButton');
startButton.addEventListener('click', startTimer);
stopButton.addEventListener('click', stopTimer);
async function fetchTimerData() {
const response = await fetch(`/timers/${timerId}`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${localStorage.getItem('token')}`,
'Content-Type': 'application/json'
}
});
if (!response.ok) {
alert('Failed to fetch timer data');
return;
}
const timerData = await response.json();
totalTime = timerData.totalTime;
setTime = timerData.setTime;
restTime = timerData.restTime;
moveTime = timerData.moveTime;
setCount = timerData.setCount;
exerciseCount = timerData.exerciseCount;
lapCount = timerData.lapCount;
timeLeft = setTime;
totalTimeLeft = totalTime;
updateDisplay();
}
function formatTime(seconds) {
const hrs = Math.floor(seconds / 3600);
const mins = Math.floor((seconds % 3600) / 60);
const secs = seconds % 60;
return `${String(hrs).padStart(2, '0')}:${String(mins).padStart(2, '0')}:${String(secs).padStart(2, '0')}`;
}
function updateDisplay() {
totalTimeDisplay.textContent = `Total Time: ${formatTime(totalTimeLeft)}`;
setDisplay.textContent = `${currentPhase === 'set' ? 'Set' : currentPhase === 'rest' ? 'Rest' : 'Transition'} Time: ${formatTime(timeLeft)}`;
setDisplay.className = `timer ${currentPhase === 'set' ? 'green' : currentPhase === 'rest' ? 'blue' : 'red'}`;
exerciseDisplay.textContent = `Exercise: ${currentExercise + 1} / ${exerciseCount}`;
lapDisplay.textContent = `Lap: ${currentLap + 1} / ${lapCount}`;
}
function startTimer() {
startButton.disabled = true;
stopButton.disabled = false;
interval = setInterval(timer, 1000);
}
function stopTimer() {
startButton.disabled = false;
stopButton.disabled = true;
clearInterval(interval);
}
function timer() {
totalTimeLeft--;
timeLeft--;
if (totalTimeLeft <= 0) {
clearInterval(interval);
alert('Workout complete!');
return;
}
if (timeLeft < 0) {
if (currentPhase === 'set') {
if (currentSet < setCount - 1) {
currentPhase = 'rest';
timeLeft = restTime;
currentSet++;
} else {
currentPhase = 'move';
timeLeft = moveTime;
}
} else if (currentPhase === 'rest') {
currentPhase = 'set';
timeLeft = setTime;
} else if (currentPhase === 'move') {
currentExercise++;
if (currentExercise >= exerciseCount) {
currentExercise = 0;
currentLap++;
if (currentLap >= lapCount) {
clearInterval(interval);
alert('Workout complete!');
return;
}
}
currentPhase = 'set';
timeLeft = setTime;
currentSet = 0;
}
}
updateDisplay();
}
document.addEventListener('DOMContentLoaded', fetchTimerData);
</script>
</body>
</html>
+274
View File
@@ -0,0 +1,274 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Upload Video</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
height: 100vh;
overflow: hidden;
}
.banner {
width: 100%;
background-color: #f1f1f1;
display: flex;
align-items: center;
justify-content: space-between;
padding: 20px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
position: relative;
}
.banner img {
max-height: 200px;
}
.menu-button {
background: none;
border: none;
font-size: 24px;
cursor: pointer;
position: absolute;
top: 0;
left: 20px;
}
.drawer {
width: 250px;
background-color: #f9f9f9;
color: black;
height: 100%;
position: fixed;
top: 0;
left: -250px;
transition: left 0.3s;
z-index: 1000;
}
.drawer.open {
left: 0;
}
.drawer-header {
display: flex;
flex-direction: column;
align-items: center;
padding: 15px;
background-color: #f9f9f9;
}
.drawer-header img {
max-height: 200px;
margin-bottom: 15px;
}
.drawer-header button {
background: none;
border: none;
color: black;
font-size: 24px;
cursor: pointer;
align-self: flex-end;
}
.drawer-content {
padding: 20px;
}
.drawer-content a {
display: block;
color: black;
text-decoration: none;
padding: 10px 0;
border-bottom: 1px solid #0056b3;
}
.main-content {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
transition: margin-left 0.3s;
}
.main-content.open {
margin-left: 250px;
}
.main-header {
display: flex;
flex-direction: column;
align-items: center;
padding: 15px;
width: 100%;
}
.main-header img {
max-height: 200px;
}
.main-header h1 {
margin: 10px 0;
}
.content {
padding: 20px;
width: 100%;
max-width: 1200px;
}
.content form {
display: flex;
flex-direction: column;
align-items: center;
}
.content form input,
.content form select {
margin: 10px 0;
padding: 10px;
font-size: 16px;
width: 100%;
max-width: 400px;
}
.content form button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
background-color: #007BFF;
color: white;
border: none;
border-radius: 5px;
}
</style>
</head>
<body>
<div class="banner">
<button class="menu-button" onclick="toggleDrawer()">&#9776;</button>
</div>
<div class="drawer" id="drawer">
<div class="drawer-header">
<img src="VitLogo.png" alt="Logo">
<button onclick="toggleDrawer()">&#10005;</button>
</div>
<div class="drawer-content">
<a href="/dashboard.html">Dashboard</a>
<a href="/upload.html">Upload Video</a>
<a href="/videos.html">Manage Videos</a>
<a href="/create-workout.html">Create Workout</a>
<a href="/workouts.html">Manage Workouts</a>
<a href="/create-crossfit-workout.html">Create CrossFit Workout</a>
<a href="/crossfit-workouts.html">Manage CrossFit Workouts</a>
<a href="/categories.html">Manage Categories</a>
<a href="/manage-timers.html">Manage Timers</a>
<a href="/create-timer.html">Create Timer</a>
<a href="/settings.html" id="settingsLink" style="display:none;">Settings</a>
<a href="#" onclick="logout()">Logout</a>
</div>
</div>
<div class="main-content" id="main-content">
<div class="main-header">
<img src="VitLogo.png" alt="Logo">
<h1>Upload Video</h1>
</div>
<div class="content">
<form id="uploadForm" enctype="multipart/form-data">
<input type="file" name="video" id="video" accept="video/*" required>
<input type="text" name="description" id="description" placeholder="Video Description" required>
<select name="category" id="category" required>
<option value="">Select Category</option>
</select>
<button type="submit">Upload Video</button>
</form>
</div>
</div>
<script>
const drawer = document.getElementById('drawer');
const mainContent = document.getElementById('main-content');
const uploadForm = document.getElementById('uploadForm');
const categorySelect = document.getElementById('category');
function toggleDrawer() {
drawer.classList.toggle('open');
mainContent.classList.toggle('open');
}
function logout() {
localStorage.removeItem('token');
window.location.href = '/';
}
async function checkAdmin() {
const token = localStorage.getItem('token');
if (!token) {
alert('No token found, redirecting to login');
window.location.href = '/';
return;
}
const response = await fetch('/profile', {
headers: {
'Authorization': `Bearer ${token}`
}
});
const user = await response.json();
console.log('User fetched:', user); // Log the fetched user
if (user.role === 'Admin') {
document.getElementById('settingsLink').style.display = 'block';
} else {
console.log('User is not an admin'); // Log if user is not admin
}
}
document.addEventListener('DOMContentLoaded', async () => {
const token = localStorage.getItem('token');
if (!token) {
alert('No token found, redirecting to login');
window.location.href = '/';
return;
}
await checkAdmin();
try {
const categoriesResponse = await fetch('/categories', {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
});
if (!categoriesResponse.ok) {
alert('Failed to load categories');
window.location.href = '/';
return;
}
const categories = await categoriesResponse.json();
categories.forEach(category => {
const option = document.createElement('option');
option.value = category.name;
option.textContent = category.name;
categorySelect.appendChild(option);
});
} catch (error) {
console.error('Error fetching categories:', error);
alert('An error occurred, redirecting to login');
window.location.href = '/';
}
uploadForm.addEventListener('submit', async (event) => {
event.preventDefault();
const formData = new FormData(uploadForm);
try {
const response = await fetch('/upload', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`
},
body: formData
});
if (response.ok) {
alert('Video uploaded successfully');
window.location.href = '/videos.html';
} else {
alert('Failed to upload video');
}
} catch (error) {
console.error('Error uploading video:', error);
alert('An error occurred while uploading the video');
}
});
});
</script>
</body>
</html>
+341
View File
@@ -0,0 +1,341 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Manage Videos</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
height: 100vh;
overflow: hidden;
}
.banner {
width: 100%;
background-color: #f1f1f1;
display: flex;
align-items: center;
justify-content: space-between;
padding: 20px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
position: relative;
}
.banner img {
max-height: 200px;
}
.menu-button {
background: none;
border: none;
font-size: 24px;
cursor: pointer;
position: absolute;
top: 0;
left: 20px;
}
.drawer {
width: 250px;
background-color: #f9f9f9;
color: black;
height: 100%;
position: fixed;
top: 0;
left: -250px;
transition: left 0.3s;
z-index: 1000;
}
.drawer.open {
left: 0;
}
.drawer-header {
display: flex;
flex-direction: column;
align-items: center;
padding: 15px;
background-color: #f9f9f9;
}
.drawer-header img {
max-height: 200px;
margin-bottom: 15px;
}
.drawer-header button {
background: none;
border: none;
color: black;
font-size: 24px;
cursor: pointer;
align-self: flex-end;
}
.drawer-content {
padding: 20px;
}
.drawer-content a {
display: block;
color: black;
text-decoration: none;
padding: 10px 0;
border-bottom: 1px solid #0056b3;
}
.main-content {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: flex-start;
overflow-y: auto; /* Enable vertical scrolling */
transition: margin-left 0.3s;
}
.main-content.open {
margin-left: 250px;
}
.main-header {
display: flex;
flex-direction: column;
align-items: center;
padding: 15px;
width: 100%;
}
.main-header img {
max-height: 200px;
}
.main-header h1 {
margin: 10px 0;
}
.content {
padding: 20px;
width: 100%;
max-width: 1200px;
}
.filter-bar {
display: flex;
justify-content: center;
margin-bottom: 20px;
}
.filter-bar select {
padding: 10px;
font-size: 16px;
}
.video-list {
display: flex;
flex-wrap: wrap;
justify-content: space-around;
}
.video-item {
display: flex;
flex-direction: column;
align-items: center;
background-color: #f9f9f9;
padding: 10px;
border: 1px solid #ddd;
border-radius: 8px;
margin-bottom: 10px;
width: 45%;
box-sizing: border-box;
}
.video-item video {
max-width: 100%;
border-radius: 8px;
}
.video-item div {
text-align: center;
}
.video-item button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
background-color: #ff4b5c;
color: white;
border: none;
border-radius: 5px;
margin-top: 10px;
}
</style>
</head>
<body>
<div class="banner">
<button class="menu-button" onclick="toggleDrawer()">&#9776;</button>
</div>
<div class="drawer" id="drawer">
<div class="drawer-header">
<img src="VitLogo.png" alt="Logo">
<button onclick="toggleDrawer()">&#10005;</button>
</div>
<div class="drawer-content">
<a href="/dashboard.html">Dashboard</a>
<a href="/upload.html">Upload Video</a>
<a href="/videos.html">Manage Videos</a>
<a href="/create-workout.html">Create Workout</a>
<a href="/workouts.html">Manage Workouts</a>
<a href="/create-crossfit-workout.html">Create CrossFit Workout</a>
<a href="/crossfit-workouts.html">Manage CrossFit Workouts</a>
<a href="/categories.html">Manage Categories</a>
<a href="/manage-timers.html">Manage Timers</a>
<a href="/create-timer.html">Create Timer</a>
<a href="/settings.html" id="settingsLink" style="display:none;">Settings</a>
<a href="#" onclick="logout()">Logout</a>
</div>
</div>
<div class="main-content" id="main-content">
<div class="main-header">
<img src="VitLogo.png" alt="Logo">
<h1>Manage Videos</h1>
</div>
<div class="content">
<div class="filter-bar">
<select id="categoryFilter">
<option value="">All Categories</option>
</select>
</div>
<div class="video-list" id="videoList"></div>
</div>
</div>
<script>
const drawer = document.getElementById('drawer');
const mainContent = document.getElementById('main-content');
const categoryFilter = document.getElementById('categoryFilter');
const videoList = document.getElementById('videoList');
function toggleDrawer() {
drawer.classList.toggle('open');
mainContent.classList.toggle('open');
}
function logout() {
localStorage.removeItem('token');
window.location.href = '/';
}
async function checkAdmin() {
const token = localStorage.getItem('token');
if (!token) {
alert('No token found, redirecting to login');
window.location.href = '/';
return;
}
const response = await fetch('/profile', {
headers: {
'Authorization': `Bearer ${token}`
}
});
const user = await response.json();
console.log('User fetched:', user); // Log the fetched user
if (user.role === 'Admin') {
document.getElementById('settingsLink').style.display = 'block';
} else {
console.log('User is not an admin'); // Log if user is not admin
}
}
document.addEventListener('DOMContentLoaded', async () => {
const token = localStorage.getItem('token');
if (!token) {
alert('No token found, redirecting to login');
window.location.href = '/';
return;
}
await checkAdmin();
try {
const [videosResponse, categoriesResponse] = await Promise.all([
fetch('/videos', {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
}),
fetch('/categories', {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
})
]);
if (!videosResponse.ok || !categoriesResponse.ok) {
alert('Failed to load data');
window.location.href = '/';
return;
}
const videos = await videosResponse.json();
const categories = await categoriesResponse.json();
categories.forEach(category => {
const option = document.createElement('option');
option.value = category.name;
option.textContent = category.name;
categoryFilter.appendChild(option);
});
function displayVideos(videosToDisplay) {
videoList.innerHTML = '';
videosToDisplay.forEach(video => {
const videoItem = document.createElement('div');
videoItem.className = 'video-item';
videoItem.innerHTML = `
<video src="/uploads/${video.filename}" controls></video>
<div>
<h3>${video.description}</h3>
<p>Category: ${video.category}</p>
</div>
<button onclick="deleteVideo(${video.id})">Delete</button>
`;
videoList.appendChild(videoItem);
});
}
displayVideos(videos);
categoryFilter.addEventListener('change', () => {
const selectedCategory = categoryFilter.value;
if (selectedCategory === '') {
displayVideos(videos);
} else {
const filteredVideos = videos.filter(video => video.category === selectedCategory);
displayVideos(filteredVideos);
}
});
} catch (error) {
console.error('Error fetching data:', error);
alert('An error occurred, redirecting to login');
window.location.href = '/';
}
});
async function deleteVideo(videoId) {
const token = localStorage.getItem('token');
if (!token) {
alert('No token found, redirecting to login');
window.location.href = '/';
return;
}
if (confirm('Are you sure you want to delete this video?')) {
try {
const response = await fetch(`/videos/${videoId}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
});
if (response.ok) {
alert('Video deleted successfully');
window.location.reload();
} else {
alert('Failed to delete video');
}
} catch (error) {
console.error('Error deleting video:', error);
alert('An error occurred while deleting the video');
}
}
}
</script>
</body>
</html>
+125
View File
@@ -0,0 +1,125 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Workout</title>
<style>
body, html {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
background-color: #000;
font-family: Arial, sans-serif;
overflow: hidden; /* Prevents scrollbars */
}
.video-container {
display: grid;
width: 100%;
height: 100%;
grid-template-columns: repeat(2, 1fr);
grid-template-rows: repeat(2, 1fr);
}
.video-item {
position: relative;
width: 100%;
height: 100%;
background-color: black;
overflow: hidden;
display: flex;
align-items: center;
justify-content: center;
}
.video-item video {
width: 100%;
height: 100%;
object-fit: cover;
}
.overlay {
position: absolute;
top: 10px;
left: 10px;
background-color: rgba(0, 0, 0, 0.7);
color: white;
padding: 5px 10px;
border-radius: 5px;
font-size: 100px;
}
</style>
</head>
<body>
<div class="video-container" id="videoContainer"></div>
<script>
document.addEventListener('DOMContentLoaded', async () => {
const videoContainer = document.getElementById('videoContainer');
const workoutId = new URLSearchParams(window.location.search).get('workoutId');
const token = localStorage.getItem('token');
if (!token) {
console.error('No token found');
videoContainer.innerHTML = "<p>Error: Unauthorized. Please log in.</p>";
return;
}
try {
const response = await fetch(`/workout-data/${workoutId}`, {
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Failed to fetch workout data: ${errorText}`);
}
const workout = await response.json();
const videos = [];
if (workout.video1) videos.push({ file: workout.video1, number: workout.number1 });
if (workout.video2) videos.push({ file: workout.video2, number: workout.number2 });
if (workout.video3) videos.push({ file: workout.video3, number: workout.number3 });
if (workout.video4) videos.push({ file: workout.video4, number: workout.number4 });
if (videos.length === 1) {
videoContainer.style.gridTemplateColumns = "1fr";
videoContainer.style.gridTemplateRows = "1fr";
} else if (videos.length === 2) {
videoContainer.style.gridTemplateColumns = "1fr 1fr";
videoContainer.style.gridTemplateRows = "1fr";
} else if (videos.length > 2) {
videoContainer.style.gridTemplateColumns = "1fr 1fr";
videoContainer.style.gridTemplateRows = "1fr 1fr";
}
videos.forEach((video) => {
if (video.file) {
const videoItem = document.createElement('div');
videoItem.className = 'video-item';
videoItem.innerHTML = `
<video src="/uploads/${video.file}" autoplay muted loop playsinline></video>
<div class="overlay">${video.number || ''}</div>
`;
videoContainer.appendChild(videoItem);
}
});
if (videoContainer.children.length === 0) {
videoContainer.innerHTML = "<p>No videos found for this workout.</p>";
}
setTimeout(() => {
location.reload();
}, 300000); // 7 minutes in milliseconds
} catch (error) {
console.error('Error fetching workout data:', error);
videoContainer.innerHTML = `<p>Error loading workout data: ${error.message}</p>`;
}
});
</script>
</body>
</html>
+407
View File
@@ -0,0 +1,407 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Manage Workouts</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
height: 100vh;
overflow: hidden; /* Prevent multiple scroll bars */
}
.banner {
width: 100%;
background-color: #f1f1f1;
display: flex;
align-items: center;
justify-content: space-between;
padding: 20px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
position: relative;
}
.banner img {
max-height: 200px;
}
.menu-button {
background: none;
border: none;
font-size: 24px;
cursor: pointer;
position: absolute;
top: 0;
left: 20px;
}
.drawer {
width: 250px;
background-color: #f9f9f9;
color: black;
height: 100%;
position: fixed;
top: 0;
left: -250px;
transition: left 0.3s;
z-index: 1000;
}
.drawer.open {
left: 0;
}
.drawer-header {
display: flex;
flex-direction: column;
align-items: center;
padding: 15px;
background-color: #f9f9f9;
}
.drawer-header img {
max-height: 200px;
margin-bottom: 15px;
}
.drawer-header button {
background: none;
border: none;
color: black;
font-size: 24px;
cursor: pointer;
align-self: flex-end;
}
.drawer-content {
padding: 20px;
}
.drawer-content a {
display: block;
color: black;
text-decoration: none;
padding: 10px 0;
border-bottom: 1px solid #ddd;
}
.main-content {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: flex-start; /* Adjusted to flex-start to align items to the top */
transition: margin-left 0.3s;
overflow-y: auto; /* Only vertical scroll bar */
width: 100%;
}
.main-content.open {
margin-left: 250px;
}
.main-header {
display: flex;
flex-direction: column;
align-items: center;
padding: 15px;
width: 100%;
}
.main-header img {
max-height: 200px;
}
.main-header h1 {
margin: 10px 0;
}
.content {
padding: 20px;
width: 100%;
max-width: 1200px; /* Center the content */
}
.workout-list {
list-style: none;
padding: 0;
width: 100%;
max-width: 1200px;
}
.workout-list li {
display: flex;
flex-direction: column;
align-items: center;
justify-content: space-between;
padding: 20px;
border-bottom: 1px solid #ddd;
margin-bottom: 10px;
background-color: #f9f9f9;
border-radius: 5px;
}
.workout-header {
display: flex;
justify-content: space-between;
width: 100%;
margin-bottom: 10px;
}
.workout-header h2 {
margin: 0;
}
.workout-details {
display: flex;
flex-wrap: wrap;
justify-content: space-around;
width: 100%;
}
.workout-details div {
display: flex;
flex-direction: column;
align-items: center;
margin: 10px;
}
.workout-details video {
width: 150px;
height: 100px;
background: black;
}
.workout-footer {
display: flex;
justify-content: flex-end;
width: 100%;
margin-top: 10px;
}
.delete-button {
background-color: #ff4b5c;
color: white;
border: none;
border-radius: 5px;
padding: 10px 20px;
cursor: pointer;
}
.view-button {
background-color: #095FF6;
color: white;
border: none;
border-radius: 5px;
padding: 10px 20px;
cursor: pointer;
}
.pagination {
display: flex;
justify-content: center;
align-items: center;
gap: 10px;
margin: 20px 0;
}
.pagination button {
background-color: #095FF6;
color: white;
border: none;
border-radius: 5px;
padding: 10px 20px;
cursor: pointer;
font-size: 16px;
transition: background-color 0.3s;
}
.pagination button:disabled {
background-color: #ccc;
cursor: not-allowed;
}
.pagination button:hover:not(:disabled) {
background-color: #063d8c;
}
/* Top pagination bar */
.pagination.top {
margin-top: 10px; /* Adjust the spacing under the header */
}
/* Bottom pagination bar */
.pagination.bottom {
margin-top: auto;
margin-bottom: 10px;
}
</style>
</head>
<body>
<div class="banner">
<button class="menu-button" onclick="toggleDrawer()">&#9776;</button>
</div>
<div class="drawer" id="drawer">
<div class="drawer-header">
<img src="VitLogo.png" alt="Logo">
<button onclick="toggleDrawer()">&#10005;</button>
</div>
<div class="drawer-content">
<a href="/dashboard.html">Dashboard</a>
<a href="/upload.html">Upload Video</a>
<a href="/videos.html">Manage Videos</a>
<a href="/create-workout.html">Create Workout</a>
<a href="/workouts.html">Manage Workouts</a>
<a href="/create-crossfit-workout.html">Create CrossFit Workout</a>
<a href="/crossfit-workouts.html">Manage CrossFit Workouts</a>
<a href="/categories.html">Manage Categories</a>
<a href="/manage-timers.html">Manage Timers</a>
<a href="/create-timer.html">Create Timer</a>
</div>
</div>
<div class="main-content" id="main-content">
<div class="main-header">
<img src="VitLogo.png" alt="Logo">
<h1>Manage Workouts</h1>
</div>
<div class="content">
<ul id="workoutList" class="workout-list"></ul>
</div>
</div>
<div class="pagination">
<button id="prevPage" disabled>Previous</button>
<span id="currentPage">Page 1</span>
<button id="nextPage">Next</button>
</div>
<script>
const drawer = document.getElementById('drawer');
const mainContent = document.getElementById('main-content');
const workoutList = document.getElementById('workoutList');
function toggleDrawer() {
drawer.classList.toggle('open');
mainContent.classList.toggle('open');
}
document.addEventListener('DOMContentLoaded', async () => {
const token = localStorage.getItem('token');
if (!token) {
alert('No token found, redirecting to login');
window.location.href = '/';
return;
}
let currentPage = 1;
const limit = 20;
async function fetchWorkouts(page) {
try {
const response = await fetch(`/workouts-details?page=${page}&limit=${limit}`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Failed to fetch workouts: ${errorText}`);
}
const { workouts, totalPages, currentPage } = await response.json();
workoutList.innerHTML = '';
workouts.forEach(workout => {
const li = document.createElement('li');
const workoutHeader = document.createElement('div');
workoutHeader.className = 'workout-header';
workoutHeader.innerHTML = `<h2>Workout ID: ${workout.id} Name: ${workout.name || 'Unnamed'} Created: ${new Date(workout.createdAt).toLocaleString()}</h2>`;
const workoutDetails = document.createElement('div');
workoutDetails.className = 'workout-details';
[workout.video1Details, workout.video2Details, workout.video3Details, workout.video4Details].forEach(video => {
if (video) {
const videoDiv = document.createElement('div');
videoDiv.innerHTML = `
<video src="/uploads/${video.filename}" controls></video>
<p>${video.description}</p>
<p>${video.category}</p>
`;
workoutDetails.appendChild(videoDiv);
}
});
const workoutFooter = document.createElement('div');
workoutFooter.className = 'workout-footer';
const deleteButton = document.createElement('button');
deleteButton.className = 'delete-button';
deleteButton.textContent = 'Delete Workout';
deleteButton.onclick = async () => {
await deleteWorkout(workout.id);
};
const viewButton = document.createElement('button');
viewButton.className = 'view-button';
viewButton.textContent = 'View Workout';
viewButton.onclick = () => viewWorkout(workout.id);
workoutFooter.appendChild(viewButton);
workoutFooter.appendChild(deleteButton);
li.appendChild(workoutHeader);
li.appendChild(workoutDetails);
li.appendChild(workoutFooter);
workoutList.appendChild(li);
});
// Update pagination controls
document.getElementById('currentPage').textContent = `Page ${currentPage}`;
document.getElementById('prevPage').disabled = currentPage === 1;
document.getElementById('nextPage').disabled = currentPage === totalPages;
} catch (error) {
console.error('Error fetching workouts:', error);
alert(`An error occurred while fetching workouts: ${error.message}`);
}
}
document.getElementById('prevPage').addEventListener('click', () => {
if (currentPage > 1) {
currentPage--;
fetchWorkouts(currentPage);
}
});
document.getElementById('nextPage').addEventListener('click', () => {
currentPage++;
fetchWorkouts(currentPage);
});
// View workout
function viewWorkout(workoutId) {
window.location.href = `/workout.html?workoutId=${workoutId}`;
}
async function deleteWorkout(workoutId) {
try {
const response = await fetch(`/workouts/${workoutId}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Failed to delete workout: ${errorText}`);
}
fetchWorkouts(currentPage);
} catch (error) {
console.error('Error deleting workout:', error);
alert(`An error occurred while deleting the workout: ${error.message}`);
}
}
fetchWorkouts(currentPage);
});
</script>
</body>
</html>
+2
View File
@@ -0,0 +1,2 @@
#!/bin/bash
forever start /home/ubuntu/site/app.js