├── .gitignore ├── LICENSE ├── README.md ├── TODO ├── librarian └── librarianlib ├── __init__.py ├── ebook_search.py ├── epub.py ├── epub_metadata.py ├── librarian_server.py ├── library.py └── openlibrary_search.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | *.yaml 3 | *.json 4 | *.tar.gz 5 | *.db 6 | *.dump 7 | *.opf 8 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | **NOTE**: if you are looking for LibrarianSync, it has been moved to [its own repository](https://github.com/barsanuphe/librariansync). 2 | 3 | # Librarian 4 | 5 | Epub Ebook managerwhich can import epub ebooks, rename them from metadata, convert them to mobi, 6 | and sync with a Kindle Paperwhite. 7 | It can also run queries using all metadata, and add and remove tags which 8 | can be converted to Kindle collections with [LibrarianSync](https://github.com/barsanuphe/librariansync). 9 | There is experimental support to write metadata, and to serve ebooks over http 10 | to LibrarianSync on a Kindle. 11 | It is in early stages. See disclaimer below. 12 | 13 | ## Quick disclaimer about librarian 14 | 15 | *librarian* is in development and not even close to being stable. This means: 16 | 17 | - Expect the commands and database formats to change any time. 18 | - Keep backups of your ebooks, both on your computer and your Kindle. 19 | - *librarian* is tested on Archlinux, it should work on other distributions/platforms, 20 | but then again it may not because reasons. 21 | 22 | ## Table of Contents 23 | 24 | - [Requirements](#requirements) 25 | - [Configuration](#configuration) 26 | - [Usage](#usage) 27 | - [Example Commands](#example-commands) 28 | 29 | ## Librarian 30 | 31 | 32 | ### Requirements 33 | 34 | - Python 3 35 | - Calibre (librarian relies on ebook-convert, which are part of Calibre) 36 | - pyyaml 37 | - python-lxml 38 | - python-colorama (optional) 39 | 40 | ### Configuration 41 | 42 | *librarian* uses several special folders, as specified in the configuration 43 | file *librarian.yaml*: 44 | 45 | - *library_root*: where all ebooks are kept. More specifically, it will be divided in subfolders: 46 | - **import**: temporary place to dump ebooks before they are imported into the library proper 47 | - **imported**: when an ebook is imported (and renamed), a copy of the original is optionnally placed here. 48 | - **kindle**: a mirror of the library, with all epubs converted into mobis. This is what will be synced with the Kindle. 49 | - **library**: where all imported ebooks are safely kept. 50 | - *kindle_root*: where the Kindle is mounted when it is connected by USB. This may depend on your Linux distribution. 51 | - *scrape_root*: if you have ebooks lying around on a drive at random, for example, scraping it will copy them all into the import subfolder. 52 | 53 | An example configuration would be: 54 | 55 | author_aliases: 56 | Alexandre Dumas Père: Alexandre Dumas 57 | China Mieville: China Miéville 58 | Richard Morgan: Richard K. Morgan 59 | backup_imported_ebooks: true 60 | interactive: true 61 | ebook_filename_template: $a/$a ($y) $t 62 | kindle_documents_subdir: library 63 | kindle_root: /run/media/login/Kindle 64 | library_root: /home/login/ebooks 65 | scrape_root: /home/login/documents 66 | server: 67 | IP: 192.168.0.5 68 | port: 13698 69 | 70 | *kindle_root* and *library_root* are mandatory. The rest is optional. 71 | 72 | *interactive* decides if importing ebooks is automatic or if manual confirmation 73 | is required for each book. 74 | 75 | *ebook_filename_template* is the template for epub filenames inside the library, 76 | by default '$a/$a ($y) $t'. 77 | Available information are: *$a* (author), *$y* (year), *$t* (title), *$s* (series), 78 | *$i* (series_index). 79 | Refreshing the database automatically applies the template. 80 | 81 | The *server* configuration allows *librarian* to serve a selection of ebooks over 82 | http. It is then possible to use a well configured *LibrarianSync* to automatically 83 | connect, download the ebooks, and update the Kindle collections accordingly. 84 | 85 | **Note**: Only epub ebooks can be added to the library. They are converted to 86 | mobi while syncing with the Kindle. 87 | If mobi ebooks are present in the *import* folder, they are converted to epub, 88 | then imported. Both the original mobi and the resulting epub are then backed up 89 | in the *imported* folder. 90 | 91 | The library database is kept in a Python dictionary saved and loaded as a json 92 | file. 93 | 94 | ### Usage 95 | 96 | Note: if python2 is the default version on your Linux distribution, launch with *python3 librarian*. 97 | 98 | $ librarian -h 99 | usage: librarian [-h] [-i] [-r] [--scrape] [-s [PATH]] [-k] [--serve] 100 | [-f [STRING [STRING ...]]] [-l [STRING [STRING ...]]] 101 | [-x STRING [STRING ...]] [-t TAG [TAG ...]] 102 | [-d TAG [TAG ...]] [-c [COLLECTION]] 103 | [--progress {read,reading,unread}] 104 | [--info [METADATA_FIELD [METADATA_FIELD ...]]] 105 | [--openlibrary] 106 | [-w METADATA_FIELD_AND_VALUE [METADATA_FIELD_AND_VALUE ...]] 107 | [--config CONFIG_FILE] [--readable-db] 108 | 109 | Librarian. A very early version of it. 110 | 111 | optional arguments: 112 | -h, --help show this help message and exit 113 | 114 | Library management: 115 | Import, analyze, and sync with Kindle. 116 | 117 | -i, --import import ebooks 118 | -r, --refresh refresh library 119 | --scrape scrape for ebooks 120 | -s [PATH], --sync [PATH] 121 | sync library (or a subset with --filter or --list) 122 | -k, --kindle when syncing, sync to kindle 123 | --serve serve filtered ebooks over http 124 | 125 | Tagging: 126 | Search and tag ebooks. For --list, --filter and --exclude, STRING can 127 | begin with author:, title:, tag:, series: or progress: for a more precise 128 | search. 129 | 130 | -f [STRING [STRING ...]], --filter [STRING [STRING ...]] 131 | list ebooks in library matching ALL patterns 132 | -l [STRING [STRING ...]], --list [STRING [STRING ...]] 133 | list ebooks in library matching ANY pattern 134 | -x STRING [STRING ...], --exclude STRING [STRING ...] 135 | exclude ALL STRINGS from current list/filter 136 | -t TAG [TAG ...], --add-tag TAG [TAG ...] 137 | tag listed ebooks in library 138 | -d TAG [TAG ...], --delete-tag TAG [TAG ...] 139 | remove tag(s) from listed ebooks in library 140 | -c [COLLECTION], --collections [COLLECTION] 141 | list all tags or ebooks with a given tag or "untagged" 142 | --progress {read,reading,unread} 143 | Set filtered ebooks as read. 144 | 145 | Metadata: 146 | Display and write epub metadata. 147 | 148 | --info [METADATA_FIELD [METADATA_FIELD ...]] 149 | Display all or a selection of metadata tags for 150 | filtered ebooks. 151 | --openlibrary Search OpenLibrary for filtered ebooks. 152 | -w METADATA_FIELD_AND_VALUE [METADATA_FIELD_AND_VALUE ...], --write-metadata METADATA_FIELD_AND_VALUE [METADATA_FIELD_AND_VALUE ...] 153 | Write one or several field:value metadata. 154 | 155 | Configuration: 156 | Configuration options. 157 | 158 | --config CONFIG_FILE Use an alternative configuration file. 159 | --readable-db Save the database in somewhat readable form. 160 | 161 | 162 | While syncing with Kindle, *librarian* will keep track of previous conversions 163 | to the mobi format (for epub ebooks), and of previously synced ebooks on the Kindle, 164 | and will try to work no more than necessary. 165 | 166 | **Syncing** means: copy the mobi versions of all filtered ebooks to the Kindle, 167 | and *remove from the Kindle all previously existing mobis not presently filtered*. 168 | Do make sure the *kindle_documents_subdir* of the configuration file only contains 169 | ebooks that are inside the library. 170 | 171 | **Writing metadata is very, very experimental.** 172 | 173 | Note that if books are imported successfully, a refresh is automatically added. 174 | Also, only .epubs and .mobis are imported/scraped, with a preference for .epub 175 | when both formats are available. 176 | 177 | ### Example commands 178 | 179 | Scrape a directory (specified in the configuration file) and automatically add 180 | to the library everything that was found: 181 | 182 | ./librarian --scrape -i 183 | 184 | Refresh the library after adding "Richard Morgan: Richard K. Morgan" to the 185 | author aliases in the configuration file, so that all "Richard Morgan" ebooks get 186 | renamed as "Richard K. Morgan": 187 | 188 | ./librarian -r 189 | 190 | List all tags and the number of ebooks for each: 191 | 192 | ./librarian -c 193 | 194 | List all yet untagged ebooks: 195 | 196 | ./librarian -c untagged 197 | 198 | Display all ebooks in the library with the tag *sf/space opera*: 199 | 200 | ./librarian -f "tag:sf/space opera" 201 | 202 | or 203 | 204 | ./librarian -c "sf/space opera" 205 | 206 | Display all ebooks in the library with the tag *sf/space opera*, but not the Peter 207 | F. Hamilton books you just read: 208 | 209 | ./librarian -f "tag:sf/space opera" -x hamilton 210 | 211 | Display all ebooks in the library with the tag *sf/space opera*, but not the Peter 212 | F. Hamilton books you just read, and also everything by Alexandre Dumas: 213 | 214 | ./librarian -l tag:opera dumas -x hamilton 215 | 216 | Tag as *best category* and *random* all ebooks in the library with the tag *sf/space opera*, but not the Peter 217 | F. Hamilton books you just read, and also everything by Alexandre Dumas: 218 | 219 | ./librarian -l tag:opera dumas -x hamilton -t "best category" random 220 | 221 | Change tag from *best category* to *best category!* for all ebooks in the library with the tag *sf/space opera*, but not the Peter 222 | F. Hamilton books you just read, and also everything by Alexandre Dumas: 223 | 224 | ./librarian -l tag:opera dumas -x hamilton -d "best category" -t "best category!" 225 | 226 | Sync to your Kindle all ebooks in the library with the tag *sf/space opera*, but not the Peter 227 | F. Hamilton books you just read, and also everything by Alexandre Dumas: 228 | 229 | ./librarian -l tag:opera dumas -x hamilton -s -k 230 | 231 | Serve over http for your Kindle, all ebooks (in .mobi forma) in the library with 232 | the tag *sf/space opera*, but not the Peter F. Hamilton books you just read, and 233 | also everything by Alexandre Dumas: 234 | 235 | ./librarian -l tag:opera dumas -x hamilton --serve -k 236 | 237 | Display the title and description for all of your Aldous Huxley ebooks: 238 | 239 | ./librarian -f author:huxley --info title description 240 | 241 | Mark all ebooks by Alexandre Dumas as read: 242 | 243 | ./librarian -f author:dumas --progress read 244 | 245 | -------------------------------------------------------------------------------- /TODO: -------------------------------------------------------------------------------- 1 | #TODO: filename template: support for optional parts (ex: "[$s] [#$i]") 2 | #TODO: support for several series? 3 | #TODO: auto-correct option (w/author_aliases) 4 | #TODO: try to query google books too 5 | #TODO: when querying by series, order by series_index 6 | 7 | #TODO: make standalone librarian_server.py 8 | #TODO: documents_subdir in librarian_download ini 9 | 10 | #TODO: Add meta tags: 11 | librarian:series = series, series_index 12 | librarian:tags = tag, tags 13 | librarian:progress = read 14 | librarian:original_year = original_year 15 | 16 | #TODO: 17 | yaml: auto-update-files-metadata = true 18 | -- display diff of changes 19 | 20 | #TODO: checks when using alternative config file -------------------------------------------------------------------------------- /librarian: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | # so that parsing this with python2 does not raise SyntaxError 5 | from __future__ import print_function 6 | 7 | import os 8 | import subprocess 9 | import sys 10 | import traceback 11 | import time 12 | import argparse 13 | import ipaddress 14 | 15 | from librarianlib.library import Library 16 | from librarianlib.ebook_search import list_authors, list_tags 17 | from librarianlib.ebook_search import Search, EvaluateMatch 18 | from librarianlib.openlibrary_search import OpenLibrarySearch 19 | 20 | if sys.version_info < (3, 0, 0): 21 | print("You need python 3.0 or later to run this script.") 22 | sys.exit(-1) 23 | 24 | try: 25 | assert subprocess.call(["ebook-convert", "--version"], 26 | stdout=subprocess.DEVNULL) == 0 27 | except AssertionError as err: 28 | print("Calibre must be installed for epub -> mobi conversions!") 29 | sys.exit(-1) 30 | 31 | try: 32 | import yaml 33 | except Exception as err: 34 | print("pyyaml (for python3) must be installed!") 35 | sys.exit(-1) 36 | 37 | librarian_dir = os.path.dirname(os.path.realpath(__file__)) 38 | 39 | 40 | def open_config(): 41 | # configuration 42 | librarian_dir = os.path.dirname(os.path.realpath(__file__)) 43 | yaml_config = os.path.join(librarian_dir, "librarian.yaml") 44 | assert os.path.exists(yaml_config) 45 | config = yaml.load(open(yaml_config, 'r')) 46 | try: 47 | assert "kindle_root" in config.keys() 48 | assert "library_root" in config.keys() 49 | assert "kindle_documents_subdir" in config.keys() 50 | 51 | config["import_dir"] = os.path.join(config["library_root"], 52 | "import") 53 | config["library_dir"] = os.path.join(config["library_root"], 54 | "library") 55 | config["mobi_dir"] = os.path.join(config["library_root"], 56 | "mobi") 57 | config["imported_dir"] = os.path.join(config["library_root"], 58 | "imported") 59 | config["collections"] = os.path.join(config["library_root"], 60 | "collections.json") 61 | config["kindle_documents"] = os.path.join(config["kindle_root"], 62 | "documents", 63 | "librarian") 64 | config["kindle_extensions"] = os.path.join(config["kindle_root"], 65 | "extensions") 66 | 67 | # create folders if necessary 68 | if not os.path.exists(config["import_dir"]): 69 | os.makedirs(config["import_dir"]) 70 | if not os.path.exists(config["imported_dir"]): 71 | os.makedirs(config["imported_dir"]) 72 | if not os.path.exists(config["library_dir"]): 73 | os.makedirs(config["library_dir"]) 74 | if not os.path.exists(config["mobi_dir"]): 75 | os.makedirs(config["mobi_dir"]) 76 | 77 | if "server" in config.keys(): 78 | # raise ValueError if not valid IP address 79 | ipaddress.ip_address(config["server"]["IP"]) 80 | # same if not int 81 | int(config["server"]["port"]) 82 | if "scrape_root" in config.keys(): 83 | assert os.path.exists(config["scrape_root"]) 84 | if "backup_imported_ebooks" in config.keys(): 85 | assert isinstance(config["backup_imported_ebooks"], bool) 86 | if "author_aliases" in config.keys(): 87 | assert isinstance(config["author_aliases"], dict) 88 | if "interactive" in config.keys(): 89 | assert isinstance(config["interactive"], bool) 90 | if "ebook_filename_template" not in config.keys(): 91 | config["ebook_filename_template"] = "$a/$a ($y) $t" 92 | 93 | except Exception as err: 94 | print("Missing config option: ", err) 95 | raise Exception("Invalid configuration file!") 96 | 97 | return config 98 | 99 | 100 | if __name__ == "__main__": 101 | 102 | start = time.perf_counter() 103 | 104 | parser = argparse.ArgumentParser(description='Librarian. A very early \ 105 | version of it.') 106 | 107 | group_import_export = parser.add_argument_group('Library management', 108 | 'Import, analyze, and sync\ 109 | with Kindle.') 110 | group_import_export.add_argument('-i', 111 | '--import', 112 | dest='import_ebooks', 113 | action='store_true', 114 | default=False, 115 | help='import ebooks') 116 | group_import_export.add_argument('-r', 117 | '--refresh', 118 | dest='refresh', 119 | action='store_true', 120 | default=False, 121 | help='refresh library') 122 | group_import_export.add_argument('--scrape', 123 | dest='scrape', 124 | action='store_true', 125 | default=False, 126 | help='scrape for ebooks') 127 | group_import_export.add_argument('-s', 128 | '--sync', 129 | dest='sync', 130 | action='store', 131 | const=True, 132 | default=False, 133 | nargs='?', 134 | metavar="PATH", 135 | help='sync library (or a subset with \ 136 | --filter or --list)') 137 | group_import_export.add_argument('-k', 138 | '--kindle', 139 | dest='kindle', 140 | action='store_true', 141 | default=False, 142 | help='when syncing, sync to kindle') 143 | group_import_export.add_argument('--serve', 144 | dest='serve', 145 | action='store_true', 146 | default=False, 147 | help='serve filtered ebooks over http') 148 | 149 | group_tagging = parser.add_argument_group( 150 | 'Tagging', 'Search and tag ebooks. For --list, --filter and --exclude,\ 151 | STRING can begin with author:, title:, tag:, series: or progress: for \ 152 | a more precise search.') 153 | group_tagging.add_argument('-f', 154 | '--filter', 155 | dest='filter_ebooks_and', 156 | action='store', 157 | nargs="*", 158 | metavar="STRING", 159 | help='list ebooks in library matching ALL \ 160 | patterns') 161 | group_tagging.add_argument('-l', 162 | '--list', 163 | dest='filter_ebooks_or', 164 | action='store', 165 | nargs="*", 166 | metavar="STRING", 167 | help='list ebooks in library matching ANY \ 168 | pattern') 169 | group_tagging.add_argument('-x', 170 | '--exclude', 171 | dest='filter_exclude', 172 | action='store', 173 | nargs="+", 174 | metavar="STRING", 175 | help='exclude ALL STRINGS from current \ 176 | list/filter') 177 | group_tagging.add_argument('-t', 178 | '--add-tag', 179 | dest='add_tag', 180 | action='store', 181 | nargs="+", 182 | metavar="TAG", 183 | help='tag listed ebooks in library') 184 | group_tagging.add_argument('-d', 185 | '--delete-tag', 186 | dest='delete_tag', 187 | action='store', 188 | nargs="+", 189 | metavar="TAG", 190 | help='remove tag(s) from listed ebooks in \ 191 | library') 192 | group_tagging.add_argument('-c', 193 | '--collections', 194 | dest='collections', 195 | action='store', 196 | nargs='?', 197 | metavar="COLLECTION", 198 | const="", 199 | help='list all tags or ebooks with a given \ 200 | tag or "untagged"') 201 | group_tagging.add_argument('-a', 202 | '--authors', 203 | dest='authors', 204 | action='store', 205 | nargs='?', 206 | metavar="AUTHOR", 207 | const="", 208 | help='list all authors') 209 | group_tagging.add_argument('--progress', 210 | dest='read', 211 | choices=['read', 'reading', 'unread'], 212 | help='Set filtered ebooks as read.') 213 | 214 | group_tagging = parser.add_argument_group('Metadata', 'Display and write\ 215 | epub metadata.') 216 | group_tagging.add_argument('--info', 217 | dest='info', 218 | action='store', 219 | metavar="METADATA_FIELD", 220 | nargs='*', 221 | help='Display all or a selection of metadata \ 222 | tags for filtered ebooks.') 223 | group_tagging.add_argument('--openlibrary', 224 | dest='openlibrary', 225 | action='store_true', 226 | default=False, 227 | help='Search OpenLibrary for filtered ebooks.') 228 | group_tagging.add_argument('-w', 229 | '--write-metadata', 230 | dest='write_metadata', 231 | action='store', 232 | metavar="METADATA_FIELD_AND_VALUE", 233 | nargs='+', 234 | help='Write one or several field:value \ 235 | metadata.') 236 | group_tagging.add_argument('--update-files-metadata', 237 | dest='write_to_file', 238 | action='store_true', 239 | default=False, 240 | help='Write the metada to the ebook file') 241 | 242 | group_tagging = parser.add_argument_group('Configuration', 243 | 'Configuration options.') 244 | group_tagging.add_argument('--config', 245 | dest='config', 246 | action='store', 247 | metavar="CONFIG_FILE", 248 | nargs=1, 249 | help='Use an alternative configuration file.') 250 | group_tagging.add_argument('--readable-db', 251 | dest='readable', 252 | action='store_true', 253 | default=False, 254 | help='Save the database in somewhat readable \ 255 | form.') 256 | 257 | args = parser.parse_args() 258 | 259 | # a few checks on the arguments 260 | if not len(sys.argv) > 1: 261 | print("No option selected. Try -h.") 262 | sys.exit() 263 | 264 | if args.kindle and (not args.sync and not args.serve): 265 | print("The --kindle option can only modify the --sync or" 266 | " --serve option.") 267 | sys.exit() 268 | 269 | is_not_filtered = (args.filter_ebooks_and is None and 270 | args.filter_ebooks_or is None) 271 | if is_not_filtered and \ 272 | (args.filter_exclude is not None or args.info is not None): 273 | print("The --exclude/--info options can only be used with --list" 274 | " or --filter.") 275 | sys.exit() 276 | if (args.add_tag is not None or args.delete_tag is not None) and \ 277 | (args.filter_ebooks_and is None or args.filter_ebooks_and == []) and \ 278 | (args.filter_ebooks_or is None or args.filter_ebooks_or == []): 279 | print("Tagging all ebooks, or removing a tag from all ebooks, arguably" 280 | " makes no sense. Use the --list/--filter options to filter" 281 | " the library.") 282 | sys.exit() 283 | 284 | if args.config is not None: 285 | config_filename = args.config[0] 286 | if os.path.isabs(config_filename): 287 | if os.path.exists(config_filename): 288 | LIBRARY_CONFIG = config_filename 289 | else: 290 | config_filename = os.path.join(librarian_dir, config_filename) 291 | if os.path.exists(config_filename): 292 | LIBRARY_CONFIG = config_filename 293 | 294 | db = os.path.join(librarian_dir, "library.json") 295 | automatic_save = True 296 | with Library(open_config(), db) as l: 297 | try: 298 | l.open_db() 299 | except Exception as err: 300 | print("Error loading DB: ", err) 301 | sys.exit(-1) 302 | 303 | try: 304 | if args.scrape: 305 | l.scrape_dir_for_ebooks() 306 | if args.import_ebooks: 307 | if l.import_new_ebooks(): 308 | args.refresh = True 309 | if args.refresh: 310 | some_are_incomplete = l.refresh_db() 311 | if some_are_incomplete: 312 | print("Fix metadata for these ebooks and run this again.") 313 | sys.exit(-1) 314 | 315 | # filtering 316 | filtered = [] 317 | s = Search(l.ebooks, is_exact=False) 318 | 319 | if args.collections is not None: 320 | if args.collections == "": 321 | all_tags = list_tags(l.ebooks) 322 | for tag in sorted(all_tags.keys()): 323 | print(" -> %s (%s)" % (tag, all_tags[tag])) 324 | elif args.collections == "untagged": 325 | filtered = s.excludes(["tag:"]) 326 | filtered = s.run_search(EvaluateMatch.AND) 327 | else: 328 | s.is_exact = True 329 | filtered = s.filters(['tag:%s' % args.collections]) 330 | filtered = s.run_search(EvaluateMatch.AND) 331 | elif args.authors is not None: 332 | if args.authors == "": 333 | all_authors = list_authors(l.ebooks) 334 | for author in sorted(all_authors.keys()): 335 | print(" -> %s (%s)" % (author, all_authors[author])) 336 | else: 337 | s.is_exact = True 338 | filtered = s.filters(['author:%s' % args.authors]) 339 | filtered = s.run_search(EvaluateMatch.AND) 340 | else: 341 | if args.filter_exclude is not None: 342 | s.excludes(args.filter_exclude) 343 | if args.filter_ebooks_and is not None: 344 | s.filters(args.filter_ebooks_and) 345 | filtered = s.run_search(EvaluateMatch.AND) 346 | elif args.filter_ebooks_or is not None: 347 | s.filters(args.filter_ebooks_or) 348 | filtered = s.run_search(EvaluateMatch.OR) 349 | 350 | # add/remove tags 351 | if args.add_tag is not None and filtered != []: 352 | for ebook in filtered: 353 | for tag in args.add_tag: 354 | ebook.add_to_collection(tag) 355 | if args.delete_tag is not None and filtered != []: 356 | for ebook in filtered: 357 | for tag in args.delete_tag: 358 | ebook.remove_from_collection(tag) 359 | 360 | for ebook in sorted(filtered, key=lambda x: x.filename): 361 | if args.info is None: 362 | print(" -> ", ebook) 363 | if args.openlibrary: 364 | s = OpenLibrarySearch() 365 | result = s.search(ebook) 366 | if result: 367 | result.compare_to_source(ebook) 368 | else: 369 | if args.info == []: 370 | print(ebook.info()) 371 | else: 372 | print(ebook.info(args.info)) 373 | 374 | if args.write_metadata is not None: 375 | if not ebook.update_metadata(args.write_metadata): 376 | automatic_save = False 377 | 378 | if args.read is not None: 379 | ebook.set_progress(args.read) 380 | 381 | if args.write_to_file: 382 | ebook.sync_ebook_metadata() 383 | 384 | if args.sync: 385 | if args.sync is True and args.kindle: 386 | l.sync_with_kindle(filtered) 387 | elif os.path.exists(args.sync) and os.path.isdir(args.sync): 388 | l.sync_with_kindle(filtered, kindle_sync=False, 389 | destination_dir=args.sync) 390 | else: 391 | print("Invalid sync command.") 392 | sys.exit() 393 | 394 | if args.serve: 395 | if args.kindle: 396 | l.serve(filtered, kindle_sync=True) 397 | else: 398 | l.serve(filtered, kindle_sync=False) 399 | 400 | if automatic_save: 401 | # TODO: automatic save to file!!! + manual 402 | l.save_db(args.readable) 403 | except Exception as err: 404 | print(err) 405 | traceback.print_exc() 406 | sys.exit(-1) 407 | 408 | print("Everything done in %.2fs." % (time.perf_counter() - start)) 409 | -------------------------------------------------------------------------------- /librarianlib/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/barsanuphe/librarian/f72d5ad9f03f6893124d8e0b5abad85be5fe50ad/librarianlib/__init__.py -------------------------------------------------------------------------------- /librarianlib/ebook_search.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | import re 3 | 4 | 5 | def list_tags(ebooks): 6 | all_tags = defaultdict(lambda: 0) 7 | for ebook in ebooks: 8 | if ebook.tags == []: 9 | all_tags["untagged"] += 1 10 | else: 11 | for tag in ebook.tags: 12 | all_tags[tag] += 1 13 | return all_tags 14 | 15 | def list_authors(ebooks): 16 | all_authors = defaultdict(lambda: 0) 17 | for ebook in ebooks: 18 | author = ebook.librarian_metadata.get_values("author")[0] 19 | all_authors[author] += 1 20 | return all_authors 21 | 22 | class Search(object): 23 | """ This class builds a EvaluateMatch object from input conditions, 24 | then loops on all ebooks to pick out the ones who match. """ 25 | def __init__(self, everything, is_exact=False): 26 | self.everything = everything 27 | self.is_exact = is_exact 28 | self.evaluate_match = EvaluateMatch() 29 | self.field_search = re.compile("^([^:]*):(.*)$") 30 | 31 | def excludes(self, exclude_list): 32 | for exclude_term in exclude_list: 33 | fields = self.field_search.findall(exclude_term) 34 | if fields == []: 35 | self.evaluate_match.add_exclude_condition(exclude_term, None, 36 | self.is_exact) 37 | else: 38 | field, value = fields[0] 39 | self.evaluate_match.add_exclude_condition(value, field, 40 | self.is_exact) 41 | 42 | def filters(self, filter_list): 43 | for filter_term in filter_list: 44 | fields = self.field_search.findall(filter_term) 45 | if fields == []: 46 | self.evaluate_match.add_condition(filter_term, None, 47 | self.is_exact) 48 | else: 49 | field, value = fields[0] 50 | self.evaluate_match.add_condition(value, field, self.is_exact) 51 | 52 | # EvaluateMatch.OR / EvaluateMatch.AND 53 | def run_search(self, and_or): 54 | filtered = [] 55 | for ebook in self.everything: 56 | if self.evaluate_match.is_a_match(ebook, and_or): 57 | filtered.append(ebook) 58 | return filtered 59 | 60 | @property 61 | def number_of_results(self): 62 | return len(self.filtered) 63 | 64 | 65 | def match_this(ebook, value, field=None, exact=False): 66 | """ Try to see if an Epub object matches the condition given by value, 67 | optionnally restricted to a field. """ 68 | value = value.lower() 69 | if field is None: 70 | # search everywhere 71 | result = False # OR search 72 | for key in ebook.librarian_metadata.keys: 73 | field_value = [el for el 74 | in ebook.librarian_metadata.get_values(key) 75 | if el is not None] 76 | is_list = (type(field_value) == list) 77 | if exact: 78 | result = result \ 79 | or (not is_list and value == field_value.lower()) \ 80 | or (is_list and value in field_value.lower()) 81 | else: 82 | result = result or \ 83 | (not is_list and any([(value == val.lower()) 84 | for val in field_value])) or \ 85 | (is_list and any([(value in val.lower()) 86 | for val in field_value])) 87 | # tags 88 | if exact: 89 | result = result or any([(value == tag.lower()) 90 | for tag in ebook.tags]) 91 | else: 92 | result = result or any([(value in tag.lower()) 93 | for tag in ebook.tags]) 94 | 95 | # progress 96 | result = result or (ebook.read.name == value) 97 | 98 | return result 99 | 100 | else: 101 | if field == "progress": 102 | return (ebook.read.name == value) 103 | elif field == "tag": 104 | if exact: 105 | return any([(value == tag.lower()) for tag in ebook.tags]) 106 | else: 107 | return any([(value in tag.lower()) for tag in ebook.tags]) 108 | else: 109 | field_value = ebook.librarian_metadata.get_values(field) 110 | is_list = (type(field_value) == list) 111 | if exact: 112 | return (not is_list and value == field_value.lower()) or \ 113 | (is_list and any([(value == val.lower()) 114 | for val in field_value])) 115 | else: 116 | return (not is_list and value in field_value.lower()) or \ 117 | (is_list and any([(value in val.lower()) 118 | for val in field_value])) 119 | 120 | 121 | class EvaluateMatch(object): 122 | """ This class builds a list of conditions, that are evaluated when 123 | is_a_match is passed with an actual Epub object. """ 124 | OR = 1 125 | AND = 2 126 | 127 | def __init__(self): 128 | self.full_expression = [] 129 | self.exclude_expression = [] 130 | 131 | def add_condition(self, value, field=None, is_exact=False): 132 | self.full_expression.append(lambda x: 133 | match_this(x, value, field, is_exact)) 134 | 135 | def add_exclude_condition(self, value, field=None, is_exact=False): 136 | self.exclude_expression.append(lambda x: 137 | not match_this(x, value, field, 138 | is_exact)) 139 | 140 | def _evaluate(self, epub): 141 | evaluated = [f(epub) for f in self.full_expression] 142 | exclude_evaluated = [f(epub) for f in self.exclude_expression] 143 | return evaluated, exclude_evaluated 144 | 145 | def apply_and_condition_to_epub(self, epub): 146 | evaluated, exclude_evaluated = self._evaluate(epub) 147 | return all(evaluated) and all(exclude_evaluated) 148 | 149 | def apply_or_condition_to_epub(self, epub): 150 | evaluated, exclude_evaluated = self._evaluate(epub) 151 | return any(evaluated) and all(exclude_evaluated) 152 | 153 | def is_a_match(self, epub, and_or): 154 | if and_or == self.AND: 155 | return self.apply_and_condition_to_epub(epub) 156 | elif and_or == self.OR: 157 | return self.apply_or_condition_to_epub(epub) 158 | else: 159 | print("What?") 160 | -------------------------------------------------------------------------------- /librarianlib/epub.py: -------------------------------------------------------------------------------- 1 | import tempfile 2 | import shutil 3 | import os 4 | import subprocess 5 | import hashlib 6 | import zipfile 7 | from lxml import etree 8 | from enum import Enum 9 | from .epub_metadata import OpfFile, FakeOpfFile, ns 10 | 11 | try: 12 | from colorama import init 13 | init(autoreset=True) 14 | from colorama import Fore, Style 15 | 16 | def unread(text): 17 | return Fore.YELLOW + Style.BRIGHT + text 18 | 19 | def reading(text): 20 | return Fore.GREEN + Style.BRIGHT + text 21 | 22 | def read(text): 23 | return Fore.BLUE + Style.BRIGHT + text 24 | except: 25 | def unread(text): 26 | return "** " + text 27 | 28 | def reading(text): 29 | return ":: " + text 30 | 31 | def read(text): 32 | return text 33 | 34 | 35 | def has_changed(f, *args): 36 | def new_f(*args): 37 | res = f(*args) 38 | if res: 39 | args[0].has_changed = True 40 | return res 41 | return new_f 42 | 43 | 44 | def strip_lower(f, *args): 45 | def new_f(*args): 46 | tag = args[1].strip().lower() 47 | f(args[0], tag) 48 | return new_f 49 | 50 | AUTHORIZED_TEMPLATE_PARTS = { 51 | "$a": "author", 52 | "$y": "year", 53 | "$t": "title", 54 | "$s": "series", 55 | "$i": "series_index", 56 | "$p": "progress", 57 | } 58 | 59 | class ReadStatus(Enum): 60 | unread = 0 61 | reading = 1 62 | read = 2 63 | 64 | 65 | class Epub(object): 66 | 67 | def __init__(self, path, library_dir, author_aliases, 68 | ebook_filename_template): 69 | self.path = path 70 | self.library_dir = library_dir 71 | self.author_aliases = author_aliases 72 | 73 | self.librarian_metadata = None 74 | self.ebook_metadata = None 75 | self.is_opf_open = False 76 | self.metadata_filename = "" 77 | 78 | self.tags = [] 79 | self.has_changed = False 80 | self.loaded_metadata = None 81 | self.template = ebook_filename_template 82 | self.was_converted_to_mobi = False 83 | self.converted_to_mobi_from_hash = "" 84 | self.converted_to_mobi_hash = "" 85 | self.last_synced_hash = "" 86 | self.read = ReadStatus(0) 87 | 88 | def __enter__(self): 89 | return self 90 | 91 | def __exit__(self, type, value, traceback): 92 | if os.path.exists(self.temp_dir): 93 | shutil.rmtree(self.temp_dir) 94 | 95 | def __str__(self): 96 | metadata = self.librarian_metadata 97 | if metadata.get_values("series") != []: 98 | first_series = metadata.get_values("series")[0] 99 | if metadata.get_values("series_index") != []: 100 | first_series_idx = metadata.get_values("series_index")[0] 101 | series_info = "[ %s #%s ]" % (first_series, first_series_idx) 102 | else: 103 | series_info = "[ %s ]" % (first_series) 104 | else: 105 | series_info = "" 106 | 107 | first_author = metadata.get_values("author")[0] 108 | first_title = metadata.get_values("title")[0] 109 | first_year = metadata.get_values("year")[0] 110 | str = "" 111 | if self.tags == []: 112 | str = "%s (%s) %s %s" % (first_author, 113 | first_year, 114 | first_title, 115 | series_info) 116 | else: 117 | str = "%s (%s) %s %s [ %s ]" % (first_author, 118 | first_year, 119 | first_title, 120 | series_info, 121 | ", ".join(self.tags)) 122 | 123 | if self.read == ReadStatus.unread: 124 | return unread(str) 125 | elif self.read == ReadStatus.reading: 126 | return reading(str) 127 | else: 128 | return read(str) 129 | 130 | @property 131 | def extension(self): 132 | # extension without the . 133 | return os.path.splitext(self.path)[1][1:].lower() 134 | 135 | @property 136 | def current_hash(self): 137 | return hashlib.sha1(open(self.path, 'rb').read()).hexdigest() 138 | 139 | def set_filename_template(self, template): 140 | self.template = template 141 | 142 | @property 143 | def filename(self): 144 | template = self.template 145 | for key in AUTHORIZED_TEMPLATE_PARTS.keys(): 146 | relevant_parts = self.librarian_metadata.get_values( 147 | AUTHORIZED_TEMPLATE_PARTS[key]) 148 | if len(relevant_parts) >= 1: 149 | template = template.replace(key, relevant_parts[0]) 150 | elif AUTHORIZED_TEMPLATE_PARTS[key] == "progress": 151 | template = template.replace(key, self.read.name) 152 | template = template.replace(":", "").replace("?", "") 153 | return "%s.%s" % (template, self.extension) 154 | 155 | @property 156 | def exported_filename(self): 157 | return os.path.splitext(self.filename)[0] + ".mobi" 158 | 159 | def load_from_database_json(self, filename_dict, filename): 160 | if not os.path.exists(filename_dict["path"]): 161 | print("File %s in DB cannot be found, ignoring." % 162 | filename_dict["path"]) 163 | return False 164 | try: 165 | self.loaded_metadata = filename_dict 166 | # for similar interface to OpfFile 167 | self.librarian_metadata = FakeOpfFile(filename_dict['metadata'], 168 | self.author_aliases) 169 | self.tags = [el.lower().strip() 170 | for el in filename_dict['tags'].split(",") 171 | if el.strip() != ""] 172 | self.converted_to_mobi_hash = \ 173 | filename_dict['converted_to_mobi_hash'] 174 | self.converted_to_mobi_from_hash = \ 175 | filename_dict['converted_to_mobi_from_hash'] 176 | self.last_synced_hash = filename_dict['last_synced_hash'] 177 | self.read = ReadStatus(int(filename_dict['read'])) 178 | except Exception as err: 179 | print("Incorrect db!", err) 180 | return False 181 | return True 182 | 183 | def to_database_json(self): 184 | if self.has_changed: 185 | return { 186 | "path": self.path, 187 | "tags": ",".join(sorted([el for el in self.tags 188 | if el.strip() != ""])), 189 | "last_synced_hash": self.last_synced_hash, 190 | "converted_to_mobi_hash": self.converted_to_mobi_hash, 191 | "converted_to_mobi_from_hash": 192 | self.converted_to_mobi_from_hash, 193 | "metadata": self.librarian_metadata.metadata_dict, 194 | "read": self.read.value 195 | } 196 | else: 197 | return self.loaded_metadata 198 | 199 | def open_ebook_metadata(self): 200 | if not self.is_opf_open: 201 | self.temp_dir = tempfile.mkdtemp() 202 | self.extract_opf_file() 203 | self.is_opf_open = True 204 | 205 | def extract_opf_file(self): 206 | zip = zipfile.ZipFile(self.path) 207 | # find the contents metafile 208 | txt = zip.read('META-INF/container.xml') 209 | tree = etree.fromstring(txt) 210 | 211 | self.metadata_filename = tree.xpath( 212 | 'n:rootfiles/n:rootfile/@full-path', 213 | namespaces=ns)[0] 214 | self.temp_opf = os.path.join(self.temp_dir, 215 | os.path.basename(self.metadata_filename)) 216 | 217 | cf = zip.read(self.metadata_filename) 218 | with open(self.temp_opf, "w") as opf: 219 | opf.write(cf.decode("utf8")) 220 | 221 | self.ebook_metadata = OpfFile(self.temp_opf, self.author_aliases) 222 | # first import 223 | if self.librarian_metadata is None: 224 | self.librarian_metadata = self.ebook_metadata 225 | 226 | def remove_from_zip(self, zipfname, *filenames): 227 | tempdir = tempfile.mkdtemp() 228 | try: 229 | tempname = os.path.join(tempdir, 'new.zip') 230 | with zipfile.ZipFile(zipfname, 'r') as zipread: 231 | with zipfile.ZipFile(tempname, 'w') as zipwrite: 232 | for item in zipread.infolist(): 233 | if item.filename not in filenames: 234 | data = zipread.read(item.filename) 235 | zipwrite.writestr(item, data) 236 | shutil.move(tempname, zipfname) 237 | finally: 238 | shutil.rmtree(tempdir) 239 | 240 | def save_metadata(self): 241 | if self.is_opf_open and self.ebook_metadata.has_changed: 242 | print("Saving epub...") 243 | self.remove_from_zip(self.path, self.metadata_filename) 244 | with zipfile.ZipFile(self.path, 'a') as z: 245 | z.write(self.temp_opf, arcname=self.metadata_filename) 246 | 247 | def close_metadata(self): 248 | if self.is_opf_open: 249 | self.is_opf_open = False 250 | # clean up 251 | self.__exit__(None, None, None) 252 | 253 | def sync_ebook_metadata(self): 254 | print("Writing metadata to ebook file is disabled for now.") 255 | return False 256 | 257 | self.open_ebook_metadata() 258 | # TODO: clear ebook_metadata ?? 259 | 260 | # copy to ebook_metadata 261 | for key in self.librarian_metadata.keys: 262 | values = self.librarian_metadata.get_values(key) 263 | for value in values: 264 | self.ebook_metadata.set_value(key, value, replace=True) 265 | self.ebook_metadata.has_changed = True 266 | #TODO: go through ebook_metadata and set all values to opf 267 | self.save_metadata() 268 | self.close_metadata() 269 | 270 | @strip_lower 271 | @has_changed 272 | def add_to_collection(self, tag): 273 | if tag != "" and tag not in self.tags: 274 | self.tags.append(tag) 275 | return True 276 | return False 277 | 278 | @strip_lower 279 | @has_changed 280 | def remove_from_collection(self, tag): 281 | if tag != "" and tag in self.tags: 282 | self.tags.remove(tag) 283 | return True 284 | return False 285 | 286 | def get_relative_path(self, path): 287 | return path.split(self.library_dir)[1][1:] 288 | 289 | @has_changed 290 | def rename_from_metadata(self, force=False): 291 | # open ebook metadata if necessary or forced 292 | self.open_ebook_metadata() 293 | if self.librarian_metadata.is_complete and self.library_dir in self.path: 294 | new_name = os.path.join(self.library_dir, self.filename) 295 | if new_name != self.path: 296 | if not os.path.exists(os.path.dirname(new_name)): 297 | print("Creating directory", 298 | self.get_relative_path(os.path.dirname(new_name))) 299 | os.makedirs(os.path.dirname(new_name)) 300 | print("Renaming to ", self.get_relative_path(new_name)) 301 | shutil.move(self.path, new_name) 302 | # refresh name 303 | self.path = new_name 304 | return True 305 | return False 306 | 307 | @has_changed 308 | def export_to_mobi(self, mobi_dir): 309 | output_filename = os.path.join(mobi_dir, self.exported_filename) 310 | if os.path.exists(output_filename): 311 | # check if ebook has changed since the mobi was created 312 | if self.current_hash == self.converted_to_mobi_from_hash: 313 | self.was_converted_to_mobi = True 314 | return False 315 | 316 | if not os.path.exists(os.path.dirname(output_filename)): 317 | print("Creating directory", os.path.dirname(output_filename)) 318 | os.makedirs(os.path.dirname(output_filename)) 319 | 320 | # conversion 321 | print(" + Converting to .mobi: ", self.filename) 322 | subprocess.check_call(['ebook-convert', 323 | self.path, 324 | output_filename, 325 | "--output-profile", 326 | "kindle_pw"], stdout=subprocess.DEVNULL) 327 | 328 | self.converted_to_mobi_hash = \ 329 | hashlib.sha1(open(output_filename, 'rb').read()).hexdigest() 330 | self.converted_to_mobi_from_hash = self.current_hash 331 | self.was_converted_to_mobi = True 332 | return True 333 | 334 | @has_changed 335 | def sync_with_kindle(self, destination_dir, mobi_dir=None): 336 | if mobi_dir is not None and not self.was_converted_to_mobi: 337 | self.export_to_mobi(mobi_dir) 338 | 339 | if mobi_dir is not None: 340 | output_filename = os.path.join(destination_dir, 341 | self.exported_filename) 342 | else: 343 | output_filename = os.path.join(destination_dir, 344 | self.filename) 345 | 346 | if not os.path.exists(os.path.dirname(output_filename)): 347 | print("Creating directory", os.path.dirname(output_filename), 348 | flush=True) 349 | os.makedirs(os.path.dirname(output_filename)) 350 | 351 | # check if exists and with latest hash 352 | already_synced_epub = (mobi_dir is None and 353 | self.last_synced_hash == self.current_hash) 354 | already_synced_mobi = (mobi_dir is not None and 355 | self.last_synced_hash == 356 | self.converted_to_mobi_hash) 357 | if (os.path.exists(output_filename) and 358 | (already_synced_mobi or already_synced_epub)): 359 | print(" - Skipping already synced ebook: ", self.filename, 360 | flush=True) 361 | return False 362 | 363 | print(" + Syncing: ", self.filename, flush=True) 364 | 365 | if mobi_dir is None: 366 | shutil.copy(os.path.join(self.library_dir, self.filename), 367 | output_filename) 368 | self.last_synced_hash = self.current_hash 369 | else: 370 | shutil.copy(os.path.join(mobi_dir, self.exported_filename), 371 | output_filename) 372 | self.last_synced_hash = self.converted_to_mobi_hash 373 | return True 374 | 375 | def info(self, field_list=None): 376 | return str(self) + "\n" + "-"*len(str(self)) + "\n" + \ 377 | self.librarian_metadata.show_fields(field_list) 378 | 379 | def write_metadata(self, key, value): 380 | if key not in self.librarian_metadata.keys: 381 | print("Adding new metadata field", key) 382 | self.librarian_metadata.set_value(key, value) 383 | 384 | @has_changed 385 | def update_metadata(self, update_list): 386 | # force metadata refresh 387 | if not self.is_opf_open: 388 | self.open_ebook_metadata() 389 | 390 | changes = "" 391 | for part in update_list: 392 | try: 393 | key, value = part.split(":") 394 | # TODO: get all values for field 395 | old_values = self.librarian_metadata.get_values(key) 396 | if value.title() not in old_values: 397 | # TODO: list of unique fields 398 | changes += "%s -> %s\n" % (old_values, value.title()) 399 | self.write_metadata(key, value.title()) 400 | 401 | except Exception as err: 402 | print("Error writing metadata", part, ":", err) 403 | continue # ignore this part only 404 | 405 | if changes == "": 406 | print("No change detected.") 407 | return # nothing to do 408 | 409 | print("Updating epub metadata:") 410 | print(changes) 411 | 412 | answer = input("Confirm update? y/n ").lower() 413 | if answer == 'y': 414 | print("Saving changes.") 415 | print(self.info()) 416 | return True 417 | else: 418 | print("Discarding changes, nothing will be saved.") 419 | return False 420 | 421 | @has_changed 422 | def set_progress(self, read_value): 423 | if read_value not in ReadStatus.__members__.keys(): 424 | return False 425 | print("Setting ", str(self), "as ", ReadStatus[read_value].name) 426 | self.read = ReadStatus[read_value] 427 | return True 428 | -------------------------------------------------------------------------------- /librarianlib/epub_metadata.py: -------------------------------------------------------------------------------- 1 | from lxml import etree 2 | from collections import defaultdict 3 | 4 | ns = { 5 | 'n': 'urn:oasis:names:tc:opendocument:xmlns:container', 6 | 'pkg': 'http://www.idpf.org/2007/opf', 7 | 'dc': 'http://purl.org/dc/elements/1.1/' 8 | } 9 | 10 | METADATA_ALIASES = { 11 | "year": "date", 12 | "author": "creator", 13 | } 14 | 15 | 16 | def sanitize(name, result, author_aliases): 17 | if name in METADATA_ALIASES.keys(): 18 | name = METADATA_ALIASES[name] 19 | if name == "creator": 20 | if ',' in result: 21 | parts = result.split(",") 22 | if len(parts) == 2: 23 | result = "%s %s" % (parts[1].strip(), parts[0].strip()) 24 | if len(parts) > 2: 25 | result = "Various" 26 | result = result.title() 27 | if result in author_aliases.keys(): 28 | result = author_aliases[result] 29 | return result 30 | 31 | if name == "date": 32 | try: 33 | return result[:4] 34 | except: 35 | return "" 36 | if name == "title": 37 | return result.replace("/", "-") 38 | 39 | return result 40 | 41 | 42 | class EbookMetadata(object): 43 | def __init__(self, author_aliases): 44 | self.author_aliases = author_aliases 45 | self.metadata_dict = defaultdict(list) 46 | self.has_changed = False 47 | 48 | @property 49 | def is_empty(self): 50 | return (self.keys == []) 51 | 52 | @property 53 | def keys(self): 54 | return sorted(self.metadata_dict.keys()) 55 | 56 | @property 57 | def is_complete(self): 58 | return ("title" in self.keys and 59 | "date" in self.keys and 60 | "creator" in self.keys) 61 | 62 | def show_fields(self, field_list=None): 63 | info = "" 64 | for key in self.keys: 65 | if (field_list and key in field_list) or not field_list: 66 | info += "\t%s : \t%s\n" % \ 67 | (key, ",".join(self.get_values(key))) 68 | info += "\n" 69 | return info 70 | 71 | def __str__(self): 72 | return self.show_fields() 73 | 74 | 75 | class FakeOpfFile(EbookMetadata): 76 | 77 | def __init__(self, entries, author_aliases): 78 | super().__init__(author_aliases) 79 | self.metadata_dict.update(entries) 80 | 81 | def get_values(self, name): 82 | name = METADATA_ALIASES.get(name, name) 83 | return self.metadata_dict.get(name, []) 84 | 85 | def set_value(self, name, value, replace=False): 86 | name = METADATA_ALIASES.get(name, name) 87 | if replace: 88 | self.metadata_dict[name] = [value] 89 | elif value not in self.metadata_dict[name]: 90 | self.metadata_dict[name].append(value) 91 | self.has_changed = True 92 | 93 | 94 | class OpfFile(EbookMetadata): 95 | 96 | def __init__(self, opf, author_aliases): 97 | super().__init__(author_aliases) 98 | self.opf = opf 99 | self.tree = etree.parse(self.opf) 100 | self.metadata_element = self.tree.xpath('/pkg:package/pkg:metadata', 101 | namespaces=ns)[0] 102 | self.epub_version = self.tree.xpath('/pkg:package', 103 | namespaces=ns)[0].get("version") 104 | 105 | self.parse() 106 | 107 | def get_elements(self, name): 108 | return self.metadata_dict.get(name, None) 109 | 110 | def parse(self): 111 | for node in self.metadata_element: 112 | # passing comments 113 | if node.tag == etree.Comment: 114 | continue 115 | tag = etree.QName(node.tag) 116 | short_tag = tag.localname 117 | if short_tag == "meta" and self.epub_version == "2.0": 118 | if "calibre" in node.get("name"): 119 | calibre_tag = node.get("name").split("calibre:")[1] 120 | self.metadata_dict[calibre_tag].append( 121 | sanitize(calibre_tag, 122 | node.get("content"), 123 | self.author_aliases)) 124 | # TODO: librarian tags 125 | else: 126 | self.metadata_dict[short_tag].append( 127 | sanitize(short_tag, node.text, self.author_aliases)) 128 | for alias in METADATA_ALIASES.keys(): 129 | self.metadata_dict[alias] = self.metadata_dict[ 130 | METADATA_ALIASES[alias]] 131 | 132 | def save(self): 133 | with open(self.opf, 'w') as file_handle: 134 | file_handle.write(etree.tostring(self.tree, 135 | pretty_print=True, 136 | encoding='utf8', 137 | xml_declaration=True 138 | ).decode("utf8")) 139 | 140 | def get_values(self, name): 141 | name = METADATA_ALIASES.get(name, name) 142 | 143 | if name not in self.keys: 144 | return [] # None? 145 | 146 | return self.get_elements(name) 147 | 148 | def set_value(self, name, value, replace=False): 149 | name = METADATA_ALIASES.get(name, name) 150 | 151 | nodes = self.get_elements(name) 152 | print(nodes, name) 153 | 154 | # TODO: 155 | # if replace, must be unambiguous 156 | #if replace: 157 | #assert len(nodes) == 1 158 | 159 | # modify or insert new metadata 160 | found = False 161 | for node in nodes: 162 | if not node or not replace: 163 | continue 164 | else: 165 | if node.text is None: # meta 166 | if node.get("name") == name and replace: 167 | node.set("content", value) 168 | found = True 169 | else: 170 | if replace: 171 | node.text = value 172 | found = True 173 | 174 | if not found: 175 | print(" -- Creating new metadata", name, '=', value) 176 | if name in ["series", "series_index"]: 177 | self.insert_new_node(name, value, is_meta=True) 178 | else: 179 | self.insert_new_node(name, value, is_meta=False) 180 | 181 | self.has_changed = True 182 | self.save() 183 | 184 | def remove_value(self, name, value): 185 | pass # TODO! 186 | 187 | def insert_new_node(self, name, value, is_meta=False): 188 | if is_meta: 189 | new_node = etree.Element("meta") 190 | new_node.set("name", "calibre:" + name) 191 | new_node.set("content", value) 192 | self.metadata_element.append(new_node) 193 | else: 194 | node_tag = etree.QName("http://purl.org/dc/elements/1.1/", name) 195 | new_node = etree.Element(node_tag) 196 | new_node.text = value 197 | self.metadata_element.append(new_node) 198 | -------------------------------------------------------------------------------- /librarianlib/librarian_server.py: -------------------------------------------------------------------------------- 1 | from http.server import HTTPServer, SimpleHTTPRequestHandler 2 | import os 3 | import threading 4 | from urllib.parse import unquote 5 | 6 | 7 | class LibrarianServer(HTTPServer): 8 | def __init__(self, server_address, RequestHandlerClass, 9 | allowed, library_dir, collections_json): 10 | HTTPServer.__init__(self, server_address, RequestHandlerClass) 11 | self.allowed = allowed 12 | # to make sure all goes well later when splitting and joining 13 | if not library_dir.endswith("/"): 14 | library_dir += "/" 15 | self.allowed_relative = [el.split(library_dir)[1] for el in allowed] 16 | self.library_dir = library_dir 17 | self.collections_json = collections_json 18 | 19 | 20 | class LibrarianHandler(SimpleHTTPRequestHandler): 21 | 22 | def do_GET(self): 23 | clean_path = unquote(self.path[1:]) 24 | if clean_path == "index": 25 | print("Sending index of filtered ebooks...") 26 | self.send_response(200) 27 | self.send_header("Content-type", "text/plain") 28 | self.end_headers() 29 | text = "|".join(self.server.allowed_relative) 30 | self.wfile.write(text.encode("utf8")) 31 | elif clean_path in self.server.allowed_relative or \ 32 | clean_path == "collections.json": 33 | super(LibrarianHandler, self).do_GET() 34 | elif clean_path == "LibrarianServer::shutdown": 35 | # return response and shutdown the server 36 | self.send_response(200) 37 | self.send_header("Content-type", "text/plain") 38 | self.end_headers() 39 | self.wfile.write("Shutting down server.".encode("utf8")) 40 | print("Shutting down server.") 41 | assassin = threading.Thread(target=self.server.shutdown) 42 | assassin.daemon = True 43 | assassin.start() 44 | else: 45 | return self.send_error(404, 'File Not Found: %s' % clean_path[1:]) 46 | 47 | def translate_path(self, path): 48 | clean_path = unquote(self.path[1:], encoding='utf-8') 49 | if clean_path == "collections.json": 50 | print("Sending collections...") 51 | return self.server.collections_json 52 | else: 53 | print("Sending %s..." % clean_path) 54 | # add library dir to path to actually retrieve the file 55 | return os.path.join(self.server.library_dir, clean_path) 56 | 57 | def log_message(self, format, *args): 58 | # mute default output 59 | return 60 | 61 | 62 | if __name__ == "__main__": 63 | try: 64 | library_dir = "" 65 | allowed = [""] 66 | port = 8080 67 | server = LibrarianServer(('IP', port), LibrarianHandler, allowed, 68 | library_dir) 69 | server.serve_forever() 70 | 71 | except KeyboardInterrupt: 72 | server.shutdown() 73 | server.socket.close() 74 | -------------------------------------------------------------------------------- /librarianlib/library.py: -------------------------------------------------------------------------------- 1 | import os 2 | import subprocess 3 | import shutil 4 | import hashlib 5 | import codecs 6 | import time 7 | from concurrent.futures import ThreadPoolExecutor, as_completed 8 | from multiprocessing import cpu_count 9 | import json 10 | 11 | from librarianlib.epub import Epub 12 | from librarianlib.librarian_server import LibrarianServer, LibrarianHandler 13 | 14 | 15 | class Library(object): 16 | 17 | def __init__(self, config, db): 18 | self.ebooks = [] 19 | self.backup_imported_ebooks = True 20 | self.scrape_root = None 21 | self.ebook_filename_template = config.get("ebook_filename_template", 22 | "$a/$a ($y) $t") 23 | self.config = config 24 | self.db = db 25 | 26 | def __enter__(self): 27 | return self 28 | 29 | def __exit__(self, type, value, traceback): 30 | # cleaning up temp opf files 31 | for epub in self.ebooks: 32 | if epub.is_opf_open: 33 | epub.close_metadata() 34 | 35 | def _load_ebook(self, everything, filename): 36 | if "path" not in everything[filename].keys(): 37 | return False, None 38 | eb = Epub(everything[filename]["path"], self.config["library_dir"], 39 | self.config["author_aliases"], self.ebook_filename_template) 40 | return eb.load_from_database_json(everything[filename], filename), eb 41 | 42 | def open_db(self): 43 | if os.path.exists(self.db): 44 | start = time.perf_counter() 45 | everything = json.load(open(self.db, 'r')) 46 | 47 | with ThreadPoolExecutor(max_workers=cpu_count()) as executor: 48 | future_to_ebook = { 49 | executor.submit(self._load_ebook, 50 | everything, 51 | f): f for f in everything.keys() 52 | } 53 | for future in as_completed(future_to_ebook): 54 | success, ebook = future.result() 55 | if success: 56 | self.ebooks.append(ebook) 57 | print("Database opened in %.2fs: loaded %s ebooks." % 58 | ((time.perf_counter() - start), len(self.ebooks))) 59 | else: 60 | print("No DB, refresh!") 61 | 62 | def _return_or_create_new_ebook(self, full_path, known_ebooks): 63 | is_already_in_db = False 64 | for eb in known_ebooks: 65 | if eb.path == full_path: 66 | is_already_in_db = True 67 | eb.open_ebook_metadata() 68 | return eb 69 | if not is_already_in_db: 70 | eb = Epub(full_path, self.config["library_dir"], 71 | self.config["author_aliases"], 72 | self.ebook_filename_template) 73 | eb.open_ebook_metadata() 74 | print(" -> NEW EBOOK: ", eb) 75 | return eb 76 | return None 77 | 78 | def refresh_db(self): 79 | print("Refreshing library...") 80 | start = time.perf_counter() 81 | old_db = list(self.ebooks) # copy 82 | self.ebooks = [] 83 | 84 | # list all books in library root 85 | all_ebooks_in_library_dir = [] 86 | for root, dirs, files in os.walk(self.config["library_dir"]): 87 | all_ebooks_in_library_dir.extend([os.path.join(root, el) 88 | for el in files 89 | if el.lower().endswith(".epub")]) 90 | 91 | # refresh list 92 | for (i,ebook) in enumerate(sorted(all_ebooks_in_library_dir)): 93 | eb = self._return_or_create_new_ebook(ebook, old_db) 94 | if eb is not None: 95 | print(" %.2f%%" % (100*i/len(all_ebooks_in_library_dir)), 96 | end="\r", flush=True) 97 | # rename if necessary 98 | eb.rename_from_metadata() 99 | self.ebooks.append(eb) 100 | 101 | # display missing ebooks 102 | deleted = [eb for eb in old_db if eb not in self.ebooks] 103 | for eb in deleted: 104 | print(" -> DELETED EBOOK: ", eb) 105 | 106 | # remove empty dirs in library root 107 | for root, dirs, files in os.walk(self.config["library_dir"], 108 | topdown=False): 109 | for dir in [os.path.join(root, el) for el in dirs if 110 | os.listdir(os.path.join(root, el)) == []]: 111 | os.rmdir(dir) 112 | 113 | is_incomplete = self.list_incomplete_metadata() 114 | print("Database refreshed in %.2fs." % (time.perf_counter() - start)) 115 | return is_incomplete 116 | 117 | def save_db(self, readable=False, sync_with_files=False): 118 | print("Saving dabatase...") 119 | data = {} 120 | # adding ebooks in alphabetical order 121 | for ebook in sorted(self.ebooks, key=lambda x: x.filename): 122 | data[ebook.filename] = ebook.to_database_json() 123 | if sync_with_files: 124 | ebook.sync_ebook_metadata() 125 | 126 | # copy previous db 127 | if os.path.exists("%s_backup" % self.db): 128 | os.remove("%s_backup" % self.db) 129 | shutil.copyfile(self.db, "%s_backup" % self.db) 130 | 131 | # dumping in json file 132 | with open(self.db, "w") as data_file: 133 | if readable: 134 | data_file.write(json.dumps(data, sort_keys=True, indent=2, 135 | separators=(',', ': '), 136 | ensure_ascii=False)) 137 | else: 138 | data_file.write(json.dumps(data, ensure_ascii=False)) 139 | 140 | def scrape_dir_for_ebooks(self): 141 | scrape_root = self.config.get("scrape_root", None) 142 | if scrape_root is None: 143 | print("scrape_root not defined in librarian.yaml, nothing to do.") 144 | return 145 | 146 | start = time.perf_counter() 147 | all_ebooks_in_scrape_dir = [] 148 | print("Finding ebooks in %s..." % scrape_root) 149 | for root, dirs, files in os.walk(scrape_root): 150 | all_ebooks_in_scrape_dir.extend([os.path.join(root, el) 151 | for el in files 152 | if os.path.splitext(el.lower())[1] 153 | in [".epub", ".mobi"]]) 154 | # if an ebook has an epub and mobi version, only take epub 155 | filtered_ebooks_in_scrape_dir = [] 156 | for ebook in all_ebooks_in_scrape_dir: 157 | if os.path.splitext(ebook)[1].lower() == ".epub": 158 | filtered_ebooks_in_scrape_dir.append(ebook) 159 | if os.path.splitext(ebook)[1].lower() == ".mobi": 160 | epub_version = os.path.splitext(ebook)[0] + ".epub" 161 | if epub_version not in all_ebooks_in_scrape_dir: 162 | filtered_ebooks_in_scrape_dir.append(ebook) 163 | 164 | if len(filtered_ebooks_in_scrape_dir) == 0: 165 | print("Nothing to scrape.") 166 | return False 167 | else: 168 | print("Scraping ", scrape_root) 169 | 170 | for ebook in filtered_ebooks_in_scrape_dir: 171 | print(" -> Scraping ", os.path.basename(ebook)) 172 | shutil.copyfile(ebook, os.path.join(self.config["import_dir"], 173 | os.path.basename(ebook))) 174 | 175 | print("Scraped ebooks in %.2fs." % (time.perf_counter() - start)) 176 | return True 177 | 178 | def _convert_to_epub_before_importing(self, mobi): 179 | epub_name = mobi.replace(".mobi", ".epub") 180 | if not os.path.exists(epub_name): 181 | print(" + Converting to .epub: ", mobi) 182 | return subprocess.call(['ebook-convert', 183 | mobi, 184 | epub_name, 185 | "--output-profile", "kindle_pw"], 186 | stdout=subprocess.DEVNULL) 187 | else: 188 | return 0 189 | 190 | def import_new_ebooks(self): 191 | # multithreaded conversion to epub before import, if necessary 192 | cpt = 1 193 | all_mobis = [os.path.join(self.config["import_dir"], el) 194 | for el in os.listdir(self.config["import_dir"]) 195 | if el.endswith(".mobi")] 196 | with ThreadPoolExecutor(max_workers=cpu_count()) as executor: 197 | future_epubs = { 198 | executor.submit(self._convert_to_epub_before_importing, 199 | mobi): mobi for mobi in all_mobis 200 | } 201 | for future in as_completed(future_epubs): 202 | if future.result() == 0: 203 | print(" %.2f%%" % (100*cpt/len(all_mobis)), 204 | end="\r", flush=True) 205 | cpt += 1 206 | else: 207 | raise Exception("Error converting to epub!") 208 | 209 | all_ebooks = [el for el in os.listdir(self.config["import_dir"]) 210 | if el.endswith(".epub")] 211 | if len(all_ebooks) == 0: 212 | print("Nothing new to import.") 213 | return False 214 | else: 215 | print("Importing.") 216 | 217 | all_already_imported_ebooks = [el 218 | for el 219 | in os.listdir( 220 | self.config["imported_dir"]) 221 | if el.endswith(".epub")] 222 | already_imported_hashes = [] 223 | for eb in all_already_imported_ebooks: 224 | already_imported_hashes.append( 225 | hashlib.sha1(open(os.path.join(self.config["imported_dir"], 226 | eb), 227 | 'rb').read()).hexdigest()) 228 | 229 | start = time.perf_counter() 230 | imported_count = 0 231 | for ebook in all_ebooks: 232 | ebook_candidate_full_path = os.path.join(self.config["import_dir"], 233 | ebook) 234 | 235 | # check for duplicate hash 236 | new_hash = hashlib.sha1(open(ebook_candidate_full_path, 237 | 'rb').read()).hexdigest() 238 | if new_hash in already_imported_hashes: 239 | print(" -> skipping already imported: ", ebook) 240 | continue 241 | 242 | # check for complete metadata 243 | temp_ebook = Epub(ebook_candidate_full_path, 244 | self.config["library_dir"], 245 | self.config["author_aliases"], 246 | self.ebook_filename_template) 247 | temp_ebook.open_ebook_metadata() 248 | if not temp_ebook.librarian_metadata.is_complete: 249 | print(" -> skipping ebook with incomplete metadata: ", ebook) 250 | continue 251 | 252 | # check if book not already in library 253 | already_in_db = False 254 | for eb in self.ebooks: 255 | same_authors = (eb.librarian_metadata.get_values("author") == 256 | temp_ebook.librarian_metadata.get_values("author")) 257 | same_title = (eb.librarian_metadata.get_values("title") == 258 | temp_ebook.librarian_metadata.get_values("title")) 259 | if same_authors and same_title: 260 | already_in_db = True 261 | break 262 | if already_in_db: 263 | print(" -> library already contains an entry for: ", 264 | temp_ebook.librarian_metadata.get_values("author")[0], 265 | " - ", temp_ebook.librarian_metadata.get_values("title")[0], 266 | ": ", ebook) 267 | continue 268 | 269 | if self.config.get("interactive", True): 270 | print("About to import: %s" % str(temp_ebook)) 271 | answer = input("Confirm? \ny/n? ") 272 | if answer.lower() == "n": 273 | print(" -> skipping ebook ", ebook) 274 | continue 275 | 276 | # if all checks are ok, importing 277 | print(" ->", ebook) 278 | # backup 279 | if self.config["backup_imported_ebooks"]: 280 | # backup original mobi version if it exists 281 | mobi_full_path = ebook_candidate_full_path.replace(".epub", 282 | ".mobi") 283 | if os.path.exists(mobi_full_path): 284 | shutil.move(mobi_full_path, 285 | os.path.join(self.config["imported_dir"], 286 | ebook.replace(".epub", ".mobi"))) 287 | shutil.copyfile(ebook_candidate_full_path, 288 | os.path.join(self.config["imported_dir"], 289 | ebook)) 290 | # import 291 | shutil.move(ebook_candidate_full_path, 292 | os.path.join(self.config["library_dir"], ebook)) 293 | imported_count += 1 294 | print("Imported ebooks in %.2fs." % (time.perf_counter() - start)) 295 | 296 | if imported_count != 0: 297 | return True 298 | else: 299 | return False 300 | 301 | def update_kindle_collections(self, outfile, filtered=[]): 302 | # generates the json file that is used 303 | # by the kual script in librariansync/ 304 | if filtered == []: 305 | ebooks_to_sync = self.ebooks 306 | else: 307 | ebooks_to_sync = filtered 308 | tags_json = {} 309 | for eb in sorted(ebooks_to_sync, key=lambda x: x.filename): 310 | relative_path = os.path.join( 311 | self.config["kindle_documents_subdir"], 312 | eb.exported_filename) 313 | tags_json[relative_path] = [eb.read.name] 314 | if eb.tags != []: 315 | tags_json[relative_path].append(eb.tags) 316 | 317 | f = codecs.open(outfile, "w", "utf8") 318 | f.write(json.dumps(tags_json, sort_keys=True, indent=2, 319 | separators=(',', ': '), ensure_ascii=False)) 320 | f.close() 321 | 322 | def sync_with_kindle(self, filtered=[], kindle_sync=True, 323 | destination_dir=None): 324 | if filtered == []: 325 | ebooks_to_sync = self.ebooks 326 | else: 327 | ebooks_to_sync = filtered 328 | 329 | if kindle_sync: 330 | print("Syncing with kindle.") 331 | if not os.path.exists(self.config["kindle_root"]): 332 | print("Kindle is not connected/mounted. Abandon ship.") 333 | return 334 | if not os.path.exists(self.config["kindle_documents"]): 335 | os.makedirs(self.config["kindle_documents"]) 336 | else: 337 | if destination_dir is None: 338 | print("Missing destination dir for sync. Abandon ship.") 339 | return 340 | if not os.path.exists(destination_dir): 341 | os.makedirs(destination_dir) 342 | 343 | start = time.perf_counter() 344 | 345 | if kindle_sync: 346 | output_dir = self.config["kindle_documents"] 347 | file_type = ".mobi" 348 | else: 349 | output_dir = destination_dir 350 | file_type = ".epub" 351 | 352 | # list all mobi/epub files in KINDLE_DOCUMENTS/destination_dir 353 | print(" -> Listing existing ebooks.") 354 | all_ebooks = [] 355 | for root, dirs, files in os.walk(output_dir): 356 | all_ebooks.extend([os.path.join(root, file) 357 | for file in files 358 | if os.path.splitext(file)[1] == file_type]) 359 | 360 | # sync books / convert to mobi 361 | print(" -> Syncing library.") 362 | cpt = 0 363 | if kindle_sync: 364 | threads = cpu_count() 365 | else: 366 | # when syncing epubs, only one thread, 367 | # to prevent race conditions when creating 368 | # directories. 369 | threads = 1 370 | 371 | with ThreadPoolExecutor(max_workers=threads) as executor: 372 | sorted_ebooks = sorted(ebooks_to_sync, key=lambda x: x.filename) 373 | if kindle_sync: 374 | all_sync = { 375 | executor.submit(eb.sync_with_kindle, 376 | self.config["kindle_documents"], 377 | self.config["mobi_dir"]): eb for eb 378 | in sorted_ebooks 379 | } 380 | else: 381 | all_sync = { 382 | executor.submit(eb.sync_with_kindle, 383 | destination_dir, 384 | None): eb for eb in sorted_ebooks 385 | } 386 | for future in as_completed(all_sync): 387 | ebook = all_sync[future] 388 | print(" %.2f%%" % (100*cpt/len(self.ebooks)), 389 | end="\r", flush=True) 390 | cpt += 1 391 | # remove ebook from the list of previously exported ebooks 392 | if kindle_sync: 393 | obsolete = os.path.join(output_dir, 394 | ebook.exported_filename) 395 | else: 396 | obsolete = os.path.join(output_dir, ebook.filename) 397 | if obsolete in all_ebooks: 398 | all_ebooks.remove(obsolete) 399 | 400 | # delete mobis on kindle that are not in library anymore 401 | print(" -> Removing obsolete ebooks.") 402 | for eb in all_ebooks: 403 | print(" + ", eb) 404 | os.remove(eb) 405 | 406 | # remove empty dirs in KINDLE_DOCUMENTS 407 | for root, dirs, files in os.walk(output_dir, topdown=False): 408 | for dir in [os.path.join(root, el) 409 | for el in dirs 410 | if os.listdir(os.path.join(root, el)) == []]: 411 | os.rmdir(dir) 412 | 413 | # sync collections.json 414 | if kindle_sync: 415 | print(" -> Generating and copying database for \ 416 | collection generation.") 417 | self.update_kindle_collections(self.config["collections"], 418 | filtered) 419 | shutil.copy(self.config["collections"], 420 | self.config["kindle_extensions"]) 421 | 422 | print("Library synced in %.2fs." % (time.perf_counter() - start)) 423 | 424 | def list_incomplete_metadata(self): 425 | found_incomplete = False 426 | incomplete_list = "" 427 | for eb in self.ebooks: 428 | if not eb.librarian_metadata.is_complete: 429 | found_incomplete = True 430 | incomplete_list += " -> %s\n" % eb.path 431 | if found_incomplete: 432 | print("The following ebooks have incomplete metadata:") 433 | print(incomplete_list) 434 | return found_incomplete 435 | 436 | def serve(self, filtered=[], kindle_sync=True): 437 | if filtered == []: 438 | ebooks_to_serve = self.ebooks 439 | else: 440 | ebooks_to_serve = filtered 441 | 442 | if not kindle_sync: 443 | allowed = [el.path for el in ebooks_to_serve] 444 | local_root = self.config["library_dir"] 445 | else: 446 | for eb in ebooks_to_serve: 447 | eb.export_to_mobi(self.config["mobi_dir"]) 448 | allowed = [os.path.join(self.config["mobi_dir"], 449 | el.exported_filename) 450 | for el in ebooks_to_serve] 451 | local_root = self.config["mobi_dir"] 452 | 453 | # create partial collections 454 | self.update_kindle_collections(self.config["collections"], filtered) 455 | 456 | print("Serving.") 457 | server = LibrarianServer((self.config["server"]["IP"], 458 | self.config["server"]["port"]), 459 | LibrarianHandler, allowed, 460 | local_root, self.config["collections"]) 461 | server.serve_forever() 462 | 463 | # removing collections json 464 | os.remove(self.config["collections"]) 465 | -------------------------------------------------------------------------------- /librarianlib/openlibrary_search.py: -------------------------------------------------------------------------------- 1 | import requests 2 | from .epub import unread, reading, read 3 | 4 | 5 | class SearchResult(object): 6 | def __init__(self, hit, description): 7 | self.author = ",".join(hit["author_name"]) 8 | self.title = hit["title"] 9 | self.year = hit.get("first_publish_year", "XXXX") 10 | self.description = description 11 | 12 | def __str__(self): 13 | return """\ 14 | Author: %s 15 | Title: %s 16 | First published: %s 17 | Description: %s 18 | """ % (self.author, self.title, self.year, self.description) 19 | 20 | def _diff(self, field, ebook): 21 | modified = "%s:\n %s -> %s" 22 | values = ebook.metadata.get_values(field) 23 | if values == []: 24 | values = ["(not found)"] 25 | if ",".join(values) != getattr(self, field): 26 | print(modified % (reading(field.title()), unread(",".join(values)), 27 | read(str(getattr(self, field))))) 28 | return True 29 | return False 30 | 31 | def compare_to_source(self, ebook): 32 | a = self._diff("author", ebook) 33 | t = self._diff("title", ebook) 34 | y = self._diff("year", ebook) 35 | d = self._diff("description", ebook) 36 | return (a or t or y or d) 37 | 38 | def copy_to_source(self, ebook): 39 | pass # TODO 40 | 41 | 42 | class OpenLibrarySearch(object): 43 | 44 | def __init__(self): 45 | self.search_url = "http://openlibrary.org/search.json?%s" 46 | self.works_url = "https://openlibrary.org/works/%s.json" 47 | 48 | def display_hit(self, hits, i): 49 | assert i < len(hits) 50 | hit = hits[i] 51 | about = requests.get(self.works_url % hit["key"]) 52 | about_json = about.json() 53 | description = about_json.get("description", None) 54 | description_str = "" 55 | if description is not None: 56 | description_str = description.get("value", "no description found.") 57 | sr = SearchResult(hit, description_str) 58 | print(sr) 59 | rep = input("(A)ccept, (N)ext, (P)revious? ").lower() 60 | if rep == "a": 61 | return sr 62 | elif rep == "n" and i < len(hits)-1: 63 | return self.display_hit(hits, i+1) # TODO test i 64 | elif rep == "p" and i != 0: 65 | return self.display_hit(hits, i-1) # TODO test i 66 | else: 67 | print("what?") 68 | 69 | def search(self, ebook): 70 | query = "author=%s&title=%s" % (ebook.metadata.get_values("author")[0], 71 | ebook.metadata.get_values("title")[0]) 72 | t = requests.get(self.search_url % 73 | query.replace(" ", "+").replace("-", "+")) 74 | hits = t.json().get("docs", None) 75 | if hits is not None and hits != []: 76 | chosen_hit = self.display_hit(hits, 0) 77 | return chosen_hit 78 | else: 79 | print("Nothing found on OpenLibrary!") 80 | return None 81 | --------------------------------------------------------------------------------