Repository: SlapBot/powir Branch: master Commit: 0b8225fefa1e Files: 39 Total size: 140.6 KB Directory structure: gitextract_qjeyn6au/ ├── .gitignore ├── LICENSE ├── README.md ├── package.json ├── public/ │ ├── app/ │ │ ├── menu.js │ │ ├── parse.js │ │ ├── scrape.js │ │ └── server.js │ ├── assets/ │ │ ├── css/ │ │ │ └── fonts.css │ │ └── images/ │ │ └── download.txt │ ├── browser.js │ ├── electron.js │ ├── index.html │ └── manifest.json └── src/ ├── App.js ├── components/ │ ├── AboutWindow.js │ ├── ActionsWindow.js │ ├── Body.js │ ├── Broadcast.js │ ├── ContentWindow.js │ ├── Footer.js │ ├── InformationWIndow.js │ ├── LinksWindow.js │ ├── Navbar.js │ ├── Sidebar.js │ ├── sub-components/ │ │ ├── Chart.js │ │ ├── ChartData.js │ │ ├── CurrentBatteryEstimate.js │ │ ├── KeyValueInformationTable.js │ │ ├── RecentBatteryEstimate.js │ │ └── SidebarRow.js │ └── utils/ │ ├── config.js │ ├── fetcher.js │ ├── liteMode.js │ ├── mainMode.js │ └── openExternalLink.js ├── index.css ├── index.js └── serviceWorker.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. # dependencies /node_modules /.pnp .pnp.js # testing /coverage # production /build # misc .DS_Store .env.local .env.development.local .env.test.local .env.production.local npm-debug.log* yarn-debug.log* yarn-error.log* .idea/ dist/ battery-report.html battery-report.xml output.json update.json battery-debug-reports/ ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: README.md ================================================

Logo

Powir

Windows 10 based tool to monitor and analyze your system's power and battery usage
Explore the website »

Join Slack · Report Bug · Request Feature · Give Feedback


![](demos/gifs/powir-main.gif) ## Table of Contents * [About the Project](#about-the-project) * [What is it?](#what-is-it) * [Installation](#installation) * [Features](#features) * [What it does?](#what-it-does) * [Why build it?](#why-build-it) * [Actions?](#actions) * [Gallery](#gallery) * [Battery Information](#battery-information) * [System Information](#system-information) * [Power And Battery Usage](#power-and-battery-usage) * [Installation Methods](#installation-methods) * [Desktop App (Main Mode)](#desktop-app-main-mode) * [Browser And Windows Defender Warnings](#browser-and-windows-defender-warnings) * [Solution](#solution) * [Browser Window (Lite Mode)](#browser-window-lite-mode) * [FAQs](#faqs) * [Developer](#developer) * [Prerequisites](#prerequisites) * [Setup](#setup) * [Build](#build) * [Usage](#usage) * [Contributing](#contributing) * [License](#license) * [Contact](#contact) * [Acknowledgement](#acknowledgement)
## About The Project ### What is it? Powir is a Windows 10 based tool to monitor and analyze your system's power and battery usage. It provides you with various information and statistics about the current and overall history of the power and battery usage of your system. ### Installation There are two ways to install powir: - [Desktop App (Main Mode)](#desktop-app-main-mode): Installation is as quick as simply downloading the executable and running it. The App is completely portable meaning you don't have to go through an installation wizard, and it can be copied from system to system seamlessly without any dependencies or extra files needed. **Recommended** - Terminal: Simply download the binary and run it: ```bash curl -L https://github.com/SlapBot/powir/releases/download/v1.0.4/powir.1.0.4.exe --output powir.exe ./powir ``` - Double Click: Again [download](#desktop-app-main-mode) the binary and run it but please read this [note](#browser-and-windows-defender-warnings) - [Browser Window (Lite Mode)](#browser-window-lite-mode): Installation requires few pre-requisites (node & npm) and firing a command from the command prompt which opens up a tab in your default browser serving file via a local server. Actions (Export PDF, JSON) are missing in the lite mode. ## Features ![](demos/processed-screenshots/about.png) ### What it does? - Provides you with a simple and clean UI to list your battery and system information. - Shows you the change in battery capacity since the OS was installed. - Analyzes the current and overall estimated battery life of your system. - Computes various statistics to give a better understanding of your power usage. - Ability to export all the data via various formats: PDF (app), JSON (processed), HTML (original report). - 100% free and completely open-source for an absolute transparency. - Completely portable app with no installation required, ready to use out of the box. ### Why build it? - Complete lack of any such power/battery monitoring analyzing tool available in the market. - Obscure documentation over how to find battery statuses on the Internet. - Required to use terminal in order to run a command showing information about the system. - Devoid of any simple and understandable metrics from the underlying API or report. ### Actions ![](demos/processed-screenshots/actions.png) - Export the current report of your system from Powir in PDF format - Export the parsed and processed data of your system from Powir in JSON format - Shows original report generated by Windows using the command: `powercfg /batteryreport` in the terminal ## Gallery ### Battery Information ![](demos/processed-screenshots/battery-information.png) ### System Information ![](demos/processed-screenshots/system-information.png) ### Power And Battery Usage ![](demos/processed-screenshots/recent-usage.png) ## Installation Methods ### Desktop App (Main Mode) - Simply go to [Releases](https://github.com/SlapBot/powir/releases) and pick the latest version to download. - Download Current Latest Version (Powir v1): [Github](https://github.com/SlapBot/powir/releases/latest/download/powir.1.0.4.exe) or [GDrive](https://drive.google.com/drive/folders/1ntEjEenEzZXMP8L_nXNoHnIFqNSLpwD9): **Please take a note below before downloading the app** #### Browser And Windows Defender Warnings Note: Since the application isn't code signed yet ([because all of the certificates require annual fee payment regardless of whether you're non-profit or open-source](https://stackoverflow.com/questions/1177552/code-signing-certificate-for-open-source-projects)). Please refer to the issue: [#1](https://github.com/SlapBot/powir/issues/1), Both (Browser & Windows Defender will raise warnings suggesting that app is not protected). This doesn't mean that application is inherently unsafe in fact entire source code is open, and you can build your own distribution following [Build](#build) section but its due to the paperwork and money involved in getting the certificates to sign the applications [which can cost as much as $699 a year or more](https://stackoverflow.com/a/58559506/6303162). If you are someone who has an experience around self signing certificates with Windows based builds which result in bypassing these warnings, kindly reply in the given thread [#1](https://github.com/SlapBot/powir/issues/1) :) #### Solution For now the solution is to simply ignore the warnings as shown below and always download the application from this [repository](https://github.com/SlapBot/powir) only: ![](demos/processed-screenshots/browser-warning.png) ![](demos/gifs/windows-defender-warnings.gif) --- ### Browser Window (Lite Mode) Open up the terminal (for non-developers: that is Command Prompt [cmd.exe]) and follow these instructions: #### Only one time setup Commands (copy-paste): ```bash git clone https://github.com/SlapBot/powir.git cd powir npm install --production ``` Explanation: - Ensure you have git, node and npm installed using commands: `git --version`, `node -v` and `npm -v` respectively, else install it from here: [Git](https://git-scm.com/downloads) and [NodeJS](https://nodejs.org/en/download/) (installer contains both node and npm) - Clone the repository using: `git clone https://github.com/SlapBot/powir.git` and cd into the folder: `cd powir` - Run `npm install --production` to install dependencies #### Anytime Command (copy-paste) ```bash npm run lite-mode ``` Explanation: - Now simply run `npm run lite-mode` whenever you want from the directory, and it will open up the dashboard allowing you to monitor and analyze power states. ## FAQs ![](demos/processed-screenshots/FAQs.png) Is it completely free? Yes, Powir is 100% free to download and use. Are the numbers displayed 100% correct? Depends, Powir parses the raw reports generated from Windows and does the computations of the various statistics and render the charts. What tooling is used to build the app? Powir runs as an electron app (chromium web engine embedded) while using React to facilitate the UI and data workflow. Does it share my data anywhere? No, Powir will never share your data anywhere outside your local system, the entire source code of the app is online for anyone to check. In fact, it never makes any request to a server since there is none. Its simply a client sided app.
## Developer If you're looking to build it from the source or inspect the app, its extremely simply and you only have to follow few instructions as listed below: ### Prerequisites - Git - Node - NPM ### Setup - Clone the repository: `git clone https://github.com/SlapBot/powir.git` - Cd into the directory: `cd powir` and run: `npm install` ### Build - Run `npm run build` which will package the app at `dist/` folder. ### Usage #### Electron App - Run these two commands in two separate sessions when you are developing in order to use HMR (hot module reloading): - Run react server: `npm run react-start` - Run electron app: `npm run electron-start` - All of the server code is located at: `public/server` directory. - Entrypoint of the electron app is at`public/electron.js`. - Everything related to rendering is done at: `src` directory. - Any of the changes you make at src directory will reflect instantly in the app. - Any of the changes made for server requires the app to be restarted using: `npm run electron-start` #### Browser Window App - Run `npm run lite-mode` which opens up a tab in your default browser again with HMR enabled. - Entrypoint of the browser window app is at`public/browser.js`. - Everything related to rendering is done at: `src` directory. - Any of the changes you make at src directory will reflect instantly in the app. - Any of the changes made for server requires the app to be restarted using: `npm run lite-mode` ## Contributing Contributions are what make the open source community such an amazing place to be learn, inspire, and create. Any contributions you make are **greatly appreciated**. 1. Fork the Project 2. Create your Feature Branch (`git checkout -b feature/AmazingFeature`) 3. Commit your Changes (`git commit -m 'Add some AmazingFeature'`) 4. Push to the Branch (`git push origin feature/AmazingFeature`) 5. Open a Pull Request Feel free to join our slack chat group to get more help: [Slack](https://join.slack.com/t/powir/shared_invite/zt-ezy7sf5d-Tt1MmP_bcf_gdGLEJSEfzw) ## License Distributed under the GPU General Public License. See `LICENSE` for more information. ## Contact Hey there! I'm [Ujjwal](https://twitter.com/ugupta41) who goes around with the name Slapbot in open source communities, You'd often find me blabbering my completely biased opinions in /r/soccer or busy building new things. I'm most accessible via Twitter and tend to update about whatever I'm working there, so feel free to follow or send a dm there. :) ## Acknowledgement Many thanks to these amazing frameworks/libraries/tools/arts without which none of this had been possible! <3 #### Major Libraries - [ElectronJS](https://www.electronjs.org/) - [NodeJS](https://nodejs.org/en/) - [ReactJS](https://reactjs.org/) - [Tailwind](https://tailwindcss.com/) - [PaperCSS](https://www.getpapercss.com/) - [ChartJS](https://www.chartjs.org/) #### Minor Libraries - [Lodash](https://lodash.com/) - [JSSoup](https://github.com/chishui/JSSoup) - [JSSoup](https://github.com/chishui/JSSoup) #### Icons - [Icons8](https://icons8.com/) ================================================ FILE: package.json ================================================ { "name": "powir", "version": "1.0.4", "description": "Windows 10 based tool to monitor and analyze your system's power and battery usage", "main": "public/electron.js", "repository": { "type": "git", "url": "git+https://github.com/SlapBot/powir.git" }, "author": { "name": "Ujjwal Gupta", "email": "ugupta41@gmail.com", "url": "https://http://slapbot.me/" }, "keywords": [ "electron", "battery", "windows-battery", "react", "battery-monitoring", "battery-analyzer" ], "build": { "productName": "powir", "appId": "powir.slapbot.me", "win": { "icon": "build/icon.ico", "target": "portable" } }, "homepage": "./", "private": true, "dependencies": { "@testing-library/jest-dom": "^4.2.4", "@testing-library/react": "^9.3.2", "@testing-library/user-event": "^7.1.2", "axios": "^0.19.2", "chart.js": "^2.9.3", "electron-is-dev": "^1.2.0", "electron-log": "^4.2.0", "jssoup": "0.0.11", "lodash": "^4.17.15", "react": "^16.13.1", "react-chartjs-2": "^2.9.0", "react-dom": "^16.13.1", "react-scripts": "3.4.1" }, "scripts": { "browser-react-start": "node public/browser.js&&set REACT_APP_LITE_MODE=1&&react-scripts start", "react-start": "set BROWSER=none&&set REACT_APP_LITE_MODE=0&&react-scripts start", "react-build": "react-scripts build", "react-test": "react-scripts test", "react-eject": "react-scripts eject", "electron-start": "set ELECTRON_START_URL=http://localhost:3000 && electron .", "electron-build": "electron-builder", "build": "npm run react-build && npm run electron-build", "lite-mode": "npm run browser-react-start" }, "eslintConfig": { "extends": "react-app" }, "browserslist": { "production": [ ">0.2%", "not dead", "not op_mini all" ], "development": [ "last 1 chrome version", "last 1 firefox version", "last 1 safari version" ] }, "devDependencies": { "electron": "^9.0.0", "electron-builder": "^22.6.1" } } ================================================ FILE: public/app/menu.js ================================================ function getMenuTemplate(server) { return [ // { role: 'fileMenu' } { label: 'File', submenu: [ { label: 'Main Website', click: async () => { await server.openLink('https://powir.slapbot.me') } },{ label: 'Author', click: async () => { server.showAuthorPage() } }, { type: 'separator' }, { role: 'quit' } ] }, // { role: 'editMenu' } { label: 'Actions', submenu: [ { label: 'Export JSON', click: async () => { server.exportJSONData() } }, { label: 'Export PDF', click: async () => { server.exportPDFReport() } }, { type: 'separator' }, { label: 'Display Original Report', click: async () => { server.showOriginalReport() } }, ] }, { label: 'View', submenu: [ { role: 'resetzoom' }, { role: 'zoomin' }, { role: 'zoomout' }, { type: 'separator' }, { role: 'togglefullscreen' } ] }, { label: 'Tools', submenu: [ { role: 'reload' }, { role: 'forcereload' }, { role: 'toggledevtools' }, ] }, { role: 'help', submenu: [ { label: 'Issues/Bugs', click: async () => { await server.openLink('https://github.com/slapbot/powir/issues') } },{ label: 'Chat/Updates', click: async () => { await server.openLink('https://twitter.com/ugupta41') } },{ label: 'Feedback/Enquiry', click: async () => { await server.openLink('https://slapbot.me') } } ] } ] } module.exports = { getMenuTemplate } ================================================ FILE: public/app/parse.js ================================================ function parseUsageInfo(data, colElements, cleanerFn) { return colElements.map((colElement, colIndex) => { let formattedElement = cleanerFn(colElement.text) switch (colIndex) { // Start-time: date time/time case 0: if (formattedElement.split(" ").length === 1) { return data[data.length-1][colIndex].split(" ")[0] + " " + formattedElement } break case 2: // Source: AC/Battery if (formattedElement === "") { return data[data.length-1][colIndex] + formattedElement } break case 3: // Energy Drained: Percentage / - if (formattedElement === '-') { return "0 %" } break case 4: // Energy Drained: mWh / - if (formattedElement === '-') { return "0 mWh" } break default: break } return formattedElement }) } function parseHistoryInfo(data, colElements, cleanerFn) { function addDays(date, days) { date.setDate(date.getDate() + days); return date; } return colElements.map((colElement, colIndex) => { let formattedElement = cleanerFn(colElement.text) switch (colIndex) { // Period: date / date - date case 0: if (formattedElement.split(" - ").length === 1) { return formattedElement + " - " + addDays(new Date(formattedElement), 1) .toISOString().split("T")[0] } if (data.length > 0) { let lastDate = new Date(data[data.length - 1][colIndex].split(" - ")[1]) let currentDate = new Date(formattedElement.split(" - ")[0]) if (lastDate > currentDate) { return addDays(currentDate, 1).toISOString().split("T")[0] + " - " + formattedElement.split(" - ")[1] } } break default: if (formattedElement === "-") { return "0:00:00" } break } return formattedElement }) } module.exports = { parseUsageInfo, parseHistoryInfo } ================================================ FILE: public/app/scrape.js ================================================ const { exec } = require('child_process') const { readFile, writeFile } = require('fs') const parser = require('./parse') const JSSoup = require('jssoup').default function generateBatteryReport(cmd) { return new Promise((resolve, reject) => { exec(cmd, (err, stdout, stderr) => { if (stdout) { resolve(stdout) } if (stderr) { reject(stderr) } reject(err) }) }) } function getHtmlFromFile(path) { return new Promise((resolve, reject) => { readFile(path, 'utf-8', (err, data) => { if (data) { resolve(data) } reject(err) }) }) } function readDataFromFile(path) { return new Promise((resolve, reject) => { readFile(path, 'utf-8', (err, data) => { if (data) { resolve(JSON.parse(data)) } reject(err) }) }) } function writeDataToFile(data, path) { return new Promise((resolve, reject) => { writeFile(path, data, (err) => { if (err) { reject(err) } resolve(true) }); }) } function getSoupInstance(html) { return new JSSoup(html); } function getTables(soup) { // noinspection JSUnresolvedFunction return soup.findAll('table') } function cleanNewlineText(text) { return text.replace(/\r?\n|\r/g, "").replace(/\s+/g, ' ').trim() } function getNote(soup, index) { switch (index) { // Don't want to scrape this part in case Windows changes the DOM and hence increasing stability case 0: return "Information about your system" case 1: return "Information about each currently installed battery" case 2: return "Power states over the last few days" case 3: return "Battery drains over the last few days" case 4: return "History of system usage on AC and battery" case 5: return "Charge capacity history of the system's batteries" case 6: return "Battery life estimates based on observed drains" case 7: return "Current estimate of battery life based on all observed drains since OS install" default: return cleanNewlineText(soup[index].previousSibling.text) } } function getKeyValueInfo(data, rInfo) { // noinspection JSUnresolvedFunction let colElements = rInfo.findAll('td') if (colElements.length > 1 && cleanNewlineText(colElements[0].text)) { data[0].push(cleanNewlineText(colElements[0].text)) data[1].push(cleanNewlineText(colElements[1].text)) } return data } function getTabulatedKeys(data, rawInfo, index) { // noinspection JSUnresolvedFunction let colElements = rawInfo[index].findAll("td").reduce((data, element) => { let formattedElement = cleanNewlineText(element.text) if (formattedElement) { data.push(formattedElement) } return data }, []) if (colElements.length === 0) { return colElements } switch (data.name) { case 'powerUsageInfo': case 'batteryUsageInfo': return colElements.splice(0, colElements.length - 1).concat([ colElements[colElements.length - 1] + " (PERCENTAGE)", colElements[colElements.length - 1] + " (VALUE)" ]) case 'powerUsageHistoryInfo': case 'batteryLifeHistory': // noinspection JSUnresolvedFunction let colSubElements = rawInfo[0].findAll("td").reduce((data, element) => { let formattedElement = cleanNewlineText(element.text) if (formattedElement) { data.push(formattedElement) } return data }, []) if (colSubElements.length < 2) { return colElements } return colElements.map((colElement, index) => { if (index > 0 && index < 3) { return colElement + ' (' + colSubElements[0] + ')' } if (index > 2 && index < 5) { return colElement + ' (' + colSubElements[1] + ')' } return colElement }) default: return colElements } } function getTabulatedData(data, rInfo) { // noinspection JSUnresolvedFunction let colElements = rInfo.findAll("td") let result = {} if (colElements.length > 2) { switch (data.name) { case 'powerUsageInfo': case 'batteryUsageInfo': result = parser.parseUsageInfo( data.data, colElements.filter(colElement => colElement.text), cleanNewlineText ) break case 'powerUsageHistoryInfo': case 'batteryCapacityHistory': case 'batteryLifeHistory': result = parser.parseHistoryInfo( data.data, colElements.filter(colElement => colElement.text), cleanNewlineText ) break case 'batteryLifeOverallHistory': result = colElements .map(colElement => { let resultElement = cleanNewlineText(colElement.text) if (resultElement === "-") { return "0:00:00" } return resultElement }).filter(colElement => colElement) break default: result = colElements .filter(colElement => colElement) .map(colElement => cleanNewlineText(colElement.text)) break } data.data.push(result) } return data } function computeInfo(soup, infoName, index, filterType) { let info = { 'name': infoName, 'note': "", 'keys': [], 'data': [] } info.note = getNote(soup, index) let rawInfo = soup[index].findAll('tr') switch (filterType) { case 'KEY_VALUE': [info.keys, info.data] = rawInfo.reduce(getKeyValueInfo, [[], []]); break case 'TABULATED_SIMPLE': info.keys = getTabulatedKeys({name: infoName}, rawInfo, 0) info.data = rawInfo.slice(1).reduce(getTabulatedData, {name: infoName, data: []}).data break case 'TABULATED_COMPLEX': info.keys = getTabulatedKeys({name: infoName}, rawInfo, 1) info.data = rawInfo.slice(2).reduce(getTabulatedData, {name: infoName, data: []}).data break case 'TABULATED_OVERALL': // hardcoded keys to ensure no dependency over each table scrape to ensure concurrency. info.keys = ["PERIOD", "ACTIVE (AT FULL CHARGE)", "CONNECTED STANDBY (AT FULL CHARGE)", "ACTIVE (AT DESIGN CAPACITY)", "CONNECTED STANDBY (AT DESIGN CAPACITY)" ] info.data = rawInfo.reduce(getTabulatedData, {name: infoName, data: []}).data break default: return info } return info } function getInfo(soup, infoName, index, filterType) { return new Promise((resolve, reject) => { // noinspection JSUnresolvedFunction try { let info = computeInfo(soup, infoName, index, filterType) resolve(info) } catch (e) { resolve({ 'name': infoName, 'note': getNote(soup, index), 'keys': [], 'data': [] }) } }) } async function scrape(html) { let soup = getSoupInstance(html) let tables = getTables(soup) let values = [ {tables: tables, name: 'systemInfo', index: 0, filterType: 'KEY_VALUE'}, {tables: tables, name: 'batteryInfo', index: 1, filterType: 'KEY_VALUE'}, {tables: tables, name: 'powerUsageInfo', index: 2, filterType: 'TABULATED_SIMPLE'}, {tables: tables, name: 'batteryUsageInfo', index: 3, filterType: 'TABULATED_SIMPLE'}, {tables: tables, name: 'powerUsageHistoryInfo', index: 4, filterType: 'TABULATED_COMPLEX'}, {tables: tables, name: 'batteryCapacityHistory', index: 5, filterType: 'TABULATED_SIMPLE'}, {tables: tables, name: 'batteryLifeHistory', index: 6, filterType: 'TABULATED_COMPLEX'}, {tables: tables, name: 'batteryLifeOverallHistory', index: 7, filterType: 'TABULATED_OVERALL'}, ] return Promise.all( values.map(info => getInfo(info.tables, info.name, info.index, info.filterType)) ) } module.exports = { generateBatteryReport, getHtmlFromFile, scrape, readDataFromFile, writeDataToFile } ================================================ FILE: public/app/server.js ================================================ const { BrowserWindow, dialog, shell } = require('electron') const path = require('path') const isDev = require('electron-is-dev') const scraper = require('./scrape') const axios = require('axios'); const logger = require('electron-log') function getBatteryReport() { return scraper.generateBatteryReport( 'powercfg batteryreport output "battery-report.html" duration 5' ) .catch(error => log('error', error)) .then(_ => scraper.getHtmlFromFile('battery-report.html')) .catch(error => log(error)) .then(html => scraper.scrape(html)) .catch(error => log(error)) // return scraper.getHtmlFromFile('battery-report.html') // .catch(error => log(error)) // .then(html => scraper.scrape(html)) } let batteryReport = getBatteryReport() function sendBatteryReport(event, _) { batteryReport.then(data => { event.reply('battery-report', data) }).catch(error => log('error', error)) } function showOriginalReport() { const win = new BrowserWindow({ width: 800, height: 600, }) win.loadURL( isDev ? `file://${path.join(__dirname, '../../battery-report.html')}` : `file://${path.join(__dirname, '../../../../battery-report.html')}` ).catch(error => log('error', error)) } function showAuthorPage() { const win = new BrowserWindow({ width: 800, height: 600, show: false, }) win.maximize() win.show() win.loadURL(`https://slapbot.me`).catch(error => log('error', error)) } function exportJSONData() { let options = { title: "Export Data: JSON format", defaultPath : __dirname + '/powir-data.json', buttonLabel : "Save JSON", filters :[ {name: 'JSON', extensions: ['json']}, {name: 'All Files', extensions: ['*']} ] } dialog.showSaveDialog(null, options).then(result => { batteryReport.then(data => scraper.writeDataToFile(JSON.stringify(data, null, 4), result.filePath)) .catch(error => log('error', error)) .then(_ => log('JSON saved!')) .catch(error => log('error', error)) }).catch(error => log('error', error)) } function exportPDFReport() { function pdfSettings() { return { landscape: false, marginsType: 0, printBackground: false, printSelectionOnly: false, pageSize: 'A4', scaleFactor: 100 }; } let currentWindow = BrowserWindow.getAllWindows().filter(window => window.isVisible())[0] let options = { title: "Export Report: PDF format", defaultPath : __dirname + '/powir-report.pdf', buttonLabel : "Save PDF", filters :[ {name: 'PDF', extensions: ['pdf']}, {name: 'All Files', extensions: ['*']} ] } currentWindow.webContents.printToPDF(pdfSettings()).then(data => { dialog.showSaveDialog(null, options).then(result => { scraper.writeDataToFile(data, result.filePath).then(_ => log('PDF saved!')) .catch(error => log('error', error)) }).catch(err => log(err)) }).catch(err => log(err)) } function openLink(url) { return shell.openExternal(url) } function makeGetRequest(url) { return axios.get(url) } function getUpdates(event, data) { makeGetRequest(data.url).then(response => { event.reply('receive-updates', response.data) }).catch(error => log('error', error)) } function log(type, message) { console.log(type, message) logger.log(message) } module.exports = { sendBatteryReport, showOriginalReport, exportJSONData, exportPDFReport, openLink, showAuthorPage, getUpdates, log } ================================================ FILE: public/assets/css/fonts.css ================================================ @font-face { font-family: 'Neucha'; font-style: normal; font-weight: 400; src: local('Neucha'), url(https://fonts.gstatic.com/s/neucha/v11/q5uGsou0JOdh94bfvQlo.ttf) format('truetype'); } @font-face { font-family: 'Patrick Hand SC'; font-style: normal; font-weight: 400; src: local('Patrick Hand SC'), local('PatrickHandSC-Regular'), url(https://fonts.gstatic.com/s/patrickhandsc/v7/0nkwC9f7MfsBiWcLtY65AWDK873ljiK-.ttf) format('truetype'); } ================================================ FILE: public/assets/images/download.txt ================================================ https://img.icons8.com/doodle/20/000000/delete-sign.png https://img.icons8.com/doodle/48/000000/picture.png https://img.icons8.com/doodle/48/000000/hourglass--v1.png https://img.icons8.com/doodle/48/000000/statistics--v1.png https://img.icons8.com/doodle/48/000000/rescan-document.png https://img.icons8.com/doodle/48/000000/console--v2.png https://img.icons8.com/doodle/48/000000/audio-cable.png https://img.icons8.com/doodle/48/000000/error.png https://img.icons8.com/doodle/48/000000/delete-sign.png https://img.icons8.com/doodle/48/000000/iphone-spinner.png https://img.icons8.com/doodle/48/000000/api.png https://img.icons8.com/doodle/48/000000/windows-client.png https://img.icons8.com/doodle/48/000000/so-so.png https://img.icons8.com/doodle/48/000000/used-product.png https://img.icons8.com/doodle/48/000000/hammer--v1.png https://img.icons8.com/doodle/48/000000/help.png https://img.icons8.com/doodle/48/000000/pdf.png https://img.icons8.com/doodle/48/000000/code-file.png https://img.icons8.com/doodle/48/000000/select-all.png https://img.icons8.com/cotton/24/000000/copyright.png https://img.icons8.com/doodle/48/000000/high-battery.png https://img.icons8.com/doodle/48/000000/windows8.png https://img.icons8.com/doodle/48/000000/lightning-arrow.png https://img.icons8.com/doodle/48/000000/link.png https://img.icons8.com/doodle/48/000000/twitter-circled.png https://img.icons8.com/doodle/48/000000/facebook.png https://img.icons8.com/doodle/48/000000/email-sign.png https://img.icons8.com/doodle/48/000000/linkedin-circled.png https://img.icons8.com/doodle/48/000000/reddit.png https://img.icons8.com/doodle/48/000000/repository.png https://img.icons8.com/doodle/48/000000/comments.png https://img.icons8.com/doodle/48/000000/mail-contact.png https://img.icons8.com/doodle/48/000000/share--v1.png https://img.icons8.com/doodle/48/000000/github--v1.png https://img.icons8.com/doodle/48/000000/twitter--v1.png https://img.icons8.com/cotton/64/000000/like--v1.png https://img.icons8.com/ios/24/000000/help.png ================================================ FILE: public/browser.js ================================================ const scraper = require('./app/scrape') const axios = require('axios'); const broadcastUrl = 'https://gist.github.com/SlapBot/4b093f88d97522e22205ae9c9d0dea02/raw/' function getBatteryReport() { return scraper.generateBatteryReport( 'powercfg batteryreport output "public/battery-report.html" duration 5' ) .catch(error => console.log('error', error)) .then(_ => scraper.getHtmlFromFile('public/battery-report.html')) .catch(error => console.log(error)) .then(html => scraper.scrape(html)) .catch(error => console.log(error)) } function getUpdates(url) { return axios.get(url) } getBatteryReport() .then(data => scraper.writeDataToFile(JSON.stringify(data, null, 4), 'public/output.json')) .catch(error => console.log(error)) .then(_ => console.log('Done!')) getUpdates(broadcastUrl) .then(response => scraper.writeDataToFile(JSON.stringify(response.data, null, 4), 'public/update.json')) .catch(error => console.log(error)) .then(_ => console.log('Done!')) ================================================ FILE: public/electron.js ================================================ const { app, BrowserWindow, ipcMain, Menu } = require('electron') const path = require('path') const isDev = require('electron-is-dev') const server = require('./app/server') const { getMenuTemplate } = require('./app/menu') function createWindow () { const win = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true, enableRemoteModule: true, }, show: false }) win.maximize() win.show() // and load the index.html of the app. win.loadURL( isDev ? "http://localhost:3000" : `file://${path.join(__dirname, '../build/index.html')}` ).catch(error => server.log('error', error)) // Open the DevTools. isDev ? win.webContents.openDevTools() : null } const menuTemplate = getMenuTemplate(server) const menu = Menu.buildFromTemplate(menuTemplate) Menu.setApplicationMenu(menu) // This method will be called when Electron has finished // initialization and is ready to create browser windows. // Some APIs can only be used after this event occurs. app.whenReady().then(createWindow) // Quit when all windows are closed. app.on('window-all-closed', () => { // On macOS it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() } }) app.on('activate', () => { // On macOS it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (BrowserWindow.getAllWindows().length === 0) { createWindow() } }) // In this file you can include the rest of your app's specific main process // code. You can also put them in separate files and require them here. ipcMain.on('battery-report-ready', (event, data) => { server.sendBatteryReport(event, data) }) ipcMain.on('show-original-report', (event, data) => { server.showOriginalReport() }) ipcMain.on('export-JSON-data', (event, data) => { server.exportJSONData() }) ipcMain.on('export-PDF-report', (event, data) => { server.exportPDFReport() }) ipcMain.on('get-updates', (event, data) => { server.getUpdates(event, data) }) ipcMain.on('open-link', async (event, data) => { server.openLink(data.url).catch(error => server.log(error)) }) ================================================ FILE: public/index.html ================================================ Powir

Loading...

================================================ FILE: public/manifest.json ================================================ { "short_name": "React App", "name": "Create React App Sample", "icons": [ { "src": "favicon.ico", "sizes": "64x64 32x32 24x24 16x16", "type": "image/x-icon" } ], "start_url": ".", "display": "standalone", "theme_color": "#000000", "background_color": "#ffffff" } ================================================ FILE: src/App.js ================================================ import React from 'react'; import { defaults } from 'react-chartjs-2'; import Navbar from "./components/Navbar"; import Body from "./components/Body"; import Footer from "./components/Footer"; import Broadcast from "./components/Broadcast"; defaults.global.defaultFontFamily = 'Neucha' function App() { return (
); } export default App; ================================================ FILE: src/components/AboutWindow.js ================================================ import React from "react"; import openExternalLink from "./utils/openExternalLink"; function AboutWindow() { let features = [ { 'id': 0, 'text': 'Provides you with a simple and clean UI to list your battery and system information.', 'icon': 'assets/images/picture.png' },{ 'id': 1, 'text': 'Shows you the change in battery capacity since the OS was installed.', 'icon': 'assets/images/high-battery.png' },{ 'id': 2, 'text': 'Analyzes the current and overall estimated battery life of your system.', 'icon': 'assets/images/hourglass--v1.png' },{ 'id': 3, 'text': 'Computes various statistics to give a better understanding of your power usage.', 'icon': 'assets/images/statistics--v1.png' },{ 'id': 4, 'text': 'Ability to export all of the data via various formats: PDF (app), JSON (processed), HTML (original report).', 'icon': 'assets/images/rescan-document.png' },{ 'id': 5, 'text': '100% free and completely open-source for absolute transparency.', 'icon': 'assets/images/console--v2.png' },{ 'id': 6, 'text': 'Completely portable app with no installation required, ready to use out of the box.', 'icon': 'assets/images/audio-cable.png' } ] let reasons = [ { 'id': 0, 'text': 'Complete lack of any such power/battery monitoring analyzing tool available in the market.', 'icon': 'assets/images/error.png' },{ 'id': 1, 'text': 'Obscure documentation over how to find battery statuses on the Internet.', 'icon': 'assets/images/delete-sign.png' },{ 'id': 2, 'text': 'Required to use terminal in order to run a command showing information about the system.', 'icon': 'assets/images/iphone-spinner.png' },{ 'id': 3, 'text': 'Devoid of any simple and understandable metrics from the underlying API or report.', 'icon': 'assets/images/api.png' }, ] return (
windows-client

What is Powir?

Powir is a Windows 10 based tool to monitor and analyze your system's power and battery usage.

It provides you with various information and statistics about the current and overall history of the power and battery usage of your system.

so-so

Who built it?

Hey there! I'm who goes around with the name Slapbot in open source communities, You'd often find me blabbering my completely biased opinions in /r/soccer or busy building new things.

I'm most accessible via and tend to update about whatever I'm working there, so feel free to follow or send a dm there. :)

used-product

What it does?

    {features.map(item => { return
  1. {item.icon}/

    {item.text}

  2. })}
hammer--v1

Why build it?

    {reasons.map(item => { return
  1. {item.icon}/

    {item.text}

  2. })}
help

FAQs

Is it completely free?

Yes, Powir is 100% free to download and use.

Are the numbers displayed 100% correct?

Depends, Powir parses the raw reports generated from Windows and does the computations of the various statistics and render the charts.

What tooling was used to build the app?

Powir runs as an electron app (chromium web engine embedded) while using React to facilitate the UI and data workflow.

Does it share my data anywhere?

No, Powir will never share your data anywhere outside your local system, the entire source code of the app is online for anyone to check. Infact, it never makes any request to a server since there is none. Its simply a client sided app.

) } export default AboutWindow ================================================ FILE: src/components/ActionsWindow.js ================================================ import React from "react"; import { sendEvent } from './utils/fetcher' import config from './utils/config' function AboutWindow(props) { function actionsNote() { return config.liteMode ? 'border-bottom pb-4' : 'hidden' } function showOriginalReport() { sendEvent("show-original-report", {status: true}) } function exportJSON() { sendEvent("export-JSON-data", {status: true}) } function exportPDF() { props.toggleInformationWindow() } return (

Note: Actions are only available via electron app: Powir

pdf

Export Report (PDF)

Export the current report of your system from Powir in PDF format:

code-file

Export Data (JSON)

Export the parsed and processed data of your system from Powir in JSON format:

select-all

Original Report

Shows original report generated by Windows using the command: powercfg /batteryreport in the terminal.

) } export default AboutWindow ================================================ FILE: src/components/Body.js ================================================ import React, {useState} from "react"; import ContentWindow from "./ContentWindow"; import Sidebar from "./Sidebar"; import { sendEvent } from './utils/fetcher' function Body() { const [currentSection, setCurrentSection] = useState(0) function notifyContentWindow(index) { setCurrentSection(index) } function setInformationWindow() { setCurrentSection(0) sendEvent("export-PDF-report", {status: true}) } return (
) } export default Body ================================================ FILE: src/components/Broadcast.js ================================================ import React, {useEffect, useState} from "react"; import openExternalLink from './utils/openExternalLink' import config from './utils/config' import { getUpdates } from './utils/fetcher' function Broadcast() { const [broadcastData, setBroadcastData] = useState({ "personal": { "status": false, "text": "" }, "update": { "status": false, "version": config.version, "text": "" }, }) const [shouldRenderPersonal, setShouldRenderPersonal] = useState(false) const [shouldRenderUpdate, setShouldRenderUpdate] = useState(false) function setValues(data) { setBroadcastData(data) if (data.personal.status) { setShouldRenderPersonal(true) } if (data.update.status && data.update.version !== config.version) { setShouldRenderUpdate(true) } } useEffect(() => { console.log("Current Version Running: " + config.version) getUpdates(setValues) }, []) function closePersonalAlert() { setShouldRenderPersonal(false) } function closeUpdateAlert() { setShouldRenderUpdate(false) } function renderMessage(rawText) { if (rawText.split("[").length < 2) { return (

{rawText}

) } let first_part = rawText.split("[")[0] let last_part = rawText.split("[")[1].split("]")[1] let link = rawText.split("[")[1].split("]")[0] return (

{first_part}[ ]{last_part}

) } function render(broadcast, closeCallback, alertClass) { return (
{renderMessage(broadcast.text)} delete-sign
) } return (
{ shouldRenderPersonal ? render(broadcastData.personal, closePersonalAlert, 'alert alert-secondary') : null } { shouldRenderUpdate ? render(broadcastData.update, closeUpdateAlert, 'alert alert-warning') : null }
) } export default Broadcast ================================================ FILE: src/components/ContentWindow.js ================================================ import React from "react"; import InformationWindow from "./InformationWIndow"; import AboutWindow from "./AboutWindow"; import ActionsWindow from "./ActionsWindow"; import LinksWindow from "./LinksWindow"; function ContentWindow(props) { function getToggleStatus(index) { return index === props.index ? "" : "hidden" } return (
) } export default ContentWindow ================================================ FILE: src/components/Footer.js ================================================ import React from "react"; import openExternalLink from "./utils/openExternalLink"; function Footer() { return (
heart
) } export default Footer ================================================ FILE: src/components/InformationWIndow.js ================================================ import React, { useState, useEffect } from "react"; import KeyValueInformationTable from "./sub-components/KeyValueInformationTable"; import Chart from "./sub-components/Chart"; import CurrentBatteryEstimate from "./sub-components/CurrentBatteryEstimate"; import RecentBatteryEstimate from "./sub-components/RecentBatteryEstimate"; import { getReport } from './utils/fetcher' function InformationWindow() { function shouldRenderComponent(component) { return dataFetchStatus ? component : "Loading..." } const [dataFetchStatus, setDataFetchStatus] = useState(false) const [systemInfo, setSystemInfo] = useState({}) const [batteryInfo, setBatteryInfo] = useState({}) const [powerUsageInfo, setPowerUsageInfo] = useState({}) const [batteryUsageInfoData, setBatteryUsageInfoData] = useState({}) const [batteryCapacityHistory, setBatteryCapacityHistory] = useState({}) const [batteryLifeHistory, setBatteryLifeHistory] = useState({}) const [batteryLifeOverallHistory, setBatteryLifeOverallHistory] = useState({}) function setValues(data) { setSystemInfo(data[0]) setBatteryInfo(data[1]) setPowerUsageInfo(data[2]) setBatteryUsageInfoData(data[3]) setBatteryCapacityHistory(data[5]) setBatteryLifeHistory(data[6]) setBatteryLifeOverallHistory(data[7]) setDataFetchStatus(true) } useEffect(() => { getReport(setValues) }, []) return (
{ shouldRenderComponent( )}
{ shouldRenderComponent( ) }
{ shouldRenderComponent( )}
{ shouldRenderComponent( )}
{ shouldRenderComponent( )}
{'lightning-arrow'}/

Recent Power & Battery Usage

Observed power and battery states of the system in the recent time period.
{ shouldRenderComponent( )}
{ shouldRenderComponent( )}
{ shouldRenderComponent( )}
{ shouldRenderComponent( )}
{ shouldRenderComponent( )}
) } export default InformationWindow ================================================ FILE: src/components/LinksWindow.js ================================================ import React from "react"; import openExternalLink from './utils/openExternalLink' function LinksWindow() { let shareLinks = [ { 'id': 0, 'text': 'Copy Link!', 'iconUrl': 'assets/images/link.png', 'url': 'https://powir.slapbot.me' },{ 'id': 1, 'text': 'Tweet about it!', 'iconUrl': 'assets/images/twitter-circled.png', 'url': 'https://twitter.com/intent/tweet?url=powir.slapbot.me&text=Check%20out%20this%20open%20source%20windows%20battery%20monitoring%20app:&hashtags=powir' },{ 'id': 2, 'text': 'Share on Facebook!', 'iconUrl': 'assets/images/facebook.png', 'url': 'http://www.facebook.com/sharer.php?s=100&p[title]=Powir&p[url]=powir.slapbot.me' },{ 'id': 3, 'text': 'Mail to someone!', 'iconUrl': 'assets/images/email-sign.png', 'url': 'mailto:?subject=Powir: open source windows based battery monitoring app&body=Check out app at: https://www.powir.slapbot.me' },{ 'id': 4, 'text': 'Share on Linkedin!', 'iconUrl': 'assets/images/linkedin-circled.png', 'url': 'https://www.linkedin.com/sharing/share-offsite/?url=powir.slapbot.me' },{ 'id': 5, 'text': 'Share on Reddit!', 'iconUrl': 'assets/images/reddit.png', 'url': 'https://www.reddit.com/submit?url=https://powir.slapbot.me&title=Powir:%20Open%20Source%20Windows%20Based%20Battery%20Monitoring%20App' }, ] let helpLinks = [ { 'id': 0, 'heading': 'Issues/Bugs', 'iconUrl': 'assets/images/repository.png', 'url': 'https://github.com/slapbot/powir/issues', 'message': 'Looking for any help related to the product or want to report a bug? Feel free to raise an issue on Github' },{ 'id': 1, 'heading': 'Chat/Updates', 'iconUrl': 'assets/images/comments.png', 'url': 'https://twitter.com/ugupta41', 'message': 'Want to share some insight without signing up on Github or looking for updates? Follow me @ugupta41 on Twitter' },{ 'id': 2, 'heading': 'Feedback/Enquiry', 'iconUrl': 'assets/images/mail-contact.png', 'url': 'mailto:ugupta41@gmail.com', 'message': 'Old school? Write me a mail at: ugupta41@gmail.com' }, ] return (
help

Help

Looking for any kind of help?
{helpLinks.map(helpLink => { return
{helpLink.iconUrl}/

{helpLink.message}
})}
share--v1

Share

Liked the product? Share the good word among your friends :)
{shareLinks.map(shareLink => { return
{shareLink.iconUrl}/

})}
) } export default LinksWindow ================================================ FILE: src/components/Navbar.js ================================================ import React from "react"; import openExternalLink from "./utils/openExternalLink"; import config from "./utils/config"; function Navbar() { function formatVersion(version) { return version.split(".").splice(0, 2).join(".") } return (
openExternalLink('https://powir.slapbot.me')} >

Powir

v{formatVersion(config.version)}
Monitoring & Analyzing Your Battery!
Github openExternalLink('https://github.com/slapbot/powir')} />
Twitter openExternalLink('https://twitter.com/ugupta41')} />
) } export default Navbar ================================================ FILE: src/components/Sidebar.js ================================================ import React, {useState} from "react"; import SidebarRow from "./sub-components/SidebarRow"; import openExternalLink from "./utils/openExternalLink"; function Sidebar(props) { const [sidebarRows, setSideBarRows] = useState([ { 'index': 0, 'name': 'Information', 'rootClass': 'mt-6', 'liClass': 'mb-3', 'spanClass': 'border border-primary p-1' },{ 'index': 1, 'name': 'About', 'rootClass': '', 'liClass': '', 'spanClass': '' },{ 'index': 2, 'name': 'Actions', 'rootClass': '', 'liClass': '', 'spanClass': '' },{ 'index': 3, 'name': 'Links', 'rootClass': '', 'liClass': '', 'spanClass': '' } ]) function notifyBody(sidebarIndex) { setSideBarRows(sidebarRows.map((item, index) => { if (index === sidebarIndex) { return {...item, liClass: 'mt-3 mb-3', spanClass: 'border border-primary p-1'} } return {...item, liClass: '', spanClass: ''} })) props.notifyContentWindow(sidebarIndex) } return (
    {sidebarRows.map( item => )}

Made With

heart

By

100 % open source

) } export default Sidebar ================================================ FILE: src/components/sub-components/Chart.js ================================================ import {Bar, Line, Pie} from "react-chartjs-2"; import React from "react"; import { createData } from "./ChartData"; function Chart(props) { function renderChart(info, type, metaData) { try { return getChart(info, type, metaData) } catch (e) { console.log(e) } } function getChart(info, type, metaData) { let data = createData(info, type, metaData) let options = { scales: { xAxes: [{ display: true, scaleLabel: { display: true, labelString: metaData.xLabel } }], yAxes: [{ display: true, scaleLabel: { display: true, labelString: metaData.yLabel } }] } } switch (type) { case 'batteryCapacityHistory': case 'batteryLifeHistory': return case 'powerUsageInfo': if (metaData.type === 'cumulativePie') { return } else if(metaData.type === 'cumulativeActiveSuspended') { return } else if (metaData.type === 'dailyBar') { return } else if (metaData.type === 'dailyLine') { return } return default: return } } return (

{props.heading}

{props.info.note}
{renderChart(props.info, props.info.name, props.metaData)}
) } export default Chart ================================================ FILE: src/components/sub-components/ChartData.js ================================================ import {groupBy, sortBy} from 'lodash' function createData(info, type, metaData) { switch (type) { case 'batteryCapacityHistory': return createBatteryCapacityData(info) case 'batteryLifeHistory': return createBatteryLifeHistoryData(info) case 'powerUsageInfo': if (metaData.type === 'cumulativePie') { return createCumulativePiePowerUsageInfoData(info) } else if (metaData.type === 'dailyBar') { return createBarPowerUsageInfoData(info) } else if (metaData.type === 'dailyLine') { return createLinePowerUsageInfoData(info) } return createActiveSuspendedPiePowerUsageInfoData(info) default: return { labels: [0, 1], datasets: [{ label: 'Default', backgroundColor: 'red', borderColor: 'red', data: [0, 100], fill: false, }] } } } function createBatteryCapacityData(info) { return info.data.reduce((data, item, index) => { if (index > 0) { if (item[1] === info.data[index-1][1]) { return data } } data.labels.push(item[0].split(" - ")[1]) data.datasets[0].data.push(item[1].split(" ")[0].split(",").join("")) data.datasets[1].data.push(item[2].split(" ")[0].split(",").join("")) return data }, { labels: [], datasets: [{ label: info.keys[1], backgroundColor: 'red', borderColor: 'red', data: [], fill: false, }, { label: info.keys[2], backgroundColor: 'blue', borderColor: 'blue', data: [], fill: false, }] }) } function createBatteryLifeHistoryData(info) { function getDaysInMonth(date) { return new Date(date.getFullYear(), date.getMonth()+1, 0).getDate() } function chooseDate(date) { let [start_date, end_date] = date.split(" - ") if (getDaysInMonth(new Date(start_date)) - new Date(start_date).getDate() > new Date(end_date).getDate()) { return start_date.split("-").slice(0, 2).join("") } return end_date.split("-").slice(0, 2).join("") } function filterOutliers(array) { /* * Reference: https://www.mathworks.com/matlabcentral/cody/problems/42485-eliminate-outliers-using-interquartile-range * Following this approach except we aren't repeating the IQR and elimination process after every step. * */ // Then sort // noinspection JSValidateTypes if (array.length < 4) { return { data: array, indexes: [] } } // noinspection JSValidateTypes let values = sortBy(array) /* Then find a generous IQR. This is generous because if (values.length / 4) * is not an int, then really you should average the two elements on either * side to find q1. */ let q1 = values[Math.floor((values.length / 4))] // Likewise for q3. let q3 = values[Math.ceil((values.length * (3 / 4)))] let iqr = q3 - q1; // Then find min and max values let maxValue = q3 + iqr*1.5; // Then reduce anything beyond or beneath these values. return array.reduce((data, item, index) => { if (item <= maxValue) { data.indexes.push(index) data.data.push(item) return data } return data }, { data: [], indexes: [] }) } function averageDatasetByMonth(value, index) { return value.reduce((data, element) => { data += element[index] return data }, 0) / value.length } let formattedInfo = groupBy(info.data.reduce((data, item) => { if (item[1] === "0:00:00" || item[3] === "0:00:00") { return data } data.push([ chooseDate(item[0]), Number(item[1].split(":")[0])*60 + Number(item[1].split(":")[1]), Number(item[3].split(":")[0])*60 + Number(item[3].split(":")[1]), ]) return data }, []), 0) let activeDataset = [] let designDataset = [] for (let [, value] of Object.entries(formattedInfo)) { activeDataset.push(averageDatasetByMonth(value, 1)) designDataset.push(averageDatasetByMonth(value, 2)) } let filteredDataset = filterOutliers(activeDataset) let filteredActiveDataset = filterOutliers(activeDataset).data let filteredDesignDataset = designDataset.filter((item, index) => filteredDataset.indexes.includes(index)) let labelsDataset = Object.keys(formattedInfo).reduce((data, item, index) => { if (filteredDataset.indexes.includes(index)) { data.push(item.slice(0, 4) + "/" + item.slice(4, 6)) return data } return data }, []) return { labels: labelsDataset, datasets: [{ label: info.keys[1], backgroundColor: 'red', borderColor: 'red', data: filteredActiveDataset, fill: false, }, { label: info.keys[3], backgroundColor: 'blue', borderColor: 'blue', data: filteredDesignDataset, fill: false, }] } } function getGroupedPowerUsageInfoData(info) { let formattedData = info.data.reduce((data, item, index) => { function getDuration(pastItem, currentItem, futureItem) { function getDateObject(dateString) { return new Date(dateString) } function getMidnightDateTime(date) { return new Date(date.toUTCString()).setHours(0, 0, 0, 0) } function getReturnItem(item, duration) { return [ item[0].split(" ")[0], item[0].split(" ")[1], duration / 1000 / 60, item[1], item[2] ] } let past = getDateObject(pastItem[0]) let current = getDateObject(currentItem[0]) let future = getDateObject(futureItem[0]) if (past.getDate() === current.getDate()) { if (future.getDate() === current.getDate()) { return [getReturnItem(currentItem, (future - current))] } return [getReturnItem(currentItem, (getMidnightDateTime(future) - current))] } else { if (future.getDate() === current.getDate()) { return [[ currentItem[0].split(" ")[0], "0:00:00", (current - getMidnightDateTime(current)) / 1000 / 60, 'suspended', null ], getReturnItem(currentItem, (future - current)) ] } return [[ currentItem[0].split(" ")[0], "0:00:00", (current - getMidnightDateTime(current)) / 1000 / 60, 'suspended', null ], getReturnItem(currentItem, (getMidnightDateTime(future) - current)) ] } } switch (index) { case info.data.length-1: return data case 0: return data default: let durations = getDuration( info.data[index-1], item, info.data[index+1] ) durations.map(duration => data.push(duration)) return data } }, []) return groupBy(formattedData, 0) } function getDailySumGroupedPowerUsageInfoData(groupData, filterConditional, segregationConditional) { let powerUsageDataset = [] for (let [, value] of Object.entries(groupData)) { powerUsageDataset.push(value.reduce((data, item) => { if (filterConditional(item)) { return data } if (segregationConditional(item)) { data[0] += item[2] } else { data[1] += item[2] } return data }, [0, 0])) } return powerUsageDataset } function formatPowerUsageInfoTime(minutes) { if (minutes > 59) { return Math.floor(minutes / 60) + ' Hr ' + Math.floor(minutes % 60) + ' Minutes' } return Math.floor(minutes) + ' Minutes' } function createCumulativePiePowerUsageInfoData(info) { let groupData = getGroupedPowerUsageInfoData(info) let powerUsageDataset = getDailySumGroupedPowerUsageInfoData( groupData, (item) => item[3].toLowerCase() === 'suspended', (item) => item[4].toUpperCase() === 'AC' ) let cumulativePowerUsageDataset = powerUsageDataset.reduce((data, item) => { data[0] += Math.floor(item[0]) data[1] += Math.floor(item[1]) return data }, [0, 0]) return { labels: [ 'AC: ' + formatPowerUsageInfoTime(cumulativePowerUsageDataset[0]), 'Battery: ' + formatPowerUsageInfoTime(cumulativePowerUsageDataset[1]) ], datasets: [{ labelString: 'AC vs Battery', backgroundColor: ['green', 'orange'], data: cumulativePowerUsageDataset, fill: false, }] } } function createBarPowerUsageInfoData(info) { let groupData = getGroupedPowerUsageInfoData(info) let powerUsageDataset = getDailySumGroupedPowerUsageInfoData( groupData, (item) => item[3].toLowerCase() === 'suspended', (item) => item[4].toUpperCase() === 'AC' ) let powerUsageActiveSuspendedDataset = getDailySumGroupedPowerUsageInfoData( groupData, (_) => false, (item) => item[3].toLowerCase() === 'active' ) return { labels: Object.keys(groupData), datasets: [{ label: 'AC', backgroundColor: 'green', borderColor: 'green', borderWidth: 1, data: powerUsageDataset.map(item => Math.round((item[0] / 60) * 10) / 10), },{ label: 'Battery', backgroundColor: 'orange', borderColor: 'orange', borderWidth: 1, data: powerUsageDataset.map(item => Math.round((item[1] / 60) * 10) / 10), },{ label: 'ON', backgroundColor: 'blue', borderColor: 'blue', borderWidth: 1, data: powerUsageActiveSuspendedDataset.map(item => Math.round((item[0] / 60) * 10) / 10), },{ label: 'OFF', backgroundColor: 'red', borderColor: 'red', borderWidth: 1, data: powerUsageActiveSuspendedDataset.map(item => Math.round((item[1] / 60) * 10) / 10), }] } } function createActiveSuspendedPiePowerUsageInfoData(info) { let groupData = getGroupedPowerUsageInfoData(info) let powerUsageActiveSuspendedDataset = getDailySumGroupedPowerUsageInfoData( groupData, (_) => false, (item) => item[3].toLowerCase() === 'active' ) let cumulativePowerUsageActiveSuspendedDataset = powerUsageActiveSuspendedDataset.reduce((data, item) => { data[0] += Math.floor(item[0]) data[1] += Math.floor(item[1]) return data }, [0, 0]) return { labels: [ 'ON ' + formatPowerUsageInfoTime(cumulativePowerUsageActiveSuspendedDataset[0]), 'OFF ' + formatPowerUsageInfoTime(cumulativePowerUsageActiveSuspendedDataset[1]) ], datasets: [{ label: 'AC vs Battery', backgroundColor: ['blue', 'red'], data: cumulativePowerUsageActiveSuspendedDataset, fill: false, }] } } function createLinePowerUsageInfoData(info) { let percentageDataset = info.data.reduce((data, item, index) => { let dateString = (date) => date.getMonth()+1 + "/" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() if (index > 1) { let currentPercentage = item[item.length-2] let lastPercentage = info.data[index-1][info.data[index-1].length-2] if (currentPercentage === lastPercentage) { return data } } data.push({ x: dateString(new Date(item[0])), y: item[item.length-2].split(" ")[0] }) return data }, []) return { labels: percentageDataset.map(item => item.x), datasets: [{ label: 'Battery Percentage', backgroundColor: 'red', borderColor: 'red', data: percentageDataset, fill: false }] } } export { createData } ================================================ FILE: src/components/sub-components/CurrentBatteryEstimate.js ================================================ import React from "react"; function CurrentBatteryEstimate(props) { function renderLabel(key) { return key.split("(")[1].split(")")[0].toLowerCase().split(" ").map(element => { return element[0].toUpperCase() + element.slice(1) }).join(" ") } return (

{props.info.data[0][0]}

{props.info.note}
{renderLabel(props.info.keys[1])}:
{props.info.data[0][1]}
{renderLabel(props.info.keys[3])}:
{props.info.data[0][3]}
) } export default CurrentBatteryEstimate ================================================ FILE: src/components/sub-components/KeyValueInformationTable.js ================================================ import React from "react"; function KeyValueInformationTable(props) { function renderInfo(element, index, type) { const extraHelp = [ { 'popoverHelp': "Amount of charge battery was designed to hold.", 'spanClass': 'badge bg-blue text-lg' },{ 'popoverHelp': "Amount of charge battery can currently hold.", 'spanClass': 'badge bg-red text-lg' }, ] switch (type) { case "batteryInfo": switch (index) { case 4: case 5: return
{element}
help
default: return

{element}

} case "systemInfo": switch (index) { case 6: return {element} default: return

{element}

} default: return

{element}

} } return (
{props.iconAlt}/

{props.heading}

{props.info.note} {props.info.keys.map((keyInfo, index) => { return })}
Key Value
{keyInfo} {renderInfo(props.info.data[index], index, props.info.name)}
) } export default KeyValueInformationTable ================================================ FILE: src/components/sub-components/RecentBatteryEstimate.js ================================================ import React from "react"; function RecentBatteryEstimate(props) { function renderValue(formattedData, type) { switch (type) { case 'MINIMUM': if (formattedData.minimum === Infinity) { return 'NONE' } return formatTime(formattedData.minimum) case 'MAXIMUM': if (formattedData.maximum === 0) { return 'NONE' } return formatTime(formattedData.maximum) case 'AVERAGE': if (formattedData.maximum === 0 || formattedData.minimum === Infinity) { return 'NONE' } return formatTime(formattedData.sum/formattedData.count) default: return 'NONE' } } function formatTime(value) { let hours = Math.floor(value / 60) let minutes = Math.floor(value % 60) let seconds = Math.floor((value - Math.floor(value)) * 100) return hours + ":" + (minutes > 9 ? minutes : "0" + minutes) + ":" + seconds } let formattedData = props.info.data.reduce((data, item) => { let percent = Number(item[3].split("%")[0]) let durationMinutes = Number(item[2].split(":")[0])*60 + Number(item[2].split(":")[1]) if (percent === 0 || durationMinutes === 0) { return data } let estimateLife = (durationMinutes * 100) / percent if (estimateLife < data.minimum) { data.minimum = estimateLife } if (estimateLife > data.maximum) { data.maximum = estimateLife } data.sum += estimateLife data.count += 1 return data }, { minimum: Infinity, maximum: 0, sum: 0, count: 0 }) return (

Recent Battery Life Estimate

{props.info.note}
Minimum:
{renderValue(formattedData, 'MINIMUM')}
Maximum:
{renderValue(formattedData, 'MAXIMUM')}
Average:
{renderValue(formattedData, 'AVERAGE')}
) } export default RecentBatteryEstimate ================================================ FILE: src/components/sub-components/SidebarRow.js ================================================ import React from "react"; function SidebarRow(props) { function notifySidebar() { props.notifyBody(props.value.index) } return (
  • ) } export default SidebarRow ================================================ FILE: src/components/utils/config.js ================================================ export default { version: '1.0.4', liteMode: process.env.REACT_APP_LITE_MODE === '1' } ================================================ FILE: src/components/utils/fetcher.js ================================================ import config from "./config"; export function getReport(callbackFunction) { if (config.liteMode) { return import('./liteMode').then(module => module.getResource('output.json', callbackFunction)) } return import('./mainMode').then(module => { module.sendElectronEvent('battery-report-ready', {status: true}) module.getElectronEvent('battery-report', callbackFunction) }) } export function getUpdates(callbackFunction) { const broadcastUrl = config.liteMode ? 'update.json' : 'https://gist.github.com/SlapBot/4b093f88d97522e22205ae9c9d0dea02/raw/' if (config.liteMode) { return import('./liteMode').then(module => module.getResource(broadcastUrl, callbackFunction)) } return import('./mainMode').then(module => { module.sendElectronEvent('get-updates', {url: broadcastUrl}) module.getElectronEvent('receive-updates', callbackFunction) }) } export function sendEvent(channel, data) { if (config.liteMode) { return } return import('./mainMode').then(module => module.sendElectronEvent(channel, data)) } ================================================ FILE: src/components/utils/liteMode.js ================================================ export function openWindowLink(url) { window.open(url, "_blank") } export function getResource(url, callbackFunction) { return fetch(url).then(response => response.json()).then(data => callbackFunction(data)) } ================================================ FILE: src/components/utils/mainMode.js ================================================ const { ipcRenderer } = window.require('electron') export function openElectronLink(url) { ipcRenderer.send('open-link', {url: url}) } // Remove async? export function getElectronEvent(channel, callbackFunction) { ipcRenderer.on(channel, async (event, data) => { callbackFunction(data) }) } export function sendElectronEvent(channel, data) { ipcRenderer.send(channel, data); } ================================================ FILE: src/components/utils/openExternalLink.js ================================================ import config from "./config"; export default function openExternalLink(url) { if (config.liteMode) { import('./liteMode').then(module => module.openWindowLink(url)) } else { import('./mainMode').then(module => module.openElectronLink(url)) } } ================================================ FILE: src/index.css ================================================ body { margin: 0; } code { font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', monospace; } html { margin: 1em; background-color: #F5F5F7; } h1, h2, h3, h4, h5, h6 { margin: 0; } .content-center { display: flex; justify-content: center; align-items: center; } .border-right { border-right: 2px solid #41403e; } .border-bottom { border-bottom: 1px solid rgba(65, 64, 62, 0.20); } .border-top { border-top: 1px solid rgba(65, 64, 62, 0.20); } /*noinspection CssReplaceWithShorthandSafely*/ .custom-border { border-bottom-left-radius: 225px 100px; border-bottom-right-radius: 15px 225px; border-top-left-radius: 255px 25px; border-top-right-radius: 25px 225px; } .bg-blue { background-color: blue; } .bg-red { background-color: red; } .no-border { border: none; } .clean-link { background: none; } .clean-button { border: none; padding: 0; box-shadow: none; } .clean-button:hover { transform: translate3d(0, 2px, 0); box-shadow: none; } .clean-button:focus { transform: translate3d(0, 2px, 0); box-shadow: none; outline: none; border: none; } .m-0-important { margin: 0 } .mt-0-3 { margin-top: 0.3em; } .sidebar-footnote { margin-left: 0.2em; font-size: 0.5em; margin-top: 10em; } .image-24 { width: 24px } ================================================ FILE: src/index.js ================================================ import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import * as serviceWorker from './serviceWorker'; ReactDOM.render( , document.getElementById('root') ); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.unregister(); ================================================ FILE: src/serviceWorker.js ================================================ // This optional code is used to register a service worker. // register() is not called by default. // This lets the app load faster on subsequent visits in production, and gives // it offline capabilities. However, it also means that developers (and users) // will only see deployed updates on subsequent visits to a page, after all the // existing tabs open on the page have been closed, since previously cached // resources are updated in the background. // To learn more about the benefits of this model and instructions on how to // opt-in, read https://bit.ly/CRA-PWA const isLocalhost = Boolean( window.location.hostname === 'localhost' || // [::1] is the IPv6 localhost address. window.location.hostname === '[::1]' || // 127.0.0.0/8 are considered localhost for IPv4. window.location.hostname.match( /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ ) ); export function register(config) { if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { // The URL constructor is available in all browsers that support SW. const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); if (publicUrl.origin !== window.location.origin) { // Our service worker won't work if PUBLIC_URL is on a different origin // from what our page is served on. This might happen if a CDN is used to // serve assets; see https://github.com/facebook/create-react-app/issues/2374 return; } window.addEventListener('load', () => { const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; if (isLocalhost) { // This is running on localhost. Let's check if a service worker still exists or not. checkValidServiceWorker(swUrl, config); // Add some additional logging to localhost, pointing developers to the // service worker/PWA documentation. navigator.serviceWorker.ready.then(() => { console.log( 'This web app is being served cache-first by a service ' + 'worker. To learn more, visit https://bit.ly/CRA-PWA' ); }); } else { // Is not localhost. Just register service worker registerValidSW(swUrl, config); } }); } } function registerValidSW(swUrl, config) { navigator.serviceWorker .register(swUrl) .then(registration => { registration.onupdatefound = () => { const installingWorker = registration.installing; if (installingWorker == null) { return; } installingWorker.onstatechange = () => { if (installingWorker.state === 'installed') { if (navigator.serviceWorker.controller) { // At this point, the updated precached content has been fetched, // but the previous service worker will still serve the older // content until all client tabs are closed. console.log( 'New content is available and will be used when all ' + 'tabs for this page are closed. See https://bit.ly/CRA-PWA.' ); // Execute callback if (config && config.onUpdate) { config.onUpdate(registration); } } else { // At this point, everything has been precached. // It's the perfect time to display a // "Content is cached for offline use." message. console.log('Content is cached for offline use.'); // Execute callback if (config && config.onSuccess) { config.onSuccess(registration); } } } }; }; }) .catch(error => { console.error('Error during service worker registration:', error); }); } function checkValidServiceWorker(swUrl, config) { // Check if the service worker can be found. If it can't reload the page. fetch(swUrl, { headers: { 'Service-Worker': 'script' }, }) .then(response => { // Ensure service worker exists, and that we really are getting a JS file. const contentType = response.headers.get('content-type'); if ( response.status === 404 || (contentType != null && contentType.indexOf('javascript') === -1) ) { // No service worker found. Probably a different app. Reload the page. navigator.serviceWorker.ready.then(registration => { registration.unregister().then(() => { window.location.reload(); }); }); } else { // Service worker found. Proceed as normal. registerValidSW(swUrl, config); } }) .catch(() => { console.log( 'No internet connection found. App is running in offline mode.' ); }); } export function unregister() { if ('serviceWorker' in navigator) { navigator.serviceWorker.ready .then(registration => { registration.unregister(); }) .catch(error => { console.error(error.message); }); } }