├── .gitignore ├── LICENSE.txt ├── README.md ├── flow.py ├── miner ├── __init__.py ├── base.py ├── bulkdata.py ├── cached_calls.py ├── fsd_binary.py ├── fsd_lite.py ├── metadata.py ├── sqlite.py ├── traits.py └── unpickle.py ├── run.py ├── scripts └── itemdiff.py ├── util ├── __init__.py ├── cached_property.py ├── eve_normalize.py ├── resource_browser.py └── translator.py └── writer ├── __init__.py ├── base.py └── json_writer.py /.gitignore: -------------------------------------------------------------------------------- 1 | .project 2 | .pydevproject 3 | *.pyc 4 | *.pyo 5 | __pycache__ 6 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 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 | Phobos - EVE Online client data converter to JSON 635 | Copyright (C) 2015 Anton Vorobyov 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 | Phobos Copyright (C) 2015 Anton Vorobyov 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 | # Phobos 2 | Phobos is script for dumping EVE client data into JSON format. 3 | 4 | It uses collection of data miners which extract data from files of various formats. It does not provide stable "API" by design: if CCP changes data scheme within EVE client, output files will also change. 5 | 6 | ### A note on safety 7 | Several data miners used in Phobos are doing potentially very dangerous thing security-wise, they are loading external code: 8 | 9 | - ResourcePickleMiner: [unpickles](https://docs.python.org/2.7/library/pickle.html) serialized python files 10 | - FsdBinaryMiner: executes loaders provided by the EVE client to access data in FSD binary format 11 | 12 | It doesn't mean that you should not use these miners. Generally speaking, if you trust EVE client and Phobos - you should have no issues with these miners. Phobos runs simple validation on files which will be worked upon (checksum according to the client's file registry). Still, it is recommended to run Phobos in some sandboxed environment (e.g. separate Wine prefix for Linux). 13 | 14 | ### Requirements 15 | 16 | * Python 2.7 17 | * [Reverence](https://github.com/ntt/reverence) 18 | * 64-bit python built for Windows is needed to access data in FSD binary format 19 | 20 | ### Arguments: 21 | 22 | * `--eve`: Required. Path to EVE client folder, e.g. `C:\CCP\EVE Online`. 23 | * `--json`: Required. Output folder for JSON files. 24 | * `--server`: Optional. Server to pull data from. Defaults to `tq`. Other options are `sisi`, `duality`, `thunderdome` and `serenity`. 25 | * `--calls`: Optional. Path to `CachedMethodCalls` folder, if you want to extract data from files contained within it. 26 | * `--translate`: Optional. Specifies language to which strings will be translated. You can choose either individual languages (run script with `--help` argument for a list) or 'multi' option. For individual language, translation will be done in-place (replaces original text with localized text), for multi-language translation, original text is not modified, but new text fields are added, named using `_` convention (e.g. `typeName_en-us`). Multi-language translation mode is default. 27 | * `--list`: Optional. Specifies list of comma-separated 'containers' to extract. It uses names the script prints to stdout. For list of all available names you can launch script without specifying this option, as by default it extracts everything it can find. 28 | 29 | ### Example 30 | 31 | $ python run.py --eve=E:\eve\client\ --json=~\Desktop\phobos_tq_en-us --list="evetypes, marketgroups, metadata" 32 | 33 | ### Phobos-specific data 34 | Besides raw data Phobos pulls from client, it provides two custom containers. 35 | 36 | #### phobos/metadata 37 | Contains just two parameters: client version and UNIX timestamp of the time script was invoked. 38 | 39 | #### phobos/traits 40 | Traits for various ships. Data has following format: 41 | 42 | Returned value: 43 | For single language: ({'typeID': int, 'traits': traits}, ...) 44 | For multi-language: ({'typeID': int, 'traits_en-us': traits, 'traits_ru': traits, ...}, ...) 45 | Traits: {'skills': (skill section, ...), 'role': role section, 'misc': misc section} 46 | // skills, role and misc fields are optional 47 | Section: {'header': string, 'bonuses': (bonus, ...)} 48 | Bonus: {'number': string, 'text': string} 49 | // number field is optional 50 | 51 | For example, Cambion traits in JSON format: 52 | 53 | { 54 | "traits": { 55 | "role": { 56 | "bonuses": [ 57 | {"number": "115%", "text": "bonus to kinetic Light Missile and Rocket damage"}, 58 | {"number": "50%", "text": "reduction in module heat damage amount taken"}, 59 | {"text": "·Can fit Assault Damage Controls"} 60 | ], 61 | "header": "Role Bonus:" 62 | }, 63 | "skills": [ 64 | { 65 | "bonuses": [{"number": "5%", "text": "bonus to Light Missile and Rocket Launcher rate of fire"}], 66 | "header": "Assault Frigates bonuses (per skill level):" 67 | }, 68 | { 69 | "bonuses": [{"number": "4%", "text": "bonus to all shield resistances"}], 70 | "header": "Caldari Frigate bonuses (per skill level):" 71 | } 72 | ] 73 | }, 74 | "typeID": 32788 75 | }, 76 | -------------------------------------------------------------------------------- /flow.py: -------------------------------------------------------------------------------- 1 | #=============================================================================== 2 | # Copyright (C) 2014-2019 Anton Vorobyov 3 | # 4 | # This file is part of Phobos. 5 | # 6 | # Phobos is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU Lesser General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # Phobos is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU Lesser General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU Lesser General Public License 17 | # along with Phobos. If not, see . 18 | #=============================================================================== 19 | 20 | 21 | import re 22 | 23 | 24 | class FlowManager(object): 25 | """ 26 | Class for handling high-level flow of script. 27 | """ 28 | 29 | def __init__(self, miners, writers): 30 | self._miners = miners 31 | self._writers = writers 32 | 33 | def run(self, filter_string, language): 34 | filter_set = self._parse_filter(name_filter=filter_string) 35 | missing_set = set(filter_set) 36 | # Filter something out only if filter was actually specified 37 | for miner in self._miners: 38 | container_names = [ 39 | cn for cn in miner.contname_iter() 40 | if not filter_set or cn in filter_set] 41 | if not container_names: 42 | continue 43 | print(u'Miner {}:'.format(miner.raw_name)) 44 | for container_name in sorted(container_names): 45 | print(u' processing {}'.format(container_name)) 46 | missing_set.discard(container_name) 47 | # Fetch data from client 48 | try: 49 | container_data = miner.get_data(container_name=container_name, language=language, verbose=True) 50 | except KeyboardInterrupt: 51 | raise 52 | except Exception as e: 53 | print(u' unable to fetch data - {}: {}'.format(type(e).__name__, e)) 54 | else: 55 | # Write data using passed writers 56 | for writer in self._writers: 57 | try: 58 | writer.write(miner_name=miner.name, container_name=container_name, container_data=container_data) 59 | except KeyboardInterrupt: 60 | raise 61 | except Exception as e: 62 | print(u' unable to write data with {} - {}: {}'.format(type(writer).__name__, type(e).__name__, e)) 63 | # Print info messages about requested, but unavailable containers 64 | if missing_set: 65 | print(u'Containers which were requested, but are not available:') 66 | for flow_name in sorted(missing_set): 67 | print(u' {}'.format(flow_name)) 68 | 69 | def _parse_filter(self, name_filter): 70 | """ 71 | Take filter string and return set of container names. 72 | """ 73 | name_set = NameSet() 74 | # Flag which indicates if we're within parenthesis 75 | # (are parsing argument substring) 76 | inarg = False 77 | pos_current = 0 78 | # Cycle through all parenthesis and commas, split string using 79 | # out-of-parenthesis commas 80 | for match in re.finditer('[(),]', name_filter): 81 | pos_start = match.start() 82 | pos_end = match.end() 83 | symbol = match.group() 84 | if symbol == ',' and inarg is False: 85 | name_set.add(name_filter[pos_current:pos_start]) 86 | pos_current = pos_end 87 | elif symbol == ',' and inarg is True: 88 | continue 89 | elif symbol == '(' and inarg is False: 90 | inarg = True 91 | elif symbol == ')' and inarg is True: 92 | inarg = False 93 | else: 94 | msg = u'unexpected character "{}" at position {}'.format(symbol, pos_start) 95 | raise FilterParseError(msg) 96 | if inarg is True: 97 | msg = 'parenthesis is not closed' 98 | raise FilterParseError(msg) 99 | # Add last segment of string after last seen comma 100 | name_set.add(name_filter[pos_current:]) 101 | return name_set 102 | 103 | 104 | class NameSet(set): 105 | """ 106 | Set derivative, which automatically strips added 107 | elements and actually adds them to internal storage 108 | only if they still contain something meaningful. 109 | """ 110 | 111 | def add(self, name): 112 | name = name.strip() 113 | if name: 114 | set.add(self, name) 115 | 116 | 117 | class FilterParseError(Exception): 118 | """ 119 | When received filter string cannot be parsed, 120 | this exception is raised. 121 | """ 122 | pass 123 | -------------------------------------------------------------------------------- /miner/__init__.py: -------------------------------------------------------------------------------- 1 | #=============================================================================== 2 | # Copyright (C) 2014-2019 Anton Vorobyov 3 | # 4 | # This file is part of Phobos. 5 | # 6 | # Phobos is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU Lesser General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # Phobos is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU Lesser General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU Lesser General Public License 17 | # along with Phobos. If not, see . 18 | #=============================================================================== 19 | 20 | 21 | from .base import ContainerNameError 22 | from .bulkdata import BulkdataMiner 23 | from .cached_calls import CachedCallsMiner 24 | from .fsd_binary import FsdBinaryMiner 25 | from .fsd_lite import FsdLiteMiner 26 | from .metadata import MetadataMiner 27 | from .sqlite import SqliteMiner 28 | from .traits import TraitMiner 29 | from .unpickle import PickleMiner 30 | 31 | 32 | __all__ = ( 33 | 'BulkdataMiner', 34 | 'CachedCallsMiner', 35 | 'FsdBinaryMiner', 36 | 'FsdLiteMiner', 37 | 'MetadataMiner', 38 | 'PickleMiner', 39 | 'SqliteMiner', 40 | 'TraitMiner') 41 | -------------------------------------------------------------------------------- /miner/base.py: -------------------------------------------------------------------------------- 1 | #=============================================================================== 2 | # Copyright (C) 2014-2019 Anton Vorobyov 3 | # 4 | # This file is part of Phobos. 5 | # 6 | # Phobos is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU Lesser General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # Phobos is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU Lesser General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU Lesser General Public License 17 | # along with Phobos. If not, see . 18 | #=============================================================================== 19 | 20 | 21 | from abc import ABCMeta, abstractmethod 22 | 23 | 24 | class BaseMiner(object): 25 | """ 26 | Abstract class, which defines interface to all data miners 27 | used in Phobos. 28 | """ 29 | __metaclass__ = ABCMeta 30 | 31 | @abstractmethod 32 | def contname_iter(self): 33 | """Provide an iterator over containers provided by miner.""" 34 | raise NotImplementedError 35 | 36 | @abstractmethod 37 | def get_data(self, container_name, **kwargs): 38 | """Fetch data from specified container.""" 39 | raise NotImplementedError 40 | 41 | @property 42 | def name(self): 43 | """Return miner group name, which can be used as output affix.""" 44 | return self.raw_name 45 | 46 | @property 47 | def raw_name(self): 48 | """Return miner class name.""" 49 | return type(self).__name__ 50 | 51 | def _container_not_found(self, cont_name): 52 | msg = u'container "{}" is not available for miner {}'.format(cont_name, type(self).__name__) 53 | raise ContainerNameError(msg) 54 | 55 | 56 | class ContainerNameError(Exception): 57 | """ 58 | When container with requested name is not available, 59 | this exception is raised by miners. 60 | """ 61 | pass 62 | -------------------------------------------------------------------------------- /miner/bulkdata.py: -------------------------------------------------------------------------------- 1 | #=============================================================================== 2 | # Copyright (C) 2014-2019 Anton Vorobyov 3 | # 4 | # This file is part of Phobos. 5 | # 6 | # Phobos is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU Lesser General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # Phobos is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU Lesser General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU Lesser General Public License 17 | # along with Phobos. If not, see . 18 | #=============================================================================== 19 | 20 | 21 | import re 22 | 23 | from reverence import blue 24 | 25 | from util import EveNormalizer, cachedproperty 26 | from .base import BaseMiner 27 | 28 | 29 | bulkdata_map = { 30 | 600005: 'invtypematerials', 31 | 600006: 'invmetagroups', 32 | 600007: 'invmetatypes', 33 | 600008: 'invcontrabandtypes', 34 | 600010: 'invtypereactions', 35 | 800003: 'dogmaexpressions', 36 | 800004: 'dogmaattributes', 37 | 800005: 'dogmaeffects', 38 | 800006: 'dogmatypeattributes', 39 | 800007: 'dogmatypeeffects', 40 | 800009: 'dogmaunits', 41 | 1400002: 'maplocationwormholeclasses', 42 | 1400008: 'mapcelestialdescriptions', 43 | 1400016: 'mapnebulas', 44 | 1800001: 'ramtyperequirements', 45 | 1800003: 'ramactivities', 46 | 1800004: 'ramassemblylinetypescategory', 47 | 1800005: 'ramassemblylinetypesgroup', 48 | 1800006: 'ramassemblylinetypes', 49 | 1800007: 'ramcompletedstatuses', 50 | 2000001: 'shiptypes', 51 | 2209987: 'stastationsstatic', 52 | 2209999: 'staoperations', 53 | 2800006: 'crpnpccorporations', 54 | 2809992: 'crptickernamesstatic', 55 | 3000012: 'agentepicarcs', 56 | 3000013: 'agentepicarcconnections', 57 | 3000015: 'agentepicarcmissions', 58 | 3009996: 'agentepicmissionmessages', 59 | 3200001: 'chrraces', 60 | 3200002: 'chrbloodlines', 61 | 3200010: 'chrbloodlinenames', 62 | 3200011: 'chrdefaultoverviews', 63 | 3200012: 'chrdefaultoverviewgroups', 64 | 3200015: 'chrfactions', 65 | 3200016: 'chrnpccharacters', 66 | 6400004: 'actbilltypes', 67 | 7300003: 'planetschematicspinmap', 68 | 7300004: 'planetschematics', 69 | 7300005: 'planetschematicstypemap', 70 | 7309999: 'planetblacklist', 71 | 100300014: 'mapdistricts', 72 | 100300015: 'mapbattlefields', 73 | 100300020: 'maplevels', 74 | 372833782: 'mapplanetsresources'} 75 | 76 | 77 | class BulkdataMiner(BaseMiner): 78 | """ 79 | Class, responsible for fetching data out of bulkdata, which is included 80 | with EVE client. 81 | """ 82 | 83 | name = 'bulkdata' 84 | 85 | def __init__(self, resbrowser, translator): 86 | self._resbrowser = resbrowser 87 | self._translator = translator 88 | 89 | def contname_iter(self): 90 | for container_name in sorted(self._contname_respath_map): 91 | yield container_name 92 | 93 | def get_data(self, container_name, language=None, verbose=False, **kwargs): 94 | try: 95 | resource_path = self._contname_respath_map[container_name] 96 | except KeyError: 97 | self._container_not_found(container_name) 98 | else: 99 | file_data = self._resbrowser.get_file_data(resource_path) 100 | container_data = blue.marshal.Load(file_data) 101 | normalized_data = EveNormalizer().run(container_data) 102 | self._translator.translate_container(normalized_data, language, verbose=verbose) 103 | return normalized_data 104 | 105 | @cachedproperty 106 | def _contname_respath_map(self): 107 | """ 108 | Map between container names and resource paths to files which hold actual data. 109 | Format: {container name: (fsd loader file path, fsd data file path)} 110 | """ 111 | contname_respath_map = {} 112 | for resource_path in self._resbrowser.respath_iter(): 113 | m = re.match('^app:/(\w+/)*(?P\d+).cache2$', resource_path, flags=re.UNICODE) 114 | if m: 115 | bulk_id = int(m.group('bulk_id')) 116 | container_name = bulkdata_map.get(bulk_id, unicode(bulk_id)) 117 | contname_respath_map[container_name] = resource_path 118 | return contname_respath_map 119 | -------------------------------------------------------------------------------- /miner/cached_calls.py: -------------------------------------------------------------------------------- 1 | #=============================================================================== 2 | # Copyright (C) 2014-2019 Anton Vorobyov 3 | # 4 | # This file is part of Phobos. 5 | # 6 | # Phobos is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU Lesser General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # Phobos is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU Lesser General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU Lesser General Public License 17 | # along with Phobos. If not, see . 18 | #=============================================================================== 19 | 20 | 21 | import glob 22 | import os.path 23 | 24 | from reverence import blue 25 | 26 | from util import EveNormalizer, cachedproperty 27 | from .base import BaseMiner 28 | 29 | 30 | class CachedCallsMiner(BaseMiner): 31 | """ 32 | Class, responsible for fetching data from EVE client's 33 | remote service call cache. 34 | """ 35 | 36 | name = 'cached_calls' 37 | 38 | def __init__(self, path_cachedcalls, translator): 39 | self._path_cachedcalls = path_cachedcalls 40 | self._translator = translator 41 | 42 | def contname_iter(self): 43 | for container_name in sorted(self._contname_filepath_map): 44 | yield container_name 45 | 46 | def get_data(self, container_name, language=None, verbose=False, **kwargs): 47 | try: 48 | filepath = self._contname_filepath_map[container_name] 49 | except KeyError: 50 | self._container_not_found(container_name) 51 | else: 52 | _, call_data = self.__read_cache_file(filepath) 53 | normalized_data = EveNormalizer().run(call_data) 54 | self._translator.translate_container(normalized_data, language, verbose=verbose) 55 | return normalized_data 56 | 57 | @cachedproperty 58 | def _contname_filepath_map(self): 59 | """ 60 | Make map with cache filenames, keyed against formatted call names. 61 | Format: {container name: path to file} 62 | """ 63 | contname_filepath_map = {} 64 | # Path might be not specified, in this case do not do anything 65 | if self._path_cachedcalls: 66 | # Cycle through CachedMethodCalls and find all .cache files 67 | for file_path in glob.glob(os.path.join(self._path_cachedcalls, '*.cache')): 68 | # In case file cannot be loaded due to any reasons, skip it 69 | try: 70 | call_info, _ = self.__read_cache_file(file_path) 71 | except KeyboardInterrupt: 72 | raise 73 | except: 74 | file_name = os.path.basename(file_path) 75 | print(u' unable to load cache file {}'.format(file_name)) 76 | continue 77 | # Info has one of 2 following formats: 78 | # - ((service name, service arg1, service arg2, ...), call name, call arg1, call arg2, ...) 79 | # - (service name, call name, call arg1, call arg2, ...) 80 | # Here we parse info structure according to one of these formats 81 | svc_info = call_info[0] 82 | call_info = call_info[1:] 83 | if isinstance(svc_info, (tuple, list)): 84 | svc_name = svc_info[0] 85 | svc_args = svc_info[1:] 86 | else: 87 | svc_name = svc_info 88 | svc_args = () 89 | call_name = call_info[0] 90 | call_args = call_info[1:] 91 | svc_args_line = u', '.join(unicode(a) for a in svc_args) 92 | call_args_line = u', '.join(unicode(a) for a in call_args) 93 | # Finally, compose full service call in human-readable format and put it into dictionary 94 | container_name = u'{}({})_{}({})'.format(svc_name, svc_args_line, call_name, call_args_line) 95 | contname_filepath_map[container_name] = file_path 96 | return contname_filepath_map 97 | 98 | def __read_cache_file(self, filepath): 99 | """ 100 | Read & load file located at filepath, and return it as 101 | tuple with call info and actual cached method result. 102 | """ 103 | with open(filepath, 'rb') as cachefile: 104 | filedata = cachefile.read() 105 | cached_call_info, cached_call_data = blue.marshal.Load(filedata) 106 | return cached_call_info, cached_call_data['lret'] 107 | -------------------------------------------------------------------------------- /miner/fsd_binary.py: -------------------------------------------------------------------------------- 1 | #=============================================================================== 2 | # Copyright (C) 2014-2019 Anton Vorobyov 3 | # 4 | # This file is part of Phobos. 5 | # 6 | # Phobos is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU Lesser General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # Phobos is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU Lesser General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU Lesser General Public License 17 | # along with Phobos. If not, see . 18 | #=============================================================================== 19 | 20 | 21 | import contextlib 22 | import gc 23 | import importlib 24 | import os 25 | import re 26 | import shutil 27 | import struct 28 | import sys 29 | import tempfile 30 | 31 | from util import EveNormalizer, cachedproperty 32 | from .base import BaseMiner 33 | 34 | 35 | class FsdBinaryMiner(BaseMiner): 36 | 37 | name = 'fsd_binary' 38 | 39 | def __init__(self, resbrowser, translator): 40 | self._resbrowser = resbrowser 41 | self._translator = translator 42 | self.__temp_dir = None 43 | 44 | def contname_iter(self): 45 | for container_name in sorted(self._contname_fsdfiles_map): 46 | yield container_name 47 | 48 | def get_data(self, container_name, language=None, verbose=False, **kwargs): 49 | try: 50 | loader_respath, data_respath = self._contname_fsdfiles_map[container_name] 51 | except KeyError: 52 | self._container_not_found(container_name) 53 | else: 54 | if os.name != 'nt' or struct.calcsize('P') * 8 != 64: 55 | msg = 'need 64-bit python under Windows to execute loader' 56 | raise PlatformError(msg) 57 | loader_filename = loader_respath.split('/')[-1] 58 | loader_info = self._resbrowser.get_file_info(loader_respath) 59 | data_info = self._resbrowser.get_file_info(data_respath) 60 | 61 | with self._temp_dir() as temp_dir: 62 | sys.path.insert(0, temp_dir) 63 | 64 | loader_dest = os.path.join(temp_dir, loader_filename) 65 | if not os.path.isfile(loader_dest) or not self._compare_files(loader_info.file_abspath, loader_dest): 66 | shutil.copyfile(loader_info.file_abspath, loader_dest) 67 | 68 | loader_modname = os.path.splitext(loader_filename)[0] 69 | loader_module = importlib.import_module(loader_modname) 70 | fsd_data = loader_module.load(data_info.file_abspath) 71 | normalized_data = EveNormalizer().run(fsd_data, loader_module=loader_module) 72 | 73 | sys.path.remove(temp_dir) 74 | del loader_module 75 | del sys.modules[loader_modname] 76 | gc.collect() 77 | 78 | self._translator.translate_container(normalized_data, language, verbose=verbose) 79 | return normalized_data 80 | 81 | @cachedproperty 82 | def _contname_fsdfiles_map(self): 83 | """ 84 | Map between container names and locations of FSD loader/data. 85 | Format: {container name: (fsd loader file path, fsd data file path)} 86 | """ 87 | loaders = {} 88 | datas = {} 89 | for resource_path in self._resbrowser.respath_iter(): 90 | m = re.match('^app:/bin64/(\w+/)*(?P\w+)Loader.pyd$', resource_path, flags=re.UNICODE) 91 | if m: 92 | loaders[m.group('name').lower()] = resource_path 93 | continue 94 | m = re.match('^res:/staticdata/(\w+/)*(?P\w+).fsdbinary$', resource_path, flags=re.UNICODE) 95 | if m: 96 | datas[m.group('name').lower()] = resource_path 97 | continue 98 | contname_fsdfiles_map = {} 99 | for container_name in set(loaders).intersection(datas): 100 | contname_fsdfiles_map[container_name] = (loaders[container_name], datas[container_name]) 101 | return contname_fsdfiles_map 102 | 103 | @contextlib.contextmanager 104 | def _temp_dir(self): 105 | """A context manager for creating and then deleting a temporary directory.""" 106 | if self.__temp_dir is None: 107 | self.__temp_dir = tempfile.mkdtemp(prefix='phobos-') 108 | try: 109 | yield self.__temp_dir 110 | # Try to remove folder, but be silent if it fails, as it is to be expected, because 111 | # python process which has used library from this folder is still running 112 | finally: 113 | error_data = [] 114 | 115 | def on_error(*args, **kwargs): 116 | error_data.append((args, kwargs)) 117 | 118 | shutil.rmtree(self.__temp_dir, ignore_errors=False, onerror=on_error) 119 | # Avoid creating new dirs in future if we haven't removed this one 120 | if not error_data: 121 | self.__temp_dir = None 122 | 123 | def _compare_files(self, file1_path, file2_path): 124 | with open(file1_path, 'rb') as f1, open(file2_path, 'rb') as f2: 125 | return f1.read() == f2.read() 126 | 127 | 128 | class PlatformError(Exception): 129 | """Raised when FSD binary miner is used on incorrect platform.""" 130 | pass 131 | -------------------------------------------------------------------------------- /miner/fsd_lite.py: -------------------------------------------------------------------------------- 1 | #=============================================================================== 2 | # Copyright (C) 2014-2019 Anton Vorobyov 3 | # 4 | # This file is part of Phobos. 5 | # 6 | # Phobos is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU Lesser General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # Phobos is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU Lesser General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU Lesser General Public License 17 | # along with Phobos. If not, see . 18 | #=============================================================================== 19 | 20 | 21 | import json 22 | import re 23 | import sqlite3 24 | 25 | from miner.base import BaseMiner 26 | from util import cachedproperty 27 | 28 | 29 | class FsdLiteMiner(BaseMiner): 30 | """Class, which fetches data from FSDLite format static cache files.""" 31 | 32 | name = 'fsd_lite' 33 | 34 | def __init__(self, resbrowser, translator): 35 | self._resbrowser = resbrowser 36 | self._translator = translator 37 | 38 | def contname_iter(self): 39 | for container_name in sorted(self._contname_respath_map): 40 | yield container_name 41 | 42 | def get_data(self, container_name, language=None, verbose=False, **kwargs): 43 | try: 44 | resource_path = self._contname_respath_map[container_name] 45 | except KeyError: 46 | self._container_not_found(container_name) 47 | else: 48 | rows = {} 49 | file_path = self._resbrowser.get_file_info(resource_path).file_abspath 50 | with sqlite3.connect(file_path) as dbconn: 51 | c = dbconn.cursor() 52 | c.execute(u'select key, value from cache') 53 | for sqlite_row in c: 54 | key = sqlite_row[0] 55 | value = sqlite_row[1] 56 | row = json.loads(value) 57 | rows[key] = row 58 | self._translator.translate_container(rows, language, verbose=verbose) 59 | return rows 60 | 61 | @cachedproperty 62 | def _contname_respath_map(self): 63 | """ 64 | Map between container names and resource path names to static cache files. 65 | Format: {container path: resource path to static cache} 66 | """ 67 | contname_respath_map = {} 68 | for resource_path in self._resbrowser.respath_iter(): 69 | # Filter by resource file path first 70 | container_name = self.__get_container_name(resource_path) 71 | if container_name is None: 72 | continue 73 | # Now, check if it's actually sqlite database and if it has cache table 74 | if not self.__check_cache(resource_path): 75 | continue 76 | contname_respath_map[container_name] = resource_path 77 | return contname_respath_map 78 | 79 | def __get_container_name(self, resource_path): 80 | """ 81 | Validate resource path and return stripped resource 82 | name if path is valid, return None otherwise. 83 | """ 84 | m = re.match(r'^res:/staticdata/(?P.+).static$', resource_path) 85 | if not m: 86 | return None 87 | return m.group('fname') 88 | 89 | def __check_cache(self, resource_path): 90 | """Check if file is actually SQLite database and has cache table.""" 91 | file_path = self._resbrowser.get_file_info(resource_path).file_abspath 92 | try: 93 | dbconn = sqlite3.connect(file_path) 94 | c = dbconn.cursor() 95 | c.execute('select count(*) from sqlite_master where type = \'table\' and name = \'cache\'') 96 | except KeyboardInterrupt: 97 | raise 98 | except: 99 | has_cache = False 100 | else: 101 | has_cache = False 102 | for row in c: 103 | has_cache = bool(row[0]) 104 | return has_cache 105 | -------------------------------------------------------------------------------- /miner/metadata.py: -------------------------------------------------------------------------------- 1 | #=============================================================================== 2 | # Copyright (C) 2014-2019 Anton Vorobyov 3 | # 4 | # This file is part of Phobos. 5 | # 6 | # Phobos is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU Lesser General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # Phobos is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU Lesser General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU Lesser General Public License 17 | # along with Phobos. If not, see . 18 | #=============================================================================== 19 | 20 | 21 | import os.path 22 | from ConfigParser import ConfigParser 23 | from time import time 24 | 25 | from .base import BaseMiner 26 | 27 | 28 | class MetadataMiner(BaseMiner): 29 | """ 30 | Provide some metadata on when this data dump has been made 31 | and which data source has been used for that. 32 | """ 33 | 34 | name = 'phobos' 35 | 36 | def __init__(self, resbrowser): 37 | self._resbrowser = resbrowser 38 | self._container_name = 'metadata' 39 | 40 | def contname_iter(self): 41 | yield self._container_name 42 | 43 | def get_data(self, container_name, **kwargs): 44 | if container_name != self._container_name: 45 | self._container_not_found(container_name) 46 | else: 47 | file_info = self._resbrowser.get_file_info('app:/start.ini') 48 | field_names = ('field_name', 'field_value') 49 | container_data = [] 50 | # Read client version 51 | try: 52 | config = ConfigParser() 53 | config.read(file_info.file_abspath) 54 | eve_version = config.getint('main', 'build') 55 | except KeyboardInterrupt: 56 | raise 57 | except: 58 | print(u' failed to detect client version') 59 | eve_version = None 60 | container_data.append({field_names[0]: 'client_build', field_names[1]: eve_version}) 61 | # Generate UNIX-style timestamp of current UTC time 62 | timestamp = int(time()) 63 | container_data.append({field_names[0]: 'dump_time', field_names[1]: timestamp}) 64 | return tuple(container_data) 65 | -------------------------------------------------------------------------------- /miner/sqlite.py: -------------------------------------------------------------------------------- 1 | #=============================================================================== 2 | # Copyright (C) 2014-2019 Anton Vorobyov 3 | # 4 | # This file is part of Phobos. 5 | # 6 | # Phobos is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU Lesser General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # Phobos is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU Lesser General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU Lesser General Public License 17 | # along with Phobos. If not, see . 18 | #=============================================================================== 19 | 20 | 21 | import sqlite3 22 | 23 | from util import cachedproperty 24 | from .base import BaseMiner 25 | 26 | 27 | class SqliteMiner(BaseMiner): 28 | """ 29 | Extract data from SQLite databases bundled with client. 30 | """ 31 | 32 | name = 'sqlite' 33 | 34 | def __init__(self, resbrowser, translator): 35 | # Format: {db alias: db path} 36 | self._resbrowser = resbrowser 37 | self._translator = translator 38 | 39 | def contname_iter(self): 40 | for container_name in sorted(self._contname_dbtable_map): 41 | yield container_name 42 | 43 | def get_data(self, container_name, language=None, verbose=False, **kwargs): 44 | try: 45 | dbpath, table_name = self._contname_dbtable_map[container_name] 46 | except KeyError: 47 | self._container_not_found(container_name) 48 | else: 49 | rows = [] 50 | with sqlite3.connect(dbpath) as dbconn: 51 | c = dbconn.cursor() 52 | c.execute(u'select * from {}'.format(table_name)) 53 | headers = list(map(lambda x: x[0], c.description)) 54 | for sqlite_row in c: 55 | row = dict(zip(headers, sqlite_row)) 56 | rows.append(row) 57 | self._translator.translate_container(rows, language, verbose=verbose) 58 | return rows 59 | 60 | @cachedproperty 61 | def _contname_dbtable_map(self): 62 | """ 63 | Map between container names and DB tables where data is stored. 64 | Format: {container name: (db alias, table name)} 65 | """ 66 | sqlite_ext = '.db' 67 | contname_dbtable_map = {} 68 | for resource_path in self._resbrowser.respath_iter(): 69 | if not resource_path.endswith(sqlite_ext): 70 | continue 71 | resource_info = self._resbrowser.get_file_info(resource_path) 72 | with sqlite3.connect(resource_info.file_abspath) as dbconn: 73 | c = dbconn.cursor() 74 | c.execute('select name from sqlite_master where type = \'table\'') 75 | for row in c: 76 | table_name = row[0] 77 | container_name = u'{}_{}'.format(resource_path[:-len(sqlite_ext)], table_name) 78 | contname_dbtable_map[container_name] = (resource_info.file_abspath, table_name) 79 | return contname_dbtable_map 80 | -------------------------------------------------------------------------------- /miner/traits.py: -------------------------------------------------------------------------------- 1 | #=============================================================================== 2 | # Copyright (C) 2014-2019 Anton Vorobyov 3 | # 4 | # This file is part of Phobos. 5 | # 6 | # Phobos is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU Lesser General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # Phobos is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU Lesser General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU Lesser General Public License 17 | # along with Phobos. If not, see . 18 | #=============================================================================== 19 | 20 | 21 | import re 22 | 23 | from .base import BaseMiner 24 | 25 | 26 | tags = re.compile('<.+?>') 27 | 28 | 29 | def striptags(text): 30 | return tags.sub('', text) 31 | 32 | 33 | class TraitMiner(BaseMiner): 34 | """ 35 | Phobos actually dumps all the required data needed 36 | to compose item traits. We're doing it internally for 37 | convenience of phobos users anyway. 38 | """ 39 | 40 | name = 'phobos' 41 | 42 | def __init__(self, fsdlite_miner, fsdbinary_miner, translator): 43 | self._fsdlite_miner = fsdlite_miner 44 | self._fsdbinary_miner = fsdbinary_miner 45 | self._translator = translator 46 | self._container_name = 'traits' 47 | # Format: {language: {type ID: type name}} 48 | self._type_name_map_all = {} 49 | # Format: {language: {unit ID: unit display name}} 50 | self._unit_display_map_all = {} 51 | 52 | def contname_iter(self): 53 | yield self._container_name 54 | 55 | def get_data(self, container_name, language='en-us', **kwargs): 56 | if container_name != self._container_name: 57 | self._container_not_found(container_name) 58 | else: 59 | return self._all_traits(language) 60 | 61 | def _all_traits(self, language): 62 | """ 63 | Compose list of traits. Format: 64 | Returned value: 65 | For single language: ({'typeID': int, 'traits': traits}, ...) 66 | For multi-language: ({'typeID': int, 'traits_en-us': traits, 'traits_ru': traits, ...}, ...) 67 | Traits: {'skills': (skill section, ...), 'role': role section, 'misc': misc section} 68 | skills, role and misc fields are optional 69 | Section: {'header': string, 'bonuses': (bonus, ...)} 70 | Bonus: {'number': string, 'text': string} 71 | number field is optional 72 | """ 73 | trait_rows = [] 74 | bubble_data = self._fsdlite_miner.get_data('infobubbles') 75 | for type_id, trait_data in bubble_data['infoBubbleTypeBonuses'].items(): 76 | type_id = int(type_id) 77 | trait_row = {'typeID': type_id} 78 | # For multi-language, each trait row will contain traits for 79 | # all languages in fields named like traits_en-us 80 | if language == 'multi': 81 | for mlanguage in self._translator.available_langs: 82 | traits_header = u'traits_{}'.format(mlanguage) 83 | traits = self._type_traits(trait_data, mlanguage) 84 | trait_row[traits_header] = traits 85 | # For single language, we will have just single field named 86 | # traits 87 | else: 88 | traits = self._type_traits(trait_data, language) 89 | trait_row['traits'] = traits 90 | trait_rows.append(trait_row) 91 | return tuple(trait_rows) 92 | 93 | def _type_traits(self, trait_data, language): 94 | """ 95 | Return traits for single item. 96 | """ 97 | traits = {} 98 | # Go through skill-based traits first 99 | if "types" in trait_data: 100 | skill_ids = [int(k) for k in trait_data["types"].keys()] 101 | if skill_ids: 102 | skill_rows = [] 103 | for skill_typeid in skill_ids: 104 | skill_name = self._get_type_name(skill_typeid, language) 105 | section_header = self._translator.get_by_label('UI/ShipTree/SkillNameCaption', language, skillName=skill_name) 106 | section_data = trait_data[u"types"][unicode(skill_typeid)] 107 | bonuses = self._section_bonuses(section_data, language) 108 | skill_row = {'header': section_header, 'bonuses': bonuses} 109 | skill_rows.append(skill_row) 110 | traits['skills'] = tuple(skill_rows) 111 | 112 | # Then traits for all known special sections 113 | for special_type, special_label, cont_alias in ( 114 | ('roleBonuses', 'UI/ShipTree/RoleBonus', 'role'), 115 | ('miscBonuses', 'UI/ShipTree/MiscBonus', 'misc') 116 | ): 117 | if special_type not in trait_data: 118 | continue 119 | section_header = self._translator.get_by_label(special_label, language) 120 | section_data = trait_data[special_type] 121 | if len(section_data) == 0: 122 | continue 123 | bonuses = self._section_bonuses(section_data, language) 124 | special_row = {'header': section_header, 'bonuses': bonuses} 125 | traits[cont_alias] = special_row 126 | return traits 127 | 128 | def _section_bonuses(self, section_data, language): 129 | """ 130 | Receive section data, in the format it is stored 131 | in client, and convert it to phobos-specific format 132 | with actual bonuses description. Section is part of 133 | what you see in traits table - e.g. bonuses from one 134 | skill with header (there can be multiple). 135 | """ 136 | bonuses = [] 137 | # Use sorting as defined by EVE (index seems to be not used 138 | # for anything apart from this) 139 | sorted_bonuses = sorted(section_data, key=lambda k: k['importance']) 140 | for bonus_data in sorted_bonuses: 141 | #bonus_data = section_data[unicode(bonus_index)] 142 | bonus_msgid = bonus_data['nameID'] 143 | bonus_text = self._translator.get_by_message(bonus_msgid, language) 144 | bonus_amt = bonus_data.get('bonus') 145 | # Bonuses can be with numerical value and without it, they have different 146 | # processing. Also, they are flooded with various HTML tags, we strip them 147 | # here. 148 | if bonus_amt is not None: 149 | # Some bonuses are represented as non-rounded float, like 150 | # 33.2999992371 for Confessor's defensive mode resistance bonus, 151 | # here we make sure it's properly rounded to values like 33.3 152 | bonus_amt = round(bonus_amt, 5) 153 | if int(bonus_amt) == bonus_amt: 154 | bonus_amt = int(bonus_amt) 155 | unit = self._get_unit_displayname(bonus_data['unitID'], language) 156 | bonus = self._translator.get_by_label( 157 | 'UI/InfoWindow/TraitWithNumber', 158 | language, 159 | color='', 160 | value=bonus_amt, 161 | unit=unit, 162 | bonusText=bonus_text) 163 | number, text = (striptags(t) for t in bonus.split('')) 164 | bonus_row = {'number': number, 'text': text} 165 | else: 166 | bonus = self._translator.get_by_label( 167 | 'UI/InfoWindow/TraitWithoutNumber', 168 | language, 169 | color='', 170 | bonusText=bonus_text) 171 | text = striptags(bonus) 172 | bonus_row = {'text': text} 173 | bonuses.append(bonus_row) 174 | return tuple(bonuses) 175 | 176 | def _get_type_name(self, typeid, language): 177 | """ 178 | Get translated name for specified type and language. 179 | """ 180 | try: 181 | type_name_map = self._type_name_map_all[language] 182 | except KeyError: 183 | types = self._fsdbinary_miner.get_data('types', language=language) 184 | type_name_map = {} 185 | for type_id, type_row in types.items(): 186 | type_id = int(type_id) 187 | type_name_map[type_id] = type_row.get('typeName') 188 | self._type_name_map_all[language] = type_name_map 189 | return type_name_map[typeid] 190 | 191 | def _get_unit_displayname(self, unitid, language): 192 | """ 193 | Get unit display name for specified type and language. 194 | """ 195 | try: 196 | unit_display_map = self._unit_display_map_all[language] 197 | except KeyError: 198 | dgmunits = self._fsdbinary_miner.get_data('dogmaunits', language=language) 199 | unit_display_map = {} 200 | for unit_id, unit_data in dgmunits.items(): 201 | unit_display_map[unit_id] = unit_data.get('displayName') 202 | self._unit_display_map_all[language] = unit_display_map 203 | return unit_display_map[unitid] 204 | -------------------------------------------------------------------------------- /miner/unpickle.py: -------------------------------------------------------------------------------- 1 | #=============================================================================== 2 | # Copyright (C) 2014-2019 Anton Vorobyov 3 | # 4 | # This file is part of Phobos. 5 | # 6 | # Phobos is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU Lesser General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # Phobos is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU Lesser General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU Lesser General Public License 17 | # along with Phobos. If not, see . 18 | #=============================================================================== 19 | 20 | 21 | import pickle 22 | 23 | from miner.base import BaseMiner 24 | from util import cachedproperty 25 | 26 | 27 | class PickleMiner(BaseMiner): 28 | """Class, which attempts to get data from resource pickles (which is not guaranteed to succeed).""" 29 | 30 | name = 'resource_pickle' 31 | 32 | def __init__(self, resbrowser): 33 | self._resbrowser = resbrowser 34 | 35 | def contname_iter(self): 36 | for container_name in sorted(self._contname_respath_map): 37 | yield container_name 38 | 39 | def get_data(self, container_name, **kwargs): 40 | try: 41 | resource_path = self._contname_respath_map[container_name] 42 | except KeyError: 43 | self._container_not_found(container_name) 44 | else: 45 | resource_data = self._resbrowser.get_file_data(resource_path) 46 | data = pickle.loads(resource_data) 47 | return data 48 | 49 | @cachedproperty 50 | def _contname_respath_map(self): 51 | """ 52 | Map between container names and resource path names to pickle files. 53 | Format: {container name: resource path to pickle} 54 | """ 55 | pickle_ext = '.pickle' 56 | contname_respath_map = {} 57 | for resource_path in self._resbrowser.respath_iter(): 58 | if not resource_path.endswith(pickle_ext): 59 | continue 60 | container_name = resource_path[:-len(pickle_ext)] 61 | contname_respath_map[container_name] = resource_path 62 | return contname_respath_map 63 | -------------------------------------------------------------------------------- /run.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | #=============================================================================== 3 | # Copyright (C) 2014-2019 Anton Vorobyov 4 | # 5 | # This file is part of Phobos. 6 | # 7 | # Phobos is free software: you can redistribute it and/or modify 8 | # it under the terms of the GNU Lesser General Public License as published by 9 | # the Free Software Foundation, either version 3 of the License, or 10 | # (at your option) any later version. 11 | # 12 | # Phobos is distributed in the hope that it will be useful, 13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | # GNU Lesser General Public License for more details. 16 | # 17 | # You should have received a copy of the GNU Lesser General Public License 18 | # along with Phobos. If not, see . 19 | #=============================================================================== 20 | 21 | 22 | import sys 23 | 24 | from flow import FlowManager 25 | from miner import * 26 | from writer import * 27 | from util import ResourceBrowser, Translator 28 | 29 | 30 | def run(path_eve, server_alias, path_cachedcalls, filter_string, language, path_json, group=None): 31 | resource_browser = ResourceBrowser(eve_path=path_eve, server_alias=server_alias) 32 | 33 | pickle_miner = PickleMiner(resbrowser=resource_browser) 34 | trans = Translator(pickle_miner=pickle_miner) 35 | fsdlite_miner = FsdLiteMiner(resbrowser=resource_browser, translator=trans) 36 | fsdbinary_miner = FsdBinaryMiner(resbrowser=resource_browser, translator=trans) 37 | miners = [ 38 | MetadataMiner(resbrowser=resource_browser), 39 | BulkdataMiner(resbrowser=resource_browser, translator=trans), 40 | fsdlite_miner, 41 | fsdbinary_miner, 42 | TraitMiner(fsdlite_miner=fsdlite_miner, fsdbinary_miner=fsdbinary_miner, translator=trans), 43 | SqliteMiner(resbrowser=resource_browser, translator=trans), 44 | CachedCallsMiner(path_cachedcalls=path_cachedcalls, translator=trans), 45 | pickle_miner] 46 | 47 | writers = [ 48 | JsonWriter(path_json, indent=2, group=group)] 49 | 50 | FlowManager(miners, writers).run(filter_string=filter_string, language=language) 51 | 52 | 53 | if __name__ == '__main__': 54 | 55 | try: 56 | major = sys.version_info.major 57 | minor = sys.version_info.minor 58 | except AttributeError: 59 | major = sys.version_info[0] 60 | minor = sys.version_info[1] 61 | if major != 2 or minor < 7: 62 | sys.stderr.write('This application requires Python 2.7 to run, but {0}.{1} was used\n'.format(major, minor)) 63 | sys.exit() 64 | 65 | import argparse 66 | import os.path 67 | 68 | parser = argparse.ArgumentParser(description='This script extracts data from EVE client and writes it into JSON files') 69 | parser.add_argument('-e', '--eve', required=True, 70 | help='Path to EVE client\'s folder') 71 | parser.add_argument('-c', '--calls', default='', 72 | help='Path to CachedMethodCalls folder') 73 | parser.add_argument('-s', '--server', default='tq', 74 | help='Server to pull data from. Default is "tq"', 75 | choices=('tq', 'sisi', 'duality', 'thunderdome', 'serenity')) 76 | parser.add_argument('-j', '--json', required=True, 77 | help='Output folder for the JSON files') 78 | parser.add_argument('-t', '--translate', default='multi', 79 | help='Attempt to translate strings into specified language. Default is "multi"', 80 | choices=('de', 'en-us', 'es', 'fr', 'it', 'ja', 'ru', 'zh', 'multi')) 81 | parser.add_argument('-l', '--list', default='', 82 | help='Comma-separated list of container names to extract. If not specified, extracts everything') 83 | parser.add_argument('-g', '--group', type=int, default=None, 84 | help='Split output into several files, containing this amount of top-level entities at most') 85 | args = parser.parse_args() 86 | 87 | # Expand home directory 88 | path_eve = os.path.expanduser(args.eve) 89 | path_cachedcalls = os.path.expanduser(args.calls) 90 | path_json = os.path.expanduser(args.json) 91 | 92 | run(path_eve=path_eve, server_alias=args.server, path_cachedcalls=path_cachedcalls, filter_string=args.list, 93 | language=args.translate, path_json=path_json, group=args.group) 94 | -------------------------------------------------------------------------------- /scripts/itemdiff.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import argparse 4 | import enum 5 | import json 6 | import os.path 7 | from collections import OrderedDict, namedtuple 8 | from datetime import datetime, timedelta, timezone 9 | 10 | 11 | ChangedItem = namedtuple('ChangedItem', ('old', 'new')) 12 | Changes = namedtuple('Changes', ('removed', 'changed', 'added')) 13 | 14 | 15 | class Container: 16 | 17 | def __init__(self, **kwargs): 18 | self.__dict__.update(**kwargs) 19 | 20 | def __repr__(self): 21 | attrs = ', '.join('{}={}'.format(attr, self.__dict__[attr]) for attr in sorted(self.__dict__)) 22 | return '{}({})'.format(type(self).__name__, attrs) 23 | 24 | 25 | class Type(Container): 26 | 27 | def __init__(self, **kwargs): 28 | self.id = None 29 | self.published = None 30 | self.name = None 31 | self.group_id = None 32 | self.market_group_id = None 33 | self.attributes = {} 34 | self.effects = [] 35 | self.mats_build = {} 36 | self.mats_reprocess = {} 37 | Container.__init__(self, **kwargs) 38 | 39 | def __eq__(self, o): 40 | if ( 41 | self.id != o.id or 42 | (process_pub and self.published != o.published) or 43 | self.name != o.name or 44 | self.group_id != o.group_id or 45 | (process_mkt and self.market_group_id != o.market_group_id) or 46 | (process_attrs and self.attributes != o.attributes) or 47 | (process_effects and self.effects != o.effects) or 48 | (process_mats and self.mats_build != o.mats_build) or 49 | (process_mats and self.mats_reprocess != o.mats_reprocess) 50 | ): 51 | return False 52 | else: 53 | return True 54 | 55 | def __neq__(self, o): 56 | return not self.__eq__(o) 57 | 58 | 59 | @enum.unique 60 | class BasicAttribs(enum.IntEnum): 61 | mass = 4 62 | capacity = 38 63 | volume = 161 64 | radius = 162 65 | 66 | 67 | class DataLoader: 68 | 69 | def __init__(self, path_old, path_new): 70 | self.path_old = path_old 71 | self.path_new = path_new 72 | # Group-category relations 73 | self.group_cat_old = {} 74 | self.group_cat_new = {} 75 | self.load_group_categories() 76 | # Items 77 | self.items_old = {} 78 | self.items_new = {} 79 | self.load_item_data() 80 | # Names 81 | self.names_old = {} 82 | self.names_new = {} 83 | self.load_name_data() 84 | # Market group full paths 85 | self.market_path_old = {} 86 | self.market_path_new = {} 87 | self.load_market_paths() 88 | # Metadata 89 | self.version_old = None 90 | self.version_new = None 91 | self.timestamp_old = None 92 | self.timestamp_new = None 93 | self.load_metadata() 94 | 95 | # Methods related to mapping groups onto categories 96 | 97 | def load_group_categories(self): 98 | for base_path, group_cat in ( 99 | (self.path_old, self.group_cat_old), 100 | (self.path_new, self.group_cat_new) 101 | ): 102 | for row in self.get_file(base_path, 'invgroups'): 103 | group_cat[row['groupID']] = row['categoryID'] 104 | 105 | def get_group_category(self, group_id): 106 | try: 107 | return self.group_cat_new[group_id] 108 | except KeyError: 109 | return self.group_cat_old[group_id] 110 | 111 | # Item-related methods 112 | 113 | def load_item_data(self): 114 | for base_path, items in ( 115 | (self.path_old, self.items_old), 116 | (self.path_new, self.items_new) 117 | ): 118 | 119 | for row in self.get_file(base_path, 'invtypes'): 120 | basic_attrs = {} 121 | for basic_attr in BasicAttribs: 122 | basic_attrs[basic_attr.value] = row[basic_attr.name] 123 | type_id = row['typeID'] 124 | items[type_id] = Type( 125 | id=type_id, 126 | published=row['published'], 127 | name=row['typeName_en-us'], 128 | group_id = row['groupID'], 129 | market_group_id = row['marketGroupID'], 130 | attributes=basic_attrs 131 | ) 132 | 133 | for row in self.get_file(base_path, 'dgmtypeattribs'): 134 | type_id = row['typeID'] 135 | try: 136 | item = items[type_id] 137 | except KeyError: 138 | continue 139 | item.attributes[row['attributeID']] = row['value'] 140 | 141 | for row in self.get_file(base_path, 'dgmtypeeffects'): 142 | type_id = row['typeID'] 143 | try: 144 | item = items[type_id] 145 | except KeyError: 146 | continue 147 | item.effects.append(row['effectID']) 148 | 149 | for bp_data in self.get_file(base_path, 'blueprints').values(): 150 | bp_activities = bp_data['activities'] 151 | try: 152 | mat_data = bp_activities['manufacturing']['materials'] 153 | prod_data = bp_activities['manufacturing']['products'][0] 154 | except (KeyError, IndexError): 155 | continue 156 | prod_type_id = prod_data['typeID'] 157 | for row in mat_data: 158 | try: 159 | prod_item = items[prod_type_id] 160 | except KeyError: 161 | continue 162 | prod_item.mats_build[row['typeID']] = row['quantity'] 163 | 164 | for reprocess_rows in self.get_file(base_path, 'invtypematerials').values(): 165 | for row in reprocess_rows: 166 | type_id = row['typeID'] 167 | try: 168 | item = items[type_id] 169 | except KeyError: 170 | continue 171 | item.mats_reprocess[row['materialTypeID']] = row['quantity'] 172 | 173 | 174 | def get_removed_items(self, unpublished): 175 | typeids_old = self._get_old_typeids(unpublished) 176 | typeids_new = self._get_new_typeids(unpublished) 177 | return dict((tid, self.items_old[tid]) for tid in typeids_old.difference(typeids_new)) 178 | 179 | def get_changed_items(self, unpublished): 180 | typeids_old = self._get_old_typeids(unpublished) 181 | typeids_new = self._get_new_typeids(unpublished) 182 | changed_items = {} 183 | for type_id in typeids_old.intersection(typeids_new): 184 | type_old = self.items_old[type_id] 185 | type_new = self.items_new[type_id] 186 | if type_old != type_new: 187 | changed_items[type_id] = ChangedItem(old=type_old, new=type_new) 188 | return changed_items 189 | 190 | def get_added_items(self, unpublished): 191 | typeids_old = self._get_old_typeids(unpublished) 192 | typeids_new = self._get_new_typeids(unpublished) 193 | return dict((tid, self.items_new[tid]) for tid in typeids_new.difference(typeids_old)) 194 | 195 | def _get_old_typeids(self, unpublished): 196 | if unpublished: 197 | return set(self.items_old) 198 | else: 199 | return set(filter(lambda i: self.items_old[i].published, self.items_old)) 200 | 201 | def _get_new_typeids(self, unpublished): 202 | if unpublished: 203 | return set(self.items_new) 204 | else: 205 | return set(filter(lambda i: self.items_new[i].published, self.items_new)) 206 | 207 | # Market-related methods 208 | 209 | def load_market_paths(self): 210 | for base_path, market_path in ( 211 | (self.path_old, self.market_path_old), 212 | (self.path_new, self.market_path_new) 213 | ): 214 | 215 | parent_map = {} 216 | 217 | market_data = self.get_file(base_path, 'mapbulk_marketGroups') 218 | for row in market_data: 219 | parent_map[row['marketGroupID']] = row['parentGroupID'] 220 | 221 | def compose_chain(market_group_id): 222 | chain = [market_group_id] 223 | parent = parent_map[market_group_id] 224 | while parent is not None: 225 | chain.append(parent) 226 | parent = parent_map[parent] 227 | return chain 228 | 229 | for row in market_data: 230 | market_group_id = row['marketGroupID'] 231 | market_path[market_group_id] = compose_chain(market_group_id) 232 | 233 | def get_market_path(self, mktgrp_id): 234 | try: 235 | return self.market_path_new[mktgrp_id] 236 | except KeyError: 237 | return self.market_path_old[mktgrp_id] 238 | 239 | # Name-related methods 240 | 241 | def load_name_data(self): 242 | for base_path, names in ( 243 | (self.path_old, self.names_old), 244 | (self.path_new, self.names_new) 245 | ): 246 | 247 | type_names = names['types'] = {} 248 | for row in self.get_file(base_path, 'invtypes'): 249 | type_names[row['typeID']] = row['typeName_en-us'] 250 | 251 | grp_names = names['groups'] = {} 252 | for row in self.get_file(base_path, 'invgroups'): 253 | grp_names[row['groupID']] = row['groupName_en-us'] 254 | 255 | cat_names = names['categories'] = {} 256 | for row in self.get_file(base_path, 'invcategories'): 257 | cat_names[row['categoryID']] = row['categoryName_en-us'] 258 | 259 | mktgrp_names = names['market_groups'] = {} 260 | for row in self.get_file(base_path, 'mapbulk_marketGroups'): 261 | mktgrp_names[row['marketGroupID']] = row['marketGroupName_en-us'] 262 | 263 | attr_names = names['attribs'] = {} 264 | for row in self.get_file(base_path, 'dgmattribs'): 265 | attr_names[row['attributeID']] = row['attributeName'] 266 | 267 | eff_names = names['effects'] = {} 268 | for row in self.get_file(base_path, 'dgmeffects'): 269 | eff_names[row['effectID']] = row['effectName'] 270 | 271 | # Metadata stuff 272 | 273 | def load_metadata(self): 274 | metadata_old = self.get_metadata_fields(self.path_old) 275 | self.version_old = metadata_old['client_build'] 276 | self.timestamp_old = metadata_old['dump_time'] 277 | metadata_new = self.get_metadata_fields(self.path_new) 278 | self.version_new = metadata_new['client_build'] 279 | self.timestamp_new = metadata_new['dump_time'] 280 | 281 | def get_metadata_fields(self, path): 282 | fields = {} 283 | metadata = self.get_file(path, 'phbmetadata') 284 | for row in metadata: 285 | name = row['field_name'] 286 | value = row['field_value'] 287 | fields[name] = value 288 | return fields 289 | 290 | def get_type_name(self, type_id, prefer_old=False): 291 | return self.__get_name('types', type_id, prefer_old) 292 | 293 | def get_group_name(self, group_id, prefer_old=False): 294 | return self.__get_name('groups', group_id, prefer_old) 295 | 296 | def get_category_name(self, category_id, prefer_old=False): 297 | return self.__get_name('categories', category_id, prefer_old) 298 | 299 | def get_attr_name(self, attr_id, prefer_old=False): 300 | return self.__get_name('attribs', attr_id, prefer_old) 301 | 302 | def get_effect_name(self, effect_id, prefer_old=False): 303 | return self.__get_name('effects', effect_id, prefer_old) 304 | 305 | def get_mktgrp_name(self, mktgrp_id, prefer_old=False): 306 | return self.__get_name('market_groups', mktgrp_id, prefer_old) 307 | 308 | def __get_name(self, alias, entity_id, prefer_old): 309 | if prefer_old: 310 | d1 = self.names_old 311 | d2 = self.names_new 312 | else: 313 | d1 = self.names_new 314 | d2 = self.names_old 315 | try: 316 | return d1[alias][entity_id] 317 | except KeyError: 318 | return d2[alias][entity_id] 319 | 320 | # Auxiliary methods 321 | 322 | def get_file(self, base_path, fname): 323 | """ 324 | Loads contents of JSON file with specified name. 325 | """ 326 | fpath = os.path.join(base_path, '{}.json'.format(fname)) 327 | with open(fpath, encoding='utf-8') as f: 328 | data = json.load(f) 329 | return data 330 | 331 | # Simple iterators over IDs of several entities 332 | 333 | def iter_types(self): 334 | for type_id in sorted(set(self.names_old['types']).union(self.names_new['types'])): 335 | yield type_id 336 | 337 | def iter_groups(self): 338 | for group_id in sorted(set(self.names_old['groups']).union(self.names_new['groups'])): 339 | yield group_id 340 | 341 | def iter_categories(self): 342 | for category_id in sorted(set(self.names_old['categories']).union(self.names_new['categories'])): 343 | yield category_id 344 | 345 | def iter_attribs(self): 346 | for attr_id in sorted(set(self.names_old['attribs']).union(self.names_new['attribs'])): 347 | yield attr_id 348 | 349 | def iter_effects(self): 350 | for eff_id in sorted(set(self.names_old['effects']).union(self.names_new['effects'])): 351 | yield eff_id 352 | 353 | def iter_mktgroups(self): 354 | for mktgrp_id in sorted(set(self.names_old['market_groups']).union(self.names_new['market_groups'])): 355 | yield mktgrp_id 356 | 357 | 358 | class PrinterSkeleton: 359 | 360 | def __init__(self, data_loader, unpublished): 361 | self._dl = data_loader 362 | self._changes = self._get_changes_summary(unpublished) 363 | 364 | def _iter_category(self, cat_list): 365 | """ 366 | Iterate over all categories which contain changed items. 367 | 368 | Required arguments: 369 | cat_list -- list with category names, when not empty 370 | this method will iterate only over categories whose 371 | names are in this list. 372 | """ 373 | cat_ids = set(self._dl.get_group_category(grp_id) for grp_id in self._changes) 374 | # Filter out category names which are not provided in the list 375 | if cat_list: 376 | # Normalize list of provided names & category names too for 377 | # easier and more user-friendly matching 378 | cat_list = tuple(c.lower() for c in cat_list) 379 | cat_ids = set(filter(lambda cat_id: self._dl.get_category_name(cat_id).lower() in cat_list, cat_ids)) 380 | for cat_id in sorted(cat_ids, key=self._dl.get_category_name): 381 | cat_name = self._dl.get_category_name(cat_id) 382 | yield cat_id, cat_name 383 | 384 | def _iter_group(self, cat_id): 385 | """ 386 | Iterate over groups which contain changed items 387 | and belong to certain category. 388 | """ 389 | grp_ids = set(filter(lambda grp_id: self._dl.get_group_category(grp_id) == cat_id, self._changes)) 390 | for grp_id in sorted(grp_ids, key=self._dl.get_group_name): 391 | grp_name = self._dl.get_group_name(grp_id) 392 | yield grp_id, grp_name 393 | 394 | def _iter_types_removed(self, grp_id): 395 | """ 396 | Iterate over all types which have been 397 | removed and belonged to given group. 398 | """ 399 | removed = self._changes[grp_id].removed 400 | for type_ in sorted(removed.values(), key=lambda t: t.name): 401 | yield type_ 402 | 403 | def _iter_types_changed(self, grp_id): 404 | """ 405 | Iterate through all types which have been 406 | changed and belonged or now belong to given 407 | group. 408 | """ 409 | changed = self._changes[grp_id].changed 410 | for type_id in sorted(changed, key=self._dl.get_type_name): 411 | yield changed[type_id].old, changed[type_id].new 412 | 413 | def _iter_types_added(self, grp_id): 414 | """ 415 | Iterate through all types which have been 416 | added and belong to given group. 417 | """ 418 | added = self._changes[grp_id].added 419 | for type_ in sorted(added.values(), key=lambda t: t.name): 420 | yield type_ 421 | 422 | def _iter_attribs(self, item): 423 | """ 424 | Iterate over attribute names and values of passed item. 425 | """ 426 | for attr_id in sorted(item.attributes, key=self._dl.get_attr_name): 427 | attr_name = self._dl.get_attr_name(attr_id) 428 | attr_val = item.attributes[attr_id] 429 | yield attr_name, attr_val 430 | 431 | def _iter_effects(self, item): 432 | """ 433 | Iterate over effect names of passed item. 434 | """ 435 | for eff_id in sorted(item.effects, key=self._dl.get_effect_name): 436 | eff_name = self._dl.get_effect_name(eff_id) 437 | yield eff_name 438 | 439 | def _iter_materials_reprocess(self, item): 440 | """ 441 | Iterate over materials and quantities you receive 442 | after reprocessing passed item. 443 | """ 444 | for mat_id in sorted(item.mats_reprocess, key=self._dl.get_type_name): 445 | mat_name = self._dl.get_type_name(mat_id) 446 | mat_amt = item.mats_reprocess[mat_id] 447 | yield mat_name, mat_amt 448 | 449 | def _iter_materials_build(self, item): 450 | """ 451 | Iterate over materials and quantities you spend 452 | to build passed item. 453 | """ 454 | for mat_id in sorted(item.mats_build, key=self._dl.get_type_name): 455 | mat_name = self._dl.get_type_name(mat_id) 456 | mat_amt = item.mats_build[mat_id] 457 | yield mat_name, mat_amt 458 | 459 | def _iter_renames_types(self): 460 | """ 461 | Iterate over changed type names. 462 | """ 463 | for type_id in self._dl.iter_types(): 464 | old_name = self._dl.get_type_name(type_id, prefer_old=True) 465 | new_name = self._dl.get_type_name(type_id, prefer_old=False) 466 | if old_name != new_name: 467 | yield type_id, old_name, new_name 468 | 469 | def _iter_renames_groups(self): 470 | """ 471 | Iterate over changed group names. 472 | """ 473 | for group_id in self._dl.iter_groups(): 474 | old_name = self._dl.get_group_name(group_id, prefer_old=True) 475 | new_name = self._dl.get_group_name(group_id, prefer_old=False) 476 | if old_name != new_name: 477 | yield group_id, old_name, new_name 478 | 479 | def _iter_renames_categories(self): 480 | """ 481 | Iterate over changed category names. 482 | """ 483 | for cat_id in self._dl.iter_categories(): 484 | old_name = self._dl.get_category_name(cat_id, prefer_old=True) 485 | new_name = self._dl.get_category_name(cat_id, prefer_old=False) 486 | if old_name != new_name: 487 | yield cat_id, old_name, new_name 488 | 489 | def _iter_renames_mktgroups(self): 490 | """ 491 | Iterate over changed market group names. 492 | """ 493 | for mktgrp_id in self._dl.iter_mktgroups(): 494 | old_name = self._dl.get_mktgrp_name(mktgrp_id, prefer_old=True) 495 | new_name = self._dl.get_mktgrp_name(mktgrp_id, prefer_old=False) 496 | if old_name != new_name: 497 | yield mktgrp_id, old_name, new_name 498 | 499 | def _iter_renames_attribs(self): 500 | """ 501 | Iterate over changed attribute names. 502 | """ 503 | for attr_id in self._dl.iter_attribs(): 504 | old_name = self._dl.get_attr_name(attr_id, prefer_old=True) 505 | new_name = self._dl.get_attr_name(attr_id, prefer_old=False) 506 | if old_name != new_name: 507 | yield attr_id, old_name, new_name 508 | 509 | def _iter_renames_effects(self): 510 | """ 511 | Iterate over changed effect names. 512 | """ 513 | for effect_id in self._dl.iter_effects(): 514 | old_name = self._dl.get_effect_name(effect_id, prefer_old=True) 515 | new_name = self._dl.get_effect_name(effect_id, prefer_old=False) 516 | if old_name != new_name: 517 | yield effect_id, old_name, new_name 518 | 519 | def _get_market_path(self, item): 520 | """ 521 | Convert path exposed by loader into human-readable 522 | Path > To > Item's > Market > Group. 523 | """ 524 | mktgrp = item.market_group_id 525 | if mktgrp is None: 526 | return None 527 | mkt_path = ' > '.join(self._dl.get_mktgrp_name(i) for i in reversed(self._dl.get_market_path(mktgrp))) 528 | return mkt_path 529 | 530 | def _get_changes_summary(self, unpublished): 531 | """ 532 | Convert data exposed by loader into format specific for printing 533 | logic we're using - top-level sections are categories, then groups 534 | are sub-sections, and items are listed in these sub-sections. 535 | Format: {group ID: (removed, changed, added)} 536 | Removed and added: {type ID: type} 537 | Changed: {type ID: (old type, new type)} 538 | """ 539 | changes = {} 540 | removed = self._dl.get_removed_items(unpublished) 541 | changed = self._dl.get_changed_items(unpublished) 542 | added = self._dl.get_added_items(unpublished) 543 | for grp_id in self._dl.iter_groups(): 544 | # Check which items were changed for this particular group 545 | filfunc = lambda i: removed[i].group_id == grp_id 546 | removed_grp = dict((i, removed[i]) for i in filter(filfunc, removed)) 547 | filfunc = lambda i: added[i].group_id == grp_id 548 | added_grp = dict((i, added[i]) for i in filter(filfunc, added)) 549 | filfunc = lambda i: changed[i].old.group_id == grp_id or changed[i].new.group_id == grp_id 550 | changed_grp = dict((tid, changed[tid]) for tid in filter(filfunc, changed)) 551 | # Do not fill anything if nothing changed 552 | if not removed_grp and not changed_grp and not added_grp: 553 | continue 554 | # Fill container with data we gathered 555 | changes[grp_id] = Changes(removed=removed_grp, changed=changed_grp, added=added_grp) 556 | return changes 557 | 558 | 559 | class moreindent: 560 | """ 561 | Context manager for text printer's indentation. 562 | """ 563 | 564 | def __init__(self, instance): 565 | self.instance = instance 566 | 567 | def __enter__(self): 568 | self.instance._indent_more() 569 | 570 | def __exit__(self, *exc_details): 571 | self.instance._indent_less() 572 | return False 573 | 574 | 575 | class TextPrinter(PrinterSkeleton): 576 | """ 577 | Print item changes as text. 578 | """ 579 | 580 | def __init__(self, data_loader, unpublished, indent_increment): 581 | PrinterSkeleton.__init__(self, data_loader, unpublished) 582 | self._indent_length = 0 583 | self._indent_increment = indent_increment 584 | 585 | def run(self, cat_list): 586 | self._print_metadata() 587 | self._print_categories(cat_list) 588 | if process_renames: 589 | self._print_renames() 590 | 591 | # Indentation stuff 592 | 593 | def _indent_more(self): 594 | self._indent_length += self._indent_increment 595 | 596 | def _indent_less(self): 597 | self._indent_length -= self._indent_increment 598 | 599 | @property 600 | def _indent(self): 601 | return ' ' * self._indent_length 602 | 603 | def _print_metadata(self): 604 | """ 605 | Print version and timestamp info about dumps being compared. 606 | """ 607 | tz_utc = timezone(timedelta(), 'UTC') 608 | time_fmt = '%Y-%m-%d %H:%M:%S %Z' 609 | time_old = datetime.fromtimestamp(self._dl.timestamp_old, tz=tz_utc).strftime(time_fmt) 610 | time_new = datetime.fromtimestamp(self._dl.timestamp_new, tz=tz_utc).strftime(time_fmt) 611 | print('{}Comparing EVE client versions:'.format(self._indent)) 612 | with moreindent(self): 613 | print('{}{} (data extracted at {})'.format(self._indent, self._dl.version_old, time_old)) 614 | print('{}{} (data extracted at {})'.format(self._indent, self._dl.version_new, time_new)) 615 | print() 616 | 617 | def _print_categories(self, cat_list): 618 | """ 619 | Print diff data for items from all categories. 620 | """ 621 | for cat_id, cat_name in self._iter_category(cat_list): 622 | print('{}Category: {}'.format(self._indent, cat_name), end='\n\n') 623 | with moreindent(self): 624 | self._print_groups(cat_id) 625 | 626 | def _print_groups(self, cat_id): 627 | """ 628 | Print diff data for items from all groups which 629 | belong to passed category. 630 | """ 631 | for grp_id, grp_name in self._iter_group(cat_id): 632 | print('{}Group: {}'.format(self._indent, grp_name), end='\n\n') 633 | with moreindent(self): 634 | self._print_items_removed(grp_id) 635 | self._print_items_changed(grp_id) 636 | self._print_items_added(grp_id) 637 | 638 | def _print_items_removed(self, grp_id): 639 | """ 640 | Print data for all removed items belonging to 641 | passed group. 642 | """ 643 | for item in self._iter_types_removed(grp_id): 644 | print('{}[-] {}'.format(self._indent, item.name), end='\n\n') 645 | print() 646 | 647 | def _print_items_changed(self, grp_id): 648 | """ 649 | Print data for all changed items belonging to 650 | passed group. 651 | """ 652 | for old, new in self._iter_types_changed(grp_id): 653 | if process_renames and new.name != old.name: 654 | name = '{} => {}'.format(old.name, new.name) 655 | else: 656 | name = new.name 657 | if old.group_id != new.group_id: 658 | # When item was moved from current group to another, print just 659 | # short notice about it, no details... 660 | if old.group_id == grp_id: 661 | new_grp = self._dl.get_group_name(new.group_id) 662 | new_cat = self._dl.get_category_name(self._dl.get_group_category((new.group_id))) 663 | print('{}[*] {} (moved to {} > {})'.format(self._indent, name, new_cat, new_grp), end='\n\n') 664 | continue 665 | # ...and details are written in the target group 666 | else: 667 | old_grp = self._dl.get_group_name(old.group_id) 668 | old_cat = self._dl.get_category_name(self._dl.get_group_category((old.group_id))) 669 | suffix = ' (moved from {} > {})'.format(old_cat, old_grp) 670 | else: 671 | suffix = '' 672 | print('{}[*] {}{}'.format(self._indent, name, suffix)) 673 | with moreindent(self): 674 | if process_effects: 675 | self._print_item_effects_comparison(old, new) 676 | if process_attrs: 677 | self._print_item_attrs_comparison(old, new) 678 | if process_mats: 679 | self._print_item_materials_comparison(old, new) 680 | if process_mkt: 681 | self._print_item_market_group_comparison(old, new) 682 | if process_pub: 683 | self._print_item_published_comparison(old, new) 684 | print() 685 | 686 | def _print_items_added(self, grp_id): 687 | """ 688 | Print data for all added items belonging to 689 | passed group. 690 | """ 691 | for item in self._iter_types_added(grp_id): 692 | print('{}[+] {}'.format(self._indent, item.name)) 693 | with moreindent(self): 694 | if process_effects: 695 | self._print_item_effects(item) 696 | if process_attrs: 697 | self._print_item_attrs(item) 698 | if process_mats: 699 | self._print_item_materials(item) 700 | if process_mkt: 701 | self._print_item_market_group(item) 702 | if process_pub: 703 | self._print_item_published(item) 704 | print() 705 | 706 | def _print_item_effects(self, item): 707 | """ 708 | Print effects for single item. 709 | """ 710 | effects = tuple(self._iter_effects(item)) 711 | if effects: 712 | print('{}Effects:'.format(self._indent)) 713 | with moreindent(self): 714 | for eff_name in effects: 715 | print('{}{}'.format(self._indent, eff_name)) 716 | 717 | def _print_item_effects_comparison(self, old, new): 718 | """ 719 | Print effect comparison for two items. 720 | """ 721 | if old.effects != new.effects: 722 | print('{}Effects:'.format(self._indent)) 723 | with moreindent(self): 724 | eff_rmvd = set(old.effects).difference(new.effects) 725 | eff_add = set(new.effects).difference(old.effects) 726 | for eff_id in sorted(eff_rmvd.union(eff_add), key=self._dl.get_effect_name): 727 | eff_name = self._dl.get_effect_name(eff_id) 728 | if eff_id in eff_rmvd: 729 | print('{}[-] {}'.format(self._indent, eff_name)) 730 | if eff_id in eff_add: 731 | print('{}[+] {}'.format(self._indent, eff_name)) 732 | 733 | def _print_item_attrs(self, item): 734 | """ 735 | Print attributes for single item. 736 | """ 737 | attribs = tuple(self._iter_attribs(item)) 738 | if attribs: 739 | print('{}Attributes:'.format(self._indent)) 740 | with moreindent(self): 741 | for attr_name, attr_val in attribs: 742 | print('{}{}: {}'.format(self._indent, attr_name, self._fti(attr_val))) 743 | 744 | def _print_item_attrs_comparison(self, old, new): 745 | """ 746 | Print attribute comparison for two items. 747 | """ 748 | if old.attributes != new.attributes: 749 | print('{}Attributes:'.format(self._indent)) 750 | self._print_dict_comparison(old.attributes, new.attributes, self._dl.get_attr_name) 751 | 752 | def _print_dict_comparison(self, old, new, key_name_fetcher): 753 | """ 754 | Take two dictionaries in {entity ID: entity value} format 755 | and name fetcher, and print human-friendly diff between 756 | them. 757 | """ 758 | keys_rmvd = set(old).difference(new) 759 | keys_changed = set(filter(lambda i: old[i] != new[i], set(new).intersection(old))) 760 | keys_added = set(new).difference(old) 761 | for key in sorted(keys_rmvd.union(keys_changed).union(keys_added), key=key_name_fetcher): 762 | with moreindent(self): 763 | name = key_name_fetcher(key) 764 | if key in keys_rmvd: 765 | value = old[key] 766 | print('{}[-] {}: {}'.format(self._indent, name, self._fti(value))) 767 | if key in keys_changed: 768 | value_old = old[key] 769 | value_new = new[key] 770 | print('{}[*] {}: {} => {}'.format(self._indent, name, self._fti(value_old), self._fti(value_new))) 771 | if key in keys_added: 772 | value = new[key] 773 | print('{}[+] {}: {}'.format(self._indent, name, self._fti(value))) 774 | 775 | def _print_item_materials(self, item): 776 | """ 777 | Print materials you receive from reprocessing and materials 778 | you need to build passed item. 779 | """ 780 | building = tuple(self._iter_materials_build(item)) 781 | reprocessing = tuple(self._iter_materials_reprocess(item)) 782 | if reprocessing or building: 783 | print('{}Materials:'.format(self._indent)) 784 | with moreindent(self): 785 | if building: 786 | print('{}Construction:'.format(self._indent)) 787 | with moreindent(self): 788 | for mat_name, mat_amt in building: 789 | print('{}{}: {}'.format(self._indent, mat_name, self._fti(mat_amt))) 790 | if reprocessing: 791 | print('{}Reprocessing:'.format(self._indent)) 792 | with moreindent(self): 793 | for mat_name, mat_amt in reprocessing: 794 | print('{}{}: {}'.format(self._indent, mat_name, self._fti(mat_amt))) 795 | 796 | def _print_item_materials_comparison(self, old, new): 797 | """ 798 | Print reprocessing/construction materials comparison for two items. 799 | """ 800 | if old.mats_build != new.mats_build or old.mats_reprocess != new.mats_reprocess: 801 | print('{}Materials:'.format(self._indent)) 802 | with moreindent(self): 803 | if old.mats_build != new.mats_build: 804 | print('{}Construction:'.format(self._indent)) 805 | self._print_dict_comparison(old.mats_build, new.mats_build, self._dl.get_type_name) 806 | if old.mats_reprocess != new.mats_reprocess: 807 | print('{}Reprocessing:'.format(self._indent)) 808 | self._print_dict_comparison(old.mats_reprocess, new.mats_reprocess, self._dl.get_type_name) 809 | 810 | def _print_item_market_group(self, item): 811 | """ 812 | Print market group for single item. 813 | """ 814 | mkt_path = self._get_market_path(item) 815 | if mkt_path is not None: 816 | print('{}Market group:'.format(self._indent)) 817 | with moreindent(self): 818 | print('{}{}'.format(self._indent, mkt_path)) 819 | 820 | def _print_item_market_group_comparison(self, old, new): 821 | """ 822 | Print market group comparison for two items. 823 | """ 824 | if old.market_group_id != new.market_group_id: 825 | print('{}Market group:'.format(self._indent)) 826 | with moreindent(self): 827 | mktgrp_old = self._get_market_path(old) 828 | mktgrp_new = self._get_market_path(new) 829 | print('{}From: {}'.format(self._indent, mktgrp_old)) 830 | print('{}To: {}'.format(self._indent, mktgrp_new)) 831 | 832 | def _print_item_published(self, item): 833 | """ 834 | Print published flag for single item. 835 | """ 836 | print('{}Published flag:'.format(self._indent)) 837 | with moreindent(self): 838 | print('{}{}'.format(self._indent, bool(item.published))) 839 | 840 | def _print_item_published_comparison(self, old, new): 841 | """ 842 | Print published flag comparison for two items. 843 | """ 844 | if old.published != new.published: 845 | print('{}Published flag:'.format(self._indent)) 846 | with moreindent(self): 847 | print('{}{} => {}'.format(self._indent, bool(old.published), bool(new.published))) 848 | 849 | def _fti(self, num): 850 | """ 851 | Convert float to int if equal. 852 | """ 853 | if int(num) == num: 854 | return int(num) 855 | else: 856 | return num 857 | 858 | def _print_renames(self): 859 | renames = OrderedDict([ 860 | ('items', self._iter_renames_types), 861 | ('groups', self._iter_renames_groups), 862 | ('categories', self._iter_renames_categories), 863 | ('attributes', self._iter_renames_attribs), 864 | ('effects', self._iter_renames_effects), 865 | ('market groups', self._iter_renames_mktgroups), 866 | ]) 867 | 868 | for header, iterator in renames.items(): 869 | rename_data = tuple(iterator()) 870 | if rename_data: 871 | print('{}Renamed {}:'.format(self._indent, header)) 872 | print() 873 | with moreindent(self): 874 | for _, old, new in rename_data: 875 | print('{}"{}"'.format(self._indent, old)) 876 | print('{}"{}"'.format(self._indent, new)) 877 | print() 878 | 879 | 880 | if __name__ == '__main__': 881 | 882 | parser = argparse.ArgumentParser(description='This script pulls data out of EVE client and writes it in JSON format') 883 | parser.add_argument('-o', '--old', help='path to phobos JSON dump with old data', required=True) 884 | parser.add_argument('-n', '--new', help='path to phobos JSON dump with new data', required=True) 885 | parser.add_argument('-a', '--all', help='print data for all items, not just published', default=False, action='store_true') 886 | parser.add_argument('-c', '--categories', help='comma-separated list of category names, for which data will be shown', default='') 887 | parser.add_argument('-x', '--exclude', help='exclude some data from comparison, specified as string with letters; e - effects, a - attributes, m - materials, k - market groups, p - published flag, r - renames', default='') 888 | args = parser.parse_args() 889 | 890 | # Global flags which control diffs for which stuff is shown 891 | process_effects = 'e' not in args.exclude 892 | process_attrs = 'a' not in args.exclude 893 | process_mats = 'm' not in args.exclude 894 | process_mkt = 'k' not in args.exclude 895 | process_pub = 'p' not in args.exclude 896 | process_renames = 'r' not in args.exclude 897 | 898 | path_old = os.path.expanduser(args.old) 899 | path_new = os.path.expanduser(args.new) 900 | 901 | category_list = tuple(filter(lambda c: c, (c.strip() for c in args.categories.split(',')))) 902 | dl = DataLoader(path_old, path_new) 903 | TextPrinter(dl, unpublished=args.all, indent_increment=2).run(category_list) 904 | -------------------------------------------------------------------------------- /util/__init__.py: -------------------------------------------------------------------------------- 1 | #=============================================================================== 2 | # Copyright (C) 2014-2019 Anton Vorobyov 3 | # 4 | # This file is part of Phobos. 5 | # 6 | # Phobos is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU Lesser General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # Phobos is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU Lesser General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU Lesser General Public License 17 | # along with Phobos. If not, see . 18 | #=============================================================================== 19 | 20 | 21 | from .cached_property import cachedproperty 22 | from .eve_normalize import EveNormalizer 23 | from .resource_browser import ResourceBrowser 24 | from .translator import Translator 25 | -------------------------------------------------------------------------------- /util/cached_property.py: -------------------------------------------------------------------------------- 1 | #=============================================================================== 2 | # Copyright (C) 2014-2019 Anton Vorobyov 3 | # 4 | # This file is part of Phobos. 5 | # 6 | # Phobos is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU Lesser General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # Phobos is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU Lesser General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU Lesser General Public License 17 | # along with Phobos. If not, see . 18 | #=============================================================================== 19 | 20 | 21 | class cachedproperty(object): 22 | """ 23 | Decorator class, imitates property behavior, but additionally 24 | caches results returned by decorated method as attribute of 25 | instance to which decorated method belongs. As python, when getting 26 | attribute with certain name, seeks for class instance's attributes 27 | first, then for methods, it gets cached result. To clear cache, just 28 | delete cached attribute. 29 | """ 30 | 31 | def __init__(self, method): 32 | self.__method = method 33 | 34 | def __get__(self, instance, owner): 35 | # Return descriptor if called from class 36 | if instance is None: 37 | return self 38 | # If called from instance, execute decorated method 39 | # and store returned value as class attribute, which 40 | # has the same name as method, then return it to caller 41 | value = self.__method(instance) 42 | setattr(instance, self.__method.__name__, value) 43 | return value 44 | -------------------------------------------------------------------------------- /util/eve_normalize.py: -------------------------------------------------------------------------------- 1 | #=============================================================================== 2 | # Copyright (C) 2014-2019 Anton Vorobyov 3 | # 4 | # This file is part of Phobos. 5 | # 6 | # Phobos is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU Lesser General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # Phobos is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU Lesser General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU Lesser General Public License 17 | # along with Phobos. If not, see . 18 | #=============================================================================== 19 | 20 | 21 | import inspect 22 | import types 23 | from collections import OrderedDict 24 | from itertools import chain 25 | 26 | from reverence.carbon.common.script.sys.row import Row 27 | 28 | 29 | class EveNormalizer(object): 30 | """ 31 | Class, which 'flattens' indexed structures into list of 32 | 'rows' and converts all eve-specific data structures into 33 | python built-in types. 34 | """ 35 | 36 | def __init__(self): 37 | self._loader_module = None 38 | 39 | def run(self, eve_container, loader_module=None): 40 | """ 41 | Entry point for conversion jobs. Runs method which recursively 42 | changes contents of passed container to present them in pythonized 43 | data structures. 44 | """ 45 | self._loader_module = loader_module 46 | data = self._route_object(eve_container) 47 | return data 48 | 49 | def _route_object(self, obj): 50 | """ 51 | Pick proper method for passed object and invoke it. 52 | """ 53 | # Primitive objects do not need any conversion 54 | if type(obj) in self._primitives: 55 | return obj 56 | # Try strict class/guid matching first 57 | cls = type(obj) 58 | try: 59 | method = self._class_match[cls] 60 | except KeyError: 61 | pass 62 | else: 63 | return method(self, obj) 64 | # __guid__ is available for many objects exposed by reverence, 65 | # use class name as fallback only when it's not available 66 | cls_name = getattr(obj, '__guid__', type(obj).__name__) 67 | try: 68 | method = self._name_match[cls_name] 69 | except KeyError: 70 | pass 71 | else: 72 | return method(self, obj) 73 | # Try to find parent class for passed object, and if we 74 | # have any in our records - run handler for it 75 | for candidate_cls in self._subclass_match: 76 | if isinstance(obj, candidate_cls): 77 | method = self._subclass_match[candidate_cls] 78 | return method(self, obj) 79 | # Stuff specific to FSD binary format 80 | if self._loader_module is not None: 81 | # Check if class is defined in passed loader, if it is, then 82 | # we're dealing with FSD binary item for certain 83 | if inspect.getmodule(type(obj)) is self._loader_module: 84 | return self.pythonize_fsdbinary_item(obj) 85 | # FSD contains bunch of vector classes which are defined outside of 86 | # loader (shown as defined in builtins), process them separately 87 | if type(obj).__name__.endswith('_vector'): 88 | return self.pythonize_fsdbinary_item(obj, ignore_attrs=( 89 | 'n_fields', 'n_sequence_fields', 'n_unnamed_fields')) 90 | # If we got here, routing failed 91 | msg = 'unable to route {}'.format(type(obj)) 92 | guid = getattr(obj, '__guid__', None) 93 | if guid is not None: 94 | msg = '{} (guid {})'.format(msg, guid) 95 | raise UnknownContainerTypeError(msg) 96 | 97 | def _pythonize_iterable(self, obj): 98 | """ 99 | For objects which have access interface similar to python 100 | iterables - convert contents and return them as tuple. 101 | """ 102 | return tuple(self._route_object(i) for i in obj) 103 | 104 | def _pythonize_map(self, obj): 105 | """ 106 | For objects which have access interface similar to python 107 | dictionaries - convert keys and values and return as dict. 108 | """ 109 | container = {} 110 | for key, value in obj.iteritems(): 111 | proc_key = self._route_object(key) 112 | proc_value = self._route_object(value) 113 | container[proc_key] = proc_value 114 | return container 115 | 116 | def _pythonize_string(self, obj): 117 | """ 118 | Sometimes EVE has non-ASCII symbols in non-unicode strings, 119 | default encoding for these is cp1252, here we ensure they are 120 | converted to unicode so we don't have to run any additional 121 | processing on them elsewhere. 122 | """ 123 | return obj.decode('cp1252') 124 | 125 | def _pythonize_dbrow(self, obj): 126 | """ 127 | DBRow can be converted into dictionary - its keys are 128 | accessed via hidden '__keys__' attribute (implementation 129 | detail, ideally we should fetch it from container's 130 | .header attribute). 131 | """ 132 | container = {} 133 | for key in obj.__keys__: 134 | value = obj[key] 135 | proc_key = self._route_object(key) 136 | proc_value = self._route_object(value) 137 | container[proc_key] = proc_value 138 | return container 139 | 140 | def _pythonize_list_of_iterables(self, obj): 141 | """ 142 | Here we suppose that passed object is list of iterables of 143 | any type; we process all of these iterables, and then 144 | concatenate them to form a single tuple. 145 | """ 146 | return tuple(chain(*(self._route_object(l) for l in obj))) 147 | 148 | def _pythonize_fsd_named_vector(self, obj): 149 | """ 150 | Named vectors resemble tuples/lists, but contain name data for 151 | their fields, thus we convert them into dicts. 152 | """ 153 | container = {} 154 | name_data = obj.schema['aliases'] 155 | for name, index in name_data.items(): 156 | value = obj.data[index] 157 | proc_name = self._route_object(name) 158 | proc_value = self._route_object(value) 159 | container[proc_name] = proc_value 160 | return container 161 | 162 | def _pythonize_fsd_object(self, obj): 163 | """ 164 | FSD_Object is similar to regular python objects - but unlike them, 165 | list of accessible attributes is stored in 'attributes' attribute. 166 | """ 167 | container = {} 168 | for key in obj.attributes: 169 | # Sometimes values are missing 170 | value = getattr(obj, key, None) 171 | proc_key = self._route_object(key) 172 | proc_value = self._route_object(value) 173 | container[proc_key] = proc_value 174 | return container 175 | 176 | def _pythonize_indexed_lists(self, obj): 177 | """ 178 | Indexed lists are represented as dictionary, where keys are some 179 | indices and values are lists of rows. This is very similar to list 180 | of iterables, thus we're reusing its conversion method. 181 | """ 182 | return self._pythonize_list_of_iterables(obj.values()) 183 | 184 | def _pythonize_indexed_rows(self, obj): 185 | """ 186 | Regular map, where values are data rows, and keys are some 187 | values taken from the rows they correspond to. 188 | """ 189 | return self._pythonize_iterable(obj.values()) 190 | 191 | def _pythonize_pyobj(self, obj): 192 | """ 193 | KeyVal is a python-like object, where attributes/values are stored 194 | as object attributes. 195 | """ 196 | return self._pythonize_map(obj.__dict__) 197 | 198 | def _pythonize_row(self, obj): 199 | """ 200 | Row objects are tricky part for phobos - they expose convenient 201 | interface to user, which is 'improved' by reverence to provide things 202 | like out-of-the-box string localization, or object references (e.g. 203 | group row provides reference to actual category row, not just 204 | categoryID). Reverence is known to break on some of these 'improvements' 205 | (e.g. RamDetail class). This can be worked around in quite a dirty 206 | way, but as we do not really need any of these improvements - we 207 | take 'raw' row (DBRow) from Row (and its subclasses) and use it, 208 | ignoring everything built on top of it. 209 | """ 210 | return self._pythonize_dbrow(obj.line) 211 | 212 | def pythonize_fsdbinary_item(self, obj, ignore_attrs=()): 213 | item = {} 214 | for attr_name in dir(obj): 215 | if attr_name.startswith('__') and attr_name.endswith('__'): 216 | continue 217 | if attr_name in ignore_attrs: 218 | continue 219 | item[attr_name] = self._route_object(getattr(obj, attr_name)) 220 | return item 221 | 222 | _primitives = ( 223 | types.NoneType, 224 | types.BooleanType, 225 | types.FloatType, 226 | types.IntType, 227 | types.LongType, 228 | types.UnicodeType) 229 | 230 | _class_match = { 231 | types.StringType: _pythonize_string, 232 | types.ListType: _pythonize_iterable, 233 | types.TupleType: _pythonize_iterable} 234 | 235 | _name_match = { 236 | # Usually seen in cache 237 | 'dbutil.CFilterRowset': _pythonize_indexed_lists, 238 | 'dbutil.CIndexedRowset': _pythonize_indexed_rows, 239 | 'dbutil.CRowset': _pythonize_iterable, 240 | 'dbutil.RowDict': _pythonize_indexed_rows, 241 | 'dbutil.RowList': _pythonize_iterable, 242 | # Conventional bulkdata classes 243 | 'util.FilterRowset': _pythonize_list_of_iterables, 244 | 'util.IndexedRowLists': _pythonize_indexed_lists, 245 | 'util.IndexRowset': _pythonize_iterable, 246 | 'util.KeyVal': _pythonize_pyobj, 247 | 'util.Rowset': _pythonize_iterable, 248 | # FSD-related classes, usually seen in bulkdata 249 | 'FSD_Dict': _pythonize_map, 250 | 'FSD_MultiIndex': _pythonize_map, 251 | 'FSD_NamedVector': _pythonize_fsd_named_vector, 252 | 'FSD_Object': _pythonize_fsd_object, 253 | '_FixedSizeList': _pythonize_iterable, 254 | '_VariableSizedList': _pythonize_iterable, 255 | # FSD binary specific classes 256 | 'dict': _pythonize_map, # cfsd.dict 257 | 'list': _pythonize_iterable, # cfsd.list 258 | # Misc 259 | 'blue.DBRow': _pythonize_dbrow, 260 | 'universe.SolarSystemWrapper': _pythonize_pyobj} 261 | 262 | _subclass_match = OrderedDict([ 263 | # Row is handled through isinstance check because reverence 264 | # actually provides its subclasses, but it doesn't make sense 265 | # to specify them all 266 | (Row, _pythonize_row), 267 | # Includes dictionaries and FSDLiteStorage 268 | (types.DictType, _pythonize_map)]) 269 | 270 | 271 | class UnknownContainerTypeError(Exception): 272 | """ 273 | Raised when normalizer doesn't know what to do 274 | with passed object. 275 | """ 276 | pass 277 | -------------------------------------------------------------------------------- /util/resource_browser.py: -------------------------------------------------------------------------------- 1 | #=============================================================================== 2 | # Copyright (C) 2014-2019 Anton Vorobyov 3 | # 4 | # This file is part of Phobos. 5 | # 6 | # Phobos is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU Lesser General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # Phobos is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU Lesser General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU Lesser General Public License 17 | # along with Phobos. If not, see . 18 | #=============================================================================== 19 | 20 | 21 | import csv 22 | import hashlib 23 | import os 24 | from collections import namedtuple 25 | 26 | from util import cachedproperty 27 | 28 | 29 | FileInfo = namedtuple('FileInfo', ('resource_path', 'file_relpath', 'file_abspath', 'file_hash', 'file_size', 'compressed_size')) 30 | 31 | 32 | def get_full_alias(short_alias): 33 | full_aliases = { 34 | 'tq': 'tranquility', 35 | 'sisi': 'singularity'} 36 | return full_aliases.get(short_alias, short_alias) 37 | 38 | 39 | class ResourceBrowser(object): 40 | """ 41 | Class, responsible for browsing/retrieval of resources. 42 | """ 43 | 44 | def __init__(self, eve_path, server_alias): 45 | self._eve_path = eve_path 46 | self._server_alias = server_alias 47 | 48 | def respath_iter(self): 49 | """ 50 | Aggregate filepaths from all resource files and return 51 | them in the form of single list. 52 | """ 53 | for resource_path in self._resource_index: 54 | yield resource_path 55 | 56 | def get_file_data(self, resource_path): 57 | """Return file contents for requested resource.""" 58 | file_info = self._resource_index[resource_path] 59 | file_path = file_info.file_abspath 60 | with open(file_path, 'rb') as f: 61 | data = f.read() 62 | self.__verify_data(data=data, file_info=file_info) 63 | return data 64 | 65 | def get_file_info(self, resource_path): 66 | """Return file info for requested resource.""" 67 | file_info = self._resource_index[resource_path] 68 | file_path = file_info.file_abspath 69 | with open(file_path, 'rb') as f: 70 | data = f.read() 71 | self.__verify_data(data=data, file_info=file_info) 72 | return file_info 73 | 74 | def __verify_data(self, data, file_info): 75 | if len(data) != file_info.file_size: 76 | raise FileIntegrityError(u'file size mismatch when reading {}'.format(file_info.resource_path)) 77 | m = hashlib.md5() 78 | m.update(data) 79 | if m.hexdigest() != file_info.file_hash: 80 | raise FileIntegrityError(u'file hash mismatch when reading {}'.format(file_info.resource_path)) 81 | 82 | @cachedproperty 83 | def _resource_index(self): 84 | index = {} 85 | res_index_path = os.path.join(self._eve_path, self._server_alias, 'resfileindex.txt') 86 | with open(res_index_path) as f: 87 | for resource_path, file_relpath, file_hash, file_size, compressed_size in csv.reader(f): 88 | index[resource_path] = FileInfo( 89 | resource_path=resource_path, 90 | file_relpath=os.path.join(*file_relpath.split('/')), 91 | file_abspath=os.path.join(self._eve_path, 'ResFiles', *file_relpath.split('/')), 92 | file_hash=file_hash, 93 | file_size=int(file_size), 94 | compressed_size=int(compressed_size)) 95 | app_index_path = os.path.join(self._eve_path, u'index_{}.txt'.format(get_full_alias(self._server_alias))) 96 | with open(app_index_path) as f: 97 | for resource_path, file_relpath, file_hash, file_size, compressed_size, version in csv.reader(f): 98 | index[resource_path] = FileInfo( 99 | resource_path=resource_path, 100 | file_relpath=os.path.join(*file_relpath.split('/')), 101 | file_abspath=os.path.join(self._eve_path, 'ResFiles', *file_relpath.split('/')), 102 | file_hash=file_hash, 103 | file_size=int(file_size), 104 | compressed_size=int(compressed_size)) 105 | return index 106 | 107 | 108 | class FileIntegrityError(Exception): 109 | pass 110 | -------------------------------------------------------------------------------- /util/translator.py: -------------------------------------------------------------------------------- 1 | #=============================================================================== 2 | # Copyright (C) 2014-2019 Anton Vorobyov 3 | # 4 | # This file is part of Phobos. 5 | # 6 | # Phobos is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU Lesser General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # Phobos is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU Lesser General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU Lesser General Public License 17 | # along with Phobos. If not, see . 18 | #=============================================================================== 19 | 20 | 21 | import re 22 | import types 23 | 24 | from miner import ContainerNameError 25 | 26 | 27 | class Translator(object): 28 | """ 29 | Class responsible for text localization. 30 | """ 31 | 32 | def __init__(self, pickle_miner): 33 | self._pickle_miner = pickle_miner 34 | # Format: {language code: {message ID: message text}} 35 | self._loaded_langs = {} 36 | # Container for data we fetch from shared language data 37 | self.__available_langs = None 38 | self.__label_map = None 39 | 40 | def translate_container(self, container_data, language, spec=None, verbose=False): 41 | """ 42 | Translate text fields in passed container 43 | to specified language. 44 | 45 | By default it attempts to do automatic translation 46 | (finds all pairs of fields in fieldName-fieldNameID 47 | format, uses ID to find translation and substitutes 48 | into fieldName[_language] field. 49 | 50 | If spec argument is passed (list of fieldNames which 51 | should be inserted into row, if fieldNameID is present), 52 | then it is used to detect translatable fields instead 53 | of automatic detection. 54 | """ 55 | if not language: 56 | return 57 | stats = {} 58 | self._route_object(container_data, language, spec, stats) 59 | if verbose: 60 | self._print_current_stats(stats) 61 | 62 | # Related to recursive translation 63 | 64 | def _route_object(self, obj, language, spec, stats): 65 | """ 66 | Pick proper method for passed object and invoke it. 67 | """ 68 | obj_type = type(obj) 69 | # We should have normalized data here, thus all objects 70 | # we deal with should be standard python types. We go 71 | # through iterable and mapping types only, other types 72 | # do not need any processing 73 | method = self._translation_map.get(obj_type) 74 | if method is not None: 75 | method(self, obj, language, spec, stats) 76 | 77 | def _translate_map(self, obj, language, spec, stats): 78 | """ 79 | We can translate only data which is in map form, 80 | thus all the translation magic is in this method. 81 | """ 82 | # First, attempt to do a pass over map key/values 83 | # (they are not always text) 84 | for key, value in obj.items(): 85 | self._route_object(key, language, spec, stats) 86 | self._route_object(value, language, spec, stats) 87 | # Now, try to actually translate stuff 88 | for text_fname, msgid_fname in self.__translatable_fields_iter(obj, spec): 89 | self.__increment_stats(stats, text_fname, 0) 90 | orig_text = obj.get(text_fname, '') 91 | msgid = obj[msgid_fname] 92 | # Following are priorities when translating: 93 | # 1) Translation to target language 94 | # 2) Translation to english 95 | # 3) Original value 96 | # 4) Empty string 97 | # If 1st is not available (gets evaluated as False), we go to next 98 | # point and check its availability, and so on 99 | if language == 'multi': 100 | self.__translation_multimode(obj, text_fname, msgid, orig_text, stats) 101 | else: 102 | self.__translation_singlemode(obj, text_fname, msgid, language, orig_text, stats) 103 | 104 | def _translate_iterable(self, obj, language, spec, stats): 105 | """ 106 | For iterables, request to make a pass over each 107 | child element. 108 | """ 109 | for item in obj: 110 | self._route_object(item, language, spec, stats) 111 | 112 | _translation_map = { 113 | types.DictType: _translate_map, 114 | types.TupleType: _translate_iterable, 115 | types.ListType: _translate_iterable 116 | } 117 | 118 | def __translation_multimode(self, row, text_fname, msgid, orig_text, stats): 119 | """ 120 | Translate one field into multiple languages, and write them as 121 | additional fields (in the _ format). Leave 122 | original field untouched. 123 | """ 124 | for language in self.available_langs: 125 | new_text_fname = u'{}_{}'.format(text_fname, language) 126 | if msgid is not None: 127 | trans_text = ( 128 | self.get_by_message(msgid, language) or 129 | orig_text or 130 | '' 131 | ) 132 | else: 133 | trans_text = orig_text or '' 134 | # Always write translation, even if it's the same as 135 | # original text - rows should have the same set of 136 | # fields,regardless of translation availability 137 | row[new_text_fname] = trans_text 138 | # Increment counter only when translation is different 139 | if trans_text != orig_text: 140 | self.__increment_stats(stats, text_fname, 1) 141 | 142 | def __translation_singlemode(self, row, text_fname, msgid, language, orig_text, stats): 143 | """ 144 | Translate one text field into single language. Translation 145 | is inplace. 146 | """ 147 | if msgid is None: 148 | return 149 | trans_text = ( 150 | self.get_by_message(msgid, language) or 151 | orig_text or 152 | '' 153 | ) 154 | row[text_fname] = trans_text 155 | if trans_text != orig_text: 156 | self.__increment_stats(stats, text_fname, 1) 157 | 158 | # Regular expression to detect message ID fields for translation 159 | _keyword_regexp = re.compile('^.*({}).*$'.format('|'.join(('description', 'name', 'text'))), flags=re.IGNORECASE) 160 | 161 | def __translatable_fields_iter(self, row, spec): 162 | """ 163 | Receive dictionary, find there pairs of field 164 | names for translation, and yield them one by one. 165 | """ 166 | suffix = 'ID' 167 | if spec is None: 168 | # We assume that key we're dealing with is field name 169 | # whose value contains message ID, and after that 170 | # we do few verification steps to confirm/deny this 171 | # claim 172 | for msgid_fname in row.keys(): 173 | # It must be string in 'ID' format, skip current 174 | # field name if it's not the case 175 | if isinstance(msgid_fname, types.StringTypes) is False: 176 | continue 177 | tail = msgid_fname[-len(suffix):] 178 | if tail != suffix: 179 | continue 180 | # Message ID can None or integer 181 | msgid = row[msgid_fname] 182 | if msgid is not None and isinstance(msgid, (types.IntType, types.LongType)) is False: 183 | continue 184 | # There're 2 conventions which CCP use for text and message fields: 185 | # 1) There're pair of fields named like fieldName / fieldNameID pair 186 | # 2) For cases when there's no fieldName, we rely on name of fieldNameID 187 | # field - it should contain one of the keywords like 'name' to be translated 188 | text_fname = msgid_fname[:-len(suffix)] 189 | # FIrst convention 190 | if text_fname in row: 191 | # Text can be string or None 192 | text = row[text_fname] 193 | if text is not None and isinstance(text, types.StringTypes) is False: 194 | continue 195 | # If both text and message ID are None, skip them to avoid 196 | # unnecessary translations (which can convert None to empty 197 | # string which is undesired in some cases) 198 | if text is None and msgid is None: 199 | continue 200 | # Second convention 201 | elif re.match(self._keyword_regexp, text_fname): 202 | # We don't have anything to check here 203 | pass 204 | # Skip field names which don't fit into any of these 2 conventions 205 | else: 206 | continue 207 | yield (text_fname, msgid_fname) 208 | else: 209 | for text_fname in spec: 210 | msgid_fname = u'{}{}'.format(text_fname, suffix) 211 | # Skip all message ID fields which are not present in row 212 | if msgid_fname not in row: 213 | continue 214 | yield (text_fname, msgid_fname) 215 | 216 | 217 | def __increment_stats(self, stats, field_name, place, amount=1): 218 | """ 219 | Increment some stat for given field: 220 | 0 - total entries processed 221 | 1 - successful translations 222 | """ 223 | try: 224 | statlist = stats[field_name] 225 | except KeyError: 226 | statlist = [0, 0] 227 | stats[field_name] = statlist 228 | statlist[place] += amount 229 | 230 | def _print_current_stats(self, stats): 231 | """ 232 | Print stats for container which has just been translated. 233 | """ 234 | for field_name in sorted(stats): 235 | total, trans = stats[field_name] 236 | # When we didn't touch translations for some field, 237 | # do not print stats about it 238 | if not trans: 239 | continue 240 | print(u' field {}: {} entries, {} translations'.format(field_name, total, trans)) 241 | 242 | # Related to loading language data 243 | def _load_pickle(self, name): 244 | return self._pickle_miner.get_data(name) 245 | 246 | def _load_lang_data(self, language): 247 | """ 248 | Compose map between message IDs and message texts 249 | and put it into loaded languages map. 250 | """ 251 | try: 252 | lang_data_eve = self._load_pickle(u'res:/localizationfsd/localization_fsd_{}'.format(language)) 253 | except ContainerNameError: 254 | msg = u'data for language "{}" cannot be loaded'.format(language) 255 | raise LanguageNotAvailable(msg) 256 | msg_map_phb = lang_data_eve[1] 257 | self._loaded_langs[language] = msg_map_phb 258 | 259 | def _get_language_data(self, lang): 260 | """ 261 | Get language data and return it; if it's not 262 | loaded yet - load. 263 | """ 264 | try: 265 | lang_data = self._loaded_langs[lang] 266 | except KeyError: 267 | self._load_lang_data(lang) 268 | lang_data = self._loaded_langs[lang] 269 | return lang_data 270 | 271 | _msg_data_stub = ('', None, {}) 272 | 273 | def get_by_message(self, msgid, lang, fallback_lang='en-us', **kwargs): 274 | """ 275 | Fetch message text for specified language and message ID. 276 | If text is empty, attempt to use fallback language. If 277 | it is not found too, return empty string. 278 | """ 279 | try: 280 | lang_data = self._get_language_data(lang) 281 | except LanguageNotAvailable: 282 | lang_data = self._get_language_data(fallback_lang) 283 | msg_data = lang_data.get(msgid, self._msg_data_stub) 284 | # Use fallback language only when fetching text for primary 285 | # language failed, and when fallback language doesn't match 286 | # primary language 287 | if not msg_data[0] and fallback_lang is not None and lang != fallback_lang: 288 | lang_data_fb = self._get_language_data(fallback_lang) 289 | msg_data = lang_data_fb.get(msgid, self._msg_data_stub) 290 | text = self._format_message(msg_data, kwargs) 291 | return text 292 | 293 | def get_by_label(self, label, *args, **kwargs): 294 | """ 295 | Fetch message text for specified language and label. 296 | If label cannot be found, raise exception. If no text 297 | found, return empty string. 298 | """ 299 | try: 300 | msgid = self._label_map[label] 301 | except KeyError: 302 | msg = u'label {} does not exist'.format(label) 303 | raise LabelError(msg) 304 | return self.get_by_message(msgid, *args, **kwargs) 305 | 306 | def _format_message(self, msg_data, kwargs): 307 | """ 308 | Take message data and substitute passed arguments 309 | into it, then return final message text. 310 | """ 311 | text, _, tokens = msg_data 312 | # Tokens may be None 313 | if not tokens: 314 | return text 315 | for tok_name, tok_data in tokens.items(): 316 | arg_name = tok_data['variableName'] 317 | try: 318 | substitution = kwargs[arg_name] 319 | except KeyError: 320 | continue 321 | text = text.replace(tok_name, unicode(substitution)) 322 | return text 323 | 324 | @property 325 | def available_langs(self): 326 | """ 327 | Returns list of available translation languages. 328 | """ 329 | if self.__available_langs is None: 330 | self._load_shared_data() 331 | return self.__available_langs 332 | 333 | @property 334 | def _label_map(self): 335 | """ 336 | Map between labels and message IDs. 337 | Format: {full/path/to/label: message ID} 338 | """ 339 | if self.__label_map is None: 340 | self._load_shared_data() 341 | return self.__label_map 342 | 343 | def _load_shared_data(self): 344 | """ 345 | To avoid loading same pickles twice, fetch necessary data 346 | from them here and assign to proper attributes. This method 347 | is intended to be called when any of shared data is requested. 348 | """ 349 | lbl_map_phb = {} 350 | main_eve = self._load_pickle('res:/localizationfsd/localization_fsd_main') 351 | # Load list of languages 352 | languages = set(main_eve['languages']) 353 | self.__available_langs = tuple(sorted(languages)) 354 | # Load label map 355 | for msgid in sorted(main_eve['labels']): 356 | lbl_data = main_eve['labels'][msgid] 357 | lbl_base = lbl_data.get('FullPath') 358 | lbl_name = lbl_data.get('label') 359 | lbl_components = [] 360 | if lbl_base: 361 | lbl_components.append(lbl_base) 362 | if lbl_name: 363 | lbl_components.append(lbl_name) 364 | lbl_path = u'/'.join(lbl_components) 365 | lbl_map_phb[lbl_path] = msgid 366 | self.__label_map = lbl_map_phb 367 | 368 | 369 | class LanguageNotAvailable(Exception): 370 | """ 371 | Raised when translator is asked to translate to language 372 | which it does not support. 373 | """ 374 | pass 375 | 376 | 377 | class LabelError(Exception): 378 | """ 379 | Raised when requested label cannot be found. 380 | """ 381 | pass 382 | -------------------------------------------------------------------------------- /writer/__init__.py: -------------------------------------------------------------------------------- 1 | #=============================================================================== 2 | # Copyright (C) 2014-2019 Anton Vorobyov 3 | # 4 | # This file is part of Phobos. 5 | # 6 | # Phobos is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU Lesser General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # Phobos is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU Lesser General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU Lesser General Public License 17 | # along with Phobos. If not, see . 18 | #=============================================================================== 19 | 20 | 21 | from .json_writer import JsonWriter 22 | 23 | 24 | __all__ = ( 25 | 'JsonWriter', 26 | ) 27 | -------------------------------------------------------------------------------- /writer/base.py: -------------------------------------------------------------------------------- 1 | #=============================================================================== 2 | # Copyright (C) 2014-2019 Anton Vorobyov 3 | # 4 | # This file is part of Phobos. 5 | # 6 | # Phobos is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU Lesser General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # Phobos is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU Lesser General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU Lesser General Public License 17 | # along with Phobos. If not, see . 18 | #=============================================================================== 19 | 20 | 21 | from abc import ABCMeta, abstractmethod 22 | 23 | 24 | class BaseWriter(object): 25 | """ 26 | Abstract class, which defines interface to classes 27 | which write data into some kind of persistent storage. 28 | """ 29 | __metaclass__ = ABCMeta 30 | 31 | @abstractmethod 32 | def write(self, miner_name, container_name, container_data): 33 | raise NotImplementedError 34 | -------------------------------------------------------------------------------- /writer/json_writer.py: -------------------------------------------------------------------------------- 1 | #=============================================================================== 2 | # Copyright (C) 2014-2019 Anton Vorobyov 3 | # 4 | # This file is part of Phobos. 5 | # 6 | # Phobos is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU Lesser General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # Phobos is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU Lesser General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU Lesser General Public License 17 | # along with Phobos. If not, see . 18 | #=============================================================================== 19 | 20 | 21 | import json 22 | import os.path 23 | import re 24 | import types 25 | from collections import OrderedDict 26 | from itertools import izip_longest 27 | 28 | from .base import BaseWriter 29 | 30 | 31 | def natural_sort(i): 32 | if isinstance(i, (str, unicode)): 33 | return [int(text) if text.isdigit() else text.lower() for text in re.split('([0-9]+)', i)] 34 | return i 35 | 36 | 37 | class CustomEncoder(json.JSONEncoder): 38 | """ 39 | If we're not happy with default encoder - all modifications 40 | are implemented in this class. 41 | """ 42 | 43 | def encode(self, obj, *args, **kwargs): 44 | obj = self._route_object(obj) 45 | return json.JSONEncoder.encode(self, obj, *args, **kwargs) 46 | 47 | def iterencode(self, obj, *args, **kwargs): 48 | obj = self._route_object(obj) 49 | return json.JSONEncoder.iterencode(self, obj, *args, **kwargs) 50 | 51 | def _route_object(self, obj): 52 | obj_type = type(obj) 53 | method = self._traversal_map.get(obj_type) 54 | if method is not None: 55 | new_obj = method(self, obj) 56 | else: 57 | new_obj = obj 58 | return new_obj 59 | 60 | def _traverse_map(self, obj): 61 | """ 62 | Traverse through dict items first, then convert 63 | keys to strings. 64 | """ 65 | new_obj = {} 66 | for k, v in obj.items(): 67 | new_obj[self._route_object(k)] = self._route_object(v) 68 | new_obj = self._prepare_map(new_obj) 69 | return new_obj 70 | 71 | def _traverse_iterable(self, obj): 72 | new_obj = [] 73 | for item in obj: 74 | new_obj.append(self._route_object(item)) 75 | return new_obj 76 | 77 | _traversal_map = { 78 | types.DictType: _traverse_map, 79 | types.TupleType: _traverse_iterable, 80 | types.ListType: _traverse_iterable} 81 | 82 | def _prepare_map(self, obj): 83 | """ 84 | Sort keys the way we want and unconditionally convert dictionary keys 85 | to strings. Default encoder doesn't do this for cases when keys are 86 | python objects like tuple, and encoding fails. 87 | """ 88 | new_obj = OrderedDict() 89 | for k in sorted(obj.keys(), key=natural_sort): 90 | new_obj[unicode(k)] = obj[k] 91 | return new_obj 92 | 93 | 94 | class JsonWriter(BaseWriter): 95 | """ 96 | Class, which stores fetched data on storage device 97 | as JSON files. 98 | """ 99 | 100 | def __init__(self, folder, indent=None, group=None): 101 | self.base_folder = folder 102 | self.indent = indent 103 | self.group = group 104 | 105 | def write(self, miner_name, container_name, container_data): 106 | # Create folder structure to path, if not created yet 107 | folder = os.path.join(self.base_folder, self.__secure_name(miner_name)) 108 | if not os.path.exists(folder): 109 | os.makedirs(folder, mode=0o755) 110 | 111 | data_type = type(container_data) 112 | grouping_method = self._grouping_map.get(data_type) 113 | if self.group is None or grouping_method is None: 114 | filepath = os.path.join(folder, u'{}.json'.format(self.__secure_name(container_name))) 115 | self.__write_file(container_data, filepath) 116 | else: 117 | for i, group_data in enumerate(grouping_method(self, container_data)): 118 | filepath = os.path.join(folder, u'{}.{}.json'.format(self.__secure_name(container_name), i)) 119 | self.__write_file(group_data, filepath) 120 | 121 | def _group_dict(self, container_data): 122 | group_data = {} 123 | for k in sorted(container_data, key=natural_sort): 124 | group_data[k] = container_data[k] 125 | if len(group_data) >= self.group: 126 | yield group_data 127 | group_data = {} 128 | if group_data: 129 | yield group_data 130 | 131 | def _group_list(self, container_data): 132 | group_data = [] 133 | for i in container_data: 134 | group_data.append(i) 135 | if len(group_data) >= self.group: 136 | yield group_data 137 | group_data = [] 138 | if group_data: 139 | yield group_data 140 | 141 | _grouping_map = { 142 | types.DictType: _group_dict, 143 | types.TupleType: _group_list, 144 | types.ListType: _group_list} 145 | 146 | def __write_file(self, data, filepath): 147 | data_str = json.dumps( 148 | data, 149 | ensure_ascii=False, 150 | cls=CustomEncoder, 151 | indent=self.indent, 152 | # We're handling sorting in customized encoder 153 | sort_keys=False) 154 | data_bytes = data_str.encode('utf8') 155 | with open(filepath, 'wb') as f: 156 | f.write(data_bytes) 157 | 158 | def __secure_name(self, name): 159 | """ 160 | As we're writing to disk, we should get rid of all 161 | filesystem-specific symbols. 162 | """ 163 | # Prefer safe way - replace any characters besides 164 | # alphanumeric and few special characters with 165 | # underscore 166 | writer_safe_name = re.sub('[^\w\-.,() ]', '_', name, flags=re.UNICODE) 167 | return writer_safe_name 168 | --------------------------------------------------------------------------------