├── .github └── dependabot.yml ├── .gitignore ├── LICENSE ├── README.md ├── __init__.py ├── _config.yml ├── assets ├── assets.json ├── geocoding.json └── iso3166-1.json ├── css ├── light.png └── tracemap.css ├── externalQuery.py ├── favicon.ico ├── geo.py ├── html └── .gitkeep ├── js └── qrcode.js ├── localQuery.py ├── log └── .gitkeep ├── main.py ├── requirements.txt ├── template └── template.html ├── traceMap.service ├── translate.py └── webServer.py /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "pip" # See documentation for possible values 9 | directory: "/" # Location of package manifests 10 | schedule: 11 | interval: "weekly" 12 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /html/*.html 2 | /log/*.json 3 | /test/ 4 | __pycache__ 5 | .idea 6 | .DS_Store 7 | .vscode 8 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 | NextTrace Logo 4 | 5 |
6 | 7 | # traceMap 8 | 9 | NextTrace Enhanced traceMap Plugin 10 | 11 | 同时支持本地查询和使用OSMAPI查询 12 | 13 | ## How To Use 14 | 15 | + 运行`traceMap`服务器 16 | 17 | 默认端口为`8888` 18 | 19 | POST接口默认路径为`/api`,GET接口默认路径为`/html/` 20 | 21 | ```bash 22 | mkdir -p /var/www 23 | cd /var/www 24 | git clone https://github.com/tsosunchia/traceMap.git 25 | cd traceMap 26 | pip3 install -r requirements.txt 27 | mv traceMap.service /etc/systemd/system/ 28 | systemctl daemon-reload 29 | systemctl enable traceMap.service 30 | systemctl start traceMap.service 31 | ``` 32 | 33 | + 调试模式:调用`main.py`中的`process`函数即可。 34 | 35 | ```python3 36 | def process(rawData) -> str: 37 | """ 38 | 处理原始数据,获取HTML文件路径 39 | :param rawData: dict, 原始数据 40 | :return: str, HTML文件路径 41 | """ 42 | ``` 43 | 44 | 默认使用本地查询,如果需要使用OSMAPI查询,请在`main.py`中设置`localQuery`为`False`。 45 | 46 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import json 3 | import logging 4 | import os 5 | import re 6 | import random 7 | import IPy 8 | import traceback 9 | import uuid 10 | from multiprocessing.dummy import Pool as ThreadPool 11 | from typing import Union 12 | from urllib import parse 13 | from packaging import version 14 | 15 | import requests 16 | from requests.adapters import HTTPAdapter 17 | 18 | import html 19 | 20 | accept_version = "1.2.7" 21 | latest_version = "1.3.0" 22 | 23 | if __name__ == '__main__': 24 | _ = str(json) + str(logging) + str(ThreadPool()) + str(datetime) + str(os) + str(html) + str(re) + str(Union) + \ 25 | str(parse) + str(requests) + str(HTTPAdapter) + str(random) + str(IPy) + str(traceback) + str(uuid) + str(version) 26 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-cayman -------------------------------------------------------------------------------- /assets/assets.json: -------------------------------------------------------------------------------- 1 | { 2 | "美国": "United States of America", 3 | "香港": "Hong Kong S.A.R.", 4 | "澳门": "Macao S.A.R.", 5 | "United States": "United States of America", 6 | "U.S.": "United States of America", 7 | "中国": "China", 8 | "丹麦": "Denmark", 9 | "乌克兰": "Ukraine", 10 | "俄罗斯": "Russia", 11 | "加拿大": "Canada", 12 | "匈牙利": "Hungary", 13 | "南非": "South Africa", 14 | "卢森堡": "Luxembourg", 15 | "印度": "India", 16 | "吉布提": "Djibouti", 17 | "墨西哥": "Mexico", 18 | "奥地利": "Austria", 19 | "巴西": "Brazil", 20 | "德国": "Germany", 21 | "意大利": "Italy", 22 | "斯洛伐克": "Slovakia", 23 | "新加坡": "Singapore", 24 | "日本": "Japan", 25 | "智利": "Chile", 26 | "法国": "France", 27 | "波兰": "Poland", 28 | "澳大利亚": "Australia", 29 | "爱尔兰": "Ireland", 30 | "瑞典": "Sweden", 31 | "瑞士": "Switzerland", 32 | "罗马尼亚": "Romania", 33 | "肯尼亚": "Kenya", 34 | "英国": "United Kingdom", 35 | "荷兰": "Netherlands", 36 | "西班牙": "Spain", 37 | "越南": "Vietnam", 38 | "韩国": "South Korea", 39 | "马来西亚": "Malaysia" 40 | } -------------------------------------------------------------------------------- /assets/iso3166-1.json: -------------------------------------------------------------------------------- 1 | { 2 | "AF": "Afghanistan", 3 | "AX": "Åland Islands", 4 | "AL": "Albania", 5 | "DZ": "Algeria", 6 | "AS": "American Samoa", 7 | "AD": "Andorra", 8 | "AO": "Angola", 9 | "AI": "Anguilla", 10 | "AQ": "Antarctica", 11 | "AG": "Antigua and Barbuda", 12 | "AR": "Argentina", 13 | "AM": "Armenia", 14 | "AW": "Aruba", 15 | "AU": "Australia", 16 | "AT": "Austria", 17 | "AZ": "Azerbaijan", 18 | "BH": "Bahrain", 19 | "BS": "Bahamas", 20 | "BD": "Bangladesh", 21 | "BB": "Barbados", 22 | "BY": "Belarus", 23 | "BE": "Belgium", 24 | "BZ": "Belize", 25 | "BJ": "Benin", 26 | "BM": "Bermuda", 27 | "BT": "Bhutan", 28 | "BO": "Bolivia", 29 | "BQ": "Bonaire", 30 | "BA": "Bosnia and Herzegovina", 31 | "BW": "Botswana", 32 | "BV": "Bouvet Island", 33 | "BR": "Brazil", 34 | "IO": "British Indian Ocean Territory", 35 | "BN": "Brunei Darussalam", 36 | "BG": "Bulgaria", 37 | "BF": "Burkina Faso", 38 | "BI": "Burundi", 39 | "KH": "Cambodia", 40 | "CM": "Cameroon", 41 | "CA": "Canada", 42 | "CV": "Cape Verde", 43 | "KY": "Cayman Islands", 44 | "CF": "Central African Republic", 45 | "TD": "Chad", 46 | "CL": "Chile", 47 | "CN": "China", 48 | "CX": "Christmas Island", 49 | "CC": "Cocos (Keeling) Islands", 50 | "CO": "Colombia", 51 | "KM": "Comoros", 52 | "CG": "Congo", 53 | "CD": "Congo", 54 | "CK": "Cook Islands", 55 | "CR": "Costa Rica", 56 | "CI": "Côte d'Ivoire", 57 | "HR": "Croatia", 58 | "CU": "Cuba", 59 | "CW": "Curaçao", 60 | "CY": "Cyprus", 61 | "CZ": "Czech Republic", 62 | "DK": "Denmark", 63 | "DJ": "Djibouti", 64 | "DM": "Dominica", 65 | "DO": "Dominican Republic", 66 | "EC": "Ecuador", 67 | "EG": "Egypt", 68 | "SV": "El Salvador", 69 | "GQ": "Equatorial Guinea", 70 | "ER": "Eritrea", 71 | "EE": "Estonia", 72 | "ET": "Ethiopia", 73 | "FK": "Falkland Islands (Malvinas)", 74 | "FO": "Faroe Islands", 75 | "FJ": "Fiji", 76 | "FI": "Finland", 77 | "FR": "France", 78 | "GF": "French Guiana", 79 | "PF": "French Polynesia", 80 | "TF": "French Southern Territories", 81 | "GA": "Gabon", 82 | "GM": "Gambia", 83 | "GE": "Georgia", 84 | "DE": "Germany", 85 | "GH": "Ghana", 86 | "GI": "Gibraltar", 87 | "GR": "Greece", 88 | "GL": "Greenland", 89 | "GD": "Grenada", 90 | "GP": "Guadeloupe", 91 | "GU": "Guam", 92 | "GT": "Guatemala", 93 | "GG": "Guernsey", 94 | "GN": "Guinea", 95 | "GW": "Guinea-Bissau", 96 | "GY": "Guyana", 97 | "HT": "Haiti", 98 | "HM": "Heard Island and McDonald Islands", 99 | "VA": "Holy See (Vatican City State)", 100 | "HN": "Honduras", 101 | "HK": "Hong Kong", 102 | "HU": "Hungary", 103 | "IS": "Iceland", 104 | "IN": "India", 105 | "ID": "Indonesia", 106 | "IR": "Iran", 107 | "IQ": "Iraq", 108 | "IE": "Ireland", 109 | "IM": "Isle of Man", 110 | "IL": "Israel", 111 | "IT": "Italy", 112 | "JM": "Jamaica", 113 | "JP": "Japan", 114 | "JE": "Jersey", 115 | "JO": "Jordan", 116 | "KZ": "Kazakhstan", 117 | "KE": "Kenya", 118 | "KI": "Kiribati", 119 | "KP": "Korea", 120 | "KR": "Korea", 121 | "KW": "Kuwait", 122 | "KG": "Kyrgyzstan", 123 | "LA": "Lao People's Democratic Republic", 124 | "LV": "Latvia", 125 | "LB": "Lebanon", 126 | "LS": "Lesotho", 127 | "LR": "Liberia", 128 | "LY": "Libya", 129 | "LI": "Liechtenstein", 130 | "LT": "Lithuania", 131 | "LU": "Luxembourg", 132 | "MO": "Macao", 133 | "MK": "Macedonia", 134 | "MG": "Madagascar", 135 | "MW": "Malawi", 136 | "MY": "Malaysia", 137 | "MV": "Maldives", 138 | "ML": "Mali", 139 | "MT": "Malta", 140 | "MH": "Marshall Islands", 141 | "MQ": "Martinique", 142 | "MR": "Mauritania", 143 | "MU": "Mauritius", 144 | "YT": "Mayotte", 145 | "MX": "Mexico", 146 | "FM": "Micronesia", 147 | "MD": "Moldova", 148 | "MC": "Monaco", 149 | "MN": "Mongolia", 150 | "ME": "Montenegro", 151 | "MS": "Montserrat", 152 | "MA": "Morocco", 153 | "MZ": "Mozambique", 154 | "MM": "Myanmar", 155 | "NA": "Namibia", 156 | "NR": "Nauru", 157 | "NP": "Nepal", 158 | "NL": "Netherlands", 159 | "NC": "New Caledonia", 160 | "NZ": "New Zealand", 161 | "NI": "Nicaragua", 162 | "NE": "Niger", 163 | "NG": "Nigeria", 164 | "NU": "Niue", 165 | "NF": "Norfolk Island", 166 | "MP": "Northern Mariana Islands", 167 | "NO": "Norway", 168 | "OM": "Oman", 169 | "PK": "Pakistan", 170 | "PW": "Palau", 171 | "PS": "Palestine", 172 | "PA": "Panama", 173 | "PG": "Papua New Guinea", 174 | "PY": "Paraguay", 175 | "PE": "Peru", 176 | "PH": "Philippines", 177 | "PN": "Pitcairn", 178 | "PL": "Poland", 179 | "PT": "Portugal", 180 | "PR": "Puerto Rico", 181 | "QA": "Qatar", 182 | "RE": "Réunion", 183 | "RO": "Romania", 184 | "RU": "Russian Federation", 185 | "RW": "Rwanda", 186 | "BL": "Saint Barthélemy", 187 | "SH": "Saint Helena", 188 | "KN": "Saint Kitts and Nevis", 189 | "LC": "Saint Lucia", 190 | "MF": "Saint Martin (French part)", 191 | "PM": "Saint Pierre and Miquelon", 192 | "VC": "Saint Vincent and the Grenadines", 193 | "WS": "Samoa", 194 | "SM": "San Marino", 195 | "ST": "Sao Tome and Principe", 196 | "SA": "Saudi Arabia", 197 | "SN": "Senegal", 198 | "RS": "Serbia", 199 | "SC": "Seychelles", 200 | "SL": "Sierra Leone", 201 | "SG": "Singapore", 202 | "SX": "Sint Maarten (Dutch part)", 203 | "SK": "Slovakia", 204 | "SI": "Slovenia", 205 | "SB": "Solomon Islands", 206 | "SO": "Somalia", 207 | "ZA": "South Africa", 208 | "GS": "South Georgia and the South Sandwich Islands", 209 | "SS": "South Sudan", 210 | "ES": "Spain", 211 | "LK": "Sri Lanka", 212 | "SD": "Sudan", 213 | "SR": "Suriname", 214 | "SJ": "Svalbard and Jan Mayen", 215 | "SZ": "Swaziland", 216 | "SE": "Sweden", 217 | "CH": "Switzerland", 218 | "SY": "Syrian Arab Republic", 219 | "TW": "Taiwan", 220 | "TJ": "Tajikistan", 221 | "TZ": "Tanzania", 222 | "TH": "Thailand", 223 | "TL": "Timor-Leste", 224 | "TG": "Togo", 225 | "TK": "Tokelau", 226 | "TO": "Tonga", 227 | "TT": "Trinidad and Tobago", 228 | "TN": "Tunisia", 229 | "TR": "Turkey", 230 | "TM": "Turkmenistan", 231 | "TC": "Turks and Caicos Islands", 232 | "TV": "Tuvalu", 233 | "UG": "Uganda", 234 | "UA": "Ukraine", 235 | "AE": "United Arab Emirates", 236 | "GB": "United Kingdom", 237 | "US": "United States of America", 238 | "UM": "United States Minor Outlying Islands", 239 | "UY": "Uruguay", 240 | "UZ": "Uzbekistan", 241 | "VU": "Vanuatu", 242 | "VE": "Venezuela", 243 | "VN": "Viet Nam", 244 | "VG": "Virgin Islands", 245 | "VI": "Virgin Islands", 246 | "WF": "Wallis and Futuna", 247 | "EH": "Western Sahara", 248 | "YE": "Yemen", 249 | "ZM": "Zambia", 250 | "ZW": "Zimbabwe" 251 | } -------------------------------------------------------------------------------- /css/light.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nxtrace/traceMap/f53370ae58171a74a672114a76536c052e324a60/css/light.png -------------------------------------------------------------------------------- /css/tracemap.css: -------------------------------------------------------------------------------- 1 | body, 2 | html, 3 | #allmap { 4 | pointer-events: auto; 5 | z-index: 1; 6 | width: 100%; 7 | height: 100%; 8 | overflow: hidden; 9 | margin: 0; 10 | } 11 | 12 | table { 13 | width: 100%; 14 | border-collapse: collapse; 15 | } 16 | 17 | @media screen and (min-width: 500px) { 18 | th, 19 | td { 20 | padding: 8px; 21 | text-align: left; 22 | border-bottom: 1px rgba(161, 190, 199, 0.705); 23 | font-size: 1vw; 24 | } 25 | 26 | th { 27 | background-color: rgba(84, 125, 138, 0.4); 28 | font-size: 1vw; 29 | } 30 | 31 | .table-container { 32 | pointer-events: auto; 33 | z-index: 2; 34 | position: fixed; 35 | height: auto; 36 | width: auto; 37 | transform: translate(0, -50%); 38 | top: 50%; 39 | background-color: rgba(195, 214, 219, 0.705); 40 | backdrop-filter: blur(12px); 41 | overflow: auto; 42 | border-radius: 10px; 43 | border: 2px solid rgba(84, 125, 138, 0.705); 44 | } 45 | 46 | .qrcode-container { 47 | pointer-events: auto; 48 | z-index: 2; 49 | position: fixed; 50 | height: auto; 51 | width: auto; 52 | transform: translate(0, -50%); 53 | top: 50%; 54 | left: 40%; 55 | background-color: rgba(195, 214, 219, 0.705); 56 | backdrop-filter: blur(12px); 57 | overflow: auto; 58 | border-radius: 10px; 59 | border: 2px solid rgba(84, 125, 138, 0.705); 60 | } 61 | } 62 | 63 | @media screen and (max-width: 500px) { 64 | .table-container { 65 | pointer-events: auto; 66 | z-index: 2; 67 | position: fixed; 68 | height: auto; 69 | width: auto; 70 | max-width: 80%; 71 | max-height: 50%; 72 | transform: translate(0, -50%); 73 | top: 50%; 74 | background-color: rgba(195, 214, 219, 0.705); 75 | backdrop-filter: blur(12px); 76 | overflow: auto; 77 | border-radius: 10px; 78 | border: 2px solid rgba(84, 125, 138, 0.705); 79 | } 80 | 81 | th, 82 | td { 83 | padding: 8px; 84 | text-align: left; 85 | border-bottom: 1px rgba(161, 190, 199, 0.705); 86 | /*font-size: 16px;*/ 87 | } 88 | 89 | th { 90 | background-color: rgba(84, 125, 138, 0.4); 91 | /*font-size: 16px;*/ 92 | } 93 | 94 | .qrcode-container { 95 | pointer-events: auto; 96 | z-index: 2; 97 | position: fixed; 98 | height: auto; 99 | width: auto; 100 | transform: translate(0, -50%); 101 | top: 50%; 102 | left: 10%; 103 | background-color: rgba(195, 214, 219, 0.705); 104 | backdrop-filter: blur(12px); 105 | overflow: auto; 106 | border-radius: 10px; 107 | border: 2px solid rgba(84, 125, 138, 0.705); 108 | } 109 | } -------------------------------------------------------------------------------- /externalQuery.py: -------------------------------------------------------------------------------- 1 | import geo 2 | from __init__ import * 3 | 4 | iso3166MapDict = json.load(open('assets/iso3166-1.json', 'r', encoding='utf-8')) 5 | session = requests.session() 6 | session.mount('https://', HTTPAdapter(max_retries=2)) 7 | 8 | 9 | def search(country: str, prov: str): 10 | """ 11 | 根据国家和省份查询经纬度 by English 12 | :param country: str, 国家 13 | :param prov: str, 省份 14 | :return: tuple(lat:float, lng:float, msg:str) 15 | """ 16 | addr = country + ',' + prov 17 | logging.debug(f'addr:{addr}') 18 | if (country == 'China') or (country == '中国'): 19 | if prov == '': 20 | return None 21 | if prov == 'Taiwan': 22 | return 23.9739374, 120.9820179, "China, Taiwan Province" 23 | try: 24 | r = session.get(f'https://nominatim.openstreetmap.org/search/{addr}?limit=1&format=json', timeout=3) 25 | r = r.json()[0] 26 | except IndexError: 27 | logging.info('{} {} not found by osmApi'.format(country, prov)) 28 | return None 29 | return float(r['lat']), float(r['lon']), addr 30 | 31 | 32 | def geocoding(geoRawDataList: list) -> list: 33 | """ 34 | 多个地址转经纬度 35 | :param geoRawDataList: list, 地址集:[['Country0','Prov0','extraMsg0'],['Country1','Prov1','extraMsg1'],...] 36 | :return: list, 经纬度:[[lat0:float, lng0:float, msg0:str],[lat1:float, lng1:float, msg1:str],...] 37 | """ 38 | coordinatesList = [] 39 | pool = ThreadPool(4) 40 | sum_result = pool.map(geocodingSingle, geoRawDataList) 41 | pool.close() 42 | pool.join() 43 | logging.info(f"geocoding_osm_sum_result:{sum_result}") 44 | for i in sum_result: 45 | if i and len(i) == 3: 46 | coordinatesList.append([i[0], i[1], i[2]]) 47 | return coordinatesList 48 | 49 | 50 | def geocodingSingle(geoRawDataList: list): 51 | return geo.geocodingSingle(geoRawDataList, localQuery=False) 52 | -------------------------------------------------------------------------------- /favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nxtrace/traceMap/f53370ae58171a74a672114a76536c052e324a60/favicon.ico -------------------------------------------------------------------------------- /geo.py: -------------------------------------------------------------------------------- 1 | import translate 2 | from __init__ import * 3 | 4 | iso3166MapDict = json.load(open('assets/iso3166-1.json', 'r', encoding='utf-8')) 5 | 6 | 7 | def listToStr(rawList: list) -> str: 8 | """ 9 | 列表转字符串 10 | :param rawList: list, 列表 11 | :return: str, 字符串 12 | """ 13 | resStr = '' 14 | for i in rawList: 15 | if type(i) is not str: 16 | i = str(i) 17 | if i: 18 | if resStr: 19 | resStr += ',' 20 | resStr += i 21 | return resStr 22 | 23 | 24 | def getRawData(rawData: dict, localQuery: bool) -> list: 25 | """ 26 | 获取原始数据 27 | :param localQuery: bool, 是否为本地查询 28 | :param rawData: dict, 原始数据 29 | :return: [['Country0','Prov0','extraMsg0'],['Country1','Prov1','extraMsg1'],...] 30 | """ 31 | logging.debug('rawData: {}'.format(rawData)) 32 | hopsList = rawData['Hops'] 33 | logging.debug('hopsList: {}'.format(hopsList)) 34 | geoRawDataList = [] 35 | for hop in hopsList: 36 | for time in hop: 37 | try: 38 | if time['Geo']['Country'] == 'LAN Address': 39 | break 40 | except TypeError: 41 | break 42 | if time['Success']: 43 | if time['Geo']['Country']: 44 | geoRawDataList.append([ 45 | time['Geo']['Country'], 46 | time['Geo']['Prov'], 47 | listToStr([ 48 | time['Geo']['City'], 49 | time['Geo']['District'], 50 | 'IP:' + time['Address']['IP'], 51 | ('asn:' + time['Geo']['Asnumber']) if time['Geo']['Asnumber'] else '', 52 | 'TTL:' + str(time['TTL']), 53 | f"RTT:{time['RTT'] / 10e5:.1f}ms", 54 | ('Owner:' + time['Geo']['Owner']) if time['Geo']['Owner'] else '', 55 | ('ISP:' + time['Geo']['Isp']) if time['Geo']['Isp'] else '', 56 | ]) 57 | ]) 58 | break 59 | if localQuery: 60 | geoRawDataList = translate.dictTranslate(geoRawDataList) 61 | logging.debug('geoRawDataList: {}'.format(geoRawDataList)) 62 | return geoRawDataList 63 | 64 | 65 | def geocodingSingle(addrList: list, localQuery: bool): 66 | """ 67 | 单个地址转经纬度 68 | :param localQuery: bool, 是否为本地查询 69 | :param addrList: list, 地址信息,格式为[国家, 省份, 额外信息] 70 | :return: list[lat:float, lng:str, msg:float], 经纬度 71 | """ 72 | if len(addrList[0].encode()) == 2: 73 | if addrList[0] in iso3166MapDict: 74 | country = iso3166MapDict[addrList[0]] 75 | else: 76 | country = addrList[0] 77 | else: 78 | country = addrList[0] 79 | logging.debug('country: {}'.format(country)) 80 | prov = addrList[1] 81 | logging.debug('prov: {}'.format(prov)) 82 | extraMsg = addrList[2] 83 | if localQuery: 84 | from localQuery import search 85 | else: 86 | from externalQuery import search 87 | coordinateTuple = search(country, prov) 88 | if coordinateTuple and len(coordinateTuple) == 3: 89 | tmpMsg = coordinateTuple[2] + ',' + extraMsg 90 | logging.debug(f"coordinateTuple: {[coordinateTuple[0], coordinateTuple[1], tmpMsg]}") 91 | return [coordinateTuple[0], coordinateTuple[1], tmpMsg] 92 | else: 93 | if not ((country == 'China') and (prov == '')): 94 | logging.info('{}, {} not found'.format(country, prov)) 95 | return None 96 | 97 | 98 | def geoInterface(rawData: dict, localQuery: bool) -> list: 99 | """ 100 | 地址转经纬度接口 101 | :param localQuery: bool, 是否为本地查询 102 | :param rawData: dict, 原始数据 103 | :return: list, 经纬度:[[lat0:float, lng0:float, msg0:str],[lat1:float, lng1:float, msg1:str],...] 104 | """ 105 | geoRawDataList = getRawData(rawData, localQuery) 106 | if localQuery: 107 | from localQuery import geocoding 108 | else: 109 | from externalQuery import geocoding 110 | coordinatesList = geocoding(geoRawDataList) 111 | if not coordinatesList: 112 | logging.warning('没有搜索到任何数据\nrawData:\n{}'.format(rawData)) 113 | logging.debug('coordinatesList: {}'.format(coordinatesList)) 114 | return coordinatesList 115 | -------------------------------------------------------------------------------- /html/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nxtrace/traceMap/f53370ae58171a74a672114a76536c052e324a60/html/.gitkeep -------------------------------------------------------------------------------- /js/qrcode.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @fileoverview 3 | * - Using the 'QRCode for Javascript library' 4 | * - Fixed dataset of 'QRCode for Javascript library' for support full-spec. 5 | * - this library has no dependencies. 6 | * 7 | * @author davidshimjs 8 | * @see http://www.d-project.com/ 9 | * @see http://jeromeetienne.github.com/jquery-qrcode/ 10 | */ 11 | var QRCode; 12 | 13 | (function () { 14 | //--------------------------------------------------------------------- 15 | // QRCode for JavaScript 16 | // 17 | // Copyright (c) 2009 Kazuhiko Arase 18 | // 19 | // URL: http://www.d-project.com/ 20 | // 21 | // Licensed under the MIT license: 22 | // http://www.opensource.org/licenses/mit-license.php 23 | // 24 | // The word "QR Code" is registered trademark of 25 | // DENSO WAVE INCORPORATED 26 | // http://www.denso-wave.com/qrcode/faqpatent-e.html 27 | // 28 | //--------------------------------------------------------------------- 29 | function QR8bitByte(data) { 30 | this.mode = QRMode.MODE_8BIT_BYTE; 31 | this.data = data; 32 | this.parsedData = []; 33 | 34 | // Added to support UTF-8 Characters 35 | for (var i = 0, l = this.data.length; i < l; i++) { 36 | var byteArray = []; 37 | var code = this.data.charCodeAt(i); 38 | 39 | if (code > 0x10000) { 40 | byteArray[0] = 0xF0 | ((code & 0x1C0000) >>> 18); 41 | byteArray[1] = 0x80 | ((code & 0x3F000) >>> 12); 42 | byteArray[2] = 0x80 | ((code & 0xFC0) >>> 6); 43 | byteArray[3] = 0x80 | (code & 0x3F); 44 | } else if (code > 0x800) { 45 | byteArray[0] = 0xE0 | ((code & 0xF000) >>> 12); 46 | byteArray[1] = 0x80 | ((code & 0xFC0) >>> 6); 47 | byteArray[2] = 0x80 | (code & 0x3F); 48 | } else if (code > 0x80) { 49 | byteArray[0] = 0xC0 | ((code & 0x7C0) >>> 6); 50 | byteArray[1] = 0x80 | (code & 0x3F); 51 | } else { 52 | byteArray[0] = code; 53 | } 54 | 55 | this.parsedData.push(byteArray); 56 | } 57 | 58 | this.parsedData = Array.prototype.concat.apply([], this.parsedData); 59 | 60 | if (this.parsedData.length != this.data.length) { 61 | this.parsedData.unshift(191); 62 | this.parsedData.unshift(187); 63 | this.parsedData.unshift(239); 64 | } 65 | } 66 | 67 | QR8bitByte.prototype = { 68 | getLength: function (buffer) { 69 | return this.parsedData.length; 70 | }, 71 | write: function (buffer) { 72 | for (var i = 0, l = this.parsedData.length; i < l; i++) { 73 | buffer.put(this.parsedData[i], 8); 74 | } 75 | } 76 | }; 77 | 78 | function QRCodeModel(typeNumber, errorCorrectLevel) { 79 | this.typeNumber = typeNumber; 80 | this.errorCorrectLevel = errorCorrectLevel; 81 | this.modules = null; 82 | this.moduleCount = 0; 83 | this.dataCache = null; 84 | this.dataList = []; 85 | } 86 | 87 | QRCodeModel.prototype={addData:function(data){var newData=new QR8bitByte(data);this.dataList.push(newData);this.dataCache=null;},isDark:function(row,col){if(row<0||this.moduleCount<=row||col<0||this.moduleCount<=col){throw new Error(row+","+col);} 88 | return this.modules[row][col];},getModuleCount:function(){return this.moduleCount;},make:function(){this.makeImpl(false,this.getBestMaskPattern());},makeImpl:function(test,maskPattern){this.moduleCount=this.typeNumber*4+17;this.modules=new Array(this.moduleCount);for(var row=0;row=7){this.setupTypeNumber(test);} 90 | if(this.dataCache==null){this.dataCache=QRCodeModel.createData(this.typeNumber,this.errorCorrectLevel,this.dataList);} 91 | this.mapData(this.dataCache,maskPattern);},setupPositionProbePattern:function(row,col){for(var r=-1;r<=7;r++){if(row+r<=-1||this.moduleCount<=row+r)continue;for(var c=-1;c<=7;c++){if(col+c<=-1||this.moduleCount<=col+c)continue;if((0<=r&&r<=6&&(c==0||c==6))||(0<=c&&c<=6&&(r==0||r==6))||(2<=r&&r<=4&&2<=c&&c<=4)){this.modules[row+r][col+c]=true;}else{this.modules[row+r][col+c]=false;}}}},getBestMaskPattern:function(){var minLostPoint=0;var pattern=0;for(var i=0;i<8;i++){this.makeImpl(true,i);var lostPoint=QRUtil.getLostPoint(this);if(i==0||minLostPoint>lostPoint){minLostPoint=lostPoint;pattern=i;}} 92 | return pattern;},createMovieClip:function(target_mc,instance_name,depth){var qr_mc=target_mc.createEmptyMovieClip(instance_name,depth);var cs=1;this.make();for(var row=0;row>i)&1)==1);this.modules[Math.floor(i/3)][i%3+this.moduleCount-8-3]=mod;} 98 | for(var i=0;i<18;i++){var mod=(!test&&((bits>>i)&1)==1);this.modules[i%3+this.moduleCount-8-3][Math.floor(i/3)]=mod;}},setupTypeInfo:function(test,maskPattern){var data=(this.errorCorrectLevel<<3)|maskPattern;var bits=QRUtil.getBCHTypeInfo(data);for(var i=0;i<15;i++){var mod=(!test&&((bits>>i)&1)==1);if(i<6){this.modules[i][8]=mod;}else if(i<8){this.modules[i+1][8]=mod;}else{this.modules[this.moduleCount-15+i][8]=mod;}} 99 | for(var i=0;i<15;i++){var mod=(!test&&((bits>>i)&1)==1);if(i<8){this.modules[8][this.moduleCount-i-1]=mod;}else if(i<9){this.modules[8][15-i-1+1]=mod;}else{this.modules[8][15-i-1]=mod;}} 100 | this.modules[this.moduleCount-8][8]=(!test);},mapData:function(data,maskPattern){var inc=-1;var row=this.moduleCount-1;var bitIndex=7;var byteIndex=0;for(var col=this.moduleCount-1;col>0;col-=2){if(col==6)col--;while(true){for(var c=0;c<2;c++){if(this.modules[row][col-c]==null){var dark=false;if(byteIndex>>bitIndex)&1)==1);} 101 | var mask=QRUtil.getMask(maskPattern,row,col-c);if(mask){dark=!dark;} 102 | this.modules[row][col-c]=dark;bitIndex--;if(bitIndex==-1){byteIndex++;bitIndex=7;}}} 103 | row+=inc;if(row<0||this.moduleCount<=row){row-=inc;inc=-inc;break;}}}}};QRCodeModel.PAD0=0xEC;QRCodeModel.PAD1=0x11;QRCodeModel.createData=function(typeNumber,errorCorrectLevel,dataList){var rsBlocks=QRRSBlock.getRSBlocks(typeNumber,errorCorrectLevel);var buffer=new QRBitBuffer();for(var i=0;itotalDataCount*8){throw new Error("code length overflow. (" 106 | +buffer.getLengthInBits() 107 | +">" 108 | +totalDataCount*8 109 | +")");} 110 | if(buffer.getLengthInBits()+4<=totalDataCount*8){buffer.put(0,4);} 111 | while(buffer.getLengthInBits()%8!=0){buffer.putBit(false);} 112 | while(true){if(buffer.getLengthInBits()>=totalDataCount*8){break;} 113 | buffer.put(QRCodeModel.PAD0,8);if(buffer.getLengthInBits()>=totalDataCount*8){break;} 114 | buffer.put(QRCodeModel.PAD1,8);} 115 | return QRCodeModel.createBytes(buffer,rsBlocks);};QRCodeModel.createBytes=function(buffer,rsBlocks){var offset=0;var maxDcCount=0;var maxEcCount=0;var dcdata=new Array(rsBlocks.length);var ecdata=new Array(rsBlocks.length);for(var r=0;r=0)?modPoly.get(modIndex):0;}} 117 | var totalCodeCount=0;for(var i=0;i=0){d^=(QRUtil.G15<<(QRUtil.getBCHDigit(d)-QRUtil.getBCHDigit(QRUtil.G15)));} 121 | return((data<<10)|d)^QRUtil.G15_MASK;},getBCHTypeNumber:function(data){var d=data<<12;while(QRUtil.getBCHDigit(d)-QRUtil.getBCHDigit(QRUtil.G18)>=0){d^=(QRUtil.G18<<(QRUtil.getBCHDigit(d)-QRUtil.getBCHDigit(QRUtil.G18)));} 122 | return(data<<12)|d;},getBCHDigit:function(data){var digit=0;while(data!=0){digit++;data>>>=1;} 123 | return digit;},getPatternPosition:function(typeNumber){return QRUtil.PATTERN_POSITION_TABLE[typeNumber-1];},getMask:function(maskPattern,i,j){switch(maskPattern){case QRMaskPattern.PATTERN000:return(i+j)%2==0;case QRMaskPattern.PATTERN001:return i%2==0;case QRMaskPattern.PATTERN010:return j%3==0;case QRMaskPattern.PATTERN011:return(i+j)%3==0;case QRMaskPattern.PATTERN100:return(Math.floor(i/2)+Math.floor(j/3))%2==0;case QRMaskPattern.PATTERN101:return(i*j)%2+(i*j)%3==0;case QRMaskPattern.PATTERN110:return((i*j)%2+(i*j)%3)%2==0;case QRMaskPattern.PATTERN111:return((i*j)%3+(i+j)%2)%2==0;default:throw new Error("bad maskPattern:"+maskPattern);}},getErrorCorrectPolynomial:function(errorCorrectLength){var a=new QRPolynomial([1],0);for(var i=0;i5){lostPoint+=(3+sameCount-5);}}} 129 | for(var row=0;row=256){n-=255;} 136 | return QRMath.EXP_TABLE[n];},EXP_TABLE:new Array(256),LOG_TABLE:new Array(256)};for(var i=0;i<8;i++){QRMath.EXP_TABLE[i]=1<>>(7-index%8))&1)==1;},put:function(num,length){for(var i=0;i>>(length-i-1))&1)==1);}},getLengthInBits:function(){return this.length;},putBit:function(bit){var bufIndex=Math.floor(this.length/8);if(this.buffer.length<=bufIndex){this.buffer.push(0);} 151 | if(bit){this.buffer[bufIndex]|=(0x80>>>(this.length%8));} 152 | this.length++;}};var QRCodeLimitLength=[[17,14,11,7],[32,26,20,14],[53,42,32,24],[78,62,46,34],[106,84,60,44],[134,106,74,58],[154,122,86,64],[192,152,108,84],[230,180,130,98],[271,213,151,119],[321,251,177,137],[367,287,203,155],[425,331,241,177],[458,362,258,194],[520,412,292,220],[586,450,322,250],[644,504,364,280],[718,560,394,310],[792,624,442,338],[858,666,482,382],[929,711,509,403],[1003,779,565,439],[1091,857,611,461],[1171,911,661,511],[1273,997,715,535],[1367,1059,751,593],[1465,1125,805,625],[1528,1190,868,658],[1628,1264,908,698],[1732,1370,982,742],[1840,1452,1030,790],[1952,1538,1112,842],[2068,1628,1168,898],[2188,1722,1228,958],[2303,1809,1283,983],[2431,1911,1351,1051],[2563,1989,1423,1093],[2699,2099,1499,1139],[2809,2213,1579,1219],[2953,2331,1663,1273]]; 153 | 154 | function _isSupportCanvas() { 155 | return typeof CanvasRenderingContext2D != "undefined"; 156 | } 157 | 158 | // android 2.x doesn't support Data-URI spec 159 | function _getAndroid() { 160 | var android = false; 161 | var sAgent = navigator.userAgent; 162 | 163 | if (/android/i.test(sAgent)) { // android 164 | android = true; 165 | var aMat = sAgent.toString().match(/android ([0-9]\.[0-9])/i); 166 | 167 | if (aMat && aMat[1]) { 168 | android = parseFloat(aMat[1]); 169 | } 170 | } 171 | 172 | return android; 173 | } 174 | 175 | var svgDrawer = (function() { 176 | 177 | var Drawing = function (el, htOption) { 178 | this._el = el; 179 | this._htOption = htOption; 180 | }; 181 | 182 | Drawing.prototype.draw = function (oQRCode) { 183 | var _htOption = this._htOption; 184 | var _el = this._el; 185 | var nCount = oQRCode.getModuleCount(); 186 | var nWidth = Math.floor(_htOption.width / nCount); 187 | var nHeight = Math.floor(_htOption.height / nCount); 188 | 189 | this.clear(); 190 | 191 | function makeSVG(tag, attrs) { 192 | var el = document.createElementNS('http://www.w3.org/2000/svg', tag); 193 | for (var k in attrs) 194 | if (attrs.hasOwnProperty(k)) el.setAttribute(k, attrs[k]); 195 | return el; 196 | } 197 | 198 | var svg = makeSVG("svg" , {'viewBox': '0 0 ' + String(nCount) + " " + String(nCount), 'width': '100%', 'height': '100%', 'fill': _htOption.colorLight}); 199 | svg.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink"); 200 | _el.appendChild(svg); 201 | 202 | svg.appendChild(makeSVG("rect", {"fill": _htOption.colorLight, "width": "100%", "height": "100%"})); 203 | svg.appendChild(makeSVG("rect", {"fill": _htOption.colorDark, "width": "1", "height": "1", "id": "template"})); 204 | 205 | for (var row = 0; row < nCount; row++) { 206 | for (var col = 0; col < nCount; col++) { 207 | if (oQRCode.isDark(row, col)) { 208 | var child = makeSVG("use", {"x": String(col), "y": String(row)}); 209 | child.setAttributeNS("http://www.w3.org/1999/xlink", "href", "#template") 210 | svg.appendChild(child); 211 | } 212 | } 213 | } 214 | }; 215 | Drawing.prototype.clear = function () { 216 | while (this._el.hasChildNodes()) 217 | this._el.removeChild(this._el.lastChild); 218 | }; 219 | return Drawing; 220 | })(); 221 | 222 | var useSVG = document.documentElement.tagName.toLowerCase() === "svg"; 223 | 224 | // Drawing in DOM by using Table tag 225 | var Drawing = useSVG ? svgDrawer : !_isSupportCanvas() ? (function () { 226 | var Drawing = function (el, htOption) { 227 | this._el = el; 228 | this._htOption = htOption; 229 | }; 230 | 231 | /** 232 | * Draw the QRCode 233 | * 234 | * @param {QRCode} oQRCode 235 | */ 236 | Drawing.prototype.draw = function (oQRCode) { 237 | var _htOption = this._htOption; 238 | var _el = this._el; 239 | var nCount = oQRCode.getModuleCount(); 240 | var nWidth = Math.floor(_htOption.width / nCount); 241 | var nHeight = Math.floor(_htOption.height / nCount); 242 | var aHTML = ['']; 243 | 244 | for (var row = 0; row < nCount; row++) { 245 | aHTML.push(''); 246 | 247 | for (var col = 0; col < nCount; col++) { 248 | aHTML.push(''); 249 | } 250 | 251 | aHTML.push(''); 252 | } 253 | 254 | aHTML.push('
'); 255 | _el.innerHTML = aHTML.join(''); 256 | 257 | // Fix the margin values as real size. 258 | var elTable = _el.childNodes[0]; 259 | var nLeftMarginTable = (_htOption.width - elTable.offsetWidth) / 2; 260 | var nTopMarginTable = (_htOption.height - elTable.offsetHeight) / 2; 261 | 262 | if (nLeftMarginTable > 0 && nTopMarginTable > 0) { 263 | elTable.style.margin = nTopMarginTable + "px " + nLeftMarginTable + "px"; 264 | } 265 | }; 266 | 267 | /** 268 | * Clear the QRCode 269 | */ 270 | Drawing.prototype.clear = function () { 271 | this._el.innerHTML = ''; 272 | }; 273 | 274 | return Drawing; 275 | })() : (function () { // Drawing in Canvas 276 | function _onMakeImage() { 277 | this._elImage.src = this._elCanvas.toDataURL("image/png"); 278 | this._elImage.style.display = "block"; 279 | this._elCanvas.style.display = "none"; 280 | } 281 | 282 | // Android 2.1 bug workaround 283 | // http://code.google.com/p/android/issues/detail?id=5141 284 | if (this._android && this._android <= 2.1) { 285 | var factor = 1 / window.devicePixelRatio; 286 | var drawImage = CanvasRenderingContext2D.prototype.drawImage; 287 | CanvasRenderingContext2D.prototype.drawImage = function (image, sx, sy, sw, sh, dx, dy, dw, dh) { 288 | if (("nodeName" in image) && /img/i.test(image.nodeName)) { 289 | for (var i = arguments.length - 1; i >= 1; i--) { 290 | arguments[i] = arguments[i] * factor; 291 | } 292 | } else if (typeof dw == "undefined") { 293 | arguments[1] *= factor; 294 | arguments[2] *= factor; 295 | arguments[3] *= factor; 296 | arguments[4] *= factor; 297 | } 298 | 299 | drawImage.apply(this, arguments); 300 | }; 301 | } 302 | 303 | /** 304 | * Check whether the user's browser supports Data URI or not 305 | * 306 | * @private 307 | * @param {Function} fSuccess Occurs if it supports Data URI 308 | * @param {Function} fFail Occurs if it doesn't support Data URI 309 | */ 310 | function _safeSetDataURI(fSuccess, fFail) { 311 | var self = this; 312 | self._fFail = fFail; 313 | self._fSuccess = fSuccess; 314 | 315 | // Check it just once 316 | if (self._bSupportDataURI === null) { 317 | var el = document.createElement("img"); 318 | var fOnError = function() { 319 | self._bSupportDataURI = false; 320 | 321 | if (self._fFail) { 322 | self._fFail.call(self); 323 | } 324 | }; 325 | var fOnSuccess = function() { 326 | self._bSupportDataURI = true; 327 | 328 | if (self._fSuccess) { 329 | self._fSuccess.call(self); 330 | } 331 | }; 332 | 333 | el.onabort = fOnError; 334 | el.onerror = fOnError; 335 | el.onload = fOnSuccess; 336 | el.src = "data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="; // the Image contains 1px data. 337 | return; 338 | } else if (self._bSupportDataURI === true && self._fSuccess) { 339 | self._fSuccess.call(self); 340 | } else if (self._bSupportDataURI === false && self._fFail) { 341 | self._fFail.call(self); 342 | } 343 | }; 344 | 345 | /** 346 | * Drawing QRCode by using canvas 347 | * 348 | * @constructor 349 | * @param {HTMLElement} el 350 | * @param {Object} htOption QRCode Options 351 | */ 352 | var Drawing = function (el, htOption) { 353 | this._bIsPainted = false; 354 | this._android = _getAndroid(); 355 | 356 | this._htOption = htOption; 357 | this._elCanvas = document.createElement("canvas"); 358 | this._elCanvas.width = htOption.width; 359 | this._elCanvas.height = htOption.height; 360 | el.appendChild(this._elCanvas); 361 | this._el = el; 362 | this._oContext = this._elCanvas.getContext("2d"); 363 | this._bIsPainted = false; 364 | this._elImage = document.createElement("img"); 365 | this._elImage.alt = "Scan me!"; 366 | this._elImage.style.display = "none"; 367 | this._el.appendChild(this._elImage); 368 | this._bSupportDataURI = null; 369 | }; 370 | 371 | /** 372 | * Draw the QRCode 373 | * 374 | * @param {QRCode} oQRCode 375 | */ 376 | Drawing.prototype.draw = function (oQRCode) { 377 | var _elImage = this._elImage; 378 | var _oContext = this._oContext; 379 | var _htOption = this._htOption; 380 | 381 | var nCount = oQRCode.getModuleCount(); 382 | var nWidth = _htOption.width / nCount; 383 | var nHeight = _htOption.height / nCount; 384 | var nRoundedWidth = Math.round(nWidth); 385 | var nRoundedHeight = Math.round(nHeight); 386 | 387 | _elImage.style.display = "none"; 388 | this.clear(); 389 | 390 | for (var row = 0; row < nCount; row++) { 391 | for (var col = 0; col < nCount; col++) { 392 | var bIsDark = oQRCode.isDark(row, col); 393 | var nLeft = col * nWidth; 394 | var nTop = row * nHeight; 395 | _oContext.strokeStyle = bIsDark ? _htOption.colorDark : _htOption.colorLight; 396 | _oContext.lineWidth = 1; 397 | _oContext.fillStyle = bIsDark ? _htOption.colorDark : _htOption.colorLight; 398 | _oContext.fillRect(nLeft, nTop, nWidth, nHeight); 399 | 400 | // 안티 앨리어싱 방지 처리 401 | _oContext.strokeRect( 402 | Math.floor(nLeft) + 0.5, 403 | Math.floor(nTop) + 0.5, 404 | nRoundedWidth, 405 | nRoundedHeight 406 | ); 407 | 408 | _oContext.strokeRect( 409 | Math.ceil(nLeft) - 0.5, 410 | Math.ceil(nTop) - 0.5, 411 | nRoundedWidth, 412 | nRoundedHeight 413 | ); 414 | } 415 | } 416 | 417 | this._bIsPainted = true; 418 | }; 419 | 420 | /** 421 | * Make the image from Canvas if the browser supports Data URI. 422 | */ 423 | Drawing.prototype.makeImage = function () { 424 | if (this._bIsPainted) { 425 | _safeSetDataURI.call(this, _onMakeImage); 426 | } 427 | }; 428 | 429 | /** 430 | * Return whether the QRCode is painted or not 431 | * 432 | * @return {Boolean} 433 | */ 434 | Drawing.prototype.isPainted = function () { 435 | return this._bIsPainted; 436 | }; 437 | 438 | /** 439 | * Clear the QRCode 440 | */ 441 | Drawing.prototype.clear = function () { 442 | this._oContext.clearRect(0, 0, this._elCanvas.width, this._elCanvas.height); 443 | this._bIsPainted = false; 444 | }; 445 | 446 | /** 447 | * @private 448 | * @param {Number} nNumber 449 | */ 450 | Drawing.prototype.round = function (nNumber) { 451 | if (!nNumber) { 452 | return nNumber; 453 | } 454 | 455 | return Math.floor(nNumber * 1000) / 1000; 456 | }; 457 | 458 | return Drawing; 459 | })(); 460 | 461 | /** 462 | * Get the type by string length 463 | * 464 | * @private 465 | * @param {String} sText 466 | * @param {Number} nCorrectLevel 467 | * @return {Number} type 468 | */ 469 | function _getTypeNumber(sText, nCorrectLevel) { 470 | var nType = 1; 471 | var length = _getUTF8Length(sText); 472 | 473 | for (var i = 0, len = QRCodeLimitLength.length; i <= len; i++) { 474 | var nLimit = 0; 475 | 476 | switch (nCorrectLevel) { 477 | case QRErrorCorrectLevel.L : 478 | nLimit = QRCodeLimitLength[i][0]; 479 | break; 480 | case QRErrorCorrectLevel.M : 481 | nLimit = QRCodeLimitLength[i][1]; 482 | break; 483 | case QRErrorCorrectLevel.Q : 484 | nLimit = QRCodeLimitLength[i][2]; 485 | break; 486 | case QRErrorCorrectLevel.H : 487 | nLimit = QRCodeLimitLength[i][3]; 488 | break; 489 | } 490 | 491 | if (length <= nLimit) { 492 | break; 493 | } else { 494 | nType++; 495 | } 496 | } 497 | 498 | if (nType > QRCodeLimitLength.length) { 499 | throw new Error("Too long data"); 500 | } 501 | 502 | return nType; 503 | } 504 | 505 | function _getUTF8Length(sText) { 506 | var replacedText = encodeURI(sText).toString().replace(/\%[0-9a-fA-F]{2}/g, 'a'); 507 | return replacedText.length + (replacedText.length != sText ? 3 : 0); 508 | } 509 | 510 | /** 511 | * @class QRCode 512 | * @constructor 513 | * @example 514 | * new QRCode(document.getElementById("test"), "http://jindo.dev.naver.com/collie"); 515 | * 516 | * @example 517 | * var oQRCode = new QRCode("test", { 518 | * text : "http://naver.com", 519 | * width : 128, 520 | * height : 128 521 | * }); 522 | * 523 | * oQRCode.clear(); // Clear the QRCode. 524 | * oQRCode.makeCode("http://map.naver.com"); // Re-create the QRCode. 525 | * 526 | * @param {HTMLElement|String} el target element or 'id' attribute of element. 527 | * @param {Object|String} vOption 528 | * @param {String} vOption.text QRCode link data 529 | * @param {Number} [vOption.width=256] 530 | * @param {Number} [vOption.height=256] 531 | * @param {String} [vOption.colorDark="#000000"] 532 | * @param {String} [vOption.colorLight="#ffffff"] 533 | * @param {QRCode.CorrectLevel} [vOption.correctLevel=QRCode.CorrectLevel.H] [L|M|Q|H] 534 | */ 535 | QRCode = function (el, vOption) { 536 | this._htOption = { 537 | width : 256, 538 | height : 256, 539 | typeNumber : 4, 540 | colorDark : "#000000", 541 | colorLight : "#ffffff", 542 | correctLevel : QRErrorCorrectLevel.H 543 | }; 544 | 545 | if (typeof vOption === 'string') { 546 | vOption = { 547 | text : vOption 548 | }; 549 | } 550 | 551 | // Overwrites options 552 | if (vOption) { 553 | for (var i in vOption) { 554 | this._htOption[i] = vOption[i]; 555 | } 556 | } 557 | 558 | if (typeof el == "string") { 559 | el = document.getElementById(el); 560 | } 561 | 562 | if (this._htOption.useSVG) { 563 | Drawing = svgDrawer; 564 | } 565 | 566 | this._android = _getAndroid(); 567 | this._el = el; 568 | this._oQRCode = null; 569 | this._oDrawing = new Drawing(this._el, this._htOption); 570 | 571 | if (this._htOption.text) { 572 | this.makeCode(this._htOption.text); 573 | } 574 | }; 575 | 576 | /** 577 | * Make the QRCode 578 | * 579 | * @param {String} sText link data 580 | */ 581 | QRCode.prototype.makeCode = function (sText) { 582 | this._oQRCode = new QRCodeModel(_getTypeNumber(sText, this._htOption.correctLevel), this._htOption.correctLevel); 583 | this._oQRCode.addData(sText); 584 | this._oQRCode.make(); 585 | this._el.title = sText; 586 | this._oDrawing.draw(this._oQRCode); 587 | this.makeImage(); 588 | }; 589 | 590 | /** 591 | * Make the Image from Canvas element 592 | * - It occurs automatically 593 | * - Android below 3 doesn't support Data-URI spec. 594 | * 595 | * @private 596 | */ 597 | QRCode.prototype.makeImage = function () { 598 | if (typeof this._oDrawing.makeImage == "function" && (!this._android || this._android >= 3)) { 599 | this._oDrawing.makeImage(); 600 | } 601 | }; 602 | 603 | /** 604 | * Clear the QRCode 605 | */ 606 | QRCode.prototype.clear = function () { 607 | this._oDrawing.clear(); 608 | }; 609 | 610 | /** 611 | * @name QRCode.CorrectLevel 612 | */ 613 | QRCode.CorrectLevel = QRErrorCorrectLevel; 614 | })(); 615 | -------------------------------------------------------------------------------- /localQuery.py: -------------------------------------------------------------------------------- 1 | import geo 2 | from __init__ import * 3 | from externalQuery import search as search_external 4 | 5 | iso3166MapDict = json.load(open('assets/iso3166-1.json', 'r', encoding='utf-8')) 6 | geoDict = json.load(open('assets/geocoding.json', 'r', encoding='utf-8')) 7 | combineQuery = True 8 | spCountryList = ["Russia", "Canada", "China", "United States of America", "Brazil", "Australia", "India", "Argentina", 9 | "Japan", "Vietnam", "Kazakhstan"] 10 | 11 | 12 | def search_cmp(country=None, prov=None): 13 | if country in spCountryList and prov == "": 14 | return 15 | # DEBUG 16 | # _ = search_external(country, prov) 17 | # print(f"OSM: country:{country} prov:{prov} res:{_}") 18 | if prov in geoDict[country]: 19 | logging.debug(f"{prov} in geoDict[{country}]") 20 | res = (geoDict[country][prov][0], geoDict[country][prov][1]), True 21 | elif prov.split(' ')[0] in geoDict[country]: 22 | logging.debug(f"(prov.split(' ')[0] = {prov.split(' ')[0]}) in geoDict[{country}]") 23 | res = (geoDict[country][prov.split(' ')[0]][0], geoDict[country][prov.split(' ')[0]][1]), True 24 | else: 25 | isFind = False 26 | tmp = None 27 | for j in geoDict[country]: 28 | tmp = (geoDict[country][j][0], geoDict[country][j][1]) 29 | if j in prov or prov in j: 30 | logging.debug(f"{prov} in geoDict[{country}][{j}] tmp:{tmp}") 31 | isFind = True 32 | break 33 | logging.debug(f"{prov} NOT FIND in geoDict[{country}] tmp:{tmp}") if isFind else None 34 | res = tmp, isFind 35 | logging.debug(f"country:{country} prov:{prov} res:{res}") 36 | if res[1]: 37 | return res[0] 38 | elif country in spCountryList: 39 | return search_external(country, prov) 40 | else: 41 | return res[0] 42 | 43 | 44 | def search(country: str, prov: str): 45 | """ 46 | 根据国家和省份查询经纬度 by English 47 | :param country: str, 国家 48 | :param prov: str, 省份 49 | :return: tuple(lat:float, lng:float, msg:str) 50 | """ 51 | addr = country + ',' + prov 52 | logging.debug(f"addr:{addr}") 53 | tmp = None 54 | if country in geoDict: 55 | _ = search_cmp(country, prov) 56 | if _: 57 | return _[0], _[1], addr 58 | else: 59 | return 60 | else: 61 | for i in geoDict: 62 | if country in i or i in country: 63 | _ = search_cmp(i, prov) 64 | if _: 65 | return _[0], _[1], addr 66 | else: 67 | return 68 | if combineQuery: 69 | return search_external(country, prov) 70 | else: 71 | for i in geoDict: 72 | for j in geoDict[i]: 73 | if j in prov or prov in j: 74 | tmp = geoDict[i][j][0], geoDict[i][j][1], addr 75 | return tmp 76 | logging.warning(f'{addr} not found') 77 | return tmp 78 | 79 | 80 | def geocoding(geoRawDataList: list) -> list: 81 | """ 82 | 多个地址转经纬度 83 | :param geoRawDataList: list, 地址集:[['Country0','Prov0','extraMsg0'],['Country1','Prov1','extraMsg1'],...] 84 | :return: list, 经纬度:[[lat0:float, lng0:float, msg0:str],[lat1:float, lng1:float, msg1:str],...] 85 | """ 86 | coordinatesList = [] 87 | for i in geoRawDataList: 88 | coordinateList = geo.geocodingSingle(i, localQuery=True) 89 | if coordinateList and len(coordinateList): 90 | coordinatesList.append(coordinateList) 91 | return coordinatesList 92 | -------------------------------------------------------------------------------- /log/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nxtrace/traceMap/f53370ae58171a74a672114a76536c052e324a60/log/.gitkeep -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | # -- coding: utf-8 -- 2 | 3 | from __init__ import * 4 | import html 5 | localQuery = True 6 | 7 | 8 | def draw(locationsRawList: list, output_path: str, file_name: str) -> None: 9 | """ 10 | 绘制traceMap 11 | :param locationsRawList: list, 需要绘制轨迹的经纬度信息,格式为[[lat0, lon0, msg0], [lat1, lon1, msg1], ...] (纬度,经度,城市名,信息) 12 | :param output_path: str, 轨迹图保存路径 13 | :param file_name: str, 轨迹图保存文件名 14 | """ 15 | # 计算中心 16 | content = [] 17 | location_center_lat = (locationsRawList[0][0] + locationsRawList[-1][0]) / 2 18 | if abs(locationsRawList[0][1] - locationsRawList[-1][1]) > 180: 19 | location_center_lng = (locationsRawList[0][1] + locationsRawList[-1][1] + 360) / 2 20 | else: 21 | location_center_lng = (locationsRawList[0][1] + locationsRawList[-1][1]) / 2 22 | content += 'map.centerAndZoom(new BMapGL.Point({}, {}), 4)\n'.format(location_center_lng, location_center_lat) 23 | 24 | isIPv4 = (IPy.IP(locationsRawList[0][5]).version() == 4) 25 | if isIPv4: 26 | locationsRawList[0][5] = str(IPy.IP(locationsRawList[0][5]).make_net('24')) 27 | locationsRawList[-1][5] = str(IPy.IP(locationsRawList[-1][5]).make_net('24')) 28 | else: 29 | locationsRawList[0][5] = str(IPy.IP(locationsRawList[0][5]).make_net('48')) 30 | locationsRawList[-1][5] = str(IPy.IP(locationsRawList[-1][5]).make_net('48')) 31 | 32 | tableDataList = [[i[7], i[5], i[9], i[8], i[4], i[2]] for i in locationsRawList] 33 | textList = [] 34 | 35 | for k, i in enumerate(locationsRawList): 36 | lat = i[0] 37 | lng = i[1] 38 | text = i[5] + ' ' \ 39 | + (('AS' + i[4]) if i[4] != '' else '') + ' ' \ 40 | + 'TTL:' + i[7] + ' ' \ 41 | + i[3] + ' ' \ 42 | + 'RTT:' + i[8] + 'ms' # + i[6] 43 | if k == len(locationsRawList) - 1: 44 | textList.append(html.escape(text)) 45 | text = '
'.join(textList) 46 | lat += random.uniform(-0.01, 0.01) 47 | lng += random.uniform(-0.01, 0.01) 48 | content += 'AddPathPoint(path, {}, {})\n'.format(lat, lng) 49 | content += 'AddPoint(map, "{}", "{}", {}, {})\n'.format(i[2], text, lat, lng) 50 | textList = [] 51 | break 52 | if lat == locationsRawList[k + 1][0] and lng == locationsRawList[k + 1][1]: 53 | textList.append(html.escape(text)) 54 | continue 55 | else: 56 | textList.append(html.escape(text)) 57 | text = '
'.join(textList) 58 | lat += random.uniform(-0.01, 0.01) 59 | lng += random.uniform(-0.01, 0.01) 60 | content += 'AddPathPoint(path, {}, {})\n'.format(lat, lng) 61 | content += 'AddPoint(map, "{}", "{}", {}, {})\n'.format(i[2], text, lat, lng) 62 | textList = [] 63 | 64 | with open('template/template.html', 'r', encoding='utf-8') as f: 65 | template = f.read() 66 | new_content = (template.replace("%_REPLACE_CONTENT0_%", ''.join(content))).replace( 67 | "%_REPLACE_CONTENT1_%", json.dumps(tableDataList, ensure_ascii=False) 68 | ) 69 | with open(os.path.join(output_path, file_name), 'w', encoding='utf-8') as fp: 70 | fp.write(new_content) 71 | 72 | 73 | def process(rawData: dict, filename=str(int(datetime.datetime.now().timestamp())) + '.html') -> str: 74 | """ 75 | 处理原始数据,获取HTML文件路径 76 | :param filename: 导出的文件名,默认时间戳 77 | :param rawData: dict, 原始数据 78 | :return: str, HTML文件路径 79 | """ 80 | # print(rawData) 81 | urlPrefix = "https://assets.nxtrace.org/tracemap/" 82 | coordinatesList = [] 83 | for k in rawData['Hops']: 84 | for j in k: 85 | if j['Success']: 86 | if 'lat' not in j['Geo']: 87 | return "不受支持的版本,请更新至最新版本NextTrace。" 88 | if j['Geo']['lat'] == 0 and j['Geo']['lng'] == 0: 89 | continue 90 | if j['Geo']['prov'] == "" and j['Geo']['country'] in ['中国', '美国', '俄罗斯']: 91 | continue 92 | tmpCity = '' 93 | if j['Geo']['country'] != '': 94 | tmpCity = j['Geo']['country'] 95 | if j['Geo']['prov'] != '': 96 | tmpCity = j['Geo']['prov'] 97 | if j['Geo']['city'] != '': 98 | tmpCity = j['Geo']['city'] 99 | coordinatesList.append( 100 | [ 101 | j['Geo']['lat'], 102 | j['Geo']['lng'], 103 | tmpCity, 104 | j['Geo']['owner'], 105 | j['Geo']['asnumber'] if 'asnumber' in j['Geo'] else '', 106 | j['Address']['IP'] if 'IP' in j['Address'] else '', 107 | j['whois'] if 'whois' in j else '', 108 | f'{j["TTL"]}' if 'TTL' in j else '', 109 | f'{(j["RTT"] / 1_000_000):.2f}' if 'RTT' in j else '', # unit: ms 110 | j['Hostname'] if 'Hostname' in j else '' 111 | ] 112 | ) 113 | break 114 | if (len(coordinatesList) == 0): 115 | return "没有需要绘制的数据。" 116 | draw(coordinatesList, './html', filename) 117 | return urlPrefix + filename 118 | 119 | 120 | if __name__ == '__main__': 121 | json.load(open('test/test.json', 'r')) 122 | print(process(json.load(open('test/test.json', 'r')), filename='demo1.html')) 123 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | requests~=2.32.3 2 | folium~=0.19.2 3 | Flask~=3.1.0 4 | gunicorn~=23.0.0 5 | IPy~=1.1 6 | translate~=3.6.1 7 | packaging~=24.2 8 | -------------------------------------------------------------------------------- /template/template.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 8 | 9 | 10 | 11 | NextTrace traceMap 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 |
TTLIPHostnameRTTASNGeography
26 |
Tips:3D视角和路由表格可通过右键菜单切换显示.
27 |
28 |
29 |
30 |
31 |
32 |
33 | 34 | 35 | 244 | -------------------------------------------------------------------------------- /traceMap.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=Gunicorn instance to serve traceMap 3 | After=network.target 4 | 5 | [Service] 6 | User=root 7 | Group=root 8 | StandardOutput=append:/var/log/traceMap_access.log 9 | StandardError=append:/var/log/traceMap_error.log 10 | WorkingDirectory=/var/www/traceMap 11 | Environment="PATH=/var/www/traceMap" 12 | ExecStart=/usr/local/bin/gunicorn --workers 3 -b 0.0.0.0:18888 webServer:APP 13 | ExecReload=/bin/kill -s HUP $MAINPID 14 | ExecStop=/bin/kill -s TERM $MAINPID 15 | Restart=on-failure 16 | KillMode=process 17 | 18 | [Install] 19 | WantedBy=multi-user.target 20 | -------------------------------------------------------------------------------- /translate.py: -------------------------------------------------------------------------------- 1 | from __init__ import * 2 | 3 | spToEngDict = json.load(open('assets/assets.json', 'r', encoding='utf-8')) 4 | GOOGLE_TRANSLATE_URL = 'https://translate.google.com/m?q=%s&tl=%s&sl=%s' 5 | session = requests.session() 6 | session.mount('https://', HTTPAdapter(max_retries=2)) 7 | 8 | 9 | def translate(text: str, to_language, text_language) -> str: 10 | """ 11 | Google翻译 12 | exmaple: 13 | type -> "en" "zh-CN" "auto" 14 | """ 15 | if text in spToEngDict: 16 | return spToEngDict[text] 17 | text = parse.quote(text) 18 | url = GOOGLE_TRANSLATE_URL % (text, to_language, text_language) 19 | response = session.get(url, timeout=3) 20 | data = response.text 21 | expr = r'(?s)class="(?:t0|result-container)">(.*?)<' 22 | result = re.findall(expr, data) 23 | if len(result) == 0: 24 | return "" 25 | return html.unescape(result[0]) 26 | 27 | 28 | def singleTranslate(text: str) -> str: 29 | return translate(text, "en", "auto") 30 | 31 | 32 | def dictTranslate(geoDataList: list) -> list: 33 | dataListCnt = len(geoDataList) 34 | forTranslateQueue = [] 35 | for i in range(dataListCnt): 36 | forTranslateQueue.append(geoDataList[i][0]) 37 | forTranslateQueue.append(geoDataList[i][1]) 38 | pool = ThreadPool(4) 39 | sum_result = pool.map(singleTranslate, forTranslateQueue) 40 | pool.close() 41 | pool.join() 42 | logging.info(f"translate_sum_result:{sum_result}") 43 | for i in range(dataListCnt): 44 | geoDataList[i][0] = sum_result[i * 2] 45 | geoDataList[i][1] = sum_result[i * 2 + 1] 46 | return geoDataList 47 | 48 | 49 | if __name__ == '__main__': 50 | # print(translate("你吃饭了么?", "en", "zh-CN")) # 汉语转英语 51 | # print(translate("你吃饭了么?", "ja", "zh-CN")) # 汉语转日语 52 | print(translate("中国,天津市", "en", "zh-CN")) 53 | print(translate("中国,天津市", "en", "zh-CN")) 54 | print(translate("China, Tianjin", "en", "auto")) 55 | print(translate("香港", "en", "auto")) 56 | -------------------------------------------------------------------------------- /webServer.py: -------------------------------------------------------------------------------- 1 | import flask 2 | from flask import request 3 | 4 | from __init__ import * 5 | from main import process 6 | 7 | 8 | def is_version_acceptable(user_agent): 9 | """ 10 | 判断客户端版本是否符合要求 11 | :param user_agent: 12 | :return: 0 不符合要求 1 最新版本 2 符合要求但可升级的版本 13 | """ 14 | # 正则表达式用于匹配版本号 15 | match = re.search(r"NextTrace v([\d.]+)/", user_agent) 16 | if match: 17 | user_version = match.group(1) 18 | try: 19 | # 使用 packaging.version 比较版本号 20 | if version.parse(user_version) >= version.parse(accept_version): 21 | if version.parse(user_version) >= version.parse(latest_version): 22 | return 1 23 | else: 24 | return 2 25 | else: 26 | return 0 27 | except ValueError: 28 | # 如果无法解析版本号,视为不符合要求 29 | return 0 30 | else: 31 | match = re.search(r"NextTrace ([\d.]+)/", user_agent) # 给 HomeBrew 版本的不规范版本擦屁股 32 | if match: 33 | user_version = match.group(1) 34 | try: 35 | # 使用 packaging.version 比较版本号 36 | if version.parse(user_version) >= version.parse(accept_version): 37 | if version.parse(user_version) >= version.parse(latest_version): 38 | return 1 39 | else: 40 | return 2 41 | else: 42 | return 0 43 | except ValueError: 44 | # 如果无法解析版本号,视为不符合要求 45 | return 0 46 | else: 47 | # 如果无法解析版本号,视为不符合要求 48 | return 0 49 | 50 | 51 | def html(filename): 52 | return flask.send_from_directory('html', filename) 53 | 54 | 55 | def favicon(): 56 | return flask.send_file('favicon.ico', mimetype='image/vnd.microsoft.icon') 57 | 58 | 59 | def api(): 60 | data = json.loads(request.data.decode("utf-8")) 61 | 62 | uName = str(uuid.uuid5(uuid.NAMESPACE_DNS, request.get_data().decode())) 63 | json_str = json.dumps(data, ensure_ascii=False) 64 | data = json.loads(json_str) 65 | with open('log/' + uName + '.json', 'w', encoding='utf-8') as f: 66 | f.write(json_str) 67 | logging.info("Saved log to log/" + uName + ".json") 68 | try: 69 | filename = process(data, filename=uName + '.html') 70 | logging.info("Saved html to " + filename) 71 | except Exception as e: 72 | logging.error("uuid:", uName) 73 | logging.error(e) 74 | print(traceback.format_exc()) 75 | return "", 500 76 | # 根据UA判断版本 77 | version_result = is_version_acceptable(request.headers.get('User-Agent')) 78 | if version_result == 1: 79 | return filename, 200 80 | elif version_result == 2: 81 | return filename, 200 82 | else: 83 | return filename + '\n' + '您正在使用的版本,将在一个月内停止支持,请及时升级您的客户端', 406 84 | 85 | 86 | class WebServer: 87 | def __init__(self): 88 | self.app = flask.Flask(__name__) 89 | if 'GUNICORN_CMD_ARGS' in os.environ: 90 | gunicorn_logger = logging.getLogger('gunicorn.error') 91 | self.app.logger.handlers = gunicorn_logger.handlers 92 | self.app.logger.setLevel(gunicorn_logger.level) 93 | else: 94 | logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s') 95 | 96 | self.app.config['JSON_AS_ASCII'] = False 97 | 98 | self.urlPrefix = "http://localhost:8888/html/" 99 | 100 | self.app.route('/api', methods=['post'])(api) 101 | self.app.route('/html/', methods=['get'])(html) 102 | self.app.route('/favicon.ico', methods=['get'])(favicon) 103 | 104 | def run(self, host="0.0.0.0", port=18888, debug=True): 105 | self.app.run(host=host, port=port, debug=debug) 106 | 107 | 108 | server = WebServer() 109 | APP = server.app 110 | if __name__ == '__main__': 111 | server.run() 112 | --------------------------------------------------------------------------------