File size: 27,520 Bytes
1ff2605 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 | const express = require('express');
const puppeteer = require('puppeteer');
const cors = require('cors');
const app = express();
const port = 7860;
app.use(cors());
app.use(express.json());
/**
* Advanced cookie banner and content bypass for StuDocu
*/
const bypassCookiesAndRestrictions = async (page) => {
console.log("πͺ Starting comprehensive cookie and restriction bypass...");
// Step 1: Set cookies before page load
const preCookies = [
{ name: 'cookieConsent', value: 'accepted', domain: '.studocu.com' },
{ name: 'cookie_consent', value: 'true', domain: '.studocu.com' },
{ name: 'gdpr_consent', value: 'accepted', domain: '.studocu.com' },
{ name: 'privacy_policy_accepted', value: 'true', domain: '.studocu.com' },
{ name: 'user_consent', value: '1', domain: '.studocu.com' },
{ name: 'analytics_consent', value: 'false', domain: '.studocu.com' },
{ name: 'marketing_consent', value: 'false', domain: '.studocu.com' },
{ name: 'functional_consent', value: 'true', domain: '.studocu.com' },
];
for (const cookie of preCookies) {
try {
await page.setCookie(cookie);
} catch (e) {
console.log(`Failed to set cookie ${cookie.name}:`, e.message);
}
}
// Step 2: Inject CSS to hide cookie banners immediately
await page.addStyleTag({
content: `
/* Hide all possible cookie banners */
[id*="cookie" i]:not(img):not(input),
[class*="cookie" i]:not(img):not(input),
[data-testid*="cookie" i],
[aria-label*="cookie" i],
.gdpr-banner, .gdpr-popup, .gdpr-modal,
.consent-banner, .consent-popup, .consent-modal,
.privacy-banner, .privacy-popup, .privacy-modal,
.cookie-law, .cookie-policy, .cookie-compliance,
.onetrust-banner-sdk, #onetrust-consent-sdk,
.cmp-banner, .cmp-popup, .cmp-modal,
[class*="CookieBanner"], [class*="CookieNotice"],
[class*="ConsentBanner"], [class*="ConsentManager"],
.cc-banner, .cc-window, .cc-compliance,
div[style*="position: fixed"]:has-text("cookie"),
div[style*="position: fixed"]:has-text("consent"),
.fixed:has-text("cookie"), .fixed:has-text("consent") {
display: none !important;
visibility: hidden !important;
opacity: 0 !important;
z-index: -9999 !important;
pointer-events: none !important;
}
/* Remove blur and premium overlays */
[class*="blur" i], [class*="premium" i],
[class*="paywall" i], [class*="sample-preview-blur" i] {
filter: none !important;
backdrop-filter: none !important;
opacity: 1 !important;
visibility: visible !important;
}
/* Ensure document content is visible */
.document-content, .page-content, [data-page] {
filter: none !important;
opacity: 1 !important;
visibility: visible !important;
pointer-events: auto !important;
}
/* Remove fixed overlays */
.fixed-overlay, .sticky-overlay, .content-overlay {
display: none !important;
}
/* Restore scrolling */
html, body {
overflow: auto !important;
position: static !important;
}
`
});
// Step 3: Inject JavaScript to handle dynamic cookie banners
await page.evaluateOnNewDocument(() => {
// Override common cookie consent functions
window.cookieConsent = { accepted: true };
window.gtag = () => { };
window.ga = () => { };
window.dataLayer = [];
// Mutation observer to catch dynamically added cookie banners
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
mutation.addedNodes.forEach((node) => {
if (node.nodeType === 1) { // Element node
const element = node;
const text = element.textContent || '';
const className = element.className || '';
const id = element.id || '';
// Check if this looks like a cookie banner
if (
text.toLowerCase().includes('cookie') ||
text.toLowerCase().includes('consent') ||
text.toLowerCase().includes('privacy policy') ||
className.toLowerCase().includes('cookie') ||
className.toLowerCase().includes('consent') ||
className.toLowerCase().includes('gdpr') ||
id.toLowerCase().includes('cookie') ||
id.toLowerCase().includes('consent')
) {
console.log('Removing detected cookie banner:', element);
element.remove();
}
}
});
});
});
observer.observe(document.body, { childList: true, subtree: true });
// Set up periodic cleanup
setInterval(() => {
const cookieElements = document.querySelectorAll(`
[id*="cookie" i]:not(img):not(input),
[class*="cookie" i]:not(img):not(input),
[data-testid*="cookie" i],
.gdpr-banner, .consent-banner, .privacy-banner,
.onetrust-banner-sdk, #onetrust-consent-sdk,
.cmp-banner, .cc-banner
`);
cookieElements.forEach(el => el.remove());
// Restore body scroll
document.body.style.overflow = 'auto';
document.documentElement.style.overflow = 'auto';
}, 1000);
});
return true;
};
/**
* Enhanced content unblurring and premium bypass (integrated from extension script)
*/
const unblurContent = async (page) => {
console.log("π Unblurring content and bypassing premium restrictions...");
await page.evaluate(() => {
// Function to remove all visual restrictions
const removeRestrictions = () => {
const removeBySelector = (selector) => {
document.querySelectorAll(selector).forEach(el => el.remove());
};
// Remove ads by known class or ID
removeBySelector("#adbox");
removeBySelector(".adsbox");
removeBySelector(".ad-box");
removeBySelector(".banner-ads");
removeBySelector(".advert");
// Remove premium banner container
removeBySelector(".PremiumBannerBlobWrapper_overflow-wrapper__xsaS8");
// Enhanced blur removal
const removeBlur = (element = document) => {
element.querySelectorAll("*").forEach(el => {
const style = window.getComputedStyle(el);
// Check for blur via filter, backdrop-filter, or class names
if (
style.filter?.includes("blur") ||
style.backdropFilter?.includes("blur") ||
parseFloat(style.opacity) < 1 ||
(el.className && el.className.toString().toLowerCase().includes("blur")) ||
(el.className && el.className.toString().toLowerCase().includes("premium"))
) {
el.style.filter = "none !important";
el.style.backdropFilter = "none !important";
el.style.opacity = "1 !important";
if (el.classList) {
el.classList.remove("blur", "blurred", "premium-blur");
}
}
// Check parent elements for blur-inducing styles
const parent = el.parentElement;
if (parent) {
const parentStyle = window.getComputedStyle(parent);
if (
parentStyle.filter?.includes("blur") ||
parentStyle.backdropFilter?.includes("blur") ||
parseFloat(parentStyle.opacity) < 1
) {
parent.style.filter = "none !important";
parent.style.backdropFilter = "none !important";
parent.style.opacity = "1 !important";
}
}
});
};
// Remove dark overlays and paywall-like elements
document.querySelectorAll("div, section, aside").forEach(el => {
const style = window.getComputedStyle(el);
if (
style.backgroundColor.includes("rgba") &&
(style.backgroundColor.includes("0.5") || parseFloat(style.zIndex) > 1000) ||
(el.className && el.className.toString().toLowerCase().includes("overlay")) ||
(el.className && el.className.toString().toLowerCase().includes("paywall"))
) {
el.remove();
}
});
removeBlur();
// Remove other restrictions
removeBySelector('[class*="blur" i], [class*="premium" i], [class*="paywall" i], [class*="sample-preview-blur" i]');
// Ensure document content is visible
const contentSelectors = [
'.document-content', '.page-content', '.content',
'[data-page]', '[data-testid*="document"]', '[data-testid*="page"]',
'.page', '.document-page', 'main', 'article'
];
contentSelectors.forEach(selector => {
document.querySelectorAll(selector).forEach(el => {
el.style.setProperty('filter', 'none', 'important');
el.style.setProperty('opacity', '1', 'important');
el.style.setProperty('visibility', 'visible', 'important');
el.style.setProperty('display', 'block', 'important');
el.style.setProperty('pointer-events', 'auto', 'important');
});
});
// Remove overlay divs that might be blocking content
const overlays = document.querySelectorAll(`
[class*="overlay" i], [class*="modal" i], [class*="popup" i],
[class*="banner" i], [style*="position: fixed"],
[style*="position: absolute"][style*="z-index"]
`);
overlays.forEach(overlay => {
const text = overlay.textContent || '';
if (text.includes('premium') || text.includes('unlock') || text.includes('subscribe') ||
text.includes('cookie') || text.includes('consent') || text.includes('login')) {
overlay.remove();
}
});
};
// Run immediately
removeRestrictions();
// Run periodically
const intervalId = setInterval(removeRestrictions, 2000);
// Clean up after 60 seconds
setTimeout(() => {
clearInterval(intervalId);
}, 60000);
});
};
/**
* Apply print styles for clean PDF output (integrated from extension script with improvements)
*/
const applyPrintStyles = async (page) => {
console.log("π¨οΈ Applying print styles for clean PDF...");
await page.evaluate(() => {
const style = document.createElement("style");
style.id = "print-style-extension";
style.innerHTML = `
@page {
size: A4 portrait;
margin: 5mm;
}
@media print {
html, body {
margin: 0 !important;
padding: 0 !important;
overflow: visible !important;
}
header, footer, nav, aside, .no-print, .ads, .sidebar,
.premium-banner, .ViewerToolbar, .Layout_info-bar-wrapper__He0Ho,
.Sidebar_sidebar-scrollable__kqeBZ, .HeaderWrapper_header-wrapper__mCmf3,
.Layout_visible-content-bottom-wrapper-sticky__yaaAB,
.Layout_bottom-section-wrapper__yBWWk, .Layout_footer-wrapper__bheJQ,
.InlineBanner_inline-banner-wrapper__DAi5X, .banner-wrapper,
#top-bar-wrapper, .Layout_sidebar-wrapper__unavM,
.Layout_is-open__9DQr4 {
display: none !important;
}
body {
background: white !important;
color: black !important;
}
* {
box-shadow: none !important;
background: transparent !important;
}
.Viewer_document-wrapper__JPBWQ, .Viewer_document-wrapper__LXzoQ,
.Viewer_document-wrapper__XsO4j, .page-content {
display: flex !important;
flex-direction: column !important;
width: 100% !important;
max-width: 210mm !important;
margin: 0 auto !important;
}
[data-page], .page, .document-page, img {
page-break-after: always !important;
page-break-inside: avoid !important;
page-break-before: avoid !important;
width: 100% !important;
max-width: 100% !important;
height: auto !important;
}
}
`;
document.head.appendChild(style);
});
};
/**
* Enhanced StuDocu downloader with comprehensive bypasses and login support
*/
const studocuDownloader = async (url, options = {}) => {
let browser;
try {
console.log("π Launching browser with stealth configuration...");
browser = await puppeteer.launch({
headless: true,
args: [
'--no-sandbox',
'--disable-setuid-sandbox',
'--disable-dev-shm-usage',
'--disable-accelerated-2d-canvas',
'--no-first-run',
'--no-zygote',
'--disable-gpu',
'--disable-features=VizDisplayCompositor',
'--disable-background-networking',
'--disable-background-timer-throttling',
'--disable-renderer-backgrounding',
'--disable-backgrounding-occluded-windows',
'--disable-ipc-flooding-protection',
'--disable-web-security',
'--disable-features=site-per-process',
'--disable-blink-features=AutomationControlled',
'--disable-extensions'
],
timeout: 300000,
});
const page = await browser.newPage();
// Set realistic browser characteristics
await page.setUserAgent('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36');
await page.setViewport({ width: 794, height: 1122 });
// Hide webdriver property
await page.evaluateOnNewDocument(() => {
Object.defineProperty(navigator, 'webdriver', { get: () => undefined });
Object.defineProperty(navigator, 'languages', { get: () => ['en-US', 'en'] });
Object.defineProperty(navigator, 'plugins', { get: () => [1, 2, 3, 4, 5] });
});
// Set up cookie and content bypass
await bypassCookiesAndRestrictions(page);
// Block unnecessary resources
await page.setRequestInterception(true);
page.on('request', (req) => {
const resourceType = req.resourceType();
const reqUrl = req.url();
// Block trackers, ads, and analytics
if (
reqUrl.includes('doubleclick') ||
reqUrl.includes('googletagmanager') ||
reqUrl.includes('facebook.com') ||
reqUrl.includes('twitter.com') ||
reqUrl.includes('analytics') ||
reqUrl.includes('gtm') ||
reqUrl.includes('hotjar') ||
reqUrl.includes('mixpanel') ||
reqUrl.includes('onetrust') ||
reqUrl.includes('cookielaw') ||
resourceType === 'other' && reqUrl.includes('track')
) {
req.abort();
} else {
req.continue();
}
});
// Login if credentials provided (for premium content)
if (options.email && options.password) {
console.log("π Logging in to StuDocu...");
await page.goto('https://www.studocu.com/en-us/login', { waitUntil: 'domcontentloaded', timeout: 60000 });
await page.waitForSelector('#email', { timeout: 15000 });
await page.type('#email', options.email);
await page.type('#password', options.password);
await page.click('button[type="submit"]');
try {
await page.waitForNavigation({ waitUntil: 'networkidle2', timeout: 30000 });
// Additional check for successful login
await page.waitForSelector('.user-profile, [data-testid="user-menu"]', { timeout: 10000 });
console.log("β
Login successful.");
} catch (e) {
console.error("β Login failed:", e.message);
throw new Error("Login failed. Check credentials, if CAPTCHA is present, or try again.");
}
} else {
console.log("β οΈ No login credentials provided. Full unblurred content requires premium account.");
}
console.log(`π Navigating to ${url}...`);
// Navigate with retry logic
let navigationSuccess = false;
let attempts = 0;
const maxAttempts = 3;
while (!navigationSuccess && attempts < maxAttempts) {
try {
attempts++;
console.log(`Navigation attempt ${attempts}/${maxAttempts}`);
await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 60000 });
navigationSuccess = true;
} catch (e) {
console.log(`Navigation attempt ${attempts} failed:`, e.message);
if (attempts >= maxAttempts) throw e;
await new Promise(resolve => setTimeout(resolve, 5000));
}
}
// Wait for initial load
await new Promise(resolve => setTimeout(resolve, 5000));
// Apply content unblurring
await unblurContent(page);
// Wait for document content with multiple selectors
console.log("β³ Waiting for document content to load...");
const contentSelectors = [
'.document-content', '.page-content', '[data-page]',
'[data-testid*="document"]', 'img[src*="document"]',
'img[src*="page"]', '.page', 'main img', 'article img'
];
let contentFound = false;
for (const selector of contentSelectors) {
try {
await page.waitForSelector(selector, { timeout: 20000 });
console.log(`β
Found content with selector: ${selector}`);
contentFound = true;
break;
} catch (e) {
console.log(`β Selector ${selector} not found, trying next...`);
}
}
if (!contentFound) {
console.log("β οΈ No specific content selector found, proceeding with page content...");
}
// Enhanced scrolling to load all content with loop for stability
console.log("π Loading all document pages with enhanced slow scroll...");
await page.evaluate(async () => {
const delay = (ms) => new Promise((res) => setTimeout(res, ms));
let scrollHeight = document.body.scrollHeight;
while (true) {
let totalHeight = 0;
const distance = 300;
while (totalHeight < scrollHeight) {
window.scrollBy(0, distance);
totalHeight += distance;
await delay(500); // Increased delay for better loading
}
await delay(2000); // Extra wait after reaching bottom
const newHeight = document.body.scrollHeight;
if (newHeight === scrollHeight) break;
scrollHeight = newHeight;
}
// Scroll to top
window.scrollTo({ top: 0, behavior: "smooth" });
await delay(1000);
});
// Re-apply unblur after loading new content
await unblurContent(page);
// Wait for all images to load
console.log("πΌοΈ Waiting for all images to load...");
await page.evaluate(async () => {
const images = Array.from(document.querySelectorAll('img'));
await Promise.all(images.map(img => {
if (img.complete) return Promise.resolve();
return new Promise((resolve) => {
img.addEventListener('load', resolve);
img.addEventListener('error', resolve);
setTimeout(resolve, 15000);
});
}));
});
// Additional wait for any lazy loading
await new Promise(resolve => setTimeout(resolve, 10000));
// Set exact height to avoid extra blank pages
console.log("π Setting exact document height...");
await page.evaluate(() => {
const getDocumentHeight = () => Math.max(
document.body.scrollHeight, document.body.offsetHeight,
document.documentElement.clientHeight, document.documentElement.scrollHeight,
document.documentElement.offsetHeight
);
const height = getDocumentHeight();
document.body.style.height = `${height}px !important`;
document.documentElement.style.height = `${height}px !important`;
document.body.style.overflow = 'hidden !important';
});
// Final content verification
const contentCheck = await page.evaluate(() => {
const textContent = document.body.textContent || '';
const images = document.querySelectorAll('img');
const documentImages = Array.from(images).filter(img =>
img.src.includes('document') || img.src.includes('page') ||
img.alt.includes('document') || img.alt.includes('page')
);
return {
totalText: textContent.length,
totalImages: images.length,
documentImages: documentImages.length,
hasDocumentContent: documentImages.length > 0 || textContent.length > 1000,
sampleText: textContent.substring(0, 300)
};
});
console.log("π Content verification:", {
textLength: contentCheck.totalText,
images: contentCheck.totalImages,
documentImages: contentCheck.documentImages,
hasContent: contentCheck.hasDocumentContent
});
if (!contentCheck.hasDocumentContent) {
console.warn("β οΈ Warning: Limited document content detected. Use premium credentials for full access.");
}
// Apply print styles
await applyPrintStyles(page);
// Emulate print media
await page.emulateMediaType('print');
// Generate PDF
console.log("π Generating PDF...");
const pdfBuffer = await page.pdf({
printBackground: true,
preferCSSPageSize: true,
displayHeaderFooter: false,
timeout: 180000,
scale: 1,
omitBackground: false
});
console.log(`β
PDF generated successfully! Size: ${(pdfBuffer.length / 1024 / 1024).toFixed(2)} MB`);
return pdfBuffer;
} catch (error) {
console.error("β Error during PDF generation:", error);
if (error.message.includes('timeout')) {
throw new Error("Request timed out. The document may be taking too long to load. Please try again.");
} else if (error.message.includes('net::')) {
throw new Error("Network error. Please check the URL and your internet connection.");
} else if (error.message.includes('ERR_BLOCKED')) {
throw new Error("Access blocked. Try again or check if the document is publicly accessible.");
} else {
throw new Error(`Failed to generate PDF: ${error.message}`);
}
} finally {
if (browser) {
console.log("π Closing browser...");
try {
await browser.close();
} catch (e) {
console.log("Error closing browser:", e.message);
}
}
}
};
// API Routes
app.post('/api/download', async (req, res) => {
const { url, filename, email, password } = req.body;
if (!url) {
return res.status(400).json({ error: 'URL is required.' });
}
if (!url.includes('studocu.com')) {
return res.status(400).json({ error: 'Please provide a valid StuDocu URL.' });
}
let normalizedUrl = url.trim();
if (!normalizedUrl.startsWith('http')) {
normalizedUrl = 'https://' + normalizedUrl;
}
console.log(`π― Processing request for: ${normalizedUrl}`);
try {
const startTime = Date.now();
const pdfBuffer = await studocuDownloader(normalizedUrl, { filename, email, password });
const processingTime = ((Date.now() - startTime) / 1000).toFixed(2);
res.setHeader('Content-Type', 'application/pdf');
res.setHeader('Content-Disposition', 'attachment; filename=studocu-document.pdf');
res.setHeader('Content-Length', pdfBuffer.length);
res.send(pdfBuffer);
console.log(`π Request completed successfully in ${processingTime}s`);
} catch (error) {
console.error(`β Failed to process ${normalizedUrl}:`, error.message);
res.status(500).json({ error: error.message });
}
});
app.get('/health', (req, res) => {
res.json({ status: 'healthy', timestamp: new Date().toISOString(), uptime: process.uptime() });
});
app.get('/', (req, res) => {
res.json({
message: 'π Enhanced StuDocu Downloader API v5.3 - Advanced Bypass with Print Styles',
version: '5.3',
features: [
'πͺ Advanced cookie banner bypass',
'π Premium content unblurring (client-side only; server-side blur requires premium login)',
'π Login support for full unblurred content access',
'π€ Anti-bot detection evasion',
'π Full document content extraction with print styles for clean PDF'
],
endpoints: {
download: 'POST /api/download (body: {url, filename?, email?, password?})',
health: 'GET /health'
},
note: 'For full unblurred content, provide premium email and password. Blurring is often server-side, so CSS bypass may not suffice without login.'
});
});
process.on('SIGTERM', () => {
console.log('SIGTERM received, shutting down gracefully...');
process.exit(0);
});
process.on('SIGINT', () => {
console.log('SIGINT received, shutting down gracefully...');
process.exit(0);
});
app.listen(port, () => {
console.log(`π Enhanced StuDocu Downloader v5.3 running on http://localhost:${port}`);
console.log(`β¨ Features: Advanced cookie bypass, content unblurring, login support, print styles, anti-detection`);
}); |