├── .gitignore ├── .jsbeautifyrc ├── .jshintrc ├── LICENSE ├── README.md ├── chronoExampleRule.png ├── createRelease.sh ├── download.zip ├── originCheck.html ├── source ├── HackTimer.js ├── HackTimerWorker.js ├── backgroundManager.js ├── blankLogo.png ├── comicReader.js ├── common.js ├── diffMatchPatch.js ├── logo.png ├── logo128.png ├── logo48.png ├── manifest.json ├── metaData.js ├── myBooks.js ├── options │ ├── League-Gothic.otf │ ├── jquery-2.1.4.min.js │ ├── logoOptions.png │ ├── logoOptions@2x.png │ ├── options.css │ ├── options.html │ ├── options.js │ ├── toastr.css │ └── toastr.js ├── reactivateDom.js ├── throttleBlocker.js └── zip │ ├── deflate.js │ ├── z-worker.js │ └── zip.js └── version /.gitignore: -------------------------------------------------------------------------------- 1 | source.pem 2 | *.log 3 | -------------------------------------------------------------------------------- /.jsbeautifyrc: -------------------------------------------------------------------------------- 1 | { 2 | "js": { 3 | "indent_level": 0, 4 | "indent_with_tabs": true, 5 | "brace_style": "end-expand", 6 | "space_after_anon_function": false, 7 | "space_before_conditional": false, 8 | "preserve_newlines": true, 9 | "max_preserve_newlines": 2, 10 | "end_with_newline": true 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /.jshintrc: -------------------------------------------------------------------------------- 1 | { 2 | "scripturl": true, 3 | "eqnull": true, 4 | "loopfunc": true, 5 | "browser": true, 6 | "globalstrict": true, 7 | "esnext": true, 8 | "globals": { 9 | "div": true, 10 | "addTopBar": true, 11 | "updateDialog": true, 12 | "checkVersion": true, 13 | "linkStyle": true, 14 | "diff_match_patch": true, 15 | "sanitizeFilename": true, 16 | "rgbToHsl": true, 17 | "hslToRgb": true, 18 | "dataURLtoBlob": true, 19 | "zip": true, 20 | "getSettings": true, 21 | "connector": true, 22 | "downloadFile": true, 23 | "nullFill": true, 24 | "settings": true, 25 | "updateDialog": true, 26 | "randomString": true, 27 | "Queue": true, 28 | "chrome": true, 29 | "TEMPORARY": true, 30 | "currentVersion": true, 31 | "MetaData": true, 32 | "toastr": true, 33 | "throttleBlocker": true, 34 | "minPxVal": true, 35 | "RTCPeerConnection": true 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /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 | 635 | Copyright (C) 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 | Copyright (C) 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 | . -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Comic Backup 2 | ====== 3 | 4 | This is a Chrome/Chromium extension, that allows you to download all the comics you bought on ~~Comix~~ *a popular online comic platform* :wink:. After the installation you are able to download comics from any publisher. It should work on any OS where Chrome works. 5 | 6 | *IMPORTANT:* Do not use the extension for piracy! Only create private backups! We do not intend to compromise any comic platform. **Downloaded comics always have your username included. Distributed comics can be [tracked back](https://cortys.github.io/comic-backup/originCheck) to you!** 7 | 8 | Installation 9 | ----- 10 | 11 | The installation is slightly complicated (since I don't want to add this to the Chrome Store). 12 | 13 | - In Chrome, click on the settings icon on the right (looks like three vertical lines on top of each other) 14 | - Select Tools > Extensions 15 | - Select "Developer mode" 16 | - Click on "Load unpacked extension" 17 | - Select the "source" folder 18 | - Done. :tada: 19 | 20 | ### Updates 21 | 22 | If you want to be notified about updates you can add an update server in the extensions options. You get there by opening the extensions panel in the settings and then click on "Options" right to the Comic Backup extension. The options should open and you should see an input field in the Updates section. 23 | 24 | The default update server URL is: `https://raw.githubusercontent.com/Cortys/comic-backup/master` 25 | 26 | ### Why it's not on Chrome Store? 27 | 28 | I am fairly certain that *certain comic platforms* will, unfortunately, try to remove this extension from Chrome Store, because it goes around their DRM. 29 | 30 | How to use 31 | ----- 32 | 33 | * Install the extension as described above. 34 | * Open your online comic library by clicking on "My Books" in the menu. 35 | * To start a backup simply click the "Scan Comic" button, that should now appear next to each comic. 36 | * Some comics also offer a direct PDF and CBZ download. Those are official high quality downloads available for a selection of publishers. 37 | * Sometimes backups of comics with many pages (~200+) fail. To circumvent that you can enable *single image* container compression in the options and all the pages of the comic will be downloaded as separate images. To get a CBZ you then have to zip the images manually. 38 | 39 | It's not working! Help! 40 | ---- 41 | ***What to do first?*** Some problems can be resolved by taking a look at the *Options* of the extension. 42 | 43 | ***This did not help! All downloaded files have cryptic names like `33984c2d-3fb2-46c3-a8f2-f1982ca0d2fa`. What to do?*** You are probably using a download manager like [Chrono Download Manager](https://www.chronodownloader.net/). You'll have to teach it to play together nicely with this extension. In *Chrono* this can be done by adding a rule like this: 44 | ![Screenshot of the Chrono Rule System Options](chronoExampleRule.png) 45 | * Condition: `*anchor*.beginwith("comic-backup/")` 46 | * Naming mask: `*anchor*` 47 | 48 | ***That also didn't help!*** :confused: Please open an issue on GitHub then. 49 | 50 | How it works 51 | ----- 52 | You can look at the source code - but basically, if you start a scan it opens the web reader in the background and automatically navigates through all the pages. For every page it fetches the pixel data from the corresponding underlying canvas elements in the reader's DOM. Finally it downloads all the fetched data as a CBZ using zip.js or as single image blobs using JavaScript-Canvas-to-Blob. 53 | 54 | About, licence 55 | ---- 56 | 57 | Project started by SpergLord Enterprises, LLC and continued by other awesome contributors. 58 | 59 | The code is licensed under GPLv3. 60 | 61 | It uses these awesome projects: 62 | * [zip.js](https://github.com/gildas-lormeau/zip.js) by Gildas Lormeau 63 | * [JavaScript-Canvas-to-Blob](https://github.com/blueimp/JavaScript-Canvas-to-Blob) by Sebastian Tschan 64 | * [Toastr](https://github.com/CodeSeven/toastr) by CodeSeven 65 | * [League Gothic](https://github.com/theleagueof/league-gothic) by Caroline Hadilaksono, Micah Rich, & Tyler Finck 66 | -------------------------------------------------------------------------------- /chronoExampleRule.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Cortys/comic-backup/293088791537283dd126f84f7d7211b3a33ab369/chronoExampleRule.png -------------------------------------------------------------------------------- /createRelease.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | cd "${BASH_SOURCE%/*}" || exit 4 | rm download.zip 5 | zip -r download.zip . -x .git/\* .gitignore .jshintrc .jsbeautifyrc ./\*\*/.DS_Store createRelease.sh 6 | -------------------------------------------------------------------------------- /download.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Cortys/comic-backup/293088791537283dd126f84f7d7211b3a33ab369/download.zip -------------------------------------------------------------------------------- /originCheck.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Comic Backup 6 | 23 | 24 | 25 | 26 |

Origin check

27 |

28 | Add a backuped file here and we will tell you who created it.

29 |

30 |

31 | 32 |

33 | The username you are looking for should be somewhere in here: 34 |

...
35 |

36 | 77 | 78 | 79 | -------------------------------------------------------------------------------- /source/HackTimer.js: -------------------------------------------------------------------------------- 1 | (function(s){var w,f={},o=window,l=console,m=Math,z='postMessage',p=0,r='hasOwnProperty',y=[].slice,x='fail',v=Worker;function d(){do{p=0x7FFFFFFF>p?p+1:0}while(f[r](p))return p}try{s=o.URL.createObjectURL(new Blob(["var f={},p=postMessage,r='hasOwnProperty';onmessage=function(e){var d=e.data,i=d.i,t=d[r]('t')?d.t:0;switch(d.n){case'a':f[i]=setInterval(function(){p(i)},t);break;case'b':if(f[r](i)){clearInterval(f[i]);delete f[i]}break;case'c':f[i]=setTimeout(function(){p(i);if(f[r](i))delete f[i]},t);break;case'd':if(f[r](i)){clearTimeout(f[i]);delete f[i]}break}}"]))}catch(e){}if(typeof(v)!=='undefined'){try{w=new v(s);o.setInterval=function(c,t){var i=d();f[i]={c:c,p:y.call(arguments,2)};w[z]({n:'a',i:i,t:t});return i};o.clearInterval=function(i){if(f[r](i))delete f[i],w[z]({n:'b',i:i})};o.setTimeout=function(c,t){var i=d();f[i]={c:c,p:y.call(arguments,2),t:!0};w[z]({n:'c',i:i,t:t});return i};o.clearTimeout=function(i){if(f[r](i))delete f[i],w[z]({n:'d',i:i})};w.onmessage=function(e){var i=e.data,c,n;if(f[r](i)){n=f[i];c=n.c;if(n[r]('t'))delete f[i]}if(typeof(c)=='string')try{c=new Function(c)}catch(k){}if(typeof(c)=='function')c.apply(o,n.p)}}catch(e){l.log(x)}}else l.log(x)})('HackTimerWorker.js'); 2 | -------------------------------------------------------------------------------- /source/HackTimerWorker.js: -------------------------------------------------------------------------------- 1 | var f={},p=postMessage,r='hasOwnProperty';onmessage=function(e){var d=e.data,i=d.i,t=d[r]('t')?d.t:0;switch(d.n){case'a':f[i]=setInterval(function(){p(i)},t);break;case'b':if(f[r](i)){clearInterval(f[i]);delete f[i]}break;case'c':f[i]=setTimeout(function(){p(i);if(f[r](i))delete f[i]},t);break;case'd':if(f[r](i)){clearTimeout(f[i]);delete f[i]}break}} 2 | -------------------------------------------------------------------------------- /source/backgroundManager.js: -------------------------------------------------------------------------------- 1 | //Code is under GNUGPLv3 - read http://www.gnu.org/licenses/gpl.html 2 | "use strict"; 3 | 4 | zip.useWebWorkers = true; 5 | 6 | zip.workerScripts = { 7 | deflater: ['zip/z-worker.js', 'zip/deflate.js'], 8 | }; 9 | 10 | var ports = { // stores all opened connections of tabs to bg page: key = tab id, value = port object 11 | reader: {}, // reader tab connections 12 | controller: {} // controller tab connections 13 | }, 14 | openers = {}, // contains the opener tab id as value for each child tab id as key 15 | closedReader = function(port) { 16 | var sender = port.senderId; 17 | if(!port.fake) { // used when a reader is closed, that was not yet initialized and connected via its own port. 18 | if(!port.zipFile) 19 | URL.revokeObjectURL(port.zipUrl); 20 | else 21 | port.zipFile.remove(function() { 22 | port.zipFile = null; 23 | }); 24 | } 25 | if(typeof openers[sender] !== "undefined") { 26 | var opener = ports.controller[openers[sender]]; 27 | if(opener) { 28 | opener.send({ 29 | what: "child_message", 30 | tab: sender, 31 | message: { 32 | what: "closed_background_tab" 33 | } 34 | }); 35 | delete opener.children[sender]; 36 | } 37 | delete openers[sender]; 38 | } 39 | }, 40 | getWriter = function(callback) { 41 | callback(new zip.BlobWriter("application/" + (settings.container ? "zip" : "x-cbz"))); 42 | }; 43 | 44 | getSettings(function() { 45 | 46 | connector.onConnect.addListener(function(port) { 47 | 48 | if(port.name == "download") { 49 | port.receive(function(request, callback) { 50 | downloadFile(request.name, request.data, request.overwrite, callback); 51 | }); 52 | return true; 53 | } 54 | 55 | var sender = port.senderId = port.sender.tab.id; 56 | 57 | ports[port.name][sender] = port; 58 | 59 | if(port.name == "controller") 60 | port.children = {}; // each connection stores the ids of the tabs it opened as children; key = tab id, value always true 61 | 62 | /* ZIPPING logic 63 | * moved to background script to have a dedicated tab/thread for compression so 64 | * that it doesn't make the reader tab itself slow 65 | */ 66 | if(port.name == "reader") 67 | port.receive(function(request, callback) { 68 | if(request.what == "new_zip") { 69 | getWriter(function(writer, zipFile) { 70 | port.zipFile = zipFile; 71 | zip.createWriter(writer, function(writer) { 72 | port.zip = writer; 73 | port.user = request.user; 74 | writer.add(".meta.asc", new zip.TextReader("This is a ComiXology backup.\nPlease do not distribute it.\nBackup created by " + (request.user || "[UNKNOWN USER]")), function() {}); 75 | callback({ 76 | what: "new_zip_created", 77 | error: false 78 | }); 79 | }, function() { 80 | callback({ 81 | what: "zip_creation_failed", 82 | error: true 83 | }); 84 | }, !settings.compression); 85 | }); 86 | return true; 87 | } 88 | else if(request.what == "add_page") { 89 | var name = "page" + nullFill(request.i, request.len) + "." + request.extension, 90 | d = callback.bind(null, { 91 | what: "page_added", 92 | name: name 93 | }); 94 | if(request.toZip && port.zip) { 95 | port.zip.add(name, new zip.Data64URIReader(request.page), function() { 96 | d(); 97 | }, undefined, { 98 | comment: port.user 99 | }); 100 | return true; 101 | } 102 | d(); 103 | } 104 | else if(request.what == "start_zipping" && port.zip) { 105 | port.zip.close(function(result) { 106 | port.zip = null; 107 | port.zipUrl = port.zipFile ? port.zipFile.toURL() : URL.createObjectURL(result); 108 | callback({ 109 | what: "completed_zipping" 110 | }); 111 | }, request.comment); 112 | return true; 113 | } 114 | else if(request.what == "download_blob") { 115 | downloadFile(request.name, port.zipUrl, false, function() { 116 | if(!port.zipFile) 117 | URL.revokeObjectURL(port.zipUrl); 118 | else 119 | port.zipFile.remove(function() { 120 | port.zipFile = null; 121 | }); 122 | callback({ 123 | what: "download_complete" 124 | }); 125 | }); 126 | return true; 127 | } 128 | else if(request.what == "message_to_opener" && openers[sender] !== "undefined" && ports.controller[openers[sender]]) { 129 | ports.controller[openers[sender]].send({ 130 | what: "child_message", 131 | tab: sender, 132 | message: request.message 133 | }, callback); 134 | return true; 135 | } 136 | else if(request.what == "broadcast_to_openers") { 137 | for(var tab in ports.controller) { 138 | ports.controller[tab].send({ 139 | what: "child_broadcast", 140 | tab: sender, 141 | message: request.message 142 | }, callback); 143 | } 144 | return true; 145 | } 146 | else if(request.what == "is_child") 147 | callback(sender in openers); 148 | else if(request.what == "unlink_from_opener") // prevents tab to be closed if opener is closed (reader and opener are still connected though and can send messages) 149 | port.unlinked = true; 150 | }); 151 | /* 152 | * TAB HANDLING logic 153 | * for the controller tabs (like "My Books") 154 | */ 155 | else if(port.name == "controller") 156 | port.receive(function(request, callback) { 157 | if(request.what == "open_background_tab") { 158 | chrome.tabs.create({ 159 | url: request.url, 160 | active: request.active 161 | }, function(tab) { 162 | openers[tab.id] = sender; 163 | port.children[tab.id] = true; 164 | ports.reader[tab.id] = true; // fake a reader port, as long as reader wasn't loaded, boolean to make it easy to check for "real" port objects 165 | callback(tab.id); 166 | }); 167 | return true; 168 | } 169 | else if(request.what == "close_background_tab") 170 | chrome.tabs.remove(request.tab, function() { 171 | return chrome.runtime.lastError; 172 | }); 173 | else if(request.what == "message_to_child" && typeof ports.reader[request.tab] === "object") { 174 | ports.reader[request.tab].send({ 175 | what: "opener_message", 176 | message: request.message 177 | }, callback); 178 | return true; 179 | } 180 | }); 181 | 182 | var disconnectAction = port.name == "controller" ? function() { 183 | for(var tab in port.children) 184 | // only not YET estabished or established linked port connections are allowed: 185 | // children that once had a port are not closed (if the user started surfing in a backup tab) 186 | if(typeof ports.reader[tab] === "object" && !ports.reader[tab].unlinked) 187 | chrome.tabs.remove(tab * 1, function() { 188 | return chrome.runtime.lastError; 189 | }); 190 | } : closedReader; 191 | 192 | port.onDisconnect.addListener(function() { 193 | delete ports[port.name][sender]; 194 | disconnectAction(port); 195 | port = sender = null; 196 | }); 197 | }); 198 | 199 | }); 200 | 201 | chrome.tabs.onRemoved.addListener(function(tab) { 202 | if(ports.reader[tab] === true && tab in openers) // tab is a backup-purpose reader but there is no port connection yet: 203 | closedReader({ 204 | senderId: tab, 205 | fake: true 206 | }); // port disconnect wont fire, so it will be "faked". 207 | }); 208 | 209 | // Old communication channel to options page. Separated from the port system to reduce memory and logic overhead. 210 | chrome.runtime.onMessage.addListener(function(request) { 211 | // Only used when settings are changed (e.g. notify background zipper when compression settings were changed at runtime): 212 | if(request.what == "update_settings") 213 | getSettings(); 214 | // Broadcast messages to all readers: 215 | else if(request.what == "reader_message") 216 | ports.reader.forEach(function(v) { 217 | v.send(request.message); 218 | }); 219 | // Broadcast messages to all controllers: 220 | else if(request.what == "controller_message") 221 | for(var i in ports.controller) 222 | ports.controller[i].send(request.message); 223 | }); 224 | -------------------------------------------------------------------------------- /source/blankLogo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Cortys/comic-backup/293088791537283dd126f84f7d7211b3a33ab369/source/blankLogo.png -------------------------------------------------------------------------------- /source/comicReader.js: -------------------------------------------------------------------------------- 1 | //Code is under GNUGPLv3 - read http://www.gnu.org/licenses/gpl.html 2 | "use strict"; 3 | 4 | var overlay = document.createElement("div"); 5 | 6 | overlay.style.position = "fixed"; 7 | overlay.style.zIndex = 299; 8 | overlay.style.top = overlay.style.left = overlay.style.bottom = overlay.style.right = 0; 9 | overlay.style.width = overlay.style.height = "auto"; 10 | overlay.style.background = "rgba(0,0,0,0.3)"; 11 | overlay.style.display = "none"; 12 | document.documentElement.appendChild(overlay); 13 | 14 | (function() { 15 | var favicons = document.head.querySelectorAll("link[rel~=icon]"); 16 | 17 | for(var i = 0; i < favicons.length; i++) 18 | document.head.removeChild(favicons[i]); 19 | }()); 20 | 21 | var favicon = document.createElement("link"); 22 | favicon.type = "image/png"; 23 | favicon.rel = "shortcut icon"; 24 | 25 | document.head.appendChild(favicon); 26 | renderFaviconPercentage(); 27 | 28 | //ENTRANCE POINT FOR READER BACKUP LOGIC: 29 | 30 | var port = connector.connect({ 31 | name: "reader" 32 | }), 33 | swapPage; 34 | 35 | getSettings(function() { 36 | 37 | if(!("pageSwapDelay" in settings)) 38 | settings.pageSwapDelay = 600; 39 | 40 | if(!("pageSkipDelay" in settings)) 41 | settings.pageSkipDelay = 1200; 42 | 43 | if(!settings.pageSwapDelay) 44 | swapPage = function swapPage(callback) { 45 | if(typeof callback === "function") 46 | callback(); 47 | }; 48 | else 49 | swapPage = function swapPage(callback) { 50 | var swap = function() { 51 | swapPage.lastSwap = Date.now(); 52 | if(typeof callback === "function") 53 | callback(); 54 | }, 55 | d = !swapPage.lastSwap ? 0 : settings.pageSwapDelay - (Date.now() - swapPage.lastSwap); 56 | if(d <= 0) 57 | swap(); 58 | else 59 | setTimeout(swap, d); 60 | }; 61 | 62 | // delete cached uncompleted zip-backups for this tab: 63 | port.send({ 64 | what: "is_child" 65 | }, function(isChild) { // tab opened by extension -> autorun / else -> show bar 66 | if(!isChild) { 67 | if(!settings.selectors && settings.selectors != null) 68 | displayExploitBar(); 69 | return; 70 | } 71 | 72 | port.send({ 73 | what: "message_to_opener", 74 | message: { 75 | what: "ready_to_download", 76 | data: getName() 77 | } 78 | }, function(start) { 79 | if(start) { 80 | if(start.download) { 81 | renderFaviconPercentage(0); 82 | 83 | loadComic(function(err) { 84 | port.send({ 85 | what: "message_to_opener", 86 | message: { 87 | what: err ? "download_failed" : "finished_download" 88 | } 89 | }); 90 | }, function(perc) { 91 | port.send({ 92 | what: "message_to_opener", 93 | message: { 94 | what: "download_progress", 95 | data: perc 96 | } 97 | }); 98 | }, start.metaData); 99 | } 100 | else if(start.exploit) { 101 | port.send({ 102 | what: "unlink_from_opener" 103 | }); 104 | setupSelectors(); 105 | } 106 | } 107 | }); 108 | }); 109 | }); 110 | 111 | function renderFaviconPercentage(perc) { 112 | 113 | if(perc === undefined) { 114 | favicon.href = chrome.extension.getURL("blankLogo.png"); 115 | return; 116 | } 117 | 118 | var canvas = document.createElement('canvas'), 119 | ctx = canvas.getContext('2d'); 120 | 121 | canvas.width = canvas.height = 32; 122 | 123 | ctx.globalCompositeOperation = "source-over"; 124 | ctx.fillStyle = perc < 1 ? "#b97c11" : "#6f9305"; 125 | 126 | ctx.beginPath(); 127 | ctx.moveTo(16, 16); 128 | ctx.arc(16, 16, 14, -Math.PI / 2, Math.PI * 2 * (perc - 0.25), false); 129 | ctx.fill(); 130 | ctx.closePath(); 131 | 132 | ctx.globalCompositeOperation = "destination-out"; 133 | 134 | ctx.beginPath(); 135 | ctx.arc(16, 16, 10, 0, Math.PI * 2, false); 136 | ctx.fill(); 137 | ctx.closePath(); 138 | 139 | if(perc < 1) { 140 | ctx.globalCompositeOperation = "source-over"; 141 | ctx.fillStyle = settings.faviconColor ? "#ffffff" : "#000000"; 142 | ctx.font = "13px Arial"; 143 | ctx.textAlign = "center"; 144 | ctx.textBaseline = "middle"; 145 | ctx.fillText("" + Math.round(perc * 100), 16, 16, 18); 146 | } 147 | 148 | favicon.href = canvas.toDataURL("image/png"); 149 | } 150 | 151 | // show orange bar: asking for exploit scan 152 | function displayExploitBar() { 153 | addTopBar(); 154 | div.style.lineHeight = "25px"; 155 | div.innerHTML = "Do you want to start an exploit scan? This is required to backup comics.
No "; 156 | var a = document.createElement("a"); 157 | a.innerHTML = "Yes"; 158 | a.href = "#"; 159 | a.addEventListener('click', function(e) { 160 | e.stopPropagation(); 161 | setupSelectors(); 162 | }, false); 163 | a.setAttribute("style", linkStyle); 164 | div.appendChild(a); 165 | } 166 | 167 | function getPathFor(e, tryE) { // returns css selector that matches e and tryE as well (if that is possible, without two comma seperated selectors) - only tags, ids and classes are used 168 | if(!e) 169 | return ""; 170 | if(e.id) 171 | return "#" + e.id; 172 | var before = getPathFor(e.parentElement) + " > " + e.tagName, 173 | classes = "", 174 | classesBefore, 175 | p = 0, 176 | selection = document.querySelectorAll(before), 177 | selectionBefore, 178 | couldMatch = function() { // returns true if the current state of path could also match tryE (directly or if it was specified further) 179 | if(!tryE) 180 | return true; 181 | var c = tryE; 182 | while(c) { 183 | if(c.matches(before + classes)) 184 | return true; 185 | c = tryE.parentElement; 186 | } 187 | return false; 188 | }; 189 | if(e.classList.length) 190 | do { 191 | classesBefore = classes; 192 | classes += "." + e.classList[p++]; 193 | selectionBefore = selection.length; 194 | selection = document.querySelectorAll(before + classes); 195 | if(selection.length >= selectionBefore || !couldMatch()) 196 | classes = classesBefore; 197 | } while (p < e.classList.length && selection.length > 1); 198 | return before + classes; 199 | } 200 | 201 | function wordDiff(text1, text2) { // word wise difference of two strings (using diff_match_patch library) 202 | 203 | text1 = text1.trim() + " "; 204 | text2 = text2.trim() + " "; 205 | 206 | var lineArray = []; // e.g. lineArray[4] == 'Hello\n' 207 | var lineHash = {}; // e.g. lineHash['Hello\n'] == 4 208 | 209 | // '\x00' is a valid character, but various debuggers don't like it. 210 | // So we'll insert a junk entry to avoid generating a null character. 211 | lineArray[0] = ''; 212 | 213 | /** 214 | * Split a text into an array of strings. Reduce the texts to a string of 215 | * hashes where each Unicode character represents one line. 216 | * Modifies linearray and linehash through being a closure. 217 | * @param {string} text String to encode. 218 | * @return {string} Encoded string. 219 | * @private 220 | */ 221 | function diff_linesToCharsMunge_(text) { 222 | var chars = ''; 223 | // Walk the text, pulling out a substring for each line. 224 | // text.split('\n') would would temporarily double our memory footprint. 225 | // Modifying text would create many large strings to garbage collect. 226 | var lineStart = 0; 227 | var lineEnd = -1; 228 | // Keeping our own length variable is faster than looking it up. 229 | var lineArrayLength = lineArray.length; 230 | while(lineEnd < text.length - 1) { 231 | lineEnd = text.indexOf(' ', lineStart); 232 | if(lineEnd == -1) { 233 | lineEnd = text.length - 1; 234 | } 235 | var line = text.substring(lineStart, lineEnd + 1); 236 | lineStart = lineEnd + 1; 237 | 238 | if(lineHash.hasOwnProperty ? lineHash.hasOwnProperty(line) : 239 | (lineHash[line] !== undefined)) { 240 | chars += String.fromCharCode(lineHash[line]); 241 | } 242 | else { 243 | chars += String.fromCharCode(lineArrayLength); 244 | lineHash[line] = lineArrayLength; 245 | lineArray[lineArrayLength++] = line; 246 | } 247 | } 248 | return chars; 249 | } 250 | 251 | var chars1 = diff_linesToCharsMunge_(text1); 252 | var chars2 = diff_linesToCharsMunge_(text2), 253 | 254 | dmp = new diff_match_patch(), 255 | result = dmp.diff_main(chars1, chars2, false); 256 | 257 | dmp.diff_charsToLines_(result, lineArray); 258 | return result; 259 | } 260 | 261 | function realClick(e) { // simulate a "real" click on given DOMElement e (can't be distinguished from a user click) 262 | if(!e) 263 | return; 264 | var evt = document.createEvent("MouseEvents"), 265 | rect = e.getBoundingClientRect(), 266 | doc = e.ownerDocument, 267 | win = (doc && (doc.defaultView || doc.parentWindow)) || window, 268 | left = rect.left || 1, 269 | top = rect.top || 1; 270 | evt.initMouseEvent("click", true, true, win, 1, left, top, left, top, false, false, false, false, 0, null); 271 | e.dispatchEvent(evt); 272 | } 273 | 274 | var scanPresets = { 275 | selectorActiveOnepageButton: "#onepage-btn.active", 276 | selectorActivePage: "#thumbnails-list > LI > FIGURE.active", 277 | selectorBrowseButton: "#browse-btn > IMG", 278 | selectorOnepageButton: "#onepage-btn", 279 | selectorPages: "#thumbnails-list > LI > FIGURE", 280 | pagenumAttr: "data-pagenumber", 281 | pagenumCorrection: 0 282 | }; 283 | 284 | var dom = { // stores DOM elements of the reader page. All DOM calls go here. No queries elsewhere to make it easier to adapt to reader changes. 285 | pagesCached: null, 286 | canvasContainer: null, 287 | browseButtonCached: null, 288 | onepageButtonCached: null, 289 | 290 | isVisible(e) { 291 | return e.style.display != "none" && e.style.visibility != "hidden"; 292 | }, 293 | 294 | get pages() { 295 | return(this.pagesCached = this.pagesCached) || function() { 296 | 297 | var pages = document.querySelectorAll(settings.selectorPages || scanPresets.selectorPages); 298 | 299 | if(pages.length > 1 && pages[0].getAttribute(this.pagenumAttr) * 1 > pages[pages.length - 1].getAttribute(this.pagenumAttr) * 1) 300 | pages = Array.prototype.slice.call(pages, 0).reverse(); 301 | 302 | return pages; 303 | }.call(this); 304 | }, 305 | get activePage() { 306 | return document.querySelector(settings.selectorActivePage || scanPresets.selectorActivePage); 307 | }, 308 | 309 | loopCanvasContainers(f) { 310 | var a = document.querySelectorAll("div.view"), 311 | v; 312 | for(var i = 0; i < a.length; i++) 313 | if(this.isVisible(a[i]) && (v = f(a[i]))) 314 | return v; 315 | return null; 316 | }, 317 | 318 | getCanvasContainer() { 319 | var t = this; 320 | if(t.canvasContainer && document.contains(t.canvasContainer) && t.isVisible(t.canvasContainer)) 321 | return this.canvasContainer; 322 | return(t.canvasContainer = t.loopCanvasContainers(function(a) { 323 | return a; 324 | })); 325 | }, 326 | get canvasContainerCount() { 327 | var i = 0; 328 | this.loopCanvasContainers(function() { 329 | i++; 330 | }); 331 | return i; 332 | }, 333 | get canvasElements() { 334 | return this.canvasContainer.querySelectorAll("canvas"); 335 | }, 336 | get browseButton() { 337 | return(this.browseButtonCached = this.browseButtonCached) || document.querySelector(settings.selectorBrowseButton || scanPresets.selectorBrowseButton); 338 | }, 339 | get onepageButton() { 340 | return(this.onepageButtonCached = this.onepageButtonCached) || document.querySelector(settings.selectorOnepageButton || scanPresets.selectorOnepageButton); 341 | }, 342 | get activeOnepageButton() { 343 | return document.querySelector(settings.selectorActiveOnepageButton || scanPresets.selectorActiveOnepageButton); 344 | }, 345 | get pagenumAttr() { 346 | return settings.pagenumAttr || scanPresets.pagenumAttr; 347 | }, 348 | get pagenumCorrection() { 349 | return settings.pagenumCorrection != null ? settings.pagenumCorrection : scanPresets.pagenumCorrection; 350 | }, 351 | get loader() { 352 | return document.querySelectorAll(".loading"); 353 | }, 354 | loaderVisible() { 355 | return this.loader && this.loader.length && Array.prototype.reduce.call(this.loader, function(prev, curr) { 356 | return prev || curr.style.display !== "none"; 357 | }, false); 358 | }, 359 | isActivePage(page) { 360 | return page.matches(settings.selectorActivePage || scanPresets.selectorActivePage); 361 | }, 362 | isActiveOnepageButton() { 363 | return this.onepageButton.matches(settings.selectorActiveOnepageButton || scanPresets.selectorActiveOnepageButton); 364 | }, 365 | countCanvas() { 366 | return this.canvasElements.length; 367 | }, 368 | isLoading() { 369 | var view; 370 | return this.canvasContainerCount !== 1 || (view = dom.getCanvasContainer(), !view.style.webkitTransform && !view.style.transform) || dom.loaderVisible() || !dom.canvasElements.length; 371 | } 372 | }; 373 | 374 | function setupSelectors() { // run a DOM scan to analyse how the reader DOM tree is structured and how it should be backuped 375 | /* 376 | - click single page button 377 | - click dual page button 378 | - click browse pages button 379 | - click first page 380 | - click second page 381 | - click on opened comic page 382 | */ 383 | addTopBar(); 384 | window.alert("A new exploit scan has to be made.\nPlease follow the upcoming instructions or the extension may stop working for you."); 385 | var step = -1, // counter: where are we in the setup process? 386 | level = function(s, a) { // toggle between two activatable elements (e.g. opened pages) s and a. Goes up the DOM starting at s until the toggle causes a change of the class-attr of the current ascendant of s. -> the ascendant and the added/removed classes per toggle are returned. 387 | if(!s) 388 | return null; 389 | var classBefore = s.className, 390 | classAfter; 391 | realClick(s); 392 | classAfter = s.className; 393 | realClick(a); 394 | if(classBefore == classAfter) 395 | return level(s.parentElement, a); 396 | return { 397 | e: s, 398 | diff: wordDiff(classBefore, classAfter) 399 | }; 400 | }, 401 | extendPath = function(path, classDiffList) { // add css-class selectors to a given css-selector path. classDiffList is a two dimensional array. the outer array contains all classes that should be added. the inner arrays have two elements: [0]=> -1/0/1 (require class not to be there / ignore this class / require class to be there), [1] => class name 402 | for(var i = 0; i < classDiffList.length; i++) { 403 | if(!classDiffList[i][0]) 404 | continue; 405 | var w = classDiffList[i][1].trim(); 406 | if(w.length) 407 | path += classDiffList[i][0] == 1 ? "." + w : ":not(." + w + ")"; 408 | } 409 | return path; 410 | }, 411 | write = { 412 | selectors: 1, 413 | scannedOnce: 1 414 | }, 415 | steps = [ // steps array contains all the steps of the setup wizard. each step has a text that is displayed to the user, explaining what to do. callback will be called as soon as the user clicks some element on the page (clicked element is passed as parameter). boolean return value of callback determines if setup should be continued or if an error occured. 416 | { 417 | text: "Click the button that enables single page view.", 418 | btn: null, 419 | callback(element) { 420 | this.btn = element; 421 | return !!this.btn; 422 | } 423 | }, { 424 | text: "Click the button that enables dual page view.", 425 | callback(dual) { 426 | var single = steps[0].btn, 427 | states = level(single, dual); 428 | if(!states) 429 | return false; 430 | var inactive = getPathFor(states.e), 431 | active = extendPath(inactive, states.diff); 432 | realClick(single); 433 | write.selectorOnepageButton = inactive; 434 | write.selectorActiveOnepageButton = active; 435 | return inactive && active; 436 | } 437 | }, { 438 | text: "Click the browse button that shows all pages.", 439 | callback(element) { 440 | var btn = getPathFor(element); 441 | write.selectorBrowseButton = btn; 442 | return !!btn; 443 | } 444 | }, { 445 | text: "Click on the thumbnail of the first page.", 446 | callback(element) { 447 | this.page = element; 448 | return this.page; 449 | } 450 | }, { 451 | text: "Click on the thumbnail of the second page.", 452 | callback(second) { 453 | var first = steps[3].page, 454 | states = level(first, second); 455 | if(!states) 456 | return false; 457 | var inactive = getPathFor(states.e, second), 458 | active = extendPath(inactive, states.diff), 459 | attrs = states.e.attributes, 460 | smallestIntAttr = null; 461 | if(document.querySelectorAll(inactive).length <= 1) 462 | return false; 463 | for(var i = 0, v; i < attrs.length; i++) { 464 | v = attrs[i].value.trim(); 465 | if(v !== "" && isFinite(v) && v % 1 === 0 && (smallestIntAttr === null || smallestIntAttr.value > v * 1)) 466 | smallestIntAttr = { 467 | value: v * 1, 468 | name: attrs[i].name 469 | }; 470 | } 471 | write.selectorPages = inactive; 472 | write.selectorActivePage = active; 473 | write.pagenumAttr = smallestIntAttr.name; 474 | write.pagenumCorrection = smallestIntAttr.value; 475 | return inactive && active && smallestIntAttr; 476 | } 477 | } 478 | ], 479 | waiter = function() {}, 480 | listener, 481 | nextStep = function() { 482 | if(++step >= steps.length) 483 | return end(); 484 | div.innerHTML = (step + 1) + ". " + steps[step].text; 485 | div.style.lineHeight = "50px"; 486 | waiter = function(p) { 487 | if(steps[step].callback(p)) 488 | nextStep(); 489 | else 490 | fail(); 491 | }; 492 | }, 493 | 494 | start = function() { 495 | div.innerHTML = "Navigate to the first page of this comic.
"; 496 | var a = document.createElement("a"); 497 | a.setAttribute("style", linkStyle); 498 | a.href = "javascript:"; 499 | a.innerHTML = "OK. I did."; 500 | a.addEventListener("click", function(event) { 501 | event.stopPropagation(); 502 | nextStep(); 503 | }, false); 504 | div.appendChild(a); 505 | }, 506 | 507 | end = function() { 508 | window.alert("Scan completed.\nIf the backup still does not work, you should force a new scan in the options."); 509 | 510 | document.documentElement.removeAttribute("scanning"); 511 | document.documentElement.removeEventListener("click", listener, false); 512 | document.documentElement.removeChild(div); 513 | 514 | chrome.storage.local.set(write, function() { 515 | for(var key in write) 516 | settings[key] = write[key]; 517 | 518 | port.send({ 519 | what: "broadcast_to_openers", 520 | message: { 521 | what: "finished_scan" 522 | } 523 | }); 524 | }); 525 | }, 526 | fail = function() { 527 | window.alert("Sorry. The scan failed.\nMaybe you should try again."); 528 | window.location.reload(); 529 | }; 530 | 531 | document.documentElement.setAttribute("scanning", "1"); 532 | 533 | document.documentElement.addEventListener("click", listener = function(e) { 534 | var w = waiter; 535 | waiter = function() {}; 536 | w(e.target); 537 | }, false); 538 | 539 | start(); 540 | } 541 | 542 | // download the opened comic. a callback and a step function can be used. 543 | function loadComic(callback, step, metaData) { 544 | throttleBlocker(); 545 | addTopBar(); 546 | overlay.style.display = "block"; 547 | 548 | div.innerHTML = "Downloading comic... 0%"; 549 | div.style.lineHeight = "50px"; 550 | renderFaviconPercentage(0); 551 | 552 | if(typeof callback != "function") 553 | callback = function() {}; 554 | if(typeof step != "function") 555 | step = function() {}; 556 | 557 | var l = dom.pages.length; 558 | 559 | if(l < 1) 560 | return callback(new Error("Found no pages to backup.")); 561 | 562 | if(!dom.getCanvasContainer() || dom.loaderVisible() || !dom.countCanvas()) // delay download if comic isn't displayed yet => reader not ready, first page is not loaded yet, first page is not displayed yet 563 | return setTimeout(function() { 564 | loadComic(callback, step, metaData); 565 | }, 100); 566 | 567 | var pos = -1, 568 | dualPageProofCount = 0, 569 | numLength = String(l - 1).length, 570 | nextPage = function(callback, mode) { 571 | var targetPage = ++pos; 572 | 573 | clearTimeout(noChangeTimeout); 574 | 575 | if(changeWaiter) 576 | changeWaiter.killed = true; 577 | 578 | if(pos >= l) { 579 | end(); 580 | return; 581 | } 582 | var fig = dom.pages[pos]; 583 | if(dom.isActivePage(fig)) { 584 | callback(); 585 | } 586 | else { 587 | callback = changeWaiter = callback.bind(); // to remove killed or toBeHandled properties 588 | // Guarantee that at least settings.pageSwapDelay ms have passed between this and last swap: 589 | swapPage(function() { 590 | function tryAgain() { 591 | // => Try opening the page again by going back and then forward: 592 | pos = targetPage === 0 ? l - 2 : targetPage - 2; 593 | nextPage(function(dualPageAssumed) { 594 | // If the previous nextPage call caused skipping to the target page, use it: 595 | if(pos === targetPage && !dualPageAssumed) 596 | callback(); 597 | else { 598 | // Skip page if dual page is assumed: 599 | pos = dualPageAssumed ? targetPage : targetPage - 1; 600 | 601 | nextPage(callback); 602 | } 603 | }, "back"); 604 | } 605 | 606 | if(changeWaiter === callback) { 607 | (function waitAgain(i) { 608 | noChangeTimeout = setTimeout(function() { 609 | if(changeWaiter === callback) { 610 | if(dom.isLoading() || !dom.isActivePage(fig)) { 611 | if(i < 5) 612 | waitAgain(i + 1); 613 | else 614 | tryAgain(); 615 | } 616 | else if(mode === "back") 617 | nextPage(callback, "forward"); 618 | else if(mode === "forward") { 619 | dualPageProofCount++; 620 | callback.killed = true; 621 | callback(true); 622 | } 623 | else if(dualPageProofCount > 1 && mode !== "noskip") { 624 | nextPage(callback, "noskip"); 625 | } 626 | else 627 | tryAgain(); 628 | } 629 | }, settings.pageSkipDelay); 630 | }(1)); 631 | 632 | realClick(fig); 633 | } 634 | }); 635 | } 636 | }, 637 | changeWaiter = null, 638 | noChangeTimeout = null, 639 | 640 | interval = function() { 641 | nextPage(function() { 642 | getOpenedPage(function(page) { 643 | port.send({ 644 | what: "add_page", 645 | page: (settings.container != 2 ? page : null), 646 | i: pos, 647 | len: numLength, 648 | extension: (settings.page ? "png" : "jpeg"), 649 | toZip: (settings.container != 2) 650 | }, function(result) { 651 | if(settings.container == 2) 652 | downloadData(getName() + "/" + result.name, page, true); 653 | 654 | var floatingPerc = (pos + 1) / l, 655 | perc = Math.round(floatingPerc * 100); 656 | div.getElementsByTagName("span")[0].innerHTML = perc; 657 | renderFaviconPercentage(floatingPerc); 658 | step(perc); 659 | interval(); 660 | }); 661 | }); 662 | }); 663 | }, 664 | start = function() { 665 | start = function() {}; 666 | interval(); 667 | }, 668 | end = function() { 669 | 670 | if(mutationObserver) 671 | mutationObserver.disconnect(); 672 | 673 | function done() { 674 | document.documentElement.removeChild(div); 675 | document.documentElement.removeChild(overlay); 676 | realClick(firstPageFig); 677 | callback(); 678 | } 679 | if(settings.container == 2) 680 | done(); 681 | else { 682 | step("zip"); 683 | zipImages(function() { 684 | step("save"); 685 | downloadBlob(getName() + "." + (settings.container ? "zip" : "cbz"), done); 686 | }, metaData); 687 | } 688 | }, 689 | rmListener = function() { 690 | var container = dom.canvasContainer, 691 | waiter = changeWaiter; 692 | 693 | if(typeof waiter === "function" && !waiter.killed && !waiter.toBeHandled && (!dom.countCanvas() || !dom.isVisible(container))) { 694 | waiter.toBeHandled = true; 695 | 696 | (function check() { 697 | if(container === dom.getCanvasContainer() || dom.isLoading()) 698 | setTimeout(check, 100); 699 | else if(!waiter.killed) { 700 | clearTimeout(noChangeTimeout); 701 | waiter(); 702 | } 703 | }()); 704 | } 705 | }, 706 | mutationObserver = null, 707 | firstPage = 0, 708 | firstPageFig = null; 709 | 710 | port.send({ 711 | what: "new_zip", 712 | user: getUsername() 713 | }, function(result) { 714 | if(result.error) // zip creation failed: stop backup immediately. 715 | return callback(new Error("Zip creation failed.")); 716 | 717 | mutationObserver = new MutationObserver(function(mutations) { 718 | var removed = false; 719 | for(var i = 0; i < mutations.length; i++) 720 | if(mutations[i].removedNodes.length > 0) { 721 | removed = true; 722 | break; 723 | } 724 | if(removed) 725 | rmListener(); 726 | }).observe(dom.getCanvasContainer().parentElement, { 727 | subtree: true, 728 | childList: true 729 | }); 730 | 731 | realClick(dom.browseButton); 732 | firstPageFig = dom.activePage; 733 | firstPage = (firstPageFig && firstPageFig.getAttribute(dom.pagenumAttr) * 1 - settings.pagenumCorrection) || 0; 734 | pos = settings.start ? Math.max(firstPage - 1, -1) : -1; 735 | if(dom.onepageButton != null && !dom.isActiveOnepageButton()) 736 | realClick(dom.onepageButton); 737 | 738 | pageLoaded(start); 739 | }); 740 | } 741 | 742 | function getName() { 743 | if(getName.title != null) 744 | return getName.title; 745 | var title = document.getElementsByTagName('title'); 746 | if(title[0]) { 747 | var spaceReplacement = { 748 | 1: "_", 749 | 2: ".", 750 | 3: "-", 751 | 4: "" 752 | }[settings.filename]; 753 | return (getName.title = sanitizeFilename(title[0].innerHTML.substr(0, title[0].innerHTML.lastIndexOf("-")).trim(), spaceReplacement) || "comic"); 754 | } 755 | return "comic"; 756 | } 757 | getName.title = null; 758 | 759 | function getUsername() { 760 | var reader = document.getElementById("reader"); 761 | return (reader && reader.getAttribute("data-username")) || ""; 762 | } 763 | 764 | function getUsernameImage(ctx, w, h) { 765 | var uName = getUsername(), 766 | uW = (uName.length + 1) * 8, 767 | data = ctx.getImageData(w - uW, h - 1, uW, 1), 768 | p, c, i, e, q, hsl, rgb; 769 | for(i = -1; i < uName.length; i++) { 770 | p = (i + 1) * 32; 771 | c = nullFill(i < 0 ? "00000000" : Number(uName.charCodeAt(i)).toString(2), 8); 772 | for(e = 0; e < c.length; e++) { 773 | q = p + e * 4; 774 | hsl = rgbToHsl(data.data[q], data.data[q + 1], data.data[q + 2]); 775 | if(c.charAt(e) * 1 && hsl[2] < 0.65) 776 | hsl[2] = 0.65; 777 | else if(c.charAt(e) * 1 === 0 && hsl[2] > 0.35) 778 | hsl[2] = 0.35; 779 | rgb = hslToRgb(hsl[0], hsl[1], hsl[2]); 780 | data.data[q] = rgb[0]; 781 | data.data[q + 1] = rgb[1]; 782 | data.data[q + 2] = rgb[2]; 783 | } 784 | } 785 | 786 | return data; 787 | } 788 | 789 | function downloadBlob(name, callback) { // overwrite is not used currently 790 | // blobs have to be downloaded from background page (same origin policy) 791 | port.send({ 792 | what: "download_blob", 793 | name: name 794 | }, callback); 795 | } 796 | 797 | function downloadData(name, data, overwrite, callback) { // overwrite is not used currently 798 | var url = URL.createObjectURL(dataURLtoBlob(data)); 799 | downloadFile(name, url, overwrite, function() { 800 | URL.revokeObjectURL(url); 801 | callback(); 802 | }); 803 | } 804 | 805 | // compress and download all pages that were backuped by this tab in the loadComic function 806 | function zipImages(callback, comment) { 807 | if(settings.container == 2) 808 | return typeof callback === "function" ? callback() : undefined; 809 | renderFaviconPercentage(1); 810 | div.innerHTML = "Zipping images..."; 811 | div.style.lineHeight = "50px"; 812 | 813 | port.send({ 814 | what: "start_zipping", 815 | comment: comment 816 | }, function(result) { 817 | renderFaviconPercentage(1); 818 | div.innerHTML = "Saving comic..."; 819 | callback(); 820 | }); 821 | } 822 | 823 | function pageLoaded(callback) { 824 | if(!dom.isLoading()) 825 | callback(); 826 | else 827 | setTimeout(function() { 828 | pageLoaded(callback); 829 | }, 100); 830 | } 831 | 832 | // get data URL of the currently opened page in the reader (async! result is given to callback) 833 | function getOpenedPage(callback) { 834 | pageLoaded(function() { 835 | var view = dom.getCanvasContainer(), 836 | canvasOnThisPage = dom.canvasElements; 837 | 838 | var w = parseInt(view.style.width), 839 | h = parseInt(view.style.height), 840 | outCanvas = document.createElement('canvas'), 841 | ctx = outCanvas.getContext('2d'), 842 | canvas, data; 843 | outCanvas.width = w; 844 | outCanvas.height = h; 845 | for(var i = 0; i < canvasOnThisPage.length; i++) { 846 | canvas = canvasOnThisPage[i]; 847 | ctx.drawImage(canvas, parseInt(canvas.style.left) || 0, parseInt(canvas.style.top) || 0, parseInt(canvas.style.width) || 0, parseInt(canvas.style.height) || 0); 848 | } 849 | data = getUsernameImage(ctx, w, h); 850 | ctx.putImageData(data, w - data.width, h - data.height); 851 | 852 | callback(outCanvas.toDataURL("image/" + (settings.page ? "png" : "jpeg"))); 853 | }); 854 | } 855 | -------------------------------------------------------------------------------- /source/common.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | var currentVersion = 123, 4 | defaultUpdateServer = "https://raw.githubusercontent.com/Cortys/comic-backup/master", 5 | div, linkStyle = "color:#ffffff;font-weight:bold;background:linear-gradient(to bottom, rgb(115, 152, 200) 0%,rgb(179, 206, 233) 1%,rgb(82, 142, 204) 5%,rgb(79, 137, 200) 20%,rgb(66, 120, 184) 50%,rgb(49, 97, 161) 100%);padding:3px;text-decoration:none;display:inline-block;width:70px;text-align:center;height:22px;box-sizing:border-box;line-height:14px;border:1px solid rgb(49,96,166);", 6 | settings; 7 | 8 | function getSettings(callback) { 9 | chrome.storage.local.get(null, function(data) { 10 | settings = data; 11 | if(typeof callback === "function") 12 | callback(); 13 | }); 14 | } 15 | 16 | function randomString(min, max) { // generates random alphanumeric string with a length between min and max - it never starts with a number so that results can be used as class names etc. 17 | var poss = "abcdefghijklmnopqrstuvwxyz0123456789", 18 | l = Math.round(Math.random() * (max - min)) + min; 19 | for(var r = ""; r.length < l;) 20 | r += poss.charAt(Math.round(Math.random() * (poss.length - (r.length ? 1 : 11)))); 21 | return r; 22 | } 23 | 24 | // Cleans up a string to be a valid cross platform filename. 25 | // Inspired by https://github.com/parshap/node-sanitize-filename. 26 | function sanitizeFilename(input, spaceReplacement) { 27 | var result = input 28 | .replace(/\s?[\/\\\|\?<>:\*\":~]+\s?/g, " ") 29 | .replace(/[\x00-\x1f\x80-\x9f]/g, "") 30 | .replace(/(\.|\s)+$/g, "") 31 | .replace(/^(\.|\s)+/g, "") 32 | .replace(/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i, ""); 33 | 34 | if(spaceReplacement != null) 35 | result = result.replace(/\s/g, spaceReplacement); 36 | 37 | return result; 38 | } 39 | 40 | function nullFill(num, len) { 41 | num += ""; 42 | while(num.length < len) 43 | num = "0" + num; 44 | return num; 45 | } 46 | 47 | // checks for updates and calls callback with true = new update available or false = no updates 48 | function checkVersion(callback) { 49 | var xhr = new XMLHttpRequest(); 50 | if(settings.updateServer != "") { 51 | xhr.open("GET", (settings.updateServer || defaultUpdateServer) + "/version", true); 52 | xhr.responseType = 'text'; 53 | 54 | xhr.onreadystatechange = function() { 55 | 56 | if(xhr.readyState == 4) { 57 | if(xhr.status != 200) 58 | callback(false); 59 | 60 | var version = +this.response; 61 | 62 | if(version > currentVersion) 63 | callback(true); 64 | else 65 | callback(false); 66 | } 67 | }; 68 | xhr.send(); 69 | } 70 | else 71 | callback(false); 72 | } 73 | 74 | function addTopBar() { 75 | if(div) 76 | return; 77 | 78 | div = document.createElement("div"); 79 | 80 | div.id = randomString(20, 40); 81 | 82 | div.style.fontSize = "13px"; 83 | div.style.top = "50%"; 84 | div.style.width = "100%"; 85 | div.style.height = "54px"; 86 | div.style.marginTop = "-150px"; 87 | div.style.paddingTop = "4px"; 88 | 89 | div.style.background = "linear-gradient(to bottom, rgba(0,0,0,0.9) 50%,rgba(0,0,0,0.7) 100%)"; 90 | div.style.color = "#ffffff"; 91 | div.style.textAlign = "center"; 92 | div.style.lineHeight = "25px"; 93 | div.style.zIndex = 2147483648; 94 | div.style.cursor = "default"; 95 | div.style.overflow = "hidden"; 96 | 97 | div.style.position = "fixed"; 98 | 99 | document.documentElement.appendChild(div); 100 | } 101 | 102 | function updateDialog() { 103 | checkVersion(function(update) { 104 | if(update) { 105 | addTopBar(); 106 | div.style.top = 0; 107 | div.style.marginTop = 0; 108 | div.innerHTML = "This version of the Comic Backup extension is outdated.
Update"; 109 | } 110 | }); 111 | } 112 | 113 | if(typeof Element.prototype.matches !== "function") 114 | Element.prototype.matches = Element.prototype.webkitMatchesSelector; 115 | 116 | function minPxVal(a) { 117 | var aNum = +(""+a).split("px", 1)[0]; 118 | 119 | return function(b) { 120 | var bNum = +(""+b).split("px", 1)[0]; 121 | 122 | return bNum == null || aNum < bNum ? a : b; 123 | }; 124 | } 125 | 126 | // Converts an RGB (0-255) color value to HSL (0-1) 127 | function rgbToHsl(r, g, b) { 128 | r /= 255; 129 | g /= 255; 130 | b /= 255; 131 | 132 | var max = Math.max(r, g, b), 133 | min = Math.min(r, g, b); 134 | var h, s, l = (max + min) / 2; 135 | 136 | if(max == min) { 137 | h = s = 0; // achromatic 138 | } 139 | else { 140 | var d = max - min; 141 | s = l > 0.5 ? d / (2 - max - min) : d / (max + min); 142 | 143 | switch(max) { 144 | case r: 145 | h = (g - b) / d + (g < b ? 6 : 0); 146 | break; 147 | case g: 148 | h = (b - r) / d + 2; 149 | break; 150 | case b: 151 | h = (r - g) / d + 4; 152 | break; 153 | } 154 | 155 | h /= 6; 156 | } 157 | 158 | return [h, s, l]; 159 | } 160 | 161 | // Converts an HSL (0-1) color value to RGB (0-255) 162 | function hslToRgb(h, s, l) { 163 | var r, g, b; 164 | 165 | if(s === 0) { 166 | r = g = b = l; // achromatic 167 | } 168 | else { 169 | var q = l < 0.5 ? l * (1 + s) : l + s - l * s, 170 | p = 2 * l - q; 171 | 172 | r = hslToRgb.hue2rgb(p, q, h + 1 / 3); 173 | g = hslToRgb.hue2rgb(p, q, h); 174 | b = hslToRgb.hue2rgb(p, q, h - 1 / 3); 175 | } 176 | 177 | return [r * 255, g * 255, b * 255]; 178 | } 179 | 180 | hslToRgb.hue2rgb = function hue2rgb(p, q, t) { 181 | if(t < 0) t += 1; 182 | if(t > 1) t -= 1; 183 | if(t < 1 / 6) return p + (q - p) * 6 * t; 184 | if(t < 1 / 2) return q; 185 | if(t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6; 186 | return p; 187 | }; 188 | 189 | /** 190 | * dataURLtoBlob by github.com/blueimp/JavaScript-Canvas-to-Blob 191 | * Released under the MIT License 192 | */ 193 | function dataURLtoBlob(dataURI) { 194 | var byteString, 195 | arrayBuffer, 196 | intArray, 197 | i, 198 | mimeString; 199 | if(dataURI.split(',')[0].indexOf('base64') >= 0) { 200 | // Convert base64 to raw binary data held in a string: 201 | byteString = atob(dataURI.split(',')[1]); 202 | } 203 | else { 204 | // Convert base64/URLEncoded data component to raw binary data: 205 | byteString = decodeURIComponent(dataURI.split(',')[1]); 206 | } 207 | // Write the bytes of the string to an ArrayBuffer: 208 | arrayBuffer = new ArrayBuffer(byteString.length); 209 | intArray = new Uint8Array(arrayBuffer); 210 | for(i = 0; i < byteString.length; i += 1) { 211 | intArray[i] = byteString.charCodeAt(i); 212 | } 213 | // Separate out the mime component: 214 | mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]; 215 | // Write the ArrayBuffer (or ArrayBufferView) to a blob: 216 | return new Blob([intArray], { 217 | type: mimeString 218 | }); 219 | } 220 | 221 | /* 222 | 223 | Queue.js 224 | 225 | A function to represent a queue 226 | 227 | Created by Stephen Morley - http://code.stephenmorley.org/ - and released under 228 | the terms of the CC0 1.0 Universal legal code: 229 | 230 | http://creativecommons.org/publicdomain/zero/1.0/legalcode 231 | 232 | */ 233 | 234 | /* Creates a new queue. A queue is a first-in-first-out (FIFO) data structure - 235 | * items are added to the end of the queue and removed from the front. 236 | */ 237 | function Queue() { 238 | 239 | // initialise the queue and offset 240 | var queue = []; 241 | var offset = 0; 242 | 243 | // Returns the length of the queue. 244 | this.getLength = function() { 245 | return(queue.length - offset); 246 | }; 247 | 248 | // Returns true if the queue is empty, and false otherwise. 249 | this.isEmpty = function() { 250 | return(queue.length === 0); 251 | }; 252 | 253 | /* Enqueues the specified item. The parameter is: 254 | * 255 | * item - the item to enqueue 256 | */ 257 | this.enqueue = function(item) { 258 | queue.push(item); 259 | }; 260 | 261 | /* Dequeues an item and returns it. If the queue is empty, the value 262 | * 'undefined' is returned. 263 | */ 264 | this.dequeue = function() { 265 | 266 | // if the queue is empty, return immediately 267 | if(queue.length === 0) return undefined; 268 | 269 | // store the item at the front of the queue 270 | var item = queue[offset]; 271 | queue[offset] = undefined; 272 | 273 | // increment the offset and remove the free space if necessary 274 | if(++offset * 2 >= queue.length) { 275 | queue = queue.slice(offset); 276 | offset = 0; 277 | } 278 | 279 | // return the dequeued item 280 | return item; 281 | 282 | }; 283 | 284 | /* Returns the item at the front of the queue (without dequeuing it). If the 285 | * queue is empty then undefined is returned. 286 | */ 287 | this.peek = function() { 288 | return(queue.length > 0 ? queue[offset] : undefined); 289 | }; 290 | 291 | } 292 | // END // 293 | 294 | // Custom communication API to enable callbacks in continous connections between content and background scripts: 295 | 296 | var connector = Object.create(chrome.runtime); 297 | 298 | connector.mutatePort = function(port) { 299 | 300 | var c = 1, 301 | l = new Queue(), 302 | callbacks = {}; 303 | 304 | port.send = function(msg, callback) { 305 | var id = l.dequeue() || c++; 306 | callbacks[id] = callback; 307 | this.postMessage({ 308 | id: id, 309 | type: 0, 310 | message: msg 311 | }); // type0 message: A transmits msg to B 312 | }; 313 | 314 | port.receive = function(callback) { 315 | var t = this, 316 | called = false; 317 | t.onMessage.addListener(function(msg) { 318 | if(msg.id !== undefined && !msg.type && !callback(msg.message, function(response) { // if callback returns true => B's response will be sent asynchronous (A will wait for a response as long as B requires => RISK this could be endless!) 319 | called = true; 320 | t.postMessage({ 321 | id: msg.id, 322 | type: 1, 323 | message: response 324 | }); // type1 message: B responds to A with response 325 | }) && !called) 326 | t.postMessage({ 327 | id: msg.id, 328 | type: 2 329 | }); // type2 message: B chose to not respond to A => A is notified, that no response will come 330 | }); 331 | }; 332 | 333 | port.onMessage.addListener(function(msg) { 334 | if(msg.id !== undefined && msg.type) { 335 | var f = callbacks[msg.id]; 336 | delete callbacks[msg.id]; 337 | if(typeof f === "function" && msg.type != 2) 338 | f(msg.message); 339 | l.enqueue(msg.id); 340 | } 341 | }); 342 | 343 | return port; 344 | }; 345 | 346 | connector.connect = function() { 347 | var p = chrome.tabs || chrome.runtime, 348 | port = p.connect.apply(p, arguments); 349 | return this.mutatePort(port); 350 | }; 351 | 352 | connector.onConnect = { 353 | addListener: function(callback) { 354 | return chrome.runtime.onConnect.addListener(function(port) { 355 | callback.call(this, connector.mutatePort(port)); 356 | }); 357 | } 358 | }; 359 | 360 | // Download files: 361 | function downloadFile(name, data, overwrite, callback) { // overwrite is not used currently 362 | if(chrome.downloads) { 363 | var filename = (settings.directory || "") + name; 364 | 365 | chrome.downloads.download({ 366 | url: data + "#comic-backup/" + filename, 367 | filename: filename, 368 | method: "GET", 369 | conflictAction: (overwrite ? "overwrite" : "uniquify") 370 | }, function(downloadId) { 371 | downloadFile.handlers[downloadId] = function(delta) { 372 | if(!delta.endTime || !delta.endTime.current) 373 | return; 374 | delete downloadFile.handlers[downloadId]; 375 | if(typeof callback === "function") 376 | callback(); 377 | }; 378 | }); 379 | } 380 | else 381 | downloadFile.port.send({ 382 | name: name, 383 | data: data, 384 | overwrite: overwrite 385 | }, callback); 386 | } 387 | 388 | if(chrome.downloads) { 389 | downloadFile.handlers = {}; 390 | chrome.downloads.onChanged.addListener(function(downloadDelta) { 391 | var a = downloadFile.handlers[downloadDelta.id]; 392 | if(typeof a === "function") 393 | a(downloadDelta); 394 | }); 395 | } 396 | else 397 | downloadFile.port = connector.connect({ 398 | name: "download" 399 | }); 400 | -------------------------------------------------------------------------------- /source/diffMatchPatch.js: -------------------------------------------------------------------------------- 1 | (function(){function diff_match_patch(){this.Diff_Timeout=1;this.Diff_EditCost=4;this.Match_Threshold=0.5;this.Match_Distance=1E3;this.Patch_DeleteThreshold=0.5;this.Patch_Margin=4;this.Match_MaxBits=32} 2 | diff_match_patch.prototype.diff_main=function(a,b,c,d){"undefined"==typeof d&&(d=0>=this.Diff_Timeout?Number.MAX_VALUE:(new Date).getTime()+1E3*this.Diff_Timeout);if(null==a||null==b)throw Error("Null input. (diff_main)");if(a==b)return a?[[0,a]]:[];"undefined"==typeof c&&(c=!0);var e=c,f=this.diff_commonPrefix(a,b);c=a.substring(0,f);a=a.substring(f);b=b.substring(f);var f=this.diff_commonSuffix(a,b),g=a.substring(a.length-f);a=a.substring(0,a.length-f);b=b.substring(0,b.length-f);a=this.diff_compute_(a, 3 | b,e,d);c&&a.unshift([0,c]);g&&a.push([0,g]);this.diff_cleanupMerge(a);return a}; 4 | diff_match_patch.prototype.diff_compute_=function(a,b,c,d){if(!a)return[[1,b]];if(!b)return[[-1,a]];var e=a.length>b.length?a:b,f=a.length>b.length?b:a,g=e.indexOf(f);return-1!=g?(c=[[1,e.substring(0,g)],[0,f],[1,e.substring(g+f.length)]],a.length>b.length&&(c[0][0]=c[2][0]=-1),c):1==f.length?[[-1,a],[1,b]]:(e=this.diff_halfMatch_(a,b))?(f=e[0],a=e[1],g=e[2],b=e[3],e=e[4],f=this.diff_main(f,g,c,d),c=this.diff_main(a,b,c,d),f.concat([[0,e]],c)):c&&100c);v++){for(var n=-v+r;n<=v-t;n+=2){var l=g+n,m;m=n==-v||n!=v&&j[l-1]d)t+=2;else if(s>e)r+=2;else if(q&&(l=g+k-n,0<=l&&l= 8 | u)return this.diff_bisectSplit_(a,b,m,s,c)}}for(n=-v+p;n<=v-w;n+=2){l=g+n;u=n==-v||n!=v&&i[l-1]d)w+=2;else if(m>e)p+=2;else if(!q&&(l=g+k-n,0<=l&&(l=u)))return this.diff_bisectSplit_(a,b,m,s,c)}}return[[-1,a],[1,b]]}; 9 | diff_match_patch.prototype.diff_bisectSplit_=function(a,b,c,d,e){var f=a.substring(0,c),g=b.substring(0,d);a=a.substring(c);b=b.substring(d);f=this.diff_main(f,g,!1,e);e=this.diff_main(a,b,!1,e);return f.concat(e)}; 10 | diff_match_patch.prototype.diff_linesToChars_=function(a,b){function c(a){for(var b="",c=0,f=-1,g=d.length;fd?a=a.substring(c-d):c=a.length?[h,j,n,l,g]:null}if(0>=this.Diff_Timeout)return null; 15 | var d=a.length>b.length?a:b,e=a.length>b.length?b:a;if(4>d.length||2*e.lengthd[4].length?g:d:d:g;var j;a.length>b.length?(g=h[0],d=h[1],e=h[2],j=h[3]):(e=h[0],j=h[1],g=h[2],d=h[3]);h=h[4];return[g,d,e,j,h]}; 16 | diff_match_patch.prototype.diff_cleanupSemantic=function(a){for(var b=!1,c=[],d=0,e=null,f=0,g=0,h=0,j=0,i=0;f=e){if(d>=b.length/2||d>=c.length/2)a.splice(f,0,[0,c.substring(0,d)]),a[f-1][1]=b.substring(0,b.length-d),a[f+1][1]=c.substring(d),f++}else if(e>=b.length/2||e>=c.length/2)a.splice(f,0,[0,b.substring(0,e)]),a[f-1][0]=1,a[f-1][1]=c.substring(0,c.length-e),a[f+1][0]=-1,a[f+1][1]=b.substring(e),f++;f++}f++}}; 18 | diff_match_patch.prototype.diff_cleanupSemanticLossless=function(a){function b(a,b){if(!a||!b)return 6;var c=a.charAt(a.length-1),d=b.charAt(0),e=c.match(diff_match_patch.nonAlphaNumericRegex_),f=d.match(diff_match_patch.nonAlphaNumericRegex_),g=e&&c.match(diff_match_patch.whitespaceRegex_),h=f&&d.match(diff_match_patch.whitespaceRegex_),c=g&&c.match(diff_match_patch.linebreakRegex_),d=h&&d.match(diff_match_patch.linebreakRegex_),i=c&&a.match(diff_match_patch.blanklineEndRegex_),j=d&&b.match(diff_match_patch.blanklineStartRegex_); 19 | return i||j?5:c||d?4:e&&!g&&h?3:g||h?2:e||f?1:0}for(var c=1;c=i&&(i=k,g=d,h=e,j=f)}a[c-1][1]!=g&&(g?a[c-1][1]=g:(a.splice(c-1,1),c--),a[c][1]= 20 | h,j?a[c+1][1]=j:(a.splice(c+1,1),c--))}c++}};diff_match_patch.nonAlphaNumericRegex_=/[^a-zA-Z0-9]/;diff_match_patch.whitespaceRegex_=/\s/;diff_match_patch.linebreakRegex_=/[\r\n]/;diff_match_patch.blanklineEndRegex_=/\n\r?\n$/;diff_match_patch.blanklineStartRegex_=/^\r?\n\r?\n/; 21 | diff_match_patch.prototype.diff_cleanupEfficiency=function(a){for(var b=!1,c=[],d=0,e=null,f=0,g=!1,h=!1,j=!1,i=!1;fb)break;e=c;f=d}return a.length!=g&&-1===a[g][0]?f:f+(b-e)}; 25 | diff_match_patch.prototype.diff_prettyHtml=function(a){for(var b=[],c=/&/g,d=//g,f=/\n/g,g=0;g");switch(h){case 1:b[g]=''+j+"";break;case -1:b[g]=''+j+"";break;case 0:b[g]=""+j+""}}return b.join("")}; 26 | diff_match_patch.prototype.diff_text1=function(a){for(var b=[],c=0;cthis.Match_MaxBits)throw Error("Pattern too long for this browser.");var e=this.match_alphabet_(b),f=this,g=this.Match_Threshold,h=a.indexOf(b,c);-1!=h&&(g=Math.min(d(0,h),g),h=a.lastIndexOf(b,c+b.length),-1!=h&&(g=Math.min(d(0,h),g)));for(var j=1<=i;p--){var w=e[a.charAt(p-1)];k[p]=0===t?(k[p+1]<<1|1)&w:(k[p+1]<<1|1)&w|((r[p+1]|r[p])<<1|1)|r[p+1];if(k[p]&j&&(w=d(t,p-1),w<=g))if(g=w,h=p-1,h>c)i=Math.max(1,2*c-h);else break}if(d(t+1,c)>g)break;r=k}return h}; 32 | diff_match_patch.prototype.match_alphabet_=function(a){for(var b={},c=0;c=2*this.Patch_Margin&& 37 | e&&(this.patch_addContext_(a,h),c.push(a),a=new diff_match_patch.patch_obj,e=0,h=d,f=g)}1!==i&&(f+=k.length);-1!==i&&(g+=k.length)}e&&(this.patch_addContext_(a,h),c.push(a));return c};diff_match_patch.prototype.patch_deepCopy=function(a){for(var b=[],c=0;cthis.Match_MaxBits){if(j=this.match_main(b,h.substring(0,this.Match_MaxBits),g),-1!=j&&(i=this.match_main(b,h.substring(h.length-this.Match_MaxBits),g+h.length-this.Match_MaxBits),-1==i||j>=i))j=-1}else j=this.match_main(b,h,g); 39 | if(-1==j)e[f]=!1,d-=a[f].length2-a[f].length1;else if(e[f]=!0,d=j-g,g=-1==i?b.substring(j,j+h.length):b.substring(j,i+this.Match_MaxBits),h==g)b=b.substring(0,j)+this.diff_text2(a[f].diffs)+b.substring(j+h.length);else if(g=this.diff_main(h,g,!1),h.length>this.Match_MaxBits&&this.diff_levenshtein(g)/h.length>this.Patch_DeleteThreshold)e[f]=!1;else{this.diff_cleanupSemanticLossless(g);for(var h=0,k,i=0;ie[0][1].length){var f=b-e[0][1].length;e[0][1]=c.substring(e[0][1].length)+e[0][1];d.start1-=f;d.start2-=f;d.length1+=f;d.length2+=f}d=a[a.length-1];e=d.diffs;0==e.length||0!=e[e.length-1][0]?(e.push([0, 42 | c]),d.length1+=b,d.length2+=b):b>e[e.length-1][1].length&&(f=b-e[e.length-1][1].length,e[e.length-1][1]+=c.substring(0,f),d.length1+=f,d.length2+=f);return c}; 43 | diff_match_patch.prototype.patch_splitMax=function(a){for(var b=this.Match_MaxBits,c=0;c2*b?(h.length1+=i.length,e+=i.length,j=!1,h.diffs.push([g,i]),d.diffs.shift()):(i=i.substring(0,b-h.length1-this.Patch_Margin),h.length1+=i.length,e+=i.length,0===g?(h.length2+=i.length,f+=i.length):j=!1,h.diffs.push([g,i]),i==d.diffs[0][1]?d.diffs.shift():d.diffs[0][1]=d.diffs[0][1].substring(i.length))}g=this.diff_text2(h.diffs);g=g.substring(g.length-this.Patch_Margin);i=this.diff_text1(d.diffs).substring(0,this.Patch_Margin);""!==i&& 45 | (h.length1+=i.length,h.length2+=i.length,0!==h.diffs.length&&0===h.diffs[h.diffs.length-1][0]?h.diffs[h.diffs.length-1][1]+=i:h.diffs.push([0,i]));j||a.splice(++c,0,h)}}};diff_match_patch.prototype.patch_toText=function(a){for(var b=[],c=0;c 0) 80 | for(var i = this.activeDownloads; i < newLimit; i++) 81 | this.queue.resume(); 82 | else 83 | while(this.queue.resume()); 84 | }; 85 | 86 | // Queue definition: Stores all backup requests 87 | Download.queue = new Queue(); 88 | Download.queue.resume = function() { 89 | var d; 90 | while((d = this.dequeue())) { 91 | if(d.canceled) 92 | continue; 93 | d.start(); 94 | return true; 95 | } 96 | return false; 97 | }; 98 | 99 | Download.prototype = { 100 | id: 0, 101 | comicHref: null, 102 | buttons: null, 103 | tab: null, 104 | queued: false, 105 | downloading: false, 106 | cancelable: false, 107 | canceled: false, 108 | currentButtonUI: null, 109 | 110 | get stale() { 111 | this.cleanUp(); 112 | 113 | return this.buttons.size === 0 && !this.downloading && !this.queued; 114 | }, 115 | 116 | cleanUp() { 117 | for(var button of this.buttons.keys()) { 118 | if(!document.contains(button)) 119 | this.buttons.delete(button); 120 | } 121 | }, 122 | 123 | show(button) { 124 | if(button.href !== this.comicHref || this.buttons.has(button)) // after switching pages via ajax new button html elements are created, those will be linked to the internal download object 125 | return; 126 | 127 | //Get Metadata 128 | this.metaData.scanMeta(button.parentNode); 129 | 130 | var clone = button.cloneNode(false), 131 | buttonComputedStyle = window.getComputedStyle(button); 132 | 133 | var randomId = randomString(20, 40); // make sure cmxlgy can not break button text rendering by changing class names 134 | clone.innerHTML = button.innerHTML.replace(button.innerHTML.trim(), "Stop"); 135 | clone.style.position = "relative"; 136 | clone.style.textAlign = button.style.textAlign = "center"; 137 | clone.href = "javascript:"; 138 | 139 | clone.setAttribute("class", button.getAttribute("class")); 140 | 141 | clone.classList.add(cssClass); 142 | 143 | var buttonWidth = parseInt(button.style.width = buttonComputedStyle.width); 144 | 145 | clone.style.width = isFinite(buttonWidth) ? buttonWidth + "px" : button.style.width; 146 | 147 | this.buttons.set(button, { 148 | button: clone, 149 | text: clone.querySelector("span.text." + randomId), 150 | progressBG: "linear-gradient(to right, rgba(0,0,0,0.4) 0%, rgba(0,0,0,0.4) {X}%, rgba(0,0,0,0) {X}%, rgba(0,0,0,0) 100%), " + buttonComputedStyle.background 151 | }); 152 | if(settings.selectors || settings.selectors == null) { 153 | clone.addEventListener("click", function() { 154 | this[this.cancelable ? "cancel" : "start"](); 155 | }.bind(this), false); 156 | if(!this.currentButtonUI) 157 | this.showDefault(); 158 | else 159 | this.setButtonUI.apply(this, this.currentButtonUI); 160 | } 161 | else { 162 | this.inactive = true; 163 | clone.addEventListener("click", this.openTab.bind(this, true), false); 164 | this.showInactive(); 165 | } 166 | 167 | var parent = button.parentElement, 168 | parentClone = parent && parent.cloneNode(false); 169 | 170 | parentClone.appendChild(clone); 171 | 172 | parent.parentElement.insertBefore(parentClone, parent.nextSibling); 173 | }, 174 | 175 | setDownloading(bool) { 176 | if(bool && !this.downloading) 177 | Download.activeDownloads++; 178 | else if(!bool && this.downloading) { 179 | Download.activeDownloads--; 180 | Download.queue.resume(); 181 | } 182 | this.downloading = bool; 183 | }, 184 | 185 | openTab(active) { 186 | var t = this; 187 | port.send({ 188 | what: "open_background_tab", 189 | url: t.comicHref, 190 | active: active 191 | }, function(tab) { 192 | t.tab = tab; 193 | downloadEvents[tab] = t; 194 | }); 195 | }, 196 | 197 | start() { 198 | var t = this; 199 | if(t.downloading) 200 | return; 201 | if(Download.activeDownloads >= settings.queueLength && settings.queueLength > 0) { 202 | t.canceled = false; 203 | t.queued = true; 204 | t.showQueued(); 205 | return Download.queue.enqueue(t); 206 | } 207 | t.queued = false; 208 | t.setDownloading(true); 209 | t.openTab(false); 210 | t.showPrepare(); 211 | }, 212 | 213 | cancel() { 214 | this.canceled = true; 215 | this.queued = false; 216 | this.showDefault(); 217 | if(!this.downloading) 218 | return; 219 | port.send({ 220 | what: "close_background_tab", 221 | tab: this.tab 222 | }); 223 | delete downloadEvents[this.tab]; 224 | this.tab = null; 225 | this.setDownloading(false); 226 | }, 227 | 228 | // event handlers (receiving messages from the downloading tab): 229 | 230 | events: { 231 | ready_to_download(callback, comicName) { 232 | if(this.inactive) 233 | callback({ 234 | exploit: true 235 | }); 236 | else { 237 | callback({ 238 | download: true, 239 | metaData: this.metaData.addTitle(comicName).toString() 240 | }); 241 | this.showProgress(0); 242 | } 243 | }, 244 | finished_download() { 245 | port.send({ 246 | what: "close_background_tab", 247 | tab: this.tab 248 | }); 249 | delete downloadEvents[this.tab]; 250 | this.tab = null; 251 | this.setDownloading(false); 252 | this.showDone(); 253 | }, 254 | download_failed() { 255 | port.send({ 256 | what: "close_background_tab", 257 | tab: this.tab 258 | }); 259 | delete downloadEvents[this.tab]; 260 | this.tab = null; 261 | this.setDownloading(false); 262 | this.showError(); 263 | }, 264 | closed_background_tab() { 265 | if(!this.downloading) 266 | return; 267 | delete downloadEvents[this.tab]; 268 | this.tab = null; 269 | this.setDownloading(false); 270 | this.showError(); 271 | }, 272 | download_progress(callback, percentage) { 273 | this["show" + (percentage == "zip" ? "Zipping" : percentage == "save" ? "Saving" : "Progress")](percentage); 274 | } 275 | }, 276 | 277 | // UI behaviour: 278 | 279 | setButtonUI(text, style, cancelable) { 280 | for(var entry of this.buttons.values()) { 281 | entry.text.innerHTML = text; 282 | entry.button.classList.toggle("cancel", cancelable); 283 | 284 | if("filter" in style) 285 | style["-webkit-filter"] = style.filter; 286 | 287 | if(style.background === "progress") { 288 | style.background = entry.progressBG.replace(/\{X\}/g, style.progress); 289 | delete style.progress; 290 | } 291 | 292 | for(var key in style) { 293 | var val = style[key]; 294 | 295 | if(val == null) 296 | entry.button.style.removeProperty(key); 297 | else 298 | entry.button.style.setProperty( 299 | key, 300 | typeof val === "function" 301 | ? val(window.getComputedStyle(entry.button).getPropertyValue(key)) 302 | : val 303 | ); 304 | } 305 | } 306 | this.currentButtonUI = arguments; 307 | this.cancelable = cancelable; 308 | }, 309 | 310 | showQueued() { 311 | this.setButtonUI("Queued", { 312 | background: null, 313 | "padding-left": minPxVal("10px"), 314 | "padding-right": minPxVal("10px"), 315 | filter: "hue-rotate(220deg)" 316 | }, true); 317 | }, 318 | showPrepare() { 319 | this.setButtonUI("Preparing", { 320 | background: null, 321 | "padding-left": minPxVal("2px"), 322 | "padding-right": minPxVal("2px"), 323 | filter: "hue-rotate(245deg)" 324 | }, true); 325 | }, 326 | showProgress(percentage) { 327 | this.setButtonUI(percentage + "%", { 328 | background: "progress", 329 | progress: percentage, 330 | "padding-left": null, 331 | "padding-right": null, 332 | filter: "hue-rotate(245deg)" 333 | }, true); 334 | }, 335 | showDefault() { 336 | this.setButtonUI("Scan", { 337 | background: null, 338 | "padding-left": null, 339 | "padding-right": null, 340 | filter: "hue-rotate(55deg)" 341 | }, false); 342 | }, 343 | showDone() { 344 | this.setButtonUI("Rescan", { 345 | background: null, 346 | "padding-left": minPxVal("10px"), 347 | "padding-right": minPxVal("10px"), 348 | filter: "hue-rotate(280deg)" 349 | }, false); 350 | }, 351 | showError() { 352 | this.setButtonUI("Failed", { 353 | background: null, 354 | "padding-left": null, 355 | "padding-right": null, 356 | filter: "hue-rotate(195deg)" 357 | }, false); 358 | }, 359 | showZipping() { 360 | this.setButtonUI("Zipping", { 361 | background: null, 362 | "padding-left": minPxVal("10px"), 363 | "padding-right": minPxVal("10px"), 364 | filter: "hue-rotate(260deg)" 365 | }, true); 366 | }, 367 | showSaving() { 368 | this.setButtonUI("Saving", { 369 | background: null, 370 | "padding-left": minPxVal("10px"), 371 | "padding-right": minPxVal("10px"), 372 | filter: "hue-rotate(270deg)" 373 | }, false); 374 | }, 375 | showInactive() { 376 | this.setButtonUI("Setup", { 377 | background: null, 378 | "padding-left": null, 379 | "padding-right": null, 380 | filter: "hue-rotate(195deg)" 381 | }, false); 382 | } 383 | }; 384 | 385 | var port = connector.connect({ 386 | name: "controller" 387 | }); 388 | 389 | port.receive(function(request, callback) { 390 | if(request.what == "child_message") 391 | return downloadEvents[request.tab] && typeof downloadEvents[request.tab].events[request.message.what] == "function" && 392 | downloadEvents[request.tab].events[request.message.what].call( 393 | downloadEvents[request.tab], 394 | callback, 395 | request.message.data 396 | ); 397 | else if((request.what == "child_broadcast" && request.message.what == "finished_scan") || request.what == "reload_page") 398 | location.reload(); 399 | else if(request.what == "update_queue") 400 | Download.updateParallelism(request.data); 401 | }); 402 | 403 | window.onbeforeunload = function() { 404 | if(Download.activeDownloads > 0 || Download.queue.getLength() > 0) 405 | return "If you close this page, all backups will be canceled."; 406 | }; 407 | -------------------------------------------------------------------------------- /source/options/League-Gothic.otf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Cortys/comic-backup/293088791537283dd126f84f7d7211b3a33ab369/source/options/League-Gothic.otf -------------------------------------------------------------------------------- /source/options/logoOptions.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Cortys/comic-backup/293088791537283dd126f84f7d7211b3a33ab369/source/options/logoOptions.png -------------------------------------------------------------------------------- /source/options/logoOptions@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Cortys/comic-backup/293088791537283dd126f84f7d7211b3a33ab369/source/options/logoOptions@2x.png -------------------------------------------------------------------------------- /source/options/options.css: -------------------------------------------------------------------------------- 1 | @font-face { 2 | font-family: League-Gothic; 3 | src: url("League-Gothic.otf") format("opentype"); 4 | } 5 | 6 | body { 7 | text-align: center; 8 | font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; 9 | line-height: 50px; 10 | cursor: default; 11 | font-size: 14px; 12 | margin: 0; 13 | padding: 0; 14 | padding-bottom: 40px; 15 | color: #3b3a3a; 16 | } 17 | 18 | #content { 19 | margin: 0; 20 | padding: 0; 21 | visibility: hidden; 22 | } 23 | 24 | h1 { 25 | margin-top: 0; 26 | margin-bottom: 20px; 27 | padding: 0; 28 | height: 200px; 29 | background-image: linear-gradient(-180deg, #3583AE 0%, #2DAF7E 100%); 30 | } 31 | 32 | h1 img { 33 | width: 200px; 34 | height: 200px; 35 | } 36 | 37 | h2 { 38 | color: #3583ae; 39 | font-size: 35px; 40 | text-transform: uppercase; 41 | letter-spacing: 1px; 42 | font-family: League-Gothic, Courier; 43 | text-shadow: 1px 1px 0 #ffffff, 3px 3px 0 #2daf7e; 44 | margin-top: 30px; 45 | margin-bottom: 10px; 46 | } 47 | 48 | select, input { 49 | background: #eddfca; 50 | border-radius: 3px; 51 | background-image: linear-gradient(-180deg, #FCF8F2 0%, #DDBA89 61%); 52 | border: 2px solid #3B3A3A; 53 | font-size: 13px; 54 | outline: none; 55 | padding: 5px; 56 | text-align: center; 57 | } 58 | select:active, input:active, input:focus { 59 | box-shadow: 0 0 10px #3b3a3a; 60 | } 61 | 62 | input[type=text] { 63 | background: #ffffff; 64 | color: #3b3a3a; 65 | text-align: left; 66 | background-image: none; 67 | width: 350px; 68 | border-width: 1px; 69 | } 70 | 71 | .aligner input[type=text] { 72 | width: 200px; 73 | } 74 | 75 | p, section { 76 | position: relative; 77 | width: 600px; 78 | margin: 10px auto; 79 | line-height: 20px; 80 | } 81 | 82 | section { 83 | margin-top: 40px; 84 | text-align: justify; 85 | } 86 | 87 | div.aligner { 88 | position: relative; 89 | display: inline-block; 90 | min-width: 240px; 91 | margin: 0 5px; 92 | text-align: right; 93 | } 94 | div.aligner.r { 95 | text-align: left; 96 | } 97 | 98 | #pageSwapDelay, #pageSkipDelay { 99 | width: 50px; 100 | text-align: right; 101 | } 102 | 103 | #credits { 104 | font-size: 10px; 105 | position: absolute; 106 | top: 10px; 107 | right: 10px; 108 | text-decoration: none; 109 | color: #3ef4b1; 110 | line-height: 12px; 111 | } 112 | #credits:hover { 113 | color: #ffffff; 114 | } 115 | -------------------------------------------------------------------------------- /source/options/options.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Comic Backup 6 | 7 | 8 | 9 | 10 | 11 | 12 | v2.4.1 by Cortys 13 |

Comic Backup Settings

14 |
15 |

Backup behaviour

16 |
Page format:

20 |
Container format:

25 |
Compression method:

29 |

Please note, that some cbz readers do not support compressed comics.

30 |
Start backup at:

34 |
Filename convention:

41 |
Max. parallel downloads per tab:

50 |

If the limit is reached, every new download will be queued.

51 |
Download Directory:
52 | 53 |

54 |

Please note, because of limitations of the extensions API, this will be a subdirectory of the default downloads folder. Absolute paths are forbidden.

55 |
Favicon text color:
59 | 60 |

Updates

61 |

To get notifications about extension updates, you have to add an update server.

62 | 63 | 64 |

I need help!

65 |
How is "Scan" different from the official backup options? When you backup a comic with this extension, it takes high quality screenshots from the web reader. Those are quite good but do not match the quality of the official downloads. You should use "Scan" if you want to have smaller files or a comic is not officially available for download.
66 |
The download never starts! To use the extension make sure you disabled the Prompt to continue message in the settings of the web reader (click the gear to get there).
67 |
My backups stop randomly and/or have blank pages! Network latencies and UI event handling delays in the reader are quite unpredictable and can cause blank pages or even stop your backups. To circumvent that, you should increase the page swap interval. It determines the shortest allowed interval between two page swaps. Default: 600 ms
68 |
Min. page swap interval:
ms
69 |
Some pages are missing in my backups! You might want to fiddle with the page skip delay. It determines how long to wait for a reaction to a page swap. If the reader did not show any reaction to a page swap for the given time, the backup will just continue with the next page. This option is essential for manga fixed format comics, that have to be backed up in dual-page-mode and thus do not rerender every second page. Default: 1200 ms
70 |
Page skip delay:
ms

71 |
It still does not work! Sometimes the code of the online reader is changed. If that happens you can force a new exploit scan and the plugin will try to detect a new way to backup your comics. In order to do that you will be asked to perform some actions the next time you open a comic.
72 |
Force new exploit scan:
76 |
77 | 78 | 79 | 80 | 81 | -------------------------------------------------------------------------------- /source/options/options.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | var selects = document.querySelectorAll("select, input"); 4 | 5 | for(var i = 0; i < selects.length; i++) 6 | (function(e) { 7 | if(typeof e.addEventListener === "undefined") 8 | return; 9 | var f = function() { 10 | e.addEventListener("change", function() { 11 | var o = {}, 12 | message = e.getAttribute("data-message"); 13 | toastr.remove(); 14 | 15 | if(e.id === "updateServer") 16 | o[e.id] = e.value.charAt(e.value.length - 1) === "/" ? e.value.substr(0, e.value.length - 1) : e.value; 17 | else if(e.id === "directory") { 18 | var ev = e.value; 19 | if(ev.match(/^\.|^([A-Za-z]:)|^(\\|\/)/g) != null) { 20 | toastr.error("Invalid download directory."); 21 | return; 22 | } 23 | ev = ev.replace(/\\/g, "/"); 24 | o[e.id] = ev.length > 1 && ev.charAt(ev.length - 1) !== "/" ? ev + "/" : ev; 25 | e.value = o[e.id]; 26 | } 27 | else { 28 | o[e.id] = +e.value; 29 | if(!Number.isFinite(o[e.id])) { 30 | toastr.error("Invalid number."); 31 | return; 32 | } 33 | if((e.id === "pageSwapDelay" || e.id === "pageSkipDelay") && o[e.id] < 0) 34 | o[e.id] = 0; 35 | e.value = o[e.id]; 36 | } 37 | 38 | /*This function will create a toast message every time the user does an action in the field options. */ 39 | toastr.success("Changes saved."); 40 | 41 | if(message) 42 | chrome.runtime.sendMessage({ 43 | what: "controller_message", 44 | message: { 45 | what: message, 46 | data: o[e.id] 47 | } 48 | }); 49 | 50 | chrome.storage.local.set(o, function() { 51 | chrome.runtime.sendMessage({ 52 | what: "update_settings" 53 | }); 54 | }); 55 | }, false); 56 | chrome.storage.local.get([e.id], function(a) { 57 | if(e.id in a) { 58 | if(e.tagName.match(/select/i)) 59 | e.querySelector("option[value='" + a[e.id] + "']").selected = "selected"; 60 | else 61 | e.value = a[e.id]; 62 | } 63 | }); 64 | }; 65 | 66 | if(e.id === "selectors") 67 | chrome.storage.local.get(["scannedOnce", "selectors"], function(a) { 68 | if(!a.scannedOnce) { 69 | var p = document.createElement("p"); 70 | p.innerHTML = "Currently using the exploit preset. This can become outdated if the reader is updated."; 71 | document.body.appendChild(p); 72 | } 73 | 74 | if(a.selectors == null) 75 | e.value = 1; 76 | 77 | f(); 78 | }); 79 | else if(e.id === "updateServer") 80 | chrome.storage.local.get(["updateServer"], function(a) { 81 | if(a.updateServer == null) 82 | e.value = "https://raw.githubusercontent.com/Cortys/comic-backup/master"; 83 | 84 | f(); 85 | }); 86 | else 87 | f(); 88 | }(selects[i])); 89 | 90 | document.getElementById("content").style.visibility = "visible"; 91 | -------------------------------------------------------------------------------- /source/options/toastr.css: -------------------------------------------------------------------------------- 1 | .toast-title { 2 | font-weight: bold; 3 | } 4 | .toast-message { 5 | -ms-word-wrap: break-word; 6 | word-wrap: break-word; 7 | } 8 | .toast-message a, 9 | .toast-message label { 10 | color: #ffffff; 11 | } 12 | .toast-message a:hover { 13 | color: #cccccc; 14 | text-decoration: none; 15 | } 16 | .toast-close-button { 17 | position: relative; 18 | right: -0.3em; 19 | top: -0.3em; 20 | float: right; 21 | font-size: 20px; 22 | font-weight: bold; 23 | color: #ffffff; 24 | -webkit-text-shadow: 0 1px 0 #ffffff; 25 | text-shadow: 0 1px 0 #ffffff; 26 | opacity: 0.8; 27 | -ms-filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=80); 28 | filter: alpha(opacity=80); 29 | } 30 | .toast-close-button:hover, 31 | .toast-close-button:focus { 32 | color: #000000; 33 | text-decoration: none; 34 | cursor: pointer; 35 | opacity: 0.4; 36 | -ms-filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=40); 37 | filter: alpha(opacity=40); 38 | } 39 | /*Additional properties for button version 40 | iOS requires the button element instead of an anchor tag. 41 | If you want the anchor version, it requires `href="#"`.*/ 42 | button.toast-close-button { 43 | padding: 0; 44 | cursor: pointer; 45 | background: transparent; 46 | border: 0; 47 | -webkit-appearance: none; 48 | } 49 | .toast-top-center { 50 | top: 0; 51 | right: 0; 52 | width: 100%; 53 | } 54 | .toast-bottom-center { 55 | bottom: 0; 56 | right: 0; 57 | width: 100%; 58 | } 59 | .toast-top-full-width { 60 | top: 0; 61 | right: 0; 62 | width: 100%; 63 | } 64 | .toast-bottom-full-width { 65 | bottom: 0; 66 | right: 0; 67 | width: 100%; 68 | } 69 | .toast-top-left { 70 | top: 12px; 71 | left: 12px; 72 | } 73 | .toast-top-right { 74 | top: 12px; 75 | right: 12px; 76 | } 77 | .toast-bottom-right { 78 | right: 12px; 79 | bottom: 12px; 80 | } 81 | .toast-bottom-left { 82 | bottom: 12px; 83 | left: 12px; 84 | } 85 | #toast-container { 86 | position: fixed; 87 | z-index: 999999; 88 | /*overrides*/ 89 | 90 | } 91 | #toast-container * { 92 | -moz-box-sizing: border-box; 93 | -webkit-box-sizing: border-box; 94 | box-sizing: border-box; 95 | } 96 | #toast-container > div { 97 | position: relative; 98 | overflow: hidden; 99 | margin: 0 0 6px; 100 | /*padding: 15px 15px 15px 50px;*/ 101 | width: 300px; 102 | -moz-border-radius: 3px 3px 3px 3px; 103 | -webkit-border-radius: 3px 3px 3px 3px; 104 | border-radius: 3px 3px 3px 3px; 105 | background-position: 15px center; 106 | background-repeat: no-repeat; 107 | -moz-box-shadow: 0 0 12px #999999; 108 | -webkit-box-shadow: 0 0 12px #999999; 109 | box-shadow: 0 0 12px #999999; 110 | color: #ffffff; 111 | opacity: 0.8; 112 | -ms-filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=80); 113 | filter: alpha(opacity=80); 114 | } 115 | #toast-container > :hover { 116 | -moz-box-shadow: 0 0 12px #000000; 117 | -webkit-box-shadow: 0 0 12px #000000; 118 | box-shadow: 0 0 12px #000000; 119 | opacity: 1; 120 | -ms-filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=100); 121 | filter: alpha(opacity=100); 122 | cursor: pointer; 123 | } 124 | #toast-container > .toast-info { 125 | background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAGwSURBVEhLtZa9SgNBEMc9sUxxRcoUKSzSWIhXpFMhhYWFhaBg4yPYiWCXZxBLERsLRS3EQkEfwCKdjWJAwSKCgoKCcudv4O5YLrt7EzgXhiU3/4+b2ckmwVjJSpKkQ6wAi4gwhT+z3wRBcEz0yjSseUTrcRyfsHsXmD0AmbHOC9Ii8VImnuXBPglHpQ5wwSVM7sNnTG7Za4JwDdCjxyAiH3nyA2mtaTJufiDZ5dCaqlItILh1NHatfN5skvjx9Z38m69CgzuXmZgVrPIGE763Jx9qKsRozWYw6xOHdER+nn2KkO+Bb+UV5CBN6WC6QtBgbRVozrahAbmm6HtUsgtPC19tFdxXZYBOfkbmFJ1VaHA1VAHjd0pp70oTZzvR+EVrx2Ygfdsq6eu55BHYR8hlcki+n+kERUFG8BrA0BwjeAv2M8WLQBtcy+SD6fNsmnB3AlBLrgTtVW1c2QN4bVWLATaIS60J2Du5y1TiJgjSBvFVZgTmwCU+dAZFoPxGEEs8nyHC9Bwe2GvEJv2WXZb0vjdyFT4Cxk3e/kIqlOGoVLwwPevpYHT+00T+hWwXDf4AJAOUqWcDhbwAAAAASUVORK5CYII=") !important; 126 | } 127 | #toast-container > .toast-error { 128 | background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAHOSURBVEhLrZa/SgNBEMZzh0WKCClSCKaIYOED+AAKeQQLG8HWztLCImBrYadgIdY+gIKNYkBFSwu7CAoqCgkkoGBI/E28PdbLZmeDLgzZzcx83/zZ2SSXC1j9fr+I1Hq93g2yxH4iwM1vkoBWAdxCmpzTxfkN2RcyZNaHFIkSo10+8kgxkXIURV5HGxTmFuc75B2RfQkpxHG8aAgaAFa0tAHqYFfQ7Iwe2yhODk8+J4C7yAoRTWI3w/4klGRgR4lO7Rpn9+gvMyWp+uxFh8+H+ARlgN1nJuJuQAYvNkEnwGFck18Er4q3egEc/oO+mhLdKgRyhdNFiacC0rlOCbhNVz4H9FnAYgDBvU3QIioZlJFLJtsoHYRDfiZoUyIxqCtRpVlANq0EU4dApjrtgezPFad5S19Wgjkc0hNVnuF4HjVA6C7QrSIbylB+oZe3aHgBsqlNqKYH48jXyJKMuAbiyVJ8KzaB3eRc0pg9VwQ4niFryI68qiOi3AbjwdsfnAtk0bCjTLJKr6mrD9g8iq/S/B81hguOMlQTnVyG40wAcjnmgsCNESDrjme7wfftP4P7SP4N3CJZdvzoNyGq2c/HWOXJGsvVg+RA/k2MC/wN6I2YA2Pt8GkAAAAASUVORK5CYII=") !important; 129 | } 130 | #toast-container > .toast-success { 131 | background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAADsSURBVEhLY2AYBfQMgf///3P8+/evAIgvA/FsIF+BavYDDWMBGroaSMMBiE8VC7AZDrIFaMFnii3AZTjUgsUUWUDA8OdAH6iQbQEhw4HyGsPEcKBXBIC4ARhex4G4BsjmweU1soIFaGg/WtoFZRIZdEvIMhxkCCjXIVsATV6gFGACs4Rsw0EGgIIH3QJYJgHSARQZDrWAB+jawzgs+Q2UO49D7jnRSRGoEFRILcdmEMWGI0cm0JJ2QpYA1RDvcmzJEWhABhD/pqrL0S0CWuABKgnRki9lLseS7g2AlqwHWQSKH4oKLrILpRGhEQCw2LiRUIa4lwAAAABJRU5ErkJggg==") !important; 132 | } 133 | #toast-container > .toast-warning { 134 | background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAGYSURBVEhL5ZSvTsNQFMbXZGICMYGYmJhAQIJAICYQPAACiSDB8AiICQQJT4CqQEwgJvYASAQCiZiYmJhAIBATCARJy+9rTsldd8sKu1M0+dLb057v6/lbq/2rK0mS/TRNj9cWNAKPYIJII7gIxCcQ51cvqID+GIEX8ASG4B1bK5gIZFeQfoJdEXOfgX4QAQg7kH2A65yQ87lyxb27sggkAzAuFhbbg1K2kgCkB1bVwyIR9m2L7PRPIhDUIXgGtyKw575yz3lTNs6X4JXnjV+LKM/m3MydnTbtOKIjtz6VhCBq4vSm3ncdrD2lk0VgUXSVKjVDJXJzijW1RQdsU7F77He8u68koNZTz8Oz5yGa6J3H3lZ0xYgXBK2QymlWWA+RWnYhskLBv2vmE+hBMCtbA7KX5drWyRT/2JsqZ2IvfB9Y4bWDNMFbJRFmC9E74SoS0CqulwjkC0+5bpcV1CZ8NMej4pjy0U+doDQsGyo1hzVJttIjhQ7GnBtRFN1UarUlH8F3xict+HY07rEzoUGPlWcjRFRr4/gChZgc3ZL2d8oAAAAASUVORK5CYII=") !important; 135 | } 136 | #toast-container.toast-top-center > div, 137 | #toast-container.toast-bottom-center > div { 138 | width: 300px; 139 | margin: auto; 140 | } 141 | #toast-container.toast-top-full-width > div, 142 | #toast-container.toast-bottom-full-width > div { 143 | width: 96%; 144 | margin: auto; 145 | } 146 | .toast { 147 | background-color: #030303; 148 | } 149 | .toast-success { 150 | background-color: #51a351; 151 | } 152 | .toast-error { 153 | background-color: #bd362f; 154 | } 155 | .toast-info { 156 | background-color: #2f96b4; 157 | } 158 | .toast-warning { 159 | background-color: #f89406; 160 | } 161 | 162 | .toast-progress { 163 | position: absolute; 164 | left: 0; 165 | bottom: 0; 166 | height: 4px; 167 | background-color: #000000; 168 | opacity: 0.4; 169 | -ms-filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=40); 170 | filter: alpha(opacity=40); 171 | } 172 | 173 | /*Responsive Design*/ 174 | @media all and (max-width: 240px) { 175 | #toast-container > div { 176 | padding: 8px 8px 8px 50px; 177 | width: 11em; 178 | } 179 | #toast-container .toast-close-button { 180 | right: -0.2em; 181 | top: -0.2em; 182 | } 183 | } 184 | @media all and (min-width: 241px) and (max-width: 480px) { 185 | #toast-container > div { 186 | padding: 8px 8px 8px 50px; 187 | width: 18em; 188 | } 189 | #toast-container .toast-close-button { 190 | right: -0.2em; 191 | top: -0.2em; 192 | } 193 | } 194 | @media all and (min-width: 481px) and (max-width: 768px) { 195 | #toast-container > div { 196 | padding: 15px 15px 15px 50px; 197 | width: 25em; 198 | } 199 | } 200 | -------------------------------------------------------------------------------- /source/options/toastr.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Toastr 3 | * Copyright 2012-2015 4 | * Authors: John Papa, Hans Fjällemark, and Tim Ferrell. 5 | * All Rights Reserved. 6 | * Use, reproduction, distribution, and modification of this code is subject to the terms and 7 | * conditions of the MIT license, available at http://www.opensource.org/licenses/mit-license.php 8 | * 9 | * ARIA Support: Greta Krafsig 10 | * 11 | * Project: https://github.com/CodeSeven/toastr 12 | */ 13 | /* global define */ 14 | (function (define) { 15 | define(['jquery'], function ($) { 16 | return (function () { 17 | var $container; 18 | var listener; 19 | var toastId = 0; 20 | var toastType = { 21 | error: 'error', 22 | info: 'info', 23 | success: 'success', 24 | warning: 'warning' 25 | }; 26 | 27 | var toastr = { 28 | clear: clear, 29 | remove: remove, 30 | error: error, 31 | getContainer: getContainer, 32 | info: info, 33 | options: {}, 34 | subscribe: subscribe, 35 | success: success, 36 | version: '2.1.2', 37 | warning: warning 38 | }; 39 | 40 | var previousToast; 41 | 42 | return toastr; 43 | 44 | //////////////// 45 | 46 | function error(message, title, optionsOverride) { 47 | return notify({ 48 | type: toastType.error, 49 | iconClass: getOptions().iconClasses.error, 50 | message: message, 51 | optionsOverride: optionsOverride, 52 | title: title 53 | }); 54 | } 55 | 56 | function getContainer(options, create) { 57 | if (!options) { options = getOptions(); } 58 | $container = $('#' + options.containerId); 59 | if ($container.length) { 60 | return $container; 61 | } 62 | if (create) { 63 | $container = createContainer(options); 64 | } 65 | return $container; 66 | } 67 | 68 | function info(message, title, optionsOverride) { 69 | return notify({ 70 | type: toastType.info, 71 | iconClass: getOptions().iconClasses.info, 72 | message: message, 73 | optionsOverride: optionsOverride, 74 | title: title 75 | }); 76 | } 77 | 78 | function subscribe(callback) { 79 | listener = callback; 80 | } 81 | 82 | function success(message, title, optionsOverride) { 83 | return notify({ 84 | type: toastType.success, 85 | iconClass: getOptions().iconClasses.success, 86 | message: message, 87 | optionsOverride: optionsOverride, 88 | title: title 89 | }); 90 | } 91 | 92 | function warning(message, title, optionsOverride) { 93 | return notify({ 94 | type: toastType.warning, 95 | iconClass: getOptions().iconClasses.warning, 96 | message: message, 97 | optionsOverride: optionsOverride, 98 | title: title 99 | }); 100 | } 101 | 102 | function clear($toastElement, clearOptions) { 103 | var options = getOptions(); 104 | if (!$container) { getContainer(options); } 105 | if (!clearToast($toastElement, options, clearOptions)) { 106 | clearContainer(options); 107 | } 108 | } 109 | 110 | function remove($toastElement) { 111 | var options = getOptions(); 112 | if (!$container) { getContainer(options); } 113 | if ($toastElement && $(':focus', $toastElement).length === 0) { 114 | removeToast($toastElement); 115 | return; 116 | } 117 | if ($container.children().length) { 118 | $container.remove(); 119 | } 120 | } 121 | 122 | // internal functions 123 | 124 | function clearContainer (options) { 125 | var toastsToClear = $container.children(); 126 | for (var i = toastsToClear.length - 1; i >= 0; i--) { 127 | clearToast($(toastsToClear[i]), options); 128 | } 129 | } 130 | 131 | function clearToast ($toastElement, options, clearOptions) { 132 | var force = clearOptions && clearOptions.force ? clearOptions.force : false; 133 | if ($toastElement && (force || $(':focus', $toastElement).length === 0)) { 134 | $toastElement[options.hideMethod]({ 135 | duration: options.hideDuration, 136 | easing: options.hideEasing, 137 | complete: function () { removeToast($toastElement); } 138 | }); 139 | return true; 140 | } 141 | return false; 142 | } 143 | 144 | function createContainer(options) { 145 | $container = $('
') 146 | .attr('id', options.containerId) 147 | .addClass(options.positionClass) 148 | .attr('aria-live', 'polite') 149 | .attr('role', 'alert'); 150 | 151 | $container.appendTo($(options.target)); 152 | return $container; 153 | } 154 | /* This function is where you edit the look and feel of the toast. */ 155 | function getDefaults() { 156 | return { 157 | tapToDismiss: true, 158 | toastClass: 'toast', 159 | containerId: 'toast-container', 160 | debug: false, 161 | 162 | showMethod: 'fadeIn', //fadeIn, slideDown, and show are built into jQuery 163 | showDuration: 300, 164 | showEasing: 'swing', //swing and linear are built into jQuery 165 | onShown: undefined, 166 | hideMethod: 'fadeOut', 167 | hideDuration: 1000, 168 | hideEasing: 'swing', 169 | onHidden: undefined, 170 | closeMethod: false, 171 | closeDuration: false, 172 | closeEasing: false, 173 | 174 | extendedTimeOut: 1000, 175 | iconClasses: { 176 | error: 'toast-error', 177 | info: 'toast-info', 178 | success: 'toast-success', 179 | warning: 'toast-warning' 180 | }, 181 | iconClass: 'toast-info', 182 | positionClass: 'toast-bottom-right', 183 | timeOut: 400, // Set timeOut and extendedTimeOut to 0 to make it sticky 184 | titleClass: 'toast-title', 185 | messageClass: 'toast-message', 186 | escapeHtml: false, 187 | target: 'body', 188 | closeHtml: '', 189 | newestOnTop: true, 190 | preventDuplicates: false, 191 | progressBar: false 192 | }; 193 | } 194 | 195 | function publish(args) { 196 | if (!listener) { return; } 197 | listener(args); 198 | } 199 | 200 | function notify(map) { 201 | var options = getOptions(); 202 | var iconClass = map.iconClass || options.iconClass; 203 | 204 | if (typeof (map.optionsOverride) !== 'undefined') { 205 | options = $.extend(options, map.optionsOverride); 206 | iconClass = map.optionsOverride.iconClass || iconClass; 207 | } 208 | 209 | if (shouldExit(options, map)) { return; } 210 | 211 | toastId++; 212 | 213 | $container = getContainer(options, true); 214 | 215 | var intervalId = null; 216 | var $toastElement = $('
'); 217 | var $titleElement = $('
'); 218 | var $messageElement = $('
'); 219 | var $progressElement = $('
'); 220 | var $closeElement = $(options.closeHtml); 221 | var progressBar = { 222 | intervalId: null, 223 | hideEta: null, 224 | maxHideTime: null 225 | }; 226 | var response = { 227 | toastId: toastId, 228 | state: 'visible', 229 | startTime: new Date(), 230 | options: options, 231 | map: map 232 | }; 233 | 234 | personalizeToast(); 235 | 236 | displayToast(); 237 | 238 | handleEvents(); 239 | 240 | publish(response); 241 | 242 | if (options.debug && console) { 243 | console.log(response); 244 | } 245 | 246 | return $toastElement; 247 | 248 | function escapeHtml(source) { 249 | if (source == null) 250 | source = ""; 251 | 252 | return new String(source) 253 | .replace(/&/g, '&') 254 | .replace(/"/g, '"') 255 | .replace(/'/g, ''') 256 | .replace(//g, '>'); 258 | } 259 | 260 | function personalizeToast() { 261 | setIcon(); 262 | setTitle(); 263 | setMessage(); 264 | setCloseButton(); 265 | setProgressBar(); 266 | setSequence(); 267 | } 268 | 269 | function handleEvents() { 270 | $toastElement.hover(stickAround, delayedHideToast); 271 | if (!options.onclick && options.tapToDismiss) { 272 | $toastElement.click(hideToast); 273 | } 274 | 275 | if (options.closeButton && $closeElement) { 276 | $closeElement.click(function (event) { 277 | if (event.stopPropagation) { 278 | event.stopPropagation(); 279 | } else if (event.cancelBubble !== undefined && event.cancelBubble !== true) { 280 | event.cancelBubble = true; 281 | } 282 | hideToast(true); 283 | }); 284 | } 285 | 286 | if (options.onclick) { 287 | $toastElement.click(function (event) { 288 | options.onclick(event); 289 | hideToast(); 290 | }); 291 | } 292 | } 293 | 294 | function displayToast() { 295 | $toastElement.hide(); 296 | 297 | $toastElement[options.showMethod]( 298 | {duration: options.showDuration, easing: options.showEasing, complete: options.onShown} 299 | ); 300 | 301 | if (options.timeOut > 0) { 302 | intervalId = setTimeout(hideToast, options.timeOut); 303 | progressBar.maxHideTime = parseFloat(options.timeOut); 304 | progressBar.hideEta = new Date().getTime() + progressBar.maxHideTime; 305 | if (options.progressBar) { 306 | progressBar.intervalId = setInterval(updateProgress, 10); 307 | } 308 | } 309 | } 310 | 311 | function setIcon() { 312 | if (map.iconClass) { 313 | $toastElement.addClass(options.toastClass).addClass(iconClass); 314 | } 315 | } 316 | 317 | function setSequence() { 318 | if (options.newestOnTop) { 319 | $container.prepend($toastElement); 320 | } else { 321 | $container.append($toastElement); 322 | } 323 | } 324 | 325 | function setTitle() { 326 | if (map.title) { 327 | $titleElement.append(!options.escapeHtml ? map.title : escapeHtml(map.title)).addClass(options.titleClass); 328 | $toastElement.append($titleElement); 329 | } 330 | } 331 | 332 | function setMessage() { 333 | if (map.message) { 334 | $messageElement.append(!options.escapeHtml ? map.message : escapeHtml(map.message)).addClass(options.messageClass); 335 | $toastElement.append($messageElement); 336 | } 337 | } 338 | 339 | function setCloseButton() { 340 | if (options.closeButton) { 341 | $closeElement.addClass('toast-close-button').attr('role', 'button'); 342 | $toastElement.prepend($closeElement); 343 | } 344 | } 345 | 346 | function setProgressBar() { 347 | if (options.progressBar) { 348 | $progressElement.addClass('toast-progress'); 349 | $toastElement.prepend($progressElement); 350 | } 351 | } 352 | 353 | function shouldExit(options, map) { 354 | if (options.preventDuplicates) { 355 | if (map.message === previousToast) { 356 | return true; 357 | } else { 358 | previousToast = map.message; 359 | } 360 | } 361 | return false; 362 | } 363 | 364 | function hideToast(override) { 365 | var method = override && options.closeMethod !== false ? options.closeMethod : options.hideMethod; 366 | var duration = override && options.closeDuration !== false ? 367 | options.closeDuration : options.hideDuration; 368 | var easing = override && options.closeEasing !== false ? options.closeEasing : options.hideEasing; 369 | if ($(':focus', $toastElement).length && !override) { 370 | return; 371 | } 372 | clearTimeout(progressBar.intervalId); 373 | return $toastElement[method]({ 374 | duration: duration, 375 | easing: easing, 376 | complete: function () { 377 | removeToast($toastElement); 378 | if (options.onHidden && response.state !== 'hidden') { 379 | options.onHidden(); 380 | } 381 | response.state = 'hidden'; 382 | response.endTime = new Date(); 383 | publish(response); 384 | } 385 | }); 386 | } 387 | 388 | function delayedHideToast() { 389 | if (options.timeOut > 0 || options.extendedTimeOut > 0) { 390 | intervalId = setTimeout(hideToast, options.extendedTimeOut); 391 | progressBar.maxHideTime = parseFloat(options.extendedTimeOut); 392 | progressBar.hideEta = new Date().getTime() + progressBar.maxHideTime; 393 | } 394 | } 395 | 396 | function stickAround() { 397 | clearTimeout(intervalId); 398 | progressBar.hideEta = 0; 399 | $toastElement.stop(true, true)[options.showMethod]( 400 | {duration: options.showDuration, easing: options.showEasing} 401 | ); 402 | } 403 | 404 | function updateProgress() { 405 | var percentage = ((progressBar.hideEta - (new Date().getTime())) / progressBar.maxHideTime) * 100; 406 | $progressElement.width(percentage + '%'); 407 | } 408 | } 409 | 410 | function getOptions() { 411 | return $.extend({}, getDefaults(), toastr.options); 412 | } 413 | 414 | function removeToast($toastElement) { 415 | if (!$container) { $container = getContainer(); } 416 | if ($toastElement.is(':visible')) { 417 | return; 418 | } 419 | $toastElement.remove(); 420 | $toastElement = null; 421 | if ($container.children().length === 0) { 422 | $container.remove(); 423 | previousToast = undefined; 424 | } 425 | } 426 | 427 | })(); 428 | }); 429 | }(typeof define === 'function' && define.amd ? define : function (deps, factory) { 430 | if (typeof module !== 'undefined' && module.exports) { //Node 431 | module.exports = factory(require('jquery')); 432 | } else { 433 | window.toastr = factory(window.jQuery); 434 | } 435 | })); 436 | -------------------------------------------------------------------------------- /source/reactivateDom.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | var script = document.createElement("script"); 4 | script.type = "text/javascript"; 5 | script.id = randomString(20, 40); 6 | script.innerHTML = `(function() { 7 | var f = function MutationObserver() {}, 8 | sp = Event.prototype.stopPropagation, 9 | ael = EventTarget.prototype.addEventListener; 10 | 11 | f.prototype.observe = function() {}; 12 | 13 | window.MutationObserver = f; 14 | Object.defineProperty(window, 'MutationObserver', { 15 | value: f, 16 | writable: false, 17 | configurable: false 18 | }); 19 | 20 | Event.prototype.stopPropagation = function stopPropagation() { 21 | if(!document.documentElement.hasAttribute('scanning')) 22 | sp.apply(this, arguments); 23 | }; 24 | EventTarget.prototype.addEventListener = function addEventListener(type) { 25 | if(type !== "beforeunload") 26 | return ael.apply(this, arguments); 27 | }; 28 | 29 | document.documentElement.removeChild(document.getElementById("${script.id}")); 30 | }())`; 31 | 32 | document.documentElement.insertBefore(script, document.documentElement.firstChild); 33 | -------------------------------------------------------------------------------- /source/throttleBlocker.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | function throttleBlocker() { 4 | if(typeof RTCPeerConnection !== "function" || throttleBlocker.active) 5 | return; 6 | 7 | throttleBlocker.active = true; 8 | 9 | var connA = new RTCPeerConnection(); 10 | var connB = new RTCPeerConnection(); 11 | connA.createDataChannel("dummy_channel"); 12 | connA.onicecandidate = e => !e.candidate || connB.addIceCandidate(e.candidate); 13 | connB.onicecandidate = e => !e.candidate || connA.addIceCandidate(e.candidate); 14 | connA.createOffer() 15 | .then(offer => connA.setLocalDescription(offer)) 16 | .then(() => connB.setRemoteDescription(connA.localDescription)) 17 | .then(() => connB.createAnswer()) 18 | .then(answer => connB.setLocalDescription(answer)) 19 | .then(() => connA.setRemoteDescription(connB.localDescription)); 20 | } 21 | -------------------------------------------------------------------------------- /source/zip/z-worker.js: -------------------------------------------------------------------------------- 1 | /* jshint worker:true */ 2 | (function main(global) { 3 | "use strict"; 4 | 5 | if (global.zWorkerInitialized) 6 | throw new Error('z-worker.js should be run only once'); 7 | global.zWorkerInitialized = true; 8 | 9 | addEventListener("message", function(event) { 10 | var message = event.data, type = message.type, sn = message.sn; 11 | var handler = handlers[type]; 12 | if (handler) { 13 | try { 14 | handler(message); 15 | } catch (e) { 16 | onError(type, sn, e); 17 | } 18 | } 19 | //for debug 20 | //postMessage({type: 'echo', originalType: type, sn: sn}); 21 | }); 22 | 23 | var handlers = { 24 | importScripts: doImportScripts, 25 | newTask: newTask, 26 | append: processData, 27 | flush: processData, 28 | }; 29 | 30 | // deflater/inflater tasks indexed by serial numbers 31 | var tasks = {}; 32 | 33 | function doImportScripts(msg) { 34 | if (msg.scripts && msg.scripts.length > 0) 35 | importScripts.apply(undefined, msg.scripts); 36 | postMessage({type: 'importScripts'}); 37 | } 38 | 39 | function newTask(msg) { 40 | var CodecClass = global[msg.codecClass]; 41 | var sn = msg.sn; 42 | if (tasks[sn]) 43 | throw Error('duplicated sn'); 44 | tasks[sn] = { 45 | codec: new CodecClass(msg.options), 46 | crcInput: msg.crcType === 'input', 47 | crcOutput: msg.crcType === 'output', 48 | crc: new Crc32(), 49 | }; 50 | postMessage({type: 'newTask', sn: sn}); 51 | } 52 | 53 | // performance may not be supported 54 | var now = global.performance ? global.performance.now.bind(global.performance) : Date.now; 55 | 56 | function processData(msg) { 57 | var sn = msg.sn, type = msg.type, input = msg.data; 58 | var task = tasks[sn]; 59 | // allow creating codec on first append 60 | if (!task && msg.codecClass) { 61 | newTask(msg); 62 | task = tasks[sn]; 63 | } 64 | var isAppend = type === 'append'; 65 | var start = now(); 66 | var output; 67 | if (isAppend) { 68 | try { 69 | output = task.codec.append(input, function onprogress(loaded) { 70 | postMessage({type: 'progress', sn: sn, loaded: loaded}); 71 | }); 72 | } catch (e) { 73 | delete tasks[sn]; 74 | throw e; 75 | } 76 | } else { 77 | delete tasks[sn]; 78 | output = task.codec.flush(); 79 | } 80 | var codecTime = now() - start; 81 | 82 | start = now(); 83 | if (input && task.crcInput) 84 | task.crc.append(input); 85 | if (output && task.crcOutput) 86 | task.crc.append(output); 87 | var crcTime = now() - start; 88 | 89 | var rmsg = {type: type, sn: sn, codecTime: codecTime, crcTime: crcTime}; 90 | var transferables = []; 91 | if (output) { 92 | rmsg.data = output; 93 | transferables.push(output.buffer); 94 | } 95 | if (!isAppend && (task.crcInput || task.crcOutput)) 96 | rmsg.crc = task.crc.get(); 97 | 98 | // posting a message with transferables will fail on IE10 99 | try { 100 | postMessage(rmsg, transferables); 101 | } catch(ex) { 102 | postMessage(rmsg); // retry without transferables 103 | } 104 | } 105 | 106 | function onError(type, sn, e) { 107 | var msg = { 108 | type: type, 109 | sn: sn, 110 | error: formatError(e) 111 | }; 112 | postMessage(msg); 113 | } 114 | 115 | function formatError(e) { 116 | return { message: e.message, stack: e.stack }; 117 | } 118 | 119 | // Crc32 code copied from file zip.js 120 | function Crc32() { 121 | this.crc = -1; 122 | } 123 | Crc32.prototype.append = function append(data) { 124 | var crc = this.crc | 0, table = this.table; 125 | for (var offset = 0, len = data.length | 0; offset < len; offset++) 126 | crc = (crc >>> 8) ^ table[(crc ^ data[offset]) & 0xFF]; 127 | this.crc = crc; 128 | }; 129 | Crc32.prototype.get = function get() { 130 | return ~this.crc; 131 | }; 132 | Crc32.prototype.table = (function() { 133 | var i, j, t, table = []; // Uint32Array is actually slower than [] 134 | for (i = 0; i < 256; i++) { 135 | t = i; 136 | for (j = 0; j < 8; j++) 137 | if (t & 1) 138 | t = (t >>> 1) ^ 0xEDB88320; 139 | else 140 | t = t >>> 1; 141 | table[i] = t; 142 | } 143 | return table; 144 | })(); 145 | 146 | // "no-op" codec 147 | function NOOP() {} 148 | global.NOOP = NOOP; 149 | NOOP.prototype.append = function append(bytes, onprogress) { 150 | return bytes; 151 | }; 152 | NOOP.prototype.flush = function flush() {}; 153 | })(this); 154 | -------------------------------------------------------------------------------- /source/zip/zip.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2013 Gildas Lormeau. All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | 1. Redistributions of source code must retain the above copyright notice, 8 | this list of conditions and the following disclaimer. 9 | 10 | 2. Redistributions in binary form must reproduce the above copyright 11 | notice, this list of conditions and the following disclaimer in 12 | the documentation and/or other materials provided with the distribution. 13 | 14 | 3. The names of the authors may not be used to endorse or promote products 15 | derived from this software without specific prior written permission. 16 | 17 | THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, 18 | INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 19 | FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, 20 | INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, 21 | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 22 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 23 | OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 24 | LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 25 | NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 26 | EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27 | */ 28 | 29 | (function(obj) { 30 | "use strict"; 31 | 32 | var ERR_BAD_FORMAT = "File format is not recognized."; 33 | var ERR_CRC = "CRC failed."; 34 | var ERR_ENCRYPTED = "File contains encrypted entry."; 35 | var ERR_ZIP64 = "File is using Zip64 (4gb+ file size)."; 36 | var ERR_READ = "Error while reading zip file."; 37 | var ERR_WRITE = "Error while writing zip file."; 38 | var ERR_WRITE_DATA = "Error while writing file data."; 39 | var ERR_READ_DATA = "Error while reading file data."; 40 | var ERR_DUPLICATED_NAME = "File already exists."; 41 | var CHUNK_SIZE = 512 * 1024; 42 | 43 | var TEXT_PLAIN = "text/plain"; 44 | 45 | var appendABViewSupported; 46 | try { 47 | appendABViewSupported = new Blob([ new DataView(new ArrayBuffer(0)) ]).size === 0; 48 | } catch (e) { 49 | } 50 | 51 | function Crc32() { 52 | this.crc = -1; 53 | } 54 | Crc32.prototype.append = function append(data) { 55 | var crc = this.crc | 0, table = this.table; 56 | for (var offset = 0, len = data.length | 0; offset < len; offset++) 57 | crc = (crc >>> 8) ^ table[(crc ^ data[offset]) & 0xFF]; 58 | this.crc = crc; 59 | }; 60 | Crc32.prototype.get = function get() { 61 | return ~this.crc; 62 | }; 63 | Crc32.prototype.table = (function() { 64 | var i, j, t, table = []; // Uint32Array is actually slower than [] 65 | for (i = 0; i < 256; i++) { 66 | t = i; 67 | for (j = 0; j < 8; j++) 68 | if (t & 1) 69 | t = (t >>> 1) ^ 0xEDB88320; 70 | else 71 | t = t >>> 1; 72 | table[i] = t; 73 | } 74 | return table; 75 | })(); 76 | 77 | // "no-op" codec 78 | function NOOP() {} 79 | NOOP.prototype.append = function append(bytes, onprogress) { 80 | return bytes; 81 | }; 82 | NOOP.prototype.flush = function flush() {}; 83 | 84 | function blobSlice(blob, index, length) { 85 | if (index < 0 || length < 0 || index + length > blob.size) 86 | throw new RangeError('offset:' + index + ', length:' + length + ', size:' + blob.size); 87 | if (blob.slice) 88 | return blob.slice(index, index + length); 89 | else if (blob.webkitSlice) 90 | return blob.webkitSlice(index, index + length); 91 | else if (blob.mozSlice) 92 | return blob.mozSlice(index, index + length); 93 | else if (blob.msSlice) 94 | return blob.msSlice(index, index + length); 95 | } 96 | 97 | function getDataHelper(byteLength, bytes) { 98 | var dataBuffer, dataArray; 99 | dataBuffer = new ArrayBuffer(byteLength); 100 | dataArray = new Uint8Array(dataBuffer); 101 | if (bytes) 102 | dataArray.set(bytes, 0); 103 | return { 104 | buffer : dataBuffer, 105 | array : dataArray, 106 | view : new DataView(dataBuffer) 107 | }; 108 | } 109 | 110 | // Readers 111 | function Reader() { 112 | } 113 | 114 | function TextReader(text) { 115 | var that = this, blobReader; 116 | 117 | function init(callback, onerror) { 118 | var blob = new Blob([ text ], { 119 | type : TEXT_PLAIN 120 | }); 121 | blobReader = new BlobReader(blob); 122 | blobReader.init(function() { 123 | that.size = blobReader.size; 124 | callback(); 125 | }, onerror); 126 | } 127 | 128 | function readUint8Array(index, length, callback, onerror) { 129 | blobReader.readUint8Array(index, length, callback, onerror); 130 | } 131 | 132 | that.size = 0; 133 | that.init = init; 134 | that.readUint8Array = readUint8Array; 135 | } 136 | TextReader.prototype = new Reader(); 137 | TextReader.prototype.constructor = TextReader; 138 | 139 | function Data64URIReader(dataURI) { 140 | var that = this, dataStart; 141 | 142 | function init(callback) { 143 | var dataEnd = dataURI.length; 144 | while (dataURI.charAt(dataEnd - 1) == "=") 145 | dataEnd--; 146 | dataStart = dataURI.indexOf(",") + 1; 147 | that.size = Math.floor((dataEnd - dataStart) * 0.75); 148 | callback(); 149 | } 150 | 151 | function readUint8Array(index, length, callback) { 152 | var i, data = getDataHelper(length); 153 | var start = Math.floor(index / 3) * 4; 154 | var end = Math.ceil((index + length) / 3) * 4; 155 | var bytes = obj.atob(dataURI.substring(start + dataStart, end + dataStart)); 156 | var delta = index - Math.floor(start / 4) * 3; 157 | for (i = delta; i < delta + length; i++) 158 | data.array[i - delta] = bytes.charCodeAt(i); 159 | callback(data.array); 160 | } 161 | 162 | that.size = 0; 163 | that.init = init; 164 | that.readUint8Array = readUint8Array; 165 | } 166 | Data64URIReader.prototype = new Reader(); 167 | Data64URIReader.prototype.constructor = Data64URIReader; 168 | 169 | function BlobReader(blob) { 170 | var that = this; 171 | 172 | function init(callback) { 173 | that.size = blob.size; 174 | callback(); 175 | } 176 | 177 | function readUint8Array(index, length, callback, onerror) { 178 | var reader = new FileReader(); 179 | reader.onload = function(e) { 180 | callback(new Uint8Array(e.target.result)); 181 | }; 182 | reader.onerror = onerror; 183 | try { 184 | reader.readAsArrayBuffer(blobSlice(blob, index, length)); 185 | } catch (e) { 186 | onerror(e); 187 | } 188 | } 189 | 190 | that.size = 0; 191 | that.init = init; 192 | that.readUint8Array = readUint8Array; 193 | } 194 | BlobReader.prototype = new Reader(); 195 | BlobReader.prototype.constructor = BlobReader; 196 | 197 | // Writers 198 | 199 | function Writer() { 200 | } 201 | Writer.prototype.getData = function(callback) { 202 | callback(this.data); 203 | }; 204 | 205 | function TextWriter(encoding) { 206 | var that = this, blob; 207 | 208 | function init(callback) { 209 | blob = new Blob([], { 210 | type : TEXT_PLAIN 211 | }); 212 | callback(); 213 | } 214 | 215 | function writeUint8Array(array, callback) { 216 | blob = new Blob([ blob, appendABViewSupported ? array : array.buffer ], { 217 | type : TEXT_PLAIN 218 | }); 219 | callback(); 220 | } 221 | 222 | function getData(callback, onerror) { 223 | var reader = new FileReader(); 224 | reader.onload = function(e) { 225 | callback(e.target.result); 226 | }; 227 | reader.onerror = onerror; 228 | reader.readAsText(blob, encoding); 229 | } 230 | 231 | that.init = init; 232 | that.writeUint8Array = writeUint8Array; 233 | that.getData = getData; 234 | } 235 | TextWriter.prototype = new Writer(); 236 | TextWriter.prototype.constructor = TextWriter; 237 | 238 | function Data64URIWriter(contentType) { 239 | var that = this, data = "", pending = ""; 240 | 241 | function init(callback) { 242 | data += "data:" + (contentType || "") + ";base64,"; 243 | callback(); 244 | } 245 | 246 | function writeUint8Array(array, callback) { 247 | var i, delta = pending.length, dataString = pending; 248 | pending = ""; 249 | for (i = 0; i < (Math.floor((delta + array.length) / 3) * 3) - delta; i++) 250 | dataString += String.fromCharCode(array[i]); 251 | for (; i < array.length; i++) 252 | pending += String.fromCharCode(array[i]); 253 | if (dataString.length > 2) 254 | data += obj.btoa(dataString); 255 | else 256 | pending = dataString; 257 | callback(); 258 | } 259 | 260 | function getData(callback) { 261 | callback(data + obj.btoa(pending)); 262 | } 263 | 264 | that.init = init; 265 | that.writeUint8Array = writeUint8Array; 266 | that.getData = getData; 267 | } 268 | Data64URIWriter.prototype = new Writer(); 269 | Data64URIWriter.prototype.constructor = Data64URIWriter; 270 | 271 | function BlobWriter(contentType) { 272 | var blob, that = this; 273 | 274 | function init(callback) { 275 | blob = new Blob([], { 276 | type : contentType 277 | }); 278 | callback(); 279 | } 280 | 281 | function writeUint8Array(array, callback) { 282 | blob = new Blob([ blob, appendABViewSupported ? array : array.buffer ], { 283 | type : contentType 284 | }); 285 | callback(); 286 | } 287 | 288 | function getData(callback) { 289 | callback(blob); 290 | } 291 | 292 | that.init = init; 293 | that.writeUint8Array = writeUint8Array; 294 | that.getData = getData; 295 | } 296 | BlobWriter.prototype = new Writer(); 297 | BlobWriter.prototype.constructor = BlobWriter; 298 | 299 | /** 300 | * inflate/deflate core functions 301 | * @param worker {Worker} web worker for the task. 302 | * @param initialMessage {Object} initial message to be sent to the worker. should contain 303 | * sn(serial number for distinguishing multiple tasks sent to the worker), and codecClass. 304 | * This function may add more properties before sending. 305 | */ 306 | function launchWorkerProcess(worker, initialMessage, reader, writer, offset, size, onprogress, onend, onreaderror, onwriteerror) { 307 | var chunkIndex = 0, index, outputSize, sn = initialMessage.sn, crc; 308 | 309 | function onflush() { 310 | worker.removeEventListener('message', onmessage, false); 311 | onend(outputSize, crc); 312 | } 313 | 314 | function onmessage(event) { 315 | var message = event.data, data = message.data, err = message.error; 316 | if (err) { 317 | err.toString = function () { return 'Error: ' + this.message; }; 318 | onreaderror(err); 319 | return; 320 | } 321 | if (message.sn !== sn) 322 | return; 323 | if (typeof message.codecTime === 'number') 324 | worker.codecTime += message.codecTime; // should be before onflush() 325 | if (typeof message.crcTime === 'number') 326 | worker.crcTime += message.crcTime; 327 | 328 | switch (message.type) { 329 | case 'append': 330 | if (data) { 331 | outputSize += data.length; 332 | writer.writeUint8Array(data, function() { 333 | step(); 334 | }, onwriteerror); 335 | } else 336 | step(); 337 | break; 338 | case 'flush': 339 | crc = message.crc; 340 | if (data) { 341 | outputSize += data.length; 342 | writer.writeUint8Array(data, function() { 343 | onflush(); 344 | }, onwriteerror); 345 | } else 346 | onflush(); 347 | break; 348 | case 'progress': 349 | if (onprogress) 350 | onprogress(index + message.loaded, size); 351 | break; 352 | case 'importScripts': //no need to handle here 353 | case 'newTask': 354 | case 'echo': 355 | break; 356 | default: 357 | console.warn('zip.js:launchWorkerProcess: unknown message: ', message); 358 | } 359 | } 360 | 361 | function step() { 362 | index = chunkIndex * CHUNK_SIZE; 363 | // use `<=` instead of `<`, because `size` may be 0. 364 | if (index <= size) { 365 | reader.readUint8Array(offset + index, Math.min(CHUNK_SIZE, size - index), function(array) { 366 | if (onprogress) 367 | onprogress(index, size); 368 | var msg = index === 0 ? initialMessage : {sn : sn}; 369 | msg.type = 'append'; 370 | msg.data = array; 371 | 372 | // posting a message with transferables will fail on IE10 373 | try { 374 | worker.postMessage(msg, [array.buffer]); 375 | } catch(ex) { 376 | worker.postMessage(msg); // retry without transferables 377 | } 378 | chunkIndex++; 379 | }, onreaderror); 380 | } else { 381 | worker.postMessage({ 382 | sn: sn, 383 | type: 'flush' 384 | }); 385 | } 386 | } 387 | 388 | outputSize = 0; 389 | worker.addEventListener('message', onmessage, false); 390 | step(); 391 | } 392 | 393 | function launchProcess(process, reader, writer, offset, size, crcType, onprogress, onend, onreaderror, onwriteerror) { 394 | var chunkIndex = 0, index, outputSize = 0, 395 | crcInput = crcType === 'input', 396 | crcOutput = crcType === 'output', 397 | crc = new Crc32(); 398 | function step() { 399 | var outputData; 400 | index = chunkIndex * CHUNK_SIZE; 401 | if (index < size) 402 | reader.readUint8Array(offset + index, Math.min(CHUNK_SIZE, size - index), function(inputData) { 403 | var outputData; 404 | try { 405 | outputData = process.append(inputData, function(loaded) { 406 | if (onprogress) 407 | onprogress(index + loaded, size); 408 | }); 409 | } catch (e) { 410 | onreaderror(e); 411 | return; 412 | } 413 | if (outputData) { 414 | outputSize += outputData.length; 415 | writer.writeUint8Array(outputData, function() { 416 | chunkIndex++; 417 | setTimeout(step, 1); 418 | }, onwriteerror); 419 | if (crcOutput) 420 | crc.append(outputData); 421 | } else { 422 | chunkIndex++; 423 | setTimeout(step, 1); 424 | } 425 | if (crcInput) 426 | crc.append(inputData); 427 | if (onprogress) 428 | onprogress(index, size); 429 | }, onreaderror); 430 | else { 431 | try { 432 | outputData = process.flush(); 433 | } catch (e) { 434 | onreaderror(e); 435 | return; 436 | } 437 | if (outputData) { 438 | if (crcOutput) 439 | crc.append(outputData); 440 | outputSize += outputData.length; 441 | writer.writeUint8Array(outputData, function() { 442 | onend(outputSize, crc.get()); 443 | }, onwriteerror); 444 | } else 445 | onend(outputSize, crc.get()); 446 | } 447 | } 448 | 449 | step(); 450 | } 451 | 452 | function inflate(worker, sn, reader, writer, offset, size, computeCrc32, onend, onprogress, onreaderror, onwriteerror) { 453 | var crcType = computeCrc32 ? 'output' : 'none'; 454 | if (obj.zip.useWebWorkers) { 455 | var initialMessage = { 456 | sn: sn, 457 | codecClass: 'Inflater', 458 | crcType: crcType, 459 | }; 460 | launchWorkerProcess(worker, initialMessage, reader, writer, offset, size, onprogress, onend, onreaderror, onwriteerror); 461 | } else 462 | launchProcess(new obj.zip.Inflater(), reader, writer, offset, size, crcType, onprogress, onend, onreaderror, onwriteerror); 463 | } 464 | 465 | function deflate(worker, sn, reader, writer, level, onend, onprogress, onreaderror, onwriteerror) { 466 | var crcType = 'input'; 467 | if (obj.zip.useWebWorkers) { 468 | var initialMessage = { 469 | sn: sn, 470 | options: {level: level}, 471 | codecClass: 'Deflater', 472 | crcType: crcType, 473 | }; 474 | launchWorkerProcess(worker, initialMessage, reader, writer, 0, reader.size, onprogress, onend, onreaderror, onwriteerror); 475 | } else 476 | launchProcess(new obj.zip.Deflater(), reader, writer, 0, reader.size, crcType, onprogress, onend, onreaderror, onwriteerror); 477 | } 478 | 479 | function copy(worker, sn, reader, writer, offset, size, computeCrc32, onend, onprogress, onreaderror, onwriteerror) { 480 | var crcType = 'input'; 481 | if (obj.zip.useWebWorkers && computeCrc32) { 482 | var initialMessage = { 483 | sn: sn, 484 | codecClass: 'NOOP', 485 | crcType: crcType, 486 | }; 487 | launchWorkerProcess(worker, initialMessage, reader, writer, offset, size, onprogress, onend, onreaderror, onwriteerror); 488 | } else 489 | launchProcess(new NOOP(), reader, writer, offset, size, crcType, onprogress, onend, onreaderror, onwriteerror); 490 | } 491 | 492 | // ZipReader 493 | 494 | function decodeASCII(str) { 495 | var i, out = "", charCode, extendedASCII = [ '\u00C7', '\u00FC', '\u00E9', '\u00E2', '\u00E4', '\u00E0', '\u00E5', '\u00E7', '\u00EA', '\u00EB', 496 | '\u00E8', '\u00EF', '\u00EE', '\u00EC', '\u00C4', '\u00C5', '\u00C9', '\u00E6', '\u00C6', '\u00F4', '\u00F6', '\u00F2', '\u00FB', '\u00F9', 497 | '\u00FF', '\u00D6', '\u00DC', '\u00F8', '\u00A3', '\u00D8', '\u00D7', '\u0192', '\u00E1', '\u00ED', '\u00F3', '\u00FA', '\u00F1', '\u00D1', 498 | '\u00AA', '\u00BA', '\u00BF', '\u00AE', '\u00AC', '\u00BD', '\u00BC', '\u00A1', '\u00AB', '\u00BB', '_', '_', '_', '\u00A6', '\u00A6', 499 | '\u00C1', '\u00C2', '\u00C0', '\u00A9', '\u00A6', '\u00A6', '+', '+', '\u00A2', '\u00A5', '+', '+', '-', '-', '+', '-', '+', '\u00E3', 500 | '\u00C3', '+', '+', '-', '-', '\u00A6', '-', '+', '\u00A4', '\u00F0', '\u00D0', '\u00CA', '\u00CB', '\u00C8', 'i', '\u00CD', '\u00CE', 501 | '\u00CF', '+', '+', '_', '_', '\u00A6', '\u00CC', '_', '\u00D3', '\u00DF', '\u00D4', '\u00D2', '\u00F5', '\u00D5', '\u00B5', '\u00FE', 502 | '\u00DE', '\u00DA', '\u00DB', '\u00D9', '\u00FD', '\u00DD', '\u00AF', '\u00B4', '\u00AD', '\u00B1', '_', '\u00BE', '\u00B6', '\u00A7', 503 | '\u00F7', '\u00B8', '\u00B0', '\u00A8', '\u00B7', '\u00B9', '\u00B3', '\u00B2', '_', ' ' ]; 504 | for (i = 0; i < str.length; i++) { 505 | charCode = str.charCodeAt(i) & 0xFF; 506 | if (charCode > 127) 507 | out += extendedASCII[charCode - 128]; 508 | else 509 | out += String.fromCharCode(charCode); 510 | } 511 | return out; 512 | } 513 | 514 | function decodeUTF8(string) { 515 | return decodeURIComponent(escape(string)); 516 | } 517 | 518 | function getString(bytes) { 519 | var i, str = ""; 520 | for (i = 0; i < bytes.length; i++) 521 | str += String.fromCharCode(bytes[i]); 522 | return str; 523 | } 524 | 525 | function getDate(timeRaw) { 526 | var date = (timeRaw & 0xffff0000) >> 16, time = timeRaw & 0x0000ffff; 527 | try { 528 | return new Date(1980 + ((date & 0xFE00) >> 9), ((date & 0x01E0) >> 5) - 1, date & 0x001F, (time & 0xF800) >> 11, (time & 0x07E0) >> 5, 529 | (time & 0x001F) * 2, 0); 530 | } catch (e) { 531 | } 532 | } 533 | 534 | function readCommonHeader(entry, data, index, centralDirectory, onerror) { 535 | entry.version = data.view.getUint16(index, true); 536 | entry.bitFlag = data.view.getUint16(index + 2, true); 537 | entry.compressionMethod = data.view.getUint16(index + 4, true); 538 | entry.lastModDateRaw = data.view.getUint32(index + 6, true); 539 | entry.lastModDate = getDate(entry.lastModDateRaw); 540 | if ((entry.bitFlag & 0x01) === 0x01) { 541 | onerror(ERR_ENCRYPTED); 542 | return; 543 | } 544 | if (centralDirectory || (entry.bitFlag & 0x0008) != 0x0008) { 545 | entry.crc32 = data.view.getUint32(index + 10, true); 546 | entry.compressedSize = data.view.getUint32(index + 14, true); 547 | entry.uncompressedSize = data.view.getUint32(index + 18, true); 548 | } 549 | if (entry.compressedSize === 0xFFFFFFFF || entry.uncompressedSize === 0xFFFFFFFF) { 550 | onerror(ERR_ZIP64); 551 | return; 552 | } 553 | entry.filenameLength = data.view.getUint16(index + 22, true); 554 | entry.extraFieldLength = data.view.getUint16(index + 24, true); 555 | } 556 | 557 | function createZipReader(reader, callback, onerror) { 558 | var inflateSN = 0; 559 | 560 | function Entry() { 561 | } 562 | 563 | Entry.prototype.getData = function(writer, onend, onprogress, checkCrc32) { 564 | var that = this; 565 | 566 | function testCrc32(crc32) { 567 | var dataCrc32 = getDataHelper(4); 568 | dataCrc32.view.setUint32(0, crc32); 569 | return that.crc32 == dataCrc32.view.getUint32(0); 570 | } 571 | 572 | function getWriterData(uncompressedSize, crc32) { 573 | if (checkCrc32 && !testCrc32(crc32)) 574 | onerror(ERR_CRC); 575 | else 576 | writer.getData(function(data) { 577 | onend(data); 578 | }); 579 | } 580 | 581 | function onreaderror(err) { 582 | onerror(err || ERR_READ_DATA); 583 | } 584 | 585 | function onwriteerror(err) { 586 | onerror(err || ERR_WRITE_DATA); 587 | } 588 | 589 | reader.readUint8Array(that.offset, 30, function(bytes) { 590 | var data = getDataHelper(bytes.length, bytes), dataOffset; 591 | if (data.view.getUint32(0) != 0x504b0304) { 592 | onerror(ERR_BAD_FORMAT); 593 | return; 594 | } 595 | readCommonHeader(that, data, 4, false, onerror); 596 | dataOffset = that.offset + 30 + that.filenameLength + that.extraFieldLength; 597 | writer.init(function() { 598 | if (that.compressionMethod === 0) 599 | copy(that._worker, inflateSN++, reader, writer, dataOffset, that.compressedSize, checkCrc32, getWriterData, onprogress, onreaderror, onwriteerror); 600 | else 601 | inflate(that._worker, inflateSN++, reader, writer, dataOffset, that.compressedSize, checkCrc32, getWriterData, onprogress, onreaderror, onwriteerror); 602 | }, onwriteerror); 603 | }, onreaderror); 604 | }; 605 | 606 | function seekEOCDR(eocdrCallback) { 607 | // "End of central directory record" is the last part of a zip archive, and is at least 22 bytes long. 608 | // Zip file comment is the last part of EOCDR and has max length of 64KB, 609 | // so we only have to search the last 64K + 22 bytes of a archive for EOCDR signature (0x06054b50). 610 | var EOCDR_MIN = 22; 611 | if (reader.size < EOCDR_MIN) { 612 | onerror(ERR_BAD_FORMAT); 613 | return; 614 | } 615 | var ZIP_COMMENT_MAX = 256 * 256, EOCDR_MAX = EOCDR_MIN + ZIP_COMMENT_MAX; 616 | 617 | // In most cases, the EOCDR is EOCDR_MIN bytes long 618 | doSeek(EOCDR_MIN, function() { 619 | // If not found, try within EOCDR_MAX bytes 620 | doSeek(Math.min(EOCDR_MAX, reader.size), function() { 621 | onerror(ERR_BAD_FORMAT); 622 | }); 623 | }); 624 | 625 | // seek last length bytes of file for EOCDR 626 | function doSeek(length, eocdrNotFoundCallback) { 627 | reader.readUint8Array(reader.size - length, length, function(bytes) { 628 | for (var i = bytes.length - EOCDR_MIN; i >= 0; i--) { 629 | if (bytes[i] === 0x50 && bytes[i + 1] === 0x4b && bytes[i + 2] === 0x05 && bytes[i + 3] === 0x06) { 630 | eocdrCallback(new DataView(bytes.buffer, i, EOCDR_MIN)); 631 | return; 632 | } 633 | } 634 | eocdrNotFoundCallback(); 635 | }, function() { 636 | onerror(ERR_READ); 637 | }); 638 | } 639 | } 640 | 641 | var zipReader = { 642 | getEntries : function(callback) { 643 | var worker = this._worker; 644 | // look for End of central directory record 645 | seekEOCDR(function(dataView) { 646 | var datalength, fileslength; 647 | datalength = dataView.getUint32(16, true); 648 | fileslength = dataView.getUint16(8, true); 649 | if (datalength < 0 || datalength >= reader.size) { 650 | onerror(ERR_BAD_FORMAT); 651 | return; 652 | } 653 | reader.readUint8Array(datalength, reader.size - datalength, function(bytes) { 654 | var i, index = 0, entries = [], entry, filename, comment, data = getDataHelper(bytes.length, bytes); 655 | for (i = 0; i < fileslength; i++) { 656 | entry = new Entry(); 657 | entry._worker = worker; 658 | if (data.view.getUint32(index) != 0x504b0102) { 659 | onerror(ERR_BAD_FORMAT); 660 | return; 661 | } 662 | readCommonHeader(entry, data, index + 6, true, onerror); 663 | entry.commentLength = data.view.getUint16(index + 32, true); 664 | entry.directory = ((data.view.getUint8(index + 38) & 0x10) == 0x10); 665 | entry.offset = data.view.getUint32(index + 42, true); 666 | filename = getString(data.array.subarray(index + 46, index + 46 + entry.filenameLength)); 667 | entry.filename = ((entry.bitFlag & 0x0800) === 0x0800) ? decodeUTF8(filename) : decodeASCII(filename); 668 | if (!entry.directory && entry.filename.charAt(entry.filename.length - 1) == "/") 669 | entry.directory = true; 670 | comment = getString(data.array.subarray(index + 46 + entry.filenameLength + entry.extraFieldLength, index + 46 671 | + entry.filenameLength + entry.extraFieldLength + entry.commentLength)); 672 | entry.comment = ((entry.bitFlag & 0x0800) === 0x0800) ? decodeUTF8(comment) : decodeASCII(comment); 673 | entries.push(entry); 674 | index += 46 + entry.filenameLength + entry.extraFieldLength + entry.commentLength; 675 | } 676 | callback(entries); 677 | }, function() { 678 | onerror(ERR_READ); 679 | }); 680 | }); 681 | }, 682 | close : function(callback) { 683 | if (this._worker) { 684 | this._worker.terminate(); 685 | this._worker = null; 686 | } 687 | if (callback) 688 | callback(); 689 | }, 690 | _worker: null 691 | }; 692 | 693 | if (!obj.zip.useWebWorkers) 694 | callback(zipReader); 695 | else { 696 | createWorker('inflater', 697 | function(worker) { 698 | zipReader._worker = worker; 699 | callback(zipReader); 700 | }, 701 | function(err) { 702 | onerror(err); 703 | } 704 | ); 705 | } 706 | } 707 | 708 | // ZipWriter 709 | 710 | function encodeUTF8(string) { 711 | return unescape(encodeURIComponent(string)); 712 | } 713 | 714 | function getBytes(str) { 715 | var i, array = []; 716 | for (i = 0; i < str.length; i++) 717 | array.push(str.charCodeAt(i)); 718 | return array; 719 | } 720 | 721 | function createZipWriter(writer, callback, onerror, dontDeflate) { 722 | var files = {}, filenames = [], datalength = 0; 723 | var deflateSN = 0; 724 | 725 | function onwriteerror(err) { 726 | onerror(err || ERR_WRITE); 727 | } 728 | 729 | function onreaderror(err) { 730 | onerror(err || ERR_READ_DATA); 731 | } 732 | 733 | var zipWriter = { 734 | add : function(name, reader, onend, onprogress, options) { 735 | var header, filename, date; 736 | var worker = this._worker; 737 | 738 | function writeHeader(callback) { 739 | var data; 740 | date = options.lastModDate || new Date(); 741 | header = getDataHelper(26); 742 | files[name] = { 743 | headerArray : header.array, 744 | directory : options.directory, 745 | filename : filename, 746 | offset : datalength, 747 | comment : getBytes(encodeUTF8(options.comment || "")) 748 | }; 749 | header.view.setUint32(0, 0x14000808); 750 | if (options.version) 751 | header.view.setUint8(0, options.version); 752 | if (!dontDeflate && options.level !== 0 && !options.directory) 753 | header.view.setUint16(4, 0x0800); 754 | header.view.setUint16(6, (((date.getHours() << 6) | date.getMinutes()) << 5) | date.getSeconds() / 2, true); 755 | header.view.setUint16(8, ((((date.getFullYear() - 1980) << 4) | (date.getMonth() + 1)) << 5) | date.getDate(), true); 756 | header.view.setUint16(22, filename.length, true); 757 | data = getDataHelper(30 + filename.length); 758 | data.view.setUint32(0, 0x504b0304); 759 | data.array.set(header.array, 4); 760 | data.array.set(filename, 30); 761 | datalength += data.array.length; 762 | writer.writeUint8Array(data.array, callback, onwriteerror); 763 | } 764 | 765 | function writeFooter(compressedLength, crc32) { 766 | var footer = getDataHelper(16); 767 | datalength += compressedLength || 0; 768 | footer.view.setUint32(0, 0x504b0708); 769 | if (typeof crc32 != "undefined") { 770 | header.view.setUint32(10, crc32, true); 771 | footer.view.setUint32(4, crc32, true); 772 | } 773 | if (reader) { 774 | footer.view.setUint32(8, compressedLength, true); 775 | header.view.setUint32(14, compressedLength, true); 776 | footer.view.setUint32(12, reader.size, true); 777 | header.view.setUint32(18, reader.size, true); 778 | } 779 | writer.writeUint8Array(footer.array, function() { 780 | datalength += 16; 781 | onend(); 782 | }, onwriteerror); 783 | } 784 | 785 | function writeFile() { 786 | options = options || {}; 787 | name = name.trim(); 788 | if (options.directory && name.charAt(name.length - 1) != "/") 789 | name += "/"; 790 | if (files.hasOwnProperty(name)) { 791 | onerror(ERR_DUPLICATED_NAME); 792 | return; 793 | } 794 | filename = getBytes(encodeUTF8(name)); 795 | filenames.push(name); 796 | writeHeader(function() { 797 | if (reader) 798 | if (dontDeflate || options.level === 0) 799 | copy(worker, deflateSN++, reader, writer, 0, reader.size, true, writeFooter, onprogress, onreaderror, onwriteerror); 800 | else 801 | deflate(worker, deflateSN++, reader, writer, options.level, writeFooter, onprogress, onreaderror, onwriteerror); 802 | else 803 | writeFooter(); 804 | }, onwriteerror); 805 | } 806 | 807 | if (reader) 808 | reader.init(writeFile, onreaderror); 809 | else 810 | writeFile(); 811 | }, 812 | close : function(callback, comment) { 813 | if (this._worker) { 814 | this._worker.terminate(); 815 | this._worker = null; 816 | } 817 | 818 | var data, length = 0, index = 0, indexFilename, file; 819 | for (indexFilename = 0; indexFilename < filenames.length; indexFilename++) { 820 | file = files[filenames[indexFilename]]; 821 | length += 46 + file.filename.length + file.comment.length; 822 | } 823 | data = getDataHelper(length + 22 + comment.length); 824 | for (indexFilename = 0; indexFilename < filenames.length; indexFilename++) { 825 | file = files[filenames[indexFilename]]; 826 | data.view.setUint32(index, 0x504b0102); 827 | data.view.setUint16(index + 4, 0x1400); 828 | data.array.set(file.headerArray, index + 6); 829 | data.view.setUint16(index + 32, file.comment.length, true); 830 | if (file.directory) 831 | data.view.setUint8(index + 38, 0x10); 832 | data.view.setUint32(index + 42, file.offset, true); 833 | data.array.set(file.filename, index + 46); 834 | data.array.set(file.comment, index + 46 + file.filename.length); 835 | index += 46 + file.filename.length + file.comment.length; 836 | } 837 | data.view.setUint32(index, 0x504b0506); 838 | data.view.setUint16(index + 8, filenames.length, true); 839 | data.view.setUint16(index + 10, filenames.length, true); 840 | data.view.setUint32(index + 12, length, true); 841 | data.view.setUint32(index + 16, datalength, true); 842 | data.view.setUint16(index + 20, comment.length, true); 843 | 844 | //ZIP comments (not file comments!) are at the end of the file 845 | for (var i = 0; i < comment.length ; i++) 846 | { 847 | data.view.setUint8(index + i + 22, comment.charCodeAt(i)); 848 | } 849 | 850 | writer.writeUint8Array(data.array, function() { 851 | writer.getData(callback); 852 | }, onwriteerror); 853 | }, 854 | _worker: null 855 | }; 856 | 857 | if (!obj.zip.useWebWorkers) 858 | callback(zipWriter); 859 | else { 860 | createWorker('deflater', 861 | function(worker) { 862 | zipWriter._worker = worker; 863 | callback(zipWriter); 864 | }, 865 | function(err) { 866 | onerror(err); 867 | } 868 | ); 869 | } 870 | } 871 | 872 | function resolveURLs(urls) { 873 | var a = document.createElement('a'); 874 | return urls.map(function(url) { 875 | a.href = url; 876 | return a.href; 877 | }); 878 | } 879 | 880 | var DEFAULT_WORKER_SCRIPTS = { 881 | deflater: ['z-worker.js', 'deflate.js'], 882 | inflater: ['z-worker.js', 'inflate.js'] 883 | }; 884 | function createWorker(type, callback, onerror) { 885 | if (obj.zip.workerScripts !== null && obj.zip.workerScriptsPath !== null) { 886 | onerror(new Error('Either zip.workerScripts or zip.workerScriptsPath may be set, not both.')); 887 | return; 888 | } 889 | var scripts; 890 | if (obj.zip.workerScripts) { 891 | scripts = obj.zip.workerScripts[type]; 892 | if (!Array.isArray(scripts)) { 893 | onerror(new Error('zip.workerScripts.' + type + ' is not an array!')); 894 | return; 895 | } 896 | scripts = resolveURLs(scripts); 897 | } else { 898 | scripts = DEFAULT_WORKER_SCRIPTS[type].slice(0); 899 | scripts[0] = (obj.zip.workerScriptsPath || '') + scripts[0]; 900 | } 901 | var worker = new Worker(scripts[0]); 902 | // record total consumed time by inflater/deflater/crc32 in this worker 903 | worker.codecTime = worker.crcTime = 0; 904 | worker.postMessage({ type: 'importScripts', scripts: scripts.slice(1) }); 905 | worker.addEventListener('message', onmessage); 906 | function onmessage(ev) { 907 | var msg = ev.data; 908 | if (msg.error) { 909 | worker.terminate(); // should before onerror(), because onerror() may throw. 910 | onerror(msg.error); 911 | return; 912 | } 913 | if (msg.type === 'importScripts') { 914 | worker.removeEventListener('message', onmessage); 915 | worker.removeEventListener('error', errorHandler); 916 | callback(worker); 917 | } 918 | } 919 | // catch entry script loading error and other unhandled errors 920 | worker.addEventListener('error', errorHandler); 921 | function errorHandler(err) { 922 | worker.terminate(); 923 | onerror(err); 924 | } 925 | } 926 | 927 | function onerror_default(error) { 928 | console.error(error); 929 | } 930 | obj.zip = { 931 | Reader : Reader, 932 | Writer : Writer, 933 | BlobReader : BlobReader, 934 | Data64URIReader : Data64URIReader, 935 | TextReader : TextReader, 936 | BlobWriter : BlobWriter, 937 | Data64URIWriter : Data64URIWriter, 938 | TextWriter : TextWriter, 939 | createReader : function(reader, callback, onerror) { 940 | onerror = onerror || onerror_default; 941 | 942 | reader.init(function() { 943 | createZipReader(reader, callback, onerror); 944 | }, onerror); 945 | }, 946 | createWriter : function(writer, callback, onerror, dontDeflate) { 947 | onerror = onerror || onerror_default; 948 | dontDeflate = !!dontDeflate; 949 | 950 | writer.init(function() { 951 | createZipWriter(writer, callback, onerror, dontDeflate); 952 | }, onerror); 953 | }, 954 | useWebWorkers : true, 955 | /** 956 | * Directory containing the default worker scripts (z-worker.js, deflate.js, and inflate.js), relative to current base url. 957 | * E.g.: zip.workerScripts = './'; 958 | */ 959 | workerScriptsPath : null, 960 | /** 961 | * Advanced option to control which scripts are loaded in the Web worker. If this option is specified, then workerScriptsPath must not be set. 962 | * workerScripts.deflater/workerScripts.inflater should be arrays of urls to scripts for deflater/inflater, respectively. 963 | * Scripts in the array are executed in order, and the first one should be z-worker.js, which is used to start the worker. 964 | * All urls are relative to current base url. 965 | * E.g.: 966 | * zip.workerScripts = { 967 | * deflater: ['z-worker.js', 'deflate.js'], 968 | * inflater: ['z-worker.js', 'inflate.js'] 969 | * }; 970 | */ 971 | workerScripts : null, 972 | }; 973 | 974 | })(this); 975 | -------------------------------------------------------------------------------- /version: -------------------------------------------------------------------------------- 1 | 123 2 | --------------------------------------------------------------------------------