Release 1.0.0
This commit is contained in:
30
.dockerignore
Normal file
30
.dockerignore
Normal file
@@ -0,0 +1,30 @@
|
||||
# Dependencies
|
||||
node_modules
|
||||
npm-debug.log*
|
||||
|
||||
# Git
|
||||
.git
|
||||
.gitignore
|
||||
|
||||
# Docker
|
||||
Dockerfile
|
||||
.dockerignore
|
||||
|
||||
# Development files
|
||||
*.log
|
||||
.env
|
||||
.env.local
|
||||
|
||||
# OS generated files
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# IDE files
|
||||
.vscode/
|
||||
.idea/
|
||||
*.swp
|
||||
*.swo
|
||||
|
||||
# Cache directories
|
||||
.npm
|
||||
.cache
|
||||
20
Dockerfile
Normal file
20
Dockerfile
Normal file
@@ -0,0 +1,20 @@
|
||||
# Use Node.js official image
|
||||
FROM node:lts-alpine
|
||||
|
||||
# Set working directory
|
||||
WORKDIR /app
|
||||
|
||||
# Copy package files
|
||||
COPY package*.json ./
|
||||
|
||||
# Install dependencies
|
||||
RUN npm ci --only=production
|
||||
|
||||
# Copy application files
|
||||
COPY . .
|
||||
|
||||
# Expose port
|
||||
EXPOSE 3000
|
||||
|
||||
# Start the application
|
||||
CMD ["npm", "start"]
|
||||
71
README.md
Normal file
71
README.md
Normal file
@@ -0,0 +1,71 @@
|
||||
# zyBooksBot
|
||||
|
||||
An automation bot for the zyBooks learning platform. Automatically complete Challenge Activities and Participation Activities with batch processing and real-time progress tracking.
|
||||
|
||||
## Features
|
||||
|
||||
- Automated completion for zyBooks Challenge and Participation Activities
|
||||
- Batch processing for multiple chapters and sections
|
||||
- Real-time progress tracking with detailed status
|
||||
- Modern web interface with multi-select capabilities
|
||||
- Stateless architecture supporting multiple users
|
||||
- Robust error handling and recovery
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Option 1: Docker (Recommended)
|
||||
|
||||
**Prerequisites:** Docker and Docker Compose
|
||||
|
||||
```bash
|
||||
git clone https://git.qzydustin.com/qzydustin/zyBooksBot
|
||||
cd zyBooksBot
|
||||
docker-compose up -d
|
||||
```
|
||||
|
||||
### Option 2: Local Development
|
||||
|
||||
**Prerequisites:** Node.js (v14+)
|
||||
|
||||
```bash
|
||||
git clone https://git.qzydustin.com/qzydustin/zyBooksBot
|
||||
cd zyBooksBot
|
||||
npm install
|
||||
npm start
|
||||
```
|
||||
|
||||
Open http://localhost:3000 in your browser.
|
||||
|
||||
## Usage
|
||||
|
||||
1. Login with your zyBooks credentials
|
||||
2. Select books and chapters
|
||||
3. Use checkboxes for batch selection
|
||||
4. Execute and monitor real-time progress
|
||||
|
||||
## Docker Commands
|
||||
|
||||
```bash
|
||||
# Start the application
|
||||
docker-compose up -d
|
||||
|
||||
# View logs
|
||||
docker-compose logs -f
|
||||
|
||||
# Stop the application
|
||||
docker-compose down
|
||||
|
||||
# Rebuild after code changes
|
||||
docker-compose up --build -d
|
||||
```
|
||||
|
||||
## Technical Details
|
||||
|
||||
**Stack:** Node.js, Express.js, JavaScript
|
||||
**Communication:** HTTP API with Server-Sent Events
|
||||
**Key Features:** Real-time streaming, frontend state management
|
||||
**Deployment:** Docker containerized with health checks
|
||||
|
||||
## Important Notes
|
||||
|
||||
This tool is for educational purposes. Ensure compliance with your institution's academic integrity policies and zyBooks terms of service.
|
||||
7
compose.yaml
Normal file
7
compose.yaml
Normal file
@@ -0,0 +1,7 @@
|
||||
services:
|
||||
zybooksbot:
|
||||
build: .
|
||||
ports:
|
||||
- "3000:3000"
|
||||
restart: unless-stopped
|
||||
|
||||
1350
package-lock.json
generated
Normal file
1350
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
28
package.json
Normal file
28
package.json
Normal file
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"name": "zyBooksBot",
|
||||
"version": "1.0.0",
|
||||
"main": "server.js",
|
||||
"scripts": {
|
||||
"start": "node server.js",
|
||||
"dev": "nodemon server.js"
|
||||
},
|
||||
"keywords": [
|
||||
"zybooks",
|
||||
"automation",
|
||||
"education",
|
||||
"challenge-activities",
|
||||
"participation-activities",
|
||||
"bot",
|
||||
"batch-processing",
|
||||
"student-tools"
|
||||
],
|
||||
"dependencies": {
|
||||
"express": "^4.18.2",
|
||||
"axios": "^1.6.0",
|
||||
"cors": "^2.8.5",
|
||||
"crypto": "^1.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"nodemon": "^3.0.1"
|
||||
}
|
||||
}
|
||||
86
public/index.html
Normal file
86
public/index.html
Normal file
@@ -0,0 +1,86 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>zyBooksBot</title>
|
||||
<link rel="stylesheet" href="style.css">
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<header>
|
||||
<h1>🚀 zyBooksBot</h1>
|
||||
<p>Automated bot for the zyBooks learning platform</p>
|
||||
</header>
|
||||
|
||||
<!-- Login Section -->
|
||||
<div id="login-section" class="section">
|
||||
<h2>Login to ZyBooks</h2>
|
||||
<form id="login-form">
|
||||
<div class="form-group">
|
||||
<label for="email">Email:</label>
|
||||
<input type="email" id="email" required>
|
||||
</div>
|
||||
<div class="form-group">
|
||||
<label for="password">Password:</label>
|
||||
<input type="password" id="password" required>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary">Login</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<!-- Books Section -->
|
||||
<div id="books-section" class="section hidden">
|
||||
<h2>Select Book</h2>
|
||||
<div id="books-list" class="list-container"></div>
|
||||
</div>
|
||||
|
||||
<!-- Chapters Section -->
|
||||
<div id="chapters-section" class="section hidden">
|
||||
<h2>Select Chapters</h2>
|
||||
<div class="back-btn" onclick="showSection('books-section')">← Back to Books</div>
|
||||
|
||||
<div class="batch-controls">
|
||||
<button class="btn btn-secondary" onclick="selectAllChapters(true)">Select All</button>
|
||||
<button class="btn btn-secondary" onclick="selectAllChapters(false)">Deselect All</button>
|
||||
<button class="btn btn-primary" onclick="executeSelectedChapters()">Execute Selected Chapters</button>
|
||||
</div>
|
||||
|
||||
<div id="chapters-list" class="list-container"></div>
|
||||
</div>
|
||||
|
||||
<!-- Sections Section -->
|
||||
<div id="sections-section" class="section hidden">
|
||||
<h2>Select Sections</h2>
|
||||
<div class="back-btn" onclick="showSection('chapters-section')">← Back to Chapters</div>
|
||||
|
||||
<div class="batch-controls">
|
||||
<button class="btn btn-secondary" onclick="selectAllSections(true)">Select All</button>
|
||||
<button class="btn btn-secondary" onclick="selectAllSections(false)">Deselect All</button>
|
||||
<button class="btn btn-primary" onclick="executeSelectedSections()">Execute Selected Sections</button>
|
||||
</div>
|
||||
|
||||
<div id="sections-list" class="list-container"></div>
|
||||
</div>
|
||||
|
||||
<!-- Progress Section -->
|
||||
<div id="progress-section" class="section hidden">
|
||||
<h2>Progress</h2>
|
||||
<div class="progress-bar">
|
||||
<div id="progress-fill" class="progress-fill"></div>
|
||||
</div>
|
||||
<div id="progress-text">Ready to start...</div>
|
||||
<div id="results-log" class="results-log"></div>
|
||||
<button class="btn btn-secondary" onclick="goHome()" style="margin-top: 20px;">Back to Home</button>
|
||||
</div>
|
||||
|
||||
<!-- Loading Animation -->
|
||||
<div id="loading" class="loading hidden">
|
||||
<div class="spinner"></div>
|
||||
<p>Processing...</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="script.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
610
public/script.js
Normal file
610
public/script.js
Normal file
@@ -0,0 +1,610 @@
|
||||
// Global variables
|
||||
let authToken = '';
|
||||
let userId = '';
|
||||
let currentBook = null;
|
||||
let currentChapter = null;
|
||||
let userTimeSpent = 0; // Track user's cumulative time spent
|
||||
|
||||
// ==================== UTILITY FUNCTIONS ====================
|
||||
|
||||
function showSection(sectionId) {
|
||||
document.querySelectorAll('.section').forEach(section => {
|
||||
section.classList.add('hidden');
|
||||
});
|
||||
document.getElementById(sectionId).classList.remove('hidden');
|
||||
}
|
||||
|
||||
function showLoading(show = true) {
|
||||
const loading = document.getElementById('loading');
|
||||
if (show) {
|
||||
loading.classList.remove('hidden');
|
||||
} else {
|
||||
loading.classList.add('hidden');
|
||||
}
|
||||
}
|
||||
|
||||
function addLogEntry(message, type = 'info') {
|
||||
const log = document.getElementById('results-log');
|
||||
const entry = document.createElement('div');
|
||||
entry.className = `log-entry log-${type}`;
|
||||
entry.textContent = `${new Date().toLocaleTimeString()} - ${message}`;
|
||||
log.appendChild(entry);
|
||||
log.scrollTop = log.scrollHeight;
|
||||
}
|
||||
|
||||
function updateProgress(current, total) {
|
||||
const progressFill = document.getElementById('progress-fill');
|
||||
const progressText = document.getElementById('progress-text');
|
||||
const percentage = Math.round((current / total) * 100);
|
||||
|
||||
progressFill.style.width = `${percentage}%`;
|
||||
progressText.textContent = `Progress: ${current}/${total} (${percentage}%)`;
|
||||
}
|
||||
|
||||
// ==================== API FUNCTIONS ====================
|
||||
|
||||
// Get section parts count
|
||||
async function getSectionPartsCount(section, chapter = currentChapter) {
|
||||
try {
|
||||
if (!section || !section.number) {
|
||||
return 99;
|
||||
}
|
||||
if (!chapter || !chapter.number) {
|
||||
return 99;
|
||||
}
|
||||
|
||||
const response = await fetch(`/api/section-parts/${currentBook.zybook_code}/${chapter.number}/${section.number}?auth_token=${authToken}`);
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
if (data.success) {
|
||||
return data.totalParts;
|
||||
}
|
||||
}
|
||||
return 99;
|
||||
} catch (error) {
|
||||
console.error('Error getting section parts count:', error);
|
||||
return 99;
|
||||
}
|
||||
}
|
||||
|
||||
// Solve single section for batch processing
|
||||
async function solveSectionForBatch(section, currentSection, totalSections, sectionIndex, globalPartTracker) {
|
||||
try {
|
||||
if (!currentBook || !currentBook.zybook_code) {
|
||||
throw new Error('Current book not set');
|
||||
}
|
||||
if (!currentChapter) {
|
||||
throw new Error('Current chapter not set');
|
||||
}
|
||||
if (!authToken) {
|
||||
throw new Error('Auth token not set');
|
||||
}
|
||||
if (!section) {
|
||||
throw new Error('Section data missing');
|
||||
}
|
||||
|
||||
const response = await fetch('/api/solve/section', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Accept': 'text/event-stream'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
bookCode: currentBook.zybook_code,
|
||||
chapter: currentChapter,
|
||||
section: section,
|
||||
auth: authToken,
|
||||
timeSpent: userTimeSpent
|
||||
})
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = '';
|
||||
let sectionResults = [];
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
|
||||
buffer += decoder.decode(value, { stream: true });
|
||||
const lines = buffer.split('\n');
|
||||
buffer = lines.pop() || '';
|
||||
|
||||
for (const line of lines) {
|
||||
if (line.startsWith('data: ')) {
|
||||
try {
|
||||
const data = JSON.parse(line.slice(6));
|
||||
|
||||
switch (data.type) {
|
||||
case 'total':
|
||||
addLogEntry(` 📊 [${sectionIndex}/${totalSections}] Section has ${data.total} parts`, 'info');
|
||||
break;
|
||||
case 'progress':
|
||||
addLogEntry(` ⚡ [${sectionIndex}/${totalSections}] Processing ${data.current}/${data.total}...`, 'info');
|
||||
break;
|
||||
case 'result':
|
||||
sectionResults.push(data);
|
||||
globalPartTracker.completedParts++;
|
||||
updateProgress(globalPartTracker.completedParts, globalPartTracker.totalParts);
|
||||
const status = data.success ? '✅' : '❌';
|
||||
addLogEntry(` ${status} [${sectionIndex}/${totalSections}] Part ${data.part || sectionResults.length}: ${data.success ? 'Success' : 'Failed'} (Global: ${globalPartTracker.completedParts}/${globalPartTracker.totalParts})`, data.success ? 'success' : 'error');
|
||||
break;
|
||||
case 'complete':
|
||||
const successCount = sectionResults.filter(r => r.success).length;
|
||||
addLogEntry(` 🎯 [${sectionIndex}/${totalSections}] Section completed! Success: ${successCount}/${sectionResults.length}`, 'success');
|
||||
break;
|
||||
case 'error':
|
||||
addLogEntry(` ❌ [${sectionIndex}/${totalSections}] Section failed: ${data.message}`, 'error');
|
||||
throw new Error(data.message);
|
||||
}
|
||||
} catch (e) {
|
||||
if (e.message && e.message !== 'Unexpected end of JSON input') {
|
||||
console.error('Error parsing SSE data:', e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Solve single section
|
||||
async function solveSection(section) {
|
||||
showSection('progress-section');
|
||||
|
||||
updateProgress(0, 1);
|
||||
document.getElementById('results-log').innerHTML = '';
|
||||
addLogEntry(`Starting section: ${currentChapter.number}.${section.number} - ${section.title}`);
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/solve/section', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Accept': 'text/event-stream'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
bookCode: currentBook.zybook_code,
|
||||
chapter: currentChapter,
|
||||
section: section,
|
||||
auth: authToken,
|
||||
timeSpent: userTimeSpent
|
||||
})
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = '';
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
|
||||
buffer += decoder.decode(value, { stream: true });
|
||||
const lines = buffer.split('\n');
|
||||
buffer = lines.pop() || '';
|
||||
|
||||
for (const line of lines) {
|
||||
if (line.startsWith('data: ')) {
|
||||
try {
|
||||
const data = JSON.parse(line.slice(6));
|
||||
handleSSEMessage(data);
|
||||
} catch (e) {
|
||||
console.error('Error parsing SSE data:', e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Section solving error:', error);
|
||||
addLogEntry('Error solving section: ' + error.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
// Handle SSE messages
|
||||
function handleSSEMessage(data) {
|
||||
switch (data.type) {
|
||||
case 'start':
|
||||
addLogEntry(data.message, 'info');
|
||||
break;
|
||||
case 'total':
|
||||
updateProgress(0, data.total);
|
||||
break;
|
||||
case 'progress':
|
||||
updateProgress(data.current, data.total);
|
||||
addLogEntry(data.message, 'info');
|
||||
break;
|
||||
case 'result':
|
||||
updateProgress(data.current, data.total);
|
||||
const resultType = data.success ? 'success' : 'error';
|
||||
addLogEntry(data.message, resultType);
|
||||
// Update user time spent if provided
|
||||
if (data.timeSpent !== undefined) {
|
||||
userTimeSpent = data.timeSpent;
|
||||
}
|
||||
break;
|
||||
case 'complete':
|
||||
addLogEntry(data.message, 'success');
|
||||
// Update final time spent if provided
|
||||
if (data.finalTimeSpent !== undefined) {
|
||||
userTimeSpent = data.finalTimeSpent;
|
||||
}
|
||||
break;
|
||||
case 'error':
|
||||
addLogEntry(data.message, 'error');
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
function goHome() {
|
||||
// Reset user time spent
|
||||
userTimeSpent = 0;
|
||||
|
||||
document.getElementById('results-log').innerHTML = '';
|
||||
document.getElementById('progress-fill').style.width = '0%';
|
||||
document.getElementById('progress-text').textContent = 'Ready to start...';
|
||||
|
||||
showSection('books-section');
|
||||
}
|
||||
|
||||
// ==================== LOGIN & DATA LOADING ====================
|
||||
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
const loading = document.getElementById('loading');
|
||||
if (loading) {
|
||||
loading.classList.add('hidden');
|
||||
}
|
||||
|
||||
const loginSection = document.getElementById('login-section');
|
||||
if (loginSection) {
|
||||
loginSection.classList.remove('hidden');
|
||||
}
|
||||
});
|
||||
|
||||
document.getElementById('login-form').addEventListener('submit', async (e) => {
|
||||
e.preventDefault();
|
||||
|
||||
const email = document.getElementById('email').value;
|
||||
const password = document.getElementById('password').value;
|
||||
|
||||
showLoading(true);
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/auth/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email, password })
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
authToken = data.auth_token;
|
||||
userId = data.user_id;
|
||||
loadBooks();
|
||||
} else {
|
||||
alert('Login failed: ' + data.message);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Login error:', error);
|
||||
alert('Login error: ' + error.message);
|
||||
} finally {
|
||||
showLoading(false);
|
||||
}
|
||||
});
|
||||
|
||||
async function loadBooks() {
|
||||
showLoading(true);
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/books/${userId}?auth_token=${authToken}`);
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
const booksList = document.getElementById('books-list');
|
||||
booksList.innerHTML = data.books.map(book =>
|
||||
`<div class="list-item" onclick="loadChapters('${book.zybook_code}', '${book.title}')">
|
||||
<strong>${book.title}</strong>
|
||||
<small>${book.zybook_code}</small>
|
||||
</div>`
|
||||
).join('');
|
||||
|
||||
showSection('books-section');
|
||||
} else {
|
||||
alert('Failed to load books: ' + data.message);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error loading books:', error);
|
||||
alert('Error loading books: ' + error.message);
|
||||
} finally {
|
||||
showLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function loadChapters(bookCode, bookTitle) {
|
||||
showLoading(true);
|
||||
currentBook = { zybook_code: bookCode, title: bookTitle };
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/chapters/${bookCode}?auth_token=${authToken}`);
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
const chaptersList = document.getElementById('chapters-list');
|
||||
chaptersList.innerHTML = data.chapters.map((chapter, index) =>
|
||||
`<div class="list-item-checkbox" data-chapter-index="${index}">
|
||||
<input type="checkbox" id="chapter-${index}" onchange="updateChapterSelection()">
|
||||
<div class="item-content">
|
||||
<strong>Chapter ${chapter.number}: ${chapter.title}</strong>
|
||||
<small>${chapter.sections.length} sections</small>
|
||||
</div>
|
||||
<div class="item-actions">
|
||||
<button class="btn btn-small" onclick="selectSingleChapter(${index})">Enter</button>
|
||||
</div>
|
||||
</div>`
|
||||
).join('');
|
||||
|
||||
window.chaptersData = data.chapters;
|
||||
updateChapterSelectionCount();
|
||||
showSection('chapters-section');
|
||||
} else {
|
||||
alert('Failed to load chapters: ' + data.message);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error loading chapters:', error);
|
||||
alert('Error loading chapters: ' + error.message);
|
||||
} finally {
|
||||
showLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
function loadSections(chapter) {
|
||||
currentChapter = chapter;
|
||||
|
||||
const sectionsList = document.getElementById('sections-list');
|
||||
sectionsList.innerHTML = chapter.sections.map((section, index) =>
|
||||
`<div class="list-item-checkbox" data-section-index="${index}">
|
||||
<input type="checkbox" id="section-${index}" onchange="updateSectionSelection()">
|
||||
<div class="item-content">
|
||||
<strong>Section ${chapter.number}.${section.number}: ${section.title}</strong>
|
||||
</div>
|
||||
</div>`
|
||||
).join('');
|
||||
|
||||
window.sectionsData = chapter.sections;
|
||||
updateSectionSelectionCount();
|
||||
showSection('sections-section');
|
||||
}
|
||||
|
||||
// ==================== CHAPTER MULTI-SELECT ====================
|
||||
|
||||
function updateChapterSelection() {
|
||||
const checkboxes = document.querySelectorAll('#chapters-list input[type="checkbox"]');
|
||||
checkboxes.forEach((checkbox, index) => {
|
||||
const listItem = checkbox.closest('.list-item-checkbox');
|
||||
if (checkbox.checked) {
|
||||
listItem.classList.add('selected');
|
||||
} else {
|
||||
listItem.classList.remove('selected');
|
||||
}
|
||||
});
|
||||
updateChapterSelectionCount();
|
||||
}
|
||||
|
||||
function updateChapterSelectionCount() {
|
||||
const checkboxes = document.querySelectorAll('#chapters-list input[type="checkbox"]:checked');
|
||||
const count = checkboxes.length;
|
||||
|
||||
const batchControls = document.querySelector('#chapters-section .batch-controls');
|
||||
let countDisplay = batchControls.querySelector('.selected-count');
|
||||
if (!countDisplay) {
|
||||
countDisplay = document.createElement('div');
|
||||
countDisplay.className = 'selected-count';
|
||||
batchControls.appendChild(countDisplay);
|
||||
}
|
||||
countDisplay.textContent = `${count} chapters selected`;
|
||||
}
|
||||
|
||||
function selectAllChapters(selectAll) {
|
||||
const checkboxes = document.querySelectorAll('#chapters-list input[type="checkbox"]');
|
||||
checkboxes.forEach(checkbox => {
|
||||
checkbox.checked = selectAll;
|
||||
});
|
||||
updateChapterSelection();
|
||||
}
|
||||
|
||||
function selectSingleChapter(index) {
|
||||
const chapter = window.chaptersData[index];
|
||||
currentChapter = chapter;
|
||||
loadSections(chapter);
|
||||
}
|
||||
|
||||
async function executeSelectedChapters() {
|
||||
const checkboxes = document.querySelectorAll('#chapters-list input[type="checkbox"]:checked');
|
||||
if (checkboxes.length === 0) {
|
||||
alert('Please select at least one chapter');
|
||||
return;
|
||||
}
|
||||
|
||||
const selectedChapters = Array.from(checkboxes).map(checkbox => {
|
||||
const parentDiv = checkbox.closest('.list-item-checkbox');
|
||||
const index = parseInt(parentDiv.dataset.chapterIndex);
|
||||
return {
|
||||
index: index,
|
||||
chapter: window.chaptersData[index]
|
||||
};
|
||||
});
|
||||
|
||||
const totalSections = selectedChapters.reduce((total, { chapter }) => total + chapter.sections.length, 0);
|
||||
|
||||
showSection('progress-section');
|
||||
|
||||
updateProgress(0, 1);
|
||||
document.getElementById('results-log').innerHTML = '';
|
||||
addLogEntry(`Starting batch processing of ${selectedChapters.length} chapters (${totalSections} sections total)`);
|
||||
addLogEntry(`📊 Calculating total parts for all sections...`, 'info');
|
||||
|
||||
// Pre-calculate total parts
|
||||
let totalParts = 0;
|
||||
let sectionIndex = 0;
|
||||
for (let i = 0; i < selectedChapters.length; i++) {
|
||||
const { chapter } = selectedChapters[i];
|
||||
addLogEntry(`📚 Calculating chapter ${chapter.number}: ${chapter.title} (${chapter.sections.length} sections)`, 'info');
|
||||
|
||||
for (let j = 0; j < chapter.sections.length; j++) {
|
||||
sectionIndex++;
|
||||
const section = chapter.sections[j];
|
||||
addLogEntry(` 🔍 Getting parts count for section ${chapter.number}.${section.number}...`, 'info');
|
||||
const sectionParts = await getSectionPartsCount(section, chapter);
|
||||
totalParts += sectionParts;
|
||||
addLogEntry(` 📊 Section ${chapter.number}.${section.number} has ${sectionParts} parts`, 'info');
|
||||
}
|
||||
}
|
||||
|
||||
const globalPartTracker = {
|
||||
totalParts: totalParts,
|
||||
completedParts: 0
|
||||
};
|
||||
|
||||
updateProgress(0, totalParts);
|
||||
addLogEntry(`🎯 Total parts to process: ${totalParts}`, 'success');
|
||||
|
||||
sectionIndex = 0;
|
||||
|
||||
for (let i = 0; i < selectedChapters.length; i++) {
|
||||
const { chapter } = selectedChapters[i];
|
||||
currentChapter = chapter;
|
||||
addLogEntry(`📚 Starting chapter ${chapter.number}: ${chapter.title} (${chapter.sections.length} sections)`, 'info');
|
||||
|
||||
for (let j = 0; j < chapter.sections.length; j++) {
|
||||
sectionIndex++;
|
||||
const section = chapter.sections[j];
|
||||
addLogEntry(`📄 Starting section ${chapter.number}.${section.number}: ${section.title}`, 'info');
|
||||
|
||||
try {
|
||||
await solveSectionForBatch(section, `${chapter.number}.${section.number}`, totalSections, sectionIndex, globalPartTracker);
|
||||
addLogEntry(`✅ Section ${chapter.number}.${section.number} completed`, 'success');
|
||||
} catch (error) {
|
||||
addLogEntry(`❌ Section ${chapter.number}.${section.number} failed: ${error.message}`, 'error');
|
||||
}
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||
}
|
||||
|
||||
addLogEntry(`✅ Chapter ${chapter.number} completed (${chapter.sections.length} sections)`, 'success');
|
||||
|
||||
if (i < selectedChapters.length - 1) {
|
||||
await new Promise(resolve => setTimeout(resolve, 2000));
|
||||
}
|
||||
}
|
||||
|
||||
addLogEntry(`🎉 Batch chapter processing completed! Processed ${totalParts} parts total`, 'success');
|
||||
}
|
||||
|
||||
// ==================== SECTION MULTI-SELECT ====================
|
||||
|
||||
function updateSectionSelection() {
|
||||
const checkboxes = document.querySelectorAll('#sections-list input[type="checkbox"]');
|
||||
checkboxes.forEach((checkbox, index) => {
|
||||
const listItem = checkbox.closest('.list-item-checkbox');
|
||||
if (checkbox.checked) {
|
||||
listItem.classList.add('selected');
|
||||
} else {
|
||||
listItem.classList.remove('selected');
|
||||
}
|
||||
});
|
||||
updateSectionSelectionCount();
|
||||
}
|
||||
|
||||
function updateSectionSelectionCount() {
|
||||
const checkboxes = document.querySelectorAll('#sections-list input[type="checkbox"]:checked');
|
||||
const count = checkboxes.length;
|
||||
|
||||
const batchControls = document.querySelector('#sections-section .batch-controls');
|
||||
let countDisplay = batchControls.querySelector('.selected-count');
|
||||
if (!countDisplay) {
|
||||
countDisplay = document.createElement('div');
|
||||
countDisplay.className = 'selected-count';
|
||||
batchControls.appendChild(countDisplay);
|
||||
}
|
||||
countDisplay.textContent = `${count} sections selected`;
|
||||
}
|
||||
|
||||
function selectAllSections(selectAll) {
|
||||
const checkboxes = document.querySelectorAll('#sections-list input[type="checkbox"]');
|
||||
checkboxes.forEach(checkbox => {
|
||||
checkbox.checked = selectAll;
|
||||
});
|
||||
updateSectionSelection();
|
||||
}
|
||||
|
||||
async function executeSelectedSections() {
|
||||
const checkboxes = document.querySelectorAll('#sections-list input[type="checkbox"]:checked');
|
||||
if (checkboxes.length === 0) {
|
||||
alert('Please select at least one section');
|
||||
return;
|
||||
}
|
||||
|
||||
const selectedSections = Array.from(checkboxes).map(checkbox => {
|
||||
const parentDiv = checkbox.closest('.list-item-checkbox');
|
||||
const index = parseInt(parentDiv.dataset.sectionIndex);
|
||||
return {
|
||||
index: index,
|
||||
section: window.sectionsData[index]
|
||||
};
|
||||
});
|
||||
|
||||
showSection('progress-section');
|
||||
|
||||
updateProgress(0, 1);
|
||||
document.getElementById('results-log').innerHTML = '';
|
||||
addLogEntry(`Starting batch processing of ${selectedSections.length} sections`);
|
||||
addLogEntry(`📊 Calculating total parts for all sections...`, 'info');
|
||||
|
||||
// Pre-calculate total parts
|
||||
let totalParts = 0;
|
||||
for (let i = 0; i < selectedSections.length; i++) {
|
||||
const { section } = selectedSections[i];
|
||||
addLogEntry(` 🔍 Getting parts count for section ${currentChapter.number}.${section.number}...`, 'info');
|
||||
const sectionParts = await getSectionPartsCount(section, currentChapter);
|
||||
totalParts += sectionParts;
|
||||
addLogEntry(` 📊 Section ${currentChapter.number}.${section.number} has ${sectionParts} parts`, 'info');
|
||||
}
|
||||
|
||||
const globalPartTracker = {
|
||||
totalParts: totalParts,
|
||||
completedParts: 0
|
||||
};
|
||||
|
||||
updateProgress(0, totalParts);
|
||||
addLogEntry(`🎯 Total parts to process: ${totalParts}`, 'success');
|
||||
|
||||
for (let i = 0; i < selectedSections.length; i++) {
|
||||
const { section } = selectedSections[i];
|
||||
addLogEntry(`📄 Starting section ${currentChapter.number}.${section.number}: ${section.title}`, 'info');
|
||||
|
||||
try {
|
||||
await solveSectionForBatch(section, i + 1, selectedSections.length, i + 1, globalPartTracker);
|
||||
addLogEntry(`✅ Section ${currentChapter.number}.${section.number} completed`, 'success');
|
||||
} catch (error) {
|
||||
addLogEntry(`❌ Section ${currentChapter.number}.${section.number} failed: ${error.message}`, 'error');
|
||||
}
|
||||
|
||||
if (i < selectedSections.length - 1) {
|
||||
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||
}
|
||||
}
|
||||
|
||||
addLogEntry(`🎉 Batch section processing completed! Processed ${totalParts} parts total`, 'success');
|
||||
}
|
||||
399
public/style.css
Normal file
399
public/style.css
Normal file
@@ -0,0 +1,399 @@
|
||||
/* Global Styles */
|
||||
* {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', sans-serif;
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
min-height: 100vh;
|
||||
color: #333;
|
||||
overflow-x: hidden;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.container {
|
||||
max-width: 900px;
|
||||
margin: 0 auto;
|
||||
padding: 20px;
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
/* Header */
|
||||
header {
|
||||
text-align: center;
|
||||
margin-bottom: 30px;
|
||||
color: white;
|
||||
}
|
||||
|
||||
header h1 {
|
||||
font-size: 2.5rem;
|
||||
margin-bottom: 10px;
|
||||
text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
|
||||
}
|
||||
|
||||
header p {
|
||||
font-size: 1.1rem;
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
/* Sections */
|
||||
.section {
|
||||
background: rgba(255, 255, 255, 0.95);
|
||||
backdrop-filter: blur(10px);
|
||||
border-radius: 20px;
|
||||
padding: 30px;
|
||||
margin-bottom: 20px;
|
||||
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
|
||||
border: 1px solid rgba(255, 255, 255, 0.2);
|
||||
}
|
||||
|
||||
.section.hidden {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.section h2 {
|
||||
margin-bottom: 20px;
|
||||
color: #4a5568;
|
||||
font-size: 1.8rem;
|
||||
}
|
||||
|
||||
/* Forms */
|
||||
.form-group {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.form-group label {
|
||||
display: block;
|
||||
margin-bottom: 8px;
|
||||
font-weight: 600;
|
||||
color: #4a5568;
|
||||
}
|
||||
|
||||
.form-group input {
|
||||
width: 100%;
|
||||
padding: 12px 16px;
|
||||
border: 2px solid #e2e8f0;
|
||||
border-radius: 10px;
|
||||
font-size: 16px;
|
||||
transition: border-color 0.3s ease;
|
||||
}
|
||||
|
||||
.form-group input:focus {
|
||||
outline: none;
|
||||
border-color: #667eea;
|
||||
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
|
||||
}
|
||||
|
||||
/* Buttons */
|
||||
.btn {
|
||||
padding: 12px 24px;
|
||||
border: none;
|
||||
border-radius: 10px;
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
text-decoration: none;
|
||||
display: inline-block;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-primary:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
|
||||
}
|
||||
|
||||
.btn-secondary {
|
||||
background: #f7fafc;
|
||||
color: #4a5568;
|
||||
border: 2px solid #e2e8f0;
|
||||
}
|
||||
|
||||
.btn-secondary:hover {
|
||||
background: #edf2f7;
|
||||
border-color: #cbd5e0;
|
||||
}
|
||||
|
||||
.btn-small {
|
||||
padding: 8px 16px;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
/* Back Button */
|
||||
.back-btn {
|
||||
display: inline-block;
|
||||
margin-bottom: 20px;
|
||||
color: #667eea;
|
||||
cursor: pointer;
|
||||
font-weight: 600;
|
||||
transition: color 0.3s ease;
|
||||
}
|
||||
|
||||
.back-btn:hover {
|
||||
color: #5a67d8;
|
||||
}
|
||||
|
||||
/* List Containers */
|
||||
.list-container {
|
||||
max-height: 400px;
|
||||
overflow-y: auto;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 10px;
|
||||
padding: 10px;
|
||||
overflow-x: hidden;
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.list-item {
|
||||
padding: 15px;
|
||||
border-bottom: 1px solid #f1f5f9;
|
||||
cursor: pointer;
|
||||
transition: background-color 0.2s ease;
|
||||
word-wrap: break-word;
|
||||
overflow-wrap: break-word;
|
||||
}
|
||||
|
||||
.list-item:hover {
|
||||
background-color: #f8fafc;
|
||||
}
|
||||
|
||||
.list-item:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.list-item strong {
|
||||
display: block;
|
||||
color: #2d3748;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.list-item small {
|
||||
color: #718096;
|
||||
}
|
||||
|
||||
/* Checkbox List Items */
|
||||
.list-item-checkbox {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 15px;
|
||||
border-bottom: 1px solid #f1f5f9;
|
||||
transition: background-color 0.2s ease;
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
word-wrap: break-word;
|
||||
overflow-wrap: break-word;
|
||||
}
|
||||
|
||||
.list-item-checkbox:hover {
|
||||
background-color: #f8fafc;
|
||||
}
|
||||
|
||||
.list-item-checkbox.selected {
|
||||
background-color: #ebf8ff;
|
||||
border-color: #bee3f8;
|
||||
}
|
||||
|
||||
.list-item-checkbox:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.list-item-checkbox input[type="checkbox"] {
|
||||
margin-right: 15px;
|
||||
transform: scale(1.2);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.item-content {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.item-content strong {
|
||||
display: block;
|
||||
color: #2d3748;
|
||||
margin-bottom: 4px;
|
||||
word-wrap: break-word;
|
||||
overflow-wrap: break-word;
|
||||
}
|
||||
|
||||
.item-content small {
|
||||
color: #718096;
|
||||
}
|
||||
|
||||
.item-actions {
|
||||
margin-left: 15px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
/* Batch Controls */
|
||||
.batch-controls {
|
||||
margin-bottom: 20px;
|
||||
padding: 15px;
|
||||
background-color: #f7fafc;
|
||||
border-radius: 10px;
|
||||
border: 1px solid #e2e8f0;
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.selected-count {
|
||||
margin-left: auto;
|
||||
font-weight: 600;
|
||||
color: #4a5568;
|
||||
}
|
||||
|
||||
/* Progress Bar */
|
||||
.progress-bar {
|
||||
width: 100%;
|
||||
height: 20px;
|
||||
background: #e2e8f0;
|
||||
border-radius: 10px;
|
||||
overflow: hidden;
|
||||
margin-bottom: 15px;
|
||||
}
|
||||
|
||||
.progress-fill {
|
||||
height: 100%;
|
||||
background: linear-gradient(90deg, #48bb78, #38a169);
|
||||
width: 0%;
|
||||
transition: width 0.5s ease;
|
||||
}
|
||||
|
||||
#progress-text {
|
||||
text-align: center;
|
||||
font-weight: 600;
|
||||
color: #4a5568;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
/* Results Log */
|
||||
.results-log {
|
||||
max-height: 300px;
|
||||
overflow-y: auto;
|
||||
background: #f7fafc;
|
||||
border: 1px solid #e2e8f0;
|
||||
border-radius: 10px;
|
||||
padding: 15px;
|
||||
font-family: 'Monaco', 'Menlo', monospace;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.log-entry {
|
||||
margin-bottom: 8px;
|
||||
padding: 4px 0;
|
||||
}
|
||||
|
||||
.log-info {
|
||||
color: #4a5568;
|
||||
}
|
||||
|
||||
.log-success {
|
||||
color: #38a169;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.log-error {
|
||||
color: #e53e3e;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* Loading Animation */
|
||||
.loading {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: rgba(0, 0, 0, 0.8);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
z-index: 1000;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.loading.hidden {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.spinner {
|
||||
width: 50px;
|
||||
height: 50px;
|
||||
border: 4px solid rgba(255, 255, 255, 0.3);
|
||||
border-top: 4px solid #fff;
|
||||
border-radius: 50%;
|
||||
animation: spin 1s linear infinite;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
0% { transform: rotate(0deg); }
|
||||
100% { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
.loading p {
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* Responsive Design */
|
||||
@media (max-width: 600px) {
|
||||
.container {
|
||||
padding: 15px;
|
||||
}
|
||||
|
||||
header h1 {
|
||||
font-size: 2rem;
|
||||
}
|
||||
|
||||
.section {
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.list-item-checkbox {
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.item-actions {
|
||||
margin-left: 0;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.item-actions .btn {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.batch-controls {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.batch-controls .btn {
|
||||
width: 100%;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.batch-controls .btn:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.selected-count {
|
||||
margin-left: 0;
|
||||
text-align: center;
|
||||
}
|
||||
}
|
||||
326
server.js
Normal file
326
server.js
Normal file
@@ -0,0 +1,326 @@
|
||||
const express = require('express');
|
||||
const axios = require('axios');
|
||||
const cors = require('cors');
|
||||
const crypto = require('crypto');
|
||||
|
||||
const app = express();
|
||||
const PORT = 3000;
|
||||
|
||||
// Configuration
|
||||
const ZYBOOKS_CONFIG = {
|
||||
BASE_URL: 'https://zyserver.zybooks.com/v1',
|
||||
TIME_URL: 'https://zyserver2.zybooks.com/v1',
|
||||
LEARN_URL: 'https://learn.zybooks.com',
|
||||
HEADERS: {
|
||||
'Host': 'zyserver.zybooks.com',
|
||||
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:120.0) Gecko/20100101 Firefox/120.0',
|
||||
'Accept': 'application/json, text/javascript, */*; q=0.01',
|
||||
'Accept-Language': 'en-US,en;q=0.5',
|
||||
'Content-Type': 'application/json',
|
||||
'Origin': 'https://learn.zybooks.com',
|
||||
'Referer': 'https://learn.zybooks.com/'
|
||||
}
|
||||
};
|
||||
|
||||
// Middleware
|
||||
app.use(cors());
|
||||
app.use(express.json());
|
||||
app.use(express.static('public'));
|
||||
|
||||
// Global error handlers
|
||||
process.on('uncaughtException', (error) => {
|
||||
console.error('Uncaught Exception:', error);
|
||||
});
|
||||
|
||||
process.on('unhandledRejection', (reason, promise) => {
|
||||
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
|
||||
});
|
||||
|
||||
// ==================== UTILITY FUNCTIONS ====================
|
||||
|
||||
function generateTimestamp(timeSpent = 0) {
|
||||
const now = new Date();
|
||||
const future = new Date(now.getTime() + timeSpent * 1000);
|
||||
const ms = String(Math.floor(Math.random() * 1000)).padStart(3, '0');
|
||||
return future.toISOString().replace(/\.\d{3}Z$/, `${ms}Z`);
|
||||
}
|
||||
|
||||
function generateChecksum(actId, timestamp, auth, part, buildkey) {
|
||||
const data = `content_resource/${actId}/activity${timestamp}${auth}${actId}${part}true${buildkey}`;
|
||||
return crypto.createHash('md5').update(data).digest('hex');
|
||||
}
|
||||
|
||||
async function getBuildkey(axiosInstance) {
|
||||
const response = await axiosInstance.get(ZYBOOKS_CONFIG.LEARN_URL);
|
||||
const match = response.data.match(/zybooks-web\/config\/environment[^>]*content="([^"]*)/);
|
||||
const decoded = decodeURIComponent(match[1]);
|
||||
const config = JSON.parse(decoded);
|
||||
return config.APP.BUILDKEY;
|
||||
}
|
||||
|
||||
async function calculateSectionParts(bookCode, chapterNumber, sectionNumber, authToken, axiosInstance) {
|
||||
try {
|
||||
const problemsResponse = await axiosInstance.get(
|
||||
`${ZYBOOKS_CONFIG.BASE_URL}/zybook/${bookCode}/chapter/${chapterNumber}/section/${sectionNumber}?auth_token=${authToken}`
|
||||
);
|
||||
|
||||
if (!problemsResponse.data || !problemsResponse.data.section) {
|
||||
throw new Error('Invalid response: missing section data');
|
||||
}
|
||||
|
||||
const problems = problemsResponse.data.section.content_resources;
|
||||
if (!problems || !Array.isArray(problems)) {
|
||||
throw new Error('Invalid response: missing or invalid content_resources');
|
||||
}
|
||||
|
||||
const totalParts = problems.reduce((total, problem) => total + Math.max(problem.parts, 1), 0);
|
||||
return { problems, totalParts };
|
||||
} catch (error) {
|
||||
console.error('Error in calculateSectionParts:', error.message);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Error response helper
|
||||
function sendError(res, statusCode, message) {
|
||||
console.error(`Error [${statusCode}]:`, message);
|
||||
res.status(statusCode).json({ success: false, message });
|
||||
}
|
||||
|
||||
// SSE message helpers
|
||||
function sendSSEMessage(res, type, data) {
|
||||
res.write(`data: ${JSON.stringify({ type, ...data })}\n\n`);
|
||||
}
|
||||
|
||||
// Core function to solve a single part
|
||||
async function solvePart(actId, secId, auth, part, code, axiosInstance, timeSpent = 0) {
|
||||
// Simulate time spent
|
||||
const spentTime = Math.floor(Math.random() * 60) + 1;
|
||||
const newTimeSpent = timeSpent + spentTime;
|
||||
|
||||
// Send time record
|
||||
await axiosInstance.post(`${ZYBOOKS_CONFIG.TIME_URL}/zybook/${code}/time_spent`, {
|
||||
time_spent_records: [{
|
||||
canonical_section_id: secId,
|
||||
content_resource_id: actId,
|
||||
part: part,
|
||||
time_spent: spentTime,
|
||||
timestamp: generateTimestamp(newTimeSpent)
|
||||
}],
|
||||
auth_token: auth
|
||||
});
|
||||
|
||||
// Get buildkey and generate checksum
|
||||
const buildkey = await getBuildkey(axiosInstance);
|
||||
const timestamp = generateTimestamp(newTimeSpent);
|
||||
const checksum = generateChecksum(actId, timestamp, auth, part, buildkey);
|
||||
|
||||
// Solve the problem
|
||||
const response = await axiosInstance.post(
|
||||
`${ZYBOOKS_CONFIG.BASE_URL}/content_resource/${actId}/activity`,
|
||||
{
|
||||
part: part,
|
||||
complete: true,
|
||||
metadata: "{}",
|
||||
zybook_code: code,
|
||||
auth_token: auth,
|
||||
timestamp: timestamp,
|
||||
__cs__: checksum
|
||||
},
|
||||
{ headers: ZYBOOKS_CONFIG.HEADERS }
|
||||
);
|
||||
|
||||
return { success: response.data.success || false, timeSpent: newTimeSpent };
|
||||
}
|
||||
|
||||
// ==================== API ROUTES ====================
|
||||
|
||||
// Login
|
||||
app.post('/api/auth/login', async (req, res) => {
|
||||
try {
|
||||
const { email, password } = req.body;
|
||||
if (!email || !password) {
|
||||
return sendError(res, 400, 'Email and password are required');
|
||||
}
|
||||
|
||||
const tempSession = axios.create();
|
||||
const response = await tempSession.post(`${ZYBOOKS_CONFIG.BASE_URL}/signin`, { email, password });
|
||||
|
||||
if (!response.data.success || !response.data.session) {
|
||||
return sendError(res, 401, 'Invalid credentials');
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
auth_token: response.data.session.auth_token,
|
||||
user_id: response.data.session.user_id
|
||||
});
|
||||
} catch (error) {
|
||||
sendError(res, 500, 'Login failed - Server error');
|
||||
}
|
||||
});
|
||||
|
||||
// Get books
|
||||
app.get('/api/books/:userId', async (req, res) => {
|
||||
try {
|
||||
const { userId } = req.params;
|
||||
const { auth_token } = req.query;
|
||||
|
||||
if (!userId || !auth_token) {
|
||||
return sendError(res, 400, 'User ID and auth token are required');
|
||||
}
|
||||
|
||||
const axiosInstance = axios.create();
|
||||
const response = await axiosInstance.get(
|
||||
`${ZYBOOKS_CONFIG.BASE_URL}/user/${userId}/items?items=%5B%22zybooks%22%5D&auth_token=${auth_token}`
|
||||
);
|
||||
|
||||
const books = response.data.items.zybooks.filter(book => !book.autosubscribe);
|
||||
res.json({ success: true, books });
|
||||
} catch (error) {
|
||||
sendError(res, 500, 'Failed to get books');
|
||||
}
|
||||
});
|
||||
|
||||
// Get chapters
|
||||
app.get('/api/chapters/:bookCode', async (req, res) => {
|
||||
try {
|
||||
const { bookCode } = req.params;
|
||||
const { auth_token } = req.query;
|
||||
|
||||
if (!bookCode || !auth_token) {
|
||||
return sendError(res, 400, 'Book code and auth token are required');
|
||||
}
|
||||
|
||||
const axiosInstance = axios.create();
|
||||
const response = await axiosInstance.get(
|
||||
`${ZYBOOKS_CONFIG.BASE_URL}/zybooks?zybooks=%5B%22${bookCode}%22%5D&auth_token=${auth_token}`
|
||||
);
|
||||
|
||||
res.json({ success: true, chapters: response.data.zybooks[0].chapters });
|
||||
} catch (error) {
|
||||
sendError(res, 500, 'Failed to get chapters');
|
||||
}
|
||||
});
|
||||
|
||||
// Get section parts count
|
||||
app.get('/api/section-parts/:bookCode/:chapterNumber/:sectionNumber', async (req, res) => {
|
||||
try {
|
||||
const { bookCode, chapterNumber, sectionNumber } = req.params;
|
||||
const { auth_token } = req.query;
|
||||
|
||||
if (!bookCode || !chapterNumber || !sectionNumber || !auth_token) {
|
||||
return sendError(res, 400, 'Missing required parameters');
|
||||
}
|
||||
|
||||
const axiosInstance = axios.create();
|
||||
const { totalParts } = await calculateSectionParts(bookCode, chapterNumber, sectionNumber, auth_token, axiosInstance);
|
||||
|
||||
res.json({ success: true, totalParts });
|
||||
} catch (error) {
|
||||
sendError(res, 500, 'Failed to get section parts');
|
||||
}
|
||||
});
|
||||
|
||||
// Solve section with SSE
|
||||
app.post('/api/solve/section', async (req, res) => {
|
||||
// Set SSE headers
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'text/event-stream',
|
||||
'Cache-Control': 'no-cache',
|
||||
'Connection': 'keep-alive',
|
||||
'Access-Control-Allow-Origin': '*'
|
||||
});
|
||||
|
||||
try {
|
||||
const { bookCode, chapter, section, auth, timeSpent = 0 } = req.body;
|
||||
|
||||
if (!bookCode || !chapter || !section || !auth) {
|
||||
sendSSEMessage(res, 'error', { message: 'Missing required parameters' });
|
||||
return res.end();
|
||||
}
|
||||
|
||||
console.log(`Solving section: ${chapter.number}.${section.number}`);
|
||||
|
||||
const axiosInstance = axios.create();
|
||||
let currentTimeSpent = timeSpent;
|
||||
|
||||
// Send start message
|
||||
sendSSEMessage(res, 'start', {
|
||||
message: `Starting section: ${chapter.number}.${section.number} - ${section.title}`
|
||||
});
|
||||
|
||||
// Get problems and total parts
|
||||
const { problems, totalParts } = await calculateSectionParts(bookCode, chapter.number, section.number, auth, axiosInstance);
|
||||
sendSSEMessage(res, 'total', { total: totalParts });
|
||||
|
||||
let currentPart = 0;
|
||||
let results = [];
|
||||
|
||||
// Process each problem
|
||||
for (let i = 0; i < problems.length; i++) {
|
||||
const problem = problems[i];
|
||||
const parts = Math.max(problem.parts, 1);
|
||||
|
||||
// Process each part
|
||||
for (let partIndex = 0; partIndex < parts; partIndex++) {
|
||||
currentPart++;
|
||||
const partNum = partIndex + 1;
|
||||
const actualPartIndex = problem.parts > 0 ? partIndex : 0;
|
||||
|
||||
// Send progress
|
||||
const progressMessage = parts > 1
|
||||
? `Solving problem ${i + 1} part ${partNum}...`
|
||||
: `Solving problem ${i + 1}...`;
|
||||
sendSSEMessage(res, 'progress', {
|
||||
current: currentPart,
|
||||
total: totalParts,
|
||||
message: progressMessage
|
||||
});
|
||||
|
||||
// Solve the part
|
||||
const result = await solvePart(problem.id, section.canonical_section_id, auth, actualPartIndex, bookCode, axiosInstance, currentTimeSpent);
|
||||
currentTimeSpent = result.timeSpent; // Update time spent
|
||||
|
||||
results.push({ problem: i + 1, part: partNum, success: result.success });
|
||||
|
||||
// Send result
|
||||
sendSSEMessage(res, 'result', {
|
||||
current: currentPart,
|
||||
total: totalParts,
|
||||
problem: i + 1,
|
||||
part: partNum,
|
||||
success: result.success,
|
||||
timeSpent: currentTimeSpent,
|
||||
message: result.success
|
||||
? `✅ Problem ${i + 1} part ${partNum} solved successfully`
|
||||
: `❌ Problem ${i + 1} part ${partNum} failed`
|
||||
});
|
||||
|
||||
console.log(`Problem ${i + 1}, Part ${partNum}: ${result.success ? 'Success' : 'Failed'}`);
|
||||
await new Promise(resolve => setTimeout(resolve, 500));
|
||||
}
|
||||
}
|
||||
|
||||
// Send completion
|
||||
const successCount = results.filter(r => r.success).length;
|
||||
sendSSEMessage(res, 'complete', {
|
||||
results,
|
||||
successCount,
|
||||
totalCount: results.length,
|
||||
finalTimeSpent: currentTimeSpent,
|
||||
message: `Completed! ${successCount}/${results.length} problems solved successfully`
|
||||
});
|
||||
|
||||
res.end();
|
||||
} catch (error) {
|
||||
console.error('Section solving error:', error.message);
|
||||
sendSSEMessage(res, 'error', { message: `Error solving section: ${error.message}` });
|
||||
res.end();
|
||||
}
|
||||
});
|
||||
|
||||
// Start server
|
||||
app.listen(PORT, () => {
|
||||
console.log(`🚀 ZyBook Auto Server running on http://localhost:${PORT}`);
|
||||
});
|
||||
Reference in New Issue
Block a user