├── .gitignore ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── phad ├── phad-simple-install.sh ├── phad.conf ├── requirements.txt └── templates ├── blank.j2 ├── clients.j2 ├── main.j2 ├── network.j2 ├── top_ads.j2 ├── top_clients.j2 └── top_domains.j2 /.gitignore: -------------------------------------------------------------------------------- 1 | phad.dat 2 | phad.pid 3 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Contributions are welcome, not just to the python code itself but also templates for different types of displays, better documentation, etc. If you plan to contribute, please: 4 | 5 | - Fork the repo and make a branch 6 | - Make any changes/additions on your local branch 7 | - Test! Test! Test! 8 | - Open a PR, preferably with an associated github issue with a detailed description of the contents of the PR 9 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # phad 2 | Pi-hole Alternative Display 3 | 4 | ### Quick Introduction 5 | 6 | While Pi-hole's chronometer is nice and other text/console displays are better, I still feel there was the potential for even more. Many of the displays that run chronometer, etc. are LCD touchscreens, yet the "touch" part isn't used. I also like having the ability to customize my Pi-hole display, so using templates for creating the display rather than hardcoding the display into a script also makes sense to me. phad combines support for touchscreens with python templates to let you display multiple screens of data by simply tapping on the screen. If you don't have a touchscreen then you can still have phad cycle between different screens at a rate you determine. 7 | 8 | phad's default screens are based on a 3x5" LCD screen and using the Terminus 8x14 console font. Examples of these screens include: 9 | 10 | ##### main page 11 | 12 | ![main page image](https://raw.githubusercontent.com/bpennypacker/images/master/phad/main.png) 13 | 14 | ##### top ads page 15 | 16 | ![top ads image](https://raw.githubusercontent.com/bpennypacker/images/master/phad/top_ads.png) 17 | 18 | ##### top domains page 19 | 20 | ![top domains image](https://raw.githubusercontent.com/bpennypacker/images/master/phad/top_domains.png) 21 | 22 | ##### top clients page 23 | 24 | ![top clients image](https://raw.githubusercontent.com/bpennypacker/images/master/phad/top_clients.png) 25 | 26 | 27 | ### Quick Installation 28 | 29 | The current version of phad requires Python 3. Prior to v0.4 phad required Python 2. If you currently only have Python 2 available to you then you can download v0.3 manually from https://github.com/bpennypacker/phad/releases/tag/v0.3 and follow its installation instructions. 30 | 31 | These following instructions assume you already have a Raspberry Pi configured with Pi-hole and a touchscreen display. As there are many options for hardware and software, any initial setup and configuration is beyond the scope of these instructions. 32 | 33 | If you have installed Pi-hole using their One-Step Automated Install, or if you installed it via their basic-install.sh shell script then you can use phad-simple-install.sh to install phad. This can be as smple as using this command in a shell on your Raspberry Pi: 34 | ``` 35 | curl -sSL https://raw.githubusercontent.com/bpennypacker/phad/master/phad-simple-install.sh | bash 36 | ``` 37 | 38 | Or you can manually download the installer script and run it that way: 39 | ``` 40 | wget https://raw.githubusercontent.com/bpennypacker/phad/master/phad-simple-install.sh 41 | bash phad-simple-install.sh 42 | ``` 43 | Or, to manually install phad: 44 | 45 | 1. Clone this repo using `git` or download and uncompress a release from the [releases page on GitHub](https://github.com/bpennypacker/phad/releases). 46 | 2. Install any missing Python 3 dependencies by invoking `/usr/bin/env python3 -m pip install -r requirements.txt` 47 | 3. Add the phad command to `~/.bashrc`: 48 | ``` 49 | if [ "$TERM" == "linux" ] ; then 50 | while : 51 | do 52 | # Run phad in touchscreen mode (the default) 53 | /home/pi/git/phad/phad 54 | 55 | # If you don't have a touchscreen or just want to cycle between screens every 10 seconds 56 | # then use this command instead: 57 | # /home/pi/git/phad/phad -s 10 58 | done 59 | fi 60 | ``` 61 | 4. reboot your pi 62 | 63 | Once your pi has rebooted it should display phad's main screen on your pi's display. Simply tap the touchscreen to cycle to other displays (or wait 10 seconds for the display to automatically cycle if you specified `-s 10`). The default phad configuration will show a summary page followed by pages that show the top ads, domains, and clients. 64 | 65 | By default (when `-s` is not specified) phad will revert back to the main summary page after 10 seconds. (The length of timeout can easily be changed or disabled via the phad.conf file.) 66 | 67 | ### Configuration 68 | 69 | phad reads the configuration file phad.conf that is located in the same directory as phad itself. This configuration file allows you to modify the appearance of variables used to render the phad screens and modify the behavior of phad itself. See the detailed comments in phad.conf for explainations of the various options. 70 | 71 | All variable formatting that is configurable via phad.conf is based on the "new style" of python formatting that can be found at https://pyformat.info 72 | 73 | The templates used to display each phad screen are located in the `templates` directory. These templates are standard Jinja2 templates. Jinja2 is a full featured template engine for Python, and its documentation can be found at http://jinja.pocoo.org/docs/templates/ 74 | 75 | Both Python variable formatting and Jinja2 templating are well beyond the scope of this README. Please refer to the above two project pages for detailed documnentation on both. 76 | 77 | ### Command Line Options 78 | 79 | Invoking `phad --help` will display a summary of command line options. Options are outlined below as well with a bit more detail. 80 | 81 | * -c [--config] configfile 82 | 83 | Load an alternate configuration file. By default phad will load the phad.conf that is found in the same directory as phad itself. 84 | 85 | * -s [--seconds] delay 86 | 87 | Run phad in "slideshow" mode, cycling through each screen on the display by ***delay*** seconds. 88 | 89 | 90 | * -t [--template] template_name 91 | 92 | Render the specified template and print it to stdout. This is handy when debugging/testing custom templates, etc. 93 | 94 | * -r [--readconf] 95 | 96 | When phad is invoked normally it will write it's process ID (PID) to a file specified in the phad.conf file. The ***--readconf*** option will send a signal to that process telling it to re-read the configuration file. This lets you SSH into a pi-hole server and make changes to the configuration of phad without having to reboot or do any other tricks to get it to start using the new configuration. 97 | 98 | * -j [--json] 99 | 100 | Dump all phad variables to stdout in a JSON structure. This lets you view all the variables that are available within the phad templates. 101 | 102 | * -i [--items] 103 | 104 | Dump a list of all the top-level variable names used by phad. Phad breaks down variables into logical groups, such as *top_ads*, *top_domains*, *host* (for host-specific data), *version* (for the version of pi-hole, it's components, etc) and so on. 105 | 106 | * -l [--list] item [item...[ 107 | 108 | Use `--list` along wtih `--json` to limit the JSON that is displayed by specifying one or more of the item names in the `--items` output. For example, use `--json --list top_ads` to see only the variable data associated with the top_ads set of data. 109 | 110 | * -d [--debug] 111 | 112 | Generate debugging output to stdout 113 | 114 | ### Upgrading to v0.4 115 | 116 | To upgrade to v0.4 simply download the phad script and place it where phad is currently installed. Or you can run the following commands. This will update the phad script itself but will not make any other changes to your environment 117 | 118 | ``` 119 | wget -c https://raw.githubusercontent.com/bpennypacker/phad/master/phad-simple-install.sh 120 | bash phad-simple-install.sh --upgrade 121 | ``` 122 | 123 | The following entries have been removed from phad.conf: 124 | 125 | * enable_main_timeout 126 | * main_timeout 127 | 128 | They have been replaced by a single new entry, `display_timeout`, that defaults to 30 seconds. 129 | 130 | If a touchscreen has a backlight then display_timeout is the number of seconds after the screen is last touched before the display is turned off. If a touchscreen does not have a backlight then the display will instead revert to the first template listed in the `templates` section of `phad.conf`. 131 | 132 | If the `-s` command line option is used then `display_timeout` is ignored. 133 | 134 | ### Tips and Tricks 135 | 136 | * To configure the font used by your Rasperry Pi's console run this command, and select the following settings. These are the settings that the default phad templates are designed to work with: 137 | ``` 138 | sudo dpkg-reconfigure console-setup 139 | 140 | Encodig: UTF-8 141 | Character set: Guess optimal character set 142 | Font for the connsole: Terminus 143 | Font Size: 8x14 144 | ``` 145 | 146 | * If your touchscreen does not support screen blanking or you are having trouble configuring it then an alternate approach is to use a blank template. It won't turn the touchscreen backlight off but it will still blank the screen. Edit the `templates` option in `phad.conf` and add the template `blank.j2` to the beginning of the list, then restart phad or tell it to re-read the configuration file via `./phad -r`. The `blank.j2` template simply clears the screen and does not print anything else. 147 | 148 | * To see a list of all the clients on your network that your pi-hole knows about and their hostnames if pi-hole knows about them as well, run `./pihole -t clients.j2`. The clients.j2 template simply dumps a list of all known client IP addresses and hostnames if known. 149 | 150 | * Template files are read in each time phad cycles to display a new template. If you are editing an existing template or creating a new one that you have already added to the `templates` option in `phad.conf` then simply tapping on your display to cycle through the templates is enough for phad to re-load it and display any changes that you have made. 151 | -------------------------------------------------------------------------------- /phad: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | # This program is free software: you can redistribute it and/or modify 5 | # it under the terms of the GNU General Public License as published by 6 | # the Free Software Foundation, either version 3 of the License, or 7 | # (at your option) any later version. 8 | # 9 | # This program is distributed in the hope that it will be useful, 10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | # GNU General Public License in the file LICENSE for more details. 13 | 14 | import os 15 | import sys 16 | import argparse 17 | import configparser 18 | import socket 19 | import json 20 | import datetime 21 | import time 22 | import re 23 | import jinja2 24 | import requests 25 | import signal 26 | import errno 27 | import shlex 28 | import struct 29 | from select import select 30 | from socket import error as socket_error 31 | from subprocess import Popen, PIPE 32 | from threading import Timer 33 | 34 | VERSION = "0.4.2" 35 | 36 | current_template_id = 0 37 | display_timeout = 0 38 | refresh_rate = 0 39 | config = None 40 | config_file_name = None 41 | templateEnv = None 42 | templates = None 43 | dev = None 44 | pid_file = None 45 | template_path = './' 46 | evdevInstalled = False 47 | 48 | backlight_enabled = False 49 | backlight_file = None 50 | backlight_sudo = True 51 | backlight_off = '1' 52 | backlight_on = '0' 53 | 54 | debug = False 55 | 56 | # ANSI foreground, background, and control colors 57 | Fore = { 58 | 'Black': u'\u001b[30m', 59 | 'Red': u'\u001b[31m', 60 | 'Green': u'\u001b[32m', 61 | 'Yellow': u'\u001b[33m', 62 | 'Blue': u'\u001b[34m', 63 | 'Magenta': u'\u001b[35m', 64 | 'Cyan': u'\u001b[36m', 65 | 'White': u'\u001b[37m', 66 | 'Bright_Red': u'\u001b[31;1m', 67 | 'Bright_Green': u'\u001b[32;1m', 68 | 'Bright_Yellow': u'\u001b[33;1m', 69 | 'Bright_Blue': u'\u001b[34;1m', 70 | 'Bright_Magenta': u'\u001b[35;1m', 71 | 'Bright_Cyan': u'\u001b[36;1m', 72 | 'Bright_White': u'\u001b[37;1m' 73 | } 74 | 75 | Back = { 76 | 'Black': u'\u001b[40m', 77 | 'Red': u'\u001b[41m', 78 | 'Green': u'\u001b[42m', 79 | 'Yellow': u'\u001b[43m', 80 | 'Blue': u'\u001b[44m', 81 | 'Magenta': u'\u001b[45m', 82 | 'Cyan': u'\u001b[46m', 83 | 'White': u'\u001b[47m', 84 | 'Bright_Red': u'\u001b[41;1m', 85 | 'Bright_Green': u'\u001b[42;1m', 86 | 'Bright_Yellow': u'\u001b[43;1m', 87 | 'Bright_Blue': u'\u001b[44;1m', 88 | 'Bright_Magenta': u'\u001b[45;1m', 89 | 'Bright_Cyan': u'\u001b[46;1m', 90 | 'Bright_White': u'\u001b[47;1m' 91 | } 92 | 93 | Ctl = { 94 | 'Reset': u'\u001b[0m', 95 | 'Bold': u'\u001b[1m', 96 | 'Underline': u'\u001b[4m', 97 | 'Reversed': u'\u001b[7m', 98 | 'Clear_Screen_End': u'\u001b[0J', # Cursor to end of screen 99 | 'Clear_Screen_Start': u'\u001b[1J', # Cursor to start of screen 100 | 'Clear_Screen': u'\u001b[2J', 101 | 'Clear_Line_End': u'\u001b[0K', # Cursor to end of line 102 | 'Clear_Line_Start': u'\u001b[1K', # Cursor to start of line 103 | 'Clear_Line': u'\u001b[2K', 104 | 'Home': u'\u001b[0;0H' 105 | } 106 | 107 | 108 | EOM = "---EOM---" # All FTL responses end with this 109 | 110 | args = None 111 | 112 | ############################################################################# 113 | 114 | def Warning(msg): 115 | if args.verbose: 116 | print ("{}Warning:{} {}".format(Fore['Bright_Red'], Ctl['Reset'], msg)) 117 | 118 | ############################################################################# 119 | 120 | def Debug(msg): 121 | if debug: 122 | with open("debug.log", "a") as f: 123 | f.write("{} {}".format(datetime.datetime.now().replace(microsecond=0).isoformat(), msg)) 124 | f.write("\n") 125 | 126 | ############################################################################# 127 | 128 | def run(cmd, timeout_sec = 30): 129 | proc = Popen(shlex.split(cmd), stdout=PIPE, stderr=PIPE) 130 | timer = Timer(timeout_sec, proc.kill) 131 | stdout = "" 132 | try: 133 | timer.start() 134 | stdout, stderr = proc.communicate() 135 | except: 136 | pass 137 | finally: 138 | timer.cancel() 139 | 140 | return stdout.decode().rstrip() 141 | 142 | ############################################################################# 143 | 144 | def create_bar_graph(percent, length, used_fill, free_fill, used_color, free_color): 145 | split = int((float(percent) / 100.0) * length) 146 | 147 | s = "" 148 | if used_color != None and split > 0: 149 | s += used_color 150 | 151 | for x in range (0, split): 152 | s += used_fill 153 | 154 | if free_color != None: 155 | s += free_color 156 | 157 | for x in range(split, length): 158 | s += free_fill 159 | 160 | if used_color != None or free_color != None: 161 | s += Ctl['Reset'] 162 | 163 | return s 164 | 165 | ############################################################################# 166 | 167 | def format_var(cfg, name, value): 168 | v = { 'value': value } 169 | 170 | if cfg.has_section(name): 171 | pass 172 | elif '/' in name: 173 | while '/' in name: 174 | name = name.rsplit('/', 1)[0] 175 | if cfg.has_section(name): 176 | break 177 | if name == '': 178 | return v 179 | else: 180 | return v 181 | 182 | if cfg.has_option(name, 'graph'): 183 | c = cfg.get(name, 'graph') 184 | length, uf, ff, uc, fc = (c.split(',') + [None] * 5)[:5] 185 | 186 | if length != None and int(length) > 0: 187 | used_fill = uf if uf else u'■' 188 | free_fill = ff if ff else u'■' 189 | 190 | if uc and uc in Fore: 191 | used_color = Fore[uc] 192 | else: 193 | used_color = Fore['Red'] 194 | 195 | if fc and fc in Fore: 196 | free_color = Fore[fc] 197 | else: 198 | free_color = Fore['Green'] 199 | 200 | v['graph'] = create_bar_graph(float(value), int(length), used_fill, free_fill, used_color, free_color) 201 | 202 | if cfg.has_option(name, 'int'): 203 | c = cfg.get(name, 'int') 204 | c = c.replace("\"","") 205 | v['int'] = c.format(int(value)) 206 | 207 | if cfg.has_option(name, 'float'): 208 | c = cfg.get(name, 'float') 209 | c = c.replace("\"","") 210 | v['float'] = c.format(float(value)) 211 | 212 | if cfg.has_option(name, 'str'): 213 | c = cfg.get(name, 'str') 214 | c = c.replace("\"","") 215 | v['str'] = c.format(str(value)) 216 | 217 | if cfg.has_option(name, 'strings'): 218 | s = cfg.get(name, 'strings') 219 | for i in s.split(','): 220 | if cfg.has_option(name, i): 221 | c = cfg.get(name, i) 222 | c = c.replace("\"","") 223 | if isinstance(value, list): 224 | v[i] = c.format(*value) 225 | elif isinstance(value, dict): 226 | v[i] = c.format(**value) 227 | else: 228 | v[i] = c.format(value) 229 | 230 | return v 231 | 232 | ############################################################################# 233 | 234 | def chomp(x): 235 | if x.endswith("\r\n"): return x[:-2] 236 | if x.endswith("\n") or x.endswith("\r"): return x[:-1] 237 | return x 238 | 239 | ############################################################################# 240 | 241 | def get_uptime(cfg): 242 | Debug('get_uptime()') 243 | 244 | with open('/proc/uptime', 'r') as f: 245 | uptime_seconds = int(f.readline().split()[0].split('.', 1)[0]) 246 | 247 | days = ( uptime_seconds // ( 24 * 3600 )) 248 | hours = ( uptime_seconds % ( 24 * 3600 )) // 3600 249 | minutes = ( uptime_seconds % 3600 // 60 ) 250 | seconds = uptime_seconds % 60 251 | 252 | uptime = { 'days': days, 'hours': hours, 'minutes': minutes, 'seconds': seconds, 'total_seconds': uptime_seconds } 253 | 254 | formatted = format_var(config, 'uptime', uptime) 255 | 256 | for i in formatted: 257 | if i != 'value': 258 | uptime[i] = formatted[i] 259 | 260 | return uptime 261 | 262 | ############################################################################# 263 | 264 | def get_pihole_results(client, command, maxsplit=-1): 265 | Debug('get_pihole_results({})'.format(command)) 266 | 267 | while True: 268 | cmd = '>{}\n'.format(command) 269 | client.send(cmd.encode()) 270 | results = "" 271 | try: 272 | while True: 273 | r = client.recv(1024).decode() 274 | results += r 275 | if EOM in r: 276 | break 277 | except socket_error as serr: 278 | if serr.errno == errno.EINTR: 279 | results = "" 280 | pass 281 | 282 | if results != "": 283 | break 284 | 285 | results = results.split(EOM, 1)[0].strip() 286 | 287 | t = [] 288 | for i in results.splitlines(): 289 | t.append(tuple(i.split(' ', maxsplit))) 290 | 291 | return t 292 | 293 | ############################################################################# 294 | # Get public IP address 295 | 296 | def get_public_ip(cfg): 297 | Debug('get_public_ip()') 298 | 299 | # originally external_ip_url was just a single url. Now it can be a list 300 | # of urls to query. If the first url throws an error then try the next, 301 | # and so on until we get a valid response 302 | 303 | if not cfg.has_option('main', 'external_ip_url'): 304 | return "unknown" 305 | 306 | urllist = cfg.get('main', 'external_ip_url').split(',') 307 | 308 | for url in urllist: 309 | Debug('Querying {} for public IP'.format(url)) 310 | try: 311 | response = requests.get(url) 312 | return response.text 313 | except: 314 | pass 315 | 316 | return "unknown" 317 | 318 | ############################################################################# 319 | # Fetched timed data once every 24 hours 320 | 321 | def get_timed_data(cfg, data): 322 | Debug('get_timed_data()') 323 | 324 | if cfg.has_option('main', 'data_file'): 325 | version_file = cfg.get('main', 'data_file') 326 | else: 327 | version_file = '/tmp/pihole.dat' 328 | 329 | d = {} 330 | t = int(time.time() / 60 / 60 / 24) 331 | 332 | if os.path.exists(version_file) and os.path.isfile(version_file): 333 | Debug('read {}'.format(version_file)) 334 | with open(version_file, "r") as f: 335 | for line in f: 336 | (key, val) = chomp(line).split("=") 337 | d[key] = val 338 | 339 | if 'last_check' not in d or int(d['last_check']) < t: 340 | Debug(' do last_check') 341 | 342 | phad_version = "unknown" 343 | try: 344 | url = "https://github.com/bpennypacker/phad/releases/latest" 345 | response = requests.get(url, allow_redirects=False) 346 | if 'Location' in response.headers: 347 | sp = response.headers['Location'].split('/') 348 | if sp[-2] == 'tag': 349 | phad_version = "{}".format(sp[-1]) 350 | except Exception as e: 351 | pass 352 | 353 | d['phad_latest'] = phad_version 354 | 355 | # Check git & hashes if desired 356 | if cfg.has_option('main', 'git_update_version_check') and cfg.getboolean('main', 'git_update_version_check') == True: 357 | 358 | if cfg.has_option('main', 'git_repo'): 359 | git_repo = cfg.get('main', 'git_repo') 360 | else: 361 | git_repo = '/etc/.pihole' 362 | 363 | if cfg.has_option('main', 'git_sudo'): 364 | git_sudo = cfg.getboolean('main', 'git_sudo') 365 | else: 366 | git_sudo = True 367 | 368 | git_cmd = "{}git -C {} remote update".format( "sudo " if git_sudo else "", git_repo) 369 | 370 | results = run(git_cmd) 371 | 372 | pattern = re.compile('.* (version|hash) is (.*) \(Latest: (.*)\)') 373 | 374 | if cfg.has_option('main', 'use_version_hashes'): 375 | use_version_hashes = cfg.getboolean('main', 'use_version_hashes') 376 | else: 377 | use_version_hashes = False 378 | 379 | cmd = "pihole -v -p" 380 | if use_version_hashes: 381 | cmd += " --hash" 382 | 383 | results = run(cmd) 384 | Debug('{}: [{}]'.format(cmd, results)) 385 | 386 | if 'not applicable' in results: 387 | d['pihole'] = "N/A" 388 | d['piholeLatest'] = "N/A" 389 | else: 390 | match = pattern.search(results) 391 | if match: 392 | d['pihole'] = match.group(2) 393 | d['piholeLatest'] = match.group(3) 394 | else: 395 | d['pihole'] = "unknown" 396 | d['piholeLatest'] = "unknown" 397 | 398 | cmd = "pihole -v -a" 399 | if use_version_hashes: 400 | cmd += " --hash" 401 | 402 | results = run(cmd) 403 | Debug('{}: [{}]'.format(cmd, results)) 404 | 405 | if 'not applicable' in results: 406 | d['web'] = "N/A" 407 | d['webLatest'] = "N/A" 408 | else: 409 | match = pattern.search(results) 410 | if match: 411 | d['web'] = match.group(2) 412 | d['webLatest'] = match.group(3) 413 | else: 414 | d['web'] = "unknown" 415 | d['webLatest'] = "unknown" 416 | 417 | cmd = "pihole -v -f" 418 | if use_version_hashes: 419 | cmd += " --hash" 420 | 421 | results = run(cmd) 422 | Debug('{}: [{}]'.format(cmd, results)) 423 | 424 | if 'not applicable' in results: 425 | d['ftl'] = "N/A" 426 | d['ftlLatest'] = "N/A" 427 | else: 428 | match = pattern.search(results) 429 | if match: 430 | d['ftl'] = match.group(2) 431 | d['ftlLatest'] = match.group(3) 432 | else: 433 | d['ftl'] = "unknown" 434 | d['ftlLatest'] = "unknown" 435 | 436 | if cfg.has_option('main', 'get_external_ip') and cfg.getboolean('main', 'get_external_ip') == True: 437 | d['public_ip'] = get_public_ip(cfg) 438 | 439 | 440 | d['last_check'] = t 441 | 442 | with open(version_file, "w") as f: 443 | for k in d: 444 | f.write("{}={}\n".format(k, d[k])) 445 | 446 | pihole = { 'pihole' : d['pihole'], 'web': d['web'], 'FTL': d['ftl'], 'phad': "v{}".format(VERSION) } 447 | latest = { 'pihole' : d['piholeLatest'], 'web': d['webLatest'], 'FTL': d['ftlLatest'], 'phad': d['phad_latest'] } 448 | 449 | pihole_up_to_date = ( pihole['pihole'] == latest['pihole'] ) 450 | web_up_to_date = ( pihole['web'] == latest['web'] ) 451 | ftl_up_to_date = ( pihole['FTL'] == latest['FTL'] ) 452 | phad_up_to_date = ( pihole['phad'] == latest['phad'] ) 453 | 454 | all_up_to_date = pihole_up_to_date and web_up_to_date and ftl_up_to_date and phad_up_to_date 455 | 456 | for i in pihole: 457 | pihole[i] = format_var(cfg, 'version/current', pihole[i]) 458 | 459 | for i in latest: 460 | latest[i] = format_var(cfg, 'version/latest', latest[i]) 461 | 462 | results = { 463 | 'all_up_to_date': all_up_to_date, 464 | 'pihole_up_to_date': pihole_up_to_date, 465 | 'web_up_to_date': web_up_to_date, 466 | 'ftl_up_to_date': ftl_up_to_date, 467 | 'phad_up_to_date': phad_up_to_date, 468 | 'current': pihole, 469 | 'latest': latest 470 | } 471 | 472 | if 'public_ip' in d: 473 | data['host']['public_ip'] = d['public_ip'] 474 | 475 | data['version'] = results 476 | 477 | ############################################################################# 478 | def ip2long(ip): 479 | try: 480 | return struct.unpack('!I', socket.inet_pton(socket.AF_INET, ip))[0] 481 | except socket.error: 482 | try: 483 | hi, lo = struct.unpack('!QQ', socket.inet_pton(socket.AF_INET6, ip)) 484 | return (hi << 64) | lo 485 | except socket.error: 486 | return 0 487 | 488 | ############################################################################# 489 | # Commands from https://github.com/pi-hole/FTL 490 | def query_pihole(cfg): 491 | Debug('query_pihole') 492 | 493 | data = {} 494 | 495 | retries = 10 496 | 497 | client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 498 | 499 | while True: 500 | try: 501 | client.connect(("localhost", 4711)) 502 | break 503 | except socket.error as e: 504 | retries -= 1 505 | if retries <= 0: 506 | print ("Unable to communicate with pihole. Aborting.") 507 | sys.exit(1) 508 | time.sleep(1) 509 | 510 | client.settimeout(10) 511 | 512 | d = dict(get_pihole_results(client, 'stats')) 513 | 514 | try: 515 | d['latest-blocked'] = get_pihole_results(client, 'recentBlocked')[0][0] 516 | except: 517 | d['latest-blocked'] = 'none' 518 | 519 | for i in d: 520 | d[i] = format_var(cfg, 'stats/' + i, d[i]) 521 | 522 | data['stats'] = d 523 | 524 | top_domains_max = 10 525 | if cfg.has_option('main', 'top_domains_max'): 526 | try: 527 | top_domains_max = cfg.getint('main', 'top_domains_max') 528 | except: 529 | pass 530 | 531 | results = get_pihole_results(client, 'top-domains ({})'.format(top_domains_max)) 532 | 533 | data['top_domains'] = [] 534 | 535 | for r in results: 536 | if len(r): 537 | res = { 'rank': int(r[0]) + 1, 'hits': int(r[1]), 'url': r[2] } 538 | for rr in res: 539 | res[rr] = format_var(cfg, 'top/domains/' + rr, res[rr]) 540 | data['top_domains'].append(res) 541 | 542 | top_ads_max = 10 543 | if cfg.has_option('main', 'top_ads_max'): 544 | try: 545 | top_ads_max = cfg.getint('main', 'top_ads_max') 546 | except: 547 | pass 548 | 549 | results = get_pihole_results(client, 'top-ads ({})'.format(top_ads_max)) 550 | 551 | data['top_ads'] = [] 552 | 553 | for r in results: 554 | if len(r): 555 | res = { 'rank': int(r[0]) + 1, 'hits': int(r[1]), 'url': r[2] } 556 | for rr in res: 557 | res[rr] = format_var(cfg, 'top/ads/' + rr, res[rr]) 558 | data['top_ads'].append(res) 559 | 560 | top_clients_max = 10 561 | if cfg.has_option('main', 'top_clients_max'): 562 | try: 563 | top_clients_max = cfg.getint('main', 'top_clients_max') 564 | except: 565 | pass 566 | 567 | results = get_pihole_results(client, 'top-clients ({})'.format(top_clients_max)) 568 | 569 | data['top_clients'] = [] 570 | 571 | for r in results: 572 | if len(r) >= 4: 573 | res = { 'rank': int(r[0]) + 1, 'requests': int(r[1]), 'IP': r[2], 'hostname': r[3] } 574 | for rr in res: 575 | res[rr] = format_var(cfg, 'top/clients/' + rr, res[rr]) 576 | data['top_clients'].append(res) 577 | 578 | data['forward_dest'] = get_pihole_results(client, 'forward-dest') 579 | 580 | d = [] 581 | results = get_pihole_results(client, 'querytypes') 582 | for r in results: 583 | res = { 'type': r[0].replace(':', ''), 'value': r[-1] } 584 | for rr in res: 585 | res[rr] = format_var(cfg, 'querytypes/' + rr, res[rr]) 586 | d.append(res) 587 | 588 | data['querytypes'] = d 589 | 590 | d = {} 591 | results = get_pihole_results(client, 'client-names') 592 | for r in results: 593 | if len(r) == 2: 594 | d[r[1]] = r[0] 595 | 596 | data['client_names'] = d 597 | 598 | d = [] 599 | for k in sorted(data['client_names'].keys(), key = ip2long): 600 | res = { 'IP': k, 'host': data['client_names'][k] } 601 | for rr in res: 602 | res[rr] = format_var(cfg, 'client_names/' + rr, res[rr]) 603 | d.append(res) 604 | 605 | data['client_names_sorted'] = d 606 | 607 | client.send('>quit\n'.encode()) 608 | client.close() 609 | 610 | status = {} 611 | 612 | try: 613 | results = run('pihole status web') 614 | if len(results): 615 | s = int(results) 616 | else: 617 | s = 2 618 | 619 | if s == 1: 620 | status['pihole'] = "Running" 621 | elif s == 0: 622 | status['pihole'] = "Offline" 623 | elif s == -1: 624 | status['pihole'] = "DNS Offline" 625 | else: 626 | status['pihole'] = "Unknown" 627 | except: 628 | status['pihole'] = "Error" 629 | 630 | try: 631 | results = run('pidof -s pihole-FTL') 632 | if len(results): 633 | s = int(results) 634 | else: 635 | s = 0 636 | 637 | if s == 0: 638 | status['ftl'] = "Not Running" 639 | else: 640 | status['ftl'] = "Running" 641 | except: 642 | status['ftl'] = "Not running" 643 | 644 | for i in status: 645 | status[i] = format_var(cfg, 'status/' + i, status[i]) 646 | 647 | systemp = '/sys/class/thermal/thermal_zone0/temp' 648 | raw_temp = 0 649 | if os.path.exists(systemp): 650 | try: 651 | with open(systemp, 'r') as f: 652 | raw_temp = int(f.readline()) 653 | except: 654 | pass 655 | 656 | temp = { 'raw' : raw_temp, 'F': float(raw_temp) * 9 / 5000 + 32, 'C': float(raw_temp) / 1000, 'K': float(raw_temp) / 1000 + 273.15 } 657 | 658 | for t in temp: 659 | temp[t] = format_var(cfg, 'status/temp/' + t, temp[t]) 660 | 661 | status['temp'] = temp 662 | 663 | data['status'] = status 664 | 665 | return data 666 | 667 | 668 | ############################################################################# 669 | 670 | def get_host_data(cfg): 671 | Debug('get_host_data()') 672 | 673 | data = {} 674 | mem = {} 675 | 676 | data['hostname'] = socket.gethostname() 677 | 678 | fqdn = socket.getfqdn().split('.', 1) 679 | if len(fqdn) > 1: 680 | data['domainname'] = fqdn[1] 681 | else: 682 | data['domainname'] = "" 683 | 684 | data['loadavg'] = os.getloadavg() 685 | 686 | data['pid'] = os.getpid() 687 | 688 | results = run('nproc') 689 | if len(results): 690 | data['numprocs'] = int(results) 691 | else: 692 | msg = "Unexpected result from nproc [{}]. Assuming 1 processor.".format(results) 693 | Warning(msg) 694 | Devug(msg) 695 | data['numprocs'] = 1 696 | 697 | data['cpuload'] = data['loadavg'][0] / data['numprocs'] * 100 698 | 699 | for i in data: 700 | data[i] = format_var(cfg, 'host/' + i, data[i]) 701 | 702 | with open('/proc/meminfo', 'rt') as f: 703 | meminfo = {} 704 | for i in f.read().splitlines(): 705 | try: 706 | name, val = i.split(':') 707 | meminfo[name.strip()] = int(val.split()[0]) 708 | except: 709 | pass 710 | 711 | memfree = meminfo['MemFree'] + meminfo['Buffers'] + meminfo['Cached'] 712 | 713 | mem['free'] = memfree 714 | mem['total'] = meminfo['MemTotal'] 715 | mem['percent'] = float(int(meminfo['MemTotal']) - int(memfree)) / float(meminfo['MemTotal']) * 100 716 | 717 | for i in mem: 718 | mem[i] = format_var(cfg, 'memory/' + i, mem[i]) 719 | 720 | data['system-memory'] = mem 721 | 722 | return data 723 | 724 | ############################################################################# 725 | 726 | def get_setupvars(cfg): 727 | Debug('get_setupvars()') 728 | 729 | data = {} 730 | 731 | with open('/etc/pihole/setupVars.conf', 'r') as f: 732 | for l in f: 733 | if '=' in l and l[0] != '#': 734 | k, v = chomp(l).split('=') 735 | if 'PASSWORD' not in k: 736 | data[k] = v 737 | 738 | for i in data: 739 | data[i] = format_var(cfg, 'host/' + i, data[i]) 740 | 741 | return data 742 | 743 | ############################################################################# 744 | 745 | def fetch_datetime(cfg): 746 | Debug('fetch_datetime()') 747 | 748 | dt = datetime.datetime.now() 749 | date_list = [dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second] 750 | 751 | data = { 'YYMMDDHHMMSS': date_list } 752 | 753 | if cfg.has_option('datetime', 'formatted'): 754 | s = cfg.get('datetime', 'formatted') 755 | for i in s.split(','): 756 | if cfg.has_option('datetime', i): 757 | c = cfg.get('datetime', i) 758 | c = c.replace("\"","") 759 | data[i] = dt.strftime(c) 760 | 761 | for i in data: 762 | data[i] = format_var(cfg, 'datetime/' + i, data[i]) 763 | 764 | return data 765 | 766 | ############################################################################# 767 | 768 | def fetch_data(cfg): 769 | Debug('fetch_data()') 770 | 771 | data = query_pihole(config) 772 | 773 | data['ANSI'] = { 'Fore': Fore, 'Back': Back, 'Ctl': Ctl } 774 | 775 | data['uptime'] = get_uptime(config) 776 | 777 | data['datetime'] = fetch_datetime(config) 778 | 779 | data['host'] = get_host_data(config) 780 | 781 | data['setupvars'] = get_setupvars(config) 782 | 783 | get_timed_data(config, data) 784 | 785 | return data 786 | 787 | ############################################################################# 788 | 789 | def load_config(enable_touchscreen): 790 | global display_timeout 791 | global refresh_rate 792 | global config 793 | global config_file_name 794 | global templateEnv 795 | global templates 796 | global template_path 797 | global dev 798 | 799 | Debug('load_config({})'.format(enable_touchscreen)) 800 | 801 | try: 802 | config.read(config_file_name) 803 | except Exception as e: 804 | print (e) 805 | sys.exit(1) 806 | 807 | if config.has_option('main', 'display_timeout'): 808 | display_timeout = config.getint('main', 'display_timeout') 809 | else: 810 | display_timeout = 30 811 | 812 | if config.has_option('main', 'refresh_rate'): 813 | refresh_rate = config.getint('main', 'refresh_rate') 814 | else: 815 | refresh_rate = 60 816 | 817 | if config.has_option('main', 'template_path'): 818 | template_path = config.get('main', 'template_path') 819 | 820 | templateLoader = jinja2.FileSystemLoader(searchpath = template_path) 821 | templateEnv = jinja2.Environment(loader=templateLoader) 822 | 823 | templates = config.get('main', 'templates').split(',') 824 | 825 | if evdevInstalled == True and config.has_option('main', 'input_device'): 826 | input_device = config.get('main', 'input_device') 827 | if os.path.exists(input_device): 828 | if enable_touchscreen == True: 829 | try: 830 | dev = InputDevice(input_device) 831 | except Exception as e: 832 | Warning("Unable to open input device '{}{}{}'. {}".format(Fore['Cyan'], input_device, Ctl['Reset'], str(e))) 833 | time.sleep(10) 834 | dev = None 835 | else: 836 | Warning("input_device '{}{}{}' not found. Will not respond to screen touches. To suppress this warning comment out input_device in phad.conf.".format(Fore['Cyan'], input_device, Ctl['Reset'])) 837 | time.sleep(10) 838 | 839 | ############################################################################# 840 | 841 | def signal_handler(sig, stack): 842 | if sig == signal.SIGHUP: 843 | load_config(True) 844 | return 845 | elif sig == signal.SIGALRM: 846 | Debug("SIGALRM") 847 | signal.alarm(0) 848 | if backlight_enabled == True: 849 | display_power(backlight_off) 850 | return 851 | elif sig == signal.SIGINT: 852 | if pid_file != None: 853 | try: 854 | os.remove(pid_file) 855 | except: 856 | pass 857 | 858 | if dev != None: 859 | try: 860 | dev.close() 861 | except: 862 | pass 863 | 864 | os.system('setterm -cursor on') 865 | print ("") 866 | sys.exit(0) 867 | 868 | ############################################################################# 869 | 870 | def fetch_template(t): 871 | 872 | template = None 873 | 874 | try: 875 | template = templateEnv.get_template(t) 876 | except jinja2.exceptions.TemplateNotFound as e: 877 | s = "Error: template file {}/{} not found".format(template_path, t) 878 | template = templateEnv.from_string(s) 879 | except jinja2.exceptions.TemplateSyntaxError as e: 880 | s = "Error: syntax error in template file {}/{}: {}, line {}".format(template_path, t, e, e.lineno) 881 | template = templateEnv.from_string(s) 882 | 883 | return template 884 | 885 | ############################################################################# 886 | 887 | def is_running(pid): 888 | if os.path.isdir('/proc/{}'.format(pid)): 889 | return True 890 | return False 891 | 892 | ############################################################################# 893 | # Return false if not toggling anything 894 | # Return true if state changed 895 | def display_power(val): 896 | try: 897 | with open(backlight_file, 'r') as f: 898 | state = f.read().rstrip() 899 | except: 900 | return False 901 | 902 | Debug("display_power() compare '{}' to '{}'".format(val, state)) 903 | 904 | if state == val: 905 | return False 906 | 907 | try: 908 | if backlight_sudo == True: 909 | cmd = "/usr/bin/sudo /bin/sh -c 'echo {} > {}'".format(val, backlight_file) 910 | Popen(cmd, shell=True) 911 | else: 912 | with open(backlight_file, 'w') as f: 913 | f.write(val) 914 | except: 915 | return False 916 | 917 | return True 918 | 919 | ############################################################################# 920 | 921 | if __name__ == '__main__': 922 | parser = argparse.ArgumentParser(description="Pi-Hole Alternate Display") 923 | parser.add_argument('-c', '--config', 924 | help="Config file", 925 | required=False, 926 | default='./phad.conf') 927 | parser.add_argument('-s', '--seconds', 928 | help="Cycle through screens every -s seconds. Will also disable responding to touchscrens.", 929 | required=False, 930 | type=int) 931 | parser.add_argument('-t', '--template', 932 | help="Template to render", 933 | required=False) 934 | parser.add_argument('-r', '--readconf', 935 | help="Re-read the config file by sending a SIGHUP to PID of the running instance.", 936 | required=False, 937 | action="store_true") 938 | parser.add_argument('-j', '--json', 939 | help="Dump json data then exit", 940 | required=False, 941 | action="store_true") 942 | parser.add_argument('-i', '--items', 943 | help="List each individual json item name. Useful for then passing to --items", 944 | required=False, 945 | action="store_true") 946 | parser.add_argument('-l', '--list', 947 | help="Requires --json. Name of individual top-level json items to list. If not specified then all items are displayed.", 948 | nargs = "+", 949 | required=False) 950 | parser.add_argument('-d', '--debug', 951 | help="Write debugging information to debug.log", 952 | required=False, 953 | action="store_true") 954 | parser.add_argument('-v', '--verbose', 955 | help="Display warning messages on stdout", 956 | required=False, 957 | action="store_true") 958 | 959 | args = parser.parse_args() 960 | 961 | try: 962 | from evdev import ecodes, InputDevice, categorize 963 | evdevInstalled = True 964 | except: 965 | Warning('Module evdev not found. Touch screen support is disabled.') 966 | if args.verbose: 967 | time.sleep(10) 968 | 969 | if args.debug: 970 | Ctl['Clear_Screen'] = '' # Disable clearing the screen & moving home so debug statement are seen 971 | Ctl['Home'] = '' 972 | debug = True 973 | 974 | script_path = os.path.dirname(os.path.realpath(__file__)) 975 | Debug("Script path: {}".format(script_path)) 976 | os.chdir(script_path) 977 | 978 | config = configparser.RawConfigParser() 979 | config_file_name = args.config 980 | 981 | enable_touchscreen = True 982 | if args.template != None or args.json == True or args.readconf == True: 983 | enable_touchscreen = False 984 | 985 | load_config(enable_touchscreen) 986 | 987 | if args.readconf == True: 988 | fname = config.get('main', 'pid_file') 989 | try: 990 | with open(fname, "r") as f: 991 | pid = f.readline() 992 | os.kill(int(pid), signal.SIGHUP) 993 | print ("Sent SIGHUP to PID {}".format(pid)) 994 | except Exception as e: 995 | print (str(e)) 996 | sys.exit(0) 997 | 998 | if args.json or args.items: 999 | data = fetch_data(config) 1000 | if args.items: 1001 | for i in sorted(data): 1002 | print (i) 1003 | sys.exit(0) 1004 | 1005 | if args.list is not None: 1006 | for i in args.list: 1007 | print (json.dumps({ i: data[i]}, indent=4, sort_keys=True)) 1008 | print ("") 1009 | else: 1010 | for i in sorted(data): 1011 | print (json.dumps({ i: data[i]}, indent=4, sort_keys=True)) 1012 | print ("") 1013 | sys.exit(0) 1014 | 1015 | if args.template: 1016 | template = fetch_template(args.template) 1017 | data = fetch_data(config) 1018 | t = template.render(**data) 1019 | sys.stdout.write(t) 1020 | sys.stdout.flush() 1021 | sys.exit(0) 1022 | 1023 | if config.has_option('main', 'pid_file'): 1024 | pid_file = config.get('main', 'pid_file') 1025 | pid_running = False 1026 | try: 1027 | with open(pid_file, "r") as f: 1028 | pid = f.readline() 1029 | pid_running = is_running(int(pid)) 1030 | except Exception as e: 1031 | pass 1032 | 1033 | if pid_running: 1034 | # Don't overwrite the PID file (or delete it on shutdown) 1035 | # if it contains a PID of a running instance. 1036 | pid_file = None 1037 | else: 1038 | try: 1039 | with open(pid_file, "w") as f: 1040 | f.write("{}".format(os.getpid())) 1041 | except Exception as e: 1042 | print ("Unable to save PID to {}".format(pid_file)) 1043 | print (str(e)) 1044 | 1045 | if config.has_option('backlight', 'enabled'): 1046 | backlight_enabled = config.getboolean('backlight', 'enabled') 1047 | if backlight_enabled: 1048 | if config.has_option('backlight', 'file_location'): 1049 | backlight_file = config.get('backlight', 'file_location') 1050 | 1051 | if config.has_option('backlight', 'use_sudo'): 1052 | backlight_sudo = config.getboolean('backlight', 'use_sudo') 1053 | 1054 | if config.has_option('backlight', 'on_value'): 1055 | backlight_on = config.get('backlight', 'on_value') 1056 | 1057 | if config.has_option('backlight', 'off_value'): 1058 | backlight_off = config.get('backlight', 'off_value') 1059 | 1060 | if os.path.exists(backlight_file) == False or \ 1061 | os.path.isfile(backlight_file) == False: 1062 | Warning("LCD backlight file {} not found".format(backlight_file)) 1063 | Warning("Disabling backlight toggling of display.") 1064 | if args.verbose: 1065 | time.sleep(10) 1066 | backlight_enabled = False 1067 | 1068 | signal.signal(signal.SIGHUP, signal_handler) 1069 | signal.signal(signal.SIGINT, signal_handler) 1070 | 1071 | template = fetch_template(templates[current_template_id]) 1072 | 1073 | os.system('setterm -cursor off') 1074 | 1075 | next_data_refresh = 0 1076 | 1077 | if args.seconds: 1078 | # Cycle periodically, so ignore touchscreen presses, etc. 1079 | seconds = args.seconds 1080 | current_template_id = 0 1081 | 1082 | while True: 1083 | secs = round(time.time()) 1084 | if secs >= next_data_refresh: 1085 | data = fetch_data(config) 1086 | next_data_refresh = secs + refresh_rate 1087 | 1088 | template = fetch_template(templates[current_template_id]) 1089 | t = template.render(**data) 1090 | sys.stdout.write(t) 1091 | sys.stdout.flush() 1092 | 1093 | current_template_id += 1 1094 | if current_template_id >= len(templates): 1095 | current_template_id = 0 1096 | 1097 | time.sleep(seconds) 1098 | 1099 | # Should never actually get here - end of args.seconds loop 1100 | sys.exit(0) 1101 | 1102 | # If we get here then handle cases of both with & without touchscreen 1103 | # support. If a touch interface exists then check for touches to toggle 1104 | # the display, etc. If no touch interface then just cycle the display 1105 | # based on the display timeout. 1106 | 1107 | if dev: 1108 | Debug("Start touchscreen loop with backlight_enabled {} & display_timeout {}".format(backlight_enabled, display_timeout)) 1109 | 1110 | if backlight_enabled: 1111 | display_power(backlight_on) 1112 | signal.signal(signal.SIGALRM, signal_handler) 1113 | signal.alarm(display_timeout) 1114 | 1115 | next_template_reset = 0 1116 | 1117 | while True: 1118 | secs = round(time.time()) 1119 | 1120 | if backlight_enabled == False: 1121 | # Check on reverting to template 0 when there's no backlight to turn off 1122 | if secs >= next_template_reset: 1123 | current_template_id = 0 1124 | template = fetch_template(templates[current_template_id]) 1125 | next_template_reset = secs + display_timeout 1126 | 1127 | if secs >= next_data_refresh: 1128 | data = fetch_data(config) 1129 | t = template.render(**data) 1130 | sys.stdout.write(t) 1131 | sys.stdout.flush() 1132 | next_data_refresh = secs + refresh_rate 1133 | 1134 | try: 1135 | r1,w1,x1 = select([dev], [], [], 1) 1136 | except Exception as e: 1137 | Debug("LOOP EXCEPTION: {}".format(str(e))) 1138 | r1 = [] 1139 | 1140 | if len(r1) != 0: 1141 | for event in dev.read(): 1142 | # event.type, event.code, event.value 1143 | if event.type == ecodes.EV_KEY and \ 1144 | event.code == ecodes.BTN_TOUCH and \ 1145 | event.value == 0: # "button" down 1146 | 1147 | Debug("EVENT: {}".format(categorize(event))) 1148 | 1149 | if backlight_enabled == False: 1150 | current_template_id += 1 1151 | else: 1152 | if display_power(backlight_on): 1153 | # display was turned on - revert to template 0 1154 | current_template_id = 0 1155 | else: 1156 | current_template_id += 1 1157 | 1158 | if current_template_id >= len(templates): 1159 | current_template_id = 0 1160 | 1161 | Debug("shift template to {}".format(current_template_id)) 1162 | 1163 | template = fetch_template(templates[current_template_id]) 1164 | 1165 | t = template.render(**data) 1166 | sys.stdout.write(t) 1167 | sys.stdout.flush() 1168 | 1169 | if backlight_enabled: 1170 | signal.alarm(display_timeout) 1171 | else: 1172 | next_template_reset = round(time.time()) + display_timeout 1173 | break 1174 | 1175 | else: 1176 | # No touch screen so enable the backlight if necessary 1177 | # then just sleep and cycle through displays 1178 | 1179 | if backlight_enabled: 1180 | display_power(backlight_on) 1181 | 1182 | while True: 1183 | secs = round(time.time()) 1184 | if secs >= next_data_refresh: 1185 | data = fetch_data(config) 1186 | next_data_refresh = secs + refresh_rate 1187 | 1188 | template = fetch_template(templates[current_template_id]) 1189 | t = template.render(**data) 1190 | sys.stdout.write(t) 1191 | sys.stdout.flush() 1192 | 1193 | current_template_id += 1 1194 | if current_template_id >= len(templates): 1195 | current_template_id = 0 1196 | 1197 | time.sleep(display_timeout) 1198 | -------------------------------------------------------------------------------- /phad-simple-install.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # Some of this code copied shamelessly from the pi-hole basic-install.sh script 4 | # found at https://install.pi-hole.net 5 | 6 | # Parse the output of udevadm, looking for the device associated with a touchscreen 7 | function get_touchscreen_dev() 8 | { 9 | local IFS=$'\n' 10 | local NEWDEV=".BLOCK" 11 | 12 | for i in $(udevadm info --export-db | sed -e "s/^$/${NEWDEV}/") ; do 13 | [[ $i == *"ID_INPUT_TOUCHSCREEN"* ]] && _DEVID=${i} 14 | [[ $i == *DEVNAME=* ]] && _DEVNAME=${i#*=} 15 | 16 | if [[ "$i" == "$NEWDEV" ]] ; then 17 | if [[ "$_DEVNAME" != "" && "$_DEVID" != "" ]] ; then 18 | echo $_DEVNAME 19 | return 20 | fi 21 | unset _DEVNAME 22 | unset _DEVID 23 | fi 24 | done 25 | } 26 | 27 | # This is a file used for the colorized output 28 | coltable=/opt/pihole/COL_TABLE 29 | 30 | # If the color table file exists, 31 | if [[ -f "${coltable}" ]]; then 32 | # source it 33 | source ${coltable} 34 | # Otherwise, 35 | else 36 | # Set these values so the installer can still run in color 37 | COL_NC='\e[0m' # No Color 38 | COL_LIGHT_GREEN='\e[1;32m' 39 | COL_LIGHT_RED='\e[1;31m' 40 | TICK="[${COL_LIGHT_GREEN}✓${COL_NC}]" 41 | CROSS="[${COL_LIGHT_RED}✗${COL_NC}]" 42 | INFO="[i]" 43 | # shellcheck disable=SC2034 44 | DONE="${COL_LIGHT_GREEN} done!${COL_NC}" 45 | OVER="\\r\\033[K" 46 | fi 47 | 48 | # Check if we are running on a real terminal and find the rows and columns 49 | # If there is no real terminal, we will default to 80x24 50 | if [ -t 0 ] ; then 51 | screen_size=$(stty size) 52 | else 53 | screen_size="24 80" 54 | fi 55 | # Set rows variable to contain first number 56 | printf -v rows '%d' "${screen_size%% *}" 57 | # Set columns variable to contain second number 58 | printf -v columns '%d' "${screen_size##* }" 59 | 60 | # Divide by two so the dialogs take up half of the screen, which looks nice. 61 | r=$(( rows / 2 )) 62 | c=$(( columns / 2 )) 63 | # Unless the screen is tiny 64 | r=$(( r < 20 ? 20 : r )) 65 | c=$(( c < 70 ? 70 : c )) 66 | 67 | # interface_filename;off_value;on_value 68 | TOUCHSCREEN_BACKLIGHT_INTERFACES=$(cat << EOM 69 | /sys/class/backlight/rpi_backlight/bl_power;1;0 70 | /sys/class/backlight/soc:backlight/bl_power;1;0 71 | EOM 72 | ) 73 | 74 | TOUCHSCREEN_INPUT_DEVICES=$(cat << EOM 75 | /dev/input/touchscreen 76 | /dev/input/event0 77 | EOM 78 | ) 79 | 80 | PIHOLE_FILES=$(cat < /dev/null 2>&1 122 | if [[ $? -ne 0 ]] ; then 123 | printf " %b %bInstalling python3-pip package%b\\n" "${INFO}" "${COL_LIGHT_RED}" "${COL_NC}" 124 | sudo apt-get install python3-pip > /dev/null 2>&1 125 | if [[ $? -ne 0 ]] ; then 126 | printf " %b %s\\n" "${CROSS}" "Unable to install python3-pip\\n" 127 | printf " %b %bThe python3-pip package is required to allow python to install other packages.%b\\n" "${INFO}" "${COL_LIGHT_RED}" "${COL_NC}" 128 | printf " Please ensure the Python3 pip module is installed then re-run this installer.\\n" 129 | exit 1 130 | fi 131 | fi 132 | 133 | if [[ "$1" == "--upgrade" ]] ; then 134 | printf " %b %bInstalling Python 3 dependencies%b\\n" "${INFO}" "${COL_LIGHT_RED}" "${COL_NC}" 135 | EVDEV=$(/usr/bin/env python3 -m pip list | grep evdev) 136 | if [[ "$EVDEV" != "" ]] ; then 137 | REQUIREMENTS="$REQUIREMENTS evdev>==1.0.0" 138 | fi 139 | /usr/bin/env python3 -m pip install -q ${REQUIREMENTS} 140 | DL_URL=$(curl --silent "https://api.github.com/repos/bpennypacker/phad/releases/latest" | grep tarball_url | sed -e 's/^.*\: "//' -e 's/".*$//') 141 | printf "\\n" 142 | DL_FILE=$(curl --silent -L $DL_URL | tar tz --strip-components=1 | grep -e '/phad$') 143 | printf " %b %bDownloading phad from %s%b\\n" "${INFO}" "${COL_LIGHT_RED}" "${DL_URL}" "${COL_NC}" 144 | curl --silent -L $DL_URL | tar xz $DL_FILE --strip-components=1 145 | printf " %b %s\\n" "${TICK}" "Successfully downloaded the phad program. No changes have been made to phad.conf or ${HOME}/.bashrc" 146 | exit 0 147 | fi 148 | 149 | grep -q -i phad ${HOME}/.bashrc 150 | if [[ $? -eq 0 ]] ; then 151 | printf " %b %s\\n" "${CROSS}" "phad already configured to run" 152 | printf " Referenes to phad exist in ${HOME}/.bashrc.\\n" 153 | printf " For this reason the installer refuses to run. Please see the\\n" 154 | printf " README file for instructions on installing phad manually.\\n" 155 | printf "\\n" 156 | printf " If you would like to replace just the phad program without\\n" 157 | printf " making any changes to your existing configuration then run\\n" 158 | printf " the following commands:\\n\\n" 159 | printf " wget -c https://raw.githubusercontent.com/bpennypacker/phad/master/phad-simple-install.sh\\n" 160 | printf " bash phad-simple-install.sh --upgrade\\n" 161 | exit 1 162 | fi 163 | 164 | # -e option instructs bash to immediately exit if any command [1] has a non-zero exit status 165 | # We do not want users to end up with a partially working install, so we exit the script 166 | # instead of continuing the installation with something broken 167 | set -e 168 | 169 | PHAD_DIR="${HOME}/phad" 170 | mkdir -p $PHAD_DIR 171 | 172 | if [ ! -d $PHAD_DIR ] ; then 173 | printf " %b %s\\n" "${CROSS}" "Directory $PHAD_DIR not found" 174 | printf " %b %bphad installs into this directory but this installer was unable to create it. Aborting.%b\\n" "${INFO}" "${COL_LIGHT_RED}" "${COL_NC}" 175 | exit 1 176 | fi 177 | 178 | cd $PHAD_DIR 179 | 180 | for i in ${PHAD_FILES} ; do 181 | if [ -f "$i" ] ; then 182 | printf " %b %s\\n" "${CROSS}" "file ${PHAD_DIR}/${i} exists" 183 | printf " %b %bphad appears to already be installed in $PHAD_DIR. Aborting.%b\\n" "${INFO}" "${COL_LIGHT_RED}" "${COL_NC}" 184 | exit 1 185 | fi 186 | done 187 | 188 | printf " %b %bChecking for touchscreen backlight interface%b\\n" "${INFO}" "${COL_LIGHT_RED}" "${COL_NC}" 189 | for i in ${TOUCHSCREEN_BACKLIGHT_INTERFACES}; do 190 | TS_FILE="$(cut -d ';' -f1 <<< "${i}")" 191 | TS_OFF="$(cut -d ';' -f2 <<< "${i}")" 192 | TS_ON="$(cut -d ';' -f3 <<< "${i}")" 193 | if [[ -f "${TS_FILE}" && "${BACKLIGHT_FILE}" == "" ]] ; then 194 | if whiptail --title "Touchscreen backlight interface" --yesno "A potential interface for your touchscreen backlight has been found at ${TS_FILE}. Would you like to test this in order to enable touchscreen blanking? If you choose 'yes' then this installer will attempt to make the LCD display go blank for 5 seconds and then turn it on again. Would you like to do this?" ${r} ${c}; then 195 | [ -w ${TS_FILE} ] || REQUIRE_SUDO=1 196 | 197 | printf "Attempting to blank LCD display in " 198 | for i in $(seq 5 -1 1) ; do printf "${i}... " ; sleep 1 ; done 199 | printf "\\n" 200 | 201 | if [ "$REQUIRE_SUDO" == "1" ] ; then 202 | sudo sh -c "echo '${TS_OFF}' > ${TS_FILE}" 203 | else 204 | echo "${TS_OFF}" > ${TS_FILE} 205 | fi 206 | 207 | for i in $(seq 5 -1 1) ; do printf "${i}... " ; sleep 1 ; done 208 | printf "\\n" 209 | 210 | if [ "$REQUIRE_SUDO" == "1" ] ; then 211 | sudo sh -c "echo '${TS_ON}' > ${TS_FILE}" 212 | else 213 | echo "${TS_ON}" > ${TS_FILE} 214 | fi 215 | 216 | if whiptail --defaultno --title "Touchscreen backlight interface" --yesno "Did your touchscreen go blank?" ${r} ${c}; then 217 | BACKLIGHT_FILE=${TS_FILE} 218 | BACKLIGHT_CMD_OFF=${TS_OFF} 219 | BACKLIGHT_CMD_ON=${TS_ON} 220 | printf "\\n" 221 | printf " %b %s\\n" "${TICK}" "Found touchscreen backlight interface: ${BACKLIGHT_FILE}" 222 | printf "\\n" 223 | fi 224 | fi 225 | fi 226 | done 227 | 228 | ts_dev=$(get_touchscreen_dev) 229 | RE='^[0-9]*$' 230 | T="x" 231 | 232 | if [ "$ts_dev" != "" ] ; then 233 | if whiptail --title "Touchscreen interface" --yesno "A touch interfface was found at ${ts_dev}. Would you like phad to wake up when you touch the touchscreen?" ${r} ${c}; then 234 | TOUCHSCREEN_DEV=${ts_dev} 235 | REQUIREMENTS="$REQUIREMENTS evdev>==1.0.0" 236 | while ! [[ $T =~ $RE ]] ; do 237 | T=$(whiptail --title "Touchscreen timeout" --inputbox "How many seconds after tapping on the display should phad blank the screen again?" ${r} ${c} 10 3>&1 1>&2 2>&3) 238 | done 239 | [ "$T" != "" ] && MAIN_TIMEOUT=$T 240 | fi 241 | fi 242 | 243 | if [[ "$TOUCHSCREEN_DEV" == "" ]] ; then 244 | T="x" 245 | while ! [[ $T =~ $RE ]] ; do 246 | T=$(whiptail --title "Display cycle time" --inputbox "No touchscreen interface was found, so touch support will be disabled. Instead, phad will be configured to cycle between displays automatically. How many seconds shold phad wait between switching its display?" ${r} ${c} 20 3>&1 1>&2 2>&3) 247 | done 248 | [ "$T" != "" ] && TEMPLATE_TIMEOUT="-s $T" 249 | fi 250 | 251 | declare -a TEMPLATE_LIST=() 252 | if [[ "$TOUCHSCREEN_DEV" != "" && "$BACKLIGHT_FILE" == "" ]] ; then 253 | TEMPLATE_LIST+=("blank.j2" "A blank screen to simulate turning off the display" ON) 254 | fi 255 | 256 | TEMPLATE_LIST+=("main.j2" "The main phad summary screen" ON) 257 | TEMPLATE_LIST+=("top_ads.j2" "A list of the top ads blocked by your Pi-Hole" ON) 258 | TEMPLATE_LIST+=("top_clients.j2" "A list of the top clients using your Pi-Hole" ON) 259 | TEMPLATE_LIST+=("top_domains.j2" "A list of the top domains resolved by your Pi-Hole" ON) 260 | TEMPLATE_LIST+=("network.j2" "A summary of your Pi-Hole's network settings" ON) 261 | 262 | L=${#TEMPLATE_LIST[@]} 263 | N=$(( L / 3 )) 264 | 265 | while [[ "$TL" == "" ]] ; do 266 | TL=$(whiptail --title "Select pages phad should cycle between" --checklist "Select the templates that phad should cycle between" ${r} ${c} $N "${TEMPLATE_LIST[@]}" 3>&1 1>&2 2>&3) 267 | done 268 | TEMPLATES=$(echo $TL | sed -e 's/"//g' -e 's/ /,/'g) 269 | 270 | printf " %b %bInstalling python dependencies:%b\\n" "${INFO}" "${COL_LIGHT_RED}" "${COL_NC}" 271 | for i in ${REQUIREMENTS} ; do 272 | printf " - %s\\n" "${i}" 273 | done 274 | /usr/bin/env python3 -m pip install -q ${REQUIREMENTS} 275 | printf " %b %s\\n" "${TICK}" "Installed python dependencies" 276 | 277 | DL_URL=$(curl --silent "https://api.github.com/repos/bpennypacker/phad/releases/latest" | grep tarball_url | sed -e 's/^.*\: "//' -e 's/".*$//') 278 | printf "\\n" 279 | printf " %b %bDownloading phad from %s%b\\n" "${INFO}" "${COL_LIGHT_RED}" "${DL_URL}" "${COL_NC}" 280 | curl --silent -L $DL_URL | tar xz --strip-components=1 281 | printf " %b %s\\n" "${TICK}" "Successfully downloaded phad" 282 | 283 | for i in ${PHAD_FILES} ; do 284 | if [ ! -f "$i" ] ; then 285 | printf " %b %s\\n" "${CROSS}" "phad file $i not found" 286 | printf " %b %bphad appears to have failed to download properly.%b\\n" "${INFO}" "${COL_LIGHT_RED}" "${COL_NC}" 287 | printf " Check that $DL_URL is valid.\\n" 288 | printf " If that URL is valid then remove the current phad directory and.\\n" 289 | printf " try running this installer again.\\n" 290 | exit 1 291 | fi 292 | done 293 | 294 | CMD=" " 295 | 296 | if [[ "$BACKLIGHT_FILE" != "" ]] ; then 297 | F=$(echo $BACKLIGHT_FILE | sed -e s'/\//\\\//g') 298 | CMD="$CMD -e s/^file_location=.*$/file_location=$F/" 299 | CMD="$CMD -e s/^on_value=.*$/on_value=$BACKLIGHT_CMD_ON/" 300 | CMD="$CMD -e s/^off_value=.*$/off_value=$BACKLIGHT_CMD_OFF/" 301 | CMD="$CMD -e s/^enabled=.*$/enabled=True/" 302 | if [[ "$REQUIRE_SUDO" == "" ]] ; then 303 | CMD="$CMD -e s/^use_sudo=.*$/use_sudo=False/" 304 | else 305 | CMD="$CMD -e s/^use_sudo=.*$/use_sudo=True/" 306 | fi 307 | else 308 | CMD="$CMD -e s/^enabled=.*$/enabled=False/" 309 | fi 310 | 311 | if [[ "$TOUCHSCREEN_DEV" != "" ]] ; then 312 | F=$(echo $TOUCHSCREEN_DEV | sed -e s'/\//\\\//g') 313 | CMD="$CMD -e s/^input_device=.*$/input_device=$F/" 314 | else 315 | CMD="$CMD -e s/^input_device=/#input_device=/" 316 | fi 317 | 318 | CMD="$CMD -e s/^templates=.*$/templates=$TEMPLATES/" 319 | 320 | if [[ "$MAIN_TIMEOUT" != "" ]] ; then 321 | CMD="$CMD -e s/^main_timeout=.*$/main_timeout=$MAIN_TIMEOUT/" 322 | else 323 | CMD="$CMD -e s/^enable_main_timeout=.*$/enable_main_timeout=False/" 324 | fi 325 | 326 | mv phad.conf phad.conf.original 327 | cat phad.conf.original | sed $CMD > phad.conf 328 | 329 | printf " %b %s\\n" "${TICK}" "Customized phad.conf" 330 | 331 | BASH_TXT=$(cat << EOM 332 | if [ "\$TERM" == "linux" ] ; then 333 | cd ${PHAD_DIR} 334 | while : 335 | do 336 | ./phad ${TEMPLATE_TIMEOUT} 2>/dev/null 337 | sleep 10 338 | done 339 | fi 340 | EOM 341 | ) 342 | 343 | BASHRC=${HOME}/.bashrc 344 | IFS=$'\n' 345 | 346 | if whiptail --defaultno --title "Start phad automatically" --yesno "Would you like phad to start up automatically by adding it to the pi users .bashrc file?" ${r} ${c}; then 347 | echo "" >> $BASHRC 348 | echo "# Start phad" >> $BASHRC 349 | for i in ${BASH_TXT} ; do 350 | echo ${i} >> $BASHRC 351 | done 352 | 353 | if whiptail --defaultno --title "Reboot?" --yesno "Your Raspberry Pi needs to be rebooted for phad to start. Reboot now?" ${r} ${c}; then 354 | sudo reboot 355 | else 356 | printf " %b %s\\n" "${TICK}" "phad installation complete" 357 | fi 358 | else 359 | printf " %b %s\\n" "${TICK}" "phad installation complete" 360 | printf " %b %bphad has not been configured to start automatically.%b\\n" "${INFO}" "${COL_LIGHT_RED}" "${COL_NC}" 361 | printf " %b %bTo start phad add something like this to your .bashrc file:%b\\n" "${INFO}" "${COL_LIGHT_RED}" "${COL_NC}" 362 | printf "\\n" 363 | for i in ${BASH_TXT} ; do 364 | printf " %s\\n" "$i" 365 | done 366 | fi 367 | -------------------------------------------------------------------------------- /phad.conf: -------------------------------------------------------------------------------- 1 | [main] 2 | # If git_update_version_check is true then phad will attempt to invoke 3 | # 'git remote update' using the git_repo and git_sudo settings whe 4 | # performing a version check. This is mostly helpful when running a 5 | # beta or test version of pihole. This will perform the equivalent 6 | # of sudo git -C /etc/.pihole remote update 7 | git_update_version_check=False 8 | git_repo=/etc/.pihole 9 | git_sudo=True 10 | 11 | # By default phad will determine pihole version information using the 12 | # version numbers returned by pihole. To perform version checking with 13 | # hashes instead of version numbers set use_version_hashes to True. 14 | # This is the equivelant of invoking "pihole -v" with the optional 15 | # --hash parameter. 16 | use_version_hashes=False 17 | 18 | # The touch screen input device. If you have a RPi with only a touchscreen 19 | # then this is likely the right device to use. If this does not work for 20 | # you then investigating the directories /dev/input/by-id or 21 | # /dev/input-by-path might help, along with the file /proc/bus/input/devices 22 | input_device=/dev/input/event0 23 | 24 | # Temporary state data is stored to this file. Manly version details provided 25 | # by pi-hole are stored here so that phad is not querying Github multiple 26 | # times a minute. This data is refreshed once a day. 27 | data_file=./phad.dat 28 | 29 | # phad will write its PID to this file so that "phad -r" can then tell phad 30 | # to re-read this file if edits are made. 31 | pid_file=./phad.pid 32 | 33 | # Path to the templates to render 34 | template_path=./templates 35 | 36 | # Comma seperated list of templates to render. The first one in the list is 37 | # the default. 38 | templates=main.j2,top_ads.j2,top_domains.j2,top_clients.j2,network.j2 39 | 40 | # If a touchscreen is used then display_timeout is the number of seconds after 41 | # the screen is last touched before the backlight is turned off (if it exists) 42 | # or the first template is displayed again. 43 | display_timeout=30 44 | 45 | # How often phad should query the pi-hole for data 46 | refresh_rate=30 47 | 48 | # Maximum number of top ads, clients, and domains to fetch from pi-hole 49 | top_ads_max=20 50 | top_clients_max=20 51 | top_domains_max=20 52 | 53 | # If True then phad will attempt to obtain your public IP once a day 54 | # and store it in phad's data_file. The URL that is queried should 55 | # return your public IP and nothing else. Multiple comma-separated 56 | # URLs can be provided. Each URL will be tried in order until one 57 | # successfully returns an IP 58 | get_external_ip=True 59 | external_ip_url=https://www.myexternalip.com/raw,http://ipv4bot.whatismyipaddress.com 60 | 61 | # The following section defined settings for querying and toggling the 62 | # backlight of LCD displays 63 | 64 | [backlight] 65 | # Location of the file that is used to query/toggle an LCD backlight. 66 | # Common values can include: 67 | # /sys/class/backlight/rpi_backlight/bl_power 68 | # /sys/class/backlight/soc:backlight/bl_power 69 | file_location=/sys/class/backlight/soc:backlight/bl_power 70 | 71 | # Whether or not to toggle the LCD backlight 72 | enabled=True 73 | 74 | # Use sudo when writing to file_location 75 | use_sudo=True 76 | 77 | # Values use for turning the display on and off 78 | on_value=0 79 | off_value=1 80 | 81 | # Date/time strings are formatted according to the standard date/time directives 82 | # documented here: 83 | # https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior 84 | [datetime] 85 | formatted=date,time,combined 86 | date="%Y-%m-%d" 87 | time="%H:%M:%S" 88 | combined="%Y-%m-%d %H:%M:%S" 89 | 90 | # uptime formats use the self-evident variables 'days', 'hours', 'minutes', 'seconds' 91 | # and 'total_seconds' 92 | [uptime] 93 | strings=long,short,seconds 94 | short="{days:4}:{hours:02}:{minutes:02}" 95 | long="{days:4} days, {hours:2} hours, {minutes:2} minutes " 96 | seconds="{total_seconds:8}" 97 | 98 | # All the following sections define how individual data is represented in the JSON 99 | # results that are used to render the templates. The basic methodology behind phad 100 | # is to define formats that pad values with strings so that the resulting values 101 | # of of known fixed lengths. This makes it easy to layout those variables in 102 | # the jinja2 templates used to generate the phad displays. 103 | # 104 | # Each [section] identifies the group of values that the subsequent formatting will 105 | # be applied to. When a [section] name contains a '/', that indicates that the [section] 106 | # formatting applies only to a specific subset of values. [sections] values are applied 107 | # from most specific to most generic, so if [foo/bar/variable] exists then it is used 108 | # to format the variable, otherwise if [foo/bar] exists then it is used, and so on. 109 | # 110 | # Example: If you invoke "./phad -j -l status" it will display all the status variables 111 | # in JSON format. The [status/temp/C] section below will format the celsius temperatore 112 | # value one way, and the [status] section will format all remaining variables in the 113 | # status JSON structure a different way. 114 | # 115 | # There are four primary options that you can specify under each section. All formatting is 116 | # based on the "new style" of python formatting that can be found at https://pyformat.info. 117 | # The three simpler options that can be specified are as follows: 118 | # 119 | # str= 120 | # float= 121 | # int= 122 | # 123 | # The above three options will cast variables as specific types. If a variable is a string, 124 | # such as a domain name, then it can be padded to a specific length using something like 125 | # "str={:20}". Note that it is possible to specify two formats if it makes sense. For 126 | # example, the [stats/ads_percentage_today] section defines both a "str" and "float" 127 | # option. 128 | # 129 | # There are two special types of options that can be specified beyond the three mentioned 130 | # above. The "strings" option provides a way to have a variable be formatted more than 131 | # one way. For example, the [version] section as a "strings" option that specifies "left" 132 | # and "right", after which there is a "left" option that defines a left-padded string 133 | # format and a "right" option that defines a right-padded string format. 134 | # 135 | # The last formatting option is "graph" which can be applied to integer or floating 136 | # values. This will generate a graphical representation of the value. To define a graph, 137 | # the option is in the following format: 138 | # 139 | # graph=length,used_fill,free_fill,used_color,free_color 140 | # 141 | # Only the length is required when defining a graph. All other values are optional 142 | # and default values will be used if they are not specified here. Examples: 143 | # 144 | # graph=40 145 | # 146 | # This will create a graph that is 40 characters long using the default values for 147 | # character fills and colors. 148 | # 149 | # graph=10,X,-,Yellow,Cyan 150 | # 151 | # This will create a graph that is 10 character long. It will use an 'X' to denote 152 | # where the graph is filled, and a hyphen ('-') to denote where it is not filled. 153 | # The 'X's will also be yellow and the '-'s will be cyan. 154 | # 155 | # Any of the following colors can be used when defining graphs: 156 | # 157 | # 'Red' 158 | # 'Green' 159 | # 'Yellow' 160 | # 'Blue' 161 | # 'Magenta' 162 | # 'Cyan' 163 | # 'White' 164 | # 'Bright_Black' 165 | # 'Bright_Red' 166 | # 'Bright_Green' 167 | # 'Bright_Yellow' 168 | # 'Bright_Blue' 169 | # 'Bright_Magenta' 170 | # 'Bright_Cyan' 171 | # 'Bright_White' 172 | 173 | [stats/ads_percentage_today] 174 | str={:>20} 175 | float={:5.2f} 176 | graph=40 177 | 178 | [stats/domains_being_blocked] 179 | int={:,} 180 | 181 | [version] 182 | strings=left,right 183 | left={:10} 184 | right={:>10} 185 | 186 | [status] 187 | str={:10} 188 | 189 | [status/temp/C] 190 | float="{:4.1f}°C " 191 | 192 | [memory/percent] 193 | graph=10,■,■,Magenta,Blue 194 | float="{:4.1f}" 195 | 196 | [host/cpuload] 197 | graph=10,-,.,Yellow,Cyan 198 | float="{:4.1f}" 199 | 200 | [top/ads/url] 201 | strings=str40 202 | str40={:40.40s} 203 | str={:35.35s} 204 | 205 | [top/ads/rank] 206 | int={:2} 207 | 208 | [top/domains/url] 209 | strings=str40 210 | str40={:40.40s} 211 | str={:35.35s} 212 | 213 | [top/domains/rank] 214 | int={:2} 215 | 216 | [top/clients/IP] 217 | str:{:35} 218 | 219 | [top/clients/hostname] 220 | str:{:35.35s} 221 | 222 | [top/clients/rank] 223 | int={:2} 224 | 225 | [client_names/IP] 226 | str={:15} 227 | 228 | [querytypes] 229 | str={:5} 230 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | jinja2>==2.0 2 | requests>==2.0 3 | evdev>==1.0 4 | -------------------------------------------------------------------------------- /templates/blank.j2: -------------------------------------------------------------------------------- 1 | {# This template will effectively blank the screen when rendered. Use this as 2 | your default template (the first template listed on the 'templates' 3 | option in phad.conf) and set the 'enable_main_timeout' option to True 4 | if you would like your pi-hole display to default to a blank screen 5 | and "wake up" when you tap on it. 6 | #} 7 | {{ ANSI['Ctl']['Clear_Screen'] }}{{ ANSI['Ctl']['Home'] }} 8 | -------------------------------------------------------------------------------- /templates/clients.j2: -------------------------------------------------------------------------------- 1 | {%- for c in client_names_sorted %} 2 | {{ c['IP']['str'] }} {% if c['host']['value']|length %}{{ c['host']['value'] }}{% else %}(unknown){% endif %} 3 | {%- endfor %} 4 | 5 | 6 | -------------------------------------------------------------------------------- /templates/main.j2: -------------------------------------------------------------------------------- 1 | {{ ANSI['Ctl']['Clear_Screen'] }}{{ ANSI['Ctl']['Home'] }}{% if version['all_up_to_date'] == true %}{{ ANSI['Fore']['Bright_Green'] }}All systems up-to-date {% else %}{{ ANSI['Fore']['Bright_Red'] }}One or more systems out-of-date{% endif %}{{ ANSI['Ctl']['Reset'] }}{{ ANSI['Fore']['Magenta'] }} {{ datetime['combined']['value'] }}{{ ANSI['Ctl']['Reset'] }} 2 | Pi-hole version {% if version['pihole_up_to_date'] == true %}{{ ANSI['Fore']['Bright_Green'] }}{% else %}{{ ANSI['Fore']['Bright_Red'] }}{% endif %}{{ version['current']['pihole']['left'] }}{{ ANSI['Ctl']['Reset'] }} (latest: {{ ANSI['Fore']['Bright_Magenta'] }}{{ version['latest']['pihole']['value'] }}{{ ANSI['Ctl']['Reset'] }}) 3 | Web version {% if version['web_up_to_date'] == true %}{{ ANSI['Fore']['Bright_Green'] }}{% else %}{{ ANSI['Fore']['Bright_Red'] }}{% endif %}{{ version['current']['web']['left'] }}{{ ANSI['Ctl']['Reset'] }} (latest: {{ ANSI['Fore']['Bright_Magenta'] }}{{ version['latest']['web']['value'] }}{{ ANSI['Ctl']['Reset'] }}) 4 | FTL version {% if version['ftl_up_to_date'] == true %}{{ ANSI['Fore']['Bright_Green'] }}{% else %}{{ ANSI['Fore']['Bright_Red'] }}{% endif %}{{ version['current']['FTL']['left'] }}{{ ANSI['Ctl']['Reset'] }} (latest: {{ ANSI['Fore']['Bright_Magenta'] }}{{ version['latest']['FTL']['value'] }}{{ ANSI['Ctl']['Reset'] }}) 5 | phad version {% if version['phad_up_to_date'] == true %}{{ ANSI['Fore']['Bright_Green'] }}{% else %}{{ ANSI['Fore']['Bright_Red'] }}{% endif %}{{ version['current']['phad']['left'] }}{{ ANSI['Ctl']['Reset'] }} (latest: {{ ANSI['Fore']['Bright_Magenta'] }}{{ version['latest']['phad']['value'] }}{{ ANSI['Ctl']['Reset'] }}) 6 | PI-HOLE ==================================================== 7 | Status: {% if status['pihole']['value'] == "Running" %}{{ ANSI['Fore']['Bright_Green'] }}{% else %}{{ ANSI['Fore']['Bright_Red'] }}{% endif %}{{status['pihole']['str'] }}{{ ANSI['Ctl']['Reset'] }} FTL: {% if status['ftl']['value'] == "Running" %}{{ ANSI['Fore']['Bright_Green'] }}{% else %}{{ ANSI['Fore']['Bright_Red'] }}{% endif %}{{status['ftl']['str'] }}{{ ANSI['Ctl']['Reset'] }} 8 | STATS ====================================================== 9 | Blocking: {{ stats['domains_being_blocked']['int'] }} 10 | Pi-holed: [{{ stats['ads_percentage_today']['graph'] }}] {{ stats['ads_percentage_today']['float']}}% 11 | Latest: {{ stats['latest-blocked']['value'] }} 12 | Top Ad: {% if top_ads|length == 0 %}N/A{% else %}{{ top_ads[0]['url']['str'] }} (req: {{ ANSI['Fore']['Bright_Magenta'] }}{{ top_ads[0]['hits']['value'] }}{{ ANSI['Ctl']['Reset'] }}){% endif %} 13 | Top Dmn: {% if top_domains|length == 0 %}N/A{% else %}{{ top_domains[0]['url']['str'] }} (req: {{ ANSI['Fore']['Bright_Magenta'] }}{{ top_domains[0]['hits']['value'] }}{{ ANSI['Ctl']['Reset'] }}){% endif %} 14 | Top Clnt: {% if top_clients | length > 0 %}{% if top_clients[0]['hostname']['value'] | length > 0 %}{{ top_clients[0]['hostname']['str'] }}{% else %}{{ top_clients[0]['IP']['str'] }}{% endif %} (req: {{ ANSI['Fore']['Bright_Magenta'] }}{{ top_clients[0]['requests']['value'] }}{{ ANSI['Ctl']['Reset'] }}){% endif %} 15 | NETWORK ==================================================== 16 | Hostname: {{ host['hostname']['value'] }} Domain: {{ host['domainname']['value'] }} 17 | IPv4: {{ setupvars['IPV4_ADDRESS']['value'] }} 18 | IPv6: {% if setupvars['IPV6_ADDRESS']['value'] == "" %}{{ ANSI['Fore']['Magenta'] }}Not Enabled{{ ANSI['Ctl']['Reset'] }}{% else %}{{ setupvars['IPV6_ADDRESS']['value'] }}{% endif %} 19 | SYSTEM ===================================================== 20 | Uptime: {{ uptime['long'] }} 21 | CPU Temp: {{ status['temp']['C']['float'] }} CPU Load: {% for i in host['loadavg']['value'] %}{{ i }}{% if not loop.last %}, {% endif %}{% endfor %} 22 | Memory: {{ host['system-memory']['percent']['graph'] }} {{ host['system-memory']['percent']['float'] }}% CPU Load: [{{ host['cpuload']['graph'] }}] {{ host['cpuload']['float'] }}% 23 | -------------------------------------------------------------------------------- /templates/network.j2: -------------------------------------------------------------------------------- 1 | {{ ANSI['Ctl']['Clear_Screen'] }}{{ ANSI['Ctl']['Home'] }}{{ ANSI['Fore']['Bright_Cyan'] }}NETWORK CONFIGURATION{{ ANSI['Ctl']['Reset'] }} 2 | 3 | Hostname : {{ ANSI['Fore']['Bright_Yellow'] }}{{ host['hostname']['value'] }}{{ ANSI['Ctl']['Reset'] }} 4 | Domain : {{ ANSI['Fore']['Bright_Yellow'] }}{{ host['domainname']['value'] }}{{ ANSI['Ctl']['Reset'] }} 5 | 6 | {% if 'IPV4_ADDRESS' in setupvars %}IPv4 Address : {{ ANSI['Fore']['Bright_Yellow'] }}{{ setupvars['IPV4_ADDRESS']['value'] }}{{ ANSI['Ctl']['Reset'] }}{% endif %} 7 | {% if 'IPV6_ADDRESS' in setupvars %}IPv6 Address : {{ ANSI['Fore']['Bright_Yellow'] }}{{ setupvars['IPV6_ADDRESS']['value'] }}{{ ANSI['Ctl']['Reset'] }}{% endif %} 8 | 9 | {% if 'public_ip' in host %}Pub IPv4 Addr: {{ ANSI['Fore']['Bright_Yellow'] }}{{ host['public_ip'] }}{{ ANSI['Ctl']['Reset'] }}{% endif %} 10 | 11 | DNS Server(s): {{ ANSI['Fore']['Bright_Yellow'] }}{{ setupvars['PIHOLE_DNS_1']['value'] }}{% if 'PIHOLE_DNS_2' in setupvars %}, {{ setupvars['PIHOLE_DNS_2']['value'] }}{% endif %}{{ ANSI['Ctl']['Reset'] }} 12 | 13 | {{ ANSI['Fore']['Bright_Cyan'] }}QUERY TYPES{{ ANSI['Ctl']['Reset'] }} 14 | {%- for q in querytypes %} 15 | {{ q['type']['str'] }} {{ q['value']['value'] }}% 16 | {%- endfor %} 17 | -------------------------------------------------------------------------------- /templates/top_ads.j2: -------------------------------------------------------------------------------- 1 | {{ ANSI['Ctl']['Clear_Screen'] }}{{ ANSI['Ctl']['Home'] }} {{ ANSI['Fore']['Bright_Cyan'] }}TOP ADS {{ ANSI['Fore']['Magenta'] }}{{ datetime['combined']['value'] }}{{ ANSI['Ctl']['Reset'] }} 2 | {{ ANSI['Fore']['Bright_Yellow'] }}Rank URL Hits{{ ANSI['Ctl']['Reset'] }} 3 | {%- for ad in top_ads %} 4 | {{ loop.cycle(ANSI['Fore']['Red'], ANSI['Fore']['Green'], ANSI['Fore']['Blue']) }} {{ ad['rank']['int'] }} : {{ ad['url']['str40'] }} {{ ad['hits']['value'] }}{{ ANSI['Ctl']['Reset'] }} 5 | {%- endfor %} 6 | -------------------------------------------------------------------------------- /templates/top_clients.j2: -------------------------------------------------------------------------------- 1 | {{ ANSI['Ctl']['Clear_Screen'] }}{{ ANSI['Ctl']['Home'] }} {{ ANSI['Fore']['Bright_Cyan'] }}TOP CLIENTS {{ ANSI['Fore']['Magenta'] }}{{ datetime['combined']['value'] }}{{ ANSI['Ctl']['Reset'] }} 2 | {{ ANSI['Fore']['Bright_Yellow'] }}Rank Client Hits{{ ANSI['Ctl']['Reset'] }} 3 | {%- for d in top_clients %} 4 | {{ loop.cycle(ANSI['Fore']['Red'], ANSI['Fore']['Green'], ANSI['Fore']['Magenta']) }} {{ d['rank']['int'] }} : {% if d['hostname']['value'] == "" %}{{ d['IP']['str'] }}{% else %}{{ d['hostname']['str'] }}{% endif %}{{ d['requests']['value'] }}{{ ANSI['Ctl']['Reset'] }} 5 | {%- endfor %} 6 | -------------------------------------------------------------------------------- /templates/top_domains.j2: -------------------------------------------------------------------------------- 1 | {{ ANSI['Ctl']['Clear_Screen'] }}{{ ANSI['Ctl']['Home'] }} {{ ANSI['Fore']['Bright_Cyan'] }}TOP DOMAINS {{ ANSI['Fore']['Magenta'] }}{{ datetime['combined']['value'] }}{{ ANSI['Ctl']['Reset'] }} 2 | {{ ANSI['Fore']['Bright_Yellow'] }}Rank URL Hits{{ ANSI['Ctl']['Reset'] }} 3 | {%- for d in top_domains %} 4 | {{ loop.cycle(ANSI['Fore']['Red'], ANSI['Fore']['Green'], ANSI['Fore']['Magenta']) }} {{ d['rank']['int'] }} : {{ d['url']['str40'] }} {{ d['hits']['value'] }}{{ ANSI['Ctl']['Reset'] }} 5 | {%- endfor %} 6 | --------------------------------------------------------------------------------