Compare commits

..

1 commit

Author SHA1 Message Date
retardgerman 70fdb5965e
Merge e38f3de6c8 into 82e50c64f0 2024-09-28 04:46:06 +10:00
4 changed files with 68 additions and 3728 deletions

View file

@ -18,22 +18,15 @@ MKBSD comes in two variants! Node.js and Python.
### Running in Node.js ### Running in Node.js
1. Ensure you have Node.js installed. 1. Ensure you have Node.js installed.
2. Save the `images.json` file in the same directory as `mkbsd.js`. 2. Run `node mkbsd.js`
3. Run `node mkbsd.js`. 3. Wait a little.
4. Wait a little. 4. All wallpapers are now in a newly created `downloads` subfolder.
5. All wallpapers are now in a newly created `downloads` subfolder.
### Changes Made in `mkbsd.js and mkbsd.py`
- **Local JSON Source**: The script was updated to read from a local `images.json` file instead of fetching data from a remote URL. This allows you to have full control over the data source.
- **File System Operations**: The script now uses Node.js's `fs` module to read and parse the JSON file directly.
- **Image Download Logic**: The image download logic was adapted to extract the artist's name and image URLs from the local JSON structure, ensuring the images are saved in artist-specific folders.
### Running in Python ### Running in Python
1. Ensure you have Python installed. 1. Ensure you have Python installed.
2. Save the `images.json` file in the same directory as `mkbsd.py`. 2. Ensure you have the `aiohttp` Python package installed (`pip install aiohttp`).
3. Run `python mkbsd.py`. 3. Run `python mkbsd.py`
4. Wait a little. 4. Wait a little.
5. All wallpapers are now in a newly created `downloads` subfolder. 5. All wallpapers are now in a newly created `downloads` subfolder.

File diff suppressed because it is too large Load diff

View file

@ -1,65 +1,51 @@
const fs = require('fs'); const fs = require('fs');
const path = require('path'); const path = require('path');
// Function to delay the downloads
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
async function main() { async function main() {
const jsonFilePath = path.join(__dirname, 'images.json'); const url = 'https://storage.googleapis.com/panels-api/data/20240916/media-1a-i-p~s';
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
// Load local JSON file
let jsonData;
try { try {
if (!fs.existsSync(jsonFilePath)) { const response = await fetch(url);
throw new Error('⛔ JSON file not found.'); if (!response.ok) {
throw new Error(`⛔ Failed to fetch JSON file: ${response.statusText}`);
}
const jsonData = await response.json();
const data = jsonData.data;
if (!data) {
throw new Error('⛔ JSON does not have a "data" property at its root.');
} }
const jsonFileContent = fs.readFileSync(jsonFilePath, 'utf-8'); for (const key in data) {
jsonData = JSON.parse(jsonFileContent); const subproperty = data[key];
console.info('📂 JSON file loaded successfully!'); if (subproperty && subproperty.dhd) {
} catch (error) { const imageUrl = subproperty.dhd;
console.error(`⛔ Failed to load JSON file: ${error.message}`); console.info(`🔍 Found image URL!`);
return;
}
const data = jsonData.data; // Extract the artist name before the underscore
if (!data) { const artistNameMatch = imageUrl.match(/a~([^_/]+)/);
console.error('⛔ JSON does not have a "data" property at its root.'); const artistName = artistNameMatch ? artistNameMatch[1] : 'unknown_artist';
return; const artistDir = path.join(__dirname, 'downloads', artistName);
}
// Loop through each item in the JSON // Create artist directory if it doesn't exist
for (const key in data) { if (!fs.existsSync(artistDir)) {
const subproperty = data[key]; fs.mkdirSync(artistDir, { recursive: true });
if (subproperty && subproperty.dhd) { console.info(`📁 Created directory: ${artistDir}`);
const imageUrl = subproperty.dhd; }
console.info(`🔍 Found image URL!`);
// Extract the artist name before the underscore // Extract the filename and extension
const artistNameMatch = imageUrl.match(/a~([^_/]+)/); const urlPath = new URL(imageUrl).pathname;
const artistName = artistNameMatch ? artistNameMatch[1] : 'unknown_artist'; const fileName = path.basename(urlPath); // Filename including extension (e.g. .jpg or .png)
const artistDir = path.join(__dirname, 'downloads', artistName); const filePath = path.join(artistDir, fileName);
// Create artist directory if it doesn't exist // Download the image and save it to the specified path
if (!fs.existsSync(artistDir)) {
fs.mkdirSync(artistDir, { recursive: true });
console.info(`📁 Created directory: ${artistDir}`);
}
// Extract the filename and extension
const urlPath = new URL(imageUrl).pathname;
const fileName = path.basename(urlPath); // Filename including extension (e.g., .jpg or .png)
const filePath = path.join(artistDir, fileName);
// Download the image and save it to the specified path
try {
await downloadImage(imageUrl, filePath); await downloadImage(imageUrl, filePath);
console.info(`🖼️ Saved image to ${filePath}`); console.info(`🖼️ Saved image to ${filePath}`);
await delay(250); // Delay between downloads await delay(250); // Delay between downloads
} catch (err) {
console.error(`❌ Error downloading image: ${err.message}`);
} }
} }
} catch (error) {
console.error(`Error: ${error.message}`);
} }
} }
@ -88,7 +74,7 @@ function asciiArt() {
console.info(`🤑 Starting downloads from your favorite sellout grifter's wallpaper app...`); console.info(`🤑 Starting downloads from your favorite sellout grifter's wallpaper app...`);
} }
// Start the program with ASCII art and delay // Start program with ASCII art and delay
(() => { (() => {
asciiArt(); asciiArt();
setTimeout(main, 5000); setTimeout(main, 5000);

View file

@ -2,11 +2,9 @@ import os
import time import time
import aiohttp import aiohttp
import asyncio import asyncio
import json
from urllib.parse import urlparse from urllib.parse import urlparse
# Load the local JSON file url = 'https://storage.googleapis.com/panels-api/data/20240916/media-1a-i-p~s'
json_file_path = 'images.json'
async def delay(ms): async def delay(ms):
await asyncio.sleep(ms / 1000) await asyncio.sleep(ms / 1000)
@ -24,37 +22,38 @@ async def download_image(session, image_url, file_path):
async def main(): async def main():
try: try:
# Load JSON data from the local file
with open(json_file_path, 'r') as json_file:
json_data = json.load(json_file)
data = json_data.get('data')
if not data:
raise Exception('⛔ JSON does not have a "data" property at its root.')
async with aiohttp.ClientSession() as session: async with aiohttp.ClientSession() as session:
for key, subproperty in data.items(): async with session.get(url) as response:
if subproperty and subproperty.get('dhd'): if response.status != 200:
image_url = subproperty['dhd'] raise Exception(f"⛔ Failed to fetch JSON file: {response.status}")
print(f"🔍 Found image URL!") json_data = await response.json()
data = json_data.get('data')
# Extract artist name from the URL if not data:
artist_name = image_url.split('a~')[1].split('_')[0] raise Exception('⛔ JSON does not have a "data" property at its root.')
artist_dir = os.path.join(os.getcwd(), 'downloads', artist_name)
if not os.path.exists(artist_dir): for key, subproperty in data.items():
os.makedirs(artist_dir) if subproperty and subproperty.get('dhd'):
print(f"📁 Created directory: {artist_dir}") image_url = subproperty['dhd']
print(f"🔍 Found image URL!")
# Extract filename from the URL # Extrahiere den Künstlernamen vor dem Unterstrich
filename = os.path.basename(urlparse(image_url).path) # Name including extension parsed_url = urlparse(image_url)
file_path = os.path.join(artist_dir, filename) artist_name = image_url.split('a~')[1].split('_')[0]
artist_dir = os.path.join(os.getcwd(), 'downloads', artist_name)
await download_image(session, image_url, file_path) if not os.path.exists(artist_dir):
print(f"🖼️ Saved image to {file_path}") os.makedirs(artist_dir)
print(f"📁 Created directory: {artist_dir}")
await delay(250) # Extrahiere den Dateinamen und die Endung
filename = os.path.basename(parsed_url.path) # Name inklusive Endung
file_path = os.path.join(artist_dir, filename)
await download_image(session, image_url, file_path)
print(f"🖼️ Saved image to {file_path}")
await delay(250)
except Exception as e: except Exception as e:
print(f"Error: {str(e)}") print(f"Error: {str(e)}")