LibImgDown

WEBのダウンロードライブラリ

As of 2025-03-06. See the latest version.

This script should not be not be installed directly. It is a library for other scripts to include with the meta directive // @require https://update.greatest.deepsurf.us/scripts/528949/1548368/LibImgDown.js

  1. /*
  2. * Dependencies:
  3.  
  4. * GM_info(optional)
  5. * Docs: https://violentmonkey.github.io/api/gm/#gm_info
  6.  
  7. * GM_xmlhttpRequest(optional)
  8. * Docs: https://violentmonkey.github.io/api/gm/#gm_xmlhttprequest
  9.  
  10. * JSZIP
  11. * Github: https://github.com/Stuk/jszip
  12. * CDN: https://unpkg.com/jszip@3.7.1/dist/jszip.min.js
  13.  
  14. * FileSaver
  15. * Github: https://github.com/eligrey/FileSaver.js
  16. * CDN: https://unpkg.com/file-saver@2.0.5/dist/FileSaver.min.js
  17. */
  18.  
  19. ;const ImageDownloader = (({ JSZip, saveAs }) => {
  20. let maxNum = 0;
  21. let promiseCount = 0;
  22. let fulfillCount = 0;
  23. let isErrorOccurred = false;
  24. let createFolder = false;
  25. let folderName = "images";
  26. let zipFileName = "download.zip";
  27.  
  28. // elements
  29. let startNumInputElement = null;
  30. let endNumInputElement = null;
  31. let downloadButtonElement = null;
  32. let panelElement = null;
  33. let folderRadioYes = null;
  34. let folderRadioNo = null;
  35. let folderNameInput = null;
  36. let zipFileNameInput = null;
  37.  
  38. // svg icons
  39. const externalLinkSVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="currentcolor" width="16" height="16"><path fill-rule="evenodd" d="M10.604 1h4.146a.25.25 0 01.25.25v4.146a.25.25 0 01-.427.177L13.03 4.03 9.28 7.78a.75.75 0 01-1.06-1.06l3.75-3.75-1.543-1.543A.25.25 0 0110.604 1zM3.75 2A1.75 1.75 0 002 3.75v8.5c0 .966.784 1.75 1.75 1.75h8.5A1.75 1.75 0 0014 12.25v-3.5a.75.75 0 00-1.5 0v3.5a.25.25 0 01-.25.25h-8.5a.25.25 0 01-.25-.25v-8.5a.25.25 0 01.25-.25h3.5a.75.75 0 000-1.5h-3.5z"></path></svg>`;
  40. const reloadSVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="currentcolor" width="16" height="16"><path fill-rule="evenodd" d="M8 2.5a5.487 5.487 0 00-4.131 1.869l1.204 1.204A.25.25 0 014.896 6H1.25A.25.25 0 011 5.75V2.104a.25.25 0 01.427-.177l1.38 1.38A7.001 7.001 0 0114.95 7.16a.75.75 0 11-1.49.178A5.501 5.501 0 008 2.5zM1.705 8.005a.75.75 0 01.834.656 5.501 5.501 0 009.592 2.97l-1.204-1.204a.25.25 0 01.177-.427h3.646a.25.25 0 01.25.25v3.646a.25.25 0 01-.427.177l-1.38-1.38A7.001 7.001 0 011.05 8.84a.75.75 0 01.656-.834z"></path></svg>`;
  41.  
  42. // initialization
  43. function init({
  44. maxImageAmount,
  45. getImagePromises,
  46. title = `package_${Date.now()}`,
  47. imageSuffix = 'jpg',
  48. zipOptions = {},
  49. positionOptions = {}
  50. }) {
  51. // assign value
  52. maxNum = maxImageAmount;
  53.  
  54. // setup UI
  55. setupUI(positionOptions, title);
  56.  
  57. // setup update notification
  58. setupUpdateNotification();
  59.  
  60. // add click event listener to download button
  61. downloadButtonElement.onclick = function () {
  62. if (!isOKToDownload()) return;
  63.  
  64. this.disabled = true;
  65. this.textContent = "Processing";
  66. this.style.backgroundColor = '#aaa';
  67. this.style.cursor = 'not-allowed';
  68. download(getImagePromises, title, imageSuffix, zipOptions);
  69. };
  70. }
  71.  
  72.  
  73. // setup UI
  74. function setupUI(positionOptions, title) {
  75. // common input element style
  76. const inputElementStyle = `
  77. box-sizing: content-box;
  78. padding: 0px 0px;
  79. width: 40%;
  80. height: 26px;
  81. border: 1px solid #aaa;
  82. border-radius: 4px;
  83. font-family: 'Consolas', 'Monaco', 'Microsoft YaHei';
  84. text-align: center;
  85. `;
  86.  
  87. // create start number input element
  88. startNumInputElement = document.createElement('input');
  89. startNumInputElement.id = 'ImageDownloader-StartNumInput';
  90. startNumInputElement.style = inputElementStyle;
  91. startNumInputElement.type = 'text';
  92. startNumInputElement.value = 1;
  93.  
  94. // create end number input element
  95. endNumInputElement = document.createElement('input');
  96. endNumInputElement.id = 'ImageDownloader-EndNumInput';
  97. endNumInputElement.style = inputElementStyle;
  98. endNumInputElement.type = 'text';
  99. endNumInputElement.value = maxNum;
  100.  
  101. // prevent keyboard input from being blocked
  102. startNumInputElement.onkeydown = (e) => e.stopPropagation();
  103. endNumInputElement.onkeydown = (e) => e.stopPropagation();
  104.  
  105. // create 'to' span element
  106. const toSpanElement = document.createElement('span');
  107. toSpanElement.id = 'ImageDownloader-ToSpan';
  108. toSpanElement.textContent = 'to';
  109. toSpanElement.style = `
  110. margin: 0 6px;
  111. color: black;
  112. line-height: 1;
  113. word-break: keep-all;
  114. user-select: none;
  115. `;
  116.  
  117. // create download button element
  118. downloadButtonElement = document.createElement('button');
  119. downloadButtonElement.id = 'ImageDownloader-DownloadButton';
  120. downloadButtonElement.textContent = 'Download';
  121. downloadButtonElement.style = `
  122. margin-top: 8px;
  123. margin-left: auto; // 追加
  124. width: 128px;
  125. height: 48px;
  126. display: block;
  127. justify-content: center;
  128. align-items: center;
  129. font-size: 14px;
  130. font-family: 'Consolas', 'Monaco', 'Microsoft YaHei';
  131. color: #fff;
  132. line-height: 1.2;
  133. background-color: #0984e3;
  134. border: none;
  135. border-radius: 4px;
  136. cursor: pointer;
  137. `;
  138.  
  139. const toggleButton = document.createElement('button');
  140. toggleButton.id = 'ImageDownloader-ToggleButton';
  141. toggleButton.textContent = 'UI CLOSE';
  142. toggleButton.style = `
  143. position: fixed;
  144. top: 45px;
  145. left: 5px;
  146. z-index: 999999999;
  147. padding: 2px 5px;
  148. font-size: 14px;
  149. font-weight: 'bold';
  150. font-family: 'Monaco', 'Microsoft YaHei';
  151. color: #fff;
  152. background-color: #0984e3;
  153. border: 1px solid #aaa;
  154. border-radius: 4px;
  155. cursor: pointer;
  156. `;
  157. document.body.appendChild(toggleButton);
  158.  
  159. let isUIVisible = true;
  160.  
  161. function toggleUI() {
  162. if (isUIVisible) {
  163. panelElement.style.display = 'none';
  164. toggleButton.textContent = 'UI OPEN';
  165. } else {
  166. panelElement.style.display = 'flex';
  167. toggleButton.textContent = 'UI CLOSE';
  168. }
  169. isUIVisible = !isUIVisible;
  170. }
  171.  
  172. toggleButton.addEventListener('click', toggleUI)
  173.  
  174. // create range input container element
  175. const rangeInputContainerElement = document.createElement('div');
  176. rangeInputContainerElement.id = 'ImageDownloader-RangeInputContainer';
  177. rangeInputContainerElement.style = `
  178. display: flex;
  179. justify-content: center;
  180. align-items: baseline;
  181. `;
  182.  
  183. // create range input container element
  184. const rangeInputRadioElement = document.createElement('div');
  185. rangeInputRadioElement.id = 'ImageDownloader-RadioChecker';
  186. rangeInputRadioElement.style = `
  187. display: flex;
  188. justify-content: center;
  189. align-items: baseline;
  190. `;
  191.  
  192. // create panel element
  193. panelElement = document.createElement('div');
  194. panelElement.id = 'ImageDownloader-Panel';
  195. panelElement.style = `
  196. position: fixed;
  197. top: 80px;
  198. left: 5px;
  199. z-index: 999999999;
  200. box-sizing: border-box;
  201. padding: 0px;
  202. width: auto;
  203. min-width: 200px;
  204. max-width: 300px;
  205. height: auto;
  206. display: flex;
  207. flex-direction: column;
  208. justify-content: center;
  209. align-items: baseline;
  210. font-size: 12px;
  211. font-family: 'Consolas', 'Monaco', 'Microsoft YaHei';
  212. letter-spacing: normal;
  213. background-color: #f1f1f1;
  214. border: 1px solid #aaa;
  215. border-radius: 4px;
  216. `;
  217.  
  218. // modify panel position according to 'positionOptions'
  219. for (const [key, value] of Object.entries(positionOptions)) {
  220. if (key === 'top' || key === 'bottom' || key === 'left' || key === 'right') {
  221. panelElement.style[key] = value;
  222. }
  223. }
  224.  
  225. // create folder radio buttons
  226. folderRadioYes = document.createElement('input');
  227. folderRadioYes.type = 'radio';
  228. folderRadioYes.name = 'createFolder';
  229. folderRadioYes.value = 'yes';
  230. folderRadioYes.id = 'createFolderYes';
  231.  
  232. folderRadioNo = document.createElement('input');
  233. folderRadioNo.type = 'radio';
  234. folderRadioNo.name = 'createFolder';
  235. folderRadioNo.value = 'no';
  236. folderRadioNo.id = 'createFolderNo';
  237. folderRadioNo.checked = true;
  238.  
  239. // フォルダ名入力欄の作成
  240. folderNameInput = document.createElement('textarea');
  241. folderNameInput.id = 'folderNameInput';
  242. folderNameInput.value = title; // titleを初期値として使用
  243. folderNameInput.disabled = true;
  244. folderNameInput.style = `
  245. ${inputElementStyle}
  246. resize: vertical;
  247. height: auto;
  248. width: 99%;
  249. min-height: 45px;
  250. max-height: 200px;
  251. padding: 0px 0px;
  252. border: 1px solid #aaa;
  253. border-radius: 1px;
  254. font-size: 11px;
  255. font-family: 'Consolas', 'Monaco', 'Microsoft YaHei';
  256. text-align: left;
  257. `;
  258.  
  259. // ZIPファイル名入力欄の作成
  260. zipFileNameInput = document.createElement('textarea');
  261. zipFileNameInput.id = 'zipFileNameInput';
  262. zipFileNameInput.value = `${title}.zip`; // titleを使用してZIPファイル名を設定
  263. zipFileNameInput.style = `
  264. ${inputElementStyle}
  265. resize: vertical;
  266. height: auto;
  267. width: 99%;
  268. min-height: 45px;
  269. max-height: 200px;
  270. padding: 0px 0px;
  271. border: 1px solid #aaa;
  272. border-radius: 1px;
  273. font-size: 11px;
  274. font-family: 'Consolas', 'Monaco', 'Microsoft YaHei';
  275. text-align: left;
  276. `;
  277.  
  278. // add event listeners for radio buttons
  279. folderRadioYes.addEventListener('change', () => {
  280. createFolder = true;
  281. folderNameInput.disabled = false;
  282. });
  283.  
  284. folderRadioNo.addEventListener('change', () => {
  285. createFolder = false;
  286. folderNameInput.disabled = true;
  287. });
  288.  
  289. // assemble and then insert into document
  290. rangeInputContainerElement.appendChild(startNumInputElement);
  291. rangeInputContainerElement.appendChild(toSpanElement);
  292. rangeInputContainerElement.appendChild(endNumInputElement);
  293. panelElement.appendChild(rangeInputContainerElement);
  294. rangeInputRadioElement.appendChild(document.createTextNode('フォルダ:'));
  295. rangeInputRadioElement.appendChild(folderRadioYes);
  296. rangeInputRadioElement.appendChild(document.createTextNode('作成 '));
  297. rangeInputRadioElement.appendChild(folderRadioNo);
  298. rangeInputRadioElement.appendChild(document.createTextNode('不要'));
  299. panelElement.appendChild(rangeInputRadioElement);
  300. panelElement.appendChild(document.createTextNode('フォルダ名: '));
  301. panelElement.appendChild(folderNameInput);
  302. panelElement.appendChild(document.createElement('br'));
  303. panelElement.appendChild(document.createTextNode('ZIPファイル名: '));
  304. panelElement.appendChild(zipFileNameInput);
  305. panelElement.appendChild(document.createElement('br'));
  306. panelElement.appendChild(downloadButtonElement);
  307. document.body.appendChild(panelElement);
  308. }
  309.  
  310. // setup update notification
  311. async function setupUpdateNotification() {
  312. if (typeof GM_info === 'undefined' || typeof GM_xmlhttpRequest === 'undefined') return;
  313.  
  314. // get local version
  315. const localVersion = Number(GM_info.script.version);
  316.  
  317. // get latest version
  318. const scriptID = (GM_info.script.homepageURL || GM_info.script.homepage).match(/scripts\/(?<id>\d+)-/)?.groups?.id;
  319. const scriptURL = `https://update.greatest.deepsurf.us/scripts/${scriptID}/raw.js`;
  320. const latestVersionString = await new Promise(resolve => {
  321. GM_xmlhttpRequest({
  322. method: 'GET',
  323. url: scriptURL,
  324. responseType: 'text',
  325. onload: res => resolve(res.response.match(/@version\s+(?<version>[0-9\.]+)/)?.groups?.version)
  326. });
  327. });
  328. const latestVersion = Number(latestVersionString);
  329.  
  330. if (Number.isNaN(localVersion) || Number.isNaN(latestVersion)) return;
  331. if (latestVersion <= localVersion) return;
  332.  
  333. // show update notification
  334. const updateLinkElement = document.createElement('a');
  335. updateLinkElement.id = 'ImageDownloader-UpdateLink';
  336. updateLinkElement.href = scriptURL.replace('raw.js', 'raw.user.js');
  337. updateLinkElement.innerHTML = `Update to V${latestVersionString}${externalLinkSVG}`;
  338. updateLinkElement.style = `
  339. position: absolute;
  340. bottom: -38px;
  341. left: -1px;
  342.  
  343. display: flex;
  344. justify-content: space-around;
  345. align-items: center;
  346.  
  347. box-sizing: border-box;
  348. padding: 8px;
  349. width: 146px;
  350. height: 32px;
  351.  
  352. font-size: 14px;
  353. font-family: 'Consolas', 'Monaco', 'Microsoft YaHei';
  354. text-decoration: none;
  355. color: white;
  356.  
  357. background-color: #32CD32;
  358. border-radius: 4px;
  359. `;
  360. updateLinkElement.onclick = () => setTimeout(() => {
  361. updateLinkElement.removeAttribute('href');
  362. updateLinkElement.innerHTML = `Please Reload${reloadSVG}`;
  363. updateLinkElement.style.cursor = 'default';
  364. }, 1000);
  365.  
  366. panelElement.appendChild(updateLinkElement);
  367. }
  368.  
  369. // check validity of page nums from input
  370. function isOKToDownload() {
  371. const startNum = Number(startNumInputElement.value);
  372. const endNum = Number(endNumInputElement.value);
  373.  
  374. if (Number.isNaN(startNum) || Number.isNaN(endNum)) { alert("请正确输入数值\nPlease enter page number correctly."); return false; }
  375. if (!Number.isInteger(startNum) || !Number.isInteger(endNum)) { alert("请正确输入数值\nPlease enter page number correctly."); return false; }
  376. if (startNum < 1 || endNum < 1) { alert("页码的值不能小于1\nPage number should not smaller than 1."); return false; }
  377. if (startNum > maxNum || endNum > maxNum) { alert(`页码的值不能大于${maxNum}\nPage number should not bigger than ${maxNum}.`); return false; }
  378. if (startNum > endNum) { alert("起始页码的值不能大于终止页码的值\nNumber of start should not bigger than number of end."); return false; }
  379.  
  380. return true;
  381. }
  382.  
  383. // start downloading
  384. async function download(getImagePromises, title, imageSuffix, zipOptions) {
  385. const startNum = Number(startNumInputElement.value);
  386. const endNum = Number(endNumInputElement.value);
  387. promiseCount = endNum - startNum + 1;
  388. // start downloading images, max amount of concurrent requests is limited to 4
  389. let images = [];
  390. for (let num = startNum; num <= endNum; num += 4) {
  391. const from = num;
  392. const to = Math.min(num + 3, endNum);
  393. try {
  394. const result = await Promise.all(getImagePromises(from, to));
  395. images = images.concat(result);
  396. } catch (error) {
  397. return; // cancel downloading
  398. }
  399. }
  400.  
  401. // configure file structure of zip archive
  402. JSZip.defaults.date = new Date(Date.now() - (new Date()).getTimezoneOffset() * 60000);
  403. const zip = new JSZip();
  404. folderName = folderNameInput.value;
  405. zipFileName = zipFileNameInput.value;
  406.  
  407. folderName = folderName.trim()
  408. folderName = folderName.replace(/[A-Za-z0-9]/g, function(s) {
  409. return String.fromCharCode(s.charCodeAt(0) - 0xFEE0);
  410. });
  411. folderName = folderName.replace(/ /g, ' ');
  412. folderName = folderName.replace(/[!?][!?]/g, '⁉');
  413. folderName = folderName.replace(/[!#$%&()+*]/g, function(s) {
  414. return '!#$%&()+*'['!#$%&()+*'.indexOf(s)];
  415. });
  416. folderName = folderName.replace(/[\\/:*?"<>|]/g, '-');
  417.  
  418. zipFileName = zipFileName.trim()
  419. zipFileName = zipFileName.replace(/[A-Za-z0-9]/g, function(s) {
  420. return String.fromCharCode(s.charCodeAt(0) - 0xFEE0);
  421. });
  422. zipFileName = zipFileName.replace(/ /g, ' ');
  423. zipFileName = zipFileName.replace(/[!?][!?]/g, '⁉');
  424. zipFileName = zipFileName.replace(/[!#$%&()+*]/g, function(s) {
  425. return '!#$%&()+*'['!#$%&()+*'.indexOf(s)];
  426. });
  427. zipFileName = zipFileName.replace(/[\\/:*?"<>|]/g, '-');
  428.  
  429. if (createFolder) {
  430. const folder = zip.folder(folderName);
  431. for (const [index, image] of images.entries()) {
  432. const filename = `${String(index + 1).padStart(images.length >= 100 ? String(images.length).length : 2, '0')}.${imageSuffix}`;
  433. folder.file(filename, image, zipOptions);
  434. }
  435. } else {
  436. for (const [index, image] of images.entries()) {
  437. const filename = `${String(index + 1).padStart(images.length >= 100 ? String(images.length).length : 2, '0')}.${imageSuffix}`;
  438. zip.file(filename, image, zipOptions);
  439. }
  440. }
  441.  
  442. // start zipping & show progress
  443. const zipProgressHandler = (metadata) => { downloadButtonElement.innerHTML = `Zipping(${metadata.percent.toFixed()}%)`; };
  444. const content = await zip.generateAsync({ type: "blob" }, zipProgressHandler);
  445. // open 'Save As' window to save
  446. saveAs(content, zipFileName);
  447. // 全て完了
  448. downloadButtonElement.textContent = "Completed";
  449.  
  450. // ボタンを再度押せるようにする
  451. downloadButtonElement.disabled = false;
  452. downloadButtonElement.style.backgroundColor = '#0984e3';
  453. downloadButtonElement.style.cursor = 'pointer';
  454. }
  455.  
  456. // handle promise fulfilled
  457. function fulfillHandler(res) {
  458. if (!isErrorOccurred) {
  459. fulfillCount++;
  460. downloadButtonElement.innerHTML = `Processing(${fulfillCount}/${promiseCount})`;
  461. }
  462. return res;
  463. }
  464.  
  465. // handle promise rejected
  466. function rejectHandler(err) {
  467. isErrorOccurred = true;
  468. console.error(err);
  469. downloadButtonElement.textContent = 'Error Occurred';
  470. downloadButtonElement.style.backgroundColor = 'red';
  471. return Promise.reject(err);
  472. }
  473.  
  474. return { init, fulfillHandler, rejectHandler };
  475. })(window);