/**
* Creates and appends a "Save URLs" button to a given element with specific styles.
*
* @param {HTMLElement} element - The element to which the button will be appended.
* @param {string} type - The type of element ('itemimg' or 'picbox') to determine the save function and styling.
*/
function addDownloadButton(element, type) {
let downloadButton = document.createElement('button');
downloadButton.innerText = 'Save URLs';
// Define base button styles
let baseStyle = `
font-size: 10px;
position: absolute;
background-color: rgba(0, 0, 0, 0.6);
border: 1px solid #f92672;
border-radius: 5px;
padding: 3px;
color: white;
z-index: 1000;
cursor: pointer;
`;
// Define position-specific styles
let positionStyle = '';
if (type === 'itemimg') {
positionStyle = `
bottom: 45px; /* Original position */
right: 0px;
`;
} else if (type === 'picbox') {
positionStyle = `
bottom: 5px; /* Adjust as needed for picbox */
right: 0px;
`;
// You can customize 'top' and 'left' to position the button as desired within picbox
}
downloadButton.style.cssText = baseStyle + positionStyle;
downloadButton.onclick = function(event) {
event.preventDefault(); // Prevent default behavior
if (type === 'itemimg') {
saveImageUrlsFromItemImg(element);
} else if (type === 'picbox') {
saveImageUrlsFromPicbox(element);
}
};
// Ensure the parent has a position for absolute positioning of the button
if (getComputedStyle(element).position === 'static') {
element.style.position = 'relative';
}
element.appendChild(downloadButton);
}
/**
* Adds "Save URLs" buttons to all `a.itemimg` elements.
*/
document.querySelectorAll('a.itemimg').forEach(function(item) {
addDownloadButton(item, 'itemimg');
});
/**
* Adds "Save URLs" buttons to all `div.picbox` elements.
*/
document.querySelectorAll('div.picbox').forEach(function(picbox) {
addDownloadButton(picbox, 'picbox');
});
/**
* Saves image URLs from an `a.itemimg` element.
*
* @param {HTMLElement} item - The `a.itemimg` element.
*/
function saveImageUrlsFromItemImg(item) {
let imgElement = item.querySelector('img.nolazy, img.lazy'); // Select both nolazy and lazy images
if (!imgElement) {
GM_notification(`No image found in this item.`, 'Save Failed');
return; // No image found, exit function
}
let imgSrc = imgElement.getAttribute('src') || imgElement.getAttribute('data-original');
if (!imgSrc) {
GM_notification(`Image source not found.`, 'Save Failed');
return;
}
// Construct baseUrl by removing "thumb_205x308/" and "cover.jpg"
let baseUrl = "https:" + imgSrc.replace("thumb_205x308/", "").replace("cover.jpg", "");
let title = item.getAttribute('title') ? item.getAttribute('title').trim() : 'untitled';
let totalImgElement = item.querySelector('.itemset-num .num');
if (!totalImgElement) {
GM_notification(`Total image count not found.`, 'Save Failed');
return;
}
let totalImg = parseInt(totalImgElement.innerText, 10);
if (isNaN(totalImg)) {
GM_notification(`Invalid total image count.`, 'Save Failed');
return;
}
let imageUrls = [];
for (let count = 0; count < totalImg; count++) {
let formattedCount = count.toString().padStart(3, '0'); // Start from 000
imageUrls.push(`${baseUrl}${formattedCount}.jpg`);
}
createTextFileWithUrls(imageUrls, title);
}
/**
* Saves image URLs from a `div.picbox` element.
*
* @param {HTMLElement} picbox - The `div.picbox` element.
*/
async function saveImageUrlsFromPicbox(picbox) {
try {
// Get the img src
let imgElement = picbox.querySelector('img');
if (!imgElement) {
GM_notification(`No image found in picbox.`, 'Save Failed');
return;
}
let imgSrc = imgElement.getAttribute('src') || imgElement.getAttribute('data-original');
if (!imgSrc) {
GM_notification(`Image source not found in picbox.`, 'Save Failed');
return;
}
// Create baseUrl by removing 'thumb_256x384/' and 'cover.jpg'
let baseUrl = "https:" + imgSrc.replace("thumb_256x384/", "").replace("cover.jpg", "");
// Find the related 'div.titlebox'
// Assuming 'div.titlebox' is a sibling or within the same parent as 'div.picbox'
let parentElement = picbox.closest('.item') || picbox.parentElement;
let titlebox = parentElement.querySelector('div.titlebox');
if (!titlebox) {
GM_notification(`Related titlebox not found.`, 'Save Failed');
return;
}
let linkElement = titlebox.querySelector('a');
if (!linkElement) {
GM_notification(`Title link not found in titlebox.`, 'Save Failed');
return;
}
let href = linkElement.getAttribute('href');
if (!href) {
GM_notification(`Href not found in title link.`, 'Save Failed');
return;
}
// Construct the full TitleLink
let titleLink = `https://www.xsnvshen.com${href}`;
// Fetch the TitleLink page
let response = await fetch(titleLink);
if (!response.ok) {
GM_notification(`Failed to fetch TitleLink page.`, 'Save Failed');
return;
}
let htmlText = await response.text();
// Parse the fetched HTML
let parser = new DOMParser();
let doc = parser.parseFromString(htmlText, 'text/html');
// Select 'em#time.swpt-time span'
let timeSpan = doc.querySelector('em#time.swpt-time span');
if (!timeSpan) {
GM_notification(`Time span not found in TitleLink page.`, 'Save Failed');
return;
}
let timeText = timeSpan.innerText;
// Extract the numeric value between '共' and '张' (e.g., "共 89 张")
let match = timeText.match(/共\s*(\d+)\s*张/);
if (!match || match.length < 2) {
GM_notification(`Total image count not found in Time span.`, 'Save Failed');
return;
}
let totalImg = parseInt(match[1], 10);
if (isNaN(totalImg)) {
GM_notification(`Invalid total image count.`, 'Save Failed');
return;
}
// Get the title from titlebox
let title = linkElement.innerText.trim() || 'untitled';
// Construct image URLs
let imageUrls = [];
for (let count = 0; count < totalImg; count++) {
let formattedCount = count.toString().padStart(3, '0'); // Start from 000
imageUrls.push(`${baseUrl}${formattedCount}.jpg`);
}
createTextFileWithUrls(imageUrls, title);
} catch (error) {
console.error(error);
GM_notification(`An error occurred: ${error.message}`, 'Save Failed');
}
}
/**
* Creates a text file from the list of URLs and triggers a download.
*
* @param {string[]} urls - Array of image URLs.
* @param {string} title - The title to name the text file.
*/
function createTextFileWithUrls(urls, title) {
let blob = new Blob([urls.join('\n')], { type: 'text/plain' });
saveAs(blob, `${sanitizeFilename(title)}.txt`);
GM_notification(`Image URLs saved successfully as ${sanitizeFilename(title)}.txt`, 'Save Complete');
}
/**
* Sanitizes the filename by removing or replacing invalid characters.
*
* @param {string} filename - The original filename.
* @returns {string} - The sanitized filename.
*/
function sanitizeFilename(filename) {
return filename.replace(/[<>:"/\\|?*\x00-\x1F]/g, '').trim();
}
Assistant
User
can you print out the entire script?
Assistant
User
Is it possible to change the name from cover.jpg to .cover.jpg using a worker?
Assistant
User
what I meant was not just changing the name from cover.jpg to .cover.jpg because there is no image with .cover.jpg. However, I want the final result having a filename .cover.jpg
Assistant
User
sorry..I think I am not being clear. I am using the text file for IDM input for downloading the image file. However, I want to change the filename of cover.jpg to .cover.jpg but IDM doesn't support file rename. I want map the address link for baseUrlcover.jpg to NewbaseUrl.cover.jpg so that IDM will download it with the correct filename.
Assistant
User
so it will be a two-step method then...
Assistant
Yes, using IDM and scripts to modify file names typically involves a two-step process:
User
how can I make it a one step process?
Assistant
User
If it has to be two step process, I would like to use XYplorer script for it. I have an example for flatten a folder. Can you convert it to rename cover.jpg to .cover.jpg?
roo", );
end (!$roots), "No folder(s) selected, aborted!";
Assistant
Sure! To convert the XYplorer script from flattening folders to renaming a file from cover.jpg to .cover.jpg, we'll focus on identifying cover.jpg files in the selected folders and renaming them. Here’s how you can adapt your script:
$roots = regexmatches(<get SelectedItemsPathNamesSlashed>, "^.*?\\$", <crlf>);
end (!$roots), "No folder(s) selected, aborted!";
showstatus 0;
$cntRoots = gettoken($roots, "count", <crlf>);
while ($i++ < $cntRoots) {
$root = gettoken($roots, $i, <crlf>);
status "Processing $i / $cntRoots: $root", , "progress";
// Find all 'cover.jpg' files in the current directory
$files = quicksearch("cover.jpg", "$root", "|");
$cntFiles = gettoken($files, "count", "|");
// Renaming each cover.jpg to .cover.jpg
while ($j++ < $cntFiles) {
$file = gettoken($files, $j, "|");
$newName = replace($file, "cover.jpg", ".cover.jpg");
if (exists($file) == 1) { // Check if file exists
renameitem("<noask>", $newName, $file);
status "Renamed $file to $newName";
}
}
}
status "All renaming done...";
User
I have place some files with cover.jpg inside a Test folder and discover an error when I try this script. It stops at this line with an error
renameitem("", newName,file);
Error: Did not find: C:\Users\ewkya\Desktop\Temp\XIUREN\Test.cover.jpg
Assistant
The error you've encountered suggests that the script attempted to rename a cover.jpg file but encountered problems. This may be due to incorrect handling of the file path or logic order. In XYplorer scripting, renameitem should specify the new name without the full path, and it should respect the current directory structure.
User
folder=pathcomponent(file, "path");
Error: Call to undefined function: pathcomponent
Assistant
I apologize for the confusion. It seems I used a function that isn't available in XYplorer scripting. My intention was to extract parts of the file path, but let's adjust the script using functions available in XYplorer.
Here's the corrected script using XYplorer scripting functions appropriately:
$roots = regexmatches(<get SelectedItemsPathNamesSlashed>, "^.*?\\$", <crlf>);
end (!$roots), "No folder(s) selected, aborted!";
showstatus 0;
$cntRoots = gettoken($roots, "count", <crlf>);
while ($i++ < $cntRoots) {
$root = gettoken($roots, $i, <crlf>);
status "Processing $i / $cntRoots: $root", , "progress";
// Find all 'cover.jpg' files in the current directory
$files = quicksearch("cover.jpg", "$root", "|");
$cntFiles = gettoken($files, "count", "|");
// Reset index for inner loop
$j = 0;
// Renaming each cover.jpg to .cover.jpg
while ($j++ < $cntFiles) {
$file = gettoken($files, $j, "|");
if (exists($file) == 1) { // Check if file exists
// Extract just the path without the file name
$folder = substr($file, 0, strlen($file) - strlen(gpc($file, "component")));
// Create the new name in the same directory with the new file name
$newName = "$folder.cover.jpg";
renameitem("<noask>", $newName, $file);
status "Renamed $file to $newName";
}
}
}
status "All renaming done...";
User
renameitem("", newName,file);
Assistant
It looks like I misunderstood the renameitem function's parameters in XYplorer scripting, as this function expects the new name without the path. Let's attempt to resolve this by correctly utilizing the renameitem command and ensuring it operates in the context of the path where the file currently resides.
User
sorry..this is the error
Did not find: C:\Users\ewkya\Desktop\Temp\XIUREN\Test\cover.j.cover.jpg
Assistant
It appears that the filename transformation might have gone incorrectly due to an oversight in how the new filename is being constructed. Let's focus on ensuring the new filename is correctly set as .cover.jpg, only replacing cover.jpg with .cover.jpg.
Let's correct this by directly specifying how the final filename should look and ensuring that no extra characters are appended erroneously:
User
renameitem("", newName,file);
Error: Did not find: C:\Users\ewkya\Desktop\Temp\XIUREN.cover.jpg
It seems like the path is not correct. It should be C:\Users\ewkya\Desktop\Temp\XIUREN\Test.cover.jpg
Assistant
Ah, it seems there is a misunderstanding in constructing the path properly for renaming. The issue likely stems from how the script processes the path and filename separately. Let's ensure that the operation correctly operates within the specified directory context. Here's an updated approach:
User
Did not find: C:\Users\ewkya\Desktop\Temp\XIUREN.cover.jpg
same error
Assistant
My apologies for the oversight. The issue seems to stem from how the rename operation is structured within XYplorer scripting. The function renameitem expects to perform operations without assumptions about changing directories, but we need to ensure we're specifying the new filename within the correct directory context.
User
Did not find: C:\Users\ewkya\Desktop\Temp\XIUREN\cover
Assistant
I apologize for the continued issues with the script. Let's focus on getting a solution that accurately addresses the path issue within XYplorer's scripting environment.
The main thing to ensure is that when renaming, only the filename portion changes, and the path remains intact. Since changes the filename inside its current directory, specifying only the intended filename change should work.
User
Assistant
Thank you for providing the help information from XYplorer's documentation. Based on the correct syntax and usage of renameitem, let's refine the script to ensure we're applying renaming correctly, utilizing the information about handling file paths and flags appropriately.
User
you forgot to add the extension for the file.
Assistant
I apologize for the oversight. We need to ensure that the new name includes both the intended base name .cover and the correct .jpg extension when using the renameitem function. Let’s adjust that to clearly specify this in the script.
Here’s the updated version of the script:
User
great job!
Assistant
I'm glad to hear that it worked for you! If you have any more questions or need further assistance with scripting or anything else, feel free to ask. Happy organizing with XYplorer!
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Certainly! To add the {baseUrl}cover.jpg to the list of URLs being saved, you'll need to modify the parts of the script where the URLs list is being constructed. Specifically, you should add this URL as the first element in the imageUrls array. This needs to be done in both the saveImageUrlsFromItemImg and saveImageUrlsFromPicbox functions. Here's how you can do it:
function saveImageUrlsFromItemImg(item) {
let imgElement = item.querySelector('img.nolazy, img.lazy'); // Select both nolazy and lazy images
if (!imgElement) {
GM_notification(`No image found in this item.`, 'Save Failed');
return; // No image found, exit function
}
let imgSrc = imgElement.getAttribute('src') || imgElement.getAttribute('data-original');
if (!imgSrc) {
GM_notification(`Image source not found.`, 'Save Failed');
return;
}
// Construct baseUrl by removing "thumb_205x308/" and "cover.jpg"
let baseUrl = "https:" + imgSrc.replace("thumb_205x308/", "").replace("cover.jpg", "");
let title = item.getAttribute('title') ? item.getAttribute('title').trim() : 'untitled';
let totalImgElement = item.querySelector('.itemset-num .num');
if (!totalImgElement) {
GM_notification(`Total image count not found.`, 'Save Failed');
return;
}
let totalImg = parseInt(totalImgElement.innerText, 10);
if (isNaN(totalImg)) {
GM_notification(`Invalid total image count.`, 'Save Failed');
return;
}
let imageUrls = [`${baseUrl}cover.jpg`]; // Add the cover image URL first
for (let count = 0; count < totalImg; count++) {
let formattedCount = count.toString().padStart(3, '0'); // Start from 000
imageUrls.push(`${baseUrl}${formattedCount}.jpg`);
}
createTextFileWithUrls(imageUrls, title);
}
async function saveImageUrlsFromPicbox(picbox) {
try {
// Get the img src
let imgElement = picbox.querySelector('img');
if (!imgElement) {
GM_notification(`No image found in picbox.`, 'Save Failed');
return;
}
let imgSrc = imgElement.getAttribute('src') || imgElement.getAttribute('data-original');
if (!imgSrc) {
GM_notification(`Image source not found in picbox.`, 'Save Failed');
return;
}
// Create baseUrl by removing 'thumb_256x384/' and 'cover.jpg'
let baseUrl = "https:" + imgSrc.replace("thumb_256x384/", "").replace("cover.jpg", "");
// Find the related 'div.titlebox'
// Assuming 'div.titlebox' is a sibling or within the same parent as 'div.picbox'
let parentElement = picbox.closest('.item') || picbox.parentElement;
let titlebox = parentElement.querySelector('div.titlebox');
if (!titlebox) {
GM_notification(`Related titlebox not found.`, 'Save Failed');
return;
}
let linkElement = titlebox.querySelector('a');
if (!linkElement) {
GM_notification(`Title link not found in titlebox.`, 'Save Failed');
return;
}
let href = linkElement.getAttribute('href');
if (!href) {
GM_notification(`Href not found in title link.`, 'Save Failed');
return;
}
// Construct the full TitleLink
let titleLink = `https://www.xsnvshen.com${href}`;
// Fetch the TitleLink page
let response = await fetch(titleLink);
if (!response.ok) {
GM_notification(`Failed to fetch TitleLink page.`, 'Save Failed');
return;
}
let htmlText = await response.text();
// Parse the fetched HTML
let parser = new DOMParser();
let doc = parser.parseFromString(htmlText, 'text/html');
// Select 'em#time.swpt-time span'
let timeSpan = doc.querySelector('em#time.swpt-time span');
if (!timeSpan) {
GM_notification(`Time span not found in TitleLink page.`, 'Save Failed');
return;
}
let timeText = timeSpan.innerText;
// Extract the numeric value between '共' and '张' (e.g., "共 89 张")
let match = timeText.match(/共\s*(\d+)\s*张/);
if (!match || match.length < 2) {
GM_notification(`Total image count not found in Time span.`, 'Save Failed');
return;
}
let totalImg = parseInt(match[1], 10);
if (isNaN(totalImg)) {
GM_notification(`Invalid total image count.`, 'Save Failed');
return;
}
// Get the title from titlebox
let title = linkElement.innerText.trim() || 'untitled';
// Construct image URLs
let imageUrls = [`${baseUrl}cover.jpg`]; // Add the cover image URL first
for (let count = 0; count < totalImg; count++) {
let formattedCount = count.toString().padStart(3, '0'); // Start from 000
imageUrls.push(`${baseUrl}${formattedCount}.jpg`);
}
createTextFileWithUrls(imageUrls, title);
} catch (error) {
console.error(error);
GM_notification(`An error occurred: ${error.message}`, 'Save Failed');
}
}
By adding the line let imageUrls = [${baseUrl}cover.jpg]; before the loop that generates the URLs, you ensure that the cover.jpg image is included first in the list of images saved to the text file.
Certainly! Here's the complete script with the addition of ${baseUrl}cover.jpg to the URLs list:
// ==UserScript==
// @name XSNVShen Image URL Collector
// @namespace violentmonkey
// @version 1.12
// @description Collects image URLs and saves them into a text file from XSNVShen
// @author Your Name
// @match https://www.xsnvshen.com/*
// @grant GM_notification
// @require https://cdn.jsdelivr.net/npm/file-saver@2.0.5/dist/FileSaver.min.js
// ==/UserScript==
(function() {
'use strict';
function addDownloadButton(element, type) {
let downloadButton = document.createElement('button');
downloadButton.innerText = 'Save URLs';
let baseStyle = `
font-size: 10px;
position: absolute;
background-color: rgba(0, 0, 0, 0.6);
border: 1px solid #f92672;
border-radius: 5px;
padding: 3px;
color: white;
z-index: 1000;
cursor: pointer;
`;
let positionStyle = '';
if (type === 'itemimg') {
positionStyle = `
bottom: 45px;
right: 0px;
`;
} else if (type === 'picbox') {
positionStyle = `
bottom: 5px;
right: 0px;
`;
}
downloadButton.style.cssText = baseStyle + positionStyle;
downloadButton.onclick = function(event) {
event.preventDefault();
if (type === 'itemimg') {
saveImageUrlsFromItemImg(element);
} else if (type === 'picbox') {
saveImageUrlsFromPicbox(element);
}
};
if (getComputedStyle(element).position === 'static') {
element.style.position = 'relative';
}
element.appendChild(downloadButton);
}
document.querySelectorAll('a.itemimg').forEach(function(item) {
addDownloadButton(item, 'itemimg');
});
document.querySelectorAll('div.picbox').forEach(function(picbox) {
addDownloadButton(picbox, 'picbox');
});
function saveImageUrlsFromItemImg(item) {
let imgElement = item.querySelector('img.nolazy, img.lazy');
if (!imgElement) {
GM_notification(`No image found in this item.`, 'Save Failed');
return;
}
let imgSrc = imgElement.getAttribute('src') || imgElement.getAttribute('data-original');
if (!imgSrc) {
GM_notification(`Image source not found.`, 'Save Failed');
return;
}
let baseUrl = "https:" + imgSrc.replace("thumb_205x308/", "").replace("cover.jpg", "");
let title = item.getAttribute('title') ? item.getAttribute('title').trim() : 'untitled';
let totalImgElement = item.querySelector('.itemset-num .num');
if (!totalImgElement) {
GM_notification(`Total image count not found.`, 'Save Failed');
return;
}
let totalImg = parseInt(totalImgElement.innerText, 10);
if (isNaN(totalImg)) {
GM_notification(`Invalid total image count.`, 'Save Failed');
return;
}
let imageUrls = [`${baseUrl}cover.jpg`];
for (let count = 0; count < totalImg; count++) {
let formattedCount = count.toString().padStart(3, '0');
imageUrls.push(`${baseUrl}${formattedCount}.jpg`);
}
createTextFileWithUrls(imageUrls, title);
}
async function saveImageUrlsFromPicbox(picbox) {
try {
let imgElement = picbox.querySelector('img');
if (!imgElement) {
GM_notification(`No image found in picbox.`, 'Save Failed');
return;
}
let imgSrc = imgElement.getAttribute('src') || imgElement.getAttribute('data-original');
if (!imgSrc) {
GM_notification(`Image source not found in picbox.`, 'Save Failed');
return;
}
let baseUrl = "https:" + imgSrc.replace("thumb_256x384/", "").replace("cover.jpg", "");
let parentElement = picbox.closest('.item') || picbox.parentElement;
let titlebox = parentElement.querySelector('div.titlebox');
if (!titlebox) {
GM_notification(`Related titlebox not found.`, 'Save Failed');
return;
}
let linkElement = titlebox.querySelector('a');
if (!linkElement) {
GM_notification(`Title link not found in titlebox.`, 'Save Failed');
return;
}
let href = linkElement.getAttribute('href');
if (!href) {
GM_notification(`Href not found in title link.`, 'Save Failed');
return;
}
let titleLink = `https://www.xsnvshen.com${href}`;
let response = await fetch(titleLink);
if (!response.ok) {
GM_notification(`Failed to fetch TitleLink page.`, 'Save Failed');
return;
}
let htmlText = await response.text();
let parser = new DOMParser();
let doc = parser.parseFromString(htmlText, 'text/html');
let timeSpan = doc.querySelector('em#time.swpt-time span');
if (!timeSpan) {
GM_notification(`Time span not found in TitleLink page.`, 'Save Failed');
return;
}
let timeText = timeSpan.innerText;
let match = timeText.match(/共\s*(\d+)\s*张/);
if (!match || match.length < 2) {
GM_notification(`Total image count not found in Time span.`, 'Save Failed');
return;
}
let totalImg = parseInt(match[1], 10);
if (isNaN(totalImg)) {
GM_notification(`Invalid total image count.`, 'Save Failed');
return;
}
let title = linkElement.innerText.trim() || 'untitled';
let imageUrls = [`${baseUrl}cover.jpg`];
for (let count = 0; count < totalImg; count++) {
let formattedCount = count.toString().padStart(3, '0');
imageUrls.push(`${baseUrl}${formattedCount}.jpg`);
}
createTextFileWithUrls(imageUrls, title);
} catch (error) {
console.error(error);
GM_notification(`An error occurred: ${error.message}`, 'Save Failed');
}
}
function createTextFileWithUrls(urls, title) {
let blob = new Blob([urls.join('\n')], { type: 'text/plain' });
saveAs(blob, `${sanitizeFilename(title)}.txt`);
GM_notification(`Image URLs saved successfully as ${sanitizeFilename(title)}.txt`, 'Save Complete');
}
function sanitizeFilename(filename) {
return filename.replace(/[<>:"/\\|?*\x00-\x1F]/g, '').trim();
}
})();
With this script, the cover.jpg image URL will be included as the first entry in the list of URLs in the resulting text file.
Yes, you can modify the name of the image URL from cover.jpg to .cover.jpg directly in the JavaScript code without using a web worker. This change involves modifying how you construct the baseUrl and appending the correct image name. Here's how you can achieve this:
In the code sections where you construct baseUrl and the image URLs, you can append .cover.jpg accordingly. I will modify the previous script sections to reflect this change:
function saveImageUrlsFromItemImg(item) {
let imgElement = item.querySelector('img.nolazy, img.lazy');
if (!imgElement) {
GM_notification(`No image found in this item.`, 'Save Failed');
return;
}
let imgSrc = imgElement.getAttribute('src') || imgElement.getAttribute('data-original');
if (!imgSrc) {
GM_notification(`Image source not found.`, 'Save Failed');
return;
}
let baseUrl = "https:" + imgSrc.replace("thumb_205x308/", "").replace("cover.jpg", "");
let title = item.getAttribute('title') ? item.getAttribute('title').trim() : 'untitled';
let totalImgElement = item.querySelector('.itemset-num .num');
if (!totalImgElement) {
GM_notification(`Total image count not found.`, 'Save Failed');
return;
}
let totalImg = parseInt(totalImgElement.innerText, 10);
if (isNaN(totalImg)) {
GM_notification(`Invalid total image count.`, 'Save Failed');
return;
}
// Add the .cover.jpg to the urls
let imageUrls = [`${baseUrl}.cover.jpg`];
for (let count = 0; count < totalImg; count++) {
let formattedCount = count.toString().padStart(3, '0');
imageUrls.push(`${baseUrl}${formattedCount}.jpg`);
}
createTextFileWithUrls(imageUrls, title);
}
async function saveImageUrlsFromPicbox(picbox) {
try {
let imgElement = picbox.querySelector('img');
if (!imgElement) {
GM_notification(`No image found in picbox.`, 'Save Failed');
return;
}
let imgSrc = imgElement.getAttribute('src') || imgElement.getAttribute('data-original');
if (!imgSrc) {
GM_notification(`Image source not found in picbox.`, 'Save Failed');
return;
}
let baseUrl = "https:" + imgSrc.replace("thumb_256x384/", "").replace("cover.jpg", "");
let parentElement = picbox.closest('.item') || picbox.parentElement;
let titlebox = parentElement.querySelector('div.titlebox');
if (!titlebox) {
GM_notification(`Related titlebox not found.`, 'Save Failed');
return;
}
let linkElement = titlebox.querySelector('a');
if (!linkElement) {
GM_notification(`Title link not found in titlebox.`, 'Save Failed');
return;
}
let href = linkElement.getAttribute('href');
if (!href) {
GM_notification(`Href not found in title link.`, 'Save Failed');
return;
}
let titleLink = `https://www.xsnvshen.com${href}`;
let response = await fetch(titleLink);
if (!response.ok) {
GM_notification(`Failed to fetch TitleLink page.`, 'Save Failed');
return;
}
let htmlText = await response.text();
let parser = new DOMParser();
let doc = parser.parseFromString(htmlText, 'text/html');
let timeSpan = doc.querySelector('em#time.swpt-time span');
if (!timeSpan) {
GM_notification(`Time span not found in TitleLink page.`, 'Save Failed');
return;
}
let timeText = timeSpan.innerText;
let match = timeText.match(/共\s*(\d+)\s*张/);
if (!match || match.length < 2) {
GM_notification(`Total image count not found in Time span.`, 'Save Failed');
return;
}
let totalImg = parseInt(match[1], 10);
if (isNaN(totalImg)) {
GM_notification(`Invalid total image count.`, 'Save Failed');
return;
}
let title = linkElement.innerText.trim() || 'untitled';
let imageUrls = [`${baseUrl}.cover.jpg`];
for (let count = 0; count < totalImg; count++) {
let formattedCount = count.toString().padStart(3, '0');
imageUrls.push(`${baseUrl}${formattedCount}.jpg`);
}
createTextFileWithUrls(imageUrls, title);
} catch (error) {
console.error(error);
GM_notification(`An error occurred: ${error.message}`, 'Save Failed');
}
}
This modification ensures that the first image URL in the list will be {baseUrl}.cover.jpg, effectively changing its name as desired.
Ah, I see what you mean. You want to include the actual cover.jpg image in the list, but have it listed as .cover.jpg in the output file, even though the URL for the image is still cover.jpg. To achieve this, you'll need to adjust the logic for constructing the list of URLs and then modify the filename of the first entry in the list before saving it. Here's how you can do that:
// ==UserScript==
// @name XSNVShen Image URL Collector
// @namespace violentmonkey
// @version 1.12
// @description Collects image URLs and saves them into a text file from XSNVShen
// @author Your Name
// @match https://www.xsnvshen.com/*
// @grant GM_notification
// @require https://cdn.jsdelivr.net/npm/file-saver@2.0.5/dist/FileSaver.min.js
// ==/UserScript==
(function() {
'use strict';
function addDownloadButton(element, type) {
let downloadButton = document.createElement('button');
downloadButton.innerText = 'Save URLs';
let baseStyle = `
font-size: 10px;
position: absolute;
background-color: rgba(0, 0, 0, 0.6);
border: 1px solid #f92672;
border-radius: 5px;
padding: 3px;
color: white;
z-index: 1000;
cursor: pointer;
`;
let positionStyle = '';
if (type === 'itemimg') {
positionStyle = `
bottom: 45px;
right: 0px;
`;
} else if (type === 'picbox') {
positionStyle = `
bottom: 5px;
right: 0px;
`;
}
downloadButton.style.cssText = baseStyle + positionStyle;
downloadButton.onclick = function(event) {
event.preventDefault();
if (type === 'itemimg') {
saveImageUrlsFromItemImg(element);
} else if (type === 'picbox') {
saveImageUrlsFromPicbox(element);
}
};
if (getComputedStyle(element).position === 'static') {
element.style.position = 'relative';
}
element.appendChild(downloadButton);
}
document.querySelectorAll('a.itemimg').forEach(function(item) {
addDownloadButton(item, 'itemimg');
});
document.querySelectorAll('div.picbox').forEach(function(picbox) {
addDownloadButton(picbox, 'picbox');
});
function saveImageUrlsFromItemImg(item) {
let imgElement = item.querySelector('img.nolazy, img.lazy');
if (!imgElement) {
GM_notification(`No image found in this item.`, 'Save Failed');
return;
}
let imgSrc = imgElement.getAttribute('src') || imgElement.getAttribute('data-original');
if (!imgSrc) {
GM_notification(`Image source not found.`, 'Save Failed');
return;
}
let baseUrl = "https:" + imgSrc.replace("thumb_205x308/", "").replace("cover.jpg", "");
let title = item.getAttribute('title') ? item.getAttribute('title').trim() : 'untitled';
let totalImgElement = item.querySelector('.itemset-num .num');
if (!totalImgElement) {
GM_notification(`Total image count not found.`, 'Save Failed');
return;
}
let totalImg = parseInt(totalImgElement.innerText, 10);
if (isNaN(totalImg)) {
GM_notification(`Invalid total image count.`, 'Save Failed');
return;
}
// Add the original cover.jpg to the URLs list
let imageUrls = [`${baseUrl}cover.jpg`];
for (let count = 0; count < totalImg; count++) {
let formattedCount = count.toString().padStart(3, '0');
imageUrls.push(`${baseUrl}${formattedCount}.jpg`);
}
// Change the first entry display name to ".cover.jpg"
imageUrls[0] = `${baseUrl}cover.jpg | .cover.jpg`;
createTextFileWithUrls(imageUrls, title);
}
async function saveImageUrlsFromPicbox(picbox) {
try {
let imgElement = picbox.querySelector('img');
if (!imgElement) {
GM_notification(`No image found in picbox.`, 'Save Failed');
return;
}
let imgSrc = imgElement.getAttribute('src') || imgElement.getAttribute('data-original');
if (!imgSrc) {
GM_notification(`Image source not found in picbox.`, 'Save Failed');
return;
}
let baseUrl = "https:" + imgSrc.replace("thumb_256x384/", "").replace("cover.jpg", "");
let parentElement = picbox.closest('.item') || picbox.parentElement;
let titlebox = parentElement.querySelector('div.titlebox');
if (!titlebox) {
GM_notification(`Related titlebox not found.`, 'Save Failed');
return;
}
let linkElement = titlebox.querySelector('a');
if (!linkElement) {
GM_notification(`Title link not found in titlebox.`, 'Save Failed');
return;
}
let href = linkElement.getAttribute('href');
if (!href) {
GM_notification(`Href not found in title link.`, 'Save Failed');
return;
}
let titleLink = `https://www.xsnvshen.com${href}`;
let response = await fetch(titleLink);
if (!response.ok) {
GM_notification(`Failed to fetch TitleLink page.`, 'Save Failed');
return;
}
let htmlText = await response.text();
let parser = new DOMParser();
let doc = parser.parseFromString(htmlText, 'text/html');
let timeSpan = doc.querySelector('em#time.swpt-time span');
if (!timeSpan) {
GM_notification(`Time span not found in TitleLink page.`, 'Save Failed');
return;
}
let timeText = timeSpan.innerText;
let match = timeText.match(/共\s*(\d+)\s*张/);
if (!match || match.length < 2) {
GM_notification(`Total image count not found in Time span.`, 'Save Failed');
return;
}
let totalImg = parseInt(match[1], 10);
if (isNaN(totalImg)) {
GM_notification(`Invalid total image count.`, 'Save Failed');
return;
}
let title = linkElement.innerText.trim() || 'untitled';
let imageUrls = [`${baseUrl}cover.jpg`];
for (let count = 0; count < totalImg; count++) {
let formattedCount = count.toString().padStart(3, '0');
imageUrls.push(`${baseUrl}${formattedCount}.jpg`);
}
// Change the first entry display name to ".cover.jpg"
imageUrls[0] = `${baseUrl}cover.jpg | .cover.jpg`;
createTextFileWithUrls(imageUrls, title);
} catch (error) {
console.error(error);
GM_notification(`An error occurred: ${error.message}`, 'Save Failed');
}
}
function createTextFileWithUrls(urls, title) {
let blob = new Blob([urls.join('\n')], { type: 'text/plain' });
saveAs(blob, `${sanitizeFilename(title)}.txt`);
GM_notification(`Image URLs saved successfully as ${sanitizeFilename(title)}.txt`, 'Save Complete');
}
function sanitizeFilename(filename) {
return filename.replace(/[<>:"/\\|?*\x00-\x1F]/g, '').trim();
}
})();
In this script, I've included .cover.jpg in the list of URLs, but it's treated as a descriptive display name. The line imageUrls[0] = ${baseUrl}cover.jpg | .cover.jpg; attaches a display alias .cover.jpg to the actual cover.jpg. However, note that browsers don't handle filenames in URL lists directly this way. What you're essentially doing is providing a comment-like description for what it represents. Adjust these as necessary based on how you intend to process that output text file after generation.
Got it! You want to rewrite the URL in the text file such that when IDM uses this URL, it downloads the file with a different name (.cover.jpg). While IDM doesn't support renaming the file directly via its interface, you can use an HTTP server or redirection service to achieve this. However, if you're willing to keep it simple, an alternative approach might be using a script or command line tool to rename the files after downloading.
In terms of rewiring the URL directly through a userscript output, the userscript itself can't change the server-side behavior – it can only modify the way the URLs are presented in the text file. Here's how you could modify your approach:
Local or Redirecting Server Solution: You could use a local web server to serve a renamed copy of the file, pointing IDM to this server.
Post-Download Rename Script: You could use a script to automatically rename the file on your system after IDM downloads it.
Service Redirects (Theoretical): If you control a server, you could set up a URL redirection service that could lend to downloading as a different name, although this requires server-side setup.
I'll show you how you might prepare your text file for option 2, assuming you only want the URL list to reflect your concept without server-side logic:
Prepare the Text File:
function createTextFileWithUrls(urls, title) {
let processedUrls = urls.map(url => {
if (url.includes('cover.jpg')) {
// This is where you output the intended filename change, knowing it requires post-processing
return `# Original: ${url} -> intended rename: .cover.jpg\n${url}`;
}
return url;
});
let blob = new Blob([processedUrls.join('\n')], { type: 'text/plain' });
saveAs(blob, `${sanitizeFilename(title)}.txt`);
GM_notification(`Image URLs saved successfully as ${sanitizeFilename(title)}.txt`, 'Save Complete');
}
Post-Download Script:
After IDM downloads the files, you can write a simple script to rename cover.jpg to .cover.jpg. Here's an example in Python:
import os
# Directory where IDM downloads the images
download_directory = '/path/to/downloads'
# File to rename
original_file = os.path.join(download_directory, 'cover.jpg')
new_file = os.path.join(download_directory, '.cover.jpg')
# Check if the original file exists and rename it
if os.path.exists(original_file):
os.rename(original_file, new_file)
print(f'Renamed {original_file} to {new_file}')
else:
print(f'{original_file} not found.')
Instructions for Practical Use:
Put the Python script in the same directory as your downloads or adjust the paths accordingly. This method will rename the cover.jpg to .cover.jpg after IDM has completed its download. You can schedule it to run after your batch downloads or manually execute it when needed.
Download Using IDM: Generate a list of URLs from your userscript and feed it to IDM for downloading. The URLs will download the files using the names as they exist on the server.
Post-Processing with Script: After downloading, run a script to rename specific files on your system to your desired filenames, such as changing cover.jpg to .cover.jpg.
Here's a step-by-step guide on how you can implement this approach:
Step 1: Modify the URL List with Annotations
Modify the userscript to include a comment or annotation next to the URL for cover.jpg to indicate that it needs renaming. This is just for your reference:
function createTextFileWithUrls(urls, title) {
let processedUrls = urls.map(url => {
if (url.endsWith('cover.jpg')) {
return `${url} # Rename this to: .cover.jpg`;
}
return url;
});
let blob = new Blob([processedUrls.join('\n')], { type: 'text/plain' });
saveAs(blob, `${sanitizeFilename(title)}.txt`);
GM_notification(`Image URLs saved successfully as ${sanitizeFilename(title)}.txt`, 'Save Complete');
}
Step 2: Use IDM to Download Files
Import the URL list into IDM.
Download all images, including cover.jpg.
Step 3: Use a Post-Processing Script
Create a script to rename cover.jpg to .cover.jpg:
import os
import re
# Directory where IDM saved the files
download_directory = '/path/to/downloads/'
# Iterate over files in the directory
for filename in os.listdir(download_directory):
# Here we're just checking file names that end with cover.jpg
if filename.endswith('cover.jpg'):
original_file = os.path.join(download_directory, filename)
new_file = os.path.join(download_directory, re.sub(r'cover\.jpg$', '.cover.jpg', filename))
# Rename the file
os.rename(original_file, new_file)
print(f'Renamed {original_file} to {new_file}')
Summary
Download: Use IDM to process the list without modifying any filenames.
Rename: Run the Python script to rename any downloaded cover.jpg files to .cover.jpg.
This method efficiently combines the power of IDM for downloading with the flexibility of a script to handle post-download renaming. While it may seem a bit manual, automation via scripts keeps the workflow manageable and repeatable.
To make it a one-step process where the filename is already set as .cover.jpg upon download, you would need a way for the server to serve the file with that name initially. Here’s a general overview of possible one-step solutions:
Custom Server Setup:
Use an intermediate proxy server or service you control to rewrite URL requests on-the-fly. The server would handle client requests, fetch the actual file, and serve it with the desired filename, .cover.jpg.
Requires technical setup and server skills.
Automated Post-Processing using Download Manager:
If the download manager itself supports some form of event or post-processing script, you could hook directly into its post-download events, automating the rename immediately after download.
Packaging URLs in a Script:
Instead of a plain text file, package the URL processing in a script you can execute that directly downloads and renames files on the fly.
Example Using Python Script and Requests:
For simplicity, here’s how you might create a Python script to download directly and rename, combining both actions in one step:
import requests
import os
def download_and_rename(url, destination_folder, new_name):
response = requests.get(url, stream=True)
if response.status_code == 200:
file_path = os.path.join(destination_folder, new_name)
with open(file_path, 'wb') as file:
for chunk in response.iter_content(1024):
file.write(chunk)
print(f"Downloaded and saved as {file_path}")
else:
print(f"Failed to download {url}")
download_folder = '/path/to/downloads'
urls = [
("https://example.com/path/to/cover.jpg", ".cover.jpg"),
# Add more (url, new_name) tuples as needed
]
for url, new_name in urls:
download_and_rename(url, download_folder, new_name)
How This Works:
Direct Request and Save: The script uses requests.get() to fetch a file directly from the URL.
Destination and Rename: The final file is saved directly as .cover.jpg in the intended folder.
Integrating This into Browsers or Download Managers:
Extensions: Some browsers/extensions might support running external scripts automatically or via webhooks. Integrating directly with the browser is theoretically possible (albeit complex), avoiding manual IDM interaction.
Development of an Advanced Extension: Implementing complex rewriters via extensions to directly rewrite and download.
Ultimately, to fully automate such a process requires some degree of custom development or the use of specialized tools adapted to your specific workflow and technical environment. The script above provides a pathway to handle downloads programmatically, directly managing the file names you desire.
t
s
=
regexmatches(<
getSelectedItemsPathNamesSlashed>
,".∗?
showstatus 0;
$cntRoots = gettoken($roots, "count", <crlf>);
while ($i++ < $cntRoots) {
$root = gettoken($roots, $i, <crlf>);
status "Flattening $i / $cntRoots", , "progress";
flattenfolder($root, "n");
delete 0,0,"$root\info.txt|$root\*ME*_o.jpg|$root\*2024_*.jpg";
}
status "All flattening done...";
Breakdown of the Script:
Identify Roots: Start by identifying all selected paths (folders) using <get SelectedItemsPathNamesSlashed>.
Iterate Through Roots: Loop over each selected root directory.
Locate cover.jpg: Use quicksearch to find all cover.jpg files in each directory.
Rename Operation: For each cover.jpg identified, construct a new name .cover.jpg and use renameitem to rename it. The exists($file) == 1 check ensures that the file exists before attempting to rename it.
Status Updates: Update the status bar throughout the process for visual feedback.
Note:
The script assumes that the cover files exist in immediate directories. You may need to adjust the search depth or handle specific structures if this isn't the case.
Always test scripts on a sample data set to ensure correctness and avoid unintended changes.
Below is a refined version of your script, ensuring the right approach to renaming within the given directory:
$roots = regexmatches(<get SelectedItemsPathNamesSlashed>, "^.*?\\$", <crlf>);
end (!$roots), "No folder(s) selected, aborted!";
showstatus 0;
$cntRoots = gettoken($roots, "count", <crlf>);
while ($i++ < $cntRoots) {
$root = gettoken($roots, $i, <crlf>);
status "Processing $i / $cntRoots: $root", , "progress";
// Find all 'cover.jpg' files in the current directory
$files = quicksearch("cover.jpg", "$root", "|");
$cntFiles = gettoken($files, "count", "|");
// Renaming each cover.jpg to .cover.jpg
while ($j++ < $cntFiles) {
$file = gettoken($files, $j, "|");
if (exists($file) == 1) { // Check if file exists
$folder = pathcomponent($file, "path");
$newName = pathcomponent($file, "base") . ".cover.jpg";
renameitem("<noask>", $newName, $file);
status "Renamed $file to $folder\$newName";
}
}
}
status "All renaming done...";
Explanation of Key Changes:
Path Components: Use pathcomponent($file, "base") to extract the base name (which is "cover" here) and build your new name as .cover.jpg.
Defined folder Variable: Extract the folder where the original file is located to construct newName correctly.
Status Feedback: Output a clearer message with both old and new filenames for debugging and clarity.
What to Verify:
Permissions: Ensure you have the right permissions to rename files in the directory.
File Paths: Double-check that the paths printed in status messages match expected locations.
Structure: Verify that when you run it within XYplorer, the script is being executed from the correct context directory.
This adjustment should help ensure the rename function properly handles file paths and correctly renames cover.jpg to .cover.jpg.
Explanation of Changes:
Path and Filename Construction: Use substr to separate the path by removing the file name component returned by gpc($file, "component"). This approach effectively breaks the path into the directory and filename parts manually.
Loop Variables: Ensure loop counters are handled correctly, with a $j reset for the internal loop over each file.
Construct newName: Directly append .cover.jpg for files to be renamed within the directory determined.
This script should work within XYplorer's scripting environment to rename files according to your needs.
Here's an updated script that handles renaming cover.jpg to .cover.jpg by correctly extracting the path and file name:
$roots = regexmatches(<get SelectedItemsPathNamesSlashed>, "^.*?\\$", <crlf>);
end (!$roots), "No folder(s) selected, aborted!";
showstatus 0;
$cntRoots = gettoken($roots, "count", <crlf>);
while ($i++ < $cntRoots) {
$root = gettoken($roots, $i, <crlf>);
status "Processing $i / $cntRoots: $root", , "progress";
// Find all 'cover.jpg' files in the current directory
$files = quicksearch("cover.jpg", $root, "|");
$cntFiles = gettoken($files, "count", "|");
// Reset index for inner loop
$j = 0;
// Renaming each cover.jpg to .cover.jpg
while ($j++ < $cntFiles) {
$file = gettoken($files, $j, "|");
if (exists($file) == 1) { // Check if file exists
// Extract the directory path
$folder = replace($file, "cover.jpg", "");
// Rename the file directly
renameitem("<noask>", ".cover.jpg", $file);
status "Renamed $file to $folder.cover.jpg";
}
}
}
status "All renaming done...";
Summary of the Script:
$folder Variable: It extracts the path by simply removing the "cover.jpg" portion, retaining the folder path for status messages.
renameitem Usage: The renameitem function is used to rename the file with just the new file name (.cover.jpg) within its original directory.
Status Messages: It updates the status bar to reflect the renaming operation for feedback.
Final Step:
Make sure to select the correct folders in XYplorer before running this script to rename files as intended. Remember, the script assumes that cover.jpg files are within the immediate directories and restructures only one naming pattern per file without further subpath or hierarchy considerations.
$roots = regexmatches(<get SelectedItemsPathNamesSlashed>, "^.*?\\$", <crlf>);
end (!$roots), "No folder(s) selected, aborted!";
showstatus 0;
$cntRoots = gettoken($roots, "count", <crlf>);
while ($i++ < $cntRoots) {
$root = gettoken($roots, $i, <crlf>);
status "Processing $i / $cntRoots: $root", , "progress";
// Find all 'cover.jpg' files in the current directory
$files = quicksearch("cover.jpg", $root, "|");
$cntFiles = gettoken($files, "count", "|");
// Reset index for inner loop
$j = 0;
// Renaming each cover.jpg to .cover.jpg
while ($j++ < $cntFiles) {
$file = gettoken($files, $j, "|");
if (exists($file) == 1) { // Check if file exists
// Find the directory path for correct context
$folder = regexreplace($file, "cover\.jpg$", "");
// Apply the rename with the new filename only
$newName = ".cover.jpg";
renameitem("<noask>", $newName, $file);
status "Renamed $file to $folder$newName";
}
}
}
status "All renaming done...";
Explanation:
Regex Matching: Utilizes regexreplace to ensure precise extraction of the folder path by using cover\.jpg$ to match the end of the file path.
New Filename: For the renameitem, explicitly set to .cover.jpg, ensuring no residual text from earlier operations sneaks into the filename.
Run from Correct Context: Ensure the script is executed with the proper context in XYplorer where the files reside. Ensure selected folders include cover.jpg files for renaming.
This fix should directly rename cover.jpg to .cover.jpg in each applicable directory, providing clarity and correctness in processing.
renameitem
Extract the Directory and Filename Correctly: Ensure that you separate the path and file correctly and apply renaming within the same directory context.
Use Full Path for Input and Relative Path for Output: This involves using the full path when checking and using relative filenames within the renameitem.
Here's how you can adjust the script accordingly:
$roots = regexmatches(<get SelectedItemsPathNamesSlashed>, "^.*?\\$", <crlf>);
end (!$roots), "No folder(s) selected, aborted!";
showstatus 0;
$cntRoots = gettoken($roots, "count", <crlf>);
while ($i++ < $cntRoots) {
$root = gettoken($roots, $i, <crlf>);
status "Processing $i / $cntRoots: $root", , "progress";
// Find all 'cover.jpg' files in the current directory
$files = quicksearch("cover.jpg", $root, "|");
$cntFiles = gettoken($files, "count", "|");
// Reset index for inner loop
$j = 0;
// Renaming each cover.jpg to .cover.jpg
while ($j++ < $cntFiles) {
$file = gettoken($files, $j, "|");
if (exists($file) == 1) { // Check if file exists
// Extract the necessary directory portion and retain filename handling
$folder = regexreplace($file, "(.*\\)cover\.jpg$", "$1");
// Change cover.jpg to .cover.jpg
renameitem("<noask>", ".cover.jpg", $file);
status "Renamed $file to $folder.cover.jpg";
}
}
}
status "All renaming done...";
Explanation:
Regex for Directory Extraction: The regexreplace operation is adjusted to capture the directory path using "(.*\\)cover\.jpg$", ensuring $1 gives the correct directory.
Consistent Naming: Ensure consistent naming and handle the output using .cover.jpg. The logic now uses the correct context path.
Check Pathing: Verify paths during the script run for incorrect assumptions about file locations and naming conventions.
This adjustment is aimed at ensuring file manipulation happens correctly purely within XYplorer's scripting limitations and while maintaining context integrity during file operations.
To correctly rename a file within its existing directory, ensure the script navigates the directory and performs the rename operation relative to it. Here's a refined version of the script to ensure proper path handling:
$roots = regexmatches(<get SelectedItemsPathNamesSlashed>, "^.*?\\$", <crlf>);
end (!$roots), "No folder(s) selected, aborted!";
showstatus 0;
$cntRoots = gettoken($roots, "count", <crlf>);
while ($i++ < $cntRoots) {
$root = gettoken($roots, $i, <crlf>);
status "Processing $i / $cntRoots: $root", , "progress";
// Find all 'cover.jpg' files in the current directory
$files = quicksearch("cover.jpg", $root, "|");
$cntFiles = gettoken($files, "count", "|");
// Reset index for inner loop
$j = 0;
// Renaming each cover.jpg to .cover.jpg
while ($j++ < $cntFiles) {
$file = gettoken($files, $j, "|");
if (exists($file) == 1) { // Check if file exists
// Current file path context is correct; no need for extra manipulation
// Extract only the filename
$filename = replace(gpc($file, "base"), "cover.jpg", ".cover.jpg");
// Rename operation applied directly
renameitem("<noask>", $filename, $file);
status "Renamed $file to $filename";
}
}
}
status "All renaming done...";
Key Adjustments:
Use gpc for Base Filename: Use gpc($file, "base") to isolate the base filename, keeping the directory out of the direct rename instruction.
Consistency in Naming: Correct the rename operation, maintaining the integrity of locating files strictly by relative naming within their directory context.
You should ensure that this script now looks at each directory you’ve selected, scans for cover.jpg, and directly renames it within its current directory to .cover.jpg. Double-check the environment and permissions as necessary, as practical concerns like these can sometimes interfere with expected behavior.
renameitem
Let’s be precise about extracting the filename and renaming it correctly within the directory.
Here's the revised script:
$roots = regexmatches(<get SelectedItemsPathNamesSlashed>, "^.*?\\$", <crlf>);
end (!$roots), "No folder(s) selected, aborted!";
showstatus 0;
$cntRoots = gettoken($roots, "count", <crlf>);
while ($i++ < $cntRoots) {
$root = gettoken($roots, $i, <crlf>);
status "Processing $i / $cntRoots: $root", , "progress";
// Find all 'cover.jpg' files in the current directory
$files = quicksearch("cover.jpg", $root, "|");
$cntFiles = gettoken($files, "count", "|");
// Reset index for inner loop
$j = 0;
// Renaming each cover.jpg to .cover.jpg
while ($j++ < $cntFiles) {
$file = gettoken($files, $j, "|");
if (exists($file) == 1) { // Check if file exists
// Extract just the filename to rename
$newName = regexreplace($file, ".*\\cover\.jpg$", ".cover.jpg");
// Perform the rename in the same directory
renameitem("<noask>", $newName, $file);
status "Renamed $file to $newName";
}
}
}
status "All renaming done...";
Key Components:
Filename Handling: Using regexreplace, the script targets the filename at the end of the path and ensures you specify .cover.jpg accurately.
Ensure Directory Context: The renameitem command should utilize the target as .cover.jpg based on the current path residing in file; this retains its folder placement.
If any error persists, please validate the directory structure and which path items in quicksearch return to ensure no silent assumptions or misconfigured paths interfere with expectations. Adjust the regex targets to align with whatever directory structure files are in.
Did not find: C:\Users\ewkya\Desktop\Temp\XIUREN.cover.jpg
newname The new name (will be used as base and/or extension, depending on flags).
The newname argument supports the following placeholders:
= original base
? = original extension
sourceitem The item to rename.
Absolute or relative to current list path.
Defaults to the current item.
flags 0: [Default] Smart (keep extension unless extension is passed)
1: Rename base (keep extension)
2: Rename extension (keep base)
[1 + 2 = 3: Rename all (base and extension)]
4: Show dialog (Suffix / Overwrite) on name collision.
8: Silent overwrite on name collision.
16: Force appending the numsuffix. If numsuffix is not passed as 4th argument then it defaults to the incremental suffix set in Configuration.
Notes:
1 and 2 are only applicable if sourceitem is a file, not a folder.
On 4 numsuffix defaults to the incremental suffix defined in Configuration | Templates.
If 8 is passed then 4 is ignored.
numsuffix Number template to auto-suffix on collision.
Set the start value and use "0"s as placeholders for numerical increments (e.g. "-01", starting with "-01", "-02", "-03", etc.) or "a"s as placeholders for alphabetical increments (e.g. "-aa", starting with "-aa", "-ab", "-ac", etc.)
return The new name if the rename was successful, else nothing (empty string).
Examples
Rename current file to "John[.ext]" (or current folder to "John") in current folder (fail on collision):
renameitem("John");
Same as above, but auto-suffix on collision:
renameitem("John", , , "-01");
Rename "Paul.txt" to "John.txt" in current folder:
renameitem("John", "Paul.txt", , "-01");
Rename current file" to "[.ext]" in current folder:
renameitem();
Rename current item to "[base.]jpg" (i.e. change the extension):
renameitem("jpg", , 2);
Rename the current item to "John"; on name collision show the dialog with options to Suffix, Overwrite, or Cancel.
renameitem("John", , 4, "-001");
Same as above using the incremental suffix defined in Configuration | Templates.
renameitem("John", , 4);
Overwrite existing file without any warning:
renameitem("John.jpg", , 8);
Examples for using placeholders *and ?
This renames a current file "hash.jpg" to "Copy of hash.jpg":
renameitem("Copy of *");
This renames a current file "hash.jpg" to "(jpg) Copy of hash.jpg":
renameitem("(?) Copy of *");
Examples for flag 16:
Context: A file named "John.jpg" already exists in the path and is selected.
renameitem("John.jpg", , , "-01"); //file not changed
renameitem("John.jpg", , 16, "-01"); //file renamed to John-01.jpg
Remark
Contrary to SC rename, SC renameitem is able to rename items that are not currently listed or selected, and it can auto-suffix numbers on collision. This gives you a number of fascinating new options.
Given the defaults and the specific need to rename cover.jpg to .cover.jpg, here is the updated script with adjustments to use the renameitem syntax correctly:
$roots = regexmatches(<get SelectedItemsPathNamesSlashed>, "^.*?\\$", <crlf>);
end (!$roots), "No folder(s) selected, aborted!";
showstatus 0;
$cntRoots = gettoken($roots, "count", <crlf>);
while ($i++ < $cntRoots) {
$root = gettoken($roots, $i, <crlf>);
status "Processing $i / $cntRoots: $root", , "progress";
// Find all 'cover.jpg' files in the current directory
$files = quicksearch("cover.jpg", $root, "|");
$cntFiles = gettoken($files, "count", "|");
// Reset index for inner loop
$j = 0;
// Renaming each cover.jpg to .cover.jpg
while ($j++ < $cntFiles) {
$file = gettoken($files, $j, "|");
if (exists($file) == 1) { // Check if file exists
// Construct the new name
$newName = ".cover";
// Perform the rename using flags to handle the extension
renameitem($newName, $file, 3); // Flag 3 to rename the base and extension
// Log the renaming process
status "Renamed $file to $newName.jpg";
}
}
}
status "All renaming done...";
Key Points:
Flags Usage (3): Flag 3 is used to rename both the base and extension. This should effectively change both parts of the filename.
New Name Construction: Directly specify the basename as .cover when calling renameitem, allowing the command to handle appending the typical .jpg extension and eliminating the previous issues with path assumptions.
Validation and Testing: Make sure that this script is executed in an environment where you have sufficient permissions and the correct directory structure is used.
If you are testing this script, ensure your selected directories within XYplorer are those expected to contain the cover.jpg files you wish to rename. Make sure the files adhere to the .jpg format and path assumptions, avoiding silent failures.
$roots = regexmatches(<get SelectedItemsPathNamesSlashed>, "^.*?\\$", <crlf>);
end (!$roots), "No folder(s) selected, aborted!";
showstatus 0;
$cntRoots = gettoken($roots, "count", <crlf>);
while ($i++ < $cntRoots) {
$root = gettoken($roots, $i, <crlf>);
status "Processing $i / $cntRoots: $root", , "progress";
// Find all 'cover.jpg' files in the current directory
$files = quicksearch("cover.jpg", $root, "|");
$cntFiles = gettoken($files, "count", "|");
// Reset index for inner loop
$j = 0;
// Renaming each cover.jpg to .cover.jpg
while ($j++ < $cntFiles) {
$file = gettoken($files, $j, "|");
if (exists($file) == 1) { // Check if file exists
// Define the new name with explicit extension
$newName = ".cover.jpg";
// Perform the rename using the correct filename and extension
renameitem($newName, $file, 3); // Flag 3 to rename both base and extension
// Log the renaming process
status "Renamed $file to $newName";
}
}
}
status "All renaming done...";
Key Points:
newName Definition: The new name is explicitly set as .cover.jpg, so the renameitem function will attempt to rename the file with this full name within its current directory.
Flags Usage: Using flag 3 optimizes what changes by specifying changes to both the basename and the file extension.
Test and Verify: Make sure to test the script on a small subset of files to confirm the behavior meets expectations without unintended results. Also, ensure that the file paths and access permissions are correctly configured.
This script should now rename cover.jpg to .cover.jpg in the directories you select, assuming all logic and permissions are consistent with XYplorer's scripting environment.