├── LICENSE ├── README.md ├── e-hentai-downloader.meta.js ├── e-hentai-downloader.user.js └── src ├── .jshintrc ├── FileSaver.js ├── JSZip.js ├── build.bat ├── build.sh ├── first.js └── main.js /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # E-Hentai-Downloader 2 | 3 | Download E-Hentai archive as zip file :package: 4 | 5 | 6 | ## Required Environment 7 | 8 | | Browser | [GreaseMonkey](https://www.greasespot.net/) | [Tampermonkey](http://tampermonkey.net/) | [Violentmonkey](https://violentmonkey.github.io/) | 9 | | ------- | ------------ | ------------ | ------------- | 10 | | Firefox (56-) | [3.2 beta2+](https://addons.mozilla.org/firefox/addon/greasemonkey/) | | | 11 | | Firefox (57+) | [4.1 beta5+](https://addons.mozilla.org/firefox/addon/greasemonkey/) | [4.0.5054+](https://addons.mozilla.org/firefox/addon/tampermonkey/) | [2.8.18+](https://addons.mozilla.org/firefox/addon/violentmonkey/) | 12 | | Chrome | | [3.5.3630+](https://chrome.google.com/webstore/detail/dhdgffkkebhmkfjojejmpbldmpobfkfo) | [2.2.6+](https://chrome.google.com/webstore/detail/jinjaccalgkegednnccohejagnlnfdag) | 13 | | Opera (15+) | | [3.5.3630+](https://addons.opera.com/extensions/details/tampermonkey-beta/) | [2.1.10+](https://addons.opera.com/extensions/details/violent-monkey/) | 14 | | Safari (10.1+) (1) | | [4.3.5421+](https://tampermonkey.net/?browser=safari) | 15 | | Edge (18-) (2) | | [4.2.5284+](https://www.microsoft.com/store/p/tampermonkey/9nblggh5162s) | 16 | | Edge (79+) | | [4.10.6111+](https://microsoftedge.microsoft.com/addons/detail/tampermonkey/iikmkjmpaadaobahmlepeloendndfphd) | [2.12.8+](https://microsoftedge.microsoft.com/addons/detail/eeagobfjdenkkddmbclomhiblgggliao) | 17 | | Maxthon | | | [2.1.10+](http://extension.maxthon.cn/detail/index.php?view_id=1680) | 18 | | Yandex Browser for Android (3) | | [4.2.5291+](https://chrome.google.com/webstore/detail/dhdgffkkebhmkfjojejmpbldmpobfkfo/) | [2.2.6+](https://chrome.google.com/webstore/detail/jinjaccalgkegednnccohejagnlnfdag) | 19 | | Kiwi Browser (3) | | [4.11+](https://chrome.google.com/webstore/detail/dhdgffkkebhmkfjojejmpbldmpobfkfo/) | [2.12.8+](https://chrome.google.com/webstore/detail/jinjaccalgkegednnccohejagnlnfdag) | 20 | | Firefox for Android (68-)(3) | Incompatible | Incompatible | [2.12.8+](https://addons.mozilla.org/firefox/addon/violentmonkey/) | 21 | | Firefox Nightly for Android (85+) (3)(4) | Incompatible | [4.11.6120+](https://addons.mozilla.org/firefox/addon/tampermonkey/) | [2.12.8+](https://addons.mozilla.org/firefox/addon/violentmonkey/) | 22 | 23 | > (1) You must upgrade your Windows 10 to 14393 which supports Edge extension. 24 | > (2) You must upgrade your macOS to 10.12.4 which supports `download` attribute of `` tag. 25 | > (3) It's not a good idea to use it on mobile with limited RAM, but it can work, so it's up to you. 26 | > (4) Firefox Nightly user requires to follow [this steps](https://blog.mozilla.org/addons/2020/09/29/expanded-extension-support-in-firefox-for-android-nightly/) to install extensions not in default list. 27 | 28 | 29 | ## Install This Script 30 | 31 | - [Download from GitHub](https://github.com/ccloli/E-Hentai-Downloader/raw/master/e-hentai-downloader.user.js) 32 | - [Download from GreasyFork](https://sleazyfork.org/scripts/10379-e-hentai-downloader) 33 | 34 | 35 | ## How To Use 36 | 37 | 1. Open E-Hentai Gallery 38 | 2. Find your interested gallery 39 | 3. Click "Download Archive" in E-Hentai Downloader box 40 | 4. Have a cup of coffee :coffee: 41 | 5. Save the Zip file 42 | 43 | ![E-Hentai Downloader box](https://cloud.githubusercontent.com/assets/8115912/10636596/56c9073c-7833-11e5-9161-c2c9f1a288a7.png) 44 | 45 | Tips: 46 | * Check "Number Images" to number download images 47 | * Set "Pages Range" to choose pages you want to download 48 | * More personalized options can be found on "Settings" 49 | 50 | 51 | ## How It Works 52 | 53 | This script won't download archive from E-Hentai archive download page, so it won't spend your GPs or credits. It will fetch all the pages of the gallery and get their images' URL. Then script will use `GM_xmlhttpRequest` API (in order to cross origin) to download them. After that, it will package them to a Zip file with [JSZip](https://github.com/Stuk/jszip) and give it to you with [FileSaver.js](https://github.com/eligrey/FileSaver.js). 54 | 55 | 56 | ## Should Be Noticed 57 | 58 | - The script is NOT provided by the offical, and using automated scripts/tools is NOT encouraged and may trigger throttle limit or even account ban, DON'T BOTHER ANYONE IN SITE FORUMS FOR ANY SCRIPT-RELATED ISSUE, AND USE AT YOUR OWN RISK. 59 | If you're downloading a large gallery, please consider using torrents if available, or using offical archiver for better and stable experience, and the cost should be closed to using script when the gallery is old enough to use GPs. 60 | For the detail rules, see [E-Hentai Image Viewing Limits](https://github.com/ccloli/E-Hentai-Downloader/wiki/E%E2%88%92Hentai-Image-Viewing-Limits). 61 | - If you see a message about out of memory on Firefox, or file not found on Chrome, [see solution here](https://github.com/ccloli/E-Hentai-Downloader/wiki/Can't-make-Zip-file-successfully). 62 | In short, use Pages Range to limit each zip file under 500 MB is recommended, and enable File System if you're using Chrome, or upgrade your PC with more RAM. 63 | However there're some hard limits, like 2 GB Blob Object limit on browser, and 4 GB size limit on ZIP itself. For such cases (and stability) please try other tools like [gallery-dl](https://github.com/mikf/gallery-dl). 64 | - You can also have a look at [E-Hentai Image Viewing Limits](https://github.com/ccloli/E-Hentai-Downloader/wiki/E%E2%88%92Hentai-Image-Viewing-Limits). 65 | - Most of galleries may have torrents to download. You can download archive with torrent to get stable download experience, get bonus content (most in cosplay gallery), earn GP and credit, and reduce the pressure of E-Hentai original servers (though it's a P2P site). 66 | 67 | Here are some other compatible information (and some of them are backed to around 10 years ago), which is not important. 68 | 69 | - ~~Tampermonkey uses a dirty way to give `GM_xhr.response` content (transfers `String` to `ArrayBuffer` everytime), so it'll stuck for 1~3 seconds or more after downloaded image (depend on your device). If you are using Microsoft Edge, you may often see the working tab is stuck, saying it's not responding. Just let it go and do nothing. And if you are using Firefox, it's better to use GreaseMonkey from this side~~. 70 | The freeze problem should be fixed in Tampermonkey [4.12.6125](https://github.com/Tampermonkey/tampermonkey/issues/279). 71 | - ~~If you are using the latest Tampermonkey, or receive a warning of _"A userscript wants to access a cross-origin resource"_ from Tampermonkey, please **Allow All** or turn off "@connect mode" at setting page. For more info, [see details here](https://github.com/ccloli/E-Hentai-Downloader/wiki/Cross-origin-request-warning-from-Tampermonkey)~~. 72 | E-Hentai now uses `hath.network` domain to access images, and it's now listed in `@connect`, so you're not needed to set this with latest Tampermonkey. 73 | - ~~ViolentMonkey doesn't support timeout, final URL and download progress.~~ 74 | The latest ViolentMonkey supports these features now. 75 | - ~~Single-thread download mode is removed in 1.18, if you need it, roll back to [old version](https://github.com/ccloli/E-Hentai-Downloader/releases/tag/v1.17.4).~~ 76 | Don't use an old version, it doesn't support current site. 77 | - Dolphin Browser (Android) doesn't support blob URL, so this script cannot be run in Tampermonkey for Dolphin probably. 78 | - UC Browser (Android) doesn't support blob constructor, so this script cannot be run in Tampermonkey for UC probably. 79 | - Opera 12- doesn't support blob URL, and if generated as data URL, it may crash, so it's not supported. 80 | - TrixIE (for IE) is too old and its `GM_xhr` cannot handle large content, so it's not supported. 81 | 82 | 83 | ## Warning And Limitation 84 | 85 | ### Memory Usage 86 | 87 | The script will store **ALL** the data in RAM, not in HDD. This will increase the memory usage of current tab process. So if you don't have enough RAM, or the archive is too large (see [file size limit section](#file-size-limit)), please pay attention to your memory usage, or try other download tools. 88 | 89 | "Out of memory" problem is **the most limitaion** of the script (in fact, all the sections of "Warning And Limitation" are about RAM problem, and here is also a specific [out of memory](https://github.com/ccloli/E-Hentai-Downloader/issues?utf8=%E2%9C%93&q=label%3A%22out+of+memory%22+) tag to label all related issues). If you get an error like out of memory, [see solution here](https://github.com/ccloli/E-Hentai-Downloader/wiki/Can't-make-Zip-file-successfully). And if you usually have the problem, try other tools. 90 | 91 | ### Browser Developer Tools 92 | 93 | To help us debug, the script will output some logs into console (F12 -> Console). If you find a bug, you can keep opening devtools to see and copy the logs. But note that it may increase memory usage and reduce running efficiency. So don't open console only if you want to see the output logs. 94 | 95 | ### File Size Limit 96 | 97 | _(This part is a bit long, you can just read the table)_ 98 | 99 | Different browsers have different maximum file size limits. Here is a table to show the maximum size the supported browser can handle. 100 | 101 | | Browser | Maximum Size | 102 | | ---------------------------- | ----------------------------- | 103 | | Chrome 56- | 500 MB | 104 | | Chrome 57+ | 2 GB or (total RAM / 5) | 105 | | Chrome (with File System) | 1 GB / > 2GB (with 1.33+) | 106 | | Firefox | 2 GB | 107 | | Opera 15+ | Same as Chrome | 108 | | Edge 18- | ? | 109 | | Edge 79+ | Same as Chrome | 110 | | Safari 10.1+ | ? | 111 | | Maxthon | ? | 112 | 113 | For **Google Chrome 56-**, it has a hard limit at **500 MB** on **Blob Storage** for years. That means all the files that in storage cannot be larger than 500MB in total, and if the storage doesn't have enough free space to save the next file, it'll return a **fake** Blob instance silently **without any errors**. Also for Chrome 45-, `Blob.close()` didn't implement (and it's depreated so no browser supports it now), so we cannot free those used Blob immediately at that time, only to pary the browser will GC them ASAP (and for most of time it didn't work). That's why here is [a wiki page](https://github.com/ccloli/E-Hentai-Downloader/wiki/Can't-make-Zip-file-successfully) to help you work around this. 114 | 115 | So to help you save larger files, the script can save the Zip file into **File System**, a deprecated HTML5 API but still works on Chrome (as it's Chrome introduce the standard first). With the API, you can handle larger file because the file data will be writing to your disk instead of storing in Blob Storage, its limit is also big enough (10% of your disk free storage, 15 GB in maximum). But when processing the file, the files are still keeping in RAM, and if datas are too large, Chrome may also cannot handle them. From my test the maximum limit maybe **1 GB** if you only have 8 GB RAM, but it may also depends on your device. If you have enough RAM, you can download a gallery larger than **2 GB** with 1.33+. 116 | 117 | **Chrome 57+** [fixes the 500 MB limit of Blob Storage](https://bugs.chromium.org/p/chromium/issues/detail?id=375297#c107), so that it can handler larger files in RAM just like File System. Its quota is still exist but it's larger, which bases on the limits below, and [here are some examples](https://stackoverflow.com/a/43816041) to make it more clear: 118 | 119 | > In-memory quota: 120 | > * `2GB` if system is x64 and NOT ChromeOS or Android 121 | > * `Total RAM amount / 5`; 122 | > 123 | > Disk quota: 124 | > * `Disk size / 2` if ChromeOS (user partition disk size) 125 | > * `Disk size / 20` if Android 126 | > * `Disk size / 10` otherwise. 127 | > 128 | > Also, if disk is almost full, we try to keep at least `(in-memory quota)*2` disk space available, and we limit the disk quota accordingly. 129 | 130 | For **Firefox**, from our previous data from [FileSaver.js](https://github.com/eligrey/FileSaver.js), the limit is 800 MB. But from our tests, you can save the file that larger than 800 MB. So we think the limit of Firefox is depending on your device, as it stores the Blob in RAM. If you have a larger RAM, you can save a larger file. However, you should care about your RAM usage, as if Firefox cannot get more RAM to generate Zip, it'll throw an "out of memory" error. To give you some advice, no more than 200 MB if you're using 4 GB RAM, and be care for more than 800 MB if you're using 8 GB RAM. 131 | 132 | **Opera 15+** is a Chromium-based browser, so you can check its Chromium version and compare it to Chrome version to get your limit. All the other Chromium-based browsers can also use this rule. 133 | 134 | **Safari 10.1+** finally supports `download` attribute on `` tag, so you can now make it works on Safari. We don't have too much data about Safari Blob limit, so if you're dealing with Safari, be care about your RAM usage. 135 | 136 | 137 | ## Todo List 138 | 139 | [See plans and progress here](https://github.com/ccloli/E-Hentai-Downloader/wiki/Todo-List), notice that some of them may changed or removed in some time. 140 | 141 | 142 | ## Report A Bug 143 | 144 | You can report a bug or give suggestions at [GitHub Issue](https://github.com/ccloli/E-Hentai-Downloader/issues) or [GreasyFork Feedback](https://sleazyfork.org/scripts/10379-e-hentai-downloader/feedback). English and Chinese are acceptable :stuck_out_tongue_closed_eyes: 145 | 146 | English is not my mother tounge, so if you found any mistakes, don't hesitate to [let me know](https://github.com/ccloli/E-Hentai-Downloader/issues/24) =ω= 147 | 148 | Sorry my code is a bit untidy, so it may hard for your development. I'll try optimizing it in a further time :sweat_smile: -------------------------------------------------------------------------------- /e-hentai-downloader.meta.js: -------------------------------------------------------------------------------- 1 | // ==UserScript== 2 | // @name E-Hentai Downloader 3 | // @version 1.35.4 4 | // @description Download E-Hentai archive as zip file 5 | // @author 864907600cc 6 | // @icon https://secure.gravatar.com/avatar/147834caf9ccb0a66b2505c753747867 7 | // @include http://exhentai.org/g/* 8 | // @include http://e-hentai.org/g/* 9 | // @include http://g.e-hentai.org/g/* 10 | // @include http://r.e-hentai.org/g/* 11 | // @include http://exhentai55ld2wyap5juskbm67czulomrouspdacjamjeloj7ugjbsad.onion/g/* 12 | // @include https://exhentai.org/g/* 13 | // @include https://e-hentai.org/g/* 14 | // @include https://g.e-hentai.org/g/* 15 | // @include https://r.e-hentai.org/g/* 16 | // @namespace http://ext.ccloli.com 17 | // @updateURL https://github.com/ccloli/E-Hentai-Downloader/raw/master/e-hentai-downloader.meta.js 18 | // @downloadURL https://github.com/ccloli/E-Hentai-Downloader/raw/master/e-hentai-downloader.user.js 19 | // @supportURL https://github.com/ccloli/E-Hentai-Downloader/issues 20 | // @connect e-hentai.org 21 | // @connect exhentai.org 22 | // @connect exhentai55ld2wyap5juskbm67czulomrouspdacjamjeloj7ugjbsad.onion 23 | // @connect hath.network 24 | // @connect * 25 | // @grant GM_getValue 26 | // @grant GM_setValue 27 | // @grant GM_xmlhttpRequest 28 | // @grant GM_info 29 | // @grant GM.getValue 30 | // @grant GM.setValue 31 | // @grant GM.xmlHttpRequest 32 | // @grant GM.info 33 | // ==/UserScript== 34 | -------------------------------------------------------------------------------- /src/.jshintrc: -------------------------------------------------------------------------------- 1 | { 2 | "multistr": true, 3 | "sub": true, 4 | "loopfunc": true 5 | } -------------------------------------------------------------------------------- /src/FileSaver.js: -------------------------------------------------------------------------------- 1 | /* FileSaver.js 2 | * A saveAs() FileSaver implementation. 3 | * 1.1.20160328 4 | * 5 | * By Eli Grey, http://eligrey.com 6 | * License: MIT 7 | * See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md 8 | */ 9 | 10 | /*global self */ 11 | /*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */ 12 | 13 | /*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */ 14 | 15 | var saveAs = saveAs || (function(view) { 16 | "use strict"; 17 | // IE <10 is explicitly unsupported 18 | if (typeof navigator !== "undefined" && /MSIE [1-9]\./.test(navigator.userAgent)) { 19 | return; 20 | } 21 | var 22 | doc = view.document 23 | // only get URL when necessary in case Blob.js hasn't overridden it yet 24 | , get_URL = function() { 25 | return view.URL || view.webkitURL || view; 26 | } 27 | , save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a") 28 | , can_use_save_link = "download" in save_link 29 | , click = function(node) { 30 | var event = new MouseEvent("click"); 31 | node.dispatchEvent(event); 32 | } 33 | , is_safari = /Version\/[\d\.]+.*Safari/.test(navigator.userAgent) 34 | , webkit_req_fs = view.webkitRequestFileSystem 35 | , req_fs = view.requestFileSystem || webkit_req_fs || view.mozRequestFileSystem 36 | , throw_outside = function(ex) { 37 | (view.setImmediate || view.setTimeout)(function() { 38 | throw ex; 39 | }, 0); 40 | } 41 | , force_saveable_type = "application/octet-stream" 42 | , fs_min_size = 0 43 | // the Blob API is fundamentally broken as there is no "downloadfinished" event to subscribe to 44 | , arbitrary_revoke_timeout = 1000 * 40 // in ms 45 | , revoke = function(file) { 46 | var revoker = function() { 47 | if (typeof file === "string") { // file is an object URL 48 | get_URL().revokeObjectURL(file); 49 | } else { // file is a File 50 | file.remove(); 51 | } 52 | }; 53 | /* // Take note W3C: 54 | var 55 | uri = typeof file === "string" ? file : file.toURL() 56 | , revoker = function(evt) { 57 | // idealy DownloadFinishedEvent.data would be the URL requested 58 | if (evt.data === uri) { 59 | if (typeof file === "string") { // file is an object URL 60 | get_URL().revokeObjectURL(file); 61 | } else { // file is a File 62 | file.remove(); 63 | } 64 | } 65 | } 66 | ; 67 | view.addEventListener("downloadfinished", revoker); 68 | */ 69 | setTimeout(revoker, arbitrary_revoke_timeout); 70 | } 71 | , dispatch = function(filesaver, event_types, event) { 72 | event_types = [].concat(event_types); 73 | var i = event_types.length; 74 | while (i--) { 75 | var listener = filesaver["on" + event_types[i]]; 76 | if (typeof listener === "function") { 77 | try { 78 | listener.call(filesaver, event || filesaver); 79 | } catch (ex) { 80 | throw_outside(ex); 81 | } 82 | } 83 | } 84 | } 85 | , auto_bom = function(blob) { 86 | // prepend BOM for UTF-8 XML and text/* types (including HTML) 87 | if (/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) { 88 | return new Blob(["\ufeff", blob], {type: blob.type}); 89 | } 90 | return blob; 91 | } 92 | , FileSaver = function(blob, name, no_auto_bom) { 93 | if (!no_auto_bom) { 94 | blob = auto_bom(blob); 95 | } 96 | // First try a.download, then web filesystem, then object URLs 97 | var 98 | filesaver = this 99 | , type = blob.type 100 | , blob_changed = false 101 | , object_url 102 | , target_view 103 | , dispatch_all = function() { 104 | dispatch(filesaver, "writestart progress write writeend".split(" ")); 105 | } 106 | // on any filesys errors revert to saving with object URLs 107 | , fs_error = function() { 108 | if (target_view && is_safari && typeof FileReader !== "undefined") { 109 | // Safari doesn't allow downloading of blob urls 110 | var reader = new FileReader(); 111 | reader.onloadend = function() { 112 | var base64Data = reader.result; 113 | target_view.location.href = "data:attachment/file" + base64Data.slice(base64Data.search(/[,;]/)); 114 | filesaver.readyState = filesaver.DONE; 115 | dispatch_all(); 116 | }; 117 | reader.readAsDataURL(blob); 118 | filesaver.readyState = filesaver.INIT; 119 | return; 120 | } 121 | // don't create more object URLs than needed 122 | if (blob_changed || !object_url) { 123 | object_url = get_URL().createObjectURL(blob); 124 | } 125 | if (target_view) { 126 | target_view.location.href = object_url; 127 | } else { 128 | var new_tab = view.open(object_url, "_blank"); 129 | if (new_tab === undefined && is_safari) { 130 | //Apple do not allow window.open, see http://bit.ly/1kZffRI 131 | view.location.href = object_url 132 | } 133 | } 134 | filesaver.readyState = filesaver.DONE; 135 | dispatch_all(); 136 | revoke(object_url); 137 | } 138 | , abortable = function(func) { 139 | return function() { 140 | if (filesaver.readyState !== filesaver.DONE) { 141 | return func.apply(this, arguments); 142 | } 143 | }; 144 | } 145 | , create_if_not_found = {create: true, exclusive: false} 146 | , slice 147 | ; 148 | filesaver.readyState = filesaver.INIT; 149 | if (!name) { 150 | name = "download"; 151 | } 152 | if (can_use_save_link) { 153 | object_url = get_URL().createObjectURL(blob); 154 | setTimeout(function() { 155 | save_link.href = object_url; 156 | save_link.download = name; 157 | click(save_link); 158 | dispatch_all(); 159 | revoke(object_url); 160 | filesaver.readyState = filesaver.DONE; 161 | }); 162 | return; 163 | } 164 | // Object and web filesystem URLs have a problem saving in Google Chrome when 165 | // viewed in a tab, so I force save with application/octet-stream 166 | // http://code.google.com/p/chromium/issues/detail?id=91158 167 | // Update: Google errantly closed 91158, I submitted it again: 168 | // https://code.google.com/p/chromium/issues/detail?id=389642 169 | if (view.chrome && type && type !== force_saveable_type) { 170 | slice = blob.slice || blob.webkitSlice; 171 | blob = slice.call(blob, 0, blob.size, force_saveable_type); 172 | blob_changed = true; 173 | } 174 | // Since I can't be sure that the guessed media type will trigger a download 175 | // in WebKit, I append .download to the filename. 176 | // https://bugs.webkit.org/show_bug.cgi?id=65440 177 | if (webkit_req_fs && name !== "download") { 178 | name += ".download"; 179 | } 180 | if (type === force_saveable_type || webkit_req_fs) { 181 | target_view = view; 182 | } 183 | if (!req_fs) { 184 | fs_error(); 185 | return; 186 | } 187 | fs_min_size += blob.size; 188 | req_fs(view.TEMPORARY, fs_min_size, abortable(function(fs) { 189 | fs.root.getDirectory("saved", create_if_not_found, abortable(function(dir) { 190 | var save = function() { 191 | dir.getFile(name, create_if_not_found, abortable(function(file) { 192 | file.createWriter(abortable(function(writer) { 193 | writer.onwriteend = function(event) { 194 | target_view.location.href = file.toURL(); 195 | filesaver.readyState = filesaver.DONE; 196 | dispatch(filesaver, "writeend", event); 197 | revoke(file); 198 | }; 199 | writer.onerror = function() { 200 | var error = writer.error; 201 | if (error.code !== error.ABORT_ERR) { 202 | fs_error(); 203 | } 204 | }; 205 | "writestart progress write abort".split(" ").forEach(function(event) { 206 | writer["on" + event] = filesaver["on" + event]; 207 | }); 208 | writer.write(blob); 209 | filesaver.abort = function() { 210 | writer.abort(); 211 | filesaver.readyState = filesaver.DONE; 212 | }; 213 | filesaver.readyState = filesaver.WRITING; 214 | }), fs_error); 215 | }), fs_error); 216 | }; 217 | dir.getFile(name, {create: false}, abortable(function(file) { 218 | // delete file if it already exists 219 | file.remove(); 220 | save(); 221 | }), abortable(function(ex) { 222 | if (ex.code === ex.NOT_FOUND_ERR) { 223 | save(); 224 | } else { 225 | fs_error(); 226 | } 227 | })); 228 | }), fs_error); 229 | }), fs_error); 230 | } 231 | , FS_proto = FileSaver.prototype 232 | , saveAs = function(blob, name, no_auto_bom) { 233 | return new FileSaver(blob, name, no_auto_bom); 234 | } 235 | ; 236 | // IE 10+ (native saveAs) 237 | if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob) { 238 | return function(blob, name, no_auto_bom) { 239 | if (!no_auto_bom) { 240 | blob = auto_bom(blob); 241 | } 242 | return navigator.msSaveOrOpenBlob(blob, name || "download"); 243 | }; 244 | } 245 | 246 | FS_proto.abort = function() { 247 | var filesaver = this; 248 | filesaver.readyState = filesaver.DONE; 249 | dispatch(filesaver, "abort"); 250 | }; 251 | FS_proto.readyState = FS_proto.INIT = 0; 252 | FS_proto.WRITING = 1; 253 | FS_proto.DONE = 2; 254 | 255 | FS_proto.error = 256 | FS_proto.onwritestart = 257 | FS_proto.onprogress = 258 | FS_proto.onwrite = 259 | FS_proto.onabort = 260 | FS_proto.onerror = 261 | FS_proto.onwriteend = 262 | null; 263 | 264 | return saveAs; 265 | }( 266 | typeof self !== "undefined" && self 267 | || typeof window !== "undefined" && window 268 | || this.content 269 | )); 270 | // `self` is undefined in Firefox for Android content script context 271 | // while `this` is nsIContentFrameMessageManager 272 | // with an attribute `content` that corresponds to the window 273 | 274 | if (typeof module !== "undefined" && module.exports) { 275 | module.exports.saveAs = saveAs; 276 | } else if ((typeof define !== "undefined" && define !== null) && (define.amd !== null)) { 277 | define([], function() { 278 | return saveAs; 279 | }); 280 | } 281 | -------------------------------------------------------------------------------- /src/build.bat: -------------------------------------------------------------------------------- 1 | :: cd to /src 2 | cd /d %~dp0 3 | 4 | set output_path=..\e-hentai-downloader.user.js 5 | set meta_js_path=..\e-hentai-downloader.meta.js 6 | set parts_js_dir=.\ 7 | 8 | type %meta_js_path%>%output_path% 9 | type %parts_js_dir%first.js>>%output_path% 10 | type %parts_js_dir%JSZip.js>>%output_path% 11 | type %parts_js_dir%FileSaver.js>>%output_path% 12 | type %parts_js_dir%main.js>>%output_path% 13 | -------------------------------------------------------------------------------- /src/build.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | cd `dirname $(pwd)/$0` 3 | output_path="../e-hentai-downloader.user.js" 4 | meta_js_path="../e-hentai-downloader.meta.js" 5 | parts_js_dir="./" 6 | 7 | cat $meta_js_path>$output_path 8 | cat $parts_js_dir"first.js">>$output_path 9 | cat $parts_js_dir"JSZip.js">>$output_path 10 | cat $parts_js_dir"FileSaver.js">>$output_path 11 | cat $parts_js_dir"main.js">>$output_path 12 | -------------------------------------------------------------------------------- /src/first.js: -------------------------------------------------------------------------------- 1 | 2 | // This script using JSZip & FileSaver.js 3 | 4 | 'use strict'; 5 | 6 | console.log('[EHD] E-Hentai Downloader is running.'); 7 | console.log('[EHD] Bugs Report >', 'https://github.com/ccloli/E-Hentai-Downloader/issues | https://greasyfork.org/scripts/10379-e-hentai-downloader/feedback'); 8 | console.log('[EHD] To report a bug, it\'s recommended to provide the logs started with "[EHD]", thanks. =w='); 9 | 10 | // GreaseMonkey 4.x compatible 11 | var loadSetting; 12 | if (typeof GM !== 'undefined' && ((GM.info || {}).scriptHandler || '').toLowerCase().indexOf('greasemonkey') >= 0) { 13 | loadSetting = GM.getValue.bind(this, 'ehD-setting'); 14 | self.GM_setValue = GM.setValue; 15 | self.GM_xmlhttpRequest = GM.xmlHttpRequest; 16 | self.GM_info = GM.info; 17 | } 18 | else { 19 | loadSetting = function (key, init) { 20 | return new Promise(function (resolve, reject) { 21 | try { 22 | resolve(GM_getValue('ehD-setting')); 23 | } 24 | catch (e) { 25 | reject(e); 26 | } 27 | }); 28 | }; 29 | } 30 | 31 | // Opera 12- (Presto) doesn't support generating blob url, and if generate as data url, it may cause crashes. 32 | if (navigator.userAgent.indexOf('Presto') >= 0) { 33 | alert('Your Opera doesn\'t support E-Hentai Downloader. You need to upgrade it to Opera 15+.'); 34 | console.error('[EHD] Opera 12- (Presto) doesn\'t support E-Hentai Downloader. UserAgent > ' + navigator.userAgent); 35 | } 36 | 37 | // Remove IE support 38 | else if (navigator.userAgent.indexOf('Trident') >= 0) { 39 | alert('Your browser doesn\'t support E-Hentai Downloader. You need to switch to other browsers.'); 40 | console.error('[EHD] IE doesn\'t support E-Hentai Downloader. UserAgent > ' + navigator.userAgent); 41 | } 42 | 43 | // GreaseMonkey 3.2 beta 1 and older version can't load content of GM_xhr.response, and this can't be fix. 44 | else if ( 45 | (!GM_info.scriptHandler || GM_info.scriptHandler.indexOf('GreaseMonkey') >= 0) && GM_info.version != null && ( 46 | GM_info.version.split('.')[0] - 0 < 3 || ( 47 | GM_info.version.split('.')[0] - 0 == 3 && ( 48 | GM_info.version.split('.')[1].split('beta')[0] - 0 <= 2 && 49 | GM_info.version.indexOf('beta') >= 0 && 50 | GM_info.version.split('beta')[1] - 0 < 2 51 | ) 52 | ) 53 | ) 54 | ) { 55 | alert('Your GreaseMonkey doesn\'t support E-Hentai Downloader. The first supported version is GreaseMonkey 3.2 beta 2. Please update your GreaseMonkey to enjoy. =w='); 56 | console.error('[EHD] GreaseMonkey doesn\'t support E-Hentai Downloader. GreaseMonkey Version > ' + GM_info.version); 57 | } 58 | 59 | // GreasyFork doesn't allow obfuscated or minified script, so if you want to see the main function, please see src/main.js at GitHub 60 | -------------------------------------------------------------------------------- /src/main.js: -------------------------------------------------------------------------------- 1 | 2 | var zip; 3 | var imageList = []; 4 | var imageData = []; 5 | var infoStr; 6 | var origin = window.location.origin; 7 | var setting = null; 8 | var fetchCount = 0; 9 | var downloadedCount = 0; 10 | var totalCount = 0; 11 | var retryCount = 0; 12 | var failedCount = 0; 13 | var fetchThread = []; 14 | var dirName; 15 | var fileName; 16 | var progressTable = null; 17 | var needNumberImages = false; 18 | var pagesRange = []; 19 | var isDownloading = false; 20 | var isPausing = false; 21 | var isSaving = false; 22 | var pageURLsList = []; 23 | var getAllPagesURLFin = false; 24 | var pretitle = document.title; 25 | var needTitleStatus = false; 26 | var delayTime = 0; 27 | var visibleState = true; 28 | var isTor = location.hostname === 'exhentai55ld2wyap5juskbm67czulomrouspdacjamjeloj7ugjbsad.onion'; 29 | var fetchPagesXHR = new XMLHttpRequest(); 30 | var emptyAudio; 31 | var emptyAudioFile = 'data:audio/mp3;base64,SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU3LjcxLjEwMAAAAAAAAAAAAAAA/+M4wAAAAAAAAAAAAEluZm8AAAAPAAAAEAAABVgANTU1NTU1Q0NDQ0NDUFBQUFBQXl5eXl5ea2tra2tra3l5eXl5eYaGhoaGhpSUlJSUlKGhoaGhoaGvr6+vr6+8vLy8vLzKysrKysrX19fX19fX5eXl5eXl8vLy8vLy////////AAAAAExhdmM1Ny44OQAAAAAAAAAAAAAAACQCgAAAAAAAAAVY82AhbwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/+MYxAALACwAAP/AADwQKVE9YWDGPkQWpT66yk4+zIiYPoTUaT3tnU487uNhOvEmQDaCm1Yz1c6DPjbs6zdZVBk0pdGpMzxF/+MYxA8L0DU0AP+0ANkwmYaAMkOKDDjmYoMtwNMyDxMzDHE/MEsLow9AtDnBlQgDhTx+Eye0GgMHoCyDC8gUswJcMVMABBGj/+MYxBoK4DVpQP8iAtVmDk7LPgi8wvDzI4/MWAwK1T7rxOQwtsItMMQBazAowc4wZMC5MF4AeQAGDpruNuMEzyfjLBJhACU+/+MYxCkJ4DVcAP8MAO9J9THVg6oxRMGNMIqCCTAEwzwwBkINOPAs/iwjgBnMepYyId0PhWo+80PXMVsBFzD/AiwwfcKGMEJB/+MYxDwKKDVkAP8eAF8wMwIxMlpU/OaDPLpNKkEw4dRoBh6qP2FC8jCJQFcweQIPMHOBtTBoAVcwOoCNMYDI0u0Dd8ANTIsy/+MYxE4KUDVsAP8eAFBVpgVVPjdGeTEWQr0wdcDtMCeBgDBkgRgwFYB7Pv/zqx0yQQMCCgKNgonHKj6RRVkxM0GwML0AhDAN/+MYxF8KCDVwAP8MAIHZMDDA3DArAQo3K+TF5WOBDQw0lgcKQUJxhT5sxRcwQQI+EIPWMA7AVBoTABgTgzfBN+ajn3c0lZMe/+MYxHEJyDV0AP7MAA4eEwsqP/PDmzC/gNcwXUGaMBVBIwMEsmB6gaxhVuGkpoqMZMQjooTBwM0+S8FTMC0BcjBTgPwwOQDm/+MYxIQKKDV4AP8WADAzAKQwI4CGPhWOEwCFAiBAYQnQMT+uwXUeGzjBWQVkwTcENMBzA2zAGgFEJfSPkPSZzPXgqFy2h0xB/+MYxJYJCDV8AP7WAE0+7kK7MQrATDAvQRIwOADKMBuA9TAYQNM3AiOSPjGxowgHMKFGcBNMQU1FMy45OS41VVU/31eYM4sK/+MYxKwJaDV8AP7SAI4y1Yq0MmOIADGwBZwwlgIJMztCM0qU5TQPG/MSkn8yEROzCdAxECVMQU1FMy45OS41VTe7Ohk+Pqcx/+MYxMEJMDWAAP6MADVLDFUx+4J6Mq7NsjN2zXo8V5fjVJCXNOhwM0vTCDAxFpMYYQU+RlVMQU1FMy45OS41VVVVVVVVVVVV/+MYxNcJADWAAP7EAFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV/+MYxOsJwDWEAP7SAFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV/+MYxPMLoDV8AP+eAFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV/+MYxPQL0DVcAP+0AFVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV'; 32 | 33 | var ehDownloadRegex = { 34 | imageURL: [ 35 | /<\/a><\/div>
([\s\S]+?) :: /, 46 | resFileName: /filename=['"]?([\s\S]+?)['"]?$/m, 47 | dangerChars: /[:"*?|<>\/\\\n]/g, 48 | pagesRange: /^(!?\d*(-\d*(\/\d+)?)?\s*,\s*)*!?\d*(-\d*(\/\d+)?)?$/, 49 | pagesURL: /(?:([\d,]+)<\/strong> towards.*?limit of ([\d,]+)<\/strong>/, 52 | pagesLength: /(\d+)<\/a>.+?<\/table>/, 53 | IPBanExpires: /The ban expires in \d+ hours?( and \d+ minutes?)?/, 54 | donatorPower: /\ 1003 | \ 1007 | '; 1011 | progressTable.appendChild(node); 1012 | } 1013 | 1014 | nodeList = { 1015 | current: node, 1016 | fileName: node.getElementsByTagName('td')[0], 1017 | status: node.getElementsByTagName('td')[2], 1018 | statusText: node.getElementsByClassName('ehD-pt-status-text')[0], 1019 | progress: node.getElementsByTagName('progress')[0], 1020 | progressText: node.getElementsByTagName('span')[0], 1021 | abort: node.getElementsByClassName('ehD-pt-abort')[0] 1022 | }; 1023 | } 1024 | var speedInfo = { 1025 | lastProgress: 0, 1026 | lastTimestamp: new Date().getTime(), 1027 | zeroDetect: null, 1028 | expiredDetect: null 1029 | }; 1030 | 1031 | if (needScrollIntoView) { 1032 | ehDownloadDialog.scrollTop = ehDownloadDialog.scrollHeight; 1033 | } 1034 | 1035 | var zeroSpeedHandler = function(res){ 1036 | if (imageData[index] instanceof ArrayBuffer) { // Has already downloaded 1037 | updateProgress(nodeList, { 1038 | name: '#' + imageList[index]['realIndex'] + ': ' + imageList[index]['imageName'], 1039 | status: 'Succeed!', 1040 | progress: '1', 1041 | progressText: '100%', 1042 | class: 'ehD-pt-succeed' 1043 | }); 1044 | 1045 | return; 1046 | } 1047 | if (!isDownloading) return; // Temporarily fixes #31 1048 | if (isPausing && setting['force-pause']) return; 1049 | 1050 | updateProgress(nodeList, { progressText: '0 KB/s' }); 1051 | 1052 | if (setting['speed-detect'] && speedInfo.expiredDetect === null) { 1053 | speedInfo.expiredDetect = setTimeout(expiredSpeedHandler, (setting['speed-expired'] ? setting['speed-expired'] : 30) * 1000, res); 1054 | } 1055 | }; 1056 | 1057 | var expiredSpeedHandler = function(res){ 1058 | if (imageData[index] instanceof ArrayBuffer) { // Has already downloaded 1059 | updateProgress(nodeList, { 1060 | name: '#' + imageList[index]['realIndex'] + ': ' + imageList[index]['imageName'], 1061 | status: 'Succeed!', 1062 | progress: '1', 1063 | progressText: '100%', 1064 | class: 'ehD-pt-succeed' 1065 | }); 1066 | 1067 | return; 1068 | } 1069 | if (!isDownloading) return; // Temporarily fixes #31 1070 | if (isPausing && setting['force-pause']) return; 1071 | 1072 | if (typeof fetchThread[index] !== 'undefined' && 'abort' in fetchThread[index]) fetchThread[index].abort(); 1073 | 1074 | console.log('[EHD] #' + (index + 1) + ': Speed Too Low'); 1075 | console.log('[EHD] #' + (index + 1) + ': RealIndex >', imageList[index]['realIndex'], ' | ReadyState >', res.readyState, ' | Status >', res.status, ' | StatusText >', res.statusText + '\nRequest URL >', requestURL, '\nFinal URL >', res.finalUrl, '\nResposeHeaders >' + res.responseHeaders); 1076 | 1077 | updateProgress(nodeList, { 1078 | status: 'Failed! (Low Speed)', 1079 | progress: '0', 1080 | progressText: '', 1081 | class: 'ehD-pt-warning' 1082 | }); 1083 | 1084 | if (ehDownloadRegex.originalImagePattern.test(imageList[index]['imageURL']) && imageList[index]['imageURL'] !== res.finalUrl) { 1085 | imageList[index]['imageFinalURL'] = res.finalUrl; 1086 | } 1087 | 1088 | for (var i in res) { 1089 | delete res[i]; 1090 | } 1091 | 1092 | failedFetching(index, nodeList); 1093 | }; 1094 | 1095 | var removeTimerHandler = function(){ 1096 | if (speedInfo.expiredDetect !== null) { 1097 | clearTimeout(speedInfo.expiredDetect); 1098 | speedInfo.expiredDetect = null; 1099 | } 1100 | 1101 | if (speedInfo.zeroDetect !== null) { 1102 | clearTimeout(speedInfo.zeroDetect); 1103 | speedInfo.zeroDetect = null; 1104 | } 1105 | }; 1106 | 1107 | var requestHeaders = { 1108 | Referer: imageList[index]['pageURL'], 1109 | 'X-Alt-Referer': imageList[index]['pageURL'] 1110 | }; 1111 | 1112 | if (setting['pass-cookies']) { 1113 | requestHeaders.Cookie = document.cookie; 1114 | } 1115 | 1116 | if (ehDownloadRegex.originalImagePattern.test(requestURL)) { 1117 | requestHeaders['Cache-Control'] = 'no-cache'; 1118 | } 1119 | 1120 | fetchThread[index] = GM_xmlhttpRequest({ 1121 | method: 'GET', 1122 | url: requestURL, 1123 | responseType: 'arraybuffer', 1124 | timeout: (setting['timeout'] !== undefined) ? Number(setting['timeout']) * 1000 || undefined : 300000, 1125 | headers: requestHeaders, 1126 | onprogress: function(res) { 1127 | var t = new Date().getTime(); 1128 | var speedText; 1129 | var speedKBs = res.lengthComputable ? Number((res.loaded - speedInfo.lastProgress) / (t - speedInfo.lastTimestamp) / 1.024) : -1; 1130 | 1131 | if (t - speedInfo.lastTimestamp >= 1000 || speedInfo.lastProgress === 0) { 1132 | speedText = res.lengthComputable ? speedKBs.toFixed(2) + ' KB/s' : ''; 1133 | speedInfo.lastProgress = res.loaded; 1134 | speedInfo.lastTimestamp = t; 1135 | } 1136 | 1137 | updateProgress(nodeList, { 1138 | name: '#' + imageList[index]['realIndex'] + ': ' + imageList[index]['imageName'], 1139 | progress: res.lengthComputable ? res.loaded / (res.total || 1) : '', 1140 | progressText: speedText, 1141 | class: '', 1142 | status: retryCount[index] === 0 ? 'Downloading...' : 'Retrying (' + retryCount[index] + '/' + (setting['retry-count'] !== undefined ? setting['retry-count'] : 3) + ') ...' 1143 | }); 1144 | 1145 | // set showing speed to 0 1146 | if (speedInfo.zeroDetect !== null) { 1147 | clearTimeout(speedInfo.zeroDetect); 1148 | speedInfo.zeroDetect = null; 1149 | } 1150 | speedInfo.zeroDetect = setTimeout(zeroSpeedHandler, 3000, res); 1151 | 1152 | if (setting['speed-detect']) { 1153 | if (speedKBs >= setting['speed-min'] ? setting['speed-min'] : 5) { 1154 | 1155 | if (speedInfo.expiredDetect !== null) { 1156 | clearTimeout(speedInfo.expiredDetect); 1157 | speedInfo.expiredDetect = null; 1158 | } 1159 | 1160 | for (var i in res) { 1161 | delete res[i]; 1162 | } 1163 | } 1164 | else if (speedInfo.expiredDetect === null) { 1165 | speedInfo.expiredDetect = setTimeout(expiredSpeedHandler, (setting['speed-expired'] ? setting['speed-expired'] : 30) * 1000, res); 1166 | console.log('[EHD] Speed detect handler is inited for', index + 1, '!'); 1167 | } 1168 | } 1169 | 1170 | if (ehDownloadRegex.originalImagePattern.test(imageList[index]['imageURL']) && imageList[index]['imageURL'] !== res.finalUrl) { 1171 | imageList[index]['imageFinalURL'] = res.finalUrl; 1172 | } 1173 | }, 1174 | onload: function(res) { 1175 | try { 1176 | removeTimerHandler(); 1177 | if (!isDownloading || imageData[index] instanceof ArrayBuffer) return; // Temporarily fixes #31 1178 | 1179 | // cache them to reduce waiting time and CPU usage on Chrome with Tampermonkey 1180 | // (Tampermonkey uses a dirty way to give res.response, transfer string to arraybuffer every time) 1181 | // now store progress just spent ~1s instead of ~8s 1182 | var response = res.response; 1183 | var responseHeaders = res.responseHeaders; 1184 | 1185 | // use regex to fixed compatibility with http/2, as its headers are lower case (at least fixed with Yandex Turbo) 1186 | var mime = responseHeaders.match(/Content-Type:/i) ? responseHeaders.split(/Content-Type:/i)[1].split('\n')[0].trim().split('/') : ['', '']; 1187 | 1188 | if (!response) { 1189 | console.log('[EHD] #' + (index + 1) + ': Empty Response (See: https://github.com/ccloli/E-Hentai-Downloader/issues/16 )'); 1190 | console.log('[EHD] #' + (index + 1) + ': RealIndex >', imageList[index]['realIndex'], ' | ReadyState >', res.readyState, ' | Status >', res.status, ' | StatusText >', res.statusText + '\nRequest URL >', requestURL, '\nFinal URL >', res.finalUrl, '\nResposeHeaders >' + res.responseHeaders); 1191 | 1192 | updateProgress(nodeList, { 1193 | status: 'Failed! (Empty Response)', 1194 | progress: '0', 1195 | progressText: '', 1196 | class: 'ehD-pt-warning' 1197 | }); 1198 | 1199 | for (var i in res) { 1200 | delete res[i]; 1201 | } 1202 | return failedFetching(index, nodeList); 1203 | 1204 | // res.response polyfill is useless, so it has been removed 1205 | } 1206 | 1207 | var byteLength = response.byteLength; 1208 | var responseText; 1209 | if (mime[0] === 'text') { 1210 | responseText = new TextDecoder().decode(new DataView(response)); 1211 | } 1212 | 1213 | if (byteLength === 925) { // '403 Access Denied' Image Byte Size 1214 | // GM_xhr only support abort() 1215 | console.log('[EHD] #' + (index + 1) + ': 403 Access Denied'); 1216 | console.log('[EHD] #' + (index + 1) + ': RealIndex >', imageList[index]['realIndex'], ' | ReadyState >', res.readyState, ' | Status >', res.status, ' | StatusText >', res.statusText + '\nRequest URL >', requestURL, '\nFinal URL >', res.finalUrl, '\nResposeHeaders >' + res.responseHeaders); 1217 | 1218 | updateProgress(nodeList, { 1219 | status: 'Failed! (Error 403)', 1220 | progress: '0', 1221 | progressText: '', 1222 | class: 'ehD-pt-warning' 1223 | }); 1224 | 1225 | for (var i in res) { 1226 | delete res[i]; 1227 | } 1228 | return failedFetching(index, nodeList, true); 1229 | } 1230 | if (byteLength === 28) { // 'An error has occurred. (403)' Length 1231 | console.log('[EHD] #' + (index + 1) + ': An error has occurred. (403)'); 1232 | console.log('[EHD] #' + (index + 1) + ': RealIndex >', imageList[index]['realIndex'], ' | ReadyState >', res.readyState, ' | Status >', res.status, ' | StatusText >', res.statusText + '\nRequest URL >', requestURL, '\nFinal URL >', res.finalUrl, '\nResposeHeaders >' + res.responseHeaders); 1233 | 1234 | updateProgress(nodeList, { 1235 | status: 'Failed! (Error 403)', 1236 | progress: '0', 1237 | progressText: '', 1238 | class: 'ehD-pt-warning' 1239 | }); 1240 | 1241 | for (var i in res) { 1242 | delete res[i]; 1243 | } 1244 | return failedFetching(index, nodeList, true); 1245 | } 1246 | if ( 1247 | byteLength === 142 || // Image Viewing Limits String Byte Size (exhentai) 1248 | byteLength === 144 || // Image Viewing Limits String Byte Size (g.e-hentai) 1249 | byteLength === 28658 || // '509 Bandwidth Exceeded' Image Byte Size 1250 | byteLength === 102 || // You have reached the image limit, and do not have sufficient GP to buy a download quota. 1251 | byteLength === 93 || // Downloading original files during peak hours requires GP, and you do not have enough. 1252 | (mime[0] === 'text' && ( 1253 | responseText.indexOf('You have exceeded your image viewing limits') >= 0 || 1254 | responseText.indexOf('do not have sufficient GP to buy') >= 0 || 1255 | responseText.indexOf('requires GP, and you do not have enough') >= 0 1256 | )) // directly detect response content in case byteLength will be modified 1257 | ) { 1258 | // thought exceed the limits, downloading image is still accessable 1259 | /*for (var i = 0; i < fetchThread.length; i++) { 1260 | if (typeof fetchThread[i] !== 'undefined' && 'abort' in fetchThread[i]) fetchThread[i].abort(); 1261 | }*/ 1262 | console.log('[EHD] #' + (index + 1) + ': Exceed Image Viewing Limits / 509 Bandwidth Exceeded'); 1263 | console.log('[EHD] #' + (index + 1) + ': RealIndex >', imageList[index]['realIndex'], ' | ReadyState >', res.readyState, ' | Status >', res.status, ' | StatusText >', res.statusText + '\nRequest URL >', requestURL, '\nFinal URL >', res.finalUrl, '\nResposeHeaders >' + res.responseHeaders); 1264 | 1265 | updateProgress(nodeList, { 1266 | status: 'Failed! (Exceed Limits/GPs)', 1267 | progress: '0', 1268 | progressText: '', 1269 | class: 'ehD-pt-failed' 1270 | }); 1271 | 1272 | for (var i in res) { 1273 | delete res[i]; 1274 | } 1275 | 1276 | failedCount++; 1277 | fetchCount--; 1278 | updateTotalStatus(); 1279 | 1280 | if (isPausing) return; 1281 | 1282 | pushDialog('You have exceeded your image viewing limits, or you need GP to download.\n'); 1283 | isPausing = true; 1284 | updateTotalStatus(); 1285 | if (emptyAudio) { 1286 | emptyAudio.pause(); 1287 | } 1288 | 1289 | if (ehDownloadDialog.contains(ehDownloadPauseBtn)) { 1290 | ehDownloadDialog.removeChild(ehDownloadPauseBtn); 1291 | } 1292 | 1293 | if (confirm('You have temporarily reached the limit for how many images you can browse.\n\ 1294 | If you don\'t have enough limit, or it\'s in site\'s peak hours, or the gallery is uploaded for a long time, you need to use GP to download, but you don\'t have enough GP to add quota.\n\n\ 1295 | To increase viewing limits, you can:\n\ 1296 | - If you are not signed in, sign in to get quota.\n\ 1297 | - Run Hentai@Home to get points which you can pay to increase your limit.\n\ 1298 | - Check back in a few hours, and it\'ll slowly recovered (3 points per minute by default).\n\ 1299 | - You can reset it by paying your GPs or credits.\n\n\ 1300 | To gain GP, you can:\n\ 1301 | - Upload galleries and earn GP from visits and users using offical archive download.\n\ 1302 | - Run Hentai@Home to earn GP from hit.\n\ 1303 | - Upload torrents.\n\ 1304 | - Write comments and gain from others voting.\n\ 1305 | - Exchange GP with credits or hath, or donation.\n\ 1306 | - Wait till your limits recovered or the peak hours passed.\n\n\ 1307 | If you want to reset your limits by paying your GPs or credits right now, or exchange GPs, choose YES, and do it in the opened window. Or if you want to wait a few minutes until you have enough free limit, then continue, choose NO.')) { 1308 | window.open('https://e-hentai.org/home.php'); 1309 | } 1310 | 1311 | var resetButton = document.createElement('a'); 1312 | resetButton.innerHTML = ''; 1313 | resetButton.setAttribute('href', 'https://e-hentai.org/home.php'); 1314 | resetButton.setAttribute('target', '_blank'); 1315 | ehDownloadDialog.appendChild(resetButton); 1316 | 1317 | var continueButton = document.createElement('button'); 1318 | continueButton.innerHTML = 'Continue Download'; 1319 | continueButton.addEventListener('click', function(){ 1320 | //fetchCount = 0; 1321 | ehDownloadDialog.removeChild(resetButton); 1322 | ehDownloadDialog.removeChild(continueButton); 1323 | ehDownloadDialog.removeChild(cancelButton); 1324 | ehDownloadDialog.appendChild(ehDownloadPauseBtn); 1325 | 1326 | isPausing = false; 1327 | initProgressTable(); 1328 | checkFailed(); 1329 | }); 1330 | ehDownloadDialog.appendChild(continueButton); 1331 | 1332 | var cancelButton = document.createElement('button'); 1333 | cancelButton.innerHTML = 'Cancel Download'; 1334 | cancelButton.addEventListener('click', function(){ 1335 | ehDownloadDialog.removeChild(resetButton); 1336 | ehDownloadDialog.removeChild(continueButton); 1337 | ehDownloadDialog.removeChild(cancelButton); 1338 | 1339 | if (setting['auto-download-cancel'] || confirm('You have exceeded your image viewing limits. Would you like to save downloaded images?')) { 1340 | saveDownloaded(); 1341 | } 1342 | else { 1343 | insertCloseButton(); 1344 | } 1345 | isPausing = false; 1346 | isDownloading = false; 1347 | 1348 | loadImageLimits(true); 1349 | }); 1350 | ehDownloadDialog.appendChild(cancelButton); 1351 | 1352 | return; 1353 | } 1354 | // ip banned 1355 | if (mime[0] === 'text') { 1356 | if (responseText.indexOf('Your IP address has been temporarily banned') >= 0) { 1357 | console.log('[EHD] #' + (index + 1) + ': IP address banned'); 1358 | console.log('[EHD] #' + (index + 1) + ': RealIndex >', imageList[index]['realIndex'], ' | ReadyState >', res.readyState, ' | Status >', res.status, ' | StatusText >', res.statusText + '\nRequest URL >', requestURL, '\nFinal URL >', res.finalUrl, '\nResposeHeaders >' + res.responseHeaders); 1359 | 1360 | updateProgress(nodeList, { 1361 | status: 'Failed! (IP banned)', 1362 | progress: '0', 1363 | progressText: '', 1364 | class: 'ehD-pt-failed' 1365 | }); 1366 | 1367 | for (var i in res) { 1368 | delete res[i]; 1369 | } 1370 | 1371 | failedCount++; 1372 | fetchCount--; 1373 | updateTotalStatus(); 1374 | 1375 | if (isPausing) return; 1376 | 1377 | pushDialog('Your IP address has been temporarily banned.\n'); 1378 | isPausing = true; 1379 | updateTotalStatus(); 1380 | if (emptyAudio) { 1381 | emptyAudio.pause(); 1382 | } 1383 | 1384 | if (ehDownloadDialog.contains(ehDownloadPauseBtn)) { 1385 | ehDownloadDialog.removeChild(ehDownloadPauseBtn); 1386 | } 1387 | 1388 | var expiredTime = responseText.match(ehDownloadRegex.IPBanExpires); 1389 | 1390 | alert('Your IP address has been temporarily banned. \n\n\ 1391 | Make sure your download settings are not configured to download too fast. If you are using conservative rules, check if your computer is infected with malware, or if you are using a shared IP with others.\n\ 1392 | If you can change your IP (like using a proxy) or wait until you\'re unblocked, you can then continue your download; or cancel your download and get downloaded images.\n\n' + 1393 | (expiredTime ? '\n' + expiredTime[0] : '') 1394 | ); 1395 | 1396 | var continueButton = document.createElement('button'); 1397 | continueButton.innerHTML = 'Continue Download'; 1398 | continueButton.addEventListener('click', function () { 1399 | //fetchCount = 0; 1400 | ehDownloadDialog.removeChild(continueButton); 1401 | ehDownloadDialog.removeChild(cancelButton); 1402 | ehDownloadDialog.appendChild(ehDownloadPauseBtn); 1403 | 1404 | isPausing = false; 1405 | initProgressTable(); 1406 | checkFailed(); 1407 | }); 1408 | ehDownloadDialog.appendChild(continueButton); 1409 | 1410 | var cancelButton = document.createElement('button'); 1411 | cancelButton.innerHTML = 'Cancel Download'; 1412 | cancelButton.addEventListener('click', function () { 1413 | ehDownloadDialog.removeChild(continueButton); 1414 | ehDownloadDialog.removeChild(cancelButton); 1415 | 1416 | if (setting['auto-download-cancel'] || confirm('Would you like to save downloaded images?')) { 1417 | saveDownloaded(); 1418 | } 1419 | else { 1420 | insertCloseButton(); 1421 | } 1422 | isPausing = false; 1423 | isDownloading = false; 1424 | 1425 | loadImageLimits(true); 1426 | }); 1427 | ehDownloadDialog.appendChild(cancelButton); 1428 | 1429 | return; 1430 | } 1431 | if (responseText.indexOf('as your account has been suspended') >= 0) { 1432 | console.log('[EHD] #' + (index + 1) + ': Account Suspended'); 1433 | console.log('[EHD] #' + (index + 1) + ': RealIndex >', imageList[index]['realIndex'], ' | ReadyState >', res.readyState, ' | Status >', res.status, ' | StatusText >', res.statusText + '\nRequest URL >', requestURL, '\nFinal URL >', res.finalUrl, '\nResposeHeaders >' + res.responseHeaders); 1434 | 1435 | updateProgress(nodeList, { 1436 | status: 'Failed! (Suspended)', 1437 | progress: '0', 1438 | progressText: '', 1439 | class: 'ehD-pt-failed' 1440 | }); 1441 | 1442 | for (var i in res) { 1443 | delete res[i]; 1444 | } 1445 | 1446 | if (setting['force-resized'] || confirm('Your account has been suspended.\n\n\ 1447 | Your account is suspended by E-Hentai, and you can check your unblock time on E-Hentai forum. At this time, you cannot access to any user-related page and download original images.\n\ 1448 | You can still access to resized images, would you like to switch to download resized images?')) { 1449 | setting['force-resized'] = true; 1450 | getPageData(index); 1451 | return; 1452 | } 1453 | 1454 | if (setting['auto-download-cancel'] || confirm('Would you like to save downloaded images?')) { 1455 | saveDownloaded(); 1456 | } 1457 | else { 1458 | insertCloseButton(); 1459 | } 1460 | isDownloading = false; 1461 | 1462 | loadImageLimits(true); 1463 | return; 1464 | } 1465 | } 1466 | // res.status should be detected at here, because we should know are we reached image limits at first 1467 | if (res.status !== 200) { 1468 | console.log('[EHD] #' + (index + 1) + ': Wrong Response Status (' + res.status + ')'); 1469 | console.log('[EHD] #' + (index + 1) + ': RealIndex >', imageList[index]['realIndex'], ' | ReadyState >', res.readyState, ' | Status >', res.status, ' | StatusText >', res.statusText + '\nRequest URL >', requestURL, '\nFinal URL >', res.finalUrl, '\nResposeHeaders >' + res.responseHeaders); 1470 | 1471 | updateProgress(nodeList, { 1472 | status: 'Failed! (Status ' + res.status + ')', 1473 | progress: '0', 1474 | progressText: '', 1475 | class: 'ehD-pt-warning' 1476 | }); 1477 | 1478 | for (var i in res) { 1479 | delete res[i]; 1480 | } 1481 | return failedFetching(index, nodeList, res.status === 404); 1482 | } 1483 | // hot fix for new E-Hentai original image server, as it returns an invalid `Content-Type` header (#153) 1484 | if (['image', 'jpg', 'jpeg', 'gif', 'png', 'bmp', 'tif', 'tiff', 'webp', 'apng'].indexOf(mime[0]) < 0) { 1485 | console.log('[EHD] #' + (index + 1) + ': Wrong Content-Type'); 1486 | console.log('[EHD] #' + (index + 1) + ': RealIndex >', imageList[index]['realIndex'], ' | ReadyState >', res.readyState, ' | Status >', res.status, ' | StatusText >', res.statusText + '\nRequest URL >', requestURL, '\nFinal URL >', res.finalUrl, '\nResposeHeaders >' + res.responseHeaders); 1487 | 1488 | updateProgress(nodeList, { 1489 | status: 'Failed! (Wrong MIME)', 1490 | progress: '0', 1491 | progressText: '', 1492 | class: 'ehD-pt-warning' 1493 | }); 1494 | 1495 | for (var i in res) { 1496 | delete res[i]; 1497 | } 1498 | return failedFetching(index, nodeList); 1499 | } 1500 | 1501 | // logs in #80 shows sometimes it didn't match the regex, but cannot reproduce right now 1502 | try { 1503 | var imageName = imageList[index]['imageName']; 1504 | if (ehDownloadRegex.resFileName.test(res.responseHeaders)) { 1505 | imageName = getSafeName(res.responseHeaders.match(ehDownloadRegex.resFileName)[1].trim()) 1506 | } else { 1507 | var fileNameFromUrl = (res.finalUrl || requestURL).split('/').pop().split('?').shift(); 1508 | // TODO: enum all image file extensions? at least blocks fullimg.php 1509 | if (fileNameFromUrl.indexOf('.') > 0 && fileNameFromUrl.indexOf('.php') < 0) { 1510 | imageName = getSafeName(fileNameFromUrl); 1511 | } else { 1512 | imageName = imageList[index]['imageName']; 1513 | } 1514 | } 1515 | imageList[index]['_imageName'] = imageList[index]['imageName'] = imageName; 1516 | } 1517 | catch (error) { 1518 | console.log('[EHD] #' + (index + 1) + ': Parse file name failed'); 1519 | console.log('[EHD] #' + (index + 1) + ': RealIndex >', imageList[index]['realIndex'], ' | ReadyState >', res.readyState, ' | Status >', res.status, ' | StatusText >', res.statusText + '\nRequest URL >', requestURL, '\nFinal URL >', res.finalUrl, '\nResposeHeaders >' + res.responseHeaders); 1520 | 1521 | imageList[index]['_imageName'] = imageList[index]['imageName']; 1522 | } 1523 | 1524 | updateProgress(nodeList, { 1525 | name: '#' + imageList[index]['realIndex'] + ': ' + imageList[index]['imageName'], 1526 | status: 'Succeed!', 1527 | progress: '1', 1528 | progressText: '100%', 1529 | class: 'ehD-pt-succeed' 1530 | }); 1531 | 1532 | storeRes(response, index); 1533 | 1534 | for (var i in res) { 1535 | delete res[i]; 1536 | } 1537 | response = null; 1538 | } 1539 | catch (error) { 1540 | console.log('[EHD] #' + (index + 1) + ': Unknown Error (Please send feedback)'); 1541 | console.log('[EHD] #' + (index + 1) + ': RealIndex >', imageList[index]['realIndex'], ' | ReadyState >', res.readyState, ' | Status >', res.status, ' | StatusText >', res.statusText + '\nRequest URL >', requestURL, '\nFinal URL >', res.finalUrl, '\nResposeHeaders >' + res.responseHeaders); 1542 | console.log(error); 1543 | 1544 | updateProgress(nodeList, { 1545 | status: 'Failed! (Unknown)', 1546 | progress: '0', 1547 | progressText: '', 1548 | class: 'ehD-pt-failed' 1549 | }); 1550 | 1551 | for (var i in res) { 1552 | delete res[i]; 1553 | } 1554 | return failedFetching(index, nodeList); 1555 | } 1556 | }, 1557 | onerror: function(res){ 1558 | removeTimerHandler(); 1559 | if (!isDownloading || imageData[index] instanceof ArrayBuffer) return; // Temporarily fixes #31 1560 | 1561 | console.log('[EHD] #' + (index + 1) + ': Network Error'); 1562 | console.log('[EHD] #' + (index + 1) + ': RealIndex >', imageList[index]['realIndex'], ' | ReadyState >', res.readyState, ' | Status >', res.status, ' | StatusText >', res.statusText + '\nRequest URL >', requestURL, '\nFinal URL >', res.finalUrl, '\nResposeHeaders >' + res.responseHeaders); 1563 | 1564 | updateProgress(nodeList, { 1565 | status: 'Failed! (Network Error)', 1566 | progress: '0', 1567 | progressText: '', 1568 | class: 'ehD-pt-warning' 1569 | }); 1570 | 1571 | if (ehDownloadRegex.originalImagePattern.test(imageList[index]['imageURL']) && imageList[index]['imageURL'] !== res.finalUrl) { 1572 | imageList[index]['imageFinalURL'] = res.finalUrl; 1573 | } 1574 | 1575 | for (var i in res) { 1576 | delete res[i]; 1577 | } 1578 | 1579 | failedFetching(index, nodeList); 1580 | }, 1581 | ontimeout: function(res){ 1582 | removeTimerHandler(); 1583 | if (!isDownloading || imageData[index] instanceof ArrayBuffer) return; // Temporarily fixes #31 1584 | 1585 | console.log('[EHD] #' + (index + 1) + ': Timed Out'); 1586 | console.log('[EHD] #' + (index + 1) + ': RealIndex >', imageList[index]['realIndex'], ' | ReadyState >', res.readyState, ' | Status >', res.status, ' | StatusText >', res.statusText + '\nRequest URL >', requestURL, '\nFinal URL >', res.finalUrl, '\nResposeHeaders >' + res.responseHeaders); 1587 | 1588 | updateProgress(nodeList, { 1589 | status: 'Failed! (Timed Out)', 1590 | progress: '0', 1591 | progressText: '', 1592 | class: 'ehD-pt-warning' 1593 | }); 1594 | 1595 | if (ehDownloadRegex.originalImagePattern.test(imageList[index]['imageURL']) && imageList[index]['imageURL'] !== res.finalUrl) { 1596 | imageList[index]['imageFinalURL'] = res.finalUrl; 1597 | } 1598 | 1599 | 1600 | for (var i in res) { 1601 | delete res[i]; 1602 | } 1603 | 1604 | failedFetching(index, nodeList); 1605 | } 1606 | }); 1607 | 1608 | if (nodeList.status.dataset.initedAbort !== '2') { 1609 | nodeList.abort.addEventListener('click', function () { 1610 | removeTimerHandler(); 1611 | }); 1612 | 1613 | nodeList.status.setAttribute('data-inited-abort', '2'); 1614 | } 1615 | 1616 | if (!nodeList.fileName.dataset.initedClick !== '1') { 1617 | nodeList.fileName.addEventListener('click', function(event) { 1618 | if (event.ctrlKey || event.altKey) { 1619 | var targetWindow = window.open(imageList[index]['imageFinalURL'] || imageList[index]['imageURL']); 1620 | try { 1621 | targetWindow.focus(); 1622 | } 1623 | catch (e) {} 1624 | } 1625 | }); 1626 | nodeList.fileName.setAttribute('data-inited-click', '2'); 1627 | } 1628 | 1629 | updateTotalStatus(); 1630 | } 1631 | 1632 | function retryAllFailed(){ 1633 | var index, refetch = 0; 1634 | initProgressTable(); 1635 | 1636 | for (index = 0; index < imageData.length; index++) { 1637 | if (imageData[index] === 'Fetching') { 1638 | imageData[index] = null; 1639 | retryCount[index] = 0; 1640 | } 1641 | } 1642 | 1643 | failedCount = 0; 1644 | fetchCount = 0; 1645 | requestDownload(); 1646 | } 1647 | 1648 | function insertCloseButton(handle) { 1649 | var exitButton = document.createElement('button'); 1650 | exitButton.style.display = 'block'; 1651 | exitButton.style.margin = '0 auto'; 1652 | exitButton.textContent = 'Close'; 1653 | exitButton.onclick = function(){ 1654 | ehDownloadDialog.removeChild(exitButton); 1655 | ehDownloadDialog.style.display = 'none'; 1656 | zip.file(/.*/).forEach(function (elem) { 1657 | zip.remove(elem.name); 1658 | }); 1659 | exitButton.onclick = null; 1660 | if (handle) { 1661 | handle(); 1662 | } 1663 | if (ehDownloadFS.needFileSystem) ehDownloadFS.removeFile(unsafeWindow.gid + '.zip'); 1664 | }; 1665 | ehDownloadDialog.appendChild(exitButton); 1666 | ehDownloadDialog.scrollTop = ehDownloadDialog.scrollHeight; 1667 | 1668 | if (ehDownloadDialog.contains(forceDownloadTips)) ehDownloadDialog.removeChild(forceDownloadTips); 1669 | } 1670 | 1671 | function getPagesURLFromMPV() { 1672 | var mpvURL = location.origin + '/mpv/' + unsafeWindow.gid + '/' + 1673 | unsafeWindow.token + '/'; 1674 | 1675 | var xhr = new XMLHttpRequest(); 1676 | xhr.open('GET', mpvURL); 1677 | xhr.onload = function () { 1678 | var responseText = xhr.responseText; 1679 | if (xhr.status !== 200 || !responseText) { 1680 | if (retryCount < (setting['retry-count'] !== undefined ? setting['retry-count'] : 3)) { 1681 | pushDialog('Failed! Retrying... '); 1682 | retryCount++; 1683 | xhr.open('GET', mpvURL); 1684 | xhr.timeout = 30000; 1685 | xhr.send(); 1686 | } 1687 | else { 1688 | pushDialog('Failed!\nFetch Pages\' URL failed, Please try again later.'); 1689 | isDownloading = false; 1690 | alert('Fetch Pages\' URL failed, Please try again later.'); 1691 | } 1692 | return; 1693 | } 1694 | 1695 | var listMatch = responseText.match(ehDownloadRegex.mpvKey); 1696 | if (!listMatch) { 1697 | console.error('[EHD] Response content is incorrect!'); 1698 | if (retryCount < (setting['retry-count'] !== undefined ? setting['retry-count'] : 3)) { 1699 | pushDialog('Failed! Retrying... '); 1700 | retryCount++; 1701 | xhr.open('GET', location.origin + location.pathname + '?p=' + curPage); 1702 | xhr.timeout = 30000; 1703 | xhr.send(); 1704 | } 1705 | else { 1706 | pushDialog('Failed!\nCan\'t get pages URL from response content.'); 1707 | isDownloading = false; 1708 | } 1709 | return; 1710 | } 1711 | 1712 | var list = new Function('return ' + listMatch[1])(); 1713 | 1714 | list.forEach(function (elem, index) { 1715 | var curURL = location.origin + '/s/' + elem.k + '/' + unsafeWindow.gid + '-' + (index + 1); 1716 | pageURLsList.push(curURL); 1717 | }); 1718 | pushDialog('Succeed!'); 1719 | 1720 | 1721 | // copied from getAllPagesURL(), THAT's UGLY!!! 1722 | // so when will 2.0 comes out /_\ 1723 | getAllPagesURLFin = true; 1724 | var wrongPages = pagesRange.filter(function (elem) { return elem > pageURLsList.length; }); 1725 | if (wrongPages.length !== 0) { 1726 | pagesRange = pagesRange.filter(function (elem) { return elem <= pageURLsList.length; }); 1727 | pushDialog('\nPage ' + wrongPages.join(', ') + (wrongPages.length > 1 ? ' are' : ' is') + ' not exist, and will be ignored.\n'); 1728 | if (pagesRange.length === 0) { 1729 | pushDialog('Nothing matches provided pages range, stop downloading.'); 1730 | alert('Nothing matches provided pages range, stop downloading.'); 1731 | if (emptyAudio) { 1732 | emptyAudio.pause(); 1733 | } 1734 | insertCloseButton(); 1735 | return; 1736 | } 1737 | } 1738 | totalCount = pagesRange.length || pageURLsList.length; 1739 | pushDialog('\n\n'); 1740 | initProgressTable(); 1741 | requestDownload(); 1742 | }; 1743 | xhr.send(); 1744 | pushDialog('Fetching Gallery Pages URL From MPV...'); 1745 | } 1746 | 1747 | // /*if pages range is set, then*/ get all pages URL to select needed pages 1748 | function getAllPagesURL() { 1749 | pagesRange = []; 1750 | var pagesRangeText = ehDownloadRange.querySelector('input').value.replace(/,/g, ',').trim(); 1751 | var retryCount = 0; 1752 | 1753 | if (pagesRangeText) { // if pages range is defined 1754 | console.log('[EHD] Pages Range >', pagesRangeText); 1755 | if (!ehDownloadRegex.pagesRange.test(pagesRangeText)) return alert('The format of Pages Range is incorrect.'); 1756 | 1757 | // range started with negative range, select all as default 1758 | if (pagesRangeText[0] === '!') { 1759 | pagesRangeText = '1-,' + pagesRangeText; 1760 | } 1761 | var rangeRegex = /!?(?:(\d*)-(\d*))(?:\/(\d+))?|!?(\d+)/g; 1762 | var matches; 1763 | var lastPage = getFileSizeAndLength().page; 1764 | 1765 | while (matches = rangeRegex.exec(pagesRangeText)) { 1766 | var selected = []; 1767 | var single = Number(matches[4]); 1768 | if (!isNaN(single)) { 1769 | selected.push(single); 1770 | } 1771 | else { 1772 | var begin = Number(matches[1]) || 1; 1773 | var end = Number(matches[2]) || lastPage; 1774 | if (begin > end) { 1775 | var tmp = begin; 1776 | begin = end; 1777 | end = tmp; 1778 | } 1779 | var mod = Number(matches[3]) || 1; 1780 | 1781 | for (var i = begin; i <= end; i += mod) { 1782 | selected.push(i); 1783 | } 1784 | } 1785 | 1786 | if (matches[0][0] === '!') { 1787 | pagesRange = pagesRange.filter(function (e) { 1788 | return selected.indexOf(e) < 0; 1789 | }); 1790 | } 1791 | else { 1792 | selected.forEach(function (e) { 1793 | pagesRange.push(e); 1794 | }); 1795 | } 1796 | } 1797 | 1798 | pagesRange.sort(function(a, b){ return a - b; }); 1799 | pagesRange = pagesRange.filter(function(e, i, arr) { return i == 0 || e != arr[i - 1] }); 1800 | } 1801 | 1802 | ehDownloadDialog.style.display = 'block'; 1803 | if (!getAllPagesURLFin) { 1804 | pageURLsList = []; 1805 | 1806 | if (isMPVAvailable()) { 1807 | console.log('[EHD] MPV is available, use MPV to fetch all pages'); 1808 | pushDialog('MPV is available, use MPV to fetch all pages.\n'); 1809 | return getPagesURLFromMPV(); 1810 | } 1811 | 1812 | var pagesLength; 1813 | try { // in case pages has been modified like #56 1814 | pagesLength = [].reduce.call(document.querySelectorAll('.ptt td'), function(x, y){ 1815 | var i = Number(y.textContent); 1816 | if (!isNaN(i)) return x > i ? x : i; 1817 | else return x; 1818 | }); 1819 | } 1820 | catch (error) {} 1821 | var curPage = 0; 1822 | retryCount = 0; 1823 | 1824 | var xhr = fetchPagesXHR; 1825 | xhr.onload = function(){ 1826 | var responseText = xhr.responseText; 1827 | if (xhr.status !== 200 || !responseText) { 1828 | if (retryCount < (setting['retry-count'] !== undefined ? setting['retry-count'] : 3)) { 1829 | pushDialog('Failed! Retrying... '); 1830 | retryCount++; 1831 | xhr.open('GET', location.origin + location.pathname + '?p=' + curPage); 1832 | xhr.timeout = 30000; 1833 | xhr.send(); 1834 | } 1835 | else { 1836 | pushDialog('Failed!\nFetch Pages\' URL failed, Please try again later.'); 1837 | isDownloading = false; 1838 | alert('Fetch Pages\' URL failed, Please try again later.'); 1839 | } 1840 | return; 1841 | } 1842 | 1843 | var pagesURL = responseText.split('
= 0) { 1862 | console.log('[EHD] Page 1 URL > ' + pagesURL[0] + ' , use MPV fetch'); 1863 | pushDialog('Pages URL is MPV link\n'); 1864 | 1865 | getPagesURLFromMPV(); 1866 | return; 1867 | } 1868 | 1869 | for (var i = 0; i < pagesURL.length; i++) { 1870 | pageURLsList.push(replaceHTMLEntites(pagesURL[i].split('"')[1])); 1871 | } 1872 | pushDialog('Succeed!'); 1873 | 1874 | curPage++; 1875 | 1876 | if (!pagesLength) { // can't get pagesLength correctly before 1877 | pagesLength = responseText.match(ehDownloadRegex.pagesLength)[1] - 0; 1878 | } 1879 | 1880 | if (curPage === pagesLength) { 1881 | getAllPagesURLFin = true; 1882 | var wrongPages = pagesRange.filter(function(elem){ return elem > pageURLsList.length; }); 1883 | if (wrongPages.length !== 0) { 1884 | pagesRange = pagesRange.filter(function(elem){ return elem <= pageURLsList.length; }); 1885 | pushDialog('\nPage ' + wrongPages.join(', ') + (wrongPages.length > 1 ? ' are' : ' is') + ' not exist, and will be ignored.\n'); 1886 | if (pagesRange.length === 0) { 1887 | pushDialog('Nothing matches provided pages range, stop downloading.'); 1888 | alert('Nothing matches provided pages range, stop downloading.'); 1889 | insertCloseButton(); 1890 | return; 1891 | } 1892 | } 1893 | totalCount = pagesRange.length || pageURLsList.length; 1894 | pushDialog('\n\n'); 1895 | initProgressTable(); 1896 | requestDownload(); 1897 | } 1898 | else { 1899 | xhr.open('GET', location.origin + location.pathname + '?p=' + curPage); 1900 | xhr.send(); 1901 | pushDialog('\nFetching Gallery Pages URL (' + (curPage + 1) + '/' + pagesLength + ') ... '); 1902 | } 1903 | }; 1904 | xhr.ontimeout = xhr.onerror = function(){ 1905 | if (retryCount < (setting['retry-count'] !== undefined ? setting['retry-count'] : 3)) { 1906 | pushDialog('Failed! Retrying... '); 1907 | retryCount++; 1908 | xhr.open('GET', location.origin + location.pathname + '?p=' + curPage); 1909 | xhr.timeout = 30000; 1910 | xhr.send(); 1911 | } 1912 | else { 1913 | pushDialog('Failed!\nFetch Pages\' URL failed, Please try again later.'); 1914 | isDownloading = false; 1915 | alert('Fetch Pages\' URL failed, Please try again later.'); 1916 | } 1917 | }; 1918 | xhr.open('GET', location.origin + location.pathname + '?p=' + curPage); 1919 | xhr.timeout = 30000; 1920 | xhr.send(); 1921 | pushDialog('\nFetching Gallery Pages URL (' + (curPage + 1) + '/' + (pagesLength || '?') + ') ... '); 1922 | } 1923 | else { 1924 | var wrongPages = pagesRange.filter(function(elem){ return elem > pageURLsList.length; }); 1925 | if (wrongPages.length !== 0) { 1926 | pagesRange = pagesRange.filter(function(elem){ return elem <= pageURLsList.length; }); 1927 | pushDialog('\nPage ' + wrongPages.join(', ') + (wrongPages.length > 1 ? ' are' : ' is') + ' not exist, and will be ignored.\n'); 1928 | if (pagesRange.length === 0) { 1929 | pushDialog('Nothing matches provided pages range, stop downloading.'); 1930 | alert('Nothing matches provided pages range, stop downloading.'); 1931 | insertCloseButton(); 1932 | return; 1933 | } 1934 | } 1935 | 1936 | totalCount = pagesRange.length || pageURLsList.length; 1937 | pushDialog('\n\n'); 1938 | initProgressTable(); 1939 | requestDownload(); 1940 | } 1941 | } 1942 | 1943 | function initEHDownload() { 1944 | for (var i = 0; i < fetchThread.length; i++) { 1945 | if (typeof fetchThread[i] !== 'undefined' && 'abort' in fetchThread[i]) fetchThread[i].abort(); 1946 | } 1947 | imageList = []; 1948 | imageData = []; 1949 | fetchThread = []; 1950 | retryCount = []; 1951 | downloadedCount = fetchCount = failedCount = 0; 1952 | isPausing = false; 1953 | zip = new JSZip(); 1954 | infoStr = ''; 1955 | fetchPagesXHR.abort(); 1956 | 1957 | if (setting['recheck-file-name']) { 1958 | var dirNameNode = document.querySelector('.ehD-box-extend-dirname'); 1959 | var fileNameNode = document.querySelector('.ehD-box-extend-filename'); 1960 | 1961 | if (dirNameNode && dirNameNode.value) { 1962 | dirName = getSafeName(dirNameNode.value, true); 1963 | } 1964 | else { 1965 | dirName = getReplacedName(!setting['dir-name'] ? '{gid}_{token}' : setting['dir-name']); 1966 | } 1967 | 1968 | if (fileNameNode && fileNameNode.value) { 1969 | fileName = getSafeName(fileNameNode.value); 1970 | } 1971 | else { 1972 | fileName = getReplacedName(!setting['file-name'] ? '{title}' : setting['file-name']); 1973 | } 1974 | } 1975 | else { 1976 | dirName = getReplacedName(!setting['dir-name'] ? '{gid}_{token}' : setting['dir-name']); 1977 | fileName = getReplacedName(!setting['file-name'] ? '{title}' : setting['file-name']); 1978 | } 1979 | 1980 | if (dirName.trim() === '/') dirName = ''; 1981 | needNumberImages = ehDownloadNumberInput.querySelector('input').checked; 1982 | 1983 | var requiredBytes = Math.ceil(getFileSizeAndLength().size + 100 * 1024); 1984 | var requiredMBs = getFileSizeAndLength().sizeMB + 0.1; 1985 | 1986 | var fsErrorHandler = function (error) { 1987 | ehDownloadFS.errorHandler(error); 1988 | 1989 | // roll back and use Blob to handle file 1990 | ehDownloadFS.needFileSystem = false; 1991 | alert('An error occured when requesting FileSystem.\n' + 1992 | 'Error Name: ' + (e.name || 'Unknown Error') + '\n' + 1993 | 'Error Message: ' + e.message + '\n\n' + 1994 | 'Roll back and use Blob to handle file.'); 1995 | }; 1996 | 1997 | if ((!setting['store-in-fs'] && !setting['never-warn-large-gallery'] && requiredMBs >= 300) && !confirm('This archive is too large (original size), please consider downloading this archive in a different way.\n\nMaximum allowed file size: Chrome 56- 500MB | Chrome 57+ 2 GB | Firefox ~800 MB (depends on your RAM)\n\nPlease also consider your operating system\'s free memory (RAM), it may take about DOUBLE the size of archive file size when generating ZIP file.\n\n* If you continue, you would probably get an error like "Failed - No File" or "Out Of Memory" if you don\'t have enough RAM and can\'t save the file successfully.\n\n* If you are using Chrome, you can try enabling "Request File System to handle large Zip file" on the settings page.\n\n* You can set Pages Range to download this archive in parts. If you have already enabled it, please ignore this message.\n\nAre you sure to continue downloading?')) return; 1998 | else if (setting['store-in-fs'] && requestFileSystem && requiredMBs >= (setting['fs-size'] !== undefined ? setting['fs-size'] : 200)) { 1999 | ehDownloadFS.needFileSystem = true; 2000 | console.log('[EHD] Required File System Space >', requiredBytes); 2001 | 2002 | // Chrome can use about 10% of free space of disk where Chrome User Data stored in as TEMPORARY File System Storage. 2003 | if (navigator.webkitTemporaryStorage) { // if support navigator.webkitTemporaryStorage to check usable space 2004 | // use `queryUsageAndQuota` instead of `requestQuota` to check storage space, 2005 | // because `requestQuota` is incorrect when harddisk is full, says have about 5GB storage 2006 | navigator.webkitTemporaryStorage.queryUsageAndQuota(function (usage, quota) { 2007 | console.log('[EHD] Free TEMPORARY File System Space >', quota - usage); 2008 | if (quota - usage < requiredBytes) { 2009 | console.log('[EHD] Free TEMPORARY File System Space is not enough.'); 2010 | 2011 | // free space is not enough, then use persistent space 2012 | // in fact, free space of persisent file storage is always 10GiB, even free disk space is not enough 2013 | navigator.webkitPersistentStorage.queryUsageAndQuota(function (usage, quota) { 2014 | console.log('[EHD] Free PERSISTENT File System Space >', quota - usage); 2015 | if (quota - usage < requiredBytes) { 2016 | // roll back and use Blob to handle file 2017 | ehDownloadFS.needFileSystem = false; 2018 | alert('You don\'t have enough free space on the drive where Chrome stores user data (Default is system drive, normally it\'s C: ), please delete some files.\n\nNeeds more than ' + (requiredBytes - (quota - usage)) + ' Bytes.\n\nRoll back and use Blob to handle file.'); 2019 | } 2020 | else { 2021 | pushDialog('\nPlease allow storing large content if the browser asked for it.\n'); 2022 | requestFileSystem(window.PERSISTENT, requiredBytes, ehDownloadFS.initHandler, fsErrorHandler); 2023 | } 2024 | }, fsErrorHandler); 2025 | } 2026 | else requestFileSystem(window.TEMPORARY, requiredBytes, ehDownloadFS.initHandler, fsErrorHandler); 2027 | }, fsErrorHandler); 2028 | } 2029 | else requestFileSystem(window.TEMPORARY, requiredBytes, ehDownloadFS.initHandler, fsErrorHandler); 2030 | } 2031 | 2032 | // Array.prototype.some() is a bit ugly, so we use toString().indexOf() lol 2033 | var infoNeeds = setting['save-info-list'].toString(); 2034 | if (infoNeeds.indexOf('title') >= 0) { 2035 | infoStr += replaceHTMLEntites( 2036 | document.getElementById('gn').textContent + '\n' + 2037 | document.getElementById('gj').textContent + '\n' + 2038 | window.location.href + '\n\n' 2039 | ); 2040 | } 2041 | 2042 | if (infoNeeds.indexOf('metas') >= 0) { 2043 | infoStr += 'Category: ' + document.querySelector('#gdc .cs').textContent.trim() + '\n' + 2044 | 'Uploader: ' + replaceHTMLEntites(document.querySelector('#gdn').textContent) + '\n'; 2045 | } 2046 | var metaNodes = document.querySelectorAll('#gdd tr'); 2047 | for (var i = 0; i < metaNodes.length; i++) { 2048 | var c1 = replaceHTMLEntites(metaNodes[i].getElementsByClassName('gdt1')[0].textContent); 2049 | var c2 = replaceHTMLEntites(metaNodes[i].getElementsByClassName('gdt2')[0].textContent); 2050 | if (infoNeeds.indexOf('metas') >= 0) infoStr += c1 + ' ' + c2 + '\n'; 2051 | } 2052 | if (infoNeeds.indexOf('metas') >= 0) infoStr += 'Rating: ' + unsafeWindow.average_rating + '\n\n'; 2053 | 2054 | if (infoNeeds.indexOf('tags') >= 0) { 2055 | infoStr += 'Tags:\n'; 2056 | 2057 | var tagsList = document.querySelectorAll('#taglist tr'); 2058 | Array.prototype.forEach.call(tagsList, function(elem){ 2059 | var tds = elem.getElementsByTagName('td'); 2060 | infoStr += '> ' + tds[0].textContent + ' '; 2061 | 2062 | var tags = tds[1].querySelectorAll('a'); 2063 | infoStr += Array.prototype.map.call(tags, function(e){ 2064 | return e.textContent; 2065 | }).join(', ') + '\n'; 2066 | }); 2067 | 2068 | infoStr += '\n'; 2069 | } 2070 | 2071 | if (infoNeeds.indexOf('uploader-comment') >= 0 && document.getElementById('comment_0')) { 2072 | infoStr += 'Uploader Comment:\n' + document.getElementById('comment_0').innerHTML.replace(/
|
/gi, '\n') + '\n\n'; 2073 | } 2074 | isDownloading = true; 2075 | pushDialog(infoStr); 2076 | 2077 | pushDialog('Start downloading at ' + new Date() + '\n'); 2078 | ehDownloadDialog.appendChild(ehDownloadStatus); 2079 | 2080 | // get all pages url to fix 403 forbidden (download request was timed out) 2081 | getAllPagesURL(); 2082 | 2083 | // init playing music 2084 | if (setting['play-silent-music'] && !emptyAudio) { 2085 | emptyAudio = new Audio(emptyAudioFile); 2086 | emptyAudio.loop = true; 2087 | } 2088 | } 2089 | 2090 | function initVisibilityListener() { 2091 | var hidden, visibilityChange; 2092 | if (typeof document.hidden !== 'undefined') { // Opera 12.10 and Firefox 18 and later support 2093 | hidden = 'hidden'; 2094 | visibilityChange = 'visibilitychange'; 2095 | } 2096 | else if (typeof document.mozHidden !== 'undefined') { 2097 | hidden = 'mozHidden'; 2098 | visibilityChange = 'mozvisibilitychange'; 2099 | } 2100 | else if (typeof document.webkitHidden !== 'undefined') { 2101 | hidden = 'webkitHidden'; 2102 | visibilityChange = 'webkitvisibilitychange'; 2103 | } 2104 | 2105 | var visibilityChangeHandler = function (isHidden) { 2106 | if (typeof isHidden !== 'boolean') { 2107 | isHidden = document[hidden]; 2108 | } 2109 | visibleState = !isHidden; 2110 | if (!emptyAudio) { 2111 | return; 2112 | } 2113 | if (isHidden && ((isDownloading && !isPausing) || isSaving)) { 2114 | emptyAudio.play(); 2115 | } 2116 | else { 2117 | emptyAudio.pause(); 2118 | loadImageLimits(); 2119 | } 2120 | }; 2121 | 2122 | if (visibilityChange) { 2123 | window.addEventListener(visibilityChange, visibilityChangeHandler); 2124 | } 2125 | else { 2126 | window.addEventListener('focus', function () { 2127 | visibilityChangeHandler(false); 2128 | }); 2129 | window.addEventListener('blur', function () { 2130 | visibilityChangeHandler(true); 2131 | }); 2132 | } 2133 | 2134 | visibilityChangeHandler(); 2135 | } 2136 | 2137 | function initProgressTable(){ 2138 | progressTable = document.createElement('table'); 2139 | progressTable.className = 'ehD-pt'; 2140 | ehDownloadDialog.style.display = 'block'; 2141 | ehDownloadDialog.appendChild(progressTable); 2142 | ehDownloadDialog.appendChild(forceDownloadTips); 2143 | ehDownloadDialog.appendChild(ehDownloadPauseBtn); 2144 | ehDownloadDialog.scrollTop = ehDownloadDialog.scrollHeight; 2145 | } 2146 | 2147 | function requestDownload(ignoreFailed){ 2148 | if (isPausing) return; 2149 | 2150 | if (setting['delay-request']) { 2151 | var curTime = Date.now(); 2152 | if (delayTime < curTime) { 2153 | delayTime = curTime; 2154 | } 2155 | } 2156 | 2157 | var j = 0; 2158 | for (var i = fetchCount; i < (setting['thread-count'] !== undefined ? setting['thread-count'] : 5); i++) { 2159 | for (/*var j = 0*/; j < totalCount; j++) { 2160 | if (imageData[j] == null && (ignoreFailed || (retryCount[j] || 0) <= (setting['retry-count'] !== undefined ? setting['retry-count'] : 3))) { 2161 | imageData[j] = 'Fetching'; 2162 | if (imageList[j] && setting['never-new-url']) fetchOriginalImage(j); 2163 | else if (setting['delay-request']) { 2164 | setTimeout(function(j) { 2165 | if (isPausing || fetchCount >= (setting['thread-count'] !== undefined ? setting['thread-count'] : 5)) { 2166 | imageData[j] = null; 2167 | return; 2168 | } 2169 | getPageData(j); 2170 | fetchCount++; 2171 | }, delayTime - curTime + setting['delay-request'] * 1000, j); 2172 | delayTime += setting['delay-request'] * 1000; 2173 | } 2174 | else { 2175 | getPageData(j); 2176 | fetchCount++; 2177 | } 2178 | break; 2179 | } 2180 | } 2181 | } 2182 | 2183 | } 2184 | 2185 | function getPageData(index) { 2186 | if (isPausing) return; 2187 | 2188 | if (pagesRange.length) var realIndex = pagesRange[index]; 2189 | else var realIndex = index + 1; 2190 | 2191 | var needScrollIntoView = ehDownloadDialog.clientHeight + ehDownloadDialog.scrollTop >= ehDownloadDialog.scrollHeight - 5; 2192 | 2193 | var node = progressTable.querySelector('tr[data-index="' + index + '"]'); 2194 | if (!node) { 2195 | node = document.createElement('tr'); 2196 | node.className = 'ehD-pt-item'; 2197 | node.setAttribute('data-index', index); 2198 | node.innerHTML = '\ 2199 |
\ 2200 | \ 2204 | '; 2208 | progressTable.appendChild(node); 2209 | } 2210 | if (needScrollIntoView) { 2211 | ehDownloadDialog.scrollTop = ehDownloadDialog.scrollHeight; 2212 | } 2213 | 2214 | var nodeList = { 2215 | current: node, 2216 | fileName: node.getElementsByTagName('td')[0], 2217 | status: node.getElementsByTagName('td')[2], 2218 | statusText: node.getElementsByClassName('ehD-pt-status-text')[0], 2219 | progress: node.getElementsByTagName('progress')[0], 2220 | progressText: node.getElementsByTagName('span')[0], 2221 | abort: node.getElementsByClassName('ehD-pt-abort')[0] 2222 | }; 2223 | 2224 | retryCount[index] = 0; 2225 | var fetchURL = replaceHTMLEntites(imageList[index] ? ( 2226 | imageList[index]['pageURL'] + ( 2227 | (!setting['never-send-nl'] && imageList[index]['nextNL']) ? ( 2228 | imageList[index]['pageURL'].indexOf('?') >= 0 ? '&' : '?' 2229 | ) + 'nl=' + imageList[index]['nextNL'] : '' 2230 | ) 2231 | ) : pageURLsList[realIndex - 1])/*.replace(/^https?:/, '')*/; 2232 | 2233 | // assign to fetchThread, so that we can abort them and all GM_xhr by one command fetchThread[i].abort() 2234 | var xhr = fetchThread[index] = new XMLHttpRequest(); 2235 | xhr.onload = function() { 2236 | var responseText = xhr.responseText; 2237 | if (xhr.status !== 200 || !responseText) { 2238 | if (retryCount[index] < (setting['retry-count'] !== undefined ? setting['retry-count'] : 3)) { 2239 | retryCount[index]++; 2240 | 2241 | updateProgress(nodeList, { 2242 | status: 'Retrying (' + retryCount[index] + '/' + (setting['retry-count'] !== undefined ? setting['retry-count'] : 3) + ')...', 2243 | progress: '', 2244 | progressText: '', 2245 | class: 'ehD-pt-warning' 2246 | }); 2247 | 2248 | xhr.open('GET', fetchURL); 2249 | xhr.timeout = 30000; 2250 | xhr.send(); 2251 | } 2252 | else { 2253 | failedCount++; 2254 | fetchCount--; 2255 | 2256 | console.error('[EHD] #' + realIndex + ': Failed getting image URL'); 2257 | updateProgress(nodeList, { 2258 | status: 'Failed getting URL', 2259 | progress: '0', 2260 | progressText: '', 2261 | class: 'ehD-pt-failed' 2262 | }); 2263 | updateTotalStatus(); 2264 | 2265 | checkFailed(); 2266 | } 2267 | 2268 | return; 2269 | } 2270 | 2271 | try { 2272 | var imageURL = replaceHTMLEntites( 2273 | ( 2274 | (unsafeWindow.apiuid !== -1 || setting['force-as-login']) 2275 | && ehDownloadRegex.imageURL[0].test(responseText) 2276 | && !setting['force-resized'] 2277 | ) ? responseText.match(ehDownloadRegex.imageURL[0])[1] : ( 2278 | responseText.indexOf('id="img"') > -1 2279 | ? responseText.match(ehDownloadRegex.imageURL[1])[1] 2280 | : responseText.match(ehDownloadRegex.imageURL[2])[1] 2281 | ) 2282 | ); 2283 | // append nl to original image in case it fails to load from H@H (wtf it's valid?!) 2284 | if (ehDownloadRegex.originalImagePattern.test(imageURL)) { 2285 | imageURL = imageURL + ( 2286 | (imageList[index] && !setting['never-send-nl'] && imageList[index]['nextNL']) ? ( 2287 | imageURL.indexOf('?') >= 0 ? '&' : '?' 2288 | ) + 'nl=' + imageList[index]['nextNL'] : '' 2289 | ); 2290 | } 2291 | var fileName = replaceHTMLEntites(responseText.match(ehDownloadRegex.fileName)[1]); 2292 | var nextNL = ehDownloadRegex.nl.test(responseText) ? responseText.match(ehDownloadRegex.nl)[1] : null; 2293 | } 2294 | catch (error) { 2295 | console.error('[EHD] Response content is not correct!', error); 2296 | if (retryCount[index] < (setting['retry-count'] !== undefined ? setting['retry-count'] : 3)) { 2297 | retryCount[index]++; 2298 | 2299 | updateProgress(nodeList, { 2300 | status: 'Retrying (' + retryCount[index] + '/' + (setting['retry-count'] !== undefined ? setting['retry-count'] : 3) + ')...', 2301 | progress: '', 2302 | progressText: '', 2303 | class: 'ehD-pt-warning' 2304 | }); 2305 | 2306 | xhr.open('GET', fetchURL); 2307 | xhr.timeout = 30000; 2308 | xhr.send(); 2309 | } 2310 | else { 2311 | failedCount++; 2312 | fetchCount--; 2313 | 2314 | console.error('[EHD] #' + realIndex + ': Can\'t get request content from response content'); 2315 | updateProgress(nodeList, { 2316 | status: 'Response Error', 2317 | progress: '0', 2318 | progressText: '', 2319 | class: 'ehD-pt-failed' 2320 | }); 2321 | updateTotalStatus(); 2322 | //alert('We can\'t get request content from response content. It\'s possible that E-Hentai changes source code format so that we can\'t find them, or your ISP modifies (or say hijacks) the page content. If it\'s sure that you can access to any pages of E-Hentai, including current page: ' + fetchURL + ' , please report a bug.'); 2323 | 2324 | checkFailed(); 2325 | } 2326 | return; 2327 | } 2328 | 2329 | var imageNumber = ''; 2330 | if (needNumberImages) { 2331 | // Number images, thanks to JingJang@GitHub, source: https://github.com/JingJang/E-Hentai-Downloader 2332 | if (!setting['number-real-index'] && pagesRange.length) { // if pages range was set and number original index is not required 2333 | var len = pagesRange.length.toString().length, 2334 | padding = new Array(len < 3 ? len + 1 : len).join('0'); 2335 | imageNumber = (padding + (index + 1)).slice(0 - len); 2336 | } 2337 | else { // pages range was not set (download all pages, so index + 1 === realIndex) or number original index is required 2338 | var len = pageURLsList.length.toString().length, 2339 | padding = new Array(len < 3 ? len + 1 : len).join('0'); 2340 | imageNumber = (padding + realIndex).slice(0 - len); 2341 | } 2342 | } 2343 | 2344 | //imageList.push(new PageData(fetchURL, imageURL, fileName, nextNL, realIndex)); 2345 | imageList[index] = new PageData(fetchURL, imageURL, fileName, nextNL, realIndex, imageNumber); 2346 | 2347 | if (isPausing) { 2348 | updateProgress(nodeList, { 2349 | name: '#' + realIndex + ': ' + fileName, 2350 | status: 'Auto Paused', 2351 | progress: '', 2352 | progressText: '', 2353 | class: 'ehD-pt-failed' 2354 | }); 2355 | fetchCount--; 2356 | imageData[index] = null; 2357 | 2358 | updateTotalStatus(); 2359 | } 2360 | else { 2361 | fetchOriginalImage(index, nodeList); 2362 | } 2363 | 2364 | }; 2365 | xhr.onerror = xhr.ontimeout = function() { 2366 | if (retryCount[index] < (setting['retry-count'] !== undefined ? setting['retry-count'] : 3)) { 2367 | retryCount[index]++; 2368 | 2369 | updateProgress(nodeList, { 2370 | status: 'Retrying (' + retryCount[index] + '/' + (setting['retry-count'] !== undefined ? setting['retry-count'] : 3) + ')...', 2371 | progress: '', 2372 | progressText: '', 2373 | class: 'ehD-pt-warning' 2374 | }); 2375 | 2376 | xhr.open('GET', fetchURL); 2377 | xhr.timeout = 30000; 2378 | xhr.send(); 2379 | } 2380 | else { 2381 | failedCount++; 2382 | fetchCount--; 2383 | 2384 | console.error('[EHD] #' + realIndex + ': Failed getting image URL'); 2385 | updateProgress(nodeList, { 2386 | status: 'Failed getting URL', 2387 | progress: '0', 2388 | progressText: '', 2389 | class: 'ehD-pt-failed' 2390 | }); 2391 | updateTotalStatus(); 2392 | 2393 | checkFailed(); 2394 | } 2395 | }; 2396 | 2397 | xhr.open('GET', fetchURL); 2398 | xhr.timeout = 30000; 2399 | xhr.send(); 2400 | 2401 | nodeList.abort.addEventListener('click', function () { 2402 | if (!isDownloading || imageData[index] instanceof ArrayBuffer) return; // Temporarily fixes #31 2403 | 2404 | if (typeof fetchThread[index] !== 'undefined' && 'abort' in fetchThread[index]) fetchThread[index].abort(); 2405 | 2406 | console.log('[EHD] #' + (index + 1) + ': Force Aborted By User'); 2407 | updateProgress(nodeList, { 2408 | status: 'Failed! (User Aborted)', 2409 | progress: '0', 2410 | progressText: '', 2411 | class: 'ehD-pt-warning' 2412 | }); 2413 | 2414 | failedFetching(index, nodeList); 2415 | }); 2416 | 2417 | nodeList.status.setAttribute('data-inited-abort', '1'); 2418 | } 2419 | 2420 | function showSettings() { 2421 | var ehDownloadSettingPanel = document.createElement('div'); 2422 | ehDownloadSettingPanel.className = 'ehD-setting'; 2423 | ehDownloadSettingPanel.setAttribute('data-active-setting', 'basic'); 2424 | ehDownloadSettingPanel.innerHTML = '\ 2425 |
    \ 2426 |
  • Basic
  • \ 2427 |
  • Advanced
  • \ 2428 |
\ 2429 |
\ 2430 | ' + ehDownloadArrow + ' Feedback\ 2431 | GitHub\ 2432 | GreasyFork\ 2433 |
\ 2434 |
\ 2435 |
\ 2436 |
\ 2437 |
\ 2438 |
\ 2439 |
\ 2440 |
\ 2441 |
\ 2442 |
\ 2443 |
\ 2444 |
\ 2445 |
\ 2446 |
\ 2447 |
\ 2448 |
\ 2449 |
\ 2450 |
\ 2451 |
\ 2452 |
\ 2453 | \ 2454 |
\ 2455 |
\ 2456 | * Available templates: \ 2457 | {gid} Gallery GID | \ 2458 | {token} Gallery token | \ 2459 | {title} Gallery title | \ 2460 | {subtitle} Gallery sub-title | \ 2461 | {tag}, {category} Gallery category | \ 2462 | {uploader} Gallery uploader\ 2463 |
\ 2464 |
\ 2465 |
\ 2466 |
\ 2467 |
(1)
\ 2468 |
(2)
\ 2469 |
\ 2470 |
(3)
\ 2471 |
(3)
\ 2472 |
\ 2473 |
\ 2474 |
\ 2475 |
(4)
\ 2476 |
(5)
\ 2477 |
\ 2478 |
...which includes
\ 2479 |
\ 2480 |
\ 2481 |
\ 2482 |
\ 2483 |
\ 2484 |
\ 2485 |
\ 2486 |
\ 2487 | (1) Higher compression level can get smaller file without lossing any data, but may takes more time. If you have a decent CPU you can set it higher, and if you\'re using macOS set it to at least 1.\ 2488 |
\ 2489 |
\ 2490 | (2) This may reduce memory usage but some decompress softwares may not support the Zip file. See JSZip Docs for more info.\ 2491 |
\ 2492 |
\ 2493 | (3) Enable these option will never let you to load from regular image server (or say force loaded from H@H). This may save your image viewing limits (See wiki), but may also cause some download problems, especially if your network cannot connect to specific H@H node.\ 2494 |
\ 2495 |
\ 2496 | (4) If enabled you can save larger Zip files (probably ~1GB).\ 2497 |
\ 2498 |
\ 2499 | (5) If enabled the script will play slient music to avoid downloading freeze when page is in background (See issue). Only needed if you have the problem, because the audio-playing icon maybe annoying.\ 2500 |
\ 2501 |
\ 2502 | (6) Comic book archive is a file type to archive comic images, you can open it with some comic viewer like CDisplay/CDisplayEX, or just extract it as a Zip file. To keep the order of images, you can also enable numbering images.\ 2503 |
\ 2504 |
\ 2505 | (7) If you cannot original images, but you\'ve already logged in and your account is not blocked or used up your limits, it may caused by your cookies is not sent to the server. This feature may helps you to pass your current cookies to the download request, but please enable it ONLY if you cannot download any original images.\ 2506 |
\ 2507 |
\ 2508 | (8) If you have already logged in, but the script detects that you\'re not logged in, you can enable this to skip login check. Please note that if you are not logged in actually, the script will not work as expect.\ 2509 |
\ 2510 |
\ 2511 | (9) If you have problem to download on the same site, like account session is misleading, you can force redirect original download link to another domain. Pass cookies manually may be needed.\ 2512 |
\ 2513 |
\ 2514 |
\ 2515 |
\ 2516 |
\ 2517 | '; 2520 | document.body.appendChild(ehDownloadSettingPanel); 2521 | 2522 | for (var i in setting) { 2523 | if (setting[i] instanceof Array) { 2524 | setting[i].forEach(function(elem){ 2525 | var element = ehDownloadSettingPanel.querySelector('input[data-ehd-setting="' + i + '[]"][value="' + elem + '"], select[data-ehd-setting="' + i + '[]"] option[value="' + elem + '"]'); 2526 | if (!element) return; 2527 | 2528 | if (element.getAttribute('type') === 'checkbox') { 2529 | element.setAttribute('checked', 'checked'); 2530 | } 2531 | else if (element.tagName.toLowerCase() === 'option') { 2532 | element.setAttribute('selected', 'selected'); 2533 | } 2534 | else element.value = elem; 2535 | }); 2536 | } 2537 | else { 2538 | var element = ehDownloadSettingPanel.querySelector('input[data-ehd-setting="' + i + '"], select[data-ehd-setting="' + i + '"]'); 2539 | if (!element) continue; 2540 | if (element.getAttribute('type') === 'checkbox') { 2541 | if (setting[i]) element.setAttribute('checked', 'checked'); 2542 | } 2543 | else if (element.tagName.toLowerCase() === 'select') { 2544 | element = element.querySelector('option[value="' + setting[i] + '"]'); 2545 | if (!element) continue; 2546 | element.setAttribute('selected', 'selected'); 2547 | } 2548 | else element.setAttribute('value', setting[i]); 2549 | } 2550 | } 2551 | 2552 | ehDownloadSettingPanel.getElementsByClassName('ehD-setting-tab')[0].addEventListener('click', function(event){ 2553 | var target = event.target; 2554 | if (target.tagName.toLowerCase() === 'li') { 2555 | ehDownloadSettingPanel.setAttribute('data-active-setting', target.dataset.targetSetting); 2556 | } 2557 | }); 2558 | 2559 | ehDownloadSettingPanel.getElementsByClassName('ehD-setting-footer')[0].addEventListener('click', function(event){ 2560 | var target = event.target; 2561 | if (target.tagName.toLowerCase() === 'button') { 2562 | if (target.dataset.action === 'save') { 2563 | var inputs = ehDownloadSettingPanel.querySelectorAll('input[data-ehd-setting], select[data-ehd-setting]'); 2564 | setting = {}; 2565 | for (var i = 0; i < inputs.length; i++) { 2566 | if (inputs[i].getAttribute('type') !== 'checkbox' && inputs[i].value === '') continue; 2567 | 2568 | var curSettingName = inputs[i].dataset.ehdSetting; 2569 | 2570 | if (inputs[i].getAttribute('type') === 'checkbox') { 2571 | if (inputs[i].checked) { 2572 | if (inputs[i].hasAttribute('value')) { 2573 | if (curSettingName.indexOf('[]') >= 0) { 2574 | curSettingName = curSettingName.split('[]')[0]; 2575 | if (!setting[curSettingName]) setting[curSettingName] = []; 2576 | setting[curSettingName].push(inputs[i].getAttribute('value')); 2577 | } 2578 | else { 2579 | setting[curSettingName] = inputs[i].getAttribute('value'); 2580 | } 2581 | } 2582 | else { 2583 | setting[curSettingName] = inputs[i].checked; 2584 | } 2585 | } 2586 | else { 2587 | setting[curSettingName] = inputs[i].checked; 2588 | } 2589 | } 2590 | else if (inputs[i].getAttribute('type') === 'number') { 2591 | setting[curSettingName] = Number(inputs[i].value); 2592 | if (isNaN(setting[curSettingName])) { 2593 | setting[curSettingName] = Number(inputs[i].getAttribute('placeholder')); 2594 | } 2595 | } 2596 | else { 2597 | setting[curSettingName] = inputs[i].value; 2598 | } 2599 | } 2600 | GM_setValue('ehD-setting', JSON.stringify(setting)); 2601 | } 2602 | document.body.removeChild(ehDownloadSettingPanel); 2603 | 2604 | if (document.querySelector('.ehD-box-extend')) { 2605 | toggleFilenameConfirmInput('reset'); 2606 | } 2607 | else { 2608 | toggleFilenameConfirmInput(!setting['recheck-file-name']); 2609 | } 2610 | 2611 | // ehDownloadBox.classList[setting['actions-sticky'] ? 'add' : 'remove']('ehD-box-sticky'); 2612 | 2613 | try { 2614 | showPreCalcCost(); 2615 | } 2616 | catch (e) { } 2617 | } 2618 | }); 2619 | 2620 | Array.prototype.forEach.call(ehDownloadSettingPanel.getElementsByClassName('ehD-setting-content'), function(elem) { 2621 | elem.addEventListener('focusin', function(event){ 2622 | ehDownloadSettingPanel.setAttribute('data-active-setting', this.dataset.settingPage); 2623 | // prevent auto-scroll from browser 2624 | ehDownloadSettingPanel.scrollLeft = 0; 2625 | }, true); 2626 | }); 2627 | } 2628 | 2629 | function getImageLimits() { 2630 | var host = host || location.hostname; 2631 | if (host === 'exhentai.org') { 2632 | host = 'e-hentai.org'; 2633 | } 2634 | 2635 | var preData = JSON.parse(localStorage.getItem('ehd-image-limits-' + host) || '{"timestamp":0}'); 2636 | return preData; 2637 | } 2638 | 2639 | function loadImageLimits(forced, host){ 2640 | if (!visibleState) { 2641 | return; 2642 | } 2643 | var host = host || location.hostname; 2644 | if (host === 'exhentai.org') { 2645 | host = 'e-hentai.org'; 2646 | } 2647 | var url = 'https://' + host + '/home.php'; 2648 | 2649 | var preData = getImageLimits(); 2650 | if (!forced && new Date() - preData.timestamp < 30000) { 2651 | return showImageLimits(); 2652 | } 2653 | 2654 | console.log('[EHD] Request Image Limits From ' + host); 2655 | 2656 | GM_xmlhttpRequest({ 2657 | method: 'GET', 2658 | url: url, 2659 | timeout: 300000, 2660 | onload: function(res) { 2661 | var responseText = res.responseText; 2662 | if (!responseText) return; 2663 | preData.timestamp = new Date().getTime(); 2664 | if (responseText.indexOf('as your account has been suspended') >= 0) { 2665 | preData.suspended = true; 2666 | } 2667 | else if (responseText.indexOf('Your IP address has been temporarily banned') >= 0) { 2668 | preData.ipBanned = true; 2669 | } 2670 | else { 2671 | var data = responseText.match(ehDownloadRegex.imageLimits); 2672 | if (!data || data.length < 3) return; 2673 | preData.cur = +data[1].replace(/,/g, ''); 2674 | preData.total = +data[2].replace(/,/g, ''); 2675 | 2676 | var donatorPower = responseText.match(ehDownloadRegex.donatorPower); 2677 | if (!donatorPower || donatorPower.length < 2) return; 2678 | preData.donatorPower = +donatorPower[1]; 2679 | delete preData.suspended; 2680 | delete preData.ipBanned; 2681 | } 2682 | console.log('[EHD] Image Limits >', JSON.stringify(preData)); 2683 | localStorage.setItem('ehd-image-limits-' + host, JSON.stringify(preData)); 2684 | showImageLimits(); 2685 | } 2686 | }); 2687 | } 2688 | 2689 | function showImageLimits(){ 2690 | // tor doesn't count to normal account since the ip is dynamic, but not sure if it counts for donator/hath perk account 2691 | // if (isTor) { 2692 | // return; 2693 | // } 2694 | 2695 | var list = Object.keys(localStorage).filter(function(elem){ 2696 | return elem.indexOf('ehd-image-limits-') === 0; 2697 | }).sort().map(function(elem){ 2698 | var curData = JSON.parse(localStorage.getItem(elem)); 2699 | if (curData.suspended) { 2700 | return '! Account Suspended !'; 2701 | } 2702 | if (curData.ipBanned) { 2703 | return '! IP Banned !'; 2704 | } 2705 | if (+curData.cur >= +curData.total) { 2706 | return '' + curData.cur + '/' + curData.total + '' 2707 | } 2708 | return curData.cur + '/' + curData.total; 2709 | }); 2710 | 2711 | ehDownloadBox.getElementsByClassName('ehD-box-limit')[0].innerHTML = ' | Image Limits: ' + list.join('; ') + ''; 2712 | } 2713 | 2714 | function getFileSizeAndLength() { 2715 | // TODO: use api.php if fails 2716 | var context = (document.getElementById('gdd') || {}).textContent || ''; 2717 | var sizeText = ((context.split('File Size:')[1] || '').split('Length:')[0] || '').trim(); 2718 | var pageText = ((context.split('Length:')[1] || '').split('page')[0] || '').trim() || 2719 | ((document.querySelector('.gpc') || {}).textContent.split('of').pop().split('images').shift() || '').trim(); 2720 | 2721 | var sizeMB, sizeKB; 2722 | var page = pageText - 0; 2723 | 2724 | if (/Mi?B/.test(sizeText)) { 2725 | sizeMB = parseFloat(sizeText) + 0.01; 2726 | sizeKB = sizeMB * 1024; 2727 | } 2728 | else if (/Gi?B/.test(sizeText)) { 2729 | sizeMB = (parseFloat(sizeText) + 0.01) * 1024; 2730 | sizeKB = sizeMB * 1024; 2731 | } 2732 | else { 2733 | sizeMB = 1; 2734 | sizeKB = parseFloat(sizeText); 2735 | } 2736 | 2737 | var result = { 2738 | sizeMB: sizeMB, 2739 | sizeKB: sizeKB, 2740 | size: sizeKB * 1024, 2741 | page: page 2742 | }; 2743 | 2744 | getFileSizeAndLength = function(){ 2745 | return result; 2746 | }; 2747 | 2748 | return result; 2749 | }; 2750 | 2751 | function toggleFilenameConfirmInput(hide){ 2752 | var extendNodes = document.querySelector('.ehD-box-extend'); 2753 | if (extendNodes) { 2754 | if (hide === 'reset') { 2755 | ehDownloadBox.removeChild(extendNodes); 2756 | if (setting['recheck-file-name']) toggleFilenameConfirmInput(); 2757 | } 2758 | else if (hide) { 2759 | extendNodes.style.display = 'none'; 2760 | } 2761 | else { 2762 | extendNodes.style.display = 'block'; 2763 | } 2764 | } 2765 | else if (!hide) { 2766 | extendNodes = document.createElement('div'); 2767 | extendNodes.className = 'ehD-box-extend'; 2768 | extendNodes.innerHTML = '
' + ehDownloadArrow + '
' + 2769 | '
' + ehDownloadArrow + '
'; 2770 | ehDownloadBox.appendChild(extendNodes); 2771 | 2772 | dirName = getReplacedName(!setting['dir-name'] ? '{gid}_{token}' : setting['dir-name']); 2773 | fileName = getReplacedName(!setting['file-name'] ? '{title}' : setting['file-name']); 2774 | extendNodes.getElementsByClassName('ehD-box-extend-filename')[0].value = fileName; 2775 | extendNodes.getElementsByClassName('ehD-box-extend-dirname')[0].value = dirName; 2776 | } 2777 | } 2778 | 2779 | function getResolutionSetting(forced){ 2780 | var url = '/uconfig.php'; 2781 | 2782 | var preData = JSON.parse(localStorage.getItem('ehd-resolution') || '{"timestamp":0}'); 2783 | if (!forced && new Date() - preData.timestamp < 3600e3) { 2784 | return; 2785 | } 2786 | 2787 | // tor site don't have original image feature 2788 | if (isTor) { 2789 | localStorage.setItem('ehd-resolution', JSON.stringify({ 2790 | withoutHentaiAtHome: 0, 2791 | resolution: 0, 2792 | timestamp: Date.now() 2793 | })); 2794 | return; 2795 | } 2796 | 2797 | console.log('[EHD] Request Resolution Setting'); 2798 | 2799 | var xhr = new XMLHttpRequest(); 2800 | xhr.onload = function() { 2801 | var responseText = xhr.responseText; 2802 | if (!responseText) return; 2803 | var preData = { 2804 | withoutHentaiAtHome: +((responseText.match(/id="uh_(\d)" checked/) || [])[1] || 0), 2805 | resolution: +((responseText.match(/id="xr_(\d)" checked/) || [])[1] || 0), 2806 | originalImages: +((responseText.match(/id="oi_(\d)".*? checked/) || [])[1] || 0), 2807 | mpvAvailable: responseText.indexOf('name="qb"') >= 0, 2808 | timestamp: Date.now() 2809 | }; 2810 | console.log('[EHD] Resolution Setting >', JSON.stringify(preData)); 2811 | localStorage.setItem('ehd-resolution', JSON.stringify(preData)); 2812 | try { 2813 | showPreCalcCost(); 2814 | } 2815 | catch (e) { } 2816 | }; 2817 | xhr.open('GET', url); 2818 | xhr.send(); 2819 | } 2820 | 2821 | function preCalculateCost(){ 2822 | // tor doesn't count to normal account since the ip is dynamic, but not sure if it counts for donator/hath perk account 2823 | // if (isTor) { 2824 | // return; 2825 | // } 2826 | 2827 | var resolutionSetting = JSON.parse(localStorage.getItem('ehd-resolution') || '{"timestamp":0}'); 2828 | var resolutionCost = { 2829 | 0: 1, 2830 | 1: 1, 2831 | 2: 1, 2832 | 3: 1, 2833 | 4: 3, 2834 | 5: 5 2835 | }; 2836 | var info = getFileSizeAndLength(); 2837 | var size = info.size; 2838 | var page = info.page; 2839 | var perCost = resolutionCost[resolutionSetting.resolution || 0]; 2840 | if ((resolutionSetting.withoutHentaiAtHome || 0) > 1) { 2841 | perCost += 10; 2842 | } 2843 | var leastCost = page * perCost; 2844 | // 1 point per 0.1 MB since August 2019, less than 0.1 MB will also be counted, so asumme each image size has the extra < 100 KB 2845 | var normalCost = Math.ceil((size / 1e5) + page * (1 + perCost)); 2846 | var cost = leastCost; 2847 | var gp = Math.ceil(size / 1e5) * 2 + page; 2848 | var isUsingGP = false; 2849 | var isUsingOriginal = !setting['force-resized'] && !isTor; 2850 | // var isSourceNexus = isSourceNexusEnabled(); 2851 | 2852 | // tor site don't have original image feature 2853 | if (isUsingOriginal) { 2854 | if (isGPRequired()) { 2855 | isUsingGP = true; 2856 | } 2857 | if (!isUsingGP) { 2858 | cost = normalCost; 2859 | } else { 2860 | cost = leastCost + ' + ' + gp + ' GP'; 2861 | } 2862 | } 2863 | 2864 | var result = { 2865 | cost: cost, 2866 | normalCost: normalCost, 2867 | leastCost: leastCost, 2868 | perCost: perCost, 2869 | gp: gp, 2870 | isUsingOriginal: isUsingOriginal, 2871 | isUsingGP: isUsingGP, 2872 | }; 2873 | 2874 | console.log('[EHD] Pre-calculate estimated cost >', JSON.stringify(result)); 2875 | return result; 2876 | } 2877 | 2878 | function showPreCalcCost(){ 2879 | var data = preCalculateCost(); 2880 | var isUsingOriginal = data.isUsingOriginal; 2881 | var isUsingGP = data.isUsingGP; 2882 | var leastCost = data.leastCost; 2883 | var gp = data.gp; 2884 | var cost = data.cost; 2885 | 2886 | ehDownloadBox.getElementsByClassName('ehD-box-cost')[0].innerHTML = ' | \ 2887 | ' 2894 | + 'Estimated Costs: ' + (/* isSourceNexus ? leastCost : */ cost || '???') + ''; 2895 | } 2896 | 2897 | // EHD Box, thanks to JingJang@GitHub, source: https://github.com/JingJang/E-Hentai-Downloader 2898 | var ehDownloadBox = document.createElement('fieldset'); 2899 | ehDownloadBox.className = 'ehD-box'; 2900 | var ehDownloadBoxTitle = document.createElement('legend'); 2901 | ehDownloadBoxTitle.innerHTML = 'E-Hentai Downloader '; 2902 | if (origin.indexOf('exhentai.org') >= 0) ehDownloadBoxTitle.style.color = '#ffff66'; 2903 | ehDownloadBox.appendChild(ehDownloadBoxTitle); 2904 | var ehDownloadStylesheet = document.createElement('style'); 2905 | ehDownloadStylesheet.textContent = ehDownloadStyle; 2906 | ehDownloadBox.appendChild(ehDownloadStylesheet); 2907 | 2908 | var extraHint; 2909 | if (isInPeakHours() && !isRecentGallery()) { 2910 | extraHint = document.createElement('a'); 2911 | extraHint.setAttribute('title', 'Peak Hours: It\'s in peak hours now, during peak hours, downloading original images of 90 days ago cost GPs'); 2912 | extraHint.textContent = '[P]'; 2913 | ehDownloadBoxTitle.appendChild(extraHint); 2914 | } 2915 | if (isAncientGallery()) { 2916 | extraHint = document.createElement('a'); 2917 | extraHint.setAttribute('title', 'Ancient Gallery: Downloading original images of 1 year ago cost GPs'); 2918 | extraHint.textContent = '[A]'; 2919 | ehDownloadBoxTitle.appendChild(extraHint); 2920 | } 2921 | 2922 | var ehDownloadArrow = ''; 2923 | 2924 | var ehDownloadAction = document.createElement('div'); 2925 | ehDownloadAction.className = 'g2'; 2926 | ehDownloadAction.innerHTML = ehDownloadArrow + ' Download Archive'; 2927 | ehDownloadAction.addEventListener('click', function(event){ 2928 | event.preventDefault(); 2929 | 2930 | var torrentsNode = document.querySelector('#gd5 a[onclick*="gallerytorrents.php"]'); 2931 | var torrentsCount = torrentsNode ? torrentsNode.textContent.match(/\d+/)[0] - 0 : 0; 2932 | if (isDownloading && !confirm('E-Hentai Downloader is working now, are you sure to stop downloading and start a new download?')) return; 2933 | 2934 | if (!setting['ignore-torrent'] && torrentsCount > 0 && !confirm('There are ' + torrentsCount + ' torrent(s) available for this gallery. You can download the torrent(s) to get a stable and controllable download experience without spending your image limits, or even get bonus content.\n\nContinue downloading with E-Hentai Downloader (Yes) or use torrent(s) directly (No)?\n(You can disable this notification in the Settings)')) { 2935 | return torrentsNode.dispatchEvent(new MouseEvent('click')); 2936 | } 2937 | 2938 | if (unsafeWindow.apiuid === -1 && !setting['force-as-login'] && !confirm('You are not logged in to E-Hentai Forums, so you can\'t download original images.\nIf you\'ve already logged in, please try logout and login again.\nContinue with resized images?')) return; 2939 | 2940 | console.log('[EHD] Is Peak Hours >', isInPeakHours(), ' | Is Recent Gallery >', isRecentGallery(), ' | Is Ancient Gallery >', isAncientGallery(), ' | Is Donator >', isDonator()); 2941 | 2942 | if ( 2943 | !setting['force-resized'] && 2944 | !isTor && 2945 | !setting['never-warn-peak-hours'] && 2946 | isGPRequired() // && 2947 | // !isSourceNexusEnabled() 2948 | ) { 2949 | if (isAncientGallery() && isDonator() < 1) { 2950 | if (!confirm('The gallery has been uploaded for a very long time, downloading original images will cost your GPs instead of viewing limits.\nYou can download resized images or disable this notification in script\'s settings.\n\nContinue downloading with original images?')) { 2951 | return; 2952 | } 2953 | } else { 2954 | if (!confirm('It\'s peak hours now, downloading original images will cost your GPs instead of viewing limits.\nYou can download resized images or disable this notification in script\'s settings.\n\nContinue downloading with original images?')) { 2955 | return; 2956 | } 2957 | } 2958 | } 2959 | 2960 | if (!setting['never-warn-limits']) { 2961 | var costData = preCalculateCost(); 2962 | var limitsData = getImageLimits(); 2963 | var totalLimitsCost = +(setting['force-resized'] ? costData.leastCost : costData.normalCost) || 0; 2964 | if (Number.isNaN(totalLimitsCost)) { 2965 | totalLimitsCost = 0; 2966 | } 2967 | var finalLimits = +(limitsData.cur || 0) + totalLimitsCost; 2968 | if (finalLimits > limitsData.total) { 2969 | if (!confirm('You may used up your image limits or will run it out, downloading images exceed your limits will cost GPs instead, or credits if you run out of GPs.\nUsed + Estimated = ' + (limitsData.cur || 0) + ' + ' + totalLimitsCost + ' = ' + finalLimits + ' > ' + limitsData.total + '\n\nContinue downloading?')) { 2970 | return; 2971 | } 2972 | } 2973 | } 2974 | 2975 | ehDownloadDialog.innerHTML = ''; 2976 | 2977 | initEHDownload(); 2978 | }); 2979 | ehDownloadBox.appendChild(ehDownloadAction); 2980 | 2981 | var ehDownloadNumberInput = document.createElement('div'); 2982 | ehDownloadNumberInput.className = 'g2'; 2983 | ehDownloadNumberInput.innerHTML = ehDownloadArrow + ' '; 2984 | ehDownloadBox.appendChild(ehDownloadNumberInput); 2985 | 2986 | var ehDownloadRange = document.createElement('div'); 2987 | ehDownloadRange.className = 'g2'; 2988 | ehDownloadRange.innerHTML = ehDownloadArrow + ' '; 2989 | ehDownloadBox.appendChild(ehDownloadRange); 2990 | 2991 | var ehDownloadSetting = document.createElement('div'); 2992 | ehDownloadSetting.className = 'g2'; 2993 | ehDownloadSetting.innerHTML = ehDownloadArrow + ' Settings'; 2994 | ehDownloadSetting.addEventListener('click', function(event){ 2995 | event.preventDefault(); 2996 | showSettings(); 2997 | }); 2998 | ehDownloadBox.appendChild(ehDownloadSetting); 2999 | 3000 | document.body.insertBefore(ehDownloadBox, document.getElementById('asm') || document.querySelector('.gm').nextElementSibling); 3001 | 3002 | var ehDownloadDialog = document.createElement('div'); 3003 | ehDownloadDialog.className = 'ehD-dialog'; 3004 | document.body.appendChild(ehDownloadDialog); 3005 | 3006 | var ehDownloadStatus = document.createElement('div'); 3007 | ehDownloadStatus.className = 'ehD-status'; 3008 | ehDownloadStatus.addEventListener('click', function(event){ 3009 | event.preventDefault(); 3010 | ehDownloadDialog.classList.toggle('hidden'); 3011 | }); 3012 | 3013 | var ehDownloadPauseBtn = document.createElement('button'); 3014 | ehDownloadPauseBtn.className = 'ehD-pause'; 3015 | ehDownloadPauseBtn.textContent ='Pause'; 3016 | ehDownloadPauseBtn.addEventListener('click', function(event){ 3017 | if (!isPausing) { 3018 | isPausing = true; 3019 | ehDownloadPauseBtn.textContent = 'Resume'; 3020 | 3021 | if (setting['force-pause']) { 3022 | // waiting Tampermonkey for transfering string to ArrayBuffer, it may stuck for a second 3023 | setTimeout(function(){ 3024 | for (var i = 0; i < fetchThread.length; i++) { 3025 | if (typeof fetchThread[i] !== 'undefined' && 'abort' in fetchThread[i]) fetchThread[i].abort(); 3026 | 3027 | if (imageData[i] === 'Fetching' && retryCount[i] < (setting['retry-count'] !== undefined ? setting['retry-count'] : 3)) { 3028 | var elem = progressTable.querySelector('tr[data-index="' + i + '"] .ehD-pt-status-text'); 3029 | if (elem) elem.textContent = 'Force Paused'; 3030 | 3031 | elem = progressTable.querySelector('tr[data-index="' + i + '"] .ehD-pt-progress-text'); 3032 | if (elem) elem.textContent = ''; 3033 | 3034 | imageData[i] = null; 3035 | //fetchCount = 0; // fixed for async 3036 | fetchCount--; 3037 | 3038 | updateTotalStatus(); 3039 | } 3040 | } 3041 | }, 0); 3042 | } 3043 | 3044 | if (emptyAudio) { 3045 | emptyAudio.pause(); 3046 | } 3047 | } 3048 | else { 3049 | isPausing = false; 3050 | ehDownloadPauseBtn.textContent = setting['force-pause'] ? 'Pause (Downloading images will be aborted)' : 'Pause (Downloading images will keep downloading)'; 3051 | 3052 | checkFailed(); 3053 | } 3054 | }); 3055 | 3056 | window.addEventListener('focus', function(){ 3057 | if (setting['status-in-title'] === 'blur') { 3058 | if (!needTitleStatus) return; 3059 | document.title = pretitle; 3060 | needTitleStatus = false; 3061 | } 3062 | }); 3063 | 3064 | window.addEventListener('blur', function(){ 3065 | if (isDownloading && setting['status-in-title'] === 'blur') { 3066 | needTitleStatus = true; 3067 | document.title = '[' + (isPausing ? '❙❙' : downloadedCount < totalCount ? '↓ ' + downloadedCount + '/' + totalCount : totalCount === 0 ? '↓' : '√' ) + '] ' + pretitle; 3068 | } 3069 | }); 3070 | 3071 | var forceDownloadTips = document.createElement('div'); 3072 | forceDownloadTips.className = 'ehD-force-download-tips'; 3073 | forceDownloadTips.innerHTML = 'If an error occured and script doesn\'t work, click here to force get your downloaded images.'; 3074 | forceDownloadTips.getElementsByTagName('a')[0].addEventListener('click', function(event){ 3075 | // fixed permission denied on GreaseMonkey 3076 | event.preventDefault(); 3077 | saveDownloaded(true); 3078 | }); 3079 | 3080 | var closeTips = document.createElement('div'); 3081 | closeTips.className = 'ehD-close-tips'; 3082 | closeTips.innerHTML = 'E-Hentai Downloader is still running, please don\'t close this tab until it finished downloading.

If any bug occured and the script doesn\'t work correctly, you can move your mouse pointer onto the progress box, and force to save downloaded images before you leave.'; 3083 | 3084 | unsafeWindow.getzip = window.getzip = function(){ 3085 | saveDownloaded(true); 3086 | }; 3087 | 3088 | initSetting(); 3089 | 3090 | window.addEventListener('storage', showImageLimits); 3091 | 3092 | window.onbeforeunload = unsafeWindow.onbeforeunload = function(){ 3093 | function clearRubbish(){ 3094 | for (var i = 0; i < fetchThread.length; i++) { 3095 | if (typeof fetchThread[i] !== 'undefined' && 'abort' in fetchThread[i]) fetchThread[i].abort(); 3096 | } 3097 | ehDownloadFS.removeFile(unsafeWindow.gid + '.zip'); 3098 | } 3099 | if (isDownloading || isPausing || isSaving) { 3100 | document.body.appendChild(closeTips); 3101 | 3102 | setTimeout(function(){ 3103 | document.body.removeChild(closeTips); 3104 | }, 100); 3105 | 3106 | return 'E-Hentai Downloader is still running, please don\'t close this tab until it finished downloading.'; 3107 | } 3108 | clearRubbish(); 3109 | }; 3110 | --------------------------------------------------------------------------------
Donations<\/td>([+-]?[\d\.]+)<\/td>/, 55 | postedTime: /Posted:<\/td>(.*?)<\/td>/, 56 | categoryTag: /g\/c\/(\w+)\./, 57 | slashOnly: /^[\\/]*$/, 58 | originalImagePattern: /\/fullimg(?:\.php\?|\/)/ 59 | }; 60 | 61 | var dateOffset = new Date().getTimezoneOffset() * 60000; 62 | Object.defineProperty(JSZip.defaults, 'date', { 63 | get: function() { 64 | return new Date(Date.now() - dateOffset); 65 | } 66 | }); 67 | 68 | var requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem; 69 | var ehDownloadFS = { 70 | fs: undefined, 71 | needFileSystem: false, 72 | initHandler: function(fs) { 73 | ehDownloadFS.fs = fs; 74 | console.log('[EHD] File System is opened! Name >', fs.name); 75 | ehDownloadFS.removeAllFiles(fs); // It's sure that user have downloaded or ignored temp archive 76 | }, 77 | errorHandler: function(e) { 78 | var errorMsg = 'File System Request Error > '; 79 | errorMsg += e.name || 'Unknown Error'; 80 | 81 | console.error('[EHD] ' + errorMsg, e.message); 82 | console.error(e); 83 | }, 84 | saveAs: function(fs, forced){ 85 | var fs = fs || ehDownloadFS.fs; 86 | if (fs === undefined) return; 87 | fs.root.getFile(unsafeWindow.gid + '.zip', {}, function (fileEntry) { 88 | var url = fileEntry.toURL(); 89 | console.log('[EHD] File URL >', url); 90 | var a = document.createElement('a'); 91 | a.setAttribute('href', url); 92 | a.setAttribute('download', fileName + (setting['save-as-cbz'] ? '.cbz' : '.zip')); 93 | a.click(); 94 | pushDialog('\n\nNot download or file is broken? Click here to download\n\n'); 95 | if (!forced) { 96 | insertCloseButton(); 97 | if (emptyAudio) { 98 | emptyAudio.pause(); 99 | } 100 | } 101 | }); 102 | }, 103 | removeFile: function(fileName, fs, isEntry){ 104 | var fs = fs || ehDownloadFS.fs; 105 | if (fs === undefined) return; 106 | var removeFunction = function(fileEntry){ 107 | if (fileEntry.isFile) fileEntry.remove(function(){ 108 | console.log('[EHD] File', fileName, 'is removed.'); 109 | }); 110 | else if (fileEntry.isDirectory) fileEntry.removeRecursively(function() { 111 | console.log('[EHD] Directory', fileName, 'is removed.'); 112 | }); 113 | }; 114 | if (isEntry) removeFunction(fileName); 115 | else fs.root.getFile(fileName, {create: false}, removeFunction); 116 | }, 117 | removeAllFiles: function(fs){ 118 | var fs = fs || ehDownloadFS.fs; 119 | if (fs === undefined) return; 120 | console.log('[EHD] Request removing all files in File System.'); 121 | fs.root.createReader().readEntries(function(entries){ 122 | if (entries.length === 0) return; 123 | for (var i = 0; i < entries.length; i++) { 124 | ehDownloadFS.removeFile(entries[i], fs, true); 125 | } 126 | }, ehDownloadFS.errorHandler); 127 | }, 128 | initCheckerHandler: function(fs) { 129 | //ehDownloadFS.fs = fs; 130 | console.log('[EHD] File System is opened! Name >', fs.name); 131 | ehDownloadFS.removeFile(unsafeWindow.gid + '.zip', fs); 132 | fs.root.getFile('config.txt', {create: false}, function(fileEntry){ 133 | fileEntry.file(function(file){ 134 | var fileReader = new FileReader(); 135 | fileReader.onloadend = function() { 136 | var value = this.result; 137 | if (value === '' || value == null) return; 138 | var data = JSON.parse(value); 139 | if (data && confirm('You have an archive that is not downloaded, save it?\n\nFile Name: ' + data.fileName + '\n\n* If you have already downloaded it, click cancel to remove the cached archive file.')) { 140 | fileName = data.fileName; 141 | dirName = data.dirName; 142 | ehDownloadFS.storeTempArchive(data, fs); 143 | } 144 | else { 145 | ehDownloadFS.removeAllFiles(fs); 146 | } 147 | }; 148 | fileReader.readAsText(file); 149 | }); 150 | }); 151 | }, 152 | storeTempArchive: function(data, fs){ 153 | var fs = fs || ehDownloadFS.fs; 154 | if (fs === undefined) return; 155 | fs.root.getDirectory('raw', {}, function(fileEntry){ 156 | fileEntry.createReader().readEntries(function(entries){ 157 | if (entries.length === 0) return; 158 | var index = 0; 159 | var fileReader = new FileReader(); 160 | zip = new JSZip(); 161 | ehDownloadDialog.style.display = 'block'; 162 | ehDownloadDialog.innerHTML = ''; 163 | pushDialog('Preparing......'); 164 | fileReader.onloadend = function() { 165 | (data.dirName && !ehDownloadRegex.slashOnly.test(data.dirName) ? zip.folder(data.dirName) : zip).file(entries[index].name, this.result); 166 | index++; 167 | if (index < entries.length) addFile(); 168 | else { 169 | ehDownloadFS.removeAllFiles(); 170 | setTimeout(generateZip, 3000, true, fs); // wait for removing all files 171 | } 172 | }; 173 | var addFile = function(){ 174 | console.log('[EHD] TempArchiveFileIndex >', index, '| TempArchiveFileName >', entries[index].name, '| TempArchiveFilePath >', entries[index].fullPath, '| TempArchiveFileLength >', entries.length); 175 | pushDialog('\n' + (index + 1) + '/' + entries.length); 176 | fs.root.getFile(entries[index].fullPath, {create: false}, function(fileEntry){ 177 | fileEntry.file(function(file){ 178 | fileReader.readAsArrayBuffer(file); 179 | }); 180 | }); 181 | }; 182 | addFile(); 183 | }, ehDownloadFS.errorHandler); 184 | }, ehDownloadFS.errorHandler); 185 | } 186 | }; 187 | 188 | var bodyBackground = getComputedStyle(document.body).backgroundColor || '#34353b'; 189 | var ehDownloadStyle = '\ 190 | @-webkit-keyframes progress { \ 191 | from { -webkit-transform: translateX(-50%) scaleX(0); transform: translateX(-50%) scaleX(0); } \ 192 | 60% { -webkit-transform: translateX(15%) scaleX(0.7); transform: translateX(15%) scaleX(0.7); } \ 193 | to { -webkit-transform: translateX(50%) scaleX(0); transform: translateX(50%) scaleX(0); } \ 194 | } \ 195 | @-moz-keyframes progress { \ 196 | from { -moz-transform: translateX(-50%) scaleX(0); transform: translateX(-50%) scaleX(0); } \ 197 | 60% { -moz-transform: translateX(15%) scaleX(0.7); transform: translateX(15%) scaleX(0.7); } \ 198 | to { -moz-transform: translateX(50%) scaleX(0); transform: translateX(50%) scaleX(0); } \ 199 | } \ 200 | @-ms-keyframes progress { \ 201 | from { -ms-transform: translateX(-50%) scaleX(0); transform: translateX(-50%) scaleX(0); } \ 202 | 60% { -ms-transform: translateX(15%) scaleX(0.7); transform: translateX(15%) scaleX(0.7); } \ 203 | to { -ms-transform: translateX(50%) scaleX(0); transform: translateX(50%) scaleX(0); } \ 204 | } \ 205 | @keyframes progress { \ 206 | from { -webkit-transform: translateX(-50%) scaleX(0); transform: translateX(-50%) scaleX(0); } \ 207 | 60% { -webkit-transform: translateX(15%) scaleX(0.7); transform: translateX(15%) scaleX(0.7); } \ 208 | to { -webkit-transform: translateX(50%) scaleX(0); transform: translateX(50%) scaleX(0); } \ 209 | } \ 210 | .ehD-box { margin: 16px auto 20px; width: 732px; box-sizing: border-box; font-size: 12px; border: 1px groove #000000; }\ 211 | .ehD-box a { cursor: pointer; }\ 212 | .ehD-box .g2 { display: inline-block; margin: 10px; padding: 0; line-height: 14px; }\ 213 | .ehD-box legend { font-weight: 700; padding: 4px 10px 0; } \ 214 | .ehD-box legend a { color: inherit; text-decoration: none; }\ 215 | .ehD-box input[type="text"] { width: 250px; }\ 216 | .ehD-box-extend input[type="text"] { width: 255px; }\ 217 | .ehD-box input::placeholder { color: #999999; -webkit-text-fill-color: #999999; }\ 218 | .ehD-box.ehD-box-sticky { position: sticky; top: 0px; z-index: 5; background: ' + bodyBackground + '; box-shadow: 0 0 0 12px ' + bodyBackground + '; }\ 219 | .ehD-setting { position: fixed; left: 0; right: 0; top: 0; bottom: 0; padding: 5px; border: 1px solid #000000; background: #34353b; color: #dddddd; width: 600px; height: 380px; max-width: 100%; max-height: 100%; overflow-x: hidden; overflow-y: auto; box-sizing: border-box; margin: auto; z-index: 999; text-align: left; font-size: 12px; outline: 5px rgba(0, 0, 0, 0.25) solid; }\ 220 | .ehD-setting-tab { list-style: none; margin: 5px 0; padding: 0 10px; border-bottom: 1px solid #cccccc; overflow: auto; }\ 221 | .ehD-setting-tab li { float: left; padding: 5px 10px; border-bottom: 0; cursor: pointer; }\ 222 | .ehD-setting[data-active-setting="basic"] li[data-target-setting="basic"], .ehD-setting[data-active-setting="advanced"] li[data-target-setting="advanced"] { font-weight: bold; background: #cccccc; color: #000000; }\ 223 | .ehD-setting-main { overflow: hidden }\ 224 | .ehD-setting-wrapper { width: 200%; overflow: hidden; -webkit-transform: translateX(0%); -moz-transform: translateX(0%); -o-transform: translateX(0%); -ms-transform: translateX(0%); transform: translateX(0%); -webkit-transition: all 0.5s cubic-bezier(0.86, 0, 0.07, 1); -moz-transition: all 0.5s cubic-bezier(0.86, 0, 0.07, 1); -o-transition: all 0.5s cubic-bezier(0.86, 0, 0.07, 1); -ms-transition: all 0.5s cubic-bezier(0.86, 0, 0.07, 1); transition: all 0.5s cubic-bezier(0.86, 0, 0.07, 1); }\ 225 | .ehD-setting[data-active-setting="advanced"] .ehD-setting-wrapper { -webkit-transform: translateX(-50%); -moz-transform: translateX(-50%); -o-transform: translateX(-50%); -ms-transform: translateX(-50%); transform: translateX(-50%); }\ 226 | .ehD-setting-content { width: 50%; float: left; box-sizing: border-box; padding: 5px 10px; height: 295px; max-height: calc(100vh - 85px); overflow: auto; }\ 227 | .ehD-setting .g2 { padding-bottom: 10px; }\ 228 | .ehD-setting input, .ehD-box input, .ehD-setting select, .ehD-box select { vertical-align: middle; top: 0; margin: 0; }\ 229 | .ehD-setting input[type="text"], .ehD-box input[type="text"], .ehD-setting input[type="number"] { height: 18px; padding: 0 0 0 3px; line-height: 18px; border-radius: 3px; }\ 230 | .ehD-setting input[type="text"], .ehD-setting input[type="number"] { border: 1px solid #8d8d8d; } \ 231 | .ehD-setting input[type="checkbox"] { margin: 3px 3px 4px 0 } \ 232 | .ehD-setting select { padding: 0 3px 1px; } \ 233 | .ehD-setting-note { border: 1px dashed #999999; padding: 10px 10px 0 10px; }\ 234 | .ehD-setting-footer { text-align: center; margin-top: 5px; border-top: 1px solid #cccccc; padding-top: 5px; }\ 235 | .ehD-setting sup { vertical-align: top; }\ 236 | .ehD-setting a { color: #ffffff; }\ 237 | .ehD-box input[type="number"] { height: 17px; }\ 238 | .ehD-dialog progress { height: 12px; -webkit-appearance: none; border: 1px solid #4f535b; color: #4f535b; background: #34353b; position: relative; } \ 239 | .ehD-dialog progress::-webkit-progress-bar { background: #34353b; } \ 240 | .ehD-dialog progress::-webkit-progress-value { background: #4f535b; -webkit-transition: all 0.2s ease; transition: all 0.2s ease; } \ 241 | .ehD-dialog progress::-moz-progress-bar { background: #4f535b; -moz-transition: all 0.2s ease; transition: all 0.2s ease; } \ 242 | .ehD-dialog progress::-ms-fill { background: #4f535b; -ms-transition: all 0.2s ease; transition: all 0.2s ease; } \ 243 | .ehD-dialog progress:not([value])::after { content: ""; will-change: transform; width: 100%; height: 100%; left: 0; top: 0; display: block; background: #4f535b; position: absolute; -webkit-animation: progress 1s linear infinite; -moz-animation: progress 1s linear infinite; -ms-animation: progress 1s linear infinite; animation: progress 1s linear infinite; } \ 244 | .ehD-dialog progress:not([value])::-moz-progress-bar { width: 0px !important; } \ 245 | .ehD-pt { table-layout: fixed; width: 100%; }\ 246 | .ehD-pt-name { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }\ 247 | .ehD-pt-progress-outer { width: 160px; position: relative; }\ 248 | .ehD-pt-progress { width: 150px; }\ 249 | .ehD-pt-progress-text { position: absolute; width: 100%; text-align: center; color: #b8b8b8; left: 0; right: 0; }\ 250 | .ehD-pt-status { width: 130px; }\ 251 | .ehD-pt-succeed .ehD-pt-status { color: #00ff00; }\ 252 | .ehD-pt-warning .ehD-pt-status { color: #ffff00; }\ 253 | .ehD-pt-failed .ehD-pt-status { color: #ff0000; }\ 254 | .ehD-pt-abort { color: #ffff00; display: none; cursor: pointer; }\ 255 | .ehD-pt-status[data-inited-abort]:hover .ehD-pt-abort, .ehD-pt-failed .ehD-pt-status[data-inited-abort]:hover .ehD-pt-status-text, .ehD-pt-succeed .ehD-pt-status[data-inited-abort]:hover .ehD-pt-status-text { display: inline; }\ 256 | .ehD-pt-status[data-inited-abort]:hover .ehD-pt-status-text, .ehD-pt-failed .ehD-pt-status[data-inited-abort]:hover .ehD-pt-abort, .ehD-pt-succeed .ehD-pt-status[data-inited-abort]:hover .ehD-pt-abort { display: none; }\ 257 | .ehD-pt-gen-progress { width: 50%; }\ 258 | .ehD-pt-gen-filename { margin-bottom: 1em; }\ 259 | .ehD-dialog { position: fixed; right: 0; bottom: 0; display: none; padding: 5px; border: 1px solid #000000; background: #34353b; color: #dddddd; width: 550px; height: 300px; overflow: auto; z-index: 999; word-break: break-all; }\ 260 | .ehD-status { position: fixed; right: 0; bottom: 311px; width: 550px; padding: 5px; border: 1px solid #000000; background: #34353b; color: #dddddd; cursor: pointer; -webkit-user-select: none; -moz-user-select: none; -o-user-select: none; -ms-user-select: none; user-select: none; }\ 261 | .ehD-dialog, .ehD-status { -webkit-transition: margin 0.5s ease; -moz-transition: margin 0.5s ease; -o-transition: margin 0.5s ease; -ms-transition: margin 0.5s ease; transition: margin 0.5s ease; }\ 262 | .ehD-dialog.hidden, .ehD-dialog.hidden .ehD-status { margin-bottom: -311px; }\ 263 | .ehD-dialog .ehD-force-download-tips { position: fixed; right: 0; bottom: 288px; border: 1px solid #000000; width: 550px; padding: 5px; background: rgba(0, 0, 0, 0.75); color: #ffffff; cursor: pointer; opacity: 0; pointer-events: none; -webkit-transition: opacity 0.5s ease, bottom 0.5s ease; -moz-transition: opacity 0.5s ease, bottom 0.5s ease; -o-transition: opacity 0.5s ease, bottom 0.5s ease; -ms-transition: opacity 0.5s ease, bottom 0.5s ease; transition: opacity 0.5s ease, bottom 0.5s ease; }\ 264 | .ehD-dialog:hover .ehD-force-download-tips { opacity: 1; }\ 265 | .ehD-dialog.hidden .ehD-force-download-tips { bottom: -24px; }\ 266 | .ehD-close-tips { position: fixed; left: 0; right: 0; bottom: 0; padding: 10px; border: 1px solid #000000; background: #34353b; color: #dddddd; width: 732px; max-width: 100%; max-height: 100%; overflow-x: hidden; overflow-y: auto; box-sizing: border-box; margin: auto; z-index: 1000; text-align: left; font-size: 14px; outline: 5px rgba(0, 0, 0, 0.25) solid; }\ 267 | .ehD-feedback { position: absolute; right: 5px; top: 14px; }\ 268 | '; 269 | 270 | function initSetting() { 271 | loadSetting().then(function (res) { 272 | setting = res ? JSON.parse(res) : {}; 273 | needNumberImages = setting['number-images']; 274 | needTitleStatus = setting['status-in-title'] === 'always' ? true : false; 275 | 276 | // overwrite settings or set default settings 277 | if (setting['status-in-title'] === true) setting['status-in-title'] = 'blur'; 278 | if (!setting['save-info-list']) { 279 | setting['save-info-list'] = ['title', 'metas', 'uploader-comment', 'page-links']; 280 | } 281 | if (localStorage.getItem('ehd-image-limits-g.e-hentai.org')) { 282 | localStorage.removeItem('ehd-image-limits-g.e-hentai.org'); 283 | } 284 | // remove config of get image limits from r.e-hentai.org 285 | if (setting['image-limits-both']) { 286 | delete setting['image-limits-both']; 287 | GM_setValue('ehD-setting', JSON.stringify(setting)); 288 | } 289 | if (localStorage.getItem('ehd-image-limits-r.e-hentai.org')) { 290 | localStorage.removeItem('ehd-image-limits-r.e-hentai.org'); 291 | } 292 | if (typeof setting['auto-download-cancel'] === 'undefined') { 293 | setting['auto-download-cancel'] = true; 294 | } 295 | if (typeof setting['actions-sticky'] === 'undefined') { 296 | setting['actions-sticky'] = true; 297 | } 298 | 299 | console.log('[EHD] E-Hentai Downloader Setting >', res, '-->', JSON.stringify(setting)); 300 | 301 | // disable single-thread download 302 | if (setting['enable-multi-threading'] === false) { 303 | delete setting['enable-multi-threading']; 304 | alert('Single-thread download is unavailable now, because its code is too old and it\'s hard to add new features on it.\n\nIf you still need it, please roll back to the last-supported version (1.17.4).\n\nYou can get it at:\n- GitHub: https://github.com/ccloli/E-Hentai-Downloader/releases\n- GreasyFork: https://greasyfork.org/scripts/10379-e-hentai-downloader/versions (requires log in and enable Adult content)\n- SleazyFork: https://sleazyfork.org/scripts/10379-e-hentai-downloader/versions'); 305 | GM_setValue('ehD-setting', JSON.stringify(setting)); 306 | } 307 | 308 | if (setting['recheck-file-name']) toggleFilenameConfirmInput(); 309 | ehDownloadNumberInput.querySelector('input').checked = needNumberImages; 310 | ehDownloadPauseBtn.textContent = setting['force-pause'] ? 'Pause (Downloading images will be aborted)' : 'Pause (Downloading images will keep downloading)'; 311 | 312 | if (!setting['hide-image-limits']) { 313 | getResolutionSetting(true); 314 | loadImageLimits(true); 315 | setInterval(loadImageLimits, 60000); 316 | } 317 | 318 | if (!setting['hide-estimated-cost']) { 319 | try { 320 | showPreCalcCost(); 321 | } 322 | catch (e) { } 323 | } 324 | 325 | initVisibilityListener(); 326 | 327 | // Forced request File System to check if have temp archive 328 | if (setting['store-in-fs'] && requestFileSystem) { 329 | requestFileSystem(window.TEMPORARY, 1024 * 1024 * 1024, ehDownloadFS.initCheckerHandler, ehDownloadFS.errorHandler); 330 | } 331 | 332 | // if (setting['actions-sticky'] !== false) { 333 | // ehDownloadBox.classList.add('ehD-box-sticky'); 334 | // } 335 | }); 336 | } 337 | 338 | // log information 339 | console.log('[EHD] UserAgent >', navigator.userAgent); 340 | console.log('[EHD] Script Handler >', GM_info.scriptHandler || (navigator.userAgent.indexOf('Firefox') >= 0 ? 'GreaseMonkey' : (navigator.userAgent.indexOf('Opera') >= 0 || navigator.userAgent.indexOf('Maxthon') >= 0) ? 'Violentmonkey' : undefined)); // (Only Tampermonkey supports GM_info.scriptHandler) 341 | console.log('[EHD] Script Handler Version >', GM_info.version); 342 | console.log('[EHD] E-Hentai Downloader Version >', GM_info.script.version); 343 | console.log('[EHD] Current URL >', window.location.href); 344 | console.log('[EHD] Is Logged In >', unsafeWindow.apiuid !== -1); 345 | 346 | 347 | var replaceHTMLEntites = function(str) { 348 | var matchEntity = function(entity) { 349 | var entitesList = {"euro":"€","nbsp":" ","quot":"\"","amp":"&","lt":"<","gt":">","iexcl":"¡","cent":"¢","pound":"£","curren":"¤","yen":"¥","brvbar":"¦","sect":"§","uml":"¨","copy":"©","ordf":"ª","not":"¬","shy":"","reg":"®","macr":"¯","deg":"°","plusmn":"±","sup2":"²","sup3":"³","acute":"´","micro":"µ","para":"¶","middot":"·","cedil":"¸","sup1":"¹","ordm":"º","raquo":"»","frac14":"¼","frac12":"½","frac34":"¾","iquest":"¿","agrave":"à","aacute":"á","acirc":"â","atilde":"ã","auml":"ä","aring":"å","aelig":"æ","ccedil":"ç","egrave":"è","eacute":"é","ecirc":"ê","euml":"ë","igrave":"ì","iacute":"í","icirc":"î","iuml":"ï","eth":"ð","ntilde":"ñ","ograve":"ò","oacute":"ó","ocirc":"ô","otilde":"õ","ouml":"ö","times":"×","oslash":"ø","ugrave":"ù","uacute":"ú","ucirc":"û","uuml":"ü","yacute":"ý","thorn":"þ","szlig":"ß","divide":"÷"}; 350 | if (entitesList[entity]) return entitesList[entity]; 351 | else if (/#\d+/.test(entity)) { 352 | var charCode = entity.match(/#(\d+)/)[1] - 0; 353 | return String.fromCharCode(charCode); 354 | } 355 | else if (/#[xX][0-9a-f]+/.test(entity)) { 356 | var charCode = parseInt(entity.match(/#[xX]([0-9a-f]+)/)[1] - 0, 16); 357 | return String.fromCharCode(charCode); 358 | } 359 | else return '&' + entity + ';'; 360 | }; 361 | var result = (str || '').replace(/&(#[xX]?\d+|[a-zA-Z]+);/g, function(match, entity) { 362 | return matchEntity(entity.toLowerCase()); 363 | }); 364 | return result; 365 | }; 366 | 367 | function isInPeakHours() { 368 | // 2022-08-07 369 | // - Adjusted the "peak hours" used by original image downloading to better match the actual measured peak periods. It is now between 14:00 and 20:00 UTC Monday-Saturday, and between 05:00 and 20:00 UTC on Sundays. 370 | var date = new Date(); 371 | var day = date.getUTCDay(); 372 | var hour = date.getUTCHours(); 373 | return (day === 0 ? hour >= 5 : hour >= 14) && hour < 20; 374 | } 375 | 376 | function isRecentGallery() { 377 | // 2022-06-07 378 | // A couple of minor tweaks to the "Download source image" changes, since it dropped the utilization by a lot more than we needed it to: 379 | // - It no longer applies to galleries posted in the last ~~7~~ 30 days. 380 | // - It no longer applies for donators. 381 | // 2022-11-25 382 | // - One of two new image servers that replace the current oldest image server is now live. (The second one will probably go live in about a month.) 383 | // - Increased the cutoff for how old a gallery has to be before it charges GP for original file downloads during peak hours from 30 days to 90 days. 384 | var galleryTime = (document.documentElement.innerHTML.match(ehDownloadRegex.postedTime) || [])[1]; 385 | var time = Date.parse(galleryTime + '+0000'); 386 | return Date.now() - time < 90 * 24 * 60 * 60 * 1000; 387 | } 388 | 389 | function isAncientGallery() { 390 | // 2023-07-07 391 | // - Galleries posted more than 1 year ago now always require GP to use the "download original image" links. As before, galleries uploaded 3-12 months ago can still use this function with the image quota outside of peak hours, while galleries uploaded less than 3 months ago can do this even during peak hours. 392 | // (This still doesn't apply to donators, whose image limits are tied to account rather than IP address and thus cannot be "refreshed" just by switching IP) 393 | var galleryTime = (document.documentElement.innerHTML.match(ehDownloadRegex.postedTime) || [])[1]; 394 | var time = Date.parse(galleryTime + '+0000'); 395 | return Date.now() - time >= 365 * 24 * 60 * 60 * 1000; 396 | } 397 | 398 | function isDonator() { 399 | return Object.keys(localStorage).filter(function (elem) { 400 | return elem.indexOf('ehd-image-limits-') === 0; 401 | }).some(function(elem) { 402 | try { 403 | var curData = JSON.parse(localStorage.getItem(elem)); 404 | return curData.donatorPower; 405 | } catch (err) { 406 | console.error(err); 407 | return 0; 408 | } 409 | }); 410 | } 411 | 412 | function isSourceNexusEnabled() { 413 | var curData = JSON.parse(localStorage.getItem('ehd-resolution') || '{"timestamp":0}'); 414 | return +curData.originalImages && +curData.resolution === 0; 415 | } 416 | 417 | function isMPVAvailable() { 418 | var curData = JSON.parse(localStorage.getItem('ehd-resolution') || '{"timestamp":0}'); 419 | return curData.mpvAvailable; 420 | } 421 | 422 | function isGPRequired() { 423 | return ( 424 | ( 425 | isInPeakHours() && !isRecentGallery() && !isDonator() 426 | ) || ( 427 | isAncientGallery() && isDonator() < 1 428 | ) 429 | ); 430 | } 431 | 432 | function createBlob(abdata, config) { 433 | try { // to detect if blob generates successfully 434 | return new Blob(abdata, config); 435 | } 436 | catch (error) { 437 | pushDialog('An error occurred when generating Blob object.'); 438 | console.error('[EHD] An error occurred when generating Blob object. Error Name >', error.name, '| Error Message >', error.message); 439 | if (confirm('An error occurred when generating Blob object.\n\nError Name: ' + error.name + '\nError Message: ' + error.message + '\n\nTry again?')) return createBlob(abdata, config); 440 | 441 | abdata = undefined; 442 | throw new Error('[EHD] An error occurred when generating Blob object, and user refused to retry.'); 443 | } 444 | } 445 | 446 | // show info in dialog box 447 | function pushDialog(str) { 448 | var needScrollIntoView = ehDownloadDialog.clientHeight + ehDownloadDialog.scrollTop >= ehDownloadDialog.scrollHeight - 5; 449 | 450 | if (typeof str === 'string') { 451 | var tn = document.createElement('span'); 452 | tn.innerHTML += str.replace(/\n/gi, '
'); 453 | ehDownloadDialog.appendChild(tn); 454 | } 455 | else ehDownloadDialog.appendChild(str); 456 | 457 | if (getAllPagesURLFin && isDownloading && ehDownloadDialog.contains(ehDownloadPauseBtn)) { 458 | ehDownloadDialog.appendChild(ehDownloadPauseBtn); 459 | } 460 | 461 | if (needScrollIntoView) { 462 | ehDownloadDialog.scrollTop = ehDownloadDialog.scrollHeight; 463 | } 464 | } 465 | 466 | function getSafeName(str, ignoreSlash) { 467 | var replaceList = { 468 | ':': ':', 469 | '"': '"', 470 | '*': '*', 471 | '?': '?', 472 | '|': '|', 473 | '<': '<', 474 | '>': '>', 475 | '/': '/', 476 | '\\': '\', 477 | '~': '~', 478 | '\n': '-' 479 | }; 480 | var replaceFn = function(match) { 481 | if (ignoreSlash && (match === '/' || match === '\\')) { 482 | return match; 483 | } 484 | else if (setting['replace-with-full-width']) { 485 | return replaceList[match]; 486 | } 487 | else { 488 | return '-'; 489 | } 490 | }; 491 | 492 | return str.trim().replace(ehDownloadRegex.dangerChars, replaceFn); 493 | } 494 | 495 | // replace dir name and zip filename 496 | function getReplacedName(str) { 497 | return replaceHTMLEntites(str.replace(/\{gid\}/gi, unsafeWindow.gid) 498 | .replace(/\{token\}/gi, unsafeWindow.token) 499 | .replace(/\{title\}/gi, getSafeName(document.getElementById('gn').textContent)) 500 | .replace(/\{subtitle\}/gi, document.getElementById('gj').textContent ? getSafeName(document.getElementById('gj').textContent) : getSafeName(document.getElementById('gn').textContent)) 501 | .replace(/\{tag\}|\{category\}/gi, document.querySelector('#gdc .cs').textContent.trim().toUpperCase()) 502 | .replace(/\{uploader\}/gi, getSafeName(document.querySelector('#gdn').textContent))); 503 | } 504 | 505 | function PageData(pageURL, imageURL, imageName, nextNL, realIndex, imageNumber) { 506 | this.pageURL = pageURL.split('?')[0]; 507 | this.imageURL = imageURL; 508 | this.imageName = getSafeName(imageName); 509 | this._imageName = this.imageName; 510 | this.equalCount = 1; 511 | this.nextNL = nextNL; 512 | this.realIndex = realIndex; 513 | this.imageNumber = imageNumber; 514 | } 515 | 516 | // rename images that have the same name 517 | function renameImages() { 518 | imageList.forEach(function(elem, index) { 519 | // if Number Images are enabled, filename won't be changed, just numbering 520 | if (!needNumberImages) { 521 | for (var i = 0; i < index; i++) { 522 | if (elem !== undefined && imageList[i] !== undefined && elem.imageName.toLowerCase() === imageList[i]['imageName'].toLowerCase()) { 523 | var nameParts = elem.imageName.split('.'); 524 | nameParts[nameParts.length - 2] += ' (' + (++imageList[i].equalCount) + ')'; 525 | elem.imageName = nameParts.join('.'); 526 | break; 527 | } 528 | } 529 | } 530 | else elem['imageName'] = elem['imageNumber'] + (setting['number-separator'] ? setting['number-separator'] : ':') + elem['imageName']; 531 | }); 532 | } 533 | 534 | // store responsed content from GM_xhr 535 | // Updated on 1.19: Now the index argument is the page's number - 1 (original is page's number) 536 | function storeRes(res, index) { 537 | imageData[index] = res; 538 | downloadedCount++; 539 | console.log('[EHD] Index >', index + 1, ' | RealIndex >', imageList[index]['realIndex'], ' | Name >', imageList[index]['imageName'], ' | RetryCount >', retryCount[index], ' | DownloadedCount >', downloadedCount, ' | FetchCount >', fetchCount, ' | FailedCount >', failedCount); 540 | fetchCount--; 541 | 542 | updateTotalStatus(); 543 | if (!isPausing) checkFailed(); 544 | 545 | res = null; 546 | } 547 | 548 | function generateZip(isFromFS, fs, isRetry, forced){ 549 | isSaving = true; 550 | 551 | // remove pause button 552 | if (!forced && ehDownloadDialog.contains(ehDownloadPauseBtn)) { 553 | ehDownloadDialog.removeChild(ehDownloadPauseBtn); 554 | while (fetchThread[0]) { 555 | fetchThread.pop(); 556 | } 557 | } 558 | 559 | if (!isFromFS && !isRetry) { 560 | if (setting['save-info-list'].toString().indexOf('page-links') >= 0) { 561 | imageList.forEach(function(elem, index){ 562 | // Image URL may useless, see https://github.com/ccloli/E-Hentai-Downloader/issues/6 563 | infoStr += '\n\nPage ' + elem['realIndex'] + ': ' + elem['pageURL'] + '\nImage ' + elem['realIndex'] + ': ' + elem['imageName'] /*+ '\nImage URL: ' + elem['imageURL']*/; 564 | }); 565 | } 566 | pushDialog('\nFinish downloading at ' + new Date() + '\n'); 567 | infoStr += '\n\nDownloaded at ' + new Date() + '\n\nGenerated by E-Hentai Downloader. https://github.com/ccloli/E-Hentai-Downloader'; 568 | 569 | if (setting['save-info'] === 'file' || !setting['save-info']) { 570 | (dirName && !ehDownloadRegex.slashOnly.test(dirName) ? zip.folder(dirName) : zip).file('info.txt', infoStr.replace(/\n/gi, '\r\n')); 571 | } 572 | } 573 | 574 | pushDialog('\n\nGenerating Zip file...\n'); 575 | 576 | var fs = fs || ehDownloadFS.fs; 577 | 578 | var progress = document.createElement('progress'); 579 | var curFile = document.createElement('div'); 580 | progress.className = 'ehD-pt-gen-progress'; 581 | curFile.className = 'ehD-pt-gen-filename'; 582 | curFile.textContent = ' '; 583 | ehDownloadDialog.appendChild(progress); 584 | ehDownloadDialog.appendChild(curFile); 585 | ehDownloadDialog.scrollTop = ehDownloadDialog.scrollHeight; 586 | 587 | var saveToFileSystem = function(abData) { 588 | curFile.textContent = ' '; 589 | 590 | var fsErrorHandler = function(error) { 591 | ehDownloadFS.errorHandler(error); 592 | ehDownloadFS.removeAllFiles(); 593 | 594 | if (confirm('An error occured when storing files to FileSystem.\n' + 595 | 'Error Name: ' + (error.name || 'Unknown Error') + '\n' + 596 | 'Error Message: ' + error.message + '\n\n' + 597 | 'Should I try FileSystem again (Yes) or redirect to try using Blob (No)? \n' + 598 | '* If the error message shows there\'s no more free disk space, try removing some files from the drive where Chrome installed (mostly C: on Windows)')) { 599 | saveToFileSystem(abData); 600 | } 601 | else { 602 | ehDownloadFS.needFileSystem = false; 603 | saveToBlob(abData); 604 | } 605 | }; 606 | 607 | var fs = fs || ehDownloadFS.fs; 608 | pushDialog('\n\nSlicing and storing Zip file to FileSystem...'); 609 | var data = abData; 610 | var dataIndex = 0; 611 | var dataLength = data.byteLength; 612 | var loopWrite = function(fileEntry){ 613 | fileEntry.createWriter(function(fileWriter){ 614 | //fileWriter.seek(fileWriter.length); 615 | dataIndex = fileWriter.length; 616 | if (dataIndex >= dataLength) { 617 | data = undefined; 618 | abData = undefined; 619 | return setTimeout(function(){ 620 | ehDownloadFS.saveAs(isFromFS ? fs : undefined, forced); 621 | isSaving = false; 622 | }, 1500); 623 | } 624 | fileWriter.seek(dataIndex); 625 | var dataLastIndex = dataIndex + 1024 * 1024 * 10; 626 | // I tried setting it as 100MB but some parts were still gone, so I have to make it smaller. 627 | console.log('[EHD] DataIndex >', dataIndex, '| DataLastIndex >', dataLastIndex, '| FileWriterLength >', fileWriter.length, '| DataLength >', dataLength); 628 | pushDialog('\n' + dataIndex + '-' + dataLastIndex + '/' + dataLength); 629 | var blob = createBlob([data.slice(dataIndex, dataLastIndex)], {type: 'application/zip'}); 630 | fileWriter.write(blob); 631 | if ('close' in blob) blob.close(); // File Blob.close() API, not supported by all the browser now 632 | blob = null; 633 | setTimeout(loopWrite, 100, fileEntry); 634 | }, fsErrorHandler); 635 | }; 636 | 637 | fs.root.getFile(unsafeWindow.gid + '.zip', {create: true}, function(fileEntry){ 638 | if (fileEntry.isFile) fileEntry.remove(function(){ 639 | console.log('[EHD] File', fileName, 'is removed.'); 640 | }, fsErrorHandler); 641 | else if (fileEntry.isDirectory) fileEntry.removeRecursively(function() { 642 | console.log('[EHD] Directory', fileName, 'is removed.'); 643 | }, fsErrorHandler); 644 | 645 | fs.root.getFile(unsafeWindow.gid + '.zip', {create: true}, loopWrite, fsErrorHandler); 646 | }, fsErrorHandler); 647 | //fs.root.getFile(unsafeWindow.gid + '.zip', {create: true}, loopWrite, fsErrorHandler); 648 | }; 649 | 650 | var saveToBlob = function(abData){ 651 | curFile.textContent = 'Generating Blob object...'; 652 | var save = function() { 653 | // rebuild blob object if "File is not exist" occured 654 | var blob = createBlob([abData], {type: setting['save-as-cbz'] ? 'application/vnd.comicbook+zip' : 'application/zip'}); 655 | saveAs(blob, fileName + (setting['save-as-cbz'] ? '.cbz' : '.zip')); 656 | 657 | setTimeout(function(){ 658 | if ('close' in blob) blob.close(); 659 | blob = null; 660 | }, 10e3); // 10s to fixed Chrome delay downloads 661 | } 662 | save(); 663 | 664 | var redownloadBtn = document.createElement('button'); 665 | redownloadBtn.textContent = 'Not download? Click here to download'; 666 | redownloadBtn.addEventListener('click', save); 667 | ehDownloadDialog.appendChild(redownloadBtn); 668 | 669 | if (!forced) { 670 | insertCloseButton(function() { 671 | redownloadBtn.removeEventListener('click', save); 672 | ehDownloadDialog.removeChild(redownloadBtn); 673 | abData = null; 674 | save = null; 675 | }); 676 | } 677 | isSaving = false; 678 | }; 679 | 680 | var errorHandler = function (error) { 681 | pushDialog('An error occurred when generating Zip file as ArrayBuffer.'); 682 | console.error('[EHD] An error occurred when generating Zip file as ArrayBuffer.'); 683 | console.error(error); 684 | if (confirm('An error occurred when generating Zip file as ArrayBuffer. Try again?')) return generateZip(isFromFS, fs, 1); 685 | 686 | var fsErrorHandler = function(error) { 687 | ehDownloadFS.errorHandler(error); 688 | ehDownloadFS.removeAllFiles(); 689 | 690 | if (confirm('An error occured when storing files to FileSystem.\n' + 691 | 'Error Name: ' + (error.name || 'Unknown Error') + '\n' + 692 | 'Error Message: ' + error.message + '\n\n' + 693 | 'Should I try again (Yes) or stop it (No, and the downloaded file will be removed)? \n' + 694 | '* If the error message shows there\'s no more free disk space, try removing some files from the drive where Chrome installed (mostly C: on Windows)')) { 695 | generateZip(isFromFS, fs, isRetry, forced); 696 | } 697 | }; 698 | 699 | if (isFromFS || ehDownloadFS.needFileSystem) { 700 | // if enabled file system, then store all files into file system 701 | pushDialog('Storing files into File System...'); 702 | var files = zip.file(/.*/); 703 | var fileIndex = 0; 704 | var filesLength = files.length; 705 | var initFS = function(r){ 706 | fs = r; 707 | fs.root.getDirectory('raw', {create: true}, loopWrite, fsErrorHandler); 708 | }; 709 | var loopWrite = function(){ 710 | fs.root.getFile('raw/' + files[fileIndex]['name'], {create: true}, function(fileEntry){ 711 | fileEntry.createWriter(function(fileWriter){ 712 | console.log('[EHD] FileIndex >', fileIndex, '| FilesLength >', filesLength); 713 | var blob = createBlob([files[fileIndex].asArrayBuffer()], {type: 'application/octet-stream'}); 714 | fileWriter.write(blob); 715 | if ('close' in blob) blob.close(); // File Blob.close() API, not supported by all the browser now 716 | blob = null; 717 | fileIndex++; // some files may still gone in this way, I have no good way to solve it 718 | if (fileIndex < filesLength) setTimeout(loopWrite, 100); 719 | else { 720 | fs.root.getFile('config.txt', {create: true}, function(fileEntry){ 721 | fileEntry.createWriter(function(fileWriter){ 722 | var t = JSON.stringify({fileName: fileName, dirName: dirName}); 723 | var blob = createBlob([t], {type: 'text/plain'}); 724 | fileWriter.write(blob); 725 | if ('close' in blob) blob.close(); // File Blob.close() API, not supported by all the browser now 726 | blob = null; 727 | pushDialog('Success!\nPlease close this tab and open a new tab to download.\nIf you still can\'t download it, try using HTML5 FileSystem Explorer to save them.'); 728 | 729 | files.forEach(function(elem){ 730 | zip.remove(elem.name); 731 | }); 732 | zip = undefined; 733 | isSaving = false; 734 | }); 735 | }); 736 | } 737 | }, fsErrorHandler); 738 | }, fsErrorHandler); 739 | }; 740 | requestFileSystem(window.TEMPORARY, 1024 * 1024 * 1024 * 1024, initFS, fsErrorHandler); 741 | } 742 | } 743 | 744 | try { 745 | var lastMetaTime = 0; 746 | var generateConfig = { 747 | type: 'arraybuffer', 748 | compression: setting['compression-level'] ? 'DEFLATE' : 'STORE', 749 | compressionOptions: { 750 | level: Math.min(Math.max(setting['compression-level'], 1), 9) 751 | }, 752 | streamFiles: setting['file-descriptor'] ? true : false, 753 | comment: setting['save-info'] === 'comment' ? infoStr.replace(/\n/gi, '\r\n') : undefined 754 | }; 755 | var onProgress = function (meta) { 756 | // meta update function will be called nearly every 1ms, for performance, update every 300ms 757 | // anyway it's still too fast so that you may still cannot see the update 758 | var thisMetaTime = Date.now(); 759 | if (thisMetaTime - lastMetaTime < 300) { 760 | return; 761 | } 762 | lastMetaTime = thisMetaTime; 763 | progress.value = meta.percent / 100; 764 | curFile.textContent = meta.currentFile || 'Calculating extra data...'; 765 | }; 766 | 767 | var defaultHandle = function() { 768 | // build arraybuffer object to detect if it generates successfully 769 | zip.generateAsync(generateConfig, onProgress).then(function (abData) { 770 | progress.value = 1; 771 | 772 | if (isFromFS || ehDownloadFS.needFileSystem) { // using filesystem to save file is needed 773 | saveToFileSystem(abData); 774 | } 775 | else { // or just using blob 776 | saveToBlob(abData); 777 | } 778 | 779 | if (!forced) { 780 | if (emptyAudio) { 781 | emptyAudio.pause(); 782 | } 783 | zip.file(/.*/).forEach(function (elem) { 784 | zip.remove(elem.name); 785 | }); 786 | } 787 | abData = undefined; 788 | }).catch(errorHandler); 789 | }; 790 | 791 | var streamHandle = function () { 792 | var stream = zip.generateInternalStream(generateConfig, onProgress); 793 | var fs = fs || ehDownloadFS.fs; 794 | var writer; 795 | 796 | var fsErrorHandler = function (err) { 797 | console.error('[EHD] An error occurred when generating Zip file as stream, fallback to default generate.'); 798 | console.error(err); 799 | pushDialog('An error occurred when generating Zip file as stream, fallback to default generate.'); 800 | stream.pause(); 801 | defaultHandle(); 802 | }; 803 | 804 | var chunk = []; 805 | var done = false; 806 | stream.on('data', function (data, meta) { 807 | if (!writer) { 808 | throw new Error('FileWriter is not usable.'); 809 | } 810 | 811 | onProgress(meta); 812 | chunk.push(data); 813 | }).on('end', function () { 814 | progress.value = 1; 815 | 816 | if (!forced) { 817 | if (emptyAudio) { 818 | emptyAudio.pause(); 819 | } 820 | zip.file(/.*/).forEach(function (elem) { 821 | zip.remove(elem.name); 822 | }); 823 | } 824 | done = true; 825 | }).on('error', fsErrorHandler); 826 | 827 | fs.root.getFile(unsafeWindow.gid + '.zip', { create: true }, function (fileEntry) { 828 | if (fileEntry.isFile) fileEntry.remove(function () { 829 | console.log('[EHD] File', fileName, 'is removed.'); 830 | }, fsErrorHandler); 831 | else if (fileEntry.isDirectory) fileEntry.removeRecursively(function () { 832 | console.log('[EHD] Directory', fileName, 'is removed.'); 833 | }, fsErrorHandler); 834 | 835 | fs.root.getFile(unsafeWindow.gid + '.zip', { create: true }, function (entry) { 836 | entry.createWriter(function (fileWriter) { 837 | writer = fileWriter; 838 | writer.onwriteend = function (e) { 839 | if (done && !chunk.length) { 840 | setTimeout(function () { 841 | ehDownloadFS.saveAs(isFromFS ? fs : undefined, forced); 842 | isSaving = false; 843 | }, 0); 844 | return; 845 | } 846 | var blob = createBlob(chunk, { type: 'application/zip' }); 847 | writer.write(blob); 848 | if ('close' in blob) blob.close(); // File Blob.close() API, depreated 849 | blob = null; 850 | chunk = []; 851 | }; 852 | writer.onerror = fsErrorHandler; 853 | if (stream) { 854 | stream.resume(); 855 | setTimeout(() => { 856 | writer.write(new Blob(chunk, { type: 'application/zip' })); 857 | }, 0); 858 | } 859 | }); 860 | }, fsErrorHandler); 861 | }, fsErrorHandler); 862 | } 863 | 864 | if (isFromFS || ehDownloadFS.needFileSystem) { 865 | streamHandle(); 866 | return; 867 | } 868 | defaultHandle(); 869 | } 870 | catch (error) { 871 | errorHandler(error); 872 | } 873 | } 874 | 875 | // update progress table info 876 | function updateProgress(nodeList, data) { 877 | if (data.name !== undefined) nodeList.fileName.textContent = data.name; 878 | if (data.progress !== undefined && !Number.isNaN(data.progress)) nodeList.progress.value = data.progress; 879 | if (data.progressText !== undefined) nodeList.progressText.textContent = data.progressText; 880 | if (data.status !== undefined) nodeList.statusText.textContent = data.status; 881 | if (data.class !== undefined) nodeList.current.className = ['ehD-pt-item', data.class].join(' ').trim(); 882 | } 883 | 884 | // update ehDownloadStatus 885 | function updateTotalStatus(){ 886 | ehDownloadStatus.textContent = 'Total: ' + totalCount + ' | Downloading: ' + fetchCount + ' | Succeed: ' + downloadedCount + ' | Failed: ' + failedCount; 887 | if (needTitleStatus) document.title = '[' + (isPausing ? '❙❙' : downloadedCount < totalCount ? '↓ ' + downloadedCount + '/' + totalCount : totalCount === 0 ? '↓' : '√' ) + '] ' + pretitle; 888 | } 889 | 890 | // Updated on 1.19: Now the index argument is the page's number - 1 (original is page's number) 891 | function failedFetching(index, nodeList, forced){ 892 | if (!isDownloading || imageData[index] instanceof ArrayBuffer) return; // Temporarily fixes #31 893 | if (typeof fetchThread[index] !== 'undefined' && 'abort' in fetchThread[index]) fetchThread[index].abort(); 894 | console.error('[EHD] Index >', index + 1, ' | RealIndex >', (imageList[index] || {})['realIndex'], ' | Name >', (imageList[index] || {})['imageName'], ' | RetryCount >', retryCount[index], ' | DownloadedCount >', downloadedCount, ' | FetchCount >', fetchCount, ' | FailedCount >', failedCount); 895 | 896 | if (!forced && retryCount[index] < (setting['retry-count'] !== undefined ? setting['retry-count'] : 3)) { 897 | retryCount[index]++; 898 | fetchOriginalImage(index, nodeList); 899 | } 900 | else { 901 | updateProgress(nodeList, { 902 | class: 'ehD-pt-failed' 903 | }); 904 | 905 | if (imageList[index]) { 906 | imageList[index]['imageFinalURL'] = null; 907 | } 908 | failedCount++; 909 | if (!isPausing || !setting['force-pause']) fetchCount--; 910 | 911 | updateTotalStatus(); 912 | checkFailed(); 913 | } 914 | } 915 | 916 | function saveDownloaded(forced){ 917 | renameImages(); 918 | 919 | for (var j = 0; j < imageData.length; j++) { 920 | if (imageData[j] != null && imageData[j] !== 'Fetching') { 921 | (dirName && !ehDownloadRegex.slashOnly.test(dirName) ? zip.folder(dirName) : zip).file(imageList[j]['imageName'], imageData[j]); 922 | if (!forced) imageData[j] = null; 923 | } 924 | } 925 | generateZip(false, undefined, false, forced); 926 | if (forced) { 927 | // if force download zip file, image data should be recoverd to original content 928 | imageList.forEach(function(elem, index) { 929 | elem.equalCount = 1; 930 | elem.imageName = elem._imageName; 931 | }); 932 | } 933 | } 934 | 935 | function checkFailed() { 936 | if (downloadedCount + failedCount < totalCount) { // download not finished, some files are not being called to download 937 | requestDownload(); 938 | } 939 | else if (failedCount > 0) { // all files are called to download and some files can't be downloaded 940 | if (fetchCount === 0) { // all files are finished downloading 941 | for (var i = 0; i < fetchThread.length; i++) { 942 | if (typeof fetchThread[i] !== 'undefined' && 'abort' in fetchThread[i]) fetchThread[i].abort(); 943 | } 944 | if (setting['number-auto-retry'] || confirm('Some images failed to download. Would you like to try them again?')) { 945 | retryAllFailed(); 946 | } 947 | else { 948 | var failedPages = []; 949 | for (var i = 0; i < imageData.length; i++) { 950 | if (imageData[i] == null || imageData[i] === 'Fetching') { 951 | failedPages.push(i + 1); 952 | } 953 | } 954 | pushDialog('\nFetch images failed.\nFailed Pages: ' + failedPages.join(',') + '\n'); 955 | if (setting['auto-download-cancel'] || confirm('Fetch images failed, Please try again later.\n\nWould you like to download downloaded images?')) { 956 | saveDownloaded(); 957 | } 958 | else { 959 | insertCloseButton(); 960 | } 961 | isDownloading = false; 962 | 963 | loadImageLimits(true); 964 | } 965 | } 966 | } 967 | else { // all files are downloaded successfully 968 | renameImages(); 969 | for (var j = 0; j < totalCount; j++) { 970 | (dirName && !ehDownloadRegex.slashOnly.test(dirName) ? zip.folder(dirName) : zip).file(imageList[j]['imageName'], imageData.shift()); 971 | } 972 | generateZip(); 973 | isDownloading = false; 974 | 975 | loadImageLimits(true); 976 | } 977 | } 978 | 979 | // Updated on 1.19: Now the index argument is the page's number - 1 (original is page's number) 980 | function fetchOriginalImage(index, nodeList) { 981 | // GM_xhr 于 GreaseMonkey 2.3 / 2.4 中开始支持 responseType 以获取返回类型为 ArrayBuffer 的请求 982 | // GM_xhr support responseType to fetch ArrayBuffer request on 2.3 / 2.4 983 | // https://github.com/greasemonkey/greasemonkey/issues/1834 984 | //console.log(imageList[index]); 985 | if (retryCount[index] === undefined) retryCount[index] = 0; 986 | if (isPausing) return; 987 | 988 | var requestURL = imageList[index]['imageFinalURL'] || imageList[index]['imageURL']; 989 | var needScrollIntoView = ehDownloadDialog.clientHeight + ehDownloadDialog.scrollTop >= ehDownloadDialog.scrollHeight - 5; 990 | 991 | if (setting['original-download-domain']) { 992 | requestURL = requestURL.replace(location.hostname, setting['original-download-domain']); 993 | } 994 | 995 | if (nodeList === undefined) { 996 | var node = progressTable.querySelector('tr[data-index="' + index + '"]'); 997 | if (!node) { 998 | node = document.createElement('tr'); 999 | node.className = 'ehD-pt-item'; 1000 | node.setAttribute('data-index', index); 1001 | node.innerHTML = '\ 1002 |
#' + imageList[index]['realIndex'] + ': ' + imageList[index]['imageName'] + '\ 1004 | \ 1005 | \ 1006 | \ 1008 | Pending...\ 1009 | Force Abort\ 1010 | #' + realIndex + '\ 2201 | \ 2202 | \ 2203 | \ 2205 | Pending...\ 2206 | Force Abort\ 2207 |