├── .bumpversion.cfg ├── .coveragerc ├── .gitignore ├── .travis.yml ├── LICENSE ├── MANIFEST.in ├── README.rst ├── docs ├── Makefile ├── conf.py ├── contributing.rst ├── images │ ├── devices_count.png │ ├── requests_timeline.png │ ├── tracker_detail.png │ └── world_map.png ├── index.rst ├── installation.rst ├── make.bat ├── settings.rst └── usage.rst ├── pylint.rc ├── pytest.ini ├── setup.py ├── tests ├── __init__.py ├── factories.py ├── models.py ├── settings.py ├── settings_postgres.py ├── test_admin.py ├── test_management_commands.py ├── test_models.py ├── urls.py └── utils.py ├── tox.ini └── tracking_analyzer ├── __init__.py ├── admin.py ├── apps.py ├── conf.py ├── management ├── __init__.py └── commands │ ├── __init__.py │ └── install_geoip_dataset.py ├── manager.py ├── migrations ├── 0001_initial.py ├── 0002_auto_20160719_2212.py └── __init__.py ├── models.py ├── static └── admin │ ├── css │ ├── d3-tip.css │ └── main.css │ └── js │ ├── devices_stats.js │ ├── requests_graph.js │ ├── vendor │ ├── d3-tip │ │ ├── LICENSE │ │ └── d3-tip.min.js │ ├── d3 │ │ ├── LICENSE │ │ └── d3.min.js │ ├── datamaps │ │ ├── LICENSE │ │ └── datamaps.world.min.js │ └── topojson │ │ ├── LICENSE │ │ └── topojson.min.js │ └── world_map.js ├── templates └── admin │ └── tracking_analyzer │ └── tracker │ └── change_list.html └── utils.py /.bumpversion.cfg: -------------------------------------------------------------------------------- 1 | [bumpversion] 2 | current_version = 1.1.1 3 | commit = True 4 | tag = True 5 | parse = (?P\d+)\.(?P\d+)\.(?P\d+) 6 | serialize = 7 | {major}.{minor}.{patch} 8 | 9 | [bumpversion:file:setup.py] 10 | 11 | [bumpversion:file:docs/conf.py] 12 | -------------------------------------------------------------------------------- /.coveragerc: -------------------------------------------------------------------------------- 1 | [run] 2 | omit = 3 | tests/* 4 | docs/* 5 | tracking_analyzer/migrations/* 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Development. 2 | .idea/ 3 | *.pyc 4 | .python-version 5 | .*.swp 6 | 7 | # Testing and code coverage. 8 | .coverage 9 | coverage.xml 10 | junit.xml 11 | .tox 12 | 13 | # Distribution / packaging 14 | build/ 15 | .cache 16 | develop-eggs/ 17 | dist/ 18 | downloads/ 19 | *.egg 20 | *.egg-info/ 21 | .eggs/ 22 | eggs/ 23 | env/ 24 | .installed.cfg 25 | lib/ 26 | lib64/ 27 | parts/ 28 | __pycache__ 29 | .Python 30 | sdist/ 31 | var/ 32 | 33 | # PyInstaller 34 | # Usually these files are written by a python script from a template 35 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 36 | *.manifest 37 | *.spec 38 | 39 | # Installer logs 40 | pip-log.txt 41 | pip-delete-this-directory.txt 42 | 43 | # Documentation builds 44 | docs/_build 45 | docs/_static 46 | docs/_templates 47 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 3 | - "3.6" 4 | - "3.7" 5 | - "3.8" 6 | 7 | dist: bionic 8 | 9 | addons: 10 | postgresql: "10.10" 11 | apt: 12 | packages: 13 | - postgresql-10 14 | - postgresql-client-10 15 | 16 | install: 17 | - pip install codecov tox 18 | 19 | services: 20 | - postgresql 21 | 22 | before_script: 23 | - sudo /etc/init.d/postgresql stop 24 | - sudo /etc/init.d/postgresql start 10.10 25 | - psql -c 'CREATE DATABASE tracking_analyzer_test;' -U postgres 26 | 27 | script: 28 | - tox -- 29 | 30 | after_success: 31 | - codecov 32 | 33 | env: 34 | - TOXENV=django22 35 | - TOXENV=django30 36 | -------------------------------------------------------------------------------- /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 | 676 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include LICENSE 2 | include README.rst 3 | recursive-include tracking_analyzer/static * 4 | recursive-include tracking_analyzer/templates * 5 | global-exclude __pycache__ 6 | global-exclude *.py[co] 7 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | ======================== 2 | Django Tracking Analyzer 3 | ======================== 4 | 5 | User actions tracking and analytics for Django sites 6 | 7 | .. image:: https://travis-ci.org/jose-lpa/django-tracking-analyzer.svg?branch=master 8 | :target: https://travis-ci.org/jose-lpa/django-tracking-analyzer 9 | 10 | .. image:: https://codecov.io/gh/jose-lpa/django-tracking-analyzer/branch/master/graph/badge.svg 11 | :target: https://codecov.io/gh/jose-lpa/django-tracking-analyzer 12 | 13 | .. image:: https://badge.fury.io/py/django-tracking-analyzer.svg 14 | :target: https://badge.fury.io/py/django-tracking-analyzer 15 | 16 | .. image:: https://readthedocs.org/projects/django-tracking-analyzer/badge/?version=latest 17 | :target: http://django-tracking-analyzer.readthedocs.io/en/latest/?badge=latest 18 | 19 | 20 | Requirements 21 | ============ 22 | 23 | - Django 2.1 or later. 24 | - `Django Countries`_ 5.5 or later. 25 | - `Django IPWare`_ 2.1.0 or later. 26 | - `Django User Agents`_ 0.4.0 or later. 27 | - `GeoIP2`_ 2.9.0 or later. 28 | - `MaxMind GeoLite2 country datasets`_. 29 | 30 | 31 | Installation 32 | ============ 33 | 34 | 1. Install Django Tracking Analyzer from PyPI by using ``pip``:: 35 | 36 | pip install django-tracking-analyzer 37 | 38 | 39 | 2. Add ``'django_user_agents'`` and ``'tracking_analyzer'`` entries to Django ``INSTALLED_APPS`` setting. 40 | 3. Run the migrations to load the ``Tracker`` model in your database:: 41 | 42 | python manage.py migrate tracking_analyzer 43 | 44 | 45 | 4. Install the MaxMind® GeoIP2 datasets. You can do this in two ways: 46 | 47 | 4.1. By running the provided management command for this:: 48 | 49 | python manage.py install_geoip_dataset 50 | 51 | 52 | 4.2. Or manually, by following the instructions in `GeoIP2 Django documentation`_. 53 | 54 | After following those steps, you should be ready to go. 55 | 56 | 57 | Explanation - Quickstart 58 | ======================== 59 | 60 | Django Tracking Analyzer is a Django pluggable application which helps you 61 | providing usage statistics and visitors data for your Django sites. 62 | 63 | DTA does this by recording requests data in those places you want to by saving 64 | ``Tracker``'s. A ``Tracker`` is a Django database model which holds all the 65 | data related to a request, including geolocation via IP address and device or 66 | browser specifications. 67 | 68 | When some data is collected, the Django admin interface for ``Tracker`` model 69 | implements some interactive widgets to help you visualize better the data. 70 | 71 | 72 | Now let's see how can you start collecting users data. Imagine the most basic 73 | example: you have a web blog and you want to check the visits to your posts, 74 | having a resume of who accessed the posts, when and from where. In such a Django 75 | site, you might have a view ``PostDetailView``, where a blog post will be served 76 | by passing its slug in the URL. Something like this: 77 | 78 | .. code-block:: python 79 | 80 | class PostDetailView(DetailView): 81 | model = Post 82 | 83 | 84 | Okay, so you can track the users who access blog posts by their instances with 85 | DTA, just like this: 86 | 87 | .. code-block:: python 88 | 89 | class PostDetailView(DetailView): 90 | model = Post 91 | 92 | def get_object(self, queryset=None): 93 | # Retrieve the blog post just using `get_object` functionality. 94 | obj = super(PostDetailView, self).get_object(queryset) 95 | 96 | # Track the users access to the blog by post! 97 | Tracker.objects.create_from_request(self.request, obj) 98 | 99 | return obj 100 | 101 | 102 | And you are now on your way to collect users data! Now give it a time (or better 103 | access the resource yourself several times) and go check your Django admin in 104 | the "Django Tracking Analyzer" - "Trackers" section. Enjoy! 105 | 106 | 107 | Documentation 108 | ============= 109 | 110 | For extensive documentation and usage explanations, you can check `Read the Docs`_. 111 | 112 | 113 | Acknowledgements 114 | ================ 115 | 116 | Django Tracking Analyzer makes use of this technologies and apps, without which it wouldn't be possible: 117 | 118 | - `Django Countries`_, by Chris Beaven. 119 | - `Django IPWare`_, by Val Neekman. 120 | - `Django User Agents`_, by Selwin Ong. 121 | - Datamaps_, by Marc DiMarco. 122 | - TopoJSON_, by Mike Bostock. 123 | - `D3 bar chart w/tooltips`_, original code by Justin Palmer. 124 | - `D3 area chart`_, by Mike Bostock. 125 | - Of course, the `D3.js library`_. 126 | - And MaxMind_, the company behind all the geographical datasets that made them publicly available. 127 | 128 | 129 | .. _Django Countries: https://pypi.python.org/pypi/django-countries 130 | .. _Django IPWare: https://pypi.python.org/pypi/django-ipware 131 | .. _Django User Agents: https://pypi.python.org/pypi/django-user_agents 132 | .. _GeoIP2: https://pypi.python.org/pypi/geoip2 133 | .. _MaxMind GeoLite2 country datasets: http://dev.maxmind.com/geoip/geoip2/geolite2/ 134 | .. _GeoIP2 Django documentation: https://docs.djangoproject.com/en/1.10/ref/contrib/gis/geoip2/ 135 | .. _Read the Docs: http://django-tracking-analyzer.readthedocs.io/en/latest/ 136 | .. _Datamaps: https://github.com/markmarkoh/datamaps 137 | .. _TopoJSON: https://github.com/mbostock/topojson 138 | .. _D3 bar chart w/tooltips: http://bl.ocks.org/Caged/6476579 139 | .. _D3 area chart: http://bl.ocks.org/mbostock/3883195 140 | .. _D3.js library: https://d3js.org/ 141 | .. _MaxMind: https://www.maxmind.com/ 142 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # Internal variables. 11 | PAPEROPT_a4 = -D latex_paper_size=a4 12 | PAPEROPT_letter = -D latex_paper_size=letter 13 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 14 | # the i18n builder cannot share the environment and doctrees with the others 15 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 16 | 17 | .PHONY: help 18 | help: 19 | @echo "Please use \`make ' where is one of" 20 | @echo " html to make standalone HTML files" 21 | @echo " dirhtml to make HTML files named index.html in directories" 22 | @echo " singlehtml to make a single large HTML file" 23 | @echo " pickle to make pickle files" 24 | @echo " json to make JSON files" 25 | @echo " htmlhelp to make HTML files and a HTML help project" 26 | @echo " qthelp to make HTML files and a qthelp project" 27 | @echo " applehelp to make an Apple Help Book" 28 | @echo " devhelp to make HTML files and a Devhelp project" 29 | @echo " epub to make an epub" 30 | @echo " epub3 to make an epub3" 31 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 32 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 33 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 34 | @echo " text to make text files" 35 | @echo " man to make manual pages" 36 | @echo " texinfo to make Texinfo files" 37 | @echo " info to make Texinfo files and run them through makeinfo" 38 | @echo " gettext to make PO message catalogs" 39 | @echo " changes to make an overview of all changed/added/deprecated items" 40 | @echo " xml to make Docutils-native XML files" 41 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 42 | @echo " linkcheck to check all external links for integrity" 43 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 44 | @echo " coverage to run coverage check of the documentation (if enabled)" 45 | @echo " dummy to check syntax errors of document sources" 46 | 47 | .PHONY: clean 48 | clean: 49 | rm -rf $(BUILDDIR)/* 50 | 51 | .PHONY: html 52 | html: 53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 54 | @echo 55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 56 | 57 | .PHONY: dirhtml 58 | dirhtml: 59 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 60 | @echo 61 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 62 | 63 | .PHONY: singlehtml 64 | singlehtml: 65 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 66 | @echo 67 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 68 | 69 | .PHONY: pickle 70 | pickle: 71 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 72 | @echo 73 | @echo "Build finished; now you can process the pickle files." 74 | 75 | .PHONY: json 76 | json: 77 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 78 | @echo 79 | @echo "Build finished; now you can process the JSON files." 80 | 81 | .PHONY: htmlhelp 82 | htmlhelp: 83 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 84 | @echo 85 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 86 | ".hhp project file in $(BUILDDIR)/htmlhelp." 87 | 88 | .PHONY: qthelp 89 | qthelp: 90 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 91 | @echo 92 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 93 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 94 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/DjangoTrackingAnalyzer.qhcp" 95 | @echo "To view the help file:" 96 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/DjangoTrackingAnalyzer.qhc" 97 | 98 | .PHONY: applehelp 99 | applehelp: 100 | $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp 101 | @echo 102 | @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." 103 | @echo "N.B. You won't be able to view it unless you put it in" \ 104 | "~/Library/Documentation/Help or install it in your application" \ 105 | "bundle." 106 | 107 | .PHONY: devhelp 108 | devhelp: 109 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 110 | @echo 111 | @echo "Build finished." 112 | @echo "To view the help file:" 113 | @echo "# mkdir -p $$HOME/.local/share/devhelp/DjangoTrackingAnalyzer" 114 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/DjangoTrackingAnalyzer" 115 | @echo "# devhelp" 116 | 117 | .PHONY: epub 118 | epub: 119 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 120 | @echo 121 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 122 | 123 | .PHONY: epub3 124 | epub3: 125 | $(SPHINXBUILD) -b epub3 $(ALLSPHINXOPTS) $(BUILDDIR)/epub3 126 | @echo 127 | @echo "Build finished. The epub3 file is in $(BUILDDIR)/epub3." 128 | 129 | .PHONY: latex 130 | latex: 131 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 132 | @echo 133 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 134 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 135 | "(use \`make latexpdf' here to do that automatically)." 136 | 137 | .PHONY: latexpdf 138 | latexpdf: 139 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 140 | @echo "Running LaTeX files through pdflatex..." 141 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 142 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 143 | 144 | .PHONY: latexpdfja 145 | latexpdfja: 146 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 147 | @echo "Running LaTeX files through platex and dvipdfmx..." 148 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 149 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 150 | 151 | .PHONY: text 152 | text: 153 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 154 | @echo 155 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 156 | 157 | .PHONY: man 158 | man: 159 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 160 | @echo 161 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 162 | 163 | .PHONY: texinfo 164 | texinfo: 165 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 166 | @echo 167 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 168 | @echo "Run \`make' in that directory to run these through makeinfo" \ 169 | "(use \`make info' here to do that automatically)." 170 | 171 | .PHONY: info 172 | info: 173 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 174 | @echo "Running Texinfo files through makeinfo..." 175 | make -C $(BUILDDIR)/texinfo info 176 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 177 | 178 | .PHONY: gettext 179 | gettext: 180 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 181 | @echo 182 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 183 | 184 | .PHONY: changes 185 | changes: 186 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 187 | @echo 188 | @echo "The overview file is in $(BUILDDIR)/changes." 189 | 190 | .PHONY: linkcheck 191 | linkcheck: 192 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 193 | @echo 194 | @echo "Link check complete; look for any errors in the above output " \ 195 | "or in $(BUILDDIR)/linkcheck/output.txt." 196 | 197 | .PHONY: doctest 198 | doctest: 199 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 200 | @echo "Testing of doctests in the sources finished, look at the " \ 201 | "results in $(BUILDDIR)/doctest/output.txt." 202 | 203 | .PHONY: coverage 204 | coverage: 205 | $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage 206 | @echo "Testing of coverage in the sources finished, look at the " \ 207 | "results in $(BUILDDIR)/coverage/python.txt." 208 | 209 | .PHONY: xml 210 | xml: 211 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 212 | @echo 213 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 214 | 215 | .PHONY: pseudoxml 216 | pseudoxml: 217 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 218 | @echo 219 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 220 | 221 | .PHONY: dummy 222 | dummy: 223 | $(SPHINXBUILD) -b dummy $(ALLSPHINXOPTS) $(BUILDDIR)/dummy 224 | @echo 225 | @echo "Build finished. Dummy builder generates no files." 226 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # 4 | # Django Tracking Analyzer documentation build configuration file, created by 5 | # sphinx-quickstart on Sat Jul 9 23:22:40 2016. 6 | # 7 | # This file is execfile()d with the current directory set to its 8 | # containing dir. 9 | # 10 | # Note that not all possible configuration values are present in this 11 | # autogenerated file. 12 | # 13 | # All configuration values have a default; values that are commented out 14 | # serve to show the default. 15 | 16 | # If extensions (or modules to document with autodoc) are in another directory, 17 | # add these directories to sys.path here. If the directory is relative to the 18 | # documentation root, use os.path.abspath to make it absolute, like shown here. 19 | # 20 | # import os 21 | # import sys 22 | # sys.path.insert(0, os.path.abspath('.')) 23 | 24 | # -- General configuration ------------------------------------------------ 25 | 26 | # If your documentation needs a minimal Sphinx version, state it here. 27 | # 28 | # needs_sphinx = '1.0' 29 | 30 | # Add any Sphinx extension module names here, as strings. They can be 31 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 32 | # ones. 33 | extensions = [] 34 | 35 | # Add any paths that contain templates here, relative to this directory. 36 | templates_path = ['_templates'] 37 | 38 | # The suffix(es) of source filenames. 39 | # You can specify multiple suffix as a list of string: 40 | # 41 | # source_suffix = ['.rst', '.md'] 42 | source_suffix = '.rst' 43 | 44 | # The encoding of source files. 45 | # 46 | # source_encoding = 'utf-8-sig' 47 | 48 | # The master toctree document. 49 | master_doc = 'index' 50 | 51 | # General information about the project. 52 | project = 'Django Tracking Analyzer' 53 | copyright = '2019, José Luis Patiño Andrés' 54 | author = 'José Luis Patiño Andrés' 55 | 56 | # The version info for the project you're documenting, acts as replacement for 57 | # |version| and |release|, also used in various other places throughout the 58 | # built documents. 59 | # 60 | # The short X.Y version. 61 | version = '1.1.1' 62 | # The full version, including alpha/beta/rc tags. 63 | release = '1.1.1' 64 | 65 | # The language for content autogenerated by Sphinx. Refer to documentation 66 | # for a list of supported languages. 67 | # 68 | # This is also used if you do content translation via gettext catalogs. 69 | # Usually you set "language" from the command line for these cases. 70 | language = None 71 | 72 | # There are two options for replacing |today|: either, you set today to some 73 | # non-false value, then it is used: 74 | # 75 | # today = '' 76 | # 77 | # Else, today_fmt is used as the format for a strftime call. 78 | # 79 | # today_fmt = '%B %d, %Y' 80 | 81 | # List of patterns, relative to source directory, that match files and 82 | # directories to ignore when looking for source files. 83 | # This patterns also effect to html_static_path and html_extra_path 84 | exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] 85 | 86 | # The reST default role (used for this markup: `text`) to use for all 87 | # documents. 88 | # 89 | # default_role = None 90 | 91 | # If true, '()' will be appended to :func: etc. cross-reference text. 92 | # 93 | # add_function_parentheses = True 94 | 95 | # If true, the current module name will be prepended to all description 96 | # unit titles (such as .. function::). 97 | # 98 | # add_module_names = True 99 | 100 | # If true, sectionauthor and moduleauthor directives will be shown in the 101 | # output. They are ignored by default. 102 | # 103 | # show_authors = False 104 | 105 | # The name of the Pygments (syntax highlighting) style to use. 106 | pygments_style = 'sphinx' 107 | 108 | # A list of ignored prefixes for module index sorting. 109 | # modindex_common_prefix = [] 110 | 111 | # If true, keep warnings as "system message" paragraphs in the built documents. 112 | # keep_warnings = False 113 | 114 | # If true, `todo` and `todoList` produce output, else they produce nothing. 115 | todo_include_todos = False 116 | 117 | 118 | # -- Options for HTML output ---------------------------------------------- 119 | 120 | # The theme to use for HTML and HTML Help pages. See the documentation for 121 | # a list of builtin themes. 122 | # 123 | html_theme = 'alabaster' 124 | 125 | # Theme options are theme-specific and customize the look and feel of a theme 126 | # further. For a list of options available for each theme, see the 127 | # documentation. 128 | # 129 | # html_theme_options = {} 130 | 131 | # Add any paths that contain custom themes here, relative to this directory. 132 | # html_theme_path = [] 133 | 134 | # The name for this set of Sphinx documents. 135 | # " v documentation" by default. 136 | # 137 | # html_title = 'Django Tracking Analyzer v1.1.1' 138 | 139 | # A shorter title for the navigation bar. Default is the same as html_title. 140 | # 141 | # html_short_title = None 142 | 143 | # The name of an image file (relative to this directory) to place at the top 144 | # of the sidebar. 145 | # 146 | # html_logo = None 147 | 148 | # The name of an image file (relative to this directory) to use as a favicon of 149 | # the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 150 | # pixels large. 151 | # 152 | # html_favicon = None 153 | 154 | # Add any paths that contain custom static files (such as style sheets) here, 155 | # relative to this directory. They are copied after the builtin static files, 156 | # so a file named "default.css" will overwrite the builtin "default.css". 157 | html_static_path = ['_static'] 158 | 159 | # Add any extra paths that contain custom files (such as robots.txt or 160 | # .htaccess) here, relative to this directory. These files are copied 161 | # directly to the root of the documentation. 162 | # 163 | # html_extra_path = [] 164 | 165 | # If not None, a 'Last updated on:' timestamp is inserted at every page 166 | # bottom, using the given strftime format. 167 | # The empty string is equivalent to '%b %d, %Y'. 168 | # 169 | # html_last_updated_fmt = None 170 | 171 | # If true, SmartyPants will be used to convert quotes and dashes to 172 | # typographically correct entities. 173 | # 174 | # html_use_smartypants = True 175 | 176 | # Custom sidebar templates, maps document names to template names. 177 | # 178 | # html_sidebars = {} 179 | 180 | # Additional templates that should be rendered to pages, maps page names to 181 | # template names. 182 | # 183 | # html_additional_pages = {} 184 | 185 | # If false, no module index is generated. 186 | # 187 | # html_domain_indices = True 188 | 189 | # If false, no index is generated. 190 | # 191 | # html_use_index = True 192 | 193 | # If true, the index is split into individual pages for each letter. 194 | # 195 | # html_split_index = False 196 | 197 | # If true, links to the reST sources are added to the pages. 198 | # 199 | # html_show_sourcelink = True 200 | 201 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 202 | # 203 | # html_show_sphinx = True 204 | 205 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 206 | # 207 | # html_show_copyright = True 208 | 209 | # If true, an OpenSearch description file will be output, and all pages will 210 | # contain a tag referring to it. The value of this option must be the 211 | # base URL from which the finished HTML is served. 212 | # 213 | # html_use_opensearch = '' 214 | 215 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 216 | # html_file_suffix = None 217 | 218 | # Language to be used for generating the HTML full-text search index. 219 | # Sphinx supports the following languages: 220 | # 'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja' 221 | # 'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr', 'zh' 222 | # 223 | # html_search_language = 'en' 224 | 225 | # A dictionary with options for the search language support, empty by default. 226 | # 'ja' uses this config value. 227 | # 'zh' user can custom change `jieba` dictionary path. 228 | # 229 | # html_search_options = {'type': 'default'} 230 | 231 | # The name of a javascript file (relative to the configuration directory) that 232 | # implements a search results scorer. If empty, the default will be used. 233 | # 234 | # html_search_scorer = 'scorer.js' 235 | 236 | # Output file base name for HTML help builder. 237 | htmlhelp_basename = 'DjangoTrackingAnalyzerdoc' 238 | 239 | # -- Options for LaTeX output --------------------------------------------- 240 | 241 | latex_elements = { 242 | # The paper size ('letterpaper' or 'a4paper'). 243 | # 244 | # 'papersize': 'letterpaper', 245 | 246 | # The font size ('10pt', '11pt' or '12pt'). 247 | # 248 | # 'pointsize': '10pt', 249 | 250 | # Additional stuff for the LaTeX preamble. 251 | # 252 | # 'preamble': '', 253 | 254 | # Latex figure (float) alignment 255 | # 256 | # 'figure_align': 'htbp', 257 | } 258 | 259 | # Grouping the document tree into LaTeX files. List of tuples 260 | # (source start file, target name, title, 261 | # author, documentclass [howto, manual, or own class]). 262 | latex_documents = [ 263 | (master_doc, 'DjangoTrackingAnalyzer.tex', 'Django Tracking Analyzer Documentation', 264 | 'José Luis Patiño Andrés', 'manual'), 265 | ] 266 | 267 | # The name of an image file (relative to this directory) to place at the top of 268 | # the title page. 269 | # 270 | # latex_logo = None 271 | 272 | # For "manual" documents, if this is true, then toplevel headings are parts, 273 | # not chapters. 274 | # 275 | # latex_use_parts = False 276 | 277 | # If true, show page references after internal links. 278 | # 279 | # latex_show_pagerefs = False 280 | 281 | # If true, show URL addresses after external links. 282 | # 283 | # latex_show_urls = False 284 | 285 | # Documents to append as an appendix to all manuals. 286 | # 287 | # latex_appendices = [] 288 | 289 | # If false, no module index is generated. 290 | # 291 | # latex_domain_indices = True 292 | 293 | 294 | # -- Options for manual page output --------------------------------------- 295 | 296 | # One entry per manual page. List of tuples 297 | # (source start file, name, description, authors, manual section). 298 | man_pages = [ 299 | (master_doc, 'djangotrackinganalyzer', 'Django Tracking Analyzer Documentation', 300 | [author], 1) 301 | ] 302 | 303 | # If true, show URL addresses after external links. 304 | # 305 | # man_show_urls = False 306 | 307 | 308 | # -- Options for Texinfo output ------------------------------------------- 309 | 310 | # Grouping the document tree into Texinfo files. List of tuples 311 | # (source start file, target name, title, author, 312 | # dir menu entry, description, category) 313 | texinfo_documents = [ 314 | (master_doc, 'DjangoTrackingAnalyzer', 'Django Tracking Analyzer Documentation', 315 | author, 'DjangoTrackingAnalyzer', 'One line description of project.', 316 | 'Miscellaneous'), 317 | ] 318 | 319 | # Documents to append as an appendix to all manuals. 320 | # 321 | # texinfo_appendices = [] 322 | 323 | # If false, no module index is generated. 324 | # 325 | # texinfo_domain_indices = True 326 | 327 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 328 | # 329 | # texinfo_show_urls = 'footnote' 330 | 331 | # If true, do not generate a @detailmenu in the "Top" node's menu. 332 | # 333 | # texinfo_no_detailmenu = False 334 | -------------------------------------------------------------------------------- /docs/contributing.rst: -------------------------------------------------------------------------------- 1 | .. _contributing: 2 | 3 | ============ 4 | Contributing 5 | ============ 6 | 7 | If you want to add some functionality or you spot a bug and you want to fix it 8 | yourself, you can fork the Github repository and make all your changes in your 9 | local clone. 10 | 11 | Once you are done, please submit all your changes by issuing a pull request. 12 | 13 | When you are writing your code, please take into account the following basic 14 | rules: 15 | 16 | - Always include some unit tests for the new code you write or the bugs you fix. Or, update the existent unit tests, if necessary. 17 | - Stick to PEP-8_ styling. 18 | 19 | Testing 20 | ======= 21 | 22 | We use Pytest to unit test Django Tracking Analyzer. You can run the tests in 23 | your local in 3 different ways, depending on what you want to check: 24 | 25 | Simply run the unit tests. This should be enough for everybody:: 26 | 27 | python setup.py test 28 | 29 | Run tests with code coverage analysis:: 30 | 31 | python setup.py test --pytest-args "--cov-report xml --cov tracking_analyzer tests/ --verbose --junit-xml=junit.xml --color=yes" 32 | 33 | Run tests with coverage and Pylint/PEP8 checking:: 34 | 35 | python setup.py test --pytest-args "--cov-report xml --cov tracking_analyzer tests/ --verbose --junit-xml=junit.xml --color=yes --pylint --pylint-rcfile=pylint.rc --pep8" 36 | 37 | Versioning 38 | ========== 39 | 40 | Compliance API uses bumpversion_ 41 | package to manage versioning. You can install bumpversion regularly via `pip`:: 42 | 43 | pip install bumpversion 44 | 45 | You can now bump parts of version. 46 | 47 | Version bumps with examples: 48 | 49 | * ``bumpversion patch``: ``0.1.0 -> 0.1.1`` 50 | * ``bumpversion minor``: ``0.1.1 -> 0.2.0`` 51 | * ``bumpversion major``: ``0.2.0 -> 1.0.0`` 52 | 53 | **Warning:** Each version bump will also create commit with tag. 54 | 55 | 56 | .. _PEP-8: https://www.python.org/dev/peps/pep-0008/ 57 | .. _bumpversion: https://pypi.python.org/pypi/bumpversion 58 | -------------------------------------------------------------------------------- /docs/images/devices_count.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jose-lpa/django-tracking-analyzer/87208e080bab7082d8a9a4acad291ec2ea68a3a6/docs/images/devices_count.png -------------------------------------------------------------------------------- /docs/images/requests_timeline.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jose-lpa/django-tracking-analyzer/87208e080bab7082d8a9a4acad291ec2ea68a3a6/docs/images/requests_timeline.png -------------------------------------------------------------------------------- /docs/images/tracker_detail.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jose-lpa/django-tracking-analyzer/87208e080bab7082d8a9a4acad291ec2ea68a3a6/docs/images/tracker_detail.png -------------------------------------------------------------------------------- /docs/images/world_map.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jose-lpa/django-tracking-analyzer/87208e080bab7082d8a9a4acad291ec2ea68a3a6/docs/images/world_map.png -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. Django Tracking Analyzer documentation master file, created by 2 | sphinx-quickstart on Sat Jul 9 23:22:40 2016. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | ======================================== 7 | Django Tracking Analyzer's documentation 8 | ======================================== 9 | 10 | .. rubric:: User actions tracking and analytics for Django sites 11 | 12 | .. image:: https://travis-ci.org/jose-lpa/django-tracking-analyzer.svg?branch=master 13 | :target: https://travis-ci.org/jose-lpa/django-tracking-analyzer 14 | 15 | .. image:: https://codecov.io/gh/jose-lpa/django-tracking-analyzer/branch/development/graph/badge.svg 16 | :target: https://codecov.io/gh/jose-lpa/django-tracking-analyzer 17 | 18 | .. image:: https://badge.fury.io/py/django-tracking-analyzer.svg 19 | :target: https://badge.fury.io/py/django-tracking-analyzer 20 | 21 | 22 | Contents 23 | ======== 24 | 25 | .. toctree:: 26 | :maxdepth: 2 27 | 28 | installation 29 | usage 30 | settings 31 | contributing 32 | 33 | 34 | License 35 | ======= 36 | 37 | Django Tracking Analyzer is licensed under the `GNU GPLv3`_ license. This makes 38 | you able to modify and redistribute the code of this package freely, as well as 39 | to use it in your own Django sites or applications publicly. 40 | 41 | The related software included in this package, such as D3.js or some code for 42 | the Javascript widgets, have its own licenses. In case you want to modify and 43 | use that software for your own purposes, please refer to their own licenses. 44 | 45 | 46 | Source code and contributions 47 | ============================= 48 | 49 | The source code can be found on Github_. 50 | 51 | Bugs can be reported on the Github repository issues. Any collaboration will be 52 | very appreciated. Please see :ref:`contributing` for more details. 53 | 54 | 55 | Indices and tables 56 | ================== 57 | 58 | * :ref:`genindex` 59 | * :ref:`modindex` 60 | * :ref:`search` 61 | 62 | 63 | .. _Github: https://github.com/jose-lpa/django-tracking-analyzer 64 | .. _GNU GPLv3: http://www.gnu.org/licenses/ 65 | -------------------------------------------------------------------------------- /docs/installation.rst: -------------------------------------------------------------------------------- 1 | .. _installation: 2 | 3 | ============ 4 | Installation 5 | ============ 6 | 7 | 8 | Prerequisites 9 | ============= 10 | 11 | The next requirements will be installed together with Django Tracking Analyzer: 12 | 13 | - Django 2.1 or later. 14 | - Django Countries 5.5 or later. 15 | - Django IPWare 2.1.0 or later. 16 | - Django User Agents 0.4.0 or later. 17 | - GeoIP2 2.9.0 or later. 18 | 19 | 20 | Package installation 21 | ==================== 22 | 23 | You can install the Django Tracking Analyzer package in the two traditional 24 | Python ways: 25 | 26 | 1. Automatically, by using PyPI (this is of course the preferred way): 27 | 28 | .. code-block:: bash 29 | 30 | pip install django-tracking-analyzer 31 | 32 | 2. Manually, by downloading the package and installing yourself: 33 | 34 | .. code-block:: bash 35 | 36 | wget https://github.com/jose-lpa/django-tracking-analyzer/archive/master.zip 37 | unzip master.zip 38 | cd django-tracking-analyzer-master/ 39 | python setup.py install 40 | 41 | 42 | Configuration 43 | ============= 44 | 45 | Once the package is installed, the next two entries have to be added to the 46 | ``INSTALLED_APPS`` setting: 47 | 48 | - ``'django_user_agents'`` (enables all the functionality needed to get user 49 | agent data) 50 | - ``'tracking_analyzer'`` 51 | 52 | 53 | MaxMind® GeoLite2 datasets installation 54 | ======================================= 55 | 56 | In order to have IP geolocation and related data collection, DTA uses the 57 | GeoIP2 library, which should have been installed together with this package. 58 | 59 | GeoIP2 uses MaxMind® geographical datasets to work, which location is pointed 60 | by the ``GEOIP_PATH`` Django setting. This means you have to dowload and 61 | install those datasets in the directory specified by that setting, which you 62 | can do in two different ways: 63 | 64 | 1. Automatically, by using the DTA management command ``install_geoip_dataset``. 65 | This is the preferred and fastest way of doing it, and you should be ready 66 | to go by just running the command: ``python setup.py install_geoip_dataset``. 67 | 68 | 2. Manually, by downloading yourself the datasets from the MaxMind® `GeoLite2 site`_. 69 | 70 | Once this last step is done, you should be ready to use Django Tracking Analyzer. 71 | 72 | 73 | ``install_geoip_dataset`` management command 74 | -------------------------------------------- 75 | 76 | The management command ``install_geoip_dataset`` is available to help you 77 | download and install the MaxMind GeoLite2 datasets without any effort. 78 | 79 | The only thing you have to make is to ensure the existence of the Django setting 80 | ``GEOIP_PATH``. This setting specifies the directory where the GeoIP data files 81 | are located. It is unset by default, you have to set it to a directory where you 82 | want the datasets to be installed. A nice place is usually the root directory of 83 | your project code. 84 | 85 | Once you have this setting, you can execute the management command and, if you 86 | don't have any GeoLite2 files in that directory, it will download and decompress 87 | the GeoLite2 "City" and "Country" datasets for you:: 88 | 89 | python manage.py install_geoip_dataset 90 | 91 | In case you already have the datasets installed, the command will ask you if you 92 | really want to download another datasets and replace the existing ones with the 93 | latest downloaded version:: 94 | 95 | Seems that MaxMind dataset GeoLite2-Country.mmdb.gz is already installed in "GeoLite2-Country.mmdb.gz". Do you want to reinstall it? 96 | (y/n) 97 | 98 | The process will run for both the "Country" and the "City" datasets. 99 | 100 | Although the management command will everything you need in a simlpe run, you 101 | might want to specify some different download options, such the datasets files 102 | names or the download URL. You can do this via the next command parameters: 103 | 104 | - ``url``: Base URL where the MaxMind(R) datasets are available. 105 | - ``countries``: Remote file name for the MaxMind(R) Country dataset (compressed). 106 | - ``cities``: Remote file name for the MaxMind(R) City dataset (compressed). 107 | 108 | 109 | .. _GeoLite2 site: http://dev.maxmind.com/geoip/geoip2/geolite2/ 110 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=_build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . 10 | set I18NSPHINXOPTS=%SPHINXOPTS% . 11 | if NOT "%PAPER%" == "" ( 12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 14 | ) 15 | 16 | if "%1" == "" goto help 17 | 18 | if "%1" == "help" ( 19 | :help 20 | echo.Please use `make ^` where ^ is one of 21 | echo. html to make standalone HTML files 22 | echo. dirhtml to make HTML files named index.html in directories 23 | echo. singlehtml to make a single large HTML file 24 | echo. pickle to make pickle files 25 | echo. json to make JSON files 26 | echo. htmlhelp to make HTML files and a HTML help project 27 | echo. qthelp to make HTML files and a qthelp project 28 | echo. devhelp to make HTML files and a Devhelp project 29 | echo. epub to make an epub 30 | echo. epub3 to make an epub3 31 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 32 | echo. text to make text files 33 | echo. man to make manual pages 34 | echo. texinfo to make Texinfo files 35 | echo. gettext to make PO message catalogs 36 | echo. changes to make an overview over all changed/added/deprecated items 37 | echo. xml to make Docutils-native XML files 38 | echo. pseudoxml to make pseudoxml-XML files for display purposes 39 | echo. linkcheck to check all external links for integrity 40 | echo. doctest to run all doctests embedded in the documentation if enabled 41 | echo. coverage to run coverage check of the documentation if enabled 42 | echo. dummy to check syntax errors of document sources 43 | goto end 44 | ) 45 | 46 | if "%1" == "clean" ( 47 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 48 | del /q /s %BUILDDIR%\* 49 | goto end 50 | ) 51 | 52 | 53 | REM Check if sphinx-build is available and fallback to Python version if any 54 | %SPHINXBUILD% 1>NUL 2>NUL 55 | if errorlevel 9009 goto sphinx_python 56 | goto sphinx_ok 57 | 58 | :sphinx_python 59 | 60 | set SPHINXBUILD=python -m sphinx.__init__ 61 | %SPHINXBUILD% 2> nul 62 | if errorlevel 9009 ( 63 | echo. 64 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 65 | echo.installed, then set the SPHINXBUILD environment variable to point 66 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 67 | echo.may add the Sphinx directory to PATH. 68 | echo. 69 | echo.If you don't have Sphinx installed, grab it from 70 | echo.http://sphinx-doc.org/ 71 | exit /b 1 72 | ) 73 | 74 | :sphinx_ok 75 | 76 | 77 | if "%1" == "html" ( 78 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 79 | if errorlevel 1 exit /b 1 80 | echo. 81 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 82 | goto end 83 | ) 84 | 85 | if "%1" == "dirhtml" ( 86 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 87 | if errorlevel 1 exit /b 1 88 | echo. 89 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 90 | goto end 91 | ) 92 | 93 | if "%1" == "singlehtml" ( 94 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 95 | if errorlevel 1 exit /b 1 96 | echo. 97 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 98 | goto end 99 | ) 100 | 101 | if "%1" == "pickle" ( 102 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 103 | if errorlevel 1 exit /b 1 104 | echo. 105 | echo.Build finished; now you can process the pickle files. 106 | goto end 107 | ) 108 | 109 | if "%1" == "json" ( 110 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 111 | if errorlevel 1 exit /b 1 112 | echo. 113 | echo.Build finished; now you can process the JSON files. 114 | goto end 115 | ) 116 | 117 | if "%1" == "htmlhelp" ( 118 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 119 | if errorlevel 1 exit /b 1 120 | echo. 121 | echo.Build finished; now you can run HTML Help Workshop with the ^ 122 | .hhp project file in %BUILDDIR%/htmlhelp. 123 | goto end 124 | ) 125 | 126 | if "%1" == "qthelp" ( 127 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 128 | if errorlevel 1 exit /b 1 129 | echo. 130 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 131 | .qhcp project file in %BUILDDIR%/qthelp, like this: 132 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\DjangoTrackingAnalyzer.qhcp 133 | echo.To view the help file: 134 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\DjangoTrackingAnalyzer.ghc 135 | goto end 136 | ) 137 | 138 | if "%1" == "devhelp" ( 139 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 140 | if errorlevel 1 exit /b 1 141 | echo. 142 | echo.Build finished. 143 | goto end 144 | ) 145 | 146 | if "%1" == "epub" ( 147 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 148 | if errorlevel 1 exit /b 1 149 | echo. 150 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 151 | goto end 152 | ) 153 | 154 | if "%1" == "epub3" ( 155 | %SPHINXBUILD% -b epub3 %ALLSPHINXOPTS% %BUILDDIR%/epub3 156 | if errorlevel 1 exit /b 1 157 | echo. 158 | echo.Build finished. The epub3 file is in %BUILDDIR%/epub3. 159 | goto end 160 | ) 161 | 162 | if "%1" == "latex" ( 163 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 164 | if errorlevel 1 exit /b 1 165 | echo. 166 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 167 | goto end 168 | ) 169 | 170 | if "%1" == "latexpdf" ( 171 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 172 | cd %BUILDDIR%/latex 173 | make all-pdf 174 | cd %~dp0 175 | echo. 176 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 177 | goto end 178 | ) 179 | 180 | if "%1" == "latexpdfja" ( 181 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 182 | cd %BUILDDIR%/latex 183 | make all-pdf-ja 184 | cd %~dp0 185 | echo. 186 | echo.Build finished; the PDF files are in %BUILDDIR%/latex. 187 | goto end 188 | ) 189 | 190 | if "%1" == "text" ( 191 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 192 | if errorlevel 1 exit /b 1 193 | echo. 194 | echo.Build finished. The text files are in %BUILDDIR%/text. 195 | goto end 196 | ) 197 | 198 | if "%1" == "man" ( 199 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 200 | if errorlevel 1 exit /b 1 201 | echo. 202 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 203 | goto end 204 | ) 205 | 206 | if "%1" == "texinfo" ( 207 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 208 | if errorlevel 1 exit /b 1 209 | echo. 210 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 211 | goto end 212 | ) 213 | 214 | if "%1" == "gettext" ( 215 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 216 | if errorlevel 1 exit /b 1 217 | echo. 218 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 219 | goto end 220 | ) 221 | 222 | if "%1" == "changes" ( 223 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 224 | if errorlevel 1 exit /b 1 225 | echo. 226 | echo.The overview file is in %BUILDDIR%/changes. 227 | goto end 228 | ) 229 | 230 | if "%1" == "linkcheck" ( 231 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 232 | if errorlevel 1 exit /b 1 233 | echo. 234 | echo.Link check complete; look for any errors in the above output ^ 235 | or in %BUILDDIR%/linkcheck/output.txt. 236 | goto end 237 | ) 238 | 239 | if "%1" == "doctest" ( 240 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 241 | if errorlevel 1 exit /b 1 242 | echo. 243 | echo.Testing of doctests in the sources finished, look at the ^ 244 | results in %BUILDDIR%/doctest/output.txt. 245 | goto end 246 | ) 247 | 248 | if "%1" == "coverage" ( 249 | %SPHINXBUILD% -b coverage %ALLSPHINXOPTS% %BUILDDIR%/coverage 250 | if errorlevel 1 exit /b 1 251 | echo. 252 | echo.Testing of coverage in the sources finished, look at the ^ 253 | results in %BUILDDIR%/coverage/python.txt. 254 | goto end 255 | ) 256 | 257 | if "%1" == "xml" ( 258 | %SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml 259 | if errorlevel 1 exit /b 1 260 | echo. 261 | echo.Build finished. The XML files are in %BUILDDIR%/xml. 262 | goto end 263 | ) 264 | 265 | if "%1" == "pseudoxml" ( 266 | %SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml 267 | if errorlevel 1 exit /b 1 268 | echo. 269 | echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml. 270 | goto end 271 | ) 272 | 273 | if "%1" == "dummy" ( 274 | %SPHINXBUILD% -b dummy %ALLSPHINXOPTS% %BUILDDIR%/dummy 275 | if errorlevel 1 exit /b 1 276 | echo. 277 | echo.Build finished. Dummy builder generates no files. 278 | goto end 279 | ) 280 | 281 | :end 282 | -------------------------------------------------------------------------------- /docs/settings.rst: -------------------------------------------------------------------------------- 1 | .. _settings: 2 | 3 | ======== 4 | Settings 5 | ======== 6 | 7 | Django Tracking Analyzer behaviour can be customized by using the next 8 | application settings in your project: 9 | 10 | ``GEOIP_PATH`` 11 | -------------- 12 | 13 | It defines the path where the GeoIP2 datasets are installed. 14 | 15 | Although this is not a Django Tracking Analyzer setting, you have to set it up 16 | in order to get the GeoIP datasets working properly. Please check `GeoIP2 Django documentation`_ 17 | for detailed information. 18 | 19 | - Default: **unset** 20 | 21 | ``TRACKING_ANALYZER_MAXMIND_URL`` 22 | --------------------------------- 23 | 24 | Specifies the URL where the GeoIP datasets have to be retrieved from. It 25 | defaults to the MaxMind database official repository. 26 | 27 | - Default: ``'http://geolite.maxmind.com/download/geoip/database/'`` 28 | 29 | ``TRACKING_ANALYZER_MAXMIND_COUNTRIES`` 30 | --------------------------------------- 31 | 32 | Specifies the file name for the *compressed* countries database. 33 | 34 | - Default: ``'GeoLite2-Country.mmdb.gz'`` 35 | 36 | ``TRACKING_ANALYZER_MAXMIND_CITIES`` 37 | ------------------------------------ 38 | 39 | Specifies the file name for the *compressed* cities database. 40 | 41 | - Default: ``'GeoLite2-City.mmdb.gz'`` 42 | 43 | 44 | .. _GeoIP2 Django documentation: https://docs.djangoproject.com/en/1.10/ref/contrib/gis/geoip2/ 45 | -------------------------------------------------------------------------------- /docs/usage.rst: -------------------------------------------------------------------------------- 1 | .. _usage: 2 | 3 | ===== 4 | Usage 5 | ===== 6 | 7 | 8 | Overview 9 | ======== 10 | 11 | Django Tracking Analyzer is a Django application that aims to help you know in 12 | a simple and user-friendly way who the visitors of your site are, where they 13 | come from, what devices are they using to browse your site, what resources of 14 | your site they access, when and how many times. 15 | 16 | In order to do this, DTA implements a database model ``Tracker``, which will be 17 | created each time a user access certain resource, like a blog post, or performs 18 | certain action, like buying a product in your web shop. 19 | 20 | Then, using the Django admin interface, you can check the "Trackers" changelist 21 | in the "Django Tracking Analyzer" app admin, and you will see a changelist of 22 | all the user accesses with details about the requests, like the IP address, the 23 | country and city (if available), the device type, browser and system information. 24 | 25 | And also, heading the traditional changelist page, you will be provided with some 26 | nice interactive graphics made in D3.js, to actually see all the data gathered 27 | in a visual fancy way: 28 | 29 | - A world map where you can see where the visitors of your site come from. 30 | 31 | .. image:: images/world_map.png 32 | :align: center 33 | :alt: World map for requests geolocation. 34 | 35 | - A bars graph showing the number of requests per device type. 36 | 37 | .. image:: images/devices_count.png 38 | :align: center 39 | :alt: Device types bar graph. 40 | 41 | - A timeline showing the number of requests for the current changelist page. 42 | 43 | .. image:: images/requests_timeline.png 44 | :align: center 45 | :alt: Requests timeline. 46 | 47 | 48 | Tracking requests or events 49 | =========================== 50 | 51 | Collecting users data is as simple as relate a user request with a Django model 52 | that represents something you want to track: a blog post, an item in a webshop 53 | or anything else you have represented as a database model in your Django site. 54 | 55 | The ``Tracker`` model then will relate a request with such an object of your 56 | choice, collecting all the relevant request data like geolocation, user device, 57 | browser and system version. When you have several ``Tracker``'s collected, you 58 | can visualize the data and get an idea of what kind of users you site have or 59 | who is buying what products in your webshop. 60 | 61 | A ``Tracker`` object can be created by using the special manager method 62 | ``create_from_request``: 63 | 64 | .. code-block:: python 65 | 66 | Tracker.objects.create_from_request(request, model_instance) 67 | 68 | 69 | As you can see, the only things needed are an HTTP request object and a model 70 | instance. This makes it very easy to record tracks in any view of your project, 71 | which will be the place where a user interacts with some resource or performs 72 | some action: the Django views. 73 | 74 | You can override the ``get_object`` method in a ``DetailView``, if you are 75 | usign class-based views, or you can create the ``Tracker`` wherever you want in 76 | your function views. The only thing you need is a ``django.http.HttpRequest`` 77 | instance, which is of course available in any Django view, and a database model 78 | instance you want to track. 79 | 80 | Examples 81 | -------- 82 | 83 | Let's see an example of how to track a user action. Imagine you have a web shop 84 | and you want to get a track of the users who buy products from it. 85 | 86 | You could have a view in your code that, once a user submits a purchasing form, 87 | executes some code to perform the purchase/payment operations. In such a view, 88 | you can simply add the ``Tracker`` object creation after the purchase is 89 | completed, making a system record of the client. 90 | 91 | .. code-block:: python 92 | 93 | from django.contrib.auth.decorators import login_required 94 | from django.shortcuts import get_object_or_404, render_to_response 95 | 96 | from tracking_analyzer.models import Tracker 97 | 98 | 99 | @login_required 100 | def purchase_item(request, product_pk): 101 | product = get_object_or_404(Product, pk=product_pk) 102 | 103 | # Here is your logic to perform the purchase... 104 | ... 105 | # ...and to make the payment and other needed operations. 106 | 107 | # Track the products purchases! 108 | Tracker.objects.create_from_request(self.request, product) 109 | 110 | return render_to_response(template, context_dict, RequestContext(request)) 111 | 112 | With that simple line added to your code, you'll have a detail log of every 113 | purchase request. Note that the special manager method ``create_from_request`` 114 | does everything for you in terms of collecting request information and relating 115 | it to the passed object instance. 116 | 117 | In other environment, you might be using Django class-based views. Let's see an 118 | example in which you have a news site, so you have daily news posted in a main 119 | page and the users can read each notice by clicking the title. Then you might 120 | have a ``DetailView`` to show a notice by its slug, and so you can track the 121 | visitors to your news by using DTA in a similar way than before: 122 | 123 | .. code-block:: python 124 | 125 | from django.views.generic import DetailView 126 | 127 | from tracking_analyzer.models import Tracker 128 | 129 | from news.models import NewsEntry 130 | 131 | 132 | class NewsEntry(DetailView): 133 | model = NewsEntry 134 | 135 | def get_object(self, queryset=None): 136 | # Retrieve the news entry just using `get_object` functionality. 137 | entry = super(PostDetailView, self).get_object(queryset) 138 | 139 | # Track the users access to the news by entry! 140 | Tracker.objects.create_from_request(self.request, entry) 141 | 142 | return entry 143 | 144 | 145 | As you can see, it's pretty simple and straightforward to start collecting 146 | user data from the requests to your site. 147 | 148 | If you go to your Django admin, "Django Tracking Analyzer" - "Trackers" section, 149 | you will see a regular Django changelist of "trackers". Then if you click the 150 | "Details" link in one of them, you can see the request data overview as follows: 151 | 152 | .. image:: images/tracker_detail.png 153 | :align: center 154 | :alt: Django admin detail view. 155 | -------------------------------------------------------------------------------- /pylint.rc: -------------------------------------------------------------------------------- 1 | [MASTER] 2 | persistent=yes 3 | ignore=migrations 4 | cache-size=500 5 | 6 | [MESSAGES CONTROL] 7 | # C0111 Missing docstring 8 | # I0011 Warning locally suppressed using disable-msg 9 | # I0012 Warning locally suppressed using disable-msg 10 | # W0704 Except doesn't do anything Used when an except clause does nothing but "pass" and there is no "else" clause 11 | # W0142 Used * or * magic* Used when a function or method is called using *args or **kwargs to dispatch arguments. 12 | # W0212 Access to a protected member %s of a client class 13 | # W0232 Class has no __init__ method Used when a class has no __init__ method, neither its parent classes. 14 | # W0613 Unused argument %r Used when a function or method argument is not used. 15 | # W0702 No exception's type specified Used when an except clause doesn't specify exceptions type to catch. 16 | # R0201 Method could be a function 17 | # W0311 Bad indentation (complains about using 4 spaces instead of 1?) 18 | # C0303 Trailing whitespace 19 | # E1101 Instance of '' has no '' member (doesn't work with multiple inheritance?) 20 | # R0801 Similar lines in X files http://stackoverflow.com/questions/12209430/pylint-raising-r0801-for-coding-declaration-lines 21 | # R0901 Too many ancestors (nearly every class-based view) 22 | # R0904 Too many public methods (every ModelAdmin subclass) 23 | disable=C0111,I0011,I0012,W0704,W0142,W0212,W0232,W0613,W0702,R0201,W0311,C0303,E1101,R0801,R0904 24 | 25 | [REPORTS] 26 | output-format=parseable 27 | 28 | 29 | [BASIC] 30 | no-docstring-rgx=__.*__|_.* 31 | class-rgx=[A-Z_][a-zA-Z0-9_]+$ 32 | function-rgx=[a-zA_][a-zA-Z0-9_]{2,70}$ 33 | method-rgx=[a-z_][a-zA-Z0-9_]{2,70}$ 34 | const-rgx=(([A-Z_][A-Z0-9_]*)|([a-z_][a-z0-9_]*)|(__.*__)|register|urlpatterns)$ 35 | good-names=_,i,j,k,e,qs,pk,setUp,tearDown 36 | 37 | [TYPECHECK] 38 | # Tells whether missing members accessed in mixin class should be ignored. A 39 | # mixin class is detected if its name ends with "mixin" (case insensitive). 40 | ignore-mixin-members=yes 41 | 42 | # List of classes names for which member attributes should not be checked 43 | # (useful for classes with attributes dynamically set). 44 | ignored-classes=SQLObject,WSGIRequest 45 | 46 | # List of members which are set dynamically and missed by pylint inference 47 | # system, and so shouldn't trigger E0201 when accessed. 48 | generated-members=REQUEST,acl_users,aq_parent,objects,DoesNotExist,id,pk,_meta,base_fields,context 49 | 50 | # List of method names used to declare (i.e. assign) instance attributes 51 | defining-attr-methods=__init__,__new__,setUp 52 | 53 | 54 | [VARIABLES] 55 | init-import=no 56 | dummy-variables-rgx=_|dummy 57 | 58 | [SIMILARITIES] 59 | min-similarity-lines=6 60 | ignore-comments=yes 61 | ignore-docstrings=yes 62 | 63 | 64 | [MISCELLANEOUS] 65 | notes=FIXME,XXX,TODO 66 | 67 | 68 | [FORMAT] 69 | max-line-length=79 70 | max-module-lines=500 71 | indent-string=' ' 72 | 73 | 74 | [DESIGN] 75 | max-args=10 76 | max-locals=20 77 | max-returns=6 78 | max-branchs=12 79 | max-statements=50 80 | max-parents=7 81 | max-attributes=7 82 | min-public-methods=0 83 | max-public-methods=50 -------------------------------------------------------------------------------- /pytest.ini: -------------------------------------------------------------------------------- 1 | [pytest] 2 | django_find_project = false 3 | DJANGO_SETTINGS_MODULE = tests.settings_postgres 4 | 5 | python_paths = . 6 | junit_family=xunit2 7 | 8 | addopts = --ignore=tracking_analyzer/migrations 9 | --cov-report=xml 10 | --cov tracking_analyzer/ tests/ 11 | --junit-xml=junit.xml 12 | --pylint tracking_analyzer 13 | --pylint-rcfile=pylint.rc 14 | --pycodestyle 15 | --verbose 16 | --color=yes 17 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import sys 4 | 5 | from setuptools import setup, find_packages 6 | from setuptools.command.test import test as TestCommand 7 | 8 | 9 | with open('README.rst', 'r') as readme: 10 | long_description = readme.read() 11 | 12 | 13 | class PyTest(TestCommand): 14 | user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")] 15 | 16 | def initialize_options(self): 17 | TestCommand.initialize_options(self) 18 | self.pytest_args = [] 19 | 20 | def finalize_options(self): 21 | TestCommand.finalize_options(self) 22 | self.test_args = [] 23 | self.test_suite = True 24 | 25 | def run_tests(self): 26 | # Import here, cause outside the eggs aren't loaded. 27 | import pytest 28 | errno = pytest.main(self.pytest_args) 29 | sys.exit(errno) 30 | 31 | 32 | setup( 33 | name='django-tracking-analyzer', 34 | version='1.1.1', 35 | description='User actions tracking and analytics for Django sites.', 36 | long_description=long_description, 37 | author='José Luis Patiño Andrés', 38 | author_email='jose.lpa@gmail.com', 39 | url='https://github.com/jose-lpa/django-tracking-analyzer', 40 | keywords=['django', 'analytics', 'web', 'monitoring', 'logging'], 41 | packages=find_packages(exclude=['tests*']), 42 | include_package_data=True, 43 | install_requires=[ 44 | 'Django>=2.1', 45 | 'django-appconf', 46 | 'django-countries', 47 | 'django-ipware>=3.0', 48 | 'django-user-agents', 49 | 'geoip2' 50 | ], 51 | test_suite='tests', 52 | tests_require=[ 53 | 'factory-boy', 54 | 'pytest-django', 55 | 'pytest-cov', 56 | 'pytest-pycodestyle', 57 | 'pytest-pylint', 58 | ], 59 | cmdclass={'test': PyTest}, 60 | classifiers=[ 61 | 'Development Status :: 5 - Production/Stable', 62 | 'Framework :: Django :: 2.1', 63 | 'Framework :: Django :: 2.2', 64 | 'Framework :: Django :: 3.0', 65 | 'Intended Audience :: Developers', 66 | 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 67 | 'Operating System :: Unix', 68 | 'Operating System :: MacOS', 69 | 'Operating System :: Microsoft :: Windows', 70 | 'Programming Language :: Python :: 3.5', 71 | 'Programming Language :: Python :: 3.6', 72 | 'Programming Language :: Python :: 3.7', 73 | 'Programming Language :: Python :: 3.8', 74 | 'Topic :: Software Development :: Libraries :: Application Frameworks', 75 | 'Topic :: System :: Logging', 76 | 'Topic :: System :: Monitoring', 77 | 'Topic :: Utilities', 78 | ] 79 | ) 80 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | import django 4 | 5 | os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.settings' 6 | 7 | django.setup() 8 | 9 | # Ojete 10 | -------------------------------------------------------------------------------- /tests/factories.py: -------------------------------------------------------------------------------- 1 | # pylint: disable=unnecessary-lambda 2 | import factory 3 | from factory import fuzzy 4 | 5 | from tracking_analyzer.models import Tracker 6 | 7 | 8 | class UserFactory(factory.DjangoModelFactory): 9 | """ 10 | Factory model for the Django ``User`` model. 11 | """ 12 | first_name = 'Test' 13 | last_name = 'User' 14 | username = factory.Sequence(lambda n: 'user_{0}'.format(n)) 15 | email = factory.Sequence(lambda n: 'user_{0}@maykinmedia.nl'.format(n)) 16 | password = factory.PostGenerationMethodCall('set_password', 'testing') 17 | 18 | class Meta: 19 | model = 'auth.User' 20 | 21 | 22 | class PostFactory(factory.django.DjangoModelFactory): 23 | user = factory.SubFactory(UserFactory) 24 | title = factory.Sequence(lambda n: 'Post {0}'.format(n)) 25 | slug = factory.Sequence(lambda n: 'post-{0}'.format(n)) 26 | body = factory.Faker('text') 27 | 28 | class Meta: 29 | model = 'tests.Post' 30 | 31 | 32 | class TrackerFactory(factory.django.DjangoModelFactory): 33 | content_object = factory.SubFactory(PostFactory) 34 | ip_address = factory.Faker('ipv4') 35 | ip_country = 'NL' 36 | ip_region = 'Noord-Holland' 37 | ip_city = 'Amsterdam' 38 | device_type = fuzzy.FuzzyChoice( 39 | choices=(choice[0] for choice in Tracker.DEVICE_TYPE)) 40 | device = 'Other' 41 | browser = 'Firefox' 42 | browser_version = '47' 43 | system = 'Windows' 44 | system_version = 'Millenium Edition' 45 | user = factory.SubFactory(UserFactory) 46 | 47 | class Meta: 48 | model = 'tracking_analyzer.Tracker' 49 | -------------------------------------------------------------------------------- /tests/models.py: -------------------------------------------------------------------------------- 1 | # Testing models to create `Tracker` instances from. 2 | from django.db import models 3 | from django.contrib.auth.models import User 4 | from django.utils.text import slugify 5 | 6 | 7 | class Post(models.Model): 8 | user = models.ForeignKey(User, on_delete=models.CASCADE) 9 | title = models.CharField(max_length=100) 10 | slug = models.SlugField() 11 | body = models.TextField() 12 | published = models.DateTimeField(auto_now_add=True) 13 | 14 | def __str__(self): 15 | return str(self.title) 16 | 17 | def save( 18 | self, force_insert=False, force_update=False, using=None, 19 | update_fields=None 20 | ): 21 | if not self.slug: 22 | self.slug = slugify(self.title) 23 | 24 | super(Post, self).save( 25 | force_insert=False, force_update=False, using=None, 26 | update_fields=None 27 | ) 28 | -------------------------------------------------------------------------------- /tests/settings.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | 4 | TESTING_DIR = os.path.abspath(os.path.dirname(__file__)) 5 | 6 | SECRET_KEY = 'django_tracking_analyzer_secret' 7 | 8 | DATABASES = { 9 | 'default': { 10 | # Memory resident database, for easy testing. 11 | 'ENGINE': 'django.db.backends.sqlite3', 12 | 'NAME': ':memory:', 13 | } 14 | } 15 | 16 | ROOT_URLCONF = 'tests.urls' 17 | 18 | INSTALLED_APPS = [ 19 | 'django.contrib.contenttypes', 20 | 'django.contrib.auth', 21 | 'django.contrib.sessions', 22 | 'django.contrib.sites', 23 | 'django.contrib.admin', 24 | 'tracking_analyzer', 25 | 'tests' 26 | ] 27 | 28 | TEMPLATES = [ 29 | { 30 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 31 | 'APP_DIRS': True, 32 | 'OPTIONS': { 33 | 'context_processors': [ 34 | 'django.contrib.auth.context_processors.auth', 35 | 'django.template.context_processors.debug', 36 | 'django.template.context_processors.media', 37 | 'django.template.context_processors.static', 38 | 'django.template.context_processors.tz', 39 | 'django.template.context_processors.request', 40 | 'django.contrib.messages.context_processors.messages', 41 | ], 42 | } 43 | }, 44 | ] 45 | 46 | STATIC_ROOT = os.path.join(TESTING_DIR, 'static') 47 | STATIC_URL = '/static/' 48 | STATICFILES_DIRS = [] 49 | STATICFILES_FINDERS = ( 50 | 'django.contrib.staticfiles.finders.FileSystemFinder', 51 | 'django.contrib.staticfiles.finders.AppDirectoriesFinder' 52 | ) 53 | 54 | MIDDLEWARE = [ 55 | 'django.middleware.security.SecurityMiddleware', 56 | 'django.contrib.sessions.middleware.SessionMiddleware', 57 | 'django.middleware.common.CommonMiddleware', 58 | 'django.middleware.csrf.CsrfViewMiddleware', 59 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 60 | 'django.contrib.messages.middleware.MessageMiddleware', 61 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 62 | 63 | # External middleware. 64 | 'django_user_agents.middleware.UserAgentMiddleware', 65 | ] 66 | 67 | # Django GIS GeoIP2 settings. 68 | # This setting is Django-mandatory to make use of GeoIP2 facilities. We are 69 | # mocking the `GeoIP2.city()` method in the unit tests, so it's not necessary 70 | # to download and set up the MaxMind databases. 71 | GEOIP_PATH = TESTING_DIR 72 | 73 | # Django Tracking Analyzer settings. 74 | TRACKING_ANALYZER_MAXMIND_URL = \ 75 | "http://geolite.maxmind.com/download/geoip/database/" 76 | TRACKING_ANALYZER_MAXMIND_COUNTRIES = "GeoLite2-Country.mmdb.gz" 77 | TRACKING_ANALYZER_MAXMIND_CITIES = "GeoLite2-City.mmdb.gz" 78 | -------------------------------------------------------------------------------- /tests/settings_postgres.py: -------------------------------------------------------------------------------- 1 | # pylint: disable=wildcard-import,unused-wildcard-import 2 | from .settings import * 3 | 4 | 5 | DATABASES = { 6 | 'default': { 7 | 'ENGINE': 'django.db.backends.postgresql', 8 | 'NAME': 'tracking_analyzer_test', 9 | 'USERNAME': 'postgres', 10 | 'PASSWORD': '', 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /tests/test_admin.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | from django.contrib.admin import AdminSite 4 | from django.test import TestCase, RequestFactory 5 | from django.urls import reverse 6 | from django.utils import timezone 7 | 8 | from django_countries import countries 9 | 10 | from tracking_analyzer.admin import TrackerAdmin 11 | from tracking_analyzer.models import Tracker 12 | from .factories import TrackerFactory, UserFactory 13 | 14 | 15 | # pylint: disable=too-many-instance-attributes 16 | class TrackerAdminTestCase(TestCase): 17 | def setUp(self): 18 | self.tracker_1 = TrackerFactory.create( 19 | device_type=Tracker.PC, ip_country='ESP') 20 | self.tracker_2 = TrackerFactory.create( 21 | device_type=Tracker.MOBILE, ip_country='NLD') 22 | self.tracker_3 = TrackerFactory.create( 23 | device_type=Tracker.TABLET, ip_country='GBR') 24 | 25 | self.admin_site = AdminSite(name='tracker_admin') 26 | self.tracker_admin = TrackerAdmin(Tracker, self.admin_site) 27 | 28 | self.url = reverse('admin:tracking_analyzer_tracker_changelist') 29 | 30 | # Create a superuser and mock a request made by it. 31 | self.user = UserFactory.create(is_staff=True, is_superuser=True) 32 | self.request = RequestFactory().get('/') 33 | self.request.user = self.user 34 | 35 | def test_content_object_link(self): 36 | """ 37 | Test response of the ``TrackerAdmin.content_object_link`` method. 38 | """ 39 | response = self.tracker_admin.content_object_link(self.tracker_1) 40 | 41 | self.assertEqual( 42 | response, 43 | '' 44 | '{3}'.format( 45 | reverse('admin:tracking_analyzer_tracker_changelist'), 46 | self.tracker_1.content_type.id, 47 | self.tracker_1.object_id, 48 | self.tracker_1 49 | ) 50 | ) 51 | 52 | def test_ip_address_link(self): 53 | """ 54 | Test response of the ``TrackerAdmin.ip_address_link`` method when 55 | an IP address is available. 56 | """ 57 | response = self.tracker_admin.ip_address_link(self.tracker_1) 58 | 59 | self.assertEqual( 60 | response, 61 | '{1}'.format( 62 | reverse('admin:tracking_analyzer_tracker_changelist'), 63 | self.tracker_1.ip_address, 64 | ) 65 | ) 66 | 67 | def test_ip_address_link_no_address(self): 68 | """ 69 | Test response of the ``TrackerAdmin.ip_address_link`` method when 70 | an IP address is NOT available. 71 | """ 72 | self.tracker_1.ip_address = None 73 | self.tracker_1.save() 74 | 75 | response = self.tracker_admin.ip_address_link(self.tracker_1) 76 | 77 | self.assertEqual(response, '-') 78 | 79 | def test_ip_country_link(self): 80 | """ 81 | Test response of the ``TrackerAdmin.ip_country_link`` method when 82 | Country data is available. 83 | """ 84 | response = self.tracker_admin.ip_country_link(self.tracker_1) 85 | 86 | self.assertEqual( 87 | response, 88 | '{2}'.format( 89 | reverse('admin:tracking_analyzer_tracker_changelist'), 90 | self.tracker_1.ip_country, 91 | self.tracker_1.ip_country.name 92 | ) 93 | ) 94 | 95 | def test_ip_country_link_no_country(self): 96 | """ 97 | Test response of the ``TrackerAdmin.ip_country_link`` method when 98 | Country data is NOT available. 99 | """ 100 | self.tracker_1.ip_country = '' 101 | self.tracker_1.save() 102 | 103 | response = self.tracker_admin.ip_country_link(self.tracker_1) 104 | 105 | self.assertEqual(response, '-') 106 | 107 | def test_ip_city_link(self): 108 | """ 109 | Test response of the ``TrackerAdmin.ip_city_link`` method when City 110 | data is available. 111 | """ 112 | response = self.tracker_admin.ip_city_link(self.tracker_1) 113 | 114 | self.assertEqual( 115 | response, 116 | '{1}'.format( 117 | reverse('admin:tracking_analyzer_tracker_changelist'), 118 | self.tracker_1.ip_city, 119 | ) 120 | ) 121 | 122 | def test_ip_city_link_no_city(self): 123 | """ 124 | Test response of the ``TrackerAdmin.ip_city_link`` method when City 125 | data is NOT available. 126 | """ 127 | self.tracker_1.ip_city = '' 128 | self.tracker_1.save() 129 | 130 | response = self.tracker_admin.ip_city_link(self.tracker_1) 131 | 132 | self.assertEqual(response, '-') 133 | 134 | def test_user_link(self): 135 | """ 136 | Test response of the ``TrackerAdmin.user_link`` method when User data 137 | is available. 138 | """ 139 | response = self.tracker_admin.user_link(self.tracker_1) 140 | 141 | self.assertEqual( 142 | response, 143 | '{2}'.format( 144 | reverse('admin:tracking_analyzer_tracker_changelist'), 145 | self.tracker_1.user.pk, 146 | self.tracker_1.user 147 | ) 148 | ) 149 | 150 | def test_user_link_no_user(self): 151 | """ 152 | Test response of the ``TrackerAdmin.user_link`` method when User data 153 | is NOT available. 154 | """ 155 | self.tracker_1.user = None 156 | self.tracker_1.save() 157 | 158 | response = self.tracker_admin.user_link(self.tracker_1) 159 | 160 | self.assertEqual(response, 'Anonymous') 161 | 162 | def test_has_add_permission_always_false(self): 163 | """ 164 | The ``has_add_permission`` method must always return ``False``, because 165 | trackers should not be manually created by users. 166 | """ 167 | self.assertFalse(self.tracker_admin.has_add_permission(self.request)) 168 | 169 | def test_change_view_overridden_to_dismiss_edition_buttons(self): 170 | response = self.tracker_admin.change_view( 171 | self.request, str(self.tracker_1.pk)) 172 | 173 | self.assertFalse(response.context_data['show_save_and_add_another']) 174 | self.assertFalse(response.context_data['show_save_and_continue']) 175 | self.assertFalse(response.context_data['show_save']) 176 | 177 | def test_changelist_view_context_countries_count_present(self): 178 | """ 179 | The ``get_request_count`` context contains a dataset for countries 180 | requests when not filtering by country. 181 | """ 182 | url = reverse('admin:tracking_analyzer_tracker_changelist') 183 | request = RequestFactory().get(url) 184 | request.user = self.user 185 | 186 | response = self.tracker_admin.changelist_view(request) 187 | self.assertEqual( 188 | response.context_data['countries_count'], 189 | '[["{0}", 1], ["{1}", 1], ["{2}", 1]]'.format( 190 | countries.alpha3(self.tracker_1.ip_country), 191 | countries.alpha3(self.tracker_3.ip_country), 192 | countries.alpha3(self.tracker_2.ip_country), 193 | ) 194 | ) 195 | 196 | def test_changelist_view_context_countries_count_not_present(self): 197 | """ 198 | The ``get_request_count`` context should NOT contain a dataset for 199 | countries requests when user is filtering by country. 200 | """ 201 | url = '{0}?ip_country__exact=ES'.format( 202 | reverse('admin:tracking_analyzer_tracker_changelist')) 203 | request = RequestFactory().get(url) 204 | request.user = self.user 205 | 206 | response = self.tracker_admin.changelist_view(request) 207 | self.assertNotIn('countries_count', response.context_data) 208 | 209 | def test_changelist_view_context_devices_count_present(self): 210 | """ 211 | The ``get_request_count`` context contains a dataset for device types 212 | when user is not filtering by them. 213 | """ 214 | url = reverse('admin:tracking_analyzer_tracker_changelist') 215 | request = RequestFactory().get(url) 216 | request.user = self.user 217 | 218 | response = self.tracker_admin.changelist_view(request) 219 | data = json.loads(response.context_data['devices_count']) 220 | 221 | self.assertEqual(len(data), 3) 222 | self.assertIn( 223 | { 224 | "count": 1, 225 | "device_type": self.tracker_1.device_type, 226 | }, 227 | data 228 | ) 229 | self.assertIn( 230 | { 231 | "count": 1, 232 | "device_type": self.tracker_2.device_type, 233 | }, 234 | data 235 | ) 236 | self.assertIn( 237 | { 238 | "count": 1, 239 | "device_type": self.tracker_3.device_type, 240 | }, 241 | data 242 | ) 243 | 244 | def test_changelist_view_context_devices_count_not_present(self): 245 | """ 246 | The ``get_request_count`` context should NOT contain a dataset for 247 | device types when user is filtering by them. 248 | """ 249 | url = '{0}?device_type__exact=pc'.format( 250 | reverse('admin:tracking_analyzer_tracker_changelist')) 251 | request = RequestFactory().get(url) 252 | request.user = self.user 253 | 254 | response = self.tracker_admin.changelist_view(request) 255 | self.assertNotIn('devices_count', response.context_data) 256 | 257 | def test_changelist_view_requests_count(self): 258 | """ 259 | The ``get_request_count`` context must always contain a dataset for 260 | requests-per-minute count. 261 | """ 262 | # Now assign discrete `timestamp` values. 263 | self.tracker_1.timestamp = timezone.datetime(2016, 7, 26, 23, 0) 264 | self.tracker_1.save() 265 | self.tracker_2.timestamp = timezone.datetime(2016, 7, 26, 23, 0) 266 | self.tracker_2.save() 267 | self.tracker_3.timestamp = timezone.datetime(2016, 7, 26, 23, 10) 268 | self.tracker_3.save() 269 | 270 | url = reverse('admin:tracking_analyzer_tracker_changelist') 271 | request = RequestFactory().get(url) 272 | request.user = self.user 273 | 274 | response = self.tracker_admin.changelist_view(request) 275 | data = json.loads(response.context_data['requests_count']) 276 | 277 | self.assertEqual(len(data), 2) 278 | self.assertIn( 279 | { 280 | "date": self.tracker_1.timestamp.strftime('%Y-%m-%dT%H:%M'), 281 | "requests": 2 282 | }, 283 | data 284 | ) 285 | self.assertIn( 286 | { 287 | "date": self.tracker_3.timestamp.strftime('%Y-%m-%dT%H:%M'), 288 | "requests": 1 289 | }, 290 | data 291 | ) 292 | 293 | def test_changelist_post_delete(self): 294 | """ 295 | Tests that the 'changelist' POST action stills working. 296 | """ 297 | self.client.login(username=self.user.username, password='testing') 298 | response = self.client.post( 299 | self.url, 300 | data={ 301 | '_selected_action': str(self.tracker_1.pk), 302 | 'action': 'delete_selected' # Add 'post': 'yes' later. 303 | } 304 | ) 305 | 306 | self.assertEqual(response.status_code, 200) 307 | 308 | response = self.client.post( 309 | self.url, 310 | data={ 311 | '_selected_action': str(self.tracker_1.pk), 312 | 'action': 'delete_selected', 313 | 'post': 'yes' 314 | }, 315 | follow=True 316 | ) 317 | 318 | self.assertEqual(response.status_code, 200) 319 | 320 | # `self.tracker_1` was actually deleted. 321 | self.assertFalse(Tracker.objects.filter(pk=self.tracker_1.pk).exists()) 322 | -------------------------------------------------------------------------------- /tests/test_management_commands.py: -------------------------------------------------------------------------------- 1 | import unittest.mock as mock 2 | from urllib.error import HTTPError, URLError 3 | 4 | from django.conf import settings 5 | from django.core.management import call_command, CommandError 6 | from django.test import override_settings, TestCase 7 | 8 | 9 | class InstallGeoIPDatasetTestCase(TestCase): 10 | @override_settings(GEOIP_PATH=None) 11 | def test_handle_missing_geoip_path(self): 12 | """ 13 | The project settings have to have a ``GEOIP_PATH``. 14 | """ 15 | del settings.GEOIP_PATH 16 | 17 | self.assertRaisesMessage( 18 | CommandError, 19 | '`GEOIP_PATH` setting not present. Unable to get the GeoIP ' 20 | 'dataset.', 21 | call_command, 'install_geoip_dataset' 22 | ) 23 | 24 | @override_settings(TRACKING_ANALYZER_MAXMIND_URL=None) 25 | def test_handle_no_url_arg_no_url_setting(self): 26 | """ 27 | If the user doesn't provide a base URL to download the dataset from, at 28 | least the ``TRACKING_ANALYZER_MAXMIND_URL`` setting have to be present. 29 | """ 30 | del settings.TRACKING_ANALYZER_MAXMIND_URL 31 | 32 | self.assertRaisesMessage( 33 | CommandError, 34 | '`TRACKING_ANALYZER_MAXMIND_URL` setting not present. Unable to ' 35 | 'get the GeoIP dataset.', 36 | call_command, 'install_geoip_dataset' 37 | ) 38 | 39 | @override_settings(TRACKING_ANALYZER_MAXMIND_COUNTRIES=None) 40 | def test_handle_no_dataset_arg_no_countries_setting(self): 41 | """ 42 | If the user doesn't provide a dataset file name to be downloaded, at 43 | least the ``TRACKING_ANALYZER_MAXMIND_COUNTRIES`` setting have to be 44 | present. 45 | """ 46 | del settings.TRACKING_ANALYZER_MAXMIND_COUNTRIES 47 | 48 | self.assertRaisesMessage( 49 | CommandError, 50 | '`TRACKING_ANALYZER_MAXMIND_COUNTRIES` setting not present. Unable' 51 | ' to get the GeoIP dataset.', 52 | call_command, 'install_geoip_dataset' 53 | ) 54 | 55 | @override_settings(TRACKING_ANALYZER_MAXMIND_URL=None) 56 | @mock.patch( 57 | 'tracking_analyzer.management.commands.install_geoip_dataset.Command.' 58 | 'install_dataset') 59 | def test_handle_no_url_setting_manual_target(self, install_mock): 60 | """ 61 | If the base URL is not available, the user should still be able to 62 | specify it in in the command arguments. 63 | """ 64 | del settings.TRACKING_ANALYZER_MAXMIND_URL 65 | 66 | call_command('install_geoip_dataset', url='http://www.maykinmedia.nl') 67 | 68 | calls = [ 69 | mock.call( 70 | settings.GEOIP_PATH, 71 | mm_url='http://www.maykinmedia.nl', 72 | mm_dataset=settings.TRACKING_ANALYZER_MAXMIND_COUNTRIES 73 | ), 74 | mock.call( 75 | settings.GEOIP_PATH, 76 | mm_url='http://www.maykinmedia.nl', 77 | mm_dataset=settings.TRACKING_ANALYZER_MAXMIND_CITIES 78 | ) 79 | ] 80 | 81 | install_mock.assert_has_calls(calls) 82 | 83 | @override_settings(TRACKING_ANALYZER_MAXMIND_COUNTRIES=None) 84 | @mock.patch( 85 | 'tracking_analyzer.management.commands.install_geoip_dataset.Command.' 86 | 'install_dataset') 87 | def test_handle_no_countries_setting_manual_target(self, install_mock): 88 | """ 89 | If the countries file name is not available, the user should still be 90 | able to specify it in in the command arguments. 91 | """ 92 | del settings.TRACKING_ANALYZER_MAXMIND_COUNTRIES 93 | 94 | call_command('install_geoip_dataset', countries='countries_db.mmdb') 95 | 96 | calls = [ 97 | mock.call( 98 | settings.GEOIP_PATH, 99 | mm_url=settings.TRACKING_ANALYZER_MAXMIND_URL, 100 | mm_dataset='countries_db.mmdb' 101 | ), 102 | mock.call( 103 | settings.GEOIP_PATH, 104 | mm_url=settings.TRACKING_ANALYZER_MAXMIND_URL, 105 | mm_dataset=settings.TRACKING_ANALYZER_MAXMIND_CITIES 106 | ) 107 | ] 108 | 109 | install_mock.assert_has_calls(calls) 110 | 111 | @override_settings(TRACKING_ANALYZER_MAXMIND_CITIES=None) 112 | @mock.patch( 113 | 'tracking_analyzer.management.commands.install_geoip_dataset.Command.' 114 | 'install_dataset') 115 | def test_a_handle_no_cities_setting_manual_target(self, install_mock): 116 | """ 117 | If the cities file name is not available, the user should still be 118 | able to specify it in in the command arguments. 119 | """ 120 | del settings.TRACKING_ANALYZER_MAXMIND_CITIES 121 | 122 | call_command('install_geoip_dataset', cities='cities_db.mmdb') 123 | 124 | calls = [ 125 | mock.call( 126 | settings.GEOIP_PATH, 127 | mm_url=settings.TRACKING_ANALYZER_MAXMIND_URL, 128 | mm_dataset=settings.TRACKING_ANALYZER_MAXMIND_COUNTRIES 129 | ), 130 | mock.call( 131 | settings.GEOIP_PATH, 132 | mm_url=settings.TRACKING_ANALYZER_MAXMIND_URL, 133 | mm_dataset='cities_db.mmdb' 134 | ) 135 | ] 136 | 137 | install_mock.assert_has_calls(calls) 138 | 139 | @mock.patch( 140 | 'tracking_analyzer.management.commands.install_geoip_dataset.Command.' 141 | 'install_dataset') 142 | def test_handle_straight_run_no_user_input_needed(self, install_mock): 143 | """ 144 | Test the management command in a straight situation where the system 145 | does not have any dataset installed yet and the settings are okay. 146 | """ 147 | call_command('install_geoip_dataset') 148 | 149 | calls = [ 150 | mock.call( 151 | settings.GEOIP_PATH, 152 | mm_url=settings.TRACKING_ANALYZER_MAXMIND_URL, 153 | mm_dataset=settings.TRACKING_ANALYZER_MAXMIND_COUNTRIES 154 | ), 155 | mock.call( 156 | settings.GEOIP_PATH, 157 | mm_url=settings.TRACKING_ANALYZER_MAXMIND_URL, 158 | mm_dataset=settings.TRACKING_ANALYZER_MAXMIND_CITIES 159 | ) 160 | ] 161 | 162 | install_mock.assert_has_calls(calls) 163 | 164 | @mock.patch( 165 | 'tracking_analyzer.management.commands.install_geoip_dataset.isfile') 166 | @mock.patch( 167 | 'tracking_analyzer.management.commands.install_geoip_dataset.Command.' 168 | 'user_input') 169 | @mock.patch( 170 | 'tracking_analyzer.management.commands.install_geoip_dataset.Command.' 171 | 'install_dataset') 172 | def test_handle_existing_datasets_user_action_required_no( 173 | self, mock_command, mock_input, mock_isfile 174 | ): 175 | """ 176 | Test the command running in a situation where there is an existent 177 | dataset already installed and the user responds "NO" when asked to 178 | update it. 179 | """ 180 | mock_isfile.return_value = True # A dataset is already placed. 181 | mock_input.return_value = False # User said 'no' 182 | 183 | call_command('install_geoip_dataset') 184 | 185 | self.assertFalse(mock_command.called) 186 | 187 | @mock.patch( 188 | 'tracking_analyzer.management.commands.install_geoip_dataset.isfile') 189 | @mock.patch( 190 | 'tracking_analyzer.management.commands.install_geoip_dataset.Command.' 191 | 'user_input') 192 | @mock.patch( 193 | 'tracking_analyzer.management.commands.install_geoip_dataset.Command.' 194 | 'install_dataset') 195 | def test_handle_existing_countries_user_action_required_yes( 196 | self, mock_command, mock_input, mock_isfile 197 | ): 198 | """ 199 | Test the command running in a situation where there is an existent 200 | dataset already installed and the user responds "YES" when asked to 201 | update it. 202 | """ 203 | mock_isfile.return_value = True # A dataset is already placed. 204 | mock_input.return_value = True # User said 'yes' 205 | 206 | call_command('install_geoip_dataset') 207 | 208 | calls = [ 209 | mock.call( 210 | settings.GEOIP_PATH, 211 | mm_url=settings.TRACKING_ANALYZER_MAXMIND_URL, 212 | mm_dataset=settings.TRACKING_ANALYZER_MAXMIND_COUNTRIES 213 | ), 214 | mock.call( 215 | settings.GEOIP_PATH, 216 | mm_url=settings.TRACKING_ANALYZER_MAXMIND_URL, 217 | mm_dataset=settings.TRACKING_ANALYZER_MAXMIND_CITIES 218 | ) 219 | ] 220 | 221 | mock_command.assert_has_calls(calls) 222 | 223 | @mock.patch( 224 | 'tracking_analyzer.management.commands.install_geoip_dataset.urlopen') 225 | def test_install_dataset_urlopen_http_error(self, urlopen_mock): 226 | """ 227 | ``install_dataset`` method is able to handle ``HTTPError`` exceptions. 228 | """ 229 | urlopen_mock.side_effect = HTTPError( 230 | url='http://www.maykinmedia.nl', 231 | code=403, 232 | msg='Forbidden', 233 | hdrs={}, 234 | fp=None 235 | ) 236 | 237 | self.assertRaisesMessage( 238 | CommandError, 239 | 'Unable to download MaxMind dataset.', 240 | call_command, 'install_geoip_dataset' 241 | ) 242 | 243 | @mock.patch( 244 | 'tracking_analyzer.management.commands.install_geoip_dataset.urlopen') 245 | def test_install_dataset_urlopen_url_error(self, urlopen_mock): 246 | """ 247 | ``install_dataset`` method is able to handle ``URLError`` exceptions. 248 | """ 249 | urlopen_mock.side_effect = URLError(reason='unknown url type') 250 | 251 | self.assertRaisesMessage( 252 | CommandError, 253 | 'Unable to download MaxMind dataset.', 254 | call_command, 'install_geoip_dataset' 255 | ) 256 | -------------------------------------------------------------------------------- /tests/test_models.py: -------------------------------------------------------------------------------- 1 | import unittest.mock as mock 2 | 3 | from django.contrib.auth.models import User 4 | from django.contrib.gis.geoip2 import GeoIP2Exception 5 | from django.test import TestCase 6 | 7 | from geoip2.errors import GeoIP2Error 8 | 9 | from tracking_analyzer.models import Tracker 10 | from .models import Post 11 | from .utils import build_mock_request 12 | 13 | 14 | class TrackerTestCase(TestCase): 15 | def setUp(self): 16 | self.user = User.objects.create( 17 | username='test_user', 18 | first_name='Test', 19 | last_name='User', 20 | email='test_user@maykinmedia.nl' 21 | ) 22 | 23 | self.post = Post.objects.create( 24 | user=self.user, 25 | title='Testing post', 26 | body='This is just a testing post.' 27 | ) 28 | 29 | self.request = build_mock_request('/testing/') 30 | 31 | @mock.patch('tracking_analyzer.manager.GeoIP2') 32 | def test_create_from_request_manager(self, mock_geoip2): 33 | """ 34 | Tests the ``create_from_request`` method from the custom 35 | ``TrackerManager`` in a successful execution. 36 | """ 37 | # Mock the response from `GeoIP2.city()` method. 38 | mock_geoip2().city.return_value = { 39 | 'country_code': 'US', 40 | 'region': 'CA', 41 | 'city': 'San Francisco' 42 | } 43 | 44 | tracker = Tracker.objects.create_from_request(self.request, self.post) 45 | 46 | self.assertEqual(tracker.browser, 'Chrome') 47 | self.assertEqual(tracker.browser_version, '49.0.2623') 48 | self.assertEqual(tracker.device, 'Mac') 49 | self.assertEqual(tracker.device_type, Tracker.PC) 50 | self.assertEqual(tracker.system, 'Mac OS X') 51 | self.assertEqual(tracker.system_version, '10.10.5') 52 | self.assertEqual(tracker.ip_address, '208.67.222.222') 53 | self.assertEqual(tracker.ip_country, 'US') 54 | self.assertEqual(tracker.ip_region, 'CA') 55 | self.assertEqual(tracker.ip_city, 'San Francisco') 56 | self.assertEqual(tracker.object_id, self.post.pk) 57 | self.assertEqual(tracker.user, self.request.user) 58 | 59 | @mock.patch('tracking_analyzer.manager.GeoIP2') 60 | def test_create_from_request_manager_null_data(self, mock_geoip2): 61 | """ 62 | Tests the ``create_from_request`` method from the custom 63 | ``TrackerManager`` when geo-location data is ``None``. 64 | """ 65 | # Mock the response from `GeoIP2.city()` method. 66 | mock_geoip2().city.return_value = { 67 | 'country_code': None, 68 | 'region': None, 69 | 'city': None 70 | } 71 | 72 | tracker = Tracker.objects.create_from_request(self.request, self.post) 73 | 74 | self.assertEqual(tracker.browser, 'Chrome') 75 | self.assertEqual(tracker.browser_version, '49.0.2623') 76 | self.assertEqual(tracker.device, 'Mac') 77 | self.assertEqual(tracker.device_type, Tracker.PC) 78 | self.assertEqual(tracker.system, 'Mac OS X') 79 | self.assertEqual(tracker.system_version, '10.10.5') 80 | self.assertEqual(tracker.ip_address, '208.67.222.222') 81 | self.assertEqual(tracker.ip_country, '') 82 | self.assertEqual(tracker.ip_region, '') 83 | self.assertEqual(tracker.ip_city, '') 84 | self.assertEqual(tracker.object_id, self.post.pk) 85 | self.assertEqual(tracker.user, self.request.user) 86 | 87 | def test_create_from_request_manager_wrong_request(self): 88 | """ 89 | Tests sanity checks for ``HTTPRequest`` object in the custom manager 90 | method. 91 | """ 92 | self.assertRaisesMessage( 93 | AssertionError, 94 | '`request` object is not an `HTTPRequest`', 95 | Tracker.objects.create_from_request, 96 | 'NOT_A_REQUEST', self.post 97 | ) 98 | 99 | def test_create_from_request_manager_wrong_link(self): 100 | """ 101 | Tests sanity checks for a ``models.Model`` object in the custom 102 | manager method. 103 | """ 104 | self.assertRaisesMessage( 105 | AssertionError, 106 | '`content_object` is not a Django model', 107 | Tracker.objects.create_from_request, 108 | self.request, 'NOT_A_MODEL' 109 | ) 110 | 111 | @mock.patch('tracking_analyzer.manager.GeoIP2') 112 | def test_create_from_request_missing_geoip_data(self, mock_geoip2): 113 | """ 114 | If GeoIP data is not available, or the ``GeoIP2.city`` function fails, 115 | the system must keep moving. Just GeoIP data won't be available. 116 | """ 117 | # Modify the request object to unset the `REMOTE_ADDR` IP meta data. 118 | # That should make the using of `ipware.ip.get_client_ip()` method 119 | # return an empty IP value. The system must deal with empty IP 120 | # addresses. 121 | self.request.META['REMOTE_ADDR'] = '' 122 | 123 | tracker = Tracker.objects.create_from_request(self.request, self.post) 124 | 125 | # Now check the results. Empty data for IP address and GeoIP stuff. 126 | self.assertEqual(tracker.ip_address, None) 127 | self.assertEqual(tracker.ip_country, '') 128 | self.assertEqual(tracker.ip_region, '') 129 | self.assertEqual(tracker.ip_city, '') 130 | 131 | # And `GeoIP2` should have been never called. 132 | self.assertFalse(mock_geoip2().city.called) 133 | 134 | @mock.patch('tracking_analyzer.manager.GeoIP2') 135 | def test_create_from_request_django_geoip_exception(self, mock_geoip2): 136 | """ 137 | Tests Django ``contrib.gis.geoip2.GeoIP2Exception`` handling. 138 | """ 139 | mock_geoip2().city.side_effect = GeoIP2Exception 140 | 141 | tracker = Tracker.objects.create_from_request(self.request, self.post) 142 | 143 | # Now check the results. Empty data for IP address and GeoIP stuff. 144 | self.assertEqual(tracker.ip_address, '208.67.222.222') 145 | self.assertEqual(tracker.ip_country, '') 146 | self.assertEqual(tracker.ip_region, '') 147 | self.assertEqual(tracker.ip_city, '') 148 | 149 | @mock.patch('tracking_analyzer.manager.GeoIP2') 150 | def test_create_from_request_geoip2_exception(self, mock_geoip2): 151 | """ 152 | Tests Django ``geoip2.GeoIP2Error`` handling. 153 | """ 154 | mock_geoip2().city.side_effect = GeoIP2Error 155 | 156 | tracker = Tracker.objects.create_from_request(self.request, self.post) 157 | 158 | # Now check the results. Empty data for IP address and GeoIP stuff. 159 | self.assertEqual(tracker.ip_address, '208.67.222.222') 160 | self.assertEqual(tracker.ip_country, '') 161 | self.assertEqual(tracker.ip_region, '') 162 | self.assertEqual(tracker.ip_city, '') 163 | 164 | @mock.patch('tracking_analyzer.manager.GeoIP2') 165 | @mock.patch( 166 | 'user_agents.parsers.UserAgent.is_pc', new_callable=mock.PropertyMock) 167 | def test_create_from_request_is_pc(self, agent_mock, geoip2_mock): 168 | """ 169 | Tests the ``create_from_request`` method when the requesting device is 170 | a PC. 171 | """ 172 | # Mock the response from `GeoIP2.city()` method. 173 | geoip2_mock().city.return_value = { 174 | 'country_code': None, 175 | 'region': None, 176 | 'city': None 177 | } 178 | agent_mock.return_value = True 179 | 180 | tracker = Tracker.objects.create_from_request(self.request, self.post) 181 | 182 | self.assertEqual(tracker.device_type, Tracker.PC) 183 | 184 | @mock.patch('tracking_analyzer.manager.GeoIP2') 185 | @mock.patch( 186 | 'user_agents.parsers.UserAgent.is_mobile', 187 | new_callable=mock.PropertyMock) 188 | def test_create_from_request_is_mobile(self, agent_mock, geoip2_mock): 189 | """ 190 | Tests the ``create_from_request`` method when the requesting device is 191 | a mobile device. 192 | """ 193 | # Mock the response from `GeoIP2.city()` method. 194 | geoip2_mock().city.return_value = { 195 | 'country_code': None, 196 | 'region': None, 197 | 'city': None 198 | } 199 | agent_mock.return_value = True 200 | 201 | tracker = Tracker.objects.create_from_request(self.request, self.post) 202 | 203 | self.assertEqual(tracker.device_type, Tracker.MOBILE) 204 | 205 | @mock.patch('tracking_analyzer.manager.GeoIP2') 206 | @mock.patch( 207 | 'user_agents.parsers.UserAgent.is_tablet', 208 | new_callable=mock.PropertyMock) 209 | def test_create_from_request_is_tablet(self, agent_mock, geoip2_mock): 210 | """ 211 | Tests the ``create_from_request`` method when the requesting device is 212 | a tablet device. 213 | """ 214 | # Mock the response from `GeoIP2.city()` method. 215 | geoip2_mock().city.return_value = { 216 | 'country_code': None, 217 | 'region': None, 218 | 'city': None 219 | } 220 | agent_mock.return_value = True 221 | 222 | tracker = Tracker.objects.create_from_request(self.request, self.post) 223 | 224 | self.assertEqual(tracker.device_type, Tracker.TABLET) 225 | 226 | @mock.patch('tracking_analyzer.manager.GeoIP2') 227 | @mock.patch( 228 | 'user_agents.parsers.UserAgent.is_pc', new_callable=mock.PropertyMock) 229 | @mock.patch( 230 | 'user_agents.parsers.UserAgent.is_bot', new_callable=mock.PropertyMock) 231 | def test_create_from_request_is_bot(self, bot_mock, pc_mock, geoip2_mock): 232 | """ 233 | Tests the ``create_from_request`` method when the requesting device is 234 | a spider bot. 235 | """ 236 | # Mock the response from `GeoIP2.city()` method. 237 | geoip2_mock().city.return_value = { 238 | 'country_code': None, 239 | 'region': None, 240 | 'city': None 241 | } 242 | bot_mock.return_value = True 243 | pc_mock.return_value = False 244 | 245 | tracker = Tracker.objects.create_from_request(self.request, self.post) 246 | 247 | self.assertEqual(tracker.device_type, Tracker.BOT) 248 | 249 | @mock.patch('tracking_analyzer.manager.GeoIP2') 250 | @mock.patch( 251 | 'user_agents.parsers.UserAgent.is_pc', new_callable=mock.PropertyMock) 252 | @mock.patch( 253 | 'user_agents.parsers.UserAgent.is_mobile', 254 | new_callable=mock.PropertyMock) 255 | @mock.patch( 256 | 'user_agents.parsers.UserAgent.is_tablet', 257 | new_callable=mock.PropertyMock) 258 | @mock.patch( 259 | 'user_agents.parsers.UserAgent.is_bot', new_callable=mock.PropertyMock) 260 | def test_create_from_request_is_unknown( 261 | self, bot_mock, tablet_mock, mobile_mock, pc_mock, geoip2_mock 262 | ): 263 | """ 264 | Tests the ``create_from_request`` method when the requesting device is 265 | an unknown device. 266 | """ 267 | # Mock the response from `GeoIP2.city()` method. 268 | geoip2_mock().city.return_value = { 269 | 'country_code': None, 270 | 'region': None, 271 | 'city': None 272 | } 273 | 274 | bot_mock.return_value = False 275 | tablet_mock.return_value = False 276 | mobile_mock.return_value = False 277 | pc_mock.return_value = False 278 | 279 | tracker = Tracker.objects.create_from_request(self.request, self.post) 280 | 281 | self.assertEqual(tracker.device_type, Tracker.UNKNOWN) 282 | 283 | @mock.patch('tracking_analyzer.manager.GeoIP2') 284 | def test_create_from_request_wrong_user_agent(self, mock_geoip2): 285 | """ 286 | Tests the ``create_from_request`` method with a wrong user agent. 287 | """ 288 | # Mock the response from `GeoIP2.city()` method. 289 | mock_geoip2().city.return_value = { 290 | 'country_code': 'US', 291 | 'region': 'CA', 292 | 'city': 'San Francisco' 293 | } 294 | 295 | request = build_mock_request( 296 | '/testing/', 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxbot' 297 | ) 298 | 299 | tracker = Tracker.objects.create_from_request(request, self.post) 300 | 301 | self.assertEqual(tracker.browser, 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx') 302 | self.assertEqual(tracker.browser_version, '') 303 | self.assertEqual(tracker.device, 'Spider') 304 | self.assertEqual(tracker.device_type, Tracker.BOT) 305 | self.assertEqual(tracker.system, 'Other') 306 | self.assertEqual(tracker.system_version, '') 307 | self.assertEqual(tracker.ip_address, '208.67.222.222') 308 | self.assertEqual(tracker.ip_country, 'US') 309 | self.assertEqual(tracker.ip_region, 'CA') 310 | self.assertEqual(tracker.ip_city, 'San Francisco') 311 | self.assertEqual(tracker.object_id, self.post.pk) 312 | self.assertEqual(tracker.user, self.request.user) 313 | -------------------------------------------------------------------------------- /tests/urls.py: -------------------------------------------------------------------------------- 1 | from django.contrib import admin 2 | from django.contrib.staticfiles.urls import staticfiles_urlpatterns 3 | from django.urls import re_path 4 | 5 | 6 | admin.autodiscover() 7 | 8 | 9 | urlpatterns = [ 10 | re_path(r'^admin/', admin.site.urls), 11 | ] 12 | 13 | urlpatterns += staticfiles_urlpatterns() 14 | -------------------------------------------------------------------------------- /tests/utils.py: -------------------------------------------------------------------------------- 1 | from django.contrib.auth.models import User 2 | from django.test import RequestFactory 3 | from django.utils.functional import SimpleLazyObject 4 | 5 | from django_user_agents.utils import get_user_agent 6 | 7 | 8 | def build_mock_request(url, user_agent=None): 9 | """ 10 | Helper function to manually build a ``WSGIRequest`` object to be used 11 | to test the view. 12 | 13 | :param url: A string representing the URL for the request. 14 | :return: A prepared ``WSGIRequest`` object. 15 | """ 16 | # Build an interesting request. 17 | request = RequestFactory().get(url) 18 | request.COOKIES = { 19 | # Some silly cookies, just a PoC. 20 | 'company': 'MaykinMedia', 21 | 'worker': 'Jose', 22 | } 23 | 24 | request.META['HTTP_USER_AGENT'] = user_agent or ( 25 | 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 ' 26 | '(KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36' 27 | ) 28 | # Set up a known IP address to retrieve GeoIP data. This one is from 29 | # OpenDNS service, check https://www.opendns.com/ 30 | request.META['REMOTE_ADDR'] = '208.67.222.222' 31 | 32 | # Request is performed by a system user. 33 | request.user, _ = User.objects.get_or_create( 34 | username='test_user', 35 | first_name='Test', 36 | last_name='User', 37 | email='test_user@maykinmedia.nl' 38 | ) 39 | 40 | # Set up the 'django-user-agent' machinery in the request, as its own 41 | # middleware does. 42 | request.user_agent = SimpleLazyObject(lambda: get_user_agent(request)) 43 | 44 | return request 45 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = django{22,30} 3 | skip_missing_interpreters = true 4 | 5 | [testenv] 6 | deps= 7 | factory-boy==2.12.0 8 | psycopg2-binary 9 | pytest==5.4.3 10 | pytest-cov==2.10.0 11 | pytest-django==3.9.0 12 | pytest-pycodestyle==2.1.3 13 | pytest-pylint==0.14.1 14 | pytest-pythonpath==0.7.3 15 | pytest-runner==5.2 16 | django22: Django>=2.2,<2.3 17 | django30: Django>=3.0,<3.1 18 | commands= 19 | py.test \ 20 | --cov-report=xml \ 21 | --cov=tracking_analyzer \ 22 | --verbose \ 23 | --junit-xml=junit.xml \ 24 | --color=yes \ 25 | {posargs} 26 | -------------------------------------------------------------------------------- /tracking_analyzer/__init__.py: -------------------------------------------------------------------------------- 1 | default_app_config = 'tracking_analyzer.apps.TrackingAnalyzerAppConfig' 2 | -------------------------------------------------------------------------------- /tracking_analyzer/admin.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | from django.contrib import admin 4 | from django.db.models import Count 5 | from django.urls import reverse 6 | from django.utils.html import format_html 7 | 8 | from django_countries import countries 9 | 10 | from .utils import get_requests_count 11 | from .models import Tracker 12 | 13 | 14 | class TrackerAdmin(admin.ModelAdmin): 15 | date_hierarchy = 'timestamp' 16 | raw_id_fields = ['user'] 17 | readonly_fields = [ 18 | 'content_type', 'object_id', 'ip_address', 'ip_country', 'ip_region', 19 | 'ip_city', 'referrer', 'device_type', 'device', 'browser', 20 | 'browser_version', 'system', 'system_version', 'user' 21 | ] 22 | list_filter = [ 23 | ('timestamp', admin.DateFieldListFilter), 'device_type', 'content_type' 24 | ] 25 | list_display = [ 26 | 'details', 'content_object_link', 'timestamp', 'ip_address_link', 27 | 'ip_country_link', 'ip_city_link', 'user_link', 28 | ] 29 | ordering = ['-timestamp'] 30 | 31 | class Media: 32 | js = [ 33 | 'admin/js/vendor/d3/d3.min.js', 34 | 'admin/js/vendor/topojson/topojson.min.js', 35 | 'admin/js/vendor/datamaps/datamaps.world.min.js', 36 | 'admin/js/vendor/d3-tip/d3-tip.min.js' 37 | ] 38 | 39 | def details(self, obj): 40 | """ 41 | Define the 'Details' column rows display. 42 | """ 43 | return format_html('Details'.format( 44 | reverse('admin:tracking_analyzer_tracker_change', args=(obj.pk,)))) 45 | 46 | details.allow_tags = True 47 | details.short_description = 'Details' 48 | 49 | def content_object_link(self, obj): 50 | """ 51 | Define the 'Content Object' column rows display. 52 | """ 53 | return format_html( 54 | '' 55 | '{3}'.format( 56 | reverse('admin:tracking_analyzer_tracker_changelist'), 57 | obj.content_type.id, 58 | obj.object_id, 59 | obj 60 | ) 61 | ) 62 | 63 | content_object_link.allow_tags = True 64 | content_object_link.short_description = 'Content object' 65 | 66 | def ip_address_link(self, obj): 67 | """ 68 | Define the 'IP Address' column rows display. 69 | """ 70 | if obj.ip_address: 71 | return format_html( 72 | '{1}'.format( 73 | reverse('admin:tracking_analyzer_tracker_changelist'), 74 | obj.ip_address, 75 | ) 76 | ) 77 | 78 | return '-' 79 | 80 | ip_address_link.allow_tags = True 81 | ip_address_link.short_description = 'IP Address' 82 | 83 | def ip_country_link(self, obj): 84 | """ 85 | Define the 'IP Country' column rows display. 86 | """ 87 | if obj.ip_country: 88 | return format_html( 89 | '{2}'.format( 90 | reverse('admin:tracking_analyzer_tracker_changelist'), 91 | obj.ip_country, 92 | obj.ip_country.name 93 | ) 94 | ) 95 | 96 | return '-' 97 | 98 | ip_country_link.allow_tags = True 99 | ip_country_link.short_description = 'IP Country' 100 | 101 | def ip_city_link(self, obj): 102 | """ 103 | Define the 'IP City' column rows display. 104 | """ 105 | if obj.ip_city: 106 | return format_html( 107 | '{1}'.format( 108 | reverse('admin:tracking_analyzer_tracker_changelist'), 109 | obj.ip_city, 110 | ) 111 | ) 112 | 113 | return '-' 114 | 115 | ip_city_link.allow_tags = True 116 | ip_city_link.short_description = 'IP City' 117 | 118 | def user_link(self, obj): 119 | """ 120 | Define the 'User' column rows display. 121 | """ 122 | if obj.user: 123 | return format_html( 124 | '{2}'.format( 125 | reverse('admin:tracking_analyzer_tracker_changelist'), 126 | obj.user.pk, 127 | obj.user 128 | ) 129 | ) 130 | 131 | return 'Anonymous' 132 | 133 | user_link.allow_tags = True 134 | user_link.short_description = 'User' 135 | 136 | def has_add_permission(self, request): 137 | """ 138 | Overrides base ``has_add_permission`` method to block up any admin user 139 | create actions. ``Tracker`` instances are only data to be seen or 140 | deleted. 141 | """ 142 | return False 143 | 144 | def change_view(self, request, object_id, form_url='', extra_context=None): 145 | """ 146 | Overrides base ``change_view`` method to block up any admin user create 147 | or update actions. ``Tracker`` instances are only data to be seen or 148 | deleted. 149 | """ 150 | extra_context = extra_context or {} 151 | extra_context.update( 152 | { 153 | 'show_save_and_add_another': False, 154 | 'show_save_and_continue': False, 155 | 'show_save': False 156 | } 157 | ) 158 | 159 | return super(TrackerAdmin, self).change_view( 160 | request, object_id, form_url, extra_context=extra_context) 161 | 162 | def changelist_view(self, request, extra_context=None): 163 | """ 164 | Overrides base ``changelist_view`` method to add analytics datasets to 165 | the response. 166 | """ 167 | extra_context = extra_context or {} 168 | countries_count = [] 169 | response = super(TrackerAdmin, self).changelist_view( 170 | request, extra_context) 171 | 172 | if request.method == 'GET': 173 | # Get the current objects queryset to analyze data from it. 174 | queryset = response.context_data['cl'].queryset 175 | 176 | # Requests by country (when no filtering by country). 177 | if 'ip_country__exact' not in request.GET: 178 | trackers = queryset.values('ip_country').annotate( 179 | trackers=Count('id')).order_by() 180 | for track in trackers: 181 | countries_count.append( 182 | [countries.alpha3(track['ip_country']), 183 | track['trackers']] 184 | ) 185 | 186 | extra_context['countries_count'] = json.dumps(countries_count) 187 | 188 | # Requests by device (when not filtering by device). 189 | if 'device_type__exact' not in request.GET: 190 | devices_count = list(queryset.values('device_type').annotate( 191 | count=Count('id')).order_by()) 192 | 193 | extra_context['devices_count'] = json.dumps(devices_count) 194 | 195 | # Requests time line for the current page changelist. 196 | current_page = response.context_data['cl'].page_num 197 | current_pks = response.context_data['cl'].paginator.page( 198 | current_page + 1).object_list.values_list('pk', flat=True) 199 | 200 | current_results = get_requests_count( 201 | Tracker.objects.filter(pk__in=list(current_pks))) 202 | 203 | for item in current_results: 204 | item['date'] = '{date}T{hour:02d}:{minute:02d}'.format( 205 | date=item.pop('date'), 206 | hour=item.pop('hour'), 207 | minute=item.pop('minute') 208 | ) 209 | 210 | extra_context['requests_count'] = json.dumps(list(current_results)) 211 | 212 | response.context_data.update(extra_context) 213 | 214 | return response 215 | 216 | 217 | admin.site.register(Tracker, TrackerAdmin) 218 | -------------------------------------------------------------------------------- /tracking_analyzer/apps.py: -------------------------------------------------------------------------------- 1 | from django.apps import AppConfig 2 | from django.utils.translation import ugettext_lazy as _ 3 | 4 | 5 | class TrackingAnalyzerAppConfig(AppConfig): 6 | name = 'tracking_analyzer' 7 | verbose_name = _('Django Tracking Analyzer') 8 | 9 | def ready(self): 10 | # pylint: disable=import-outside-toplevel 11 | # pylint: disable=unused-import 12 | from . import conf 13 | -------------------------------------------------------------------------------- /tracking_analyzer/conf.py: -------------------------------------------------------------------------------- 1 | from django.conf import settings # pylint: disable=unused-import 2 | 3 | from appconf import AppConf 4 | 5 | 6 | class TrackingAnalyzerAppConf(AppConf): 7 | """ 8 | Configuration settings for Django Tracking Analyzer. 9 | 10 | - ``MAXMIND_URL``: The MaxMind datasets URL. 11 | - ``MAXMIND_COUNTRIES``: The file name of the MaxMind Country dataset. 12 | - ``MAXMIND_CITIES``: The file name of the MaxMind City dataset. 13 | """ 14 | MAXMIND_URL = "http://geolite.maxmind.com/download/geoip/database/" 15 | MAXMIND_COUNTRIES = "GeoLite2-Country.mmdb.gz" 16 | MAXMIND_CITIES = "GeoLite2-City.mmdb.gz" 17 | -------------------------------------------------------------------------------- /tracking_analyzer/management/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jose-lpa/django-tracking-analyzer/87208e080bab7082d8a9a4acad291ec2ea68a3a6/tracking_analyzer/management/__init__.py -------------------------------------------------------------------------------- /tracking_analyzer/management/commands/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jose-lpa/django-tracking-analyzer/87208e080bab7082d8a9a4acad291ec2ea68a3a6/tracking_analyzer/management/commands/__init__.py -------------------------------------------------------------------------------- /tracking_analyzer/management/commands/install_geoip_dataset.py: -------------------------------------------------------------------------------- 1 | import gzip 2 | from os.path import isfile, join, splitext 3 | from urllib.error import HTTPError, URLError 4 | from urllib.request import urlopen 5 | 6 | from django.conf import settings 7 | from django.core.management.base import BaseCommand, CommandError 8 | 9 | 10 | class Command(BaseCommand): 11 | help = 'Installs/updates the MaxMind(R) datasets. Plase check ' \ 12 | 'https://www.maxmind.com/ for more information.' 13 | 14 | def add_arguments(self, parser): 15 | parser.add_argument( 16 | '--url', 17 | help='Base URL where the MaxMind(R) datasets are available.' 18 | ' Optional, probably better not to use it.' 19 | ) 20 | parser.add_argument( 21 | '--countries', 22 | help='Remote file name for the MaxMind(R) Country dataset.' 23 | ' Optional, probably better not to use it.' 24 | ) 25 | parser.add_argument( 26 | '--cities', 27 | help='Remote file name for the MaxMind(R) City dataset.' 28 | ' Optional, probably better not to use it.' 29 | ) 30 | 31 | def user_input(self): 32 | """ 33 | Helper method to handle user input when required. 34 | """ 35 | if input('(y/n) ').lower() in ['y', 'yes']: 36 | return True 37 | 38 | return False 39 | 40 | def install_dataset(self, geoip_dir, mm_url, mm_dataset): 41 | """ 42 | Downloads the MaxMind datasets and unpacks it into the selected Django 43 | project ``GEOIP_PATH`` directory. 44 | 45 | :param geoip_dir: The directory where the GeoIP datasets live, set in 46 | the ``GEOIP_PATH`` Django project setting. 47 | :param mm_url: The URL where the dataset has to be retrieved from. 48 | :param mm_dataset: The name of the dataset file. 49 | """ 50 | url = '{0}{1}'.format(mm_url, mm_dataset) 51 | 52 | try: 53 | resource = urlopen(url) 54 | except (HTTPError, URLError) as error: 55 | self.stderr.write(str(error)) 56 | raise CommandError('Unable to download MaxMind dataset.') 57 | 58 | filename = join(geoip_dir, mm_dataset) 59 | 60 | with open(filename, 'wb') as file: 61 | metadata = resource.info() 62 | if hasattr(metadata, 'getheaders'): 63 | meta_func = metadata.getheaders 64 | else: 65 | meta_func = metadata.get_all 66 | 67 | meta_length = meta_func('Content-Length') 68 | file_size = None 69 | if meta_length: 70 | file_size = int(meta_length[0]) 71 | 72 | print("Downloading: {0} Bytes: {1}".format(url, file_size)) 73 | 74 | file_size_dl = 0 75 | block_sz = 8192 76 | while True: 77 | buffer = resource.read(block_sz) 78 | if not buffer: 79 | break 80 | 81 | file_size_dl += len(buffer) 82 | file.write(buffer) 83 | 84 | status = "{0:16}".format(file_size_dl) 85 | if file_size: 86 | status += " downloaded [{0:6.2f}%]".format( 87 | file_size_dl * 100 / file_size) 88 | status += chr(13) 89 | print(status, end="") 90 | print() 91 | 92 | self.stdout.write('Uncompressing downloaded dataset...') 93 | 94 | with gzip.open(filename, 'rb') as gzipped: 95 | with open(splitext(filename)[0], 'wb') as gunzipped: 96 | gunzipped.write(gzipped.read()) 97 | self.stdout.write( 98 | '{0} dataset installed and ready for use.'.format( 99 | splitext(filename)[0] 100 | ) 101 | ) 102 | 103 | def checkout_datasets(self, geoip_dir, url, datasets): 104 | for dataset in datasets: 105 | if isfile(join(geoip_dir, splitext(dataset)[0])): 106 | self.stdout.write( 107 | '\nSeems that MaxMind dataset {0} is already installed in ' 108 | '"{1}". Do you want to reinstall it?'.format( 109 | dataset, geoip_dir) 110 | ) 111 | 112 | if self.user_input() is True: 113 | self.stdout.write( 114 | 'Updating MaxMind {0} dataset...'.format(dataset)) 115 | self.install_dataset( 116 | geoip_dir, mm_url=url, mm_dataset=dataset) 117 | else: 118 | self.stdout.write( 119 | '{0} dataset should be ready.'.format(dataset)) 120 | else: 121 | self.stdout.write( 122 | 'Installing MaxMind {0} dataset...'.format(dataset)) 123 | self.install_dataset(geoip_dir, mm_url=url, mm_dataset=dataset) 124 | 125 | def handle(self, *args, **options): 126 | # Check `GEOIP_PATH` setting is ready. 127 | try: 128 | geoip_dir = getattr(settings, 'GEOIP_PATH') 129 | except AttributeError: 130 | raise CommandError('`GEOIP_PATH` setting not present. Unable to ' 131 | 'get the GeoIP dataset.') 132 | 133 | url = options.get('url') 134 | if not url: 135 | # Check `TRACKING_ANALYZER_MAXMIND_URL` setting is ready. 136 | try: 137 | url = getattr(settings, 'TRACKING_ANALYZER_MAXMIND_URL') 138 | except AttributeError: 139 | raise CommandError( 140 | '`TRACKING_ANALYZER_MAXMIND_URL` setting not present. ' 141 | 'Unable to get the GeoIP dataset.' 142 | ) 143 | 144 | countries = options.get('countries') 145 | if not countries: 146 | # Check `TRACKING_ANALYZER_MAXMIND_COUNTRIES` setting is ready. 147 | try: 148 | countries = getattr( 149 | settings, 'TRACKING_ANALYZER_MAXMIND_COUNTRIES') 150 | except AttributeError: 151 | raise CommandError( 152 | '`TRACKING_ANALYZER_MAXMIND_COUNTRIES` setting not ' 153 | 'present. Unable to get the GeoIP dataset.' 154 | ) 155 | 156 | cities = options.get('cities') 157 | if not cities: 158 | # Check `TRACKING_ANALYZER_MAXMIND_CITIES` setting is ready. 159 | try: 160 | cities = getattr( 161 | settings, 'TRACKING_ANALYZER_MAXMIND_CITIES') 162 | except AttributeError: 163 | raise CommandError( 164 | '`TRACKING_ANALYZER_MAXMIND_CITIES` setting not ' 165 | 'present. Unable to get the GeoIP dataset.' 166 | ) 167 | 168 | self.checkout_datasets(geoip_dir, url, [countries, cities]) 169 | -------------------------------------------------------------------------------- /tracking_analyzer/manager.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | from django.contrib.auth.models import User 4 | from django.contrib.gis.geoip2 import GeoIP2, GeoIP2Exception 5 | from django.db import models 6 | from django.http import HttpRequest 7 | 8 | from geoip2.errors import GeoIP2Error 9 | from ipware.ip import get_client_ip 10 | 11 | 12 | logger = logging.getLogger('tracking_analyzer') 13 | 14 | 15 | class TrackerManager(models.Manager): 16 | """ 17 | Custom ``Tracker`` model manager that implements a method to create a new 18 | object instance from an HTTP request. 19 | """ 20 | def create_from_request(self, request, content_object): 21 | """ 22 | Given an ``HTTPRequest`` object and a generic content, it creates a 23 | ``Tracker`` object to store the data of that request. 24 | 25 | :param request: A Django ``HTTPRequest`` object. 26 | :param content_object: A Django model instance. Any object can be 27 | related. 28 | :return: A newly created ``Tracker`` instance. 29 | """ 30 | # Sanity checks. 31 | assert isinstance(request, HttpRequest), \ 32 | '`request` object is not an `HTTPRequest`' 33 | assert issubclass(content_object.__class__, models.Model), \ 34 | '`content_object` is not a Django model' 35 | 36 | user = request.user 37 | user = user if isinstance(user, User) else None 38 | 39 | if request.user_agent.is_mobile: 40 | device_type = self.model.MOBILE 41 | elif request.user_agent.is_tablet: 42 | device_type = self.model.TABLET 43 | elif request.user_agent.is_pc: 44 | device_type = self.model.PC 45 | elif request.user_agent.is_bot: 46 | device_type = self.model.BOT 47 | else: 48 | device_type = self.model.UNKNOWN 49 | 50 | city = {} 51 | 52 | # Get the IP address and so the geographical info, if available. 53 | ip_address, _ = get_client_ip(request) or '' 54 | if not ip_address: 55 | logger.debug( 56 | 'Could not determine IP address for request %s', request) 57 | else: 58 | geo = GeoIP2() 59 | try: 60 | city = geo.city(ip_address) 61 | except (GeoIP2Error, GeoIP2Exception): 62 | logger.exception( 63 | 'Unable to determine geolocation for address %s', 64 | ip_address 65 | ) 66 | 67 | tracker = self.model.objects.create( 68 | content_object=content_object, 69 | ip_address=ip_address, 70 | ip_country=city.get('country_code', '') or '', 71 | ip_region=city.get('region', '') or '', 72 | ip_city=city.get('city', '') or '', 73 | referrer=request.META.get('HTTP_REFERER', ''), 74 | device_type=device_type, 75 | device=request.user_agent.device.family, 76 | browser=request.user_agent.browser.family[:30], 77 | browser_version=request.user_agent.browser.version_string, 78 | system=request.user_agent.os.family, 79 | system_version=request.user_agent.os.version_string, 80 | user=user 81 | ) 82 | logger.info( 83 | 'Tracked click in %s %s.', 84 | content_object._meta.object_name, content_object.pk 85 | ) 86 | 87 | return tracker 88 | -------------------------------------------------------------------------------- /tracking_analyzer/migrations/0001_initial.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Generated by Django 1.9 on 2016-05-14 17:20 3 | from __future__ import unicode_literals 4 | 5 | from django.conf import settings 6 | from django.db import migrations, models 7 | import django.db.models.deletion 8 | import django_countries.fields 9 | 10 | 11 | class Migration(migrations.Migration): 12 | 13 | initial = True 14 | 15 | dependencies = [ 16 | ('contenttypes', '0002_remove_content_type_name'), 17 | migrations.swappable_dependency(settings.AUTH_USER_MODEL), 18 | ] 19 | 20 | operations = [ 21 | migrations.CreateModel( 22 | name='Tracker', 23 | fields=[ 24 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), 25 | ('object_id', models.PositiveIntegerField()), 26 | ('timestamp', models.DateTimeField(auto_now_add=True)), 27 | ('ip_address', models.GenericIPAddressField(blank=True, null=True)), 28 | ('ip_country', django_countries.fields.CountryField(blank=True, max_length=2)), 29 | ('ip_region', models.CharField(blank=True, max_length=255)), 30 | ('ip_city', models.CharField(blank=True, max_length=255)), 31 | ('referrer', models.URLField(blank=True)), 32 | ('device_type', models.CharField(choices=[('pc', 'PC'), ('mobile', 'Mobile'), ('tablet', 'Tablet'), ('bot', 'Bot'), ('unknown', 'Unknown')], default='unknown', max_length=10)), 33 | ('device', models.CharField(blank=True, max_length=30)), 34 | ('browser', models.CharField(blank=True, max_length=30)), 35 | ('browser_version', models.CharField(blank=True, max_length=30)), 36 | ('system', models.CharField(blank=True, max_length=30)), 37 | ('system_version', models.CharField(blank=True, max_length=30)), 38 | ('content_type', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType')), 39 | ('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), 40 | ], 41 | options={ 42 | 'ordering': ('-timestamp',), 43 | }, 44 | ), 45 | ] 46 | -------------------------------------------------------------------------------- /tracking_analyzer/migrations/0002_auto_20160719_2212.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Generated by Django 1.9 on 2016-07-19 20:12 3 | from __future__ import unicode_literals 4 | 5 | from django.db import migrations 6 | 7 | 8 | class Migration(migrations.Migration): 9 | 10 | dependencies = [ 11 | ('tracking_analyzer', '0001_initial'), 12 | ] 13 | 14 | operations = [ 15 | migrations.AlterModelOptions( 16 | name='tracker', 17 | options={}, 18 | ), 19 | ] 20 | -------------------------------------------------------------------------------- /tracking_analyzer/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jose-lpa/django-tracking-analyzer/87208e080bab7082d8a9a4acad291ec2ea68a3a6/tracking_analyzer/migrations/__init__.py -------------------------------------------------------------------------------- /tracking_analyzer/models.py: -------------------------------------------------------------------------------- 1 | from django.conf import settings 2 | from django.contrib.contenttypes.fields import GenericForeignKey 3 | from django.contrib.contenttypes.models import ContentType 4 | from django.db import models 5 | 6 | from django_countries.fields import CountryField 7 | 8 | from .manager import TrackerManager 9 | 10 | 11 | class Tracker(models.Model): 12 | """ 13 | A generic tracker model, which can be related to any other model to track 14 | actions that involves it. 15 | """ 16 | PC = 'pc' 17 | MOBILE = 'mobile' 18 | TABLET = 'tablet' 19 | BOT = 'bot' 20 | UNKNOWN = 'unknown' 21 | DEVICE_TYPE = ( 22 | (PC, 'PC'), 23 | (MOBILE, 'Mobile'), 24 | (TABLET, 'Tablet'), 25 | (BOT, 'Bot'), 26 | (UNKNOWN, 'Unknown'), 27 | ) 28 | 29 | content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) 30 | object_id = models.PositiveIntegerField() 31 | content_object = GenericForeignKey('content_type', 'object_id') 32 | timestamp = models.DateTimeField(auto_now_add=True) 33 | ip_address = models.GenericIPAddressField(null=True, blank=True) 34 | ip_country = CountryField(blank=True) 35 | ip_region = models.CharField(max_length=255, blank=True) 36 | ip_city = models.CharField(max_length=255, blank=True) 37 | referrer = models.URLField(blank=True) 38 | device_type = models.CharField( 39 | max_length=10, 40 | choices=DEVICE_TYPE, 41 | default=UNKNOWN 42 | ) 43 | device = models.CharField(max_length=30, blank=True) 44 | browser = models.CharField(max_length=30, blank=True) 45 | browser_version = models.CharField(max_length=30, blank=True) 46 | system = models.CharField(max_length=30, blank=True) 47 | system_version = models.CharField(max_length=30, blank=True) 48 | user = models.ForeignKey( 49 | settings.AUTH_USER_MODEL, 50 | null=True, 51 | blank=True, 52 | on_delete=models.CASCADE 53 | ) 54 | 55 | objects = TrackerManager() 56 | 57 | def __str__(self): 58 | return '{0} :: {1}, {2}'.format( 59 | self.content_object, self.user, self.timestamp) 60 | -------------------------------------------------------------------------------- /tracking_analyzer/static/admin/css/d3-tip.css: -------------------------------------------------------------------------------- 1 | #devices-stats { 2 | font: 10px sans-serif; 3 | } 4 | 5 | .axis path, 6 | .axis line { 7 | fill: none; 8 | stroke: #000; 9 | shape-rendering: crispEdges; 10 | } 11 | 12 | .bar { 13 | fill: lightblue; 14 | } 15 | 16 | .bar:hover { 17 | fill: blue ; 18 | } 19 | 20 | .x.axis path { 21 | display: none; 22 | } 23 | 24 | .d3-tip { 25 | line-height: 1; 26 | font-weight: bold; 27 | padding: 12px; 28 | background: rgba(0, 0, 0, 0.8); 29 | color: #fff; 30 | border-radius: 2px; 31 | } 32 | 33 | /* Creates a small triangle extender for the tooltip */ 34 | .d3-tip:after { 35 | box-sizing: border-box; 36 | display: inline; 37 | font-size: 10px; 38 | width: 100%; 39 | line-height: 1; 40 | color: rgba(0, 0, 0, 0.8); 41 | content: "\25BC"; 42 | position: absolute; 43 | text-align: center; 44 | } 45 | 46 | /* Style northward tooltips differently */ 47 | .d3-tip.n:after { 48 | margin: -1px 0 0 0; 49 | top: 100%; 50 | left: 0; 51 | } -------------------------------------------------------------------------------- /tracking_analyzer/static/admin/css/main.css: -------------------------------------------------------------------------------- 1 | .stats-panel { 2 | overflow: hidden; 3 | width: 100%; 4 | } 5 | 6 | .stats-widget { 7 | float: left; 8 | text-align: center; 9 | } 10 | 11 | .graph-widget { 12 | font: 10px sans-serif; 13 | } 14 | 15 | .graph-widget .axis path, 16 | .graph-widget .axis line { 17 | fill: none; 18 | stroke: #000; 19 | shape-rendering: crispEdges; 20 | } 21 | 22 | .graph-widget .area { 23 | fill: steelblue; 24 | } -------------------------------------------------------------------------------- /tracking_analyzer/static/admin/js/devices_stats.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Requests per device statistics. 3 | * 4 | * Original code by Justin Palmer http://bl.ocks.org/Caged/6476579 5 | * 6 | * This script expects a `devices` var loaded with some JSON text in the 7 | * template stated before it is loaded. 8 | **/ 9 | 10 | var margin = {top: 40, right: 20, bottom: 30, left: 50}, 11 | width = 500 - margin.left - margin.right, 12 | height = 300 - margin.top - margin.bottom; 13 | 14 | var x = d3.scale.ordinal() 15 | .rangeRoundBands([0, width], .1); 16 | 17 | var y = d3.scale.linear() 18 | .range([height, 0]); 19 | 20 | var xAxis = d3.svg.axis() 21 | .scale(x) 22 | .orient("bottom"); 23 | 24 | var yAxis = d3.svg.axis() 25 | .scale(y) 26 | .orient("left"); 27 | 28 | var tip = d3.tip() 29 | .attr('class', 'd3-tip') 30 | .offset([-10, 0]) 31 | .html(function(d) { 32 | return "Requests: " + d.count + ""; 33 | }); 34 | 35 | var svg = d3.select("#devices-stats").append("svg") 36 | .attr("width", width + margin.left + margin.right) 37 | .attr("height", height + margin.top + margin.bottom) 38 | .append("g") 39 | .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); 40 | 41 | svg.call(tip); 42 | 43 | var data = JSON.parse(devices); 44 | 45 | x.domain(data.map(function(d) { return d.device_type; })); 46 | y.domain([0, d3.max(data, function(d) { return d.count; })]); 47 | 48 | svg.append("g") 49 | .attr("class", "x axis") 50 | .attr("transform", "translate(0," + height + ")") 51 | .call(xAxis); 52 | 53 | svg.append("g") 54 | .attr("class", "y axis") 55 | .call(yAxis) 56 | .append("text") 57 | .attr("transform", "rotate(-90)") 58 | .attr("y", 6) 59 | .attr("dy", ".71em") 60 | .style("text-anchor", "end"); 61 | 62 | svg.selectAll(".bar") 63 | .data(data) 64 | .enter().append("rect") 65 | .attr("class", "bar") 66 | .attr("x", function(d) { return x(d.device_type); }) 67 | .attr("width", x.rangeBand()) 68 | .attr("y", function(d) { return y(d.count); }) 69 | .attr("height", function(d) { return height - y(d.count); }) 70 | .on('mouseover', tip.show) 71 | .on('mouseout', tip.hide); 72 | 73 | function type(d) { 74 | d.count = +d.count; 75 | return d; 76 | } -------------------------------------------------------------------------------- /tracking_analyzer/static/admin/js/requests_graph.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Area chart to represent a time line of requests tracked. Code borrowed from 3 | * Mike Bostock http://bl.ocks.org/mbostock/3883195 4 | * 5 | * Licensed under GPLv3. 6 | **/ 7 | 8 | var margin = {top: 20, right: 20, bottom: 30, left: 50}, 9 | width = 960 - margin.left - margin.right, 10 | height = 200 - margin.top - margin.bottom; 11 | 12 | var parseDate = d3.time.format("%Y-%m-%dT%H:%M").parse; 13 | 14 | var x = d3.time.scale() 15 | .range([0, width]); 16 | 17 | var y = d3.scale.linear() 18 | .range([height, 0]); 19 | 20 | var xAxis = d3.svg.axis() 21 | .scale(x) 22 | .orient("bottom"); 23 | 24 | var yAxis = d3.svg.axis() 25 | .scale(y) 26 | .orient("left") 27 | .tickFormat(d3.format("d")); 28 | 29 | var area = d3.svg.area() 30 | .x(function(d) { return x(d.date); }) 31 | .y0(height) 32 | .y1(function(d) { return y(d.requests); }); 33 | 34 | var svg = d3.select("#requests-graph").append("svg") 35 | .attr("width", width + margin.left + margin.right) 36 | .attr("height", height + margin.top + margin.bottom) 37 | .append("g") 38 | .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); 39 | 40 | var data = JSON.parse(requests); 41 | 42 | data.forEach(function(d) { 43 | d.date = parseDate(d.date); 44 | d.requests = +d.requests; 45 | }); 46 | 47 | x.domain(d3.extent(data, function(d) { return d.date; })); 48 | y.domain([0, d3.max(data, function(d) { return d.requests; })]); 49 | 50 | svg.append("path") 51 | .datum(data) 52 | .attr("class", "area") 53 | .attr("d", area); 54 | 55 | svg.append("g") 56 | .attr("class", "x axis") 57 | .attr("transform", "translate(0," + height + ")") 58 | .call(xAxis); 59 | 60 | svg.append("g") 61 | .attr("class", "y axis") 62 | .call(yAxis) 63 | .append("text") 64 | .attr("transform", "rotate(-90)") 65 | .attr("y", 6) 66 | .attr("dy", ".71em") 67 | .style("text-anchor", "end") 68 | .text("Requests"); -------------------------------------------------------------------------------- /tracking_analyzer/static/admin/js/vendor/d3-tip/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | Copyright (c) 2013 Justin Palmer 3 | 4 | Permission is hereby granted, free of charge, to any person obtaining a copy of 5 | this software and associated documentation files (the "Software"), to deal in 6 | the Software without restriction, including without limitation the rights to 7 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 8 | the Software, and to permit persons to whom the Software is furnished to do so, 9 | subject to the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be included in all 12 | copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 16 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 17 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 18 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 19 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 20 | -------------------------------------------------------------------------------- /tracking_analyzer/static/admin/js/vendor/d3-tip/d3-tip.min.js: -------------------------------------------------------------------------------- 1 | !function(t,e){"function"==typeof define&&define.amd?define(["d3"],e):"object"==typeof module&&module.exports?module.exports=function(t){return t.tip=e(t),t.tip}:t.d3.tip=e(t.d3)}(this,function(t){return function(){function e(t){T=d(t),b=T.createSVGPoint(),document.body.appendChild(w)}function n(){return"n"}function r(){return[0,0]}function o(){return" "}function f(){var t=h();return{top:t.n.y-w.offsetHeight,left:t.n.x-w.offsetWidth/2}}function i(){var t=h();return{top:t.s.y,left:t.s.x-w.offsetWidth/2}}function l(){var t=h();return{top:t.e.y-w.offsetHeight/2,left:t.e.x}}function u(){var t=h();return{top:t.w.y-w.offsetHeight/2,left:t.w.x-w.offsetWidth}}function s(){var t=h();return{top:t.nw.y-w.offsetHeight,left:t.nw.x-w.offsetWidth}}function a(){var t=h();return{top:t.ne.y-w.offsetHeight,left:t.ne.x}}function c(){var t=h();return{top:t.sw.y,left:t.sw.x-w.offsetWidth}}function p(){var t=h();return{top:t.se.y,left:t.e.x}}function y(){var e=t.select(document.createElement("div"));return e.style({position:"absolute",top:0,opacity:0,"pointer-events":"none","box-sizing":"border-box"}),e.node()}function d(t){return t=t.node(),"svg"===t.tagName.toLowerCase()?t:t.ownerSVGElement}function m(){return null===w&&(w=y(),document.body.appendChild(w)),t.select(w)}function h(){for(var e=C||t.event.target;"undefined"==typeof e.getScreenCTM&&"undefined"===e.parentNode;)e=e.parentNode;var n={},r=e.getScreenCTM(),o=e.getBBox(),f=o.width,i=o.height,l=o.x,u=o.y;return b.x=l,b.y=u,n.nw=b.matrixTransform(r),b.x+=f,n.ne=b.matrixTransform(r),b.y+=i,n.se=b.matrixTransform(r),b.x-=f,n.sw=b.matrixTransform(r),b.y-=i/2,n.w=b.matrixTransform(r),b.x+=f,n.e=b.matrixTransform(r),b.x-=f/2,b.y-=i/2,n.n=b.matrixTransform(r),b.y+=i,n.s=b.matrixTransform(r),n}var x=n,v=r,g=o,w=y(),T=null,b=null,C=null;e.show=function(){var t=Array.prototype.slice.call(arguments);t[t.length-1]instanceof SVGElement&&(C=t.pop());var n,r=g.apply(this,t),o=v.apply(this,t),f=x.apply(this,t),i=m(),l=H.length,u=document.documentElement.scrollTop||document.body.scrollTop,s=document.documentElement.scrollLeft||document.body.scrollLeft;for(i.html(r).style({opacity:1,"pointer-events":"all"});l--;)i.classed(H[l],!1);return n=E.get(f).apply(this),i.classed(f,!0).style({top:n.top+o[0]+u+"px",left:n.left+o[1]+s+"px"}),e},e.hide=function(){var t=m();return t.style({opacity:0,"pointer-events":"none"}),e},e.attr=function(n,r){if(arguments.length<2&&"string"==typeof n)return m().attr(n);var o=Array.prototype.slice.call(arguments);return t.selection.prototype.attr.apply(m(),o),e},e.style=function(n,r){if(arguments.length<2&&"string"==typeof n)return m().style(n);var o=Array.prototype.slice.call(arguments);return t.selection.prototype.style.apply(m(),o),e},e.direction=function(n){return arguments.length?(x=null==n?n:t.functor(n),e):x},e.offset=function(n){return arguments.length?(v=null==n?n:t.functor(n),e):v},e.html=function(n){return arguments.length?(g=null==n?n:t.functor(n),e):g},e.destroy=function(){return w&&(m().remove(),w=null),e};var E=t.map({n:f,s:i,e:l,w:u,nw:s,ne:a,sw:c,se:p}),H=E.keys();return e}}); -------------------------------------------------------------------------------- /tracking_analyzer/static/admin/js/vendor/d3/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2010-2016, Michael Bostock 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, this 8 | list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright notice, 11 | this list of conditions and the following disclaimer in the documentation 12 | and/or other materials provided with the distribution. 13 | 14 | * The name Michael Bostock may not be used to endorse or promote products 15 | derived from this software without specific prior written permission. 16 | 17 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 18 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 19 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 20 | DISCLAIMED. IN NO EVENT SHALL MICHAEL BOSTOCK BE LIABLE FOR ANY DIRECT, 21 | INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 22 | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 23 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 24 | OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 25 | NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 26 | EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27 | -------------------------------------------------------------------------------- /tracking_analyzer/static/admin/js/vendor/datamaps/LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | Copyright (c) 2012 Mark DiMarco 3 | 4 | Permission is hereby granted, free of charge, to any person obtaining a copy of 5 | this software and associated documentation files (the "Software"), to deal in 6 | the Software without restriction, including without limitation the rights to 7 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies 8 | of the Software, and to permit persons to whom the Software is furnished to do 9 | so, subject to the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be included in all 12 | copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | SOFTWARE. -------------------------------------------------------------------------------- /tracking_analyzer/static/admin/js/vendor/topojson/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2012, Michael Bostock 2 | All rights reserved. 3 | 4 | Redistribution and use in source and binary forms, with or without 5 | modification, are permitted provided that the following conditions are met: 6 | 7 | * Redistributions of source code must retain the above copyright notice, this 8 | list of conditions and the following disclaimer. 9 | 10 | * Redistributions in binary form must reproduce the above copyright notice, 11 | this list of conditions and the following disclaimer in the documentation 12 | and/or other materials provided with the distribution. 13 | 14 | * The name Michael Bostock may not be used to endorse or promote products 15 | derived from this software without specific prior written permission. 16 | 17 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 18 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 19 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 20 | DISCLAIMED. IN NO EVENT SHALL MICHAEL BOSTOCK BE LIABLE FOR ANY DIRECT, 21 | INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 22 | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 23 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY 24 | OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 25 | NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 26 | EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -------------------------------------------------------------------------------- /tracking_analyzer/static/admin/js/vendor/topojson/topojson.min.js: -------------------------------------------------------------------------------- 1 | !function(){function t(n,t){function r(t){var r,e=n.arcs[0>t?~t:t],o=e[0];return n.transform?(r=[0,0],e.forEach(function(n){r[0]+=n[0],r[1]+=n[1]})):r=e[e.length-1],0>t?[r,o]:[o,r]}function e(n,t){for(var r in n){var e=n[r];delete t[e.start],delete e.start,delete e.end,e.forEach(function(n){o[0>n?~n:n]=1}),f.push(e)}}var o={},i={},u={},f=[],c=-1;return t.forEach(function(r,e){var o,i=n.arcs[0>r?~r:r];i.length<3&&!i[1][0]&&!i[1][1]&&(o=t[++c],t[c]=r,t[e]=o)}),t.forEach(function(n){var t,e,o=r(n),f=o[0],c=o[1];if(t=u[f])if(delete u[t.end],t.push(n),t.end=c,e=i[c]){delete i[e.start];var a=e===t?t:t.concat(e);i[a.start=t.start]=u[a.end=e.end]=a}else i[t.start]=u[t.end]=t;else if(t=i[c])if(delete i[t.start],t.unshift(n),t.start=f,e=u[f]){delete u[e.end];var s=e===t?t:e.concat(t);i[s.start=e.start]=u[s.end=t.end]=s}else i[t.start]=u[t.end]=t;else t=[n],i[t.start=f]=u[t.end=c]=t}),e(u,i),e(i,u),t.forEach(function(n){o[0>n?~n:n]||f.push([n])}),f}function r(n,r,e){function o(n){var t=0>n?~n:n;(s[t]||(s[t]=[])).push({i:n,g:a})}function i(n){n.forEach(o)}function u(n){n.forEach(i)}function f(n){"GeometryCollection"===n.type?n.geometries.forEach(f):n.type in l&&(a=n,l[n.type](n.arcs))}var c=[];if(arguments.length>1){var a,s=[],l={LineString:i,MultiLineString:u,Polygon:u,MultiPolygon:function(n){n.forEach(u)}};f(r),s.forEach(arguments.length<3?function(n){c.push(n[0].i)}:function(n){e(n[0].g,n[n.length-1].g)&&c.push(n[0].i)})}else for(var h=0,p=n.arcs.length;p>h;++h)c.push(h);return{type:"MultiLineString",arcs:t(n,c)}}function e(r,e){function o(n){n.forEach(function(t){t.forEach(function(t){(f[t=0>t?~t:t]||(f[t]=[])).push(n)})}),c.push(n)}function i(n){return l(u(r,{type:"Polygon",arcs:[n]}).coordinates[0])>0}var f={},c=[],a=[];return e.forEach(function(n){"Polygon"===n.type?o(n.arcs):"MultiPolygon"===n.type&&n.arcs.forEach(o)}),c.forEach(function(n){if(!n._){var t=[],r=[n];for(n._=1,a.push(t);n=r.pop();)t.push(n),n.forEach(function(n){n.forEach(function(n){f[0>n?~n:n].forEach(function(n){n._||(n._=1,r.push(n))})})})}}),c.forEach(function(n){delete n._}),{type:"MultiPolygon",arcs:a.map(function(e){var o=[];if(e.forEach(function(n){n.forEach(function(n){n.forEach(function(n){f[0>n?~n:n].length<2&&o.push(n)})})}),o=t(r,o),(n=o.length)>1)for(var u,c=i(e[0][0]),a=0;n>a;++a)if(c===i(o[a])){u=o[0],o[0]=o[a],o[a]=u;break}return o})}}function o(n,t){return"GeometryCollection"===t.type?{type:"FeatureCollection",features:t.geometries.map(function(t){return i(n,t)})}:i(n,t)}function i(n,t){var r={type:"Feature",id:t.id,properties:t.properties||{},geometry:u(n,t)};return null==t.id&&delete r.id,r}function u(n,t){function r(n,t){t.length&&t.pop();for(var r,e=s[0>n?~n:n],o=0,i=e.length;i>o;++o)t.push(r=e[o].slice()),a(r,o);0>n&&f(t,i)}function e(n){return n=n.slice(),a(n,0),n}function o(n){for(var t=[],e=0,o=n.length;o>e;++e)r(n[e],t);return t.length<2&&t.push(t[0].slice()),t}function i(n){for(var t=o(n);t.length<4;)t.push(t[0].slice());return t}function u(n){return n.map(i)}function c(n){var t=n.type;return"GeometryCollection"===t?{type:t,geometries:n.geometries.map(c)}:t in l?{type:t,coordinates:l[t](n)}:null}var a=g(n.transform),s=n.arcs,l={Point:function(n){return e(n.coordinates)},MultiPoint:function(n){return n.coordinates.map(e)},LineString:function(n){return o(n.arcs)},MultiLineString:function(n){return n.arcs.map(o)},Polygon:function(n){return u(n.arcs)},MultiPolygon:function(n){return n.arcs.map(u)}};return c(t)}function f(n,t){for(var r,e=n.length,o=e-t;o<--e;)r=n[o],n[o++]=n[e],n[e]=r}function c(n,t){for(var r=0,e=n.length;e>r;){var o=r+e>>>1;n[o]n&&(n=~n);var r=o[n];r?r.push(t):o[n]=[t]})}function r(n,r){n.forEach(function(n){t(n,r)})}function e(n,t){"GeometryCollection"===n.type?n.geometries.forEach(function(n){e(n,t)}):n.type in u&&u[n.type](n.arcs,t)}var o={},i=n.map(function(){return[]}),u={LineString:t,MultiLineString:r,Polygon:r,MultiPolygon:function(n,t){n.forEach(function(n){r(n,t)})}};n.forEach(e);for(var f in o)for(var a=o[f],s=a.length,l=0;s>l;++l)for(var h=l+1;s>h;++h){var p,v=a[l],g=a[h];(p=i[v])[f=c(p,g)]!==g&&p.splice(f,0,g),(p=i[g])[f=c(p,v)]!==v&&p.splice(f,0,v)}return i}function s(n,t){function r(n){u.remove(n),n[1][2]=t(n),u.push(n)}var e,o=g(n.transform),i=m(n.transform),u=v(),f=0;for(t||(t=h),n.arcs.forEach(function(n){var r=[];n.forEach(o);for(var i=1,f=n.length-1;f>i;++i)e=n.slice(i-1,i+2),e[1][2]=t(e),r.push(e),u.push(e);n[0][2]=n[f][2]=1/0;for(var i=0,f=r.length;f>i;++i)e=r[i],e.previous=r[i-1],e.next=r[i+1]});e=u.pop();){var c=e.previous,a=e.next;e[1][2]0;){var r=(t+1>>1)-1,o=e[r];if(p(n,o)>=0)break;e[o._=t]=o,e[n._=t=r]=n}}function t(n,t){for(;;){var r=t+1<<1,i=r-1,u=t,f=e[u];if(o>i&&p(e[i],f)<0&&(f=e[u=i]),o>r&&p(e[r],f)<0&&(f=e[u=r]),u===t)break;e[f._=t]=f,e[n._=t=u]=n}}var r={},e=[],o=0;return r.push=function(t){return n(e[t._=o]=t,o++),o},r.pop=function(){if(!(0>=o)){var n,r=e[0];return--o>0&&(n=e[o],t(e[n._=0]=n,0)),r}},r.remove=function(r){var i,u=r._;if(e[u]===r)return u!==--o&&(i=e[o],(p(i,r)<0?n:t)(e[i._=u]=i,u)),u},r}function g(n){if(!n)return y;var t,r,e=n.scale[0],o=n.scale[1],i=n.translate[0],u=n.translate[1];return function(n,f){f||(t=r=0),n[0]=(t+=n[0])*e+i,n[1]=(r+=n[1])*o+u}}function m(n){if(!n)return y;var t,r,e=n.scale[0],o=n.scale[1],i=n.translate[0],u=n.translate[1];return function(n,f){f||(t=r=0);var c=(n[0]-i)/e|0,a=(n[1]-u)/o|0;n[0]=c-t,n[1]=a-r,t=c,r=a}}function y(){}var d={version:"1.6.9",mesh:function(n){return u(n,r.apply(this,arguments))},meshArcs:r,merge:function(n){return u(n,e.apply(this,arguments))},mergeArcs:e,feature:o,neighbors:a,presimplify:s};"function"==typeof define&&define.amd?define(d):"object"==typeof module&&module.exports?module.exports=d:this.topojson=d}(); -------------------------------------------------------------------------------- /tracking_analyzer/static/admin/js/world_map.js: -------------------------------------------------------------------------------- 1 | /** 2 | * World map data rendering code from https://github.com/markmarkoh/datamaps 3 | * 4 | * Original code by Marc DiMarco. Licensed under MIT license. 5 | * 6 | * This script expects a `countries` var loaded with some JSON in the template 7 | * stated before it is loaded. 8 | **/ 9 | 10 | var dataset = {}; 11 | 12 | var onlyValues = countries.map(function(obj){ return obj[1]; }); 13 | var minValue = Math.min.apply(null, onlyValues), 14 | maxValue = Math.max.apply(null, onlyValues); 15 | 16 | var paletteScale = d3.scale.linear().domain([minValue,maxValue]).range(["#EFEFFF","#02386F"]); 17 | 18 | countries.forEach(function(item){ 19 | var iso = item[0]; 20 | var value = item[1]; 21 | dataset[iso] = { 22 | requestsPerCountry: value, 23 | fillColor: paletteScale(value) 24 | }; 25 | }); 26 | 27 | new Datamap({ 28 | element: document.getElementById('world-map'), 29 | projection: 'mercator', 30 | fills: { defaultFill: '#F5F5F5' }, 31 | data: dataset, 32 | geographyConfig: { 33 | borderColor: '#DEDEDE', 34 | highlightBorderWidth: 2, 35 | highlightFillColor: function(geo) { 36 | return geo['fillColor'] || '#F5F5F5'; 37 | }, 38 | highlightBorderColor: '#B7B7B7', 39 | popupTemplate: function(geo, data) { 40 | if (!data) { return ; } 41 | return ['
', 42 | '', geo.properties.name, '', 43 | '
Requests: ', data.requestsPerCountry, '', 44 | '
'].join(''); 45 | } 46 | } 47 | }); -------------------------------------------------------------------------------- /tracking_analyzer/templates/admin/tracking_analyzer/tracker/change_list.html: -------------------------------------------------------------------------------- 1 | {% extends "admin/change_list.html" %} 2 | {% load i18n admin_urls static admin_list %} 3 | 4 | {% block extrastyle %} 5 | {{ block.super }} 6 | 7 | 8 | {% endblock %} 9 | 10 | {% block pretitle %} 11 |
12 |
13 |
14 |
15 |
16 | {% endblock %} 17 | 18 | {% block result_list %} 19 | {# Countries statistics #} 20 | {% if countries_count %} 21 | 24 | 25 | {% endif %} 26 | 27 | {# Devices statistics #} 28 | {% if devices_count %} 29 | 32 | 33 | {% endif %} 34 | 35 | 38 | 39 | 40 | {{ block.super }} 41 | {% endblock %} -------------------------------------------------------------------------------- /tracking_analyzer/utils.py: -------------------------------------------------------------------------------- 1 | from django.db.models import Count 2 | from django.db.models.functions import TruncDate, Extract 3 | 4 | 5 | def get_requests_count(queryset): 6 | """ 7 | This function returns a list of dictionaries containing each one the 8 | requests count per minute of a certain ``Tracker``s queryset. 9 | 10 | :param queryset: A Django QuerySet of ``Tracker``s. 11 | :return: List of dictionaries with the requests count per minute. 12 | """ 13 | return queryset.annotate( 14 | date=TruncDate('timestamp'), 15 | hour=Extract('timestamp', 'hour'), 16 | minute=Extract('timestamp', 'minute') 17 | ).values( 18 | 'date', 'hour', 'minute' 19 | ).annotate(requests=Count('pk')) 20 | --------------------------------------------------------------------------------