// ==UserScript== // @name Add Buttons to Xiuren // @namespace http://tampermonkey.net/…
- User
// ==UserScript== // @name Add Buttons to Xiuren // @namespace http://tampermonkey.net/ // @version 2.2 // @description Add custom buttons to each index_selected_box anchor in the Xiuren website for parallel downloads, ensuring valid image files only // @author Your Name // @match https://xiuren.mobi/* // @grant none // ==/UserScript==
(function() { 'use strict';
const script = document.createElement('script'); script.src = "https://cdnjs.cloudflare.com/ajax/libs/jszip/3.7.1/jszip.min.js"; script.onload = function() { console.log('JSZip loaded'); createButtons(); }; document.head.appendChild(script); function createButtons() { const targetDivs = document.querySelectorAll('div.index_selected_warp div.index_selected_box a'); if (targetDivs.length > 0) { console.log(`Found ${targetDivs.length} target divs.`); targetDivs.forEach((targetDiv) => { const downloadButton = document.createElement('button'); downloadButton.className = 'download-button'; downloadButton.innerText = 'Download'; downloadButton.style.cssText = ` font-size: 8px; position: absolute; background-color: #336699; border: 1px solid #f92672; border-radius: 3px; padding: 2px; color: white; z-index: 10; cursor: pointer; opacity: 0.9; `; downloadButton.addEventListener('click', function() { const imgElement = targetDiv.querySelector('img.lazy.index_selected_img.img-responsive'); const textElement = targetDiv.parentElement.querySelector('div.index_selected_text'); if (imgElement && textElement) { const title = textElement.textContent || textElement.innerText; const totalImagesMatch = title.match(/(\d+)P\b/); const totalImages = totalImagesMatch ? Math.min(parseInt(totalImagesMatch[1], 10), 99) : 99; // Max 99 const imageUrl = imgElement.dataset.src || imgElement.src; const issue = imageUrl.match(/\/(\d{5,8})\//)[1]; const alt = imgElement.alt; console.log(`Attempting to download ${totalImages} images for issue: ${issue}`); downloadImagesInParallel(imageUrl, issue, alt, totalImages); } else { console.error('Required elements not found.'); } }); const parentDiv = targetDiv.parentElement; const parentRect = parentDiv.getBoundingClientRect(); downloadButton.style.top = `${parentRect.height + 5}px`; downloadButton.style.right = '2px'; parentDiv.appendChild(downloadButton); }); } else { console.error('No target divs found!'); } } async function fetchImageThroughWorker(url) { try { console.log(`Fetching image from ${url}`); const proxyUrl = `https://xiuren.maestro1four1.workers.dev/?url=${encodeURIComponent(url)}`; const response = await fetch(proxyUrl); if (response.ok) { const blob = await response.blob(); if (blob.size > 100) { // Example threshold to avoid very small or empty blobs console.log(`Successfully fetched image from ${url}`); return blob; } else { console.warn(`Received empty or small blob from ${url}`); return null; } } else { console.warn(`Failed response for ${url}: ${response.statusText}`); return null; } } catch (error) { console.error(`Error fetching from ${url}:`, error); return null; } } async function downloadImagesInParallel(baseImageUrl, issue, alt, totalImages) { if (!baseImageUrl || !issue) { console.error('Invalid image URL or issue number.'); return; } const baseDir = baseImageUrl.match(/https:\/\/.*\/(\d{4})\//)[0]; const zip = new JSZip(); let downloadedCount = 0; const imageUrls = []; for (let index = 1; index <= 99; index++) { // Prepare up to 99 potential requests const imageIndex = index.toString().padStart(2, '0'); const imageUrlWithIndex = `${baseDir}${issue}/${issue}${imageIndex}.jpg`; imageUrls.push(imageUrlWithIndex); } const CONCURRENT_DOWNLOADS = 100; let index = 0; while (index < imageUrls.length && downloadedCount < totalImages) { const batch = imageUrls.slice(index, index + CONCURRENT_DOWNLOADS).map(url => fetchImageThroughWorker(url)); const results = await Promise.allSettled(batch); results.forEach((result, resultIndex) => { if (result.status === 'fulfilled' && result.value) { const imageIndex = (index + resultIndex + 1).toString().padStart(2, '0'); zip.file(`${issue}${imageIndex}.jpg`, result.value); downloadedCount++; console.log(`Added ${issue}${imageIndex}.jpg to zip. Total downloaded: ${downloadedCount}`); } else { console.warn(`Image from batch index ${index + resultIndex} not included: ${result.reason || 'Failed to fetch'}`); } }); index += CONCURRENT_DOWNLOADS; } try { if (Object.keys(zip.files).length > 0) { console.log('Generating zip file...'); const zipContent = await zip.generateAsync({ type: "blob" }); const link = document.createElement('a'); link.href = URL.createObjectURL(zipContent); link.download = `${alt || issue}.zip`; document.body.appendChild(link); link.click(); document.body.removeChild(link); console.log('Zip file created and downloaded successfully.'); } else { console.warn('No valid images were added to the zip file.'); } } catch (error) { console.error('Error during zip generation:', error); } } window.addEventListener('load', function() { if (typeof JSZip !== 'undefined') { createButtons(); } }); - Assistant
The loop in the provided script will potentially iterate up to 99 times due to the line:
for (let index = 1; index <= 99; index++) {However, whether it actually fetches 99 images depends on multiple factors:
-
Title Parsing Logic: The title of the image set is parsed to extract the number of images (
totalImages). The script uses a regular expression to find a number in the format like(\d+)P. If such a pattern is found, the script takes the minimum value between parsed number and 99. If no pattern is found, it defaults to a maximum of 99 images. -
Image Availability: The
fetchImageThroughWorkerfunction is called for each potential image URL. If the server has corresponding images and the fetch requests are successful and return sufficiently large blobs, these images will be counted towards the .
-
- User
If this title, [XIUREN秀人网] 2024.10.09 NO.9255 杏子Yada [82P], is encountered. Where will the loop end?
- Assistant
If the title
[XIUREN秀人网] 2024.10.09 NO.9255 杏子Yada [82P]is encountered, the script will interpret82Pto mean that there are 82 images in the set.Here's how the script processes this scenario:
-
Title Parsing:
- The script uses the regular expression
(\d+)P\bto extract the number of images. In this title,82Pmatches, sototalImagesMatch[1]would be82.
- The script uses the regular expression
-
Determine Total Images:
- The
totalImagesis calculated asMath.min(parseInt(totalImagesMatch[1], 10), 99). In this case,parseInt(totalImagesMatch[1], 10)gives82, and the minimum between82and99is82.
- The
-
Loop Execution:
- The loop
for (let index = 1; index <= 99; index++)prepares up to 99 potential requests, but the actual download process will continue only untildownloadedCountreaches82(assuming all images are available and properly fetched).
- The loop
-
- User
From the control panel of the Developer, I can see it is still trying fetch for images after 82. This is the url I see which was canceled in the status. https://xiuren.maestro1four1.workers.dev/?url=https%3A%2F%2Fxiuren.mobi%2Fuploadfiles%2Fxiuren%2F2024%2F20249255%2F2024925583.jpg
- Assistant
In your scenario, it seems that the script is still attempting to fetch images even after reaching the 82nd image. This is because of the way the loop and concurrency are set up:
-
Loop Execution: The loop is designed to prepare all potential URL requests up to image 99, regardless of
totalImages. It generates all possible image URLs and then fetches them in batches controlled byCONCURRENT_DOWNLOADS. -
Batch Processing: The script creates batches of requests and processes these batches in parallel (up to a configured concurrency level of 100 images). This explains why you might see requests for image numbers beyond 82, as the script pre-schedules them before checking if the desired count is reached.
-
- User
Please modify it and print out the entire script.
- Assistant
- User
I can see it is no longer fetching for images after the TotalImage is reached. However, it doesn't download the zip file. Please help me fix this.
- Assistant
- User
I am not getting any zip file. Can you add a console.log which states how many images are downloaded?
- Assistant
- User
it is not working. I have noticed something is missing in the UserScript...something similar to these lines. // @require https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js // @require https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js
- Assistant
- User
Great...everything is working now. Could you help me include the cover.jpg image in the zip file. However, I would like rename it ${issue}00 so that it is always at the beginning of all the images.
- Assistant
- User
I have run into a problem when the TotalImage from the Title doesn't match with the actual downloadable image number.
Is it possible to find the actually total image from scanning all the url (with loop from 01 to 99) before setting this number for the download loop? - Assistant
- User
It fails to download zip file again. could you help me add a prompt on the window saying showing the actual Total number of Image?
- Assistant