-
Notifications
You must be signed in to change notification settings - Fork 0
/
flickrezdl.user.js
233 lines (208 loc) · 8.51 KB
/
flickrezdl.user.js
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
// ==UserScript==
// @name flickr easy download
// @version 1.0.5
// @description download the highest resolution image on flickr with just one click!
// @author Mjokfox
// @updateURL https://github.com/Mjokfox/flickr_easy_dl/raw/main/flickrezdl.user.js
// @license GPLv3
// @match https://www.flickr.com/*
// @match https://flickr.com/*
// @icon https://www.google.com/s2/favicons?sz=64&domain=flickr.com
// @grant none
// @inject-into content
// ==/UserScript==
(function() {
'use strict';
// Function to fetch HTML content
async function fetchHtml(url) {
try {
const response = await fetch(url);
return await response.text();
} catch (error) {
console.error(`Error fetching the HTML page for ${url}: ${error}`);
return null;
}
}
// Function to find the image URL from HTML content
function findImageUrl(html) {
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
const element = doc.querySelector('div#allsizes-photo img'); // child of div.allsizes-photo with type <img>
return element ? element.src : null;
}
// Function to find the largest resolution image URL
async function findLargestResolution(html) {
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
const smallElements = doc.querySelectorAll('small');
let maxResolution = 0;
let largesti = 0;
let maxHref = null;
// instead of doing arithmatic, exploit the standard page layout
if (smallElements[0].textContent == "(75 × 75)") {
largesti = smallElements.length - 1;
} else if (smallElements[1].parentElement.querySelector(':scope > a').innerHTML == "Original"){
largesti = 1;
} else {
largesti = 0;
}
// find the next page url to the largest image
const parent = smallElements[largesti].parentElement;
if (parent) {
const link = parent.querySelector(':scope > a'); // single layer depth
maxHref = link ? link.href : null; // if there is no <a> element, we are already on the largest size page
}
if (smallElements[largesti].textContent == "(All sizes of this photo are available for download under a Creative Commons license)") {
return maxHref // stupid edge case
}
if (maxHref) { // If it's not null, fetch the HTML for the larger image
html = await fetchHtml(maxHref);
return findImageUrl(html);
}
return findImageUrl(html);
}
// download the image
function downloadImage(url) {
fetch(url)
.then(response => response.blob())
.then(blob => {
const burl = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.style.display = 'none';
a.href = burl;
a.download = url.split('/').pop();;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
})
.catch((error) => console.error(`Failed to download image for: ${url}: ${error}`));
}
// remove everything after /in/ because that can sometimes be in the url
function stripAfterIn(url) {
var index = url.indexOf("/in/");
if (index !== -1) {
return url.substring(0, index);
}
return url;
}
// main function
async function downloadLargestFlickrImage(element) {
let pageUrl = "";
if (element.type != "click"){pageUrl = element.parentElement.parentElement.querySelector('a').href;}
else{pageUrl = window.location.href;}
if (!pageUrl){console.error("url not found"); return}
pageUrl = stripAfterIn(pageUrl);
// add "sizes" to the url
if (!pageUrl.includes("sizes")) {
pageUrl += pageUrl.endsWith("/") ? "sizes/" : "/sizes/"
}
const html = await fetchHtml(pageUrl);
if (html) {
const imageUrl = await findLargestResolution(html);
if (imageUrl) {
downloadImage(imageUrl);
} else {
console.error('Failed to find the image URL.');
}
} else {
console.error('Failed to download the HTML page.');
}
}
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function downloadAll(buttonelement) {
buttonelement.disabled = true
const elements = document.querySelectorAll("a.overlay");
for (const element of elements) {
downloadLargestFlickrImage(element)
await delay(500 + Math.floor(Math.random() * 500));
}
buttonelement.disabled = false
}
// Add a global floating button so it can be added and removed without querying
function makeButton(text, clickHandler) {
const button = document.createElement('button');
button.style.position = 'fixed';
button.style.bottom = '10px';
button.style.right = '10px';
button.style.height = "32px";
button.style.fontFamily = "Proxima Nova, helvetica neue, helvetica, arial, sans-serif";
button.style.fontWeight = "600";
button.style.padding = '0px 20px';
button.style.zIndex = '1000';
button.style.backgroundColor = '#1c9be9';
button.style.color = '#FFF';
button.style.border = 'none';
button.style.borderRadius = '5px';
button.style.fontSize = '16px';
button.id = "amogus";
button.innerHTML = text;
button.addEventListener('click', clickHandler);
return button;
}
const buttonSingle = makeButton('Download Image', downloadLargestFlickrImage);
buttonSingle.style.cursor = "pointer"
const buttonAll = makeButton('Download All Images', function() {
downloadAll(buttonAll);
});
function addFloatingButton(){
if (document.getElementById('amogus')){document.body.removeChild(document.getElementById('amogus'));}
if (document.documentElement.classList.contains('html-photo-page-scrappy-view') || window.location.href.includes("sizes")) {
document.body.appendChild(buttonSingle);
} else if (document.documentElement.classList.contains('html-search-photos-unified-page-view')) {
document.body.appendChild(buttonAll);
}
}
// in photostream download button
function addDownloadButton(element) {
if(element.querySelector('a.engagement-item.download')){return} // skip if it already exists
const a = document.createElement('a');
a.className = 'engagement-item download';
a.title = "Download this photo";
const i = document.createElement('i');
i.className = 'ui-icon-download'; // use the page built in icon
a.appendChild(i);
a.addEventListener('click', function() {
a.style.cursor = "wait"
a.style.backgroundColor = "#0a0"
a.style.border = "2px solid white"
downloadLargestFlickrImage(element).then(() => {
a.style.cursor = "inherit";
})
});
element.appendChild(a);
}
// Callback function to execute when mutations are observed
const observerCallback = function(mutationsList, observer) {
for (const mutation of mutationsList) {
if (mutation.type === 'childList') {
for (const node of mutation.addedNodes) {
if (node.nodeType === Node.ELEMENT_NODE && node.matches('div.engagement')) {
addDownloadButton(node);
}
// check descendants
const overlayElements = node.querySelectorAll && node.querySelectorAll('div.engagement');
if (overlayElements) {overlayElements.forEach(addDownloadButton);}
}
}
if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
addFloatingButton()
}
}
};
const style = document.createElement('style');
style.innerHTML = `
#amogus:disabled {
cursor: wait !important;
opacity: 0.6;
}
`;
document.head.appendChild(style);
// Create an observer instance linked to the callback function
const observer = new MutationObserver(observerCallback);
observer.observe(document.body, { childList: true, subtree: true, attributes: true });
// maybe some already exist on load
document.querySelectorAll('div.engagement').forEach(addDownloadButton);
})();