-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWallhavenDownloader.java
More file actions
234 lines (186 loc) · 9.35 KB
/
Copy pathWallhavenDownloader.java
File metadata and controls
234 lines (186 loc) · 9.35 KB
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
import java.io.InputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class WallhavenDownloader {
private static final String RESET = "\u001B[0m";
private static final String BOLD = "\u001B[1m";
private static final String DIM = "\u001B[2m";
private static final String CYAN = "\u001B[36m";
private static final String MAGENTA = "\u001B[35m";
private static final String GREEN = "\u001B[32m";
private static final String YELLOW = "\u001B[33m";
private static final String RED = "\u001B[31m";
private static final String BLUE = "\u001B[34m";
private static final String USER_AGENT =
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " +
"(KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36";
private static final AtomicInteger downloaded = new AtomicInteger(0);
private static final AtomicInteger failed = new AtomicInteger(0);
private static int totalTarget = 0;
public static void main(String[] args) throws Exception {
printBanner();
var sc = new Scanner(System.in);
System.out.print(CYAN + " ❯ " + BOLD + "Search term " + RESET + CYAN + "→ " + RESET);
String query = sc.nextLine().trim();
System.out.print(CYAN + " ❯ " + BOLD + "How many " + RESET + CYAN + "→ " + RESET);
int count = Integer.parseInt(sc.nextLine().trim());
totalTarget = count;
System.out.print(CYAN + " ❯ " + BOLD + "Threads " + RESET + CYAN + "→ " + RESET
+ DIM + "(default 8, press enter to skip) " + RESET);
String threadInput = sc.nextLine().trim();
int threads = threadInput.isEmpty() ? 8 : Integer.parseInt(threadInput);
Path downloadDir = Paths.get("C:\\Users\\konda\\OneDrive\\Desktop\\wallpaper");
Files.createDirectories(downloadDir);
System.out.println();
System.out.println(DIM + " Saving to → " + downloadDir + RESET);
System.out.println();
printDivider();
System.out.println(MAGENTA + BOLD + " [ FETCHING WALLPAPER LINKS ]" + RESET);
printDivider();
Instant start = Instant.now();
List<String> wallpaperPages = fetchWallpaperPages(query, count);
System.out.println(GREEN + " ✔ Found " + wallpaperPages.size() + " pages" + RESET);
System.out.println();
printDivider();
System.out.println(MAGENTA + BOLD + " [ DOWNLOADING ×" + threads + " virtual threads ]" + RESET);
printDivider();
System.out.println();
List<Future<?>> futures = new ArrayList<>();
try (ExecutorService pool = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < wallpaperPages.size(); i++) {
final String page = wallpaperPages.get(i);
final int slot = i + 1;
futures.add(pool.submit(() -> {
try {
String imageUrl = getImageUrl(page);
if (imageUrl == null) {
failed.incrementAndGet();
printStatus(RED, "✘", slot, "No image found on " + page);
return;
}
String ext = imageUrl.substring(imageUrl.lastIndexOf('.'));
Path dest = downloadDir.resolve("wallpaper_" + slot + ext);
downloadImage(imageUrl, dest);
int n = downloaded.incrementAndGet();
printProgress(n, count, imageUrl);
} catch (Exception e) {
failed.incrementAndGet();
printStatus(RED, "✘", slot, "Failed: " + page);
}
}));
}
}
Duration elapsed = Duration.between(start, Instant.now());
System.out.println();
printDivider();
printSummary(downloaded.get(), failed.get(), elapsed, downloadDir);
printDivider();
}
private static List<String> fetchWallpaperPages(String query, int count) throws Exception {
var pages = new CopyOnWriteArrayList<String>();
int page = 1;
var pattern = Pattern.compile("href=\"(https://wallhaven\\.cc/w/[a-zA-Z0-9]+)\"");
while (pages.size() < count) {
String url = "https://wallhaven.cc/search?q=" + query.replace(" ", "%20") + "&page=" + page;
String html = fetch(url);
Matcher m = pattern.matcher(html);
while (m.find()) {
String wp = m.group(1);
if (!pages.contains(wp)) pages.add(wp);
if (pages.size() >= count) break;
}
if (!m.reset().find()) break;
page++;
}
return pages.subList(0, Math.min(pages.size(), count));
}
private static String getImageUrl(String wallpaperPage) throws Exception {
String html = fetch(wallpaperPage);
var pattern = Pattern.compile("<img[^>]*id=\"wallpaper\"[^>]*src=\"([^\"]+)\"");
Matcher m = pattern.matcher(html);
return m.find() ? m.group(1) : null;
}
private static String fetch(String url) throws Exception {
var conn = (HttpURLConnection) URI.create(url).toURL().openConnection();
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setConnectTimeout(12_000);
conn.setReadTimeout(20_000);
try (InputStream in = conn.getInputStream()) {
return new String(in.readAllBytes());
}
}
private static void downloadImage(String imageUrl, Path dest) throws IOException {
var conn = (HttpURLConnection) URI.create(imageUrl).toURL().openConnection();
conn.setRequestProperty("User-Agent", USER_AGENT);
conn.setConnectTimeout(12_000);
conn.setReadTimeout(60_000);
try (InputStream in = conn.getInputStream()) {
Files.copy(in, dest, StandardCopyOption.REPLACE_EXISTING);
}
}
private static void printBanner() {
System.out.println();
System.out.println(CYAN + BOLD +
" ██╗ ██╗ █████╗ ██╗ ██╗ " + RESET);
System.out.println(CYAN + BOLD +
" ██║ ██║██╔══██╗██║ ██║ " + RESET);
System.out.println(CYAN + BOLD +
" ██║ █╗ ██║███████║██║ ██║ " + RESET);
System.out.println(CYAN + BOLD +
" ██║███╗██║██╔══██║██║ ██║ " + RESET);
System.out.println(CYAN + BOLD +
" ╚███╔███╔╝██║ ██║███████╗███████╗" + RESET);
System.out.println(CYAN + BOLD +
" ╚══╝╚══╝ ╚═╝ ╚═╝╚══════╝╚══════╝" + RESET);
System.out.println();
System.out.println(MAGENTA + " WALLHAVEN DOWNLOADER " + DIM + "Created By OMEE-Y" + RESET);
System.out.println();
printDivider();
System.out.println();
}
private static void printDivider() {
System.out.println(DIM + " " + "─".repeat(52) + RESET);
}
private static synchronized void printProgress(int done, int total, String url) {
int barWidth = 20;
int filled = (int) ((done / (double) total) * barWidth);
String bar = "█".repeat(filled) + "░".repeat(barWidth - filled);
String pct = String.format("%3d%%", (int) ((done / (double) total) * 100));
String filename = url.substring(url.lastIndexOf('/') + 1);
System.out.printf(" %s%s%s %s[%s/%s]%s %s%s%s%n",
GREEN, bar, RESET,
DIM, done, total, RESET,
YELLOW, filename, RESET);
}
private static synchronized void printStatus(String colour, String icon, int slot, String msg) {
System.out.printf(" %s%s%s [%d] %s%n", colour, icon, RESET, slot, msg);
}
private static void printSummary(int ok, int fail, Duration elapsed, Path dir) {
double secs = elapsed.toMillis() / 1000.0;
System.out.println();
System.out.printf(" %s%s✔ %d downloaded%s %s✘ %d failed%s %s⏱ %.1fs%s%n",
BOLD, GREEN, ok, RESET,
RED, fail, RESET,
DIM, secs, RESET);
System.out.println();
System.out.println(DIM + " Saved to → " + dir + RESET);
System.out.println();
}
}