├── .env.example ├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── database.json.example ├── db.js ├── docker-compose.yml ├── init.js ├── migrations ├── 20210328182509-initial.js ├── 20210328183552-remove-hash-columns.js ├── 20210328185725-add-images-column.js ├── 20210329110833-change-search-index.js ├── 20210329172239-create-accounts-table.js ├── 20210329183119-create-uploader-column.js ├── 20210330124837-add-chapter-column.js ├── 20210401181359-add-added-column-to-uploads.js ├── 20210404221702-add-volume-column-to-uploads.js ├── 20210404224951-change-volume-and-chapter-to-text.js └── sqls │ ├── 20210328182509-initial-down.sql │ ├── 20210328182509-initial-up.sql │ ├── 20210328183552-remove-hash-columns-down.sql │ ├── 20210328183552-remove-hash-columns-up.sql │ ├── 20210328185725-add-images-column-down.sql │ ├── 20210328185725-add-images-column-up.sql │ ├── 20210329110833-change-search-index-down.sql │ ├── 20210329110833-change-search-index-up.sql │ ├── 20210329172239-create-accounts-table-down.sql │ ├── 20210329172239-create-accounts-table-up.sql │ ├── 20210329183119-create-uploader-column-down.sql │ ├── 20210329183119-create-uploader-column-up.sql │ ├── 20210330124837-add-chapter-column-down.sql │ ├── 20210330124837-add-chapter-column-up.sql │ ├── 20210401181359-add-added-column-to-uploads-down.sql │ ├── 20210401181359-add-added-column-to-uploads-up.sql │ ├── 20210404221702-add-volume-column-to-uploads-down.sql │ ├── 20210404221702-add-volume-column-to-uploads-up.sql │ ├── 20210404224951-change-volume-and-chapter-to-text-down.sql │ └── 20210404224951-change-volume-and-chapter-to-text-up.sql ├── package.json ├── public ├── css │ ├── awesomplete.css │ └── index.css └── js │ ├── awesomplete.min.js │ ├── reader.js │ ├── resumable.js │ └── upload.js ├── resumable.js ├── server.js ├── testing-scripts ├── populate-manga.js └── populate-uploads.js ├── views ├── components │ ├── header.js │ └── shell.js ├── create.js ├── home.js ├── login.js ├── manga.js ├── reader.js ├── register.js ├── upload.js └── user.js └── yarn.lock /.env.example: -------------------------------------------------------------------------------- 1 | SECRET=lolololol 2 | ### Only change values below if you're running without Docker. ### 3 | # FILES_ROOT= 4 | # DB_HOST=localhost 5 | # DB_USER=yuuko 6 | # DB_PASSWORD=mio 7 | # DB_DATABASE=ramune -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | 9 | # Diagnostic reports (https://nodejs.org/api/report.html) 10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 11 | 12 | # Runtime data 13 | pids 14 | *.pid 15 | *.seed 16 | *.pid.lock 17 | 18 | # Directory for instrumented libs generated by jscoverage/JSCover 19 | lib-cov 20 | 21 | # Coverage directory used by tools like istanbul 22 | coverage 23 | *.lcov 24 | 25 | # nyc test coverage 26 | .nyc_output 27 | 28 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 29 | .grunt 30 | 31 | # Bower dependency directory (https://bower.io/) 32 | bower_components 33 | 34 | # node-waf configuration 35 | .lock-wscript 36 | 37 | # Compiled binary addons (https://nodejs.org/api/addons.html) 38 | build/Release 39 | 40 | # Dependency directories 41 | node_modules/ 42 | jspm_packages/ 43 | 44 | # Snowpack dependency directory (https://snowpack.dev/) 45 | web_modules/ 46 | 47 | # TypeScript cache 48 | *.tsbuildinfo 49 | 50 | # Optional npm cache directory 51 | .npm 52 | 53 | # Optional eslint cache 54 | .eslintcache 55 | 56 | # Microbundle cache 57 | .rpt2_cache/ 58 | .rts2_cache_cjs/ 59 | .rts2_cache_es/ 60 | .rts2_cache_umd/ 61 | 62 | # Optional REPL history 63 | .node_repl_history 64 | 65 | # Output of 'npm pack' 66 | *.tgz 67 | 68 | # Yarn Integrity file 69 | .yarn-integrity 70 | 71 | # dotenv environment variables file 72 | .env 73 | .env.test 74 | 75 | # parcel-bundler cache (https://parceljs.org/) 76 | .cache 77 | .parcel-cache 78 | 79 | # Next.js build output 80 | .next 81 | out 82 | 83 | # Nuxt.js build / generate output 84 | .nuxt 85 | dist 86 | 87 | # Gatsby files 88 | .cache/ 89 | # Comment in the public line in if your project uses Gatsby and not Next.js 90 | # https://nextjs.org/blog/next-9-1#public-directory-support 91 | # public 92 | 93 | # vuepress build output 94 | .vuepress/dist 95 | 96 | # Serverless directories 97 | .serverless/ 98 | 99 | # FuseBox cache 100 | .fusebox/ 101 | 102 | # DynamoDB Local files 103 | .dynamodb/ 104 | 105 | # TernJS port file 106 | .tern-port 107 | 108 | # Stores VSCode versions used for testing VSCode extensions 109 | .vscode-test 110 | 111 | # yarn v2 112 | .yarn/cache 113 | .yarn/unplugged 114 | .yarn/build-state.yml 115 | .yarn/install-state.gz 116 | .pnp.* 117 | 118 | # Ramune 119 | assets/ 120 | tmp/ 121 | database.json -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:12.18 2 | WORKDIR /app 3 | COPY . /app 4 | RUN apt-get update && apt-get install -y python3 git build-essential curl && yarn 5 | EXPOSE 8000 6 | ENV FILES_ROOT=/storage 7 | VOLUME [ "/storage" ] 8 | CMD ["yarn", "start"] -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 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 Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | A (WIP) manga CMS developed by /a/ and /g/ as an alternative/successor to MangaDex. 2 | 3 | ### Running 4 | Requires Postgres, Yarn, and Node.js. Docker setup coming soon. 5 | 6 | ```sh 7 | yarn 8 | yarn global add db-migrate 9 | cp .env.example .env # then open .env and configure 10 | cp database.json.example database.json # then open database.json and configure 11 | db-migrate up 12 | # you might want to run the scripts in "testing-scripts" here to populate the database 13 | yarn run dev 14 | ``` 15 | 16 | ### To-do before public release 17 | This is MVP stuff; more features will be considered and implemented latter. 18 | 19 | - [x] Uploading 20 | - [x] Downloading 21 | - [x] Manga search 22 | - [ ] Columns for volumes (instead of just chapters) 23 | - [ ] Groups 24 | - [x] Switch to Font Awesome -------------------------------------------------------------------------------- /database.json.example: -------------------------------------------------------------------------------- 1 | { 2 | "dev": { 3 | "driver": "pg", 4 | "host": "localhost", 5 | "user": "yuuko", 6 | "password": "mio", 7 | "database": "ramune" 8 | } 9 | } -------------------------------------------------------------------------------- /db.js: -------------------------------------------------------------------------------- 1 | const { Pool } = require('pg') 2 | module.exports = { 3 | db: new Pool({ 4 | host: process.env.DB_HOST, 5 | user: process.env.DB_USER, 6 | password: process.env.DB_PASSWORD, 7 | database: process.env.DB_DATABASE, 8 | max: 100 9 | }) 10 | } -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '2.3' 2 | services: 3 | ramune-db: 4 | image: healthcheck/postgres 5 | container_name: ramune-db 6 | restart: unless-stopped 7 | environment: 8 | - POSTGRES_USER=nano 9 | - POSTGRES_PASSWORD=shinonome 10 | - POSTGRES_DB=ramunedb 11 | volumes: 12 | - db-data:/var/lib/postgresql/data/ 13 | ramune: 14 | build: . 15 | container_name: ramune 16 | restart: unless-stopped 17 | depends_on: 18 | ramune-db: 19 | condition: service_healthy 20 | ports: 21 | - 127.0.0.1:9000:9000 22 | env_file: 23 | - .env 24 | environment: 25 | - DB_USER=nano 26 | - DB_PASSWORD=shinonome 27 | - DB_DATABASE=ramunedb 28 | - DB_HOST=ramune-db 29 | volumes: 30 | - data:/storage 31 | healthcheck: 32 | test: ["CMD", "curl", "-f", "http://localhost:9000"] 33 | interval: 1m 34 | timeout: 2m 35 | retries: 3 36 | start_period: 30s 37 | ramune-update: 38 | image: containrrr/watchtower 39 | container_name: ramune-update 40 | command: ramune 41 | environment: 42 | - WATCHTOWER_CLEANUP=true 43 | - WATCHTOWER_POLL_INTERVAL=30 44 | restart: unless-stopped 45 | volumes: 46 | - /var/run/docker.sock:/var/run/docker.sock 47 | autoheal: 48 | restart: always 49 | container_name: ramune-autoheal 50 | image: willfarrell/autoheal 51 | environment: 52 | - AUTOHEAL_CONTAINER_LABEL=all 53 | volumes: 54 | - /var/run/docker.sock:/var/run/docker.sock 55 | volumes: 56 | # If you need to store your volumes manually, uncomment the "driver_opts" lines and specify your "device" location. 57 | db-data: 58 | driver: local 59 | # driver_opts: 60 | # type: 'none' 61 | # o: 'bind' 62 | # device: "/mnt/hdd/ramune-db" 63 | data: 64 | driver: local 65 | # driver_opts: 66 | # type: 'none' 67 | # o: 'bind' 68 | # device: "/mnt/hdd/ramune" -------------------------------------------------------------------------------- /init.js: -------------------------------------------------------------------------------- 1 | require('dotenv').config() 2 | const migrations = require('db-migrate'); 3 | (async () => { 4 | const _migrations = migrations.getInstance(true, { 5 | config: { 6 | dev: { 7 | driver: 'pg', 8 | host: process.env.DB_HOST, 9 | user: process.env.DB_USER, 10 | password: process.env.DB_PASSWORD, 11 | database: process.env.DB_DATABASE, 12 | } 13 | } 14 | }) 15 | 16 | await _migrations.up(); 17 | })() -------------------------------------------------------------------------------- /migrations/20210328182509-initial.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var dbm; 4 | var type; 5 | var seed; 6 | var fs = require('fs'); 7 | var path = require('path'); 8 | var Promise; 9 | 10 | /** 11 | * We receive the dbmigrate dependency from dbmigrate initially. 12 | * This enables us to not have to rely on NODE_PATH. 13 | */ 14 | exports.setup = function(options, seedLink) { 15 | dbm = options.dbmigrate; 16 | type = dbm.dataType; 17 | seed = seedLink; 18 | Promise = options.Promise; 19 | }; 20 | 21 | exports.up = function(db) { 22 | var filePath = path.join(__dirname, 'sqls', '20210328182509-initial-up.sql'); 23 | return new Promise( function( resolve, reject ) { 24 | fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){ 25 | if (err) return reject(err); 26 | console.log('received data: ' + data); 27 | 28 | resolve(data); 29 | }); 30 | }) 31 | .then(function(data) { 32 | return db.runSql(data); 33 | }); 34 | }; 35 | 36 | exports.down = function(db) { 37 | var filePath = path.join(__dirname, 'sqls', '20210328182509-initial-down.sql'); 38 | return new Promise( function( resolve, reject ) { 39 | fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){ 40 | if (err) return reject(err); 41 | console.log('received data: ' + data); 42 | 43 | resolve(data); 44 | }); 45 | }) 46 | .then(function(data) { 47 | return db.runSql(data); 48 | }); 49 | }; 50 | 51 | exports._meta = { 52 | "version": 1 53 | }; 54 | -------------------------------------------------------------------------------- /migrations/20210328183552-remove-hash-columns.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var dbm; 4 | var type; 5 | var seed; 6 | var fs = require('fs'); 7 | var path = require('path'); 8 | var Promise; 9 | 10 | /** 11 | * We receive the dbmigrate dependency from dbmigrate initially. 12 | * This enables us to not have to rely on NODE_PATH. 13 | */ 14 | exports.setup = function(options, seedLink) { 15 | dbm = options.dbmigrate; 16 | type = dbm.dataType; 17 | seed = seedLink; 18 | Promise = options.Promise; 19 | }; 20 | 21 | exports.up = function(db) { 22 | var filePath = path.join(__dirname, 'sqls', '20210328183552-remove-hash-columns-up.sql'); 23 | return new Promise( function( resolve, reject ) { 24 | fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){ 25 | if (err) return reject(err); 26 | console.log('received data: ' + data); 27 | 28 | resolve(data); 29 | }); 30 | }) 31 | .then(function(data) { 32 | return db.runSql(data); 33 | }); 34 | }; 35 | 36 | exports.down = function(db) { 37 | var filePath = path.join(__dirname, 'sqls', '20210328183552-remove-hash-columns-down.sql'); 38 | return new Promise( function( resolve, reject ) { 39 | fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){ 40 | if (err) return reject(err); 41 | console.log('received data: ' + data); 42 | 43 | resolve(data); 44 | }); 45 | }) 46 | .then(function(data) { 47 | return db.runSql(data); 48 | }); 49 | }; 50 | 51 | exports._meta = { 52 | "version": 1 53 | }; 54 | -------------------------------------------------------------------------------- /migrations/20210328185725-add-images-column.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var dbm; 4 | var type; 5 | var seed; 6 | var fs = require('fs'); 7 | var path = require('path'); 8 | var Promise; 9 | 10 | /** 11 | * We receive the dbmigrate dependency from dbmigrate initially. 12 | * This enables us to not have to rely on NODE_PATH. 13 | */ 14 | exports.setup = function(options, seedLink) { 15 | dbm = options.dbmigrate; 16 | type = dbm.dataType; 17 | seed = seedLink; 18 | Promise = options.Promise; 19 | }; 20 | 21 | exports.up = function(db) { 22 | var filePath = path.join(__dirname, 'sqls', '20210328185725-add-images-column-up.sql'); 23 | return new Promise( function( resolve, reject ) { 24 | fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){ 25 | if (err) return reject(err); 26 | console.log('received data: ' + data); 27 | 28 | resolve(data); 29 | }); 30 | }) 31 | .then(function(data) { 32 | return db.runSql(data); 33 | }); 34 | }; 35 | 36 | exports.down = function(db) { 37 | var filePath = path.join(__dirname, 'sqls', '20210328185725-add-images-column-down.sql'); 38 | return new Promise( function( resolve, reject ) { 39 | fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){ 40 | if (err) return reject(err); 41 | console.log('received data: ' + data); 42 | 43 | resolve(data); 44 | }); 45 | }) 46 | .then(function(data) { 47 | return db.runSql(data); 48 | }); 49 | }; 50 | 51 | exports._meta = { 52 | "version": 1 53 | }; 54 | -------------------------------------------------------------------------------- /migrations/20210329110833-change-search-index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var dbm; 4 | var type; 5 | var seed; 6 | var fs = require('fs'); 7 | var path = require('path'); 8 | var Promise; 9 | 10 | /** 11 | * We receive the dbmigrate dependency from dbmigrate initially. 12 | * This enables us to not have to rely on NODE_PATH. 13 | */ 14 | exports.setup = function(options, seedLink) { 15 | dbm = options.dbmigrate; 16 | type = dbm.dataType; 17 | seed = seedLink; 18 | Promise = options.Promise; 19 | }; 20 | 21 | exports.up = function(db) { 22 | var filePath = path.join(__dirname, 'sqls', '20210329110833-change-search-index-up.sql'); 23 | return new Promise( function( resolve, reject ) { 24 | fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){ 25 | if (err) return reject(err); 26 | console.log('received data: ' + data); 27 | 28 | resolve(data); 29 | }); 30 | }) 31 | .then(function(data) { 32 | return db.runSql(data); 33 | }); 34 | }; 35 | 36 | exports.down = function(db) { 37 | var filePath = path.join(__dirname, 'sqls', '20210329110833-change-search-index-down.sql'); 38 | return new Promise( function( resolve, reject ) { 39 | fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){ 40 | if (err) return reject(err); 41 | console.log('received data: ' + data); 42 | 43 | resolve(data); 44 | }); 45 | }) 46 | .then(function(data) { 47 | return db.runSql(data); 48 | }); 49 | }; 50 | 51 | exports._meta = { 52 | "version": 1 53 | }; 54 | -------------------------------------------------------------------------------- /migrations/20210329172239-create-accounts-table.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var dbm; 4 | var type; 5 | var seed; 6 | var fs = require('fs'); 7 | var path = require('path'); 8 | var Promise; 9 | 10 | /** 11 | * We receive the dbmigrate dependency from dbmigrate initially. 12 | * This enables us to not have to rely on NODE_PATH. 13 | */ 14 | exports.setup = function(options, seedLink) { 15 | dbm = options.dbmigrate; 16 | type = dbm.dataType; 17 | seed = seedLink; 18 | Promise = options.Promise; 19 | }; 20 | 21 | exports.up = function(db) { 22 | var filePath = path.join(__dirname, 'sqls', '20210329172239-create-accounts-table-up.sql'); 23 | return new Promise( function( resolve, reject ) { 24 | fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){ 25 | if (err) return reject(err); 26 | console.log('received data: ' + data); 27 | 28 | resolve(data); 29 | }); 30 | }) 31 | .then(function(data) { 32 | return db.runSql(data); 33 | }); 34 | }; 35 | 36 | exports.down = function(db) { 37 | var filePath = path.join(__dirname, 'sqls', '20210329172239-create-accounts-table-down.sql'); 38 | return new Promise( function( resolve, reject ) { 39 | fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){ 40 | if (err) return reject(err); 41 | console.log('received data: ' + data); 42 | 43 | resolve(data); 44 | }); 45 | }) 46 | .then(function(data) { 47 | return db.runSql(data); 48 | }); 49 | }; 50 | 51 | exports._meta = { 52 | "version": 1 53 | }; 54 | -------------------------------------------------------------------------------- /migrations/20210329183119-create-uploader-column.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var dbm; 4 | var type; 5 | var seed; 6 | var fs = require('fs'); 7 | var path = require('path'); 8 | var Promise; 9 | 10 | /** 11 | * We receive the dbmigrate dependency from dbmigrate initially. 12 | * This enables us to not have to rely on NODE_PATH. 13 | */ 14 | exports.setup = function(options, seedLink) { 15 | dbm = options.dbmigrate; 16 | type = dbm.dataType; 17 | seed = seedLink; 18 | Promise = options.Promise; 19 | }; 20 | 21 | exports.up = function(db) { 22 | var filePath = path.join(__dirname, 'sqls', '20210329183119-create-uploader-column-up.sql'); 23 | return new Promise( function( resolve, reject ) { 24 | fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){ 25 | if (err) return reject(err); 26 | console.log('received data: ' + data); 27 | 28 | resolve(data); 29 | }); 30 | }) 31 | .then(function(data) { 32 | return db.runSql(data); 33 | }); 34 | }; 35 | 36 | exports.down = function(db) { 37 | var filePath = path.join(__dirname, 'sqls', '20210329183119-create-uploader-column-down.sql'); 38 | return new Promise( function( resolve, reject ) { 39 | fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){ 40 | if (err) return reject(err); 41 | console.log('received data: ' + data); 42 | 43 | resolve(data); 44 | }); 45 | }) 46 | .then(function(data) { 47 | return db.runSql(data); 48 | }); 49 | }; 50 | 51 | exports._meta = { 52 | "version": 1 53 | }; 54 | -------------------------------------------------------------------------------- /migrations/20210330124837-add-chapter-column.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var dbm; 4 | var type; 5 | var seed; 6 | var fs = require('fs'); 7 | var path = require('path'); 8 | var Promise; 9 | 10 | /** 11 | * We receive the dbmigrate dependency from dbmigrate initially. 12 | * This enables us to not have to rely on NODE_PATH. 13 | */ 14 | exports.setup = function(options, seedLink) { 15 | dbm = options.dbmigrate; 16 | type = dbm.dataType; 17 | seed = seedLink; 18 | Promise = options.Promise; 19 | }; 20 | 21 | exports.up = function(db) { 22 | var filePath = path.join(__dirname, 'sqls', '20210330124837-add-chapter-column-up.sql'); 23 | return new Promise( function( resolve, reject ) { 24 | fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){ 25 | if (err) return reject(err); 26 | console.log('received data: ' + data); 27 | 28 | resolve(data); 29 | }); 30 | }) 31 | .then(function(data) { 32 | return db.runSql(data); 33 | }); 34 | }; 35 | 36 | exports.down = function(db) { 37 | var filePath = path.join(__dirname, 'sqls', '20210330124837-add-chapter-column-down.sql'); 38 | return new Promise( function( resolve, reject ) { 39 | fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){ 40 | if (err) return reject(err); 41 | console.log('received data: ' + data); 42 | 43 | resolve(data); 44 | }); 45 | }) 46 | .then(function(data) { 47 | return db.runSql(data); 48 | }); 49 | }; 50 | 51 | exports._meta = { 52 | "version": 1 53 | }; 54 | -------------------------------------------------------------------------------- /migrations/20210401181359-add-added-column-to-uploads.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var dbm; 4 | var type; 5 | var seed; 6 | var fs = require('fs'); 7 | var path = require('path'); 8 | var Promise; 9 | 10 | /** 11 | * We receive the dbmigrate dependency from dbmigrate initially. 12 | * This enables us to not have to rely on NODE_PATH. 13 | */ 14 | exports.setup = function(options, seedLink) { 15 | dbm = options.dbmigrate; 16 | type = dbm.dataType; 17 | seed = seedLink; 18 | Promise = options.Promise; 19 | }; 20 | 21 | exports.up = function(db) { 22 | var filePath = path.join(__dirname, 'sqls', '20210401181359-add-added-column-to-uploads-up.sql'); 23 | return new Promise( function( resolve, reject ) { 24 | fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){ 25 | if (err) return reject(err); 26 | console.log('received data: ' + data); 27 | 28 | resolve(data); 29 | }); 30 | }) 31 | .then(function(data) { 32 | return db.runSql(data); 33 | }); 34 | }; 35 | 36 | exports.down = function(db) { 37 | var filePath = path.join(__dirname, 'sqls', '20210401181359-add-added-column-to-uploads-down.sql'); 38 | return new Promise( function( resolve, reject ) { 39 | fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){ 40 | if (err) return reject(err); 41 | console.log('received data: ' + data); 42 | 43 | resolve(data); 44 | }); 45 | }) 46 | .then(function(data) { 47 | return db.runSql(data); 48 | }); 49 | }; 50 | 51 | exports._meta = { 52 | "version": 1 53 | }; 54 | -------------------------------------------------------------------------------- /migrations/20210404221702-add-volume-column-to-uploads.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var dbm; 4 | var type; 5 | var seed; 6 | var fs = require('fs'); 7 | var path = require('path'); 8 | var Promise; 9 | 10 | /** 11 | * We receive the dbmigrate dependency from dbmigrate initially. 12 | * This enables us to not have to rely on NODE_PATH. 13 | */ 14 | exports.setup = function(options, seedLink) { 15 | dbm = options.dbmigrate; 16 | type = dbm.dataType; 17 | seed = seedLink; 18 | Promise = options.Promise; 19 | }; 20 | 21 | exports.up = function(db) { 22 | var filePath = path.join(__dirname, 'sqls', '20210404221702-add-volume-column-to-uploads-up.sql'); 23 | return new Promise( function( resolve, reject ) { 24 | fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){ 25 | if (err) return reject(err); 26 | console.log('received data: ' + data); 27 | 28 | resolve(data); 29 | }); 30 | }) 31 | .then(function(data) { 32 | return db.runSql(data); 33 | }); 34 | }; 35 | 36 | exports.down = function(db) { 37 | var filePath = path.join(__dirname, 'sqls', '20210404221702-add-volume-column-to-uploads-down.sql'); 38 | return new Promise( function( resolve, reject ) { 39 | fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){ 40 | if (err) return reject(err); 41 | console.log('received data: ' + data); 42 | 43 | resolve(data); 44 | }); 45 | }) 46 | .then(function(data) { 47 | return db.runSql(data); 48 | }); 49 | }; 50 | 51 | exports._meta = { 52 | "version": 1 53 | }; 54 | -------------------------------------------------------------------------------- /migrations/20210404224951-change-volume-and-chapter-to-text.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var dbm; 4 | var type; 5 | var seed; 6 | var fs = require('fs'); 7 | var path = require('path'); 8 | var Promise; 9 | 10 | /** 11 | * We receive the dbmigrate dependency from dbmigrate initially. 12 | * This enables us to not have to rely on NODE_PATH. 13 | */ 14 | exports.setup = function(options, seedLink) { 15 | dbm = options.dbmigrate; 16 | type = dbm.dataType; 17 | seed = seedLink; 18 | Promise = options.Promise; 19 | }; 20 | 21 | exports.up = function(db) { 22 | var filePath = path.join(__dirname, 'sqls', '20210404224951-change-volume-and-chapter-to-text-up.sql'); 23 | return new Promise( function( resolve, reject ) { 24 | fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){ 25 | if (err) return reject(err); 26 | console.log('received data: ' + data); 27 | 28 | resolve(data); 29 | }); 30 | }) 31 | .then(function(data) { 32 | return db.runSql(data); 33 | }); 34 | }; 35 | 36 | exports.down = function(db) { 37 | var filePath = path.join(__dirname, 'sqls', '20210404224951-change-volume-and-chapter-to-text-down.sql'); 38 | return new Promise( function( resolve, reject ) { 39 | fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){ 40 | if (err) return reject(err); 41 | console.log('received data: ' + data); 42 | 43 | resolve(data); 44 | }); 45 | }) 46 | .then(function(data) { 47 | return db.runSql(data); 48 | }); 49 | }; 50 | 51 | exports._meta = { 52 | "version": 1 53 | }; 54 | -------------------------------------------------------------------------------- /migrations/sqls/20210328182509-initial-down.sql: -------------------------------------------------------------------------------- 1 | DROP TABLE manga; 2 | DROP INDEX IF EXISTS search_idx; 3 | DROP INDEX IF EXISTS romaji_title_idx; 4 | DROP INDEX IF EXISTS japanese_title; 5 | DROP INDEX IF EXISTS author_idx; 6 | DROP INDEX IF EXISTS artist_idx; 7 | 8 | DROP TABLE chapters; 9 | DROP INDEX IF EXISTS manga_id_idx; 10 | 11 | DROP TABLE uploads; 12 | DROP INDEX IF EXISTS chapter_id_idx; 13 | DROP INDEX IF EXISTS original_hash_idx; -------------------------------------------------------------------------------- /migrations/sqls/20210328182509-initial-up.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE IF NOT EXISTS manga ( 2 | "id" SERIAL PRIMARY KEY, 3 | "eng_title" text NOT NULL, 4 | "romaji_title" text, 5 | "japanese_title" text, 6 | "author" text, 7 | "artist" text, 8 | "description" text NOT NULL DEFAULT '', 9 | "cover" text NOT NULL, 10 | "added" timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, 11 | "views" integer NOT NULL DEFAULT 0 12 | ); 13 | CREATE INDEX IF NOT EXISTS search_idx ON manga USING GIN (to_tsvector('english', eng_title)); 14 | CREATE INDEX IF NOT EXISTS eng_title_idx ON manga USING btree ("eng_title"); 15 | CREATE INDEX IF NOT EXISTS romaji_title_idx ON manga USING btree ("romaji_title"); 16 | CREATE INDEX IF NOT EXISTS japanese_title_idx ON manga USING btree ("japanese_title"); 17 | CREATE INDEX IF NOT EXISTS author_idx ON manga USING btree ("author"); 18 | CREATE INDEX IF NOT EXISTS artist_idx ON manga USING btree ("artist"); 19 | 20 | CREATE TABLE IF NOT EXISTS chapters ( 21 | "id" SERIAL PRIMARY KEY, 22 | "manga_id" integer NOT NULL, 23 | "identifier" integer NOT NULL, 24 | "title" text 25 | ); 26 | CREATE INDEX IF NOT EXISTS manga_id_idx ON chapters USING btree ("manga_id"); 27 | 28 | CREATE TABLE IF NOT EXISTS uploads ( 29 | "id" SERIAL PRIMARY KEY, 30 | "chapter_id" integer NOT NULL, 31 | "source" text, 32 | "group" integer, 33 | -- "uploader" integer NOT NULL, 34 | "rating" integer NOT NULL DEFAULT 0, 35 | "rating_count" integer NOT NULL DEFAULT 0, 36 | "original_hash" text NOT NULL, 37 | "repacked_hash" text NOT NULL, 38 | "resized_hash" text NOT NULL 39 | ); 40 | CREATE INDEX IF NOT EXISTS chapter_id_idx ON uploads USING btree ("chapter_id"); 41 | CREATE INDEX IF NOT EXISTS original_hash_idx ON uploads USING btree ("original_hash"); -------------------------------------------------------------------------------- /migrations/sqls/20210328183552-remove-hash-columns-down.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE uploads ADD COLUMN original_hash text; 2 | ALTER TABLE uploads ADD COLUMN repacked_hash text; 3 | ALTER TABLE uploads ADD COLUMN resized_hash text; 4 | 5 | UPDATE uploads SET original_hash = ''; 6 | UPDATE uploads SET repacked_hash = ''; 7 | UPDATE uploads SET resized_hash = ''; 8 | 9 | ALTER TABLE uploads ALTER COLUMN original_hash SET NOT NULL; 10 | ALTER TABLE uploads ALTER COLUMN repacked_hash SET NOT NULL; 11 | ALTER TABLE uploads ALTER COLUMN resized_hash SET NOT NULL; -------------------------------------------------------------------------------- /migrations/sqls/20210328183552-remove-hash-columns-up.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE uploads DROP COLUMN original_hash; 2 | ALTER TABLE uploads DROP COLUMN repacked_hash; 3 | ALTER TABLE uploads DROP COLUMN resized_hash; -------------------------------------------------------------------------------- /migrations/sqls/20210328185725-add-images-column-down.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE uploads DROP COLUMN images; -------------------------------------------------------------------------------- /migrations/sqls/20210328185725-add-images-column-up.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE uploads ADD COLUMN images text[] NOT NULL DEFAULT '{}'; -------------------------------------------------------------------------------- /migrations/sqls/20210329110833-change-search-index-down.sql: -------------------------------------------------------------------------------- 1 | DROP INDEX IF EXISTS search_idx; 2 | CREATE INDEX IF NOT EXISTS search_idx ON manga USING GIN (to_tsvector('english', eng_title)); -------------------------------------------------------------------------------- /migrations/sqls/20210329110833-change-search-index-up.sql: -------------------------------------------------------------------------------- 1 | DROP INDEX IF EXISTS search_idx; 2 | CREATE INDEX IF NOT EXISTS search_idx ON manga USING GIN (to_tsvector('english', eng_title || ' ' || romaji_title || ' ' || author || ' ' || artist || ' ' || romaji_title)); -------------------------------------------------------------------------------- /migrations/sqls/20210329172239-create-accounts-table-down.sql: -------------------------------------------------------------------------------- 1 | DROP TABLE accounts; -------------------------------------------------------------------------------- /migrations/sqls/20210329172239-create-accounts-table-up.sql: -------------------------------------------------------------------------------- 1 | CREATE TABLE accounts ( 2 | id serial primary key, 3 | username varchar not null, 4 | password_hash varchar not null, 5 | UNIQUE(username) 6 | ); -------------------------------------------------------------------------------- /migrations/sqls/20210329183119-create-uploader-column-down.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE uploads DROP COLUMN uploader; -------------------------------------------------------------------------------- /migrations/sqls/20210329183119-create-uploader-column-up.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE uploads ADD COLUMN uploader integer; 2 | UPDATE uploads SET uploader = 0; 3 | ALTER TABLE uploads ALTER COLUMN uploader SET NOT NULL; -------------------------------------------------------------------------------- /migrations/sqls/20210330124837-add-chapter-column-down.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE uploads DROP COLUMN manga_id; -------------------------------------------------------------------------------- /migrations/sqls/20210330124837-add-chapter-column-up.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE uploads ADD COLUMN manga_id integer; 2 | UPDATE uploads SET manga_id = ( 3 | SELECT manga_id 4 | FROM chapters 5 | WHERE uploads.chapter_id = chapters.identifier 6 | ); 7 | DELETE FROM uploads WHERE manga_id is null; 8 | ALTER TABLE uploads ALTER COLUMN manga_id SET NOT NULL; -------------------------------------------------------------------------------- /migrations/sqls/20210401181359-add-added-column-to-uploads-down.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE uploads DROP COLUMN added; -------------------------------------------------------------------------------- /migrations/sqls/20210401181359-add-added-column-to-uploads-up.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE uploads ADD COLUMN added timestamp; 2 | UPDATE uploads SET added = CURRENT_TIMESTAMP; 3 | ALTER TABLE uploads ALTER COLUMN added SET NOT NULL; 4 | ALTER TABLE uploads ALTER COLUMN added SET DEFAULT CURRENT_TIMESTAMP; -------------------------------------------------------------------------------- /migrations/sqls/20210404221702-add-volume-column-to-uploads-down.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE uploads DROP COLUMN volume_id; -------------------------------------------------------------------------------- /migrations/sqls/20210404221702-add-volume-column-to-uploads-up.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE uploads ADD COLUMN volume_id numeric; 2 | UPDATE uploads SET volume_id = 0; 3 | ALTER TABLE uploads ALTER COLUMN volume_id SET NOT NULL; -------------------------------------------------------------------------------- /migrations/sqls/20210404224951-change-volume-and-chapter-to-text-down.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE uploads ALTER COLUMN chapter_id SET DATA TYPE integer; -------------------------------------------------------------------------------- /migrations/sqls/20210404224951-change-volume-and-chapter-to-text-up.sql: -------------------------------------------------------------------------------- 1 | ALTER TABLE uploads ALTER COLUMN chapter_id SET DATA TYPE numeric; -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "private": true, 3 | "scripts": { 4 | "dev": "supervisor -i node_modules -n error server.js", 5 | "start": "node init.js && pm2-runtime start server.js", 6 | "lint": "semistandard --fix --verbose | snazzy" 7 | }, 8 | "dependencies": { 9 | "@types/express": "^4.17.11", 10 | "@types/fs-extra": "^9.0.9", 11 | "@types/multer": "^1.4.5", 12 | "bcrypt": "^5.0.1", 13 | "bluebird": "^3.7.2", 14 | "body-parser": "^1.19.0", 15 | "connect-multiparty": "^2.2.0", 16 | "cookie-session": "^1.4.0", 17 | "db-migrate": "^0.11.12", 18 | "db-migrate-pg": "^1.2.2", 19 | "dotenv": "^8.2.0", 20 | "express": "^4.17.1", 21 | "flash": "^1.1.0", 22 | "fs-extra": "^9.1.0", 23 | "hasha": "^5.2.2", 24 | "image-size": "^0.9.7", 25 | "image-type": "^4.1.0", 26 | "knex": "^0.95.3", 27 | "multer": "^1.4.2", 28 | "node-stream-zip": "^1.13.2", 29 | "path": "^0.12.7", 30 | "pg": "^8.5.1", 31 | "pm2": "4.5.0", 32 | "read-chunk": "^3.2.0", 33 | "xss": "^1.0.8", 34 | "yazl": "^2.5.1" 35 | }, 36 | "devDependencies": { 37 | "semistandard": "^16.0.0", 38 | "snazzy": "^9.0.0", 39 | "supervisor": "^0.12.0" 40 | }, 41 | "semistandard": { 42 | "globals": [ 43 | "fetch", 44 | "lazyload", 45 | "getParameterByName", 46 | "renderPost", 47 | "debounce", 48 | "confirm", 49 | "self", 50 | "clients", 51 | "localStorage", 52 | "location" 53 | ] 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /public/css/awesomplete.css: -------------------------------------------------------------------------------- 1 | .awesomplete [hidden] { 2 | display: none; 3 | } 4 | 5 | .awesomplete .visually-hidden { 6 | position: absolute; 7 | clip: rect(0, 0, 0, 0); 8 | } 9 | 10 | .awesomplete { 11 | display: inline-block; 12 | position: relative; 13 | } 14 | 15 | .awesomplete > input { 16 | display: block; 17 | } 18 | 19 | .awesomplete > ul { 20 | position: absolute; 21 | left: 0; 22 | z-index: 1; 23 | min-width: 100%; 24 | box-sizing: border-box; 25 | list-style: none; 26 | padding: 0; 27 | margin: 0; 28 | background: #fff; 29 | } 30 | 31 | .awesomplete > ul:empty { 32 | display: none; 33 | } 34 | 35 | .awesomplete > ul { 36 | border-radius: .3em; 37 | margin: .2em 0 0; 38 | background: #3c3c3c; 39 | /* background: linear-gradient(to bottom right, white, hsla(0,0%,100%,.8)); */ 40 | border: 1px solid rgba(0,0,0,.3); 41 | box-shadow: .05em .2em .6em rgba(0,0,0,.2); 42 | text-shadow: none; 43 | } 44 | 45 | @supports (transform: scale(0)) { 46 | .awesomplete > ul { 47 | transition: .3s cubic-bezier(.4,.2,.5,1.4); 48 | transform-origin: 1.43em -.43em; 49 | } 50 | 51 | .awesomplete > ul[hidden], 52 | .awesomplete > ul:empty { 53 | opacity: 0; 54 | transform: scale(0); 55 | display: block; 56 | transition-timing-function: ease; 57 | } 58 | } 59 | 60 | /* Pointer */ 61 | .awesomplete > ul:before { 62 | content: ""; 63 | position: absolute; 64 | top: -.43em; 65 | left: 1em; 66 | width: 0; height: 0; 67 | padding: .4em; 68 | background: #3c3c3c; 69 | border: inherit; 70 | border-right: 0; 71 | border-bottom: 0; 72 | -webkit-transform: rotate(45deg); 73 | transform: rotate(45deg); 74 | } 75 | 76 | .awesomplete > ul > li { 77 | position: relative; 78 | padding: .2em .5em; 79 | cursor: pointer; 80 | } 81 | 82 | .awesomplete > ul > li[aria-selected="true"] { 83 | background: hsl(205, 40%, 40%); 84 | color: white; 85 | } 86 | 87 | .awesomplete mark { 88 | background: hsl(65, 100%, 50%); 89 | } 90 | 91 | .awesomplete li:hover mark { 92 | background: hsl(68, 100%, 41%); 93 | } 94 | 95 | .awesomplete li[aria-selected="true"] mark { 96 | background: hsl(86, 100%, 21%); 97 | color: inherit; 98 | } 99 | /*# sourceMappingURL=awesomplete.css.map */ 100 | -------------------------------------------------------------------------------- /public/css/index.css: -------------------------------------------------------------------------------- 1 | html, body { 2 | background: #222222; 3 | } 4 | 5 | * { 6 | font-family: Helvetica, sans-serif 7 | } 8 | 9 | input[type="file"] { 10 | color: #fff; 11 | } 12 | 13 | h1, h2, h3, h4, h5, h6, p, li, label { 14 | color: #fff; 15 | } 16 | 17 | h1, h2, h3, h4, h5, h6 { 18 | font-weight: normal; 19 | } 20 | 21 | .subtitle { 22 | color: #737373; 23 | } 24 | 25 | .manga-title { 26 | font-size: 32px; 27 | color: white; 28 | } 29 | 30 | .sep { 31 | height: 0.5em; 32 | } 33 | 34 | a:visited { 35 | text-decoration: none; 36 | } 37 | 38 | a:link { 39 | text-decoration: none; 40 | } 41 | 42 | .chapterlist { 43 | list-style-type: none; 44 | } 45 | 46 | .manga-preview { 47 | display: inline-block; 48 | background-color: #3c3c3c; 49 | border-radius: 9px; 50 | width: 228px; 51 | height: 335px; 52 | margin: 5px; 53 | } 54 | 55 | .manga-preview h4 { 56 | overflow: hidden; 57 | text-overflow: ellipsis; 58 | white-space: nowrap; 59 | font-size: 10pt; 60 | font-weight: bold; 61 | margin: 0; 62 | } 63 | 64 | .manga-preview img { 65 | max-height: 308px; 66 | } 67 | 68 | .manga-container { 69 | display: flex; 70 | flex-wrap: wrap; 71 | justify-content: center; 72 | } 73 | 74 | .manga-image { 75 | max-width: 228px; 76 | } 77 | 78 | details summary::-webkit-details-marker { 79 | display:none; 80 | } 81 | 82 | summary { 83 | color: #fff; 84 | padding: 2px; 85 | border-radius: 5px; 86 | font-size: 1.3em; 87 | } 88 | 89 | summary h4 { 90 | margin: 0; 91 | } 92 | 93 | summary:hover { 94 | background-color: #3c3c3c; 95 | } 96 | 97 | ol { 98 | margin: 0; 99 | } 100 | 101 | .chapterlist { 102 | color: #fff; 103 | } 104 | 105 | .chapterlist > thead > tr > th { 106 | text-align: left; 107 | padding-left: 8px; 108 | } 109 | 110 | .chapterlist > tbody > tr > .detail-column { 111 | font-size: 18px; 112 | padding-left: 8px; 113 | } 114 | 115 | .chapterlist > tbody > tr { 116 | padding: 2px; 117 | } 118 | 119 | .imageView { 120 | position: absolute; 121 | margin: 0 auto; 122 | bottom: 0; 123 | left: 0; 124 | right: 0; 125 | top: 0; 126 | z-index: 95; 127 | object-fit: contain; 128 | } 129 | 130 | #pageLeft { 131 | position: fixed; 132 | height: 100%; 133 | width: 50%; 134 | left: 0%; 135 | z-index: 97; 136 | } 137 | 138 | .flash-messages { 139 | background-color: #3c3c3c; 140 | border-radius: 4px; 141 | color: #fff; 142 | text-align: center; 143 | padding: 10px; 144 | } 145 | 146 | #endView { 147 | text-align: center; 148 | z-index: 98; 149 | position: fixed; 150 | top: 50%; 151 | left: 50%; 152 | transform: translate(-50%, -50%); 153 | } 154 | 155 | #pageRight { 156 | position: fixed; 157 | height: 100%; 158 | width: 50%; 159 | left:50%; 160 | z-index: 97; 161 | } 162 | 163 | #titlebarContainer { 164 | z-index: 99; 165 | position: fixed; 166 | width: 100%; 167 | height: 200px; 168 | } 169 | 170 | #titlebar { 171 | z-index: 98; 172 | text-align: center; 173 | border-radius: 4px; 174 | position: relative; 175 | border: 1px solid rgba(0, 0, 0, 0.2); 176 | transform: translate(-50%, -50%); 177 | background-color: #3c3c3c; 178 | left: 50%; 179 | width: 80%; 180 | height: 40px; 181 | margin-top: 30px; 182 | } 183 | 184 | #titlebarText { 185 | margin: 10px; 186 | float: left; 187 | color: #fff; 188 | } 189 | 190 | .titlebarButton { 191 | background-color: rgba(0, 0, 0, 0); 192 | float: right; 193 | border: none; 194 | height: 40px; 195 | width: 40px; 196 | } 197 | 198 | #backButton { 199 | float: left; 200 | } 201 | 202 | .titlebarIcon { 203 | width: 20px; 204 | height: 20px; 205 | } 206 | 207 | #pageFooter { 208 | z-index: 98; 209 | position: fixed; 210 | bottom: 0; 211 | left: 50%; 212 | transform: translate(-50%, -50%); 213 | } 214 | 215 | #pageCounter { 216 | font-weight: bold; 217 | font-size: 18px; 218 | color: #fff; 219 | text-shadow: -1px -1px 0 #333333, 1px -1px 0 #333333, -1px 1px 0 #333333, 1px 1px 0 #333333, 0 -2px 0 #333333, 0 2px 0 #333333, -2px 0 0 #333333, 2px 0 0 #333333; 220 | } 221 | 222 | .visually-hidden { 223 | position: absolute; 224 | left: -100vw; 225 | } 226 | 227 | .new-manga-dialog { 228 | display: none; 229 | } 230 | 231 | #new-manga:checked ~ .new-manga-dialog { 232 | display: block; 233 | } 234 | 235 | #new-manga:checked ~ .manga-id { 236 | pointer-events: none; 237 | background-color: #3c3c3c; 238 | } 239 | 240 | .fas { 241 | font-family: 'FontAwesome'; 242 | color: white; 243 | } 244 | 245 | .manga-cover { 246 | max-height: 250px; 247 | } 248 | 249 | .upload-button { 250 | padding: 30px; 251 | margin-top: 5px; 252 | border-radius: 0.25rem; 253 | font-size: 24px; 254 | text-align: center; 255 | } -------------------------------------------------------------------------------- /public/js/awesomplete.min.js: -------------------------------------------------------------------------------- 1 | // Awesomplete - Lea Verou - MIT license 2 | !function(){function t(t){var e=Array.isArray(t)?{label:t[0],value:t[1]}:"object"==typeof t&&"label"in t&&"value"in t?t:{label:t,value:t};this.label=e.label||e.value,this.value=e.value}function e(t,e,i){for(var n in e){var s=e[n],r=t.input.getAttribute("data-"+n.toLowerCase());"number"==typeof s?t[n]=parseInt(r):!1===s?t[n]=null!==r:s instanceof Function?t[n]=null:t[n]=r,t[n]||0===t[n]||(t[n]=n in i?i[n]:s)}}function i(t,e){return"string"==typeof t?(e||document).querySelector(t):t||null}function n(t,e){return o.call((e||document).querySelectorAll(t))}function s(){n("input.awesomplete").forEach(function(t){new r(t)})}var r=function(t,n){var s=this;r.count=(r.count||0)+1,this.count=r.count,this.isOpened=!1,this.input=i(t),this.input.setAttribute("autocomplete","off"),this.input.setAttribute("aria-expanded","false"),this.input.setAttribute("aria-owns","awesomplete_list_"+this.count),this.input.setAttribute("role","combobox"),this.options=n=n||{},e(this,{minChars:2,maxItems:10,autoFirst:!1,data:r.DATA,filter:r.FILTER_CONTAINS,sort:!1!==n.sort&&r.SORT_BYLENGTH,container:r.CONTAINER,item:r.ITEM,replace:r.REPLACE,tabSelect:!1,listLabel:"Results List"},n),this.index=-1,this.container=this.container(t),this.ul=i.create("ul",{hidden:"hidden",role:"listbox",id:"awesomplete_list_"+this.count,inside:this.container,"aria-label":this.listLabel}),this.status=i.create("span",{className:"visually-hidden",role:"status","aria-live":"assertive","aria-atomic":!0,inside:this.container,textContent:0!=this.minChars?"Type "+this.minChars+" or more characters for results.":"Begin typing for results."}),this._events={input:{input:this.evaluate.bind(this),blur:this.close.bind(this,{reason:"blur"}),keydown:function(t){var e=t.keyCode;s.opened&&(13===e&&s.selected?(t.preventDefault(),s.select(void 0,void 0,t)):9===e&&s.selected&&s.tabSelect?s.select(void 0,void 0,t):27===e?s.close({reason:"esc"}):38!==e&&40!==e||(t.preventDefault(),s[38===e?"previous":"next"]()))}},form:{submit:this.close.bind(this,{reason:"submit"})},ul:{mousedown:function(t){t.preventDefault()},click:function(t){var e=t.target;if(e!==this){for(;e&&!/li/i.test(e.nodeName);)e=e.parentNode;e&&0===t.button&&(t.preventDefault(),s.select(e,t.target,t))}}}},i.bind(this.input,this._events.input),i.bind(this.input.form,this._events.form),i.bind(this.ul,this._events.ul),this.input.hasAttribute("list")?(this.list="#"+this.input.getAttribute("list"),this.input.removeAttribute("list")):this.list=this.input.getAttribute("data-list")||n.list||[],r.all.push(this)};r.prototype={set list(t){if(Array.isArray(t))this._list=t;else if("string"==typeof t&&t.indexOf(",")>-1)this._list=t.split(/\s*,\s*/);else if((t=i(t))&&t.children){var e=[];o.apply(t.children).forEach(function(t){if(!t.disabled){var i=t.textContent.trim(),n=t.value||i,s=t.label||i;""!==n&&e.push({label:s,value:n})}}),this._list=e}document.activeElement===this.input&&this.evaluate()},get selected(){return this.index>-1},get opened(){return this.isOpened},close:function(t){this.opened&&(this.input.setAttribute("aria-expanded","false"),this.ul.setAttribute("hidden",""),this.isOpened=!1,this.index=-1,this.status.setAttribute("hidden",""),i.fire(this.input,"awesomplete-close",t||{}))},open:function(){this.input.setAttribute("aria-expanded","true"),this.ul.removeAttribute("hidden"),this.isOpened=!0,this.status.removeAttribute("hidden"),this.autoFirst&&-1===this.index&&this.goto(0),i.fire(this.input,"awesomplete-open")},destroy:function(){if(i.unbind(this.input,this._events.input),i.unbind(this.input.form,this._events.form),!this.options.container){var t=this.container.parentNode;t.insertBefore(this.input,this.container),t.removeChild(this.container)}this.input.removeAttribute("autocomplete"),this.input.removeAttribute("aria-autocomplete");var e=r.all.indexOf(this);-1!==e&&r.all.splice(e,1)},next:function(){var t=this.ul.children.length;this.goto(this.index-1&&e.length>0&&(e[t].setAttribute("aria-selected","true"),this.status.textContent=e[t].textContent+", list item "+(t+1)+" of "+e.length,this.input.setAttribute("aria-activedescendant",this.ul.id+"_item_"+this.index),this.ul.scrollTop=e[t].offsetTop-this.ul.clientHeight+e[t].clientHeight,i.fire(this.input,"awesomplete-highlight",{text:this.suggestions[this.index]}))},select:function(t,e,n){if(t?this.index=i.siblingIndex(t):t=this.ul.children[this.index],t){var s=this.suggestions[this.index];i.fire(this.input,"awesomplete-select",{text:s,origin:e||t,originalEvent:n})&&(this.replace(s),this.close({reason:"select"}),i.fire(this.input,"awesomplete-selectcomplete",{text:s,originalEvent:n}))}},evaluate:function(){var e=this,i=this.input.value;i.length>=this.minChars&&this._list&&this._list.length>0?(this.index=-1,this.ul.innerHTML="",this.suggestions=this._list.map(function(n){return new t(e.data(n,i))}).filter(function(t){return e.filter(t,i)}),!1!==this.sort&&(this.suggestions=this.suggestions.sort(this.sort)),this.suggestions=this.suggestions.slice(0,this.maxItems),this.suggestions.forEach(function(t,n){e.ul.appendChild(e.item(t,i,n))}),0===this.ul.children.length?(this.status.textContent="No results found",this.close({reason:"nomatches"})):(this.open(),this.status.textContent=this.ul.children.length+" results found")):(this.close({reason:"nomatches"}),this.status.textContent="No results found")}},r.all=[],r.FILTER_CONTAINS=function(t,e){return RegExp(i.regExpEscape(e.trim()),"i").test(t)},r.FILTER_STARTSWITH=function(t,e){return RegExp("^"+i.regExpEscape(e.trim()),"i").test(t)},r.SORT_BYLENGTH=function(t,e){return t.length!==e.length?t.length-e.length:t$&"),role:"option","aria-selected":"false",id:"awesomplete_list_"+this.count+"_item_"+n})},r.REPLACE=function(t){this.input.value=t.value},r.DATA=function(t){return t},Object.defineProperty(t.prototype=Object.create(String.prototype),"length",{get:function(){return this.label.length}}),t.prototype.toString=t.prototype.valueOf=function(){return""+this.label};var o=Array.prototype.slice;i.create=function(t,e){var n=document.createElement(t);for(var s in e){var r=e[s];if("inside"===s)i(r).appendChild(n);else if("around"===s){var o=i(r);o.parentNode.insertBefore(n,o),n.appendChild(o),null!=o.getAttribute("autofocus")&&o.focus()}else s in n?n[s]=r:n.setAttribute(s,r)}return n},i.bind=function(t,e){if(t)for(var i in e){var n=e[i];i.split(/\s+/).forEach(function(e){t.addEventListener(e,n)})}},i.unbind=function(t,e){if(t)for(var i in e){var n=e[i];i.split(/\s+/).forEach(function(e){t.removeEventListener(e,n)})}},i.fire=function(t,e,i){var n=document.createEvent("HTMLEvents");n.initEvent(e,!0,!0);for(var s in i)n[s]=i[s];return t.dispatchEvent(n)},i.regExpEscape=function(t){return t.replace(/[-\\^$*+?.()|[\]{}]/g,"\\$&")},i.siblingIndex=function(t){for(var e=0;t=t.previousElementSibling;e++);return e},"undefined"!=typeof self&&(self.Awesomplete=r),"undefined"!=typeof Document&&("loading"!==document.readyState?s():document.addEventListener("DOMContentLoaded",s)),r.$=i,r.$$=n,"object"==typeof module&&module.exports&&(module.exports=r)}(); 3 | //# sourceMappingURL=awesomplete.min.js.map 4 | -------------------------------------------------------------------------------- /public/js/reader.js: -------------------------------------------------------------------------------- 1 | var current_page = 1; 2 | var total_pages; 3 | var images; 4 | var fitCurrent = 'height'; 5 | var atEnd = false; 6 | 7 | const loadPage = () => { 8 | for(let i = 1; i <= total_pages; i++){ 9 | document.getElementById(`image${i}`).style.display = 'none'; 10 | } 11 | document.getElementById(`image${current_page}`).style.display = 'block'; 12 | document.getElementById('pageCounter').textContent = `${current_page}/${total_pages}`; 13 | } 14 | let leftPage = () => { 15 | if (atEnd) { 16 | atEnd = false; 17 | document.getElementById(`image${total_pages}`).style.display = 'block'; 18 | document.getElementById(`endView`).style.display = 'none'; 19 | } else { 20 | if (current_page - 1 >= 1) { 21 | current_page -= 1; 22 | window.scrollTo(0,0); 23 | loadPage(); 24 | } 25 | } 26 | } 27 | 28 | let rightPage = () => { 29 | if (current_page + 1 <= total_pages) { 30 | current_page += 1; 31 | window.scrollTo(0,0); 32 | loadPage(); 33 | } else { 34 | if (!atEnd) { 35 | atEnd = true; 36 | document.getElementById(`image${total_pages}`).style.display = 'none'; 37 | document.getElementById(`endView`).style.display = 'block'; 38 | } 39 | } 40 | } 41 | 42 | const invertPage = () => { 43 | [leftPage, rightPage] = [rightPage, leftPage]; 44 | } 45 | 46 | const fitWidth = () => { 47 | fitCurrent = 'width'; 48 | for(let i = 1; i <= total_pages; i++) { 49 | document.getElementById(`image${i}`).style.maxWidth = '100%'; 50 | document.getElementById(`image${i}`).style.height = 'auto'; 51 | } 52 | } 53 | 54 | const fitHeight = () => { 55 | fitCurrent = 'height'; 56 | for(let i = 1; i <= total_pages; i++) { 57 | document.getElementById(`image${i}`).style.maxWidth = null; 58 | document.getElementById(`image${i}`).style.height = '100%'; 59 | } 60 | } 61 | 62 | document.getElementById("fitButton").addEventListener("click", function (e) { 63 | if (fitCurrent == "height") { 64 | fitWidth(); 65 | } else{ 66 | fitHeight(); 67 | } 68 | }); 69 | 70 | document.addEventListener("keydown", function (e) { 71 | e = e || window.event; 72 | switch (e.keyCode) { 73 | case 32: 74 | case 39: 75 | case 76: 76 | rightPage(); 77 | break; 78 | case 37: 79 | case 72: 80 | leftPage(); 81 | break; 82 | default: return; 83 | } 84 | e.preventDefault(); 85 | }); 86 | 87 | document.getElementById("invertButton").addEventListener("click", function (e) { 88 | invertPage(); 89 | }); 90 | 91 | document.getElementById("pageLeft").addEventListener("click", function (e) { 92 | leftPage() 93 | }); 94 | 95 | document.getElementById("pageRight").addEventListener("click", function (e) { 96 | rightPage() 97 | }); 98 | 99 | document.getElementById("titlebar").style.display = 'none'; 100 | document.getElementById("endView").style.display = 'none'; 101 | 102 | document.getElementById("titlebarContainer").addEventListener("mouseenter", function () { 103 | document.getElementById("titlebar").style.display = 'block'; 104 | }); 105 | 106 | document.getElementById("titlebarContainer").addEventListener("mouseleave", function () { 107 | document.getElementById("titlebar").style.display = 'none'; 108 | }); 109 | 110 | (async () => { 111 | const release_data = await (await fetch('/api/release/' + document.getElementsByName('id')[0].content)).json(); 112 | const all_release_data = await (await fetch('/api/manga/' + release_data[0].manga_id + '/releases')).json(); 113 | const manga_data = await (await fetch('/api/manga/' + release_data[0].manga_id)).json(); 114 | 115 | images = release_data[0].images; 116 | total_pages = images.length 117 | 118 | images.forEach((image, i) => { 119 | var img = document.createElement('img'); 120 | img.setAttribute('draggable', 'false'); 121 | img.setAttribute('src', '/assets/' + image); 122 | img.className = "imageView"; 123 | img.id = `image${i + 1}`; 124 | img.style.display = 'none'; 125 | img.style.maxWidth = null; 126 | img.style.height = '100%'; 127 | document.getElementById('pageView').appendChild(img); 128 | }); 129 | 130 | document.getElementById('titlebarText').innerHTML = manga_data[0].eng_title; 131 | document.getElementById('pageCounter').textContent = `${current_page}/${total_pages}`; 132 | document.getElementById(`image1`).style.display = 'block'; 133 | 134 | all_release_data.forEach(release => { 135 | document.getElementById('endSelect').innerHTML += ` 136 | 139 | ` 140 | }) 141 | 142 | const results_above_current_chapter = all_release_data.filter(x => x.volume_id === release_data[0].volume_id && x.chapter_id > release_data[0].chapter_id); 143 | if (results_above_current_chapter.length) { 144 | document.getElementById('endView').innerHTML += ` 145 |
146 | Next chapter 147 | ` 148 | } else { 149 | const results_above_current_volume = all_release_data.filter(x => x.volume_id > release_data[0].volume_id); 150 | if (results_above_current_volume.length) { 151 | document.getElementById('endView').innerHTML += ` 152 |
153 | Next volume 154 | ` 155 | } 156 | } 157 | 158 | document.getElementById("endSelect").addEventListener('change', function () { 159 | window.location = '/release/' + document.getElementById("endSelect").value; 160 | }); 161 | })() -------------------------------------------------------------------------------- /public/js/resumable.js: -------------------------------------------------------------------------------- 1 | /* 2 | * MIT Licensed 3 | * http://www.23developer.com/opensource 4 | * http://github.com/23/resumable.js 5 | * Steffen Tiedemann Christensen, steffen@23company.com 6 | */ 7 | 8 | (function(){ 9 | "use strict"; 10 | 11 | var Resumable = function(opts){ 12 | if ( !(this instanceof Resumable) ) { 13 | return new Resumable(opts); 14 | } 15 | this.version = 1.0; 16 | // SUPPORTED BY BROWSER? 17 | // Check if these features are support by the browser: 18 | // - File object type 19 | // - Blob object type 20 | // - FileList object type 21 | // - slicing files 22 | this.support = ( 23 | (typeof(File)!=='undefined') 24 | && 25 | (typeof(Blob)!=='undefined') 26 | && 27 | (typeof(FileList)!=='undefined') 28 | && 29 | (!!Blob.prototype.webkitSlice||!!Blob.prototype.mozSlice||!!Blob.prototype.slice||false) 30 | ); 31 | if(!this.support) return(false); 32 | 33 | 34 | // PROPERTIES 35 | var $ = this; 36 | $.files = []; 37 | $.defaults = { 38 | chunkSize:1*1024*1024, 39 | forceChunkSize:false, 40 | simultaneousUploads:3, 41 | fileParameterName:'file', 42 | chunkNumberParameterName: 'resumableChunkNumber', 43 | chunkSizeParameterName: 'resumableChunkSize', 44 | currentChunkSizeParameterName: 'resumableCurrentChunkSize', 45 | totalSizeParameterName: 'resumableTotalSize', 46 | typeParameterName: 'resumableType', 47 | identifierParameterName: 'resumableIdentifier', 48 | fileNameParameterName: 'resumableFilename', 49 | relativePathParameterName: 'resumableRelativePath', 50 | totalChunksParameterName: 'resumableTotalChunks', 51 | dragOverClass: 'dragover', 52 | throttleProgressCallbacks: 0.5, 53 | query:{}, 54 | headers:{}, 55 | preprocess:null, 56 | preprocessFile:null, 57 | method:'multipart', 58 | uploadMethod: 'POST', 59 | testMethod: 'GET', 60 | prioritizeFirstAndLastChunk:false, 61 | target:'/', 62 | testTarget: null, 63 | parameterNamespace:'', 64 | testChunks:true, 65 | generateUniqueIdentifier:null, 66 | getTarget:null, 67 | maxChunkRetries:100, 68 | chunkRetryInterval:undefined, 69 | permanentErrors:[400, 401, 403, 404, 409, 415, 500, 501], 70 | maxFiles:undefined, 71 | withCredentials:false, 72 | xhrTimeout:0, 73 | clearInput:true, 74 | chunkFormat:'blob', 75 | setChunkTypeFromFile:false, 76 | maxFilesErrorCallback:function (files, errorCount) { 77 | var maxFiles = $.getOpt('maxFiles'); 78 | alert('Please upload no more than ' + maxFiles + ' file' + (maxFiles === 1 ? '' : 's') + ' at a time.'); 79 | }, 80 | minFileSize:1, 81 | minFileSizeErrorCallback:function(file, errorCount) { 82 | alert(file.fileName||file.name +' is too small, please upload files larger than ' + $h.formatSize($.getOpt('minFileSize')) + '.'); 83 | }, 84 | maxFileSize:undefined, 85 | maxFileSizeErrorCallback:function(file, errorCount) { 86 | alert(file.fileName||file.name +' is too large, please upload files less than ' + $h.formatSize($.getOpt('maxFileSize')) + '.'); 87 | }, 88 | fileType: [], 89 | fileTypeErrorCallback: function(file, errorCount) { 90 | alert(file.fileName||file.name +' has type not allowed, please upload files of type ' + $.getOpt('fileType') + '.'); 91 | } 92 | }; 93 | $.opts = opts||{}; 94 | $.getOpt = function(o) { 95 | var $opt = this; 96 | // Get multiple option if passed an array 97 | if(o instanceof Array) { 98 | var options = {}; 99 | $h.each(o, function(option){ 100 | options[option] = $opt.getOpt(option); 101 | }); 102 | return options; 103 | } 104 | // Otherwise, just return a simple option 105 | if ($opt instanceof ResumableChunk) { 106 | if (typeof $opt.opts[o] !== 'undefined') { return $opt.opts[o]; } 107 | else { $opt = $opt.fileObj; } 108 | } 109 | if ($opt instanceof ResumableFile) { 110 | if (typeof $opt.opts[o] !== 'undefined') { return $opt.opts[o]; } 111 | else { $opt = $opt.resumableObj; } 112 | } 113 | if ($opt instanceof Resumable) { 114 | if (typeof $opt.opts[o] !== 'undefined') { return $opt.opts[o]; } 115 | else { return $opt.defaults[o]; } 116 | } 117 | }; 118 | $.indexOf = function(array, obj) { 119 | if (array.indexOf) { return array.indexOf(obj); } 120 | for (var i = 0; i < array.length; i++) { 121 | if (array[i] === obj) { return i; } 122 | } 123 | return -1; 124 | } 125 | 126 | // EVENTS 127 | // catchAll(event, ...) 128 | // fileSuccess(file), fileProgress(file), fileAdded(file, event), filesAdded(files, filesSkipped), fileRetry(file), 129 | // fileError(file, message), complete(), progress(), error(message, file), pause() 130 | $.events = []; 131 | $.on = function(event,callback){ 132 | $.events.push(event.toLowerCase(), callback); 133 | }; 134 | $.fire = function(){ 135 | // `arguments` is an object, not array, in FF, so: 136 | var args = []; 137 | for (var i=0; i= 0) { // only for file drop 241 | e.stopPropagation(); 242 | dt.dropEffect = "copy"; 243 | dt.effectAllowed = "copy"; 244 | e.currentTarget.classList.add($.getOpt('dragOverClass')); 245 | } else { // not work on IE/Edge.... 246 | dt.dropEffect = "none"; 247 | dt.effectAllowed = "none"; 248 | } 249 | }; 250 | 251 | /** 252 | * processes a single upload item (file or directory) 253 | * @param {Object} item item to upload, may be file or directory entry 254 | * @param {string} path current file path 255 | * @param {File[]} items list of files to append new items to 256 | * @param {Function} cb callback invoked when item is processed 257 | */ 258 | function processItem(item, path, items, cb) { 259 | var entry; 260 | if(item.isFile){ 261 | // file provided 262 | return item.file(function(file){ 263 | file.relativePath = path + file.name; 264 | items.push(file); 265 | cb(); 266 | }); 267 | }else if(item.isDirectory){ 268 | // item is already a directory entry, just assign 269 | entry = item; 270 | }else if(item instanceof File) { 271 | items.push(item); 272 | } 273 | if('function' === typeof item.webkitGetAsEntry){ 274 | // get entry from file object 275 | entry = item.webkitGetAsEntry(); 276 | } 277 | if(entry && entry.isDirectory){ 278 | // directory provided, process it 279 | return processDirectory(entry, path + entry.name + '/', items, cb); 280 | } 281 | if('function' === typeof item.getAsFile){ 282 | // item represents a File object, convert it 283 | item = item.getAsFile(); 284 | if(item instanceof File) { 285 | item.relativePath = path + item.name; 286 | items.push(item); 287 | } 288 | } 289 | cb(); // indicate processing is done 290 | } 291 | 292 | 293 | /** 294 | * cps-style list iteration. 295 | * invokes all functions in list and waits for their callback to be 296 | * triggered. 297 | * @param {Function[]} items list of functions expecting callback parameter 298 | * @param {Function} cb callback to trigger after the last callback has been invoked 299 | */ 300 | function processCallbacks(items, cb){ 301 | if(!items || items.length === 0){ 302 | // empty or no list, invoke callback 303 | return cb(); 304 | } 305 | // invoke current function, pass the next part as continuation 306 | items[0](function(){ 307 | processCallbacks(items.slice(1), cb); 308 | }); 309 | } 310 | 311 | /** 312 | * recursively traverse directory and collect files to upload 313 | * @param {Object} directory directory to process 314 | * @param {string} path current path 315 | * @param {File[]} items target list of items 316 | * @param {Function} cb callback invoked after traversing directory 317 | */ 318 | function processDirectory (directory, path, items, cb) { 319 | var dirReader = directory.createReader(); 320 | var allEntries = []; 321 | 322 | function readEntries () { 323 | dirReader.readEntries(function(entries){ 324 | if (entries.length) { 325 | allEntries = allEntries.concat(entries); 326 | return readEntries(); 327 | } 328 | 329 | // process all conversion callbacks, finally invoke own one 330 | processCallbacks( 331 | allEntries.map(function(entry){ 332 | // bind all properties except for callback 333 | return processItem.bind(null, entry, path, items); 334 | }), 335 | cb 336 | ); 337 | }); 338 | } 339 | 340 | readEntries(); 341 | } 342 | 343 | /** 344 | * process items to extract files to be uploaded 345 | * @param {File[]} items items to process 346 | * @param {Event} event event that led to upload 347 | */ 348 | function loadFiles(items, event) { 349 | if(!items.length){ 350 | return; // nothing to do 351 | } 352 | $.fire('beforeAdd'); 353 | var files = []; 354 | processCallbacks( 355 | Array.prototype.map.call(items, function(item){ 356 | // bind all properties except for callback 357 | var entry = item; 358 | if('function' === typeof item.webkitGetAsEntry){ 359 | entry = item.webkitGetAsEntry(); 360 | } 361 | return processItem.bind(null, entry, "", files); 362 | }), 363 | function(){ 364 | if(files.length){ 365 | // at least one file found 366 | appendFilesFromFileList(files, event); 367 | } 368 | } 369 | ); 370 | }; 371 | 372 | var appendFilesFromFileList = function(fileList, event){ 373 | // check for uploading too many files 374 | var errorCount = 0; 375 | var o = $.getOpt(['maxFiles', 'minFileSize', 'maxFileSize', 'maxFilesErrorCallback', 'minFileSizeErrorCallback', 'maxFileSizeErrorCallback', 'fileType', 'fileTypeErrorCallback']); 376 | if (typeof(o.maxFiles)!=='undefined' && o.maxFiles<(fileList.length+$.files.length)) { 377 | // if single-file upload, file is already added, and trying to add 1 new file, simply replace the already-added file 378 | if (o.maxFiles===1 && $.files.length===1 && fileList.length===1) { 379 | $.removeFile($.files[0]); 380 | } else { 381 | o.maxFilesErrorCallback(fileList, errorCount++); 382 | return false; 383 | } 384 | } 385 | var files = [], filesSkipped = [], remaining = fileList.length; 386 | var decreaseReamining = function(){ 387 | if(!--remaining){ 388 | // all files processed, trigger event 389 | if(!files.length && !filesSkipped.length){ 390 | // no succeeded files, just skip 391 | return; 392 | } 393 | window.setTimeout(function(){ 394 | $.fire('filesAdded', files, filesSkipped); 395 | },0); 396 | } 397 | }; 398 | $h.each(fileList, function(file){ 399 | var fileName = file.name; 400 | var fileType = file.type; // e.g video/mp4 401 | if(o.fileType.length > 0){ 402 | var fileTypeFound = false; 403 | for(var index in o.fileType){ 404 | // For good behaviour we do some inital sanitizing. Remove spaces and lowercase all 405 | o.fileType[index] = o.fileType[index].replace(/\s/g, '').toLowerCase(); 406 | 407 | // Allowing for both [extension, .extension, mime/type, mime/*] 408 | var extension = ((o.fileType[index].match(/^[^.][^/]+$/)) ? '.' : '') + o.fileType[index]; 409 | 410 | if ((fileName.substr(-1 * extension.length).toLowerCase() === extension) || 411 | //If MIME type, check for wildcard or if extension matches the files tiletype 412 | (extension.indexOf('/') !== -1 && ( 413 | (extension.indexOf('*') !== -1 && fileType.substr(0, extension.indexOf('*')) === extension.substr(0, extension.indexOf('*'))) || 414 | fileType === extension 415 | )) 416 | ){ 417 | fileTypeFound = true; 418 | break; 419 | } 420 | } 421 | if (!fileTypeFound) { 422 | o.fileTypeErrorCallback(file, errorCount++); 423 | return true; 424 | } 425 | } 426 | 427 | if (typeof(o.minFileSize)!=='undefined' && file.sizeo.maxFileSize) { 432 | o.maxFileSizeErrorCallback(file, errorCount++); 433 | return true; 434 | } 435 | 436 | function addFile(uniqueIdentifier){ 437 | if (!$.getFromUniqueIdentifier(uniqueIdentifier)) {(function(){ 438 | file.uniqueIdentifier = uniqueIdentifier; 439 | var f = new ResumableFile($, file, uniqueIdentifier); 440 | $.files.push(f); 441 | files.push(f); 442 | f.container = (typeof event != 'undefined' ? event.srcElement : null); 443 | window.setTimeout(function(){ 444 | $.fire('fileAdded', f, event) 445 | },0); 446 | })()} else { 447 | filesSkipped.push(file); 448 | }; 449 | decreaseReamining(); 450 | } 451 | // directories have size == 0 452 | var uniqueIdentifier = $h.generateUniqueIdentifier(file, event); 453 | if(uniqueIdentifier && typeof uniqueIdentifier.then === 'function'){ 454 | // Promise or Promise-like object provided as unique identifier 455 | uniqueIdentifier 456 | .then( 457 | function(uniqueIdentifier){ 458 | // unique identifier generation succeeded 459 | addFile(uniqueIdentifier); 460 | }, 461 | function(){ 462 | // unique identifier generation failed 463 | // skip further processing, only decrease file count 464 | decreaseReamining(); 465 | } 466 | ); 467 | }else{ 468 | // non-Promise provided as unique identifier, process synchronously 469 | addFile(uniqueIdentifier); 470 | } 471 | }); 472 | }; 473 | 474 | // INTERNAL OBJECT TYPES 475 | function ResumableFile(resumableObj, file, uniqueIdentifier){ 476 | var $ = this; 477 | $.opts = {}; 478 | $.getOpt = resumableObj.getOpt; 479 | $._prevProgress = 0; 480 | $.resumableObj = resumableObj; 481 | $.file = file; 482 | $.fileName = file.fileName||file.name; // Some confusion in different versions of Firefox 483 | $.size = file.size; 484 | $.relativePath = file.relativePath || file.webkitRelativePath || $.fileName; 485 | $.uniqueIdentifier = uniqueIdentifier; 486 | $._pause = false; 487 | $.container = ''; 488 | $.preprocessState = 0; // 0 = unprocessed, 1 = processing, 2 = finished 489 | var _error = uniqueIdentifier !== undefined; 490 | 491 | // Callback when something happens within the chunk 492 | var chunkEvent = function(event, message){ 493 | // event can be 'progress', 'success', 'error' or 'retry' 494 | switch(event){ 495 | case 'progress': 496 | $.resumableObj.fire('fileProgress', $, message); 497 | break; 498 | case 'error': 499 | $.abort(); 500 | _error = true; 501 | $.chunks = []; 502 | $.resumableObj.fire('fileError', $, message); 503 | break; 504 | case 'success': 505 | if(_error) return; 506 | $.resumableObj.fire('fileProgress', $, message); // it's at least progress 507 | if($.isComplete()) { 508 | $.resumableObj.fire('fileSuccess', $, message); 509 | } 510 | break; 511 | case 'retry': 512 | $.resumableObj.fire('fileRetry', $); 513 | break; 514 | } 515 | }; 516 | 517 | // Main code to set up a file object with chunks, 518 | // packaged to be able to handle retries if needed. 519 | $.chunks = []; 520 | $.abort = function(){ 521 | // Stop current uploads 522 | var abortCount = 0; 523 | $h.each($.chunks, function(c){ 524 | if(c.status()=='uploading') { 525 | c.abort(); 526 | abortCount++; 527 | } 528 | }); 529 | if(abortCount>0) $.resumableObj.fire('fileProgress', $); 530 | }; 531 | $.cancel = function(){ 532 | // Reset this file to be void 533 | var _chunks = $.chunks; 534 | $.chunks = []; 535 | // Stop current uploads 536 | $h.each(_chunks, function(c){ 537 | if(c.status()=='uploading') { 538 | c.abort(); 539 | $.resumableObj.uploadNextChunk(); 540 | } 541 | }); 542 | $.resumableObj.removeFile($); 543 | $.resumableObj.fire('fileProgress', $); 544 | }; 545 | $.retry = function(){ 546 | $.bootstrap(); 547 | var firedRetry = false; 548 | $.resumableObj.on('chunkingComplete', function(){ 549 | if(!firedRetry) $.resumableObj.upload(); 550 | firedRetry = true; 551 | }); 552 | }; 553 | $.bootstrap = function(){ 554 | $.abort(); 555 | _error = false; 556 | // Rebuild stack of chunks from file 557 | $.chunks = []; 558 | $._prevProgress = 0; 559 | var round = $.getOpt('forceChunkSize') ? Math.ceil : Math.floor; 560 | var maxOffset = Math.max(round($.file.size/$.getOpt('chunkSize')),1); 561 | for (var offset=0; offset0.99999 ? 1 : ret)); 579 | ret = Math.max($._prevProgress, ret); // We don't want to lose percentages when an upload is paused 580 | $._prevProgress = ret; 581 | return(ret); 582 | }; 583 | $.isUploading = function(){ 584 | var uploading = false; 585 | $h.each($.chunks, function(chunk){ 586 | if(chunk.status()=='uploading') { 587 | uploading = true; 588 | return(false); 589 | } 590 | }); 591 | return(uploading); 592 | }; 593 | $.isComplete = function(){ 594 | var outstanding = false; 595 | if ($.preprocessState === 1) { 596 | return(false); 597 | } 598 | $h.each($.chunks, function(chunk){ 599 | var status = chunk.status(); 600 | if(status=='pending' || status=='uploading' || chunk.preprocessState === 1) { 601 | outstanding = true; 602 | return(false); 603 | } 604 | }); 605 | return(!outstanding); 606 | }; 607 | $.pause = function(pause){ 608 | if(typeof(pause)==='undefined'){ 609 | $._pause = ($._pause ? false : true); 610 | }else{ 611 | $._pause = pause; 612 | } 613 | }; 614 | $.isPaused = function() { 615 | return $._pause; 616 | }; 617 | $.preprocessFinished = function(){ 618 | $.preprocessState = 2; 619 | $.upload(); 620 | }; 621 | $.upload = function () { 622 | var found = false; 623 | if ($.isPaused() === false) { 624 | var preprocess = $.getOpt('preprocessFile'); 625 | if(typeof preprocess === 'function') { 626 | switch($.preprocessState) { 627 | case 0: $.preprocessState = 1; preprocess($); return(true); 628 | case 1: return(true); 629 | case 2: break; 630 | } 631 | } 632 | $h.each($.chunks, function (chunk) { 633 | if (chunk.status() == 'pending' && chunk.preprocessState !== 1) { 634 | chunk.send(); 635 | found = true; 636 | return(false); 637 | } 638 | }); 639 | } 640 | return(found); 641 | } 642 | $.markChunksCompleted = function (chunkNumber) { 643 | if (!$.chunks || $.chunks.length <= chunkNumber) { 644 | return; 645 | } 646 | for (var num = 0; num < chunkNumber; num++) { 647 | $.chunks[num].markComplete = true; 648 | } 649 | }; 650 | 651 | // Bootstrap and return 652 | $.resumableObj.fire('chunkingStart', $); 653 | $.bootstrap(); 654 | return(this); 655 | } 656 | 657 | 658 | function ResumableChunk(resumableObj, fileObj, offset, callback){ 659 | var $ = this; 660 | $.opts = {}; 661 | $.getOpt = resumableObj.getOpt; 662 | $.resumableObj = resumableObj; 663 | $.fileObj = fileObj; 664 | $.fileObjSize = fileObj.size; 665 | $.fileObjType = fileObj.file.type; 666 | $.offset = offset; 667 | $.callback = callback; 668 | $.lastProgressCallback = (new Date); 669 | $.tested = false; 670 | $.retries = 0; 671 | $.pendingRetry = false; 672 | $.preprocessState = 0; // 0 = unprocessed, 1 = processing, 2 = finished 673 | $.markComplete = false; 674 | 675 | // Computed properties 676 | var chunkSize = $.getOpt('chunkSize'); 677 | $.loaded = 0; 678 | $.startByte = $.offset*chunkSize; 679 | $.endByte = Math.min($.fileObjSize, ($.offset+1)*chunkSize); 680 | if ($.fileObjSize-$.endByte < chunkSize && !$.getOpt('forceChunkSize')) { 681 | // The last chunk will be bigger than the chunk size, but less than 2*chunkSize 682 | $.endByte = $.fileObjSize; 683 | } 684 | $.xhr = null; 685 | 686 | // test() makes a GET request without any data to see if the chunk has already been uploaded in a previous session 687 | $.test = function(){ 688 | // Set up request and listen for event 689 | $.xhr = new XMLHttpRequest(); 690 | 691 | var testHandler = function(e){ 692 | $.tested = true; 693 | var status = $.status(); 694 | if(status=='success') { 695 | $.callback(status, $.message()); 696 | $.resumableObj.uploadNextChunk(); 697 | } else { 698 | $.send(); 699 | } 700 | }; 701 | $.xhr.addEventListener('load', testHandler, false); 702 | $.xhr.addEventListener('error', testHandler, false); 703 | $.xhr.addEventListener('timeout', testHandler, false); 704 | 705 | // Add data from the query options 706 | var params = []; 707 | var parameterNamespace = $.getOpt('parameterNamespace'); 708 | var customQuery = $.getOpt('query'); 709 | if(typeof customQuery == 'function') customQuery = customQuery($.fileObj, $); 710 | $h.each(customQuery, function(k,v){ 711 | params.push([encodeURIComponent(parameterNamespace+k), encodeURIComponent(v)].join('=')); 712 | }); 713 | // Add extra data to identify chunk 714 | params = params.concat( 715 | [ 716 | // define key/value pairs for additional parameters 717 | ['chunkNumberParameterName', $.offset + 1], 718 | ['chunkSizeParameterName', $.getOpt('chunkSize')], 719 | ['currentChunkSizeParameterName', $.endByte - $.startByte], 720 | ['totalSizeParameterName', $.fileObjSize], 721 | ['typeParameterName', $.fileObjType], 722 | ['identifierParameterName', $.fileObj.uniqueIdentifier], 723 | ['fileNameParameterName', $.fileObj.fileName], 724 | ['relativePathParameterName', $.fileObj.relativePath], 725 | ['totalChunksParameterName', $.fileObj.chunks.length] 726 | ].filter(function(pair){ 727 | // include items that resolve to truthy values 728 | // i.e. exclude false, null, undefined and empty strings 729 | return $.getOpt(pair[0]); 730 | }) 731 | .map(function(pair){ 732 | // map each key/value pair to its final form 733 | return [ 734 | parameterNamespace + $.getOpt(pair[0]), 735 | encodeURIComponent(pair[1]) 736 | ].join('='); 737 | }) 738 | ); 739 | // Append the relevant chunk and send it 740 | $.xhr.open($.getOpt('testMethod'), $h.getTarget('test', params)); 741 | $.xhr.timeout = $.getOpt('xhrTimeout'); 742 | $.xhr.withCredentials = $.getOpt('withCredentials'); 743 | // Add data from header options 744 | var customHeaders = $.getOpt('headers'); 745 | if(typeof customHeaders === 'function') { 746 | customHeaders = customHeaders($.fileObj, $); 747 | } 748 | $h.each(customHeaders, function(k,v) { 749 | $.xhr.setRequestHeader(k, v); 750 | }); 751 | $.xhr.send(null); 752 | }; 753 | 754 | $.preprocessFinished = function(){ 755 | $.preprocessState = 2; 756 | $.send(); 757 | }; 758 | 759 | // send() uploads the actual data in a POST call 760 | $.send = function(){ 761 | var preprocess = $.getOpt('preprocess'); 762 | if(typeof preprocess === 'function') { 763 | switch($.preprocessState) { 764 | case 0: $.preprocessState = 1; preprocess($); return; 765 | case 1: return; 766 | case 2: break; 767 | } 768 | } 769 | if($.getOpt('testChunks') && !$.tested) { 770 | $.test(); 771 | return; 772 | } 773 | 774 | // Set up request and listen for event 775 | $.xhr = new XMLHttpRequest(); 776 | 777 | // Progress 778 | $.xhr.upload.addEventListener('progress', function(e){ 779 | if( (new Date) - $.lastProgressCallback > $.getOpt('throttleProgressCallbacks') * 1000 ) { 780 | $.callback('progress'); 781 | $.lastProgressCallback = (new Date); 782 | } 783 | $.loaded=e.loaded||0; 784 | }, false); 785 | $.loaded = 0; 786 | $.pendingRetry = false; 787 | $.callback('progress'); 788 | 789 | // Done (either done, failed or retry) 790 | var doneHandler = function(e){ 791 | var status = $.status(); 792 | if(status=='success'||status=='error') { 793 | $.callback(status, $.message()); 794 | $.resumableObj.uploadNextChunk(); 795 | } else { 796 | $.callback('retry', $.message()); 797 | $.abort(); 798 | $.retries++; 799 | var retryInterval = $.getOpt('chunkRetryInterval'); 800 | if(retryInterval !== undefined) { 801 | $.pendingRetry = true; 802 | setTimeout($.send, retryInterval); 803 | } else { 804 | $.send(); 805 | } 806 | } 807 | }; 808 | $.xhr.addEventListener('load', doneHandler, false); 809 | $.xhr.addEventListener('error', doneHandler, false); 810 | $.xhr.addEventListener('timeout', doneHandler, false); 811 | 812 | // Set up the basic query data from Resumable 813 | var query = [ 814 | ['chunkNumberParameterName', $.offset + 1], 815 | ['chunkSizeParameterName', $.getOpt('chunkSize')], 816 | ['currentChunkSizeParameterName', $.endByte - $.startByte], 817 | ['totalSizeParameterName', $.fileObjSize], 818 | ['typeParameterName', $.fileObjType], 819 | ['identifierParameterName', $.fileObj.uniqueIdentifier], 820 | ['fileNameParameterName', $.fileObj.fileName], 821 | ['relativePathParameterName', $.fileObj.relativePath], 822 | ['totalChunksParameterName', $.fileObj.chunks.length], 823 | ].filter(function(pair){ 824 | // include items that resolve to truthy values 825 | // i.e. exclude false, null, undefined and empty strings 826 | return $.getOpt(pair[0]); 827 | }) 828 | .reduce(function(query, pair){ 829 | // assign query key/value 830 | query[$.getOpt(pair[0])] = pair[1]; 831 | return query; 832 | }, {}); 833 | // Mix in custom data 834 | var customQuery = $.getOpt('query'); 835 | if(typeof customQuery == 'function') customQuery = customQuery($.fileObj, $); 836 | $h.each(customQuery, function(k,v){ 837 | query[k] = v; 838 | }); 839 | 840 | var func = ($.fileObj.file.slice ? 'slice' : ($.fileObj.file.mozSlice ? 'mozSlice' : ($.fileObj.file.webkitSlice ? 'webkitSlice' : 'slice'))); 841 | var bytes = $.fileObj.file[func]($.startByte, $.endByte, $.getOpt('setChunkTypeFromFile') ? $.fileObj.file.type : ""); 842 | var data = null; 843 | var params = []; 844 | 845 | var parameterNamespace = $.getOpt('parameterNamespace'); 846 | if ($.getOpt('method') === 'octet') { 847 | // Add data from the query options 848 | data = bytes; 849 | $h.each(query, function (k, v) { 850 | params.push([encodeURIComponent(parameterNamespace + k), encodeURIComponent(v)].join('=')); 851 | }); 852 | } else { 853 | // Add data from the query options 854 | data = new FormData(); 855 | $h.each(query, function (k, v) { 856 | data.append(parameterNamespace + k, v); 857 | params.push([encodeURIComponent(parameterNamespace + k), encodeURIComponent(v)].join('=')); 858 | }); 859 | if ($.getOpt('chunkFormat') == 'blob') { 860 | data.append(parameterNamespace + $.getOpt('fileParameterName'), bytes, $.fileObj.fileName); 861 | } 862 | else if ($.getOpt('chunkFormat') == 'base64') { 863 | var fr = new FileReader(); 864 | fr.onload = function (e) { 865 | data.append(parameterNamespace + $.getOpt('fileParameterName'), fr.result); 866 | $.xhr.send(data); 867 | } 868 | fr.readAsDataURL(bytes); 869 | } 870 | } 871 | 872 | var target = $h.getTarget('upload', params); 873 | var method = $.getOpt('uploadMethod'); 874 | 875 | $.xhr.open(method, target); 876 | if ($.getOpt('method') === 'octet') { 877 | $.xhr.setRequestHeader('Content-Type', 'application/octet-stream'); 878 | } 879 | $.xhr.timeout = $.getOpt('xhrTimeout'); 880 | $.xhr.withCredentials = $.getOpt('withCredentials'); 881 | // Add data from header options 882 | var customHeaders = $.getOpt('headers'); 883 | if(typeof customHeaders === 'function') { 884 | customHeaders = customHeaders($.fileObj, $); 885 | } 886 | 887 | $h.each(customHeaders, function(k,v) { 888 | $.xhr.setRequestHeader(k, v); 889 | }); 890 | 891 | if ($.getOpt('chunkFormat') == 'blob') { 892 | $.xhr.send(data); 893 | } 894 | }; 895 | $.abort = function(){ 896 | // Abort and reset 897 | if($.xhr) $.xhr.abort(); 898 | $.xhr = null; 899 | }; 900 | $.status = function(){ 901 | // Returns: 'pending', 'uploading', 'success', 'error' 902 | if($.pendingRetry) { 903 | // if pending retry then that's effectively the same as actively uploading, 904 | // there might just be a slight delay before the retry starts 905 | return('uploading'); 906 | } else if($.markComplete) { 907 | return 'success'; 908 | } else if(!$.xhr) { 909 | return('pending'); 910 | } else if($.xhr.readyState<4) { 911 | // Status is really 'OPENED', 'HEADERS_RECEIVED' or 'LOADING' - meaning that stuff is happening 912 | return('uploading'); 913 | } else { 914 | if($.xhr.status == 200 || $.xhr.status == 201) { 915 | // HTTP 200, 201 (created) 916 | return('success'); 917 | } else if($h.contains($.getOpt('permanentErrors'), $.xhr.status) || $.retries >= $.getOpt('maxChunkRetries')) { 918 | // HTTP 400, 404, 409, 415, 500, 501 (permanent error) 919 | return('error'); 920 | } else { 921 | // this should never happen, but we'll reset and queue a retry 922 | // a likely case for this would be 503 service unavailable 923 | $.abort(); 924 | return('pending'); 925 | } 926 | } 927 | }; 928 | $.message = function(){ 929 | return($.xhr ? $.xhr.responseText : ''); 930 | }; 931 | $.progress = function(relative){ 932 | if(typeof(relative)==='undefined') relative = false; 933 | var factor = (relative ? ($.endByte-$.startByte)/$.fileObjSize : 1); 934 | if($.pendingRetry) return(0); 935 | if((!$.xhr || !$.xhr.status) && !$.markComplete) factor*=.95; 936 | var s = $.status(); 937 | switch(s){ 938 | case 'success': 939 | case 'error': 940 | return(1*factor); 941 | case 'pending': 942 | return(0*factor); 943 | default: 944 | return($.loaded/($.endByte-$.startByte)*factor); 945 | } 946 | }; 947 | return(this); 948 | } 949 | 950 | // QUEUE 951 | $.uploadNextChunk = function(){ 952 | var found = false; 953 | 954 | // In some cases (such as videos) it's really handy to upload the first 955 | // and last chunk of a file quickly; this let's the server check the file's 956 | // metadata and determine if there's even a point in continuing. 957 | if ($.getOpt('prioritizeFirstAndLastChunk')) { 958 | $h.each($.files, function(file){ 959 | if(file.chunks.length && file.chunks[0].status()=='pending' && file.chunks[0].preprocessState === 0) { 960 | file.chunks[0].send(); 961 | found = true; 962 | return(false); 963 | } 964 | if(file.chunks.length>1 && file.chunks[file.chunks.length-1].status()=='pending' && file.chunks[file.chunks.length-1].preprocessState === 0) { 965 | file.chunks[file.chunks.length-1].send(); 966 | found = true; 967 | return(false); 968 | } 969 | }); 970 | if(found) return(true); 971 | } 972 | 973 | // Now, simply look for the next, best thing to upload 974 | $h.each($.files, function(file){ 975 | found = file.upload(); 976 | if(found) return(false); 977 | }); 978 | if(found) return(true); 979 | 980 | // The are no more outstanding chunks to upload, check is everything is done 981 | var outstanding = false; 982 | $h.each($.files, function(file){ 983 | if(!file.isComplete()) { 984 | outstanding = true; 985 | return(false); 986 | } 987 | }); 988 | if(!outstanding) { 989 | // All chunks have been uploaded, complete 990 | $.fire('complete'); 991 | } 992 | return(false); 993 | }; 994 | 995 | 996 | // PUBLIC METHODS FOR RESUMABLE.JS 997 | $.assignBrowse = function(domNodes, isDirectory){ 998 | if(typeof(domNodes.length)=='undefined') domNodes = [domNodes]; 999 | $h.each(domNodes, function(domNode) { 1000 | var input; 1001 | if(domNode.tagName==='INPUT' && domNode.type==='file'){ 1002 | input = domNode; 1003 | } else { 1004 | input = document.createElement('input'); 1005 | input.setAttribute('type', 'file'); 1006 | input.style.display = 'none'; 1007 | domNode.addEventListener('click', function(){ 1008 | input.style.opacity = 0; 1009 | input.style.display='block'; 1010 | input.focus(); 1011 | input.click(); 1012 | input.style.display='none'; 1013 | }, false); 1014 | domNode.appendChild(input); 1015 | } 1016 | var maxFiles = $.getOpt('maxFiles'); 1017 | if (typeof(maxFiles)==='undefined'||maxFiles!=1){ 1018 | input.setAttribute('multiple', 'multiple'); 1019 | } else { 1020 | input.removeAttribute('multiple'); 1021 | } 1022 | if(isDirectory){ 1023 | input.setAttribute('webkitdirectory', 'webkitdirectory'); 1024 | } else { 1025 | input.removeAttribute('webkitdirectory'); 1026 | } 1027 | var fileTypes = $.getOpt('fileType'); 1028 | if (typeof (fileTypes) !== 'undefined' && fileTypes.length >= 1) { 1029 | input.setAttribute('accept', fileTypes.map(function (e) { 1030 | e = e.replace(/\s/g, '').toLowerCase(); 1031 | if(e.match(/^[^.][^/]+$/)){ 1032 | e = '.' + e; 1033 | } 1034 | return e; 1035 | }).join(',')); 1036 | } 1037 | else { 1038 | input.removeAttribute('accept'); 1039 | } 1040 | // When new files are added, simply append them to the overall list 1041 | input.addEventListener('change', function(e){ 1042 | appendFilesFromFileList(e.target.files,e); 1043 | var clearInput = $.getOpt('clearInput'); 1044 | if (clearInput) { 1045 | e.target.value = ''; 1046 | } 1047 | }, false); 1048 | }); 1049 | }; 1050 | $.assignDrop = function(domNodes){ 1051 | if(typeof(domNodes.length)=='undefined') domNodes = [domNodes]; 1052 | 1053 | $h.each(domNodes, function(domNode) { 1054 | domNode.addEventListener('dragover', onDragOverEnter, false); 1055 | domNode.addEventListener('dragenter', onDragOverEnter, false); 1056 | domNode.addEventListener('dragleave', onDragLeave, false); 1057 | domNode.addEventListener('drop', onDrop, false); 1058 | }); 1059 | }; 1060 | $.unAssignDrop = function(domNodes) { 1061 | if (typeof(domNodes.length) == 'undefined') domNodes = [domNodes]; 1062 | 1063 | $h.each(domNodes, function(domNode) { 1064 | domNode.removeEventListener('dragover', onDragOverEnter); 1065 | domNode.removeEventListener('dragenter', onDragOverEnter); 1066 | domNode.removeEventListener('dragleave', onDragLeave); 1067 | domNode.removeEventListener('drop', onDrop); 1068 | }); 1069 | }; 1070 | $.isUploading = function(){ 1071 | var uploading = false; 1072 | $h.each($.files, function(file){ 1073 | if (file.isUploading()) { 1074 | uploading = true; 1075 | return(false); 1076 | } 1077 | }); 1078 | return(uploading); 1079 | }; 1080 | $.upload = function(){ 1081 | // Make sure we don't start too many uploads at once 1082 | if($.isUploading()) return; 1083 | // Kick off the queue 1084 | $.fire('uploadStart'); 1085 | for (var num=1; num<=$.getOpt('simultaneousUploads'); num++) { 1086 | $.uploadNextChunk(); 1087 | } 1088 | }; 1089 | $.pause = function(){ 1090 | // Resume all chunks currently being uploaded 1091 | $h.each($.files, function(file){ 1092 | file.abort(); 1093 | }); 1094 | $.fire('pause'); 1095 | }; 1096 | $.cancel = function(){ 1097 | $.fire('beforeCancel'); 1098 | for(var i = $.files.length - 1; i >= 0; i--) { 1099 | $.files[i].cancel(); 1100 | } 1101 | $.fire('cancel'); 1102 | }; 1103 | $.progress = function(){ 1104 | var totalDone = 0; 1105 | var totalSize = 0; 1106 | // Resume all chunks currently being uploaded 1107 | $h.each($.files, function(file){ 1108 | totalDone += file.progress()*file.size; 1109 | totalSize += file.size; 1110 | }); 1111 | return(totalSize>0 ? totalDone/totalSize : 0); 1112 | }; 1113 | $.addFile = function(file, event){ 1114 | appendFilesFromFileList([file], event); 1115 | }; 1116 | $.addFiles = function(files, event){ 1117 | appendFilesFromFileList(files, event); 1118 | }; 1119 | $.removeFile = function(file){ 1120 | for(var i = $.files.length - 1; i >= 0; i--) { 1121 | if($.files[i] === file) { 1122 | $.files.splice(i, 1); 1123 | } 1124 | } 1125 | }; 1126 | $.getFromUniqueIdentifier = function(uniqueIdentifier){ 1127 | var ret = false; 1128 | $h.each($.files, function(f){ 1129 | if(f.uniqueIdentifier==uniqueIdentifier) ret = f; 1130 | }); 1131 | return(ret); 1132 | }; 1133 | $.getSize = function(){ 1134 | var totalSize = 0; 1135 | $h.each($.files, function(file){ 1136 | totalSize += file.size; 1137 | }); 1138 | return(totalSize); 1139 | }; 1140 | $.handleDropEvent = function (e) { 1141 | onDrop(e); 1142 | }; 1143 | $.handleChangeEvent = function (e) { 1144 | appendFilesFromFileList(e.target.files, e); 1145 | e.target.value = ''; 1146 | }; 1147 | $.updateQuery = function(query){ 1148 | $.opts.query = query; 1149 | }; 1150 | 1151 | return(this); 1152 | }; 1153 | 1154 | 1155 | // Node.js-style export for Node and Component 1156 | if (typeof module != 'undefined') { 1157 | // left here for backwards compatibility 1158 | module.exports = Resumable; 1159 | module.exports.Resumable = Resumable; 1160 | } else if (typeof define === "function" && define.amd) { 1161 | // AMD/requirejs: Define the module 1162 | define(function(){ 1163 | return Resumable; 1164 | }); 1165 | } else { 1166 | // Browser: Expose to window 1167 | window.Resumable = Resumable; 1168 | } 1169 | 1170 | })(); 1171 | -------------------------------------------------------------------------------- /public/js/upload.js: -------------------------------------------------------------------------------- 1 | if (document.getElementById('manga-id').type === 'text') { 2 | const mangaInput = document.getElementById('manga-id'); 3 | const awesomplete = new Awesomplete(mangaInput, { 4 | filter: () => true, 5 | sort: false, 6 | list: [] 7 | }); 8 | mangaInput.addEventListener('input', (event) => { 9 | const inputText = event.target.value; 10 | fetch(`/api/autocomplete?q=${inputText}`) 11 | .then(res => res.json()) 12 | .then(json => { 13 | awesomplete.list = json; 14 | awesomplete.evaluate(); 15 | }) 16 | }); 17 | } 18 | 19 | document.getElementById('upload').style.opacity = '20%'; 20 | 21 | var activated = false; 22 | 23 | function update() { 24 | if (activated) { 25 | document.getElementById('upload').innerHTML = ''; 26 | document.getElementById('upload').innerHTML = ` 27 | 30 | 2GB size limit. ZIP with JPEG/PNG/GIF only. Your upload will be sorted by alphanumeric order. 31 | `; 32 | activated = false; 33 | } 34 | 35 | if ( 36 | document.getElementById('chapter').value && 37 | document.getElementById('manga-id').value 38 | ) { 39 | activated = true; 40 | document.getElementById('upload').style.opacity = '100%'; 41 | var r = new Resumable({ 42 | target: '/api/upload', 43 | chunkSize: 1 * 1024 * 1024, 44 | maxFiles: 1, 45 | simultaneousUploads: 10, 46 | testChunks: false, 47 | query:{ 48 | manga_id: document.getElementById('manga-id').value, 49 | source: document.getElementById('source').value, 50 | volume: document.getElementById('volume').value, 51 | chapter: document.getElementById('chapter').value 52 | } 53 | }); 54 | 55 | r.on('fileAdded', function () { 56 | document.getElementById('upload-button').classList.forEach(className => { 57 | if (className.startsWith('btn-')) { 58 | document.getElementById('upload-button').classList.remove(className) 59 | }; 60 | }); 61 | document.getElementById('upload-button').classList.add('btn-warning'); 62 | document.getElementById('upload-button').innerHTML = 'Uploading...'; 63 | r.upload(); 64 | }); 65 | 66 | r.on('fileSuccess', function() { 67 | document.getElementById('upload-button').classList.forEach(className => { 68 | if (className.startsWith('btn-')) { 69 | document.getElementById('upload-button').classList.remove(className) 70 | }; 71 | }); 72 | document.getElementById('upload-button').classList.add('btn-success'); 73 | document.getElementById('upload-button').innerHTML = 'Done!'; 74 | document.getElementById('upload-button').replaceWith(document.getElementById('upload-button').cloneNode(true)) 75 | }); 76 | 77 | r.on('fileError', function(file, msg) { 78 | document.getElementById('upload-button').classList.forEach(className => { 79 | if (className.startsWith('btn-')) { 80 | document.getElementById('upload-button').classList.remove(className) 81 | }; 82 | }); 83 | document.getElementById('upload-button').classList.add('btn-danger'); 84 | document.getElementById('upload-button').innerHTML = msg; 85 | }); 86 | 87 | r.on('fileProgress', function(file) { 88 | document.getElementById('upload-button').innerHTML = `Uploading... (${Math.floor((file.progress() / 1) * 100)}%)`; 89 | }); 90 | 91 | r.assignBrowse(document.getElementById('upload-button')); 92 | r.assignDrop(document.getElementById('upload-button')); 93 | } else { 94 | document.getElementById('upload').style.opacity = '20%'; 95 | } 96 | } 97 | 98 | document.getElementById('manga-id').addEventListener('input', update); 99 | document.getElementById('source').addEventListener('input', update); 100 | document.getElementById('volume').addEventListener('input', update); 101 | document.getElementById('chapter').addEventListener('input', update); -------------------------------------------------------------------------------- /resumable.js: -------------------------------------------------------------------------------- 1 | var fs = require('fs'), path = require('path'), util = require('util'), Stream = require('stream').Stream; 2 | 3 | 4 | 5 | module.exports = resumable = function(temporaryFolder){ 6 | var $ = this; 7 | $.temporaryFolder = temporaryFolder; 8 | $.maxFileSize = null; 9 | $.fileParameterName = 'file'; 10 | 11 | try { 12 | fs.mkdirSync($.temporaryFolder); 13 | }catch(e){} 14 | 15 | 16 | var cleanIdentifier = function(identifier){ 17 | return identifier.replace(/^0-9A-Za-z_-/img, ''); 18 | } 19 | 20 | var getChunkFilename = function(chunkNumber, identifier){ 21 | // Clean up the identifier 22 | identifier = cleanIdentifier(identifier); 23 | // What would the file name be? 24 | return path.join($.temporaryFolder, './resumable-'+identifier+'.'+chunkNumber); 25 | } 26 | 27 | var validateRequest = function(chunkNumber, chunkSize, totalSize, identifier, filename, fileSize){ 28 | // Clean up the identifier 29 | identifier = cleanIdentifier(identifier); 30 | 31 | // Check if the request is sane 32 | if (chunkNumber==0 || chunkSize==0 || totalSize==0 || identifier.length==0 || filename.length==0) { 33 | return 'non_resumable_request'; 34 | } 35 | var numberOfChunks = Math.max(Math.floor(totalSize/(chunkSize*1.0)), 1); 36 | if (chunkNumber>numberOfChunks) { 37 | return 'invalid_resumable_request1'; 38 | } 39 | 40 | // Is the file too big? 41 | if($.maxFileSize && totalSize>$.maxFileSize) { 42 | return 'invalid_resumable_request2'; 43 | } 44 | 45 | if(typeof(fileSize)!='undefined') { 46 | if(chunkNumber1 && chunkNumber==numberOfChunks && fileSize!=((totalSize%chunkSize)+chunkSize)) { 51 | // The chunks in the POST is the last one, and the fil is not the correct size 52 | return 'invalid_resumable_request4'; 53 | } 54 | if(numberOfChunks==1 && fileSize!=totalSize) { 55 | // The file is only a single chunk, and the data size does not fit 56 | return 'invalid_resumable_request5'; 57 | } 58 | } 59 | 60 | return 'valid'; 61 | } 62 | 63 | //'found', filename, original_filename, identifier 64 | //'not_found', null, null, null 65 | $.get = function(req, callback){ 66 | var chunkNumber = req.param('resumableChunkNumber', 0); 67 | var chunkSize = req.param('resumableChunkSize', 0); 68 | var totalSize = req.param('resumableTotalSize', 0); 69 | var identifier = req.param('resumableIdentifier', ""); 70 | var filename = req.param('resumableFilename', ""); 71 | 72 | if(validateRequest(chunkNumber, chunkSize, totalSize, identifier, filename)=='valid') { 73 | var chunkFilename = getChunkFilename(chunkNumber, identifier); 74 | fs.exists(chunkFilename, function(exists){ 75 | if(exists){ 76 | callback('found', chunkFilename, filename, identifier); 77 | } else { 78 | callback('not_found', null, null, null); 79 | } 80 | }); 81 | } else { 82 | callback('not_found', null, null, null); 83 | } 84 | } 85 | 86 | //'partly_done', filename, original_filename, identifier 87 | //'done', filename, original_filename, identifier 88 | //'invalid_resumable_request', null, null, null 89 | //'non_resumable_request', null, null, null 90 | $.post = function(req, callback){ 91 | 92 | var fields = req.body; 93 | var files = req.files; 94 | 95 | var chunkNumber = fields['resumableChunkNumber']; 96 | var chunkSize = fields['resumableChunkSize']; 97 | var totalSize = fields['resumableTotalSize']; 98 | var identifier = cleanIdentifier(fields['resumableIdentifier']); 99 | var filename = fields['resumableFilename']; 100 | 101 | var original_filename = fields['resumableIdentifier']; 102 | 103 | if(!files[$.fileParameterName] || !files[$.fileParameterName].size) { 104 | callback('invalid_resumable_request', null, null, null); 105 | return; 106 | } 107 | var validation = validateRequest(chunkNumber, chunkSize, totalSize, identifier, files[$.fileParameterName].size); 108 | if(validation=='valid') { 109 | var chunkFilename = getChunkFilename(chunkNumber, identifier); 110 | 111 | // Save the chunk (TODO: OVERWRITE) 112 | fs.rename(files[$.fileParameterName].path, chunkFilename, function(){ 113 | 114 | // Do we have all the chunks? 115 | var currentTestChunk = 1; 116 | var numberOfChunks = Math.max(Math.floor(totalSize/(chunkSize*1.0)), 1); 117 | var testChunkExists = function(){ 118 | fs.exists(getChunkFilename(currentTestChunk, identifier), function(exists){ 119 | if(exists){ 120 | currentTestChunk++; 121 | if(currentTestChunk>numberOfChunks) { 122 | callback('done', filename, original_filename, identifier); 123 | } else { 124 | // Recursion 125 | testChunkExists(); 126 | } 127 | } else { 128 | callback('partly_done', filename, original_filename, identifier); 129 | } 130 | }); 131 | } 132 | testChunkExists(); 133 | }); 134 | } else { 135 | callback(validation, filename, original_filename, identifier); 136 | } 137 | } 138 | 139 | 140 | // Pipe chunks directly in to an existsing WritableStream 141 | // r.write(identifier, response); 142 | // r.write(identifier, response, {end:false}); 143 | // 144 | // var stream = fs.createWriteStream(filename); 145 | // r.write(identifier, stream); 146 | // stream.on('data', function(data){...}); 147 | // stream.on('end', function(){...}); 148 | $.write = function(identifier, writableStream, options) { 149 | options = options || {}; 150 | options.end = (typeof options['end'] == 'undefined' ? true : options['end']); 151 | 152 | // Iterate over each chunk 153 | var pipeChunk = function(number) { 154 | 155 | var chunkFilename = getChunkFilename(number, identifier); 156 | fs.exists(chunkFilename, function(exists) { 157 | 158 | if (exists) { 159 | // If the chunk with the current number exists, 160 | // then create a ReadStream from the file 161 | // and pipe it to the specified writableStream. 162 | var sourceStream = fs.createReadStream(chunkFilename); 163 | sourceStream.pipe(writableStream, { 164 | end: false 165 | }); 166 | sourceStream.on('end', function() { 167 | // When the chunk is fully streamed, 168 | // jump to the next one 169 | pipeChunk(number + 1); 170 | }); 171 | } else { 172 | // When all the chunks have been piped, end the stream 173 | if (options.end) writableStream.end(); 174 | if (options.onDone) options.onDone(); 175 | } 176 | }); 177 | } 178 | pipeChunk(1); 179 | } 180 | 181 | 182 | $.clean = function(identifier, options) { 183 | options = options || {}; 184 | 185 | // Iterate over each chunk 186 | var pipeChunkRm = function(number) { 187 | 188 | var chunkFilename = getChunkFilename(number, identifier); 189 | 190 | //console.log('removing pipeChunkRm ', number, 'chunkFilename', chunkFilename); 191 | fs.exists(chunkFilename, function(exists) { 192 | if (exists) { 193 | 194 | console.log('exist removing ', chunkFilename); 195 | fs.unlink(chunkFilename, function(err) { 196 | if (err && options.onError) options.onError(err); 197 | }); 198 | 199 | pipeChunkRm(number + 1); 200 | 201 | } else { 202 | 203 | if (options.onDone) options.onDone(); 204 | 205 | } 206 | }); 207 | } 208 | pipeChunkRm(1); 209 | } 210 | 211 | return $; 212 | } -------------------------------------------------------------------------------- /server.js: -------------------------------------------------------------------------------- 1 | require('dotenv').config() 2 | const path = require('path'); 3 | const flash = require('flash'); 4 | const StreamZip = require('node-stream-zip'); 5 | const express = require('express'); 6 | const bodyParser = require('body-parser'); 7 | const resumable = require('./resumable')('/tmp'); 8 | const multipart = require('connect-multiparty'); 9 | const xss = require('xss'); 10 | const home = require('./views/home'); 11 | const upload = require('./views/upload'); 12 | const manga = require('./views/manga'); 13 | const reader = require('./views/reader'); 14 | const user = require('./views/user'); 15 | const create = require('./views/create'); 16 | const hasha = require('hasha') 17 | const read_chunk = require('read-chunk'); 18 | const img_size = require('image-size') 19 | const img_type = require('image-type') 20 | const yazl = require('yazl'); 21 | const crypto = require('crypto'); 22 | const Promise = require('bluebird'); 23 | const fs = require('fs-extra') 24 | const multer = require('multer'); 25 | const bcrypt = require('bcrypt'); 26 | const { db } = require('./db'); 27 | const cookieSession = require('cookie-session'); 28 | const login = require('./views/login'); 29 | const register = require('./views/register'); 30 | 31 | const { promisify } = require('util') 32 | const sizeOf = promisify(img_size) 33 | 34 | const file_upload = multer({ 35 | storage: multer.diskStorage({ 36 | destination: path.join(process.env.FILES_ROOT, 'assets', 'temp') 37 | }), 38 | limits: { 39 | files: 2, 40 | fileSize: 5000000000 // 5GB 41 | }, 42 | fileFilter: (_, file, cb) => { 43 | const allowed_mimes = [ 44 | 'image/jpeg', 45 | 'image/png', 46 | 'application/x-zip-compressed', 47 | 'application/zip' 48 | ] 49 | cb(null, allowed_mimes.includes(file.mimetype)) 50 | } 51 | }); 52 | 53 | express() 54 | .use(cookieSession({ 55 | name: 'session', 56 | secret: process.env.SECRET 57 | })) 58 | .use(flash()) 59 | .use(bodyParser.urlencoded({ extended: false })) 60 | .use(bodyParser.json()) 61 | .use(express.static('public')) 62 | .use('/assets', express.static(path.join(process.env.FILES_ROOT, 'assets'))) 63 | .get('/*', function(req, res, next) { 64 | req.session.flash = []; 65 | next(); 66 | }) 67 | .get('/', async (req, res) => { 68 | let query = 'SELECT * FROM manga '; 69 | let params = []; 70 | if (req.query.q) { 71 | query += `WHERE to_tsvector('english', eng_title || ' ' || romaji_title || ' ' || author || ' ' || artist || ' ' || romaji_title) @@ websearch_to_tsquery($1) `; 72 | params.push(req.query.q) 73 | } 74 | query += 'LIMIT 25'; 75 | 76 | const results = await db.query(query, params); 77 | res.send(home({ 78 | req: req, 79 | results: results.rows, 80 | flash: res.locals.flash 81 | })) 82 | }) 83 | .get('/users/:id', async (req, res) => { 84 | const account_results = await db.query('SELECT * FROM accounts WHERE id = $1', [req.params.id]); 85 | if (!account_results.rows.length) return res.flash(`That user doesn't exist.`).redirect('back'); 86 | 87 | const upload_results = await db.query('SELECT * FROM uploads WHERE uploader = $1', [req.params.id]); 88 | 89 | const manga_results = await Promise.map(upload_results.rows, async upload => { 90 | const account = await db.query('SELECT * FROM manga WHERE id = $1', [upload.manga_id]) 91 | return account.rows[0] 92 | }) 93 | 94 | res.send(user({ 95 | req: req, 96 | account: account_results.rows[0], 97 | uploads: upload_results.rows, 98 | manga: manga_results, 99 | flash: res.locals.flash 100 | })) 101 | }) 102 | .get('/manga/:id', async (req, res) => { 103 | const results = await db.query('SELECT * FROM manga WHERE id = $1', [req.params.id]); 104 | const upload_results = await db.query('SELECT * FROM uploads WHERE manga_id = $1', [req.params.id]); 105 | 106 | const uploader_results = await Promise.map(upload_results.rows, async upload => { 107 | if (upload.uploader > 0) { 108 | const account = await db.query('SELECT * FROM accounts WHERE id = $1', [upload.uploader]) 109 | return account.rows[0].username 110 | } else { 111 | return null; 112 | } 113 | }) 114 | 115 | res.send(manga({ 116 | req: req, 117 | results: results.rows, 118 | uploads: upload_results.rows.sort((a, b) => a['volume_id'] - b['volume_id'] || a['chapter_id'] - b['chapter_id']), 119 | uploaders: uploader_results, 120 | flash: res.locals.flash 121 | })) 122 | }) 123 | .get('/release/:id', (req, res) => { 124 | res.send(reader({ req: req })); 125 | }) 126 | .get('/upload', (req, res) => { 127 | if (!req.session || !req.session.account_id) return res.redirect('/login') 128 | return res.send(upload({ 129 | req: req, 130 | flash: res.locals.flash 131 | })) 132 | }) 133 | .get('/create', (req, res) => { 134 | if (!req.session || !req.session.account_id) return res.redirect('/login') 135 | return res.send(create({ 136 | req: req, 137 | flash: res.locals.flash 138 | })) 139 | }) 140 | .get('/login', (req, res) => { 141 | res.send(login({ 142 | req: req, 143 | flash: res.locals.flash 144 | })) 145 | }) 146 | .get('/register', (req, res) => res.send(register({ 147 | req: req, 148 | flash: res.locals.flash 149 | }))) 150 | .get('/download/:id', async (req, res) => { 151 | const zip = new yazl.ZipFile(); 152 | const upload_rows = await db.query('SELECT * FROM uploads WHERE id = $1', [req.params.id]); 153 | if (!upload_rows.rows.length) return res.sendStatus(404); 154 | await Promise.mapSeries(upload_rows.rows[0].images, async (image, i) => { 155 | const buffer = await read_chunk(path.join(process.env.FILES_ROOT, 'assets', image), 0, img_type.minimumBytes) 156 | const _img_type = img_type(buffer); 157 | zip.addFile(path.join(process.env.FILES_ROOT, 'assets', image), (i + 1) + '.' + _img_type.ext); 158 | }); 159 | zip.end(); 160 | zip.outputStream.pipe(res); 161 | }) 162 | .post('/api/upload', multipart(), async (req, res) => { 163 | if (!req.session.account_id) return res.sendStatus(401); 164 | if (!req.body.manga_id) return res.status(415).send('Missing manga ID.'); 165 | if (!req.body.chapter) return res.status(415).send('Missing chapter.'); 166 | if (!req.files.file) return res.status(415).send('Missing file.') 167 | 168 | resumable.post(req, (status, filename, original_filename, identifier) => { 169 | if (status === 'done') { 170 | const stream = fs.createWriteStream('/tmp/' + filename); 171 | resumable.write(identifier, stream); 172 | stream.once('finish', async () => { 173 | const file_path = '/tmp/' + filename; 174 | let manga_id = parseInt(req.body.manga_id); 175 | const zip = new StreamZip.async({ file: file_path }); 176 | const entries = await zip.entries(); 177 | const sorted_entries = Object.values(entries) 178 | .filter(entry => !entry.isDirectory) 179 | .map(entry => entry.name) 180 | .sort(); 181 | 182 | const hashed_entries = await Promise.mapSeries(sorted_entries, async entry => { 183 | const temp_name = crypto.randomBytes(5).toString('hex'); 184 | await zip.extract(entry, path.join(process.env.FILES_ROOT, 'assets', 'temp', temp_name)); 185 | const buffer = await read_chunk(path.join(process.env.FILES_ROOT, 'assets', 'temp', temp_name), 0, img_type.minimumBytes) 186 | const _img_type = img_type(buffer); 187 | if (!_img_type) return; 188 | if (!/(gif|jpe?g|png)/i.test(_img_type.ext)) return; 189 | const dimensions = await sizeOf(path.join(process.env.FILES_ROOT, 'assets', 'temp', temp_name)); 190 | if (dimensions.width > 10000 || dimensions.height > 10000) return res.status(415).send('There was an image in your ZIP that was too large. Resolution limit is 10000x10000.'); 191 | const hash = await hasha.fromFile(path.join(process.env.FILES_ROOT, 'assets', 'temp', temp_name), { algorithm: 'md5' }); 192 | 193 | await fs.move(path.join(process.env.FILES_ROOT, 'assets', 'temp', temp_name), path.join(process.env.FILES_ROOT, 'assets', hash + '.' + _img_type.ext)) 194 | .catch(() => {}) 195 | await fs.remove(path.join(process.env.FILES_ROOT, 'assets', 'temp', temp_name)) 196 | return hash + '.' + _img_type.ext 197 | }) 198 | 199 | await zip.close(); 200 | await fs.remove(file_path); 201 | 202 | const schema = { 203 | manga_id: manga_id, 204 | volume_id: req.body.volume || 0, 205 | chapter_id: req.body.chapter, 206 | source: xss(req.body.source), 207 | uploader: req.session.account_id, 208 | images: hashed_entries 209 | } 210 | 211 | await db.query(`INSERT INTO uploads (${Object.keys(schema).join(', ')}) VALUES (${Object.values(schema).map((_, i) => `$${i + 1}`).join(', ')})`, Object.values(schema)) 212 | res.send(status) 213 | }); 214 | } else { 215 | res.send(status) 216 | } 217 | }) 218 | }) 219 | .post('/api/create', file_upload.single('cover'), async (req, res) => { 220 | if (!req.file) return res.flash('Missing cover image.').redirect('back'); 221 | const buffer = await read_chunk(req.file.path, 0, img_type.minimumBytes) 222 | const _img_type = img_type(buffer); 223 | if (!_img_type) return res.flash('That manga cover was not an image.').redirect('back'); 224 | if (!/(gif|jpe?g|png)/i.test(_img_type.ext)) return res.flash('That manga cover was not a supported image. JPG/GIF/PNG only.').redirect('back'); 225 | const dimensions = await sizeOf(req.file.path); 226 | if (dimensions.width > 10000 || dimensions.height > 10000) return res.flash('That manga cover was too large. Resolution limit is 10000x10000.').redirect('back'); 227 | const cover_hash = await hasha.fromFile(req.file.path, { algorithm: 'md5' }); 228 | await fs.move(req.file.path, path.join(process.env.FILES_ROOT, 'assets', cover_hash + '.' + _img_type.ext)) 229 | .catch(() => {}) 230 | 231 | const schema = { 232 | eng_title: xss(req.body.eng_title), 233 | romaji_title: xss(req.body.romaji_title), 234 | author: xss(req.body.author), 235 | artist: xss(req.body.artist), 236 | description: xss(req.body.description), 237 | cover: cover_hash + '.' + _img_type.ext, 238 | } 239 | 240 | const manga_results = await db.query(`INSERT INTO manga (${Object.keys(schema).join(', ')}) VALUES (${Object.values(schema).map((_, i) => `$${i + 1}`).join(', ')}) returning id`, Object.values(schema)) 241 | manga_id = manga_results.rows[0].id; 242 | 243 | res.flash('Success!').redirect('/manga/' + manga_id) 244 | }) 245 | .get('/api/logout', (req, res) => { 246 | req.session.account_id = null; 247 | res.redirect('back'); 248 | }) 249 | .post('/api/register', async (req, res) => { 250 | if (!req.body.username || !req.body.password || !req.body.confirm) return res.sendStatus(401); 251 | 252 | const username = xss(req.body.username); 253 | const password = req.body.password; 254 | const c_password = req.body.confirm; 255 | 256 | if (username.trim() === '') return res.flash('Username cannot be empty.').redirect('back'); 257 | if (password.trim() === '') return res.flash('Password cannot be empty.').redirect('back'); 258 | if (password !== c_password) return res.flash('Passwords do not match.').redirect('back'); 259 | const account_results = await db.query('SELECT * FROM accounts WHERE username = $1', [username]); 260 | if (account_results.rows.length) return res.flash('Username taken.').redirect('back'); 261 | 262 | const pw_hash = await bcrypt.hash(password, 10); 263 | const account_data = { 264 | username: username, 265 | password_hash: pw_hash 266 | } 267 | const id_data = await db.query(`INSERT INTO accounts (${Object.keys(account_data).join(', ')}) VALUES (${Object.values(account_data).map((_, i) => `$${i + 1}`).join(', ')}) returning id`, Object.values(account_data)) 268 | req.session.account_id = id_data.rows[0].id 269 | 270 | res.flash('Successfully registered. Welcome to Ramune, ' + username + '!').redirect('/') 271 | }) 272 | .post('/api/login', async (req, res) => { 273 | const username = req.body.username; 274 | const password = req.body.password; 275 | 276 | const account_results = await db.query('SELECT * FROM accounts WHERE username = $1', [username]); 277 | if (!account_results.rows.length) return res.flash('Incorrect username or password.').redirect('back'); 278 | 279 | const is_password_correct = await bcrypt.compare(password, account_results.rows[0].password_hash); 280 | if (!is_password_correct) return res.flash('Incorrect username or password.').redirect('back'); 281 | 282 | req.session.account_id = account_results.rows[0].id; 283 | res.flash('Successfully logged in!').redirect('/') 284 | }) 285 | .get('/api/autocomplete', async (req, res) => { 286 | if (!req.query.q) return res.sendStatus(400); 287 | const manga_rows = await db.query(`SELECT * FROM manga WHERE to_tsvector('english', eng_title || ' ' || romaji_title || ' ' || author || ' ' || artist || ' ' || romaji_title) @@ websearch_to_tsquery($1) LIMIT 10`, [req.query.q]); 288 | const manga_list = manga_rows.rows.map(row => { 289 | return { 290 | label: row.eng_title, 291 | value: row.id 292 | } 293 | }); 294 | res.json(manga_list); 295 | }) 296 | .get('/api/release/:id', async (req, res) => { 297 | const upload_rows = await db.query('SELECT * FROM uploads WHERE id = $1', [req.params.id]); 298 | res.json(upload_rows.rows); 299 | }) 300 | .get('/api/manga/:id', async (req, res) => { 301 | const manga_rows = await db.query('SELECT * FROM manga WHERE id = $1', [req.params.id]); 302 | res.json(manga_rows.rows); 303 | }) 304 | .get('/api/manga/:id/releases', async (req, res) => { 305 | const manga_rows = await db.query('SELECT * FROM uploads WHERE manga_id = $1', [req.params.id]); 306 | res.json(manga_rows.rows); 307 | }) 308 | .listen(process.env.PORT || 9001) -------------------------------------------------------------------------------- /testing-scripts/populate-manga.js: -------------------------------------------------------------------------------- 1 | const { db } = require('../db'); 2 | (async () => { 3 | const schema = { 4 | eng_title: 'Nichijou', 5 | romaji_title: 'Nichijou', 6 | author: 'Keiichi Arawi', 7 | artist: 'Keiichi Arawi', 8 | description: "While the title suggests a story of simple, everyday school life, the contents are more the opposite. The setting is a strange school where you may see the principal wrestle a deer or a robot's arm hide a rollcake. However there are still normal stories, like making a card castle or taking a test you didn't study for. The art style is cute but mixes with extreme expressions and action sequences for surprising comedy bits.", 9 | cover: 'test.png', 10 | } 11 | 12 | // const schema = { 13 | // eng_title: "Miss Kobayashi's Dragon Maid", 14 | // romaji_title: 'Kobayashi-san Chi no Meidoragon', 15 | // author: 'Coolkyousinnjya', 16 | // description: "As office worker and programmer Kobayashi gets ready for work, she is greeted by a large dragon right outside her front door. The dragon immediately transforms into a human girl in a maid outfit, and introduces herself as Tohru. It turns out, that during a drunken excursion into the mountains the night before, Kobayashi had encountered the dragon, who claimed to have come from another world. Subsequently, Kobayashi had removed a holy sword from Tohru's back, earning her gratitude. With Tohru having no place to stay, Kobayashi offers to let the dragon stay at her home and become her personal maid, to which she agrees.", 17 | // cover: 'anothertest.jpg' 18 | // } 19 | 20 | await db.query(`INSERT INTO manga (${Object.keys(schema).join(', ')}) VALUES (${Object.values(schema).map((_, i) => `$${i + 1}`).join(', ')})`, Object.values(schema)) 21 | })() -------------------------------------------------------------------------------- /testing-scripts/populate-uploads.js: -------------------------------------------------------------------------------- 1 | const { db } = require('../db'); 2 | (async () => { 3 | const schema = { 4 | manga_id: 1, 5 | chapter_id: 1, 6 | source: 'Dekai Manga Archive [Musashi Quality]', 7 | uploader: 0, 8 | images: [ 9 | '001.jpg', 10 | '002.jpg', 11 | '003.jpg', 12 | '004.jpg', 13 | '005.jpg', 14 | '006.jpg', 15 | '007.jpg', 16 | '008.jpg', 17 | '009.jpg', 18 | '010.jpg', 19 | '011.jpg', 20 | '012.jpg', 21 | '013.jpg', 22 | '014.jpg', 23 | '015.jpg', 24 | '016.jpg' 25 | ] 26 | } 27 | 28 | await db.query(`INSERT INTO uploads (${Object.keys(schema).join(', ')}) VALUES (${Object.values(schema).map((_, i) => `$${i + 1}`).join(', ')})`, Object.values(schema)) 29 | })() -------------------------------------------------------------------------------- /views/components/header.js: -------------------------------------------------------------------------------- 1 | module.exports = props => ` 2 | 35 | ` -------------------------------------------------------------------------------- /views/components/shell.js: -------------------------------------------------------------------------------- 1 | const header = require('./header'); 2 | 3 | module.exports = (html, props = {}) => ` 4 | 5 | 6 | 7 | 8 | 9 | ${ props.title ? `${props.title} | Ramune` : 'Ramune'} 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | ${header({ req: props.req })} 22 | ${html} 23 | 24 | 25 | ` -------------------------------------------------------------------------------- /views/create.js: -------------------------------------------------------------------------------- 1 | const shell = require('./components/shell'); 2 | module.exports = (props) => shell(` 3 | ${props.flash.map(flash => ` 4 |
5 | ${flash.message} 6 |
7 |
8 | `).join('')} 9 |
10 |

Submit new manga

11 |
16 | 17 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 46 | 47 | 48 |
49 | Required. JPEG/PNG only.
50 | 51 | 52 |
53 |
54 | `, { req: props.req }) -------------------------------------------------------------------------------- /views/home.js: -------------------------------------------------------------------------------- 1 | const shell = require('./components/shell'); 2 | module.exports = (props) => shell(` 3 | ${props.flash.map(flash => ` 4 |
5 | ${flash.message} 6 |
7 |
8 | `).join('')} 9 |
10 | ${props.results.length ? ` 11 |
12 | ${props.results.map(manga => ` 13 | 14 |
15 |

${manga.eng_title}

16 |
17 | 18 |
19 |
20 |
21 | `).join('')} 22 |
23 | ` : '

No uploads.

'} 24 |
25 | `, { req: props.req }) -------------------------------------------------------------------------------- /views/login.js: -------------------------------------------------------------------------------- 1 | const shell = require('./components/shell') 2 | module.exports = props => shell(` 3 | ${props.flash.map(flash => ` 4 |
5 | ${flash.message} 6 |
7 |
8 | `).join('')} 9 |
10 | 24 |
25 | `, { req: props.req }) -------------------------------------------------------------------------------- /views/manga.js: -------------------------------------------------------------------------------- 1 | const shell = require('./components/shell'); 2 | module.exports = (props) => shell(` 3 | ${props.flash.map(flash => ` 4 |
5 | ${flash.message} 6 |
7 |
8 | `).join('')} 9 |
10 | ${props.results.length ? ` 11 |
12 |
13 | 14 |
15 |
16 |
17 | ${props.results[0].eng_title} 18 | ${props.results[0].romaji_title ? `(${props.results[0].romaji_title})` : ''} 19 | ${props.results[0].japanese_title ? `(${props.results[0].japanese_title})` : ''} 20 |

21 | ${props.results[0].author ? `Author: ${props.results[0].author}
` : ''} 22 | ${props.results[0].artist ? `Artist: ${props.results[0].artist}
` : ''} 23 | Description: ${props.results[0].description} 24 |

25 | ${props.uploads.length ? ` 26 | 27 | 28 | 29 | ` : ` 30 | 31 | `} 32 | 33 | 34 | 35 |
36 |
37 |
38 |
39 | ${props.uploads.length ? ` 40 |

Chapters

41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | ${props.uploads.map((upload, i) => ` 53 | 54 | 86 | 89 | 92 | 95 | 98 | 99 | `).join('')} 100 | 101 |
ChapterGroupSourceUploader
55 | 56 | 57 | 58 | 59 | 62 | 63 | ${props.password || props.req.session.account_id === upload.uploader ? ` 64 | 65 | 68 | 69 | ` : ` 70 | 73 | `} 74 | ${props.req.session.account_id === upload.uploader ? ` 75 | 76 | 79 | 80 | ` : ` 81 | 84 | `} 85 | 87 | ${upload.volume_id && upload.volume_id > 0 ? `Vol. ${upload.volume_id} ` : ''}Ch. ${upload.chapter_id} 88 | 90 | ${upload.group ? `${upload.group}` : 'None'} 91 | 93 | ${upload.source ? `${upload.source}` : 'None'} 94 | 96 | ${props.uploaders[i] ? `${props.uploaders[i]}` : 'System'} 97 |
102 | `: '

No chapters.

'} 103 |
104 |
105 | ` : `

There's nothing here.

`} 106 |
107 | `, { req: props.req }) 108 | -------------------------------------------------------------------------------- /views/reader.js: -------------------------------------------------------------------------------- 1 | module.exports = (props) => ` 2 | 3 | 4 | 5 | 6 | 7 | ${ props.title ? `${props.title} | Ramune` : 'Ramune' } 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 |
20 | 23 | 24 | 25 | 26 | 29 | 32 |
33 |
34 | 35 |
36 | 37 | 38 |
39 | 40 |
41 | End of chapter
42 | 43 |
44 | 45 | 48 | 49 | 50 | 51 | 52 | ` -------------------------------------------------------------------------------- /views/register.js: -------------------------------------------------------------------------------- 1 | const shell = require('./components/shell') 2 | module.exports = props => shell(` 3 | ${props.flash.map(flash => ` 4 |
5 | ${flash.message} 6 |
7 |
8 | `).join('')} 9 |
10 | 26 |
27 | `, { req: props.req }) -------------------------------------------------------------------------------- /views/upload.js: -------------------------------------------------------------------------------- 1 | const shell = require('./components/shell'); 2 | module.exports = (props) => shell(` 3 | ${props.flash.map(flash => ` 4 |
5 | ${flash.message} 6 |
7 |
8 | `).join('')} 9 |
10 |

Upload

11 |
16 |

Manga

17 | ${props.req.query.id ? ` 18 | 19 | ` : ` 20 | 21 |
29 | Or submit a new manga! 30 | `} 31 | 32 | 33 |
39 | 40 | If this upload is a mirror from a different website, or created by a group you aren't a part of, optionally credit them in the field above.
41 |

42 | 43 |

Volume/Chapter

44 | 45 |
46 | Leave blank if this upload is not part of a volume. 47 | 48 | 49 |
50 |
51 | 54 | 2GB size limit. ZIP with JPEG/PNG/GIF only. Your upload will be sorted by alphanumeric order. 55 |
56 |
57 | 58 | 59 | `, { req: props.req }) -------------------------------------------------------------------------------- /views/user.js: -------------------------------------------------------------------------------- 1 | const shell = require('./components/shell'); 2 | module.exports = (props) => shell(` 3 |
4 |
5 |
6 |

${props.account.username.endsWith('s') ? props.account.username + '\'' : props.account.username + '\'s'} uploads

7 |
8 |
9 |
10 |
11 | ${props.uploads.length ? ` 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | ${props.uploads.map((upload, i) => ` 24 | 25 | 28 | 31 | 34 | 37 | 40 | 41 | `).join('')} 42 | 43 |
MangaChapterGroupSourceUploader
26 | ${props.manga[i].eng_title} 27 | 29 | ${upload.volume_id && upload.volume_id > 0 ? `Vol. ${upload.volume_id} ` : ''}Ch. ${upload.chapter_id} 30 | 32 | ${upload.group ? `${upload.group}` : 'None'} 33 | 35 | ${upload.source ? `${upload.source}` : 'None'} 36 | 38 | ${props.account.username} 39 |
44 | `: '

No chapters.

'} 45 |
46 |
47 |
48 | `, { req: props.req }) 49 | --------------------------------------------------------------------------------